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
accepton/accepton-apple
Example/Tests/AcceptOnAPIKeys.swift
1
1652
import Foundation //List of API keys that have different services enabled with them enum AcceptOnKeyProperty { case PaypalRest case Stripe case PublicKey case StripeApplePay case ApplePay } struct AcceptOnAPIKeyInfo { var key: String var properties: [AcceptOnKeyProperty] //Meta-data is just extra information var metadata: [String:AnyObject] } let keys = [ AcceptOnAPIKeyInfo(key: "pkey_24b6fa78e2bf234d", properties: [.PaypalRest, .Stripe, .PublicKey, .StripeApplePay, .ApplePay], metadata: ["stripe_merchant_identifier": "merchant.com.accepton"]), AcceptOnAPIKeyInfo(key: "pkey_89f2cc7f2c423553", properties: [.Stripe], metadata: [:]) ] //Get a key with a set of properties func apiKeyWithProperties(properties: [AcceptOnKeyProperty], withoutProperties: [AcceptOnKeyProperty]) -> AcceptOnAPIKeyInfo { //Must contain all mentioned properties var filteredKeys = keys.filter { keyInfo in for p in properties { if keyInfo.properties.indexOf(p) == nil { return false } } return true } //Must *not* contain all negatively mentioned properties filteredKeys = filteredKeys.filter { keyInfo in for p in withoutProperties { if keyInfo.properties.indexOf(p) != nil { return false } } return true } let resultKey = filteredKeys.first if resultKey == nil { NSException(name: "apiKeyWithProperties", reason: "Couldn't find an API key that had the properties of \(properties) without the properties of \(withoutProperties)", userInfo: nil).raise() } return resultKey! }
mit
8d3c29d264af64427d42028f164fb974
31.392157
196
0.687651
4.268734
false
false
false
false
hollance/YOLO-CoreML-MPSNNGraph
TinyYOLO-NNGraph/TinyYOLO-NNGraph/Float16.swift
1
2056
import Foundation import Accelerate /* Utility functions for dealing with 16-bit floating point values in Swift. */ /** Since Swift has no datatype for a 16-bit float we use `UInt16`s instead, which take up the same amount of memory. (Note: The simd framework does have "half" types but only for 2, 3, or 4-element vectors, not scalars.) */ public typealias Float16 = UInt16 /** Creates a new array of Swift `Float` values from a buffer of float-16s. */ public func float16to32(_ input: UnsafeMutablePointer<Float16>, count: Int) -> [Float] { var output = [Float](repeating: 0, count: count) float16to32(input: input, output: &output, count: count) return output } /** Converts a buffer of float-16s into a buffer of `Float`s, in-place. */ public func float16to32(input: UnsafeMutablePointer<Float16>, output: UnsafeMutableRawPointer, count: Int) { var bufferFloat16 = vImage_Buffer(data: input, height: 1, width: UInt(count), rowBytes: count * 2) var bufferFloat32 = vImage_Buffer(data: output, height: 1, width: UInt(count), rowBytes: count * 4) if vImageConvert_Planar16FtoPlanarF(&bufferFloat16, &bufferFloat32, 0) != kvImageNoError { print("Error converting float16 to float32") } } /** Creates a new array of float-16 values from a buffer of `Float`s. */ public func float32to16(_ input: UnsafeMutablePointer<Float>, count: Int) -> [Float16] { var output = [Float16](repeating: 0, count: count) float32to16(input: input, output: &output, count: count) return output } /** Converts a buffer of `Float`s into a buffer of float-16s, in-place. */ public func float32to16(input: UnsafeMutablePointer<Float>, output: UnsafeMutableRawPointer, count: Int) { var bufferFloat32 = vImage_Buffer(data: input, height: 1, width: UInt(count), rowBytes: count * 4) var bufferFloat16 = vImage_Buffer(data: output, height: 1, width: UInt(count), rowBytes: count * 2) if vImageConvert_PlanarFtoPlanar16F(&bufferFloat32, &bufferFloat16, 0) != kvImageNoError { print("Error converting float32 to float16") } }
mit
725790dad3c7eda1f847c3c653700c14
37.792453
108
0.725681
3.532646
false
false
false
false
jasl/MoyaX
Sources/Endpoint.swift
2
687
import Foundation /// Endpoint is the intermediate representation for a target on requesting public final class Endpoint { /// The raw target instance public let target: Target? public let URL: NSURL public let method: HTTPMethod public var headerFields: [String:String] public var parameters: [String:AnyObject] public let parameterEncoding: ParameterEncoding public init(target: Target) { self.target = target self.URL = target.fullURL self.method = target.method self.parameterEncoding = target.parameterEncoding self.parameters = target.parameters self.headerFields = target.headerFields } }
mit
cd30068adf675e6a7d9df7dbb94e3be5
25.423077
74
0.701601
5.165414
false
false
false
false
zhaobin19918183/zhaobinCode
miniship/minishop/HomeViewController/ShoppingCartViewCobtroller/ShoppingCar/ProductTableViewCell.swift
1
3175
// // ProductTableViewCell.swift // minishop // // Created by Zhao.bin on 16/3/15. // Copyright © 2016年 Zhao.bin. All rights reserved. // import UIKit class ProductTableViewCell: UITableViewCell { @IBOutlet weak var numberLable: UILabel! @IBOutlet weak var addButton: UIButton! @IBOutlet weak var deleteButton: UIButton! @IBOutlet weak var _nameLable: UILabel! @IBOutlet weak var _moneyLable: UILabel! @IBOutlet weak var _weightLable: UILabel! @IBOutlet weak var _selectLable: UILabel! @IBOutlet weak var _productImageView: UIImageView! var index:Int! var section:Int! var animationLayers: [CALayer]? var animationBigLayers: [CALayer]? override func awakeFromNib() { super.awakeFromNib() // Initialization code } @IBAction func deleteProductAction(_ sender: UIButton) { print("section==\(section)","index==\(index)") } @IBAction func addProductAction(_ sender: UIButton) { print("section==\(section)","index==\(index)") // addProductsAnimation(_productImageView) } // //MARK:动画效果 func addProductsAnimation(_ imageView: UIImageView) { if (self.animationLayers == nil) { self.animationLayers = [CALayer](); } let frame = imageView.convert(imageView.bounds, to:self) let transitionLayer = CALayer() transitionLayer.frame = frame transitionLayer.contents = imageView.layer.contents self.layer.addSublayer(transitionLayer) self.animationLayers?.append(transitionLayer) let p1 = transitionLayer.position; let p3 = CGPoint(x: self.width - 20 , y: self.layer.bounds.size.height * 4 + 20); let positionAnimation = CAKeyframeAnimation(keyPath: "position") let path = CGMutablePath(); // CGPathMoveToPoint(path, nil, p1.x, p1.y); // CGPathAddCurveToPoint(path, nil, p1.x, p1.y - 30, p3.x, p1.y - 30, p3.x, p3.y); // positionAnimation.path = path; let opacityAnimation = CABasicAnimation(keyPath: "opacity") opacityAnimation.fromValue = 1 opacityAnimation.toValue = 0.9 opacityAnimation.fillMode = kCAFillModeForwards opacityAnimation.isRemovedOnCompletion = true let transformAnimation = CABasicAnimation(keyPath: "transform") transformAnimation.fromValue = NSValue(caTransform3D: CATransform3DIdentity) transformAnimation.toValue = NSValue(caTransform3D: CATransform3DScale(CATransform3DIdentity, 0.2, 0.2, 1)) let groupAnimation = CAAnimationGroup() groupAnimation.animations = [positionAnimation, transformAnimation, opacityAnimation]; groupAnimation.duration = 0.8 // groupAnimation.delegate = self; transitionLayer.add(groupAnimation, forKey: "cartParabola") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
gpl-3.0
188b98e78b31553faee8de987e55c7a2
30.959596
115
0.642857
4.76506
false
false
false
false
michelleran/FicFeed
iOS/FicFeed/AppDelegate.swift
1
3511
// // AppDelegate.swift // FicFeed // // Created by Michelle Ran on 7/24/16. // Copyright © 2016 Michelle Ran LLC. All rights reserved. // import UIKit import Firebase import FirebaseMessaging @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Register for remote notifications if #available(iOS 8.0, *) { let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } else { // Fallback let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound] application.registerForRemoteNotificationTypes(types) } FIRApp.configure() // Configuring nav bar appearance UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont(name: "Arial Rounded MT Bold", size: 18)!, NSForegroundColorAttributeName: UIColor.whiteColor()] // Configuring tab bar appearance UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor(red: 0xCC, green: 0x5A, blue: 0x5A)], forState: UIControlState.Normal) UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState: UIControlState.Selected) return true } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown) let tokenChars = UnsafePointer<CChar>(deviceToken.bytes) var tokenString = "" for i in 0..<deviceToken.length { tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]]) } Cloud.setup(tokenString) } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { if application.applicationState != UIApplicationState.Active { if let tab = window?.rootViewController as? UITabBarController { if let navigation = tab.selectedViewController as? UINavigationController { if let link = userInfo["link"] as? String, title = userInfo["title"] as? String { let ficController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("Fic") as! FicController ficController.ficTitle = title ficController.link = NSURL(string: link)! navigation.pushViewController(ficController, animated: true) } } } } } // [START connect_to_fcm] func connectToFcm() { FIRMessaging.messaging().connectWithCompletion { (error) in } } // [END connect_to_fcm] func applicationDidBecomeActive(application: UIApplication) { connectToFcm() } // [START disconnect_from_fcm] func applicationDidEnterBackground(application: UIApplication) { FIRMessaging.messaging().disconnect() } // [END disconnect_from_fcm] }
mit
ebdf0ac6d9822bc53bf3b22d446ca95f
40.294118
184
0.658974
5.536278
false
false
false
false
tsolomko/SWCompression
Sources/XZ/Sha256.swift
1
5112
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation infix operator >>> @inline(__always) fileprivate func >>> (num: UInt32, count: Int) -> UInt32 { // This implementation assumes without checking that `count` is in the 1...31 range. return (num >> count) | (num << (32 - count)) } struct Sha256 { private static let k: [UInt32] = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2] static func hash(data: Data) -> [UInt8] { var h0 = 0x6a09e667 as UInt32 var h1 = 0xbb67ae85 as UInt32 var h2 = 0x3c6ef372 as UInt32 var h3 = 0xa54ff53a as UInt32 var h4 = 0x510e527f as UInt32 var h5 = 0x9b05688c as UInt32 var h6 = 0x1f83d9ab as UInt32 var h7 = 0x5be0cd19 as UInt32 // Padding var bytes = data.withUnsafeBytes { $0.map { $0 } } let originalLength = bytes.count var newLength = originalLength * 8 + 1 while newLength % 512 != 448 { newLength += 1 } newLength /= 8 bytes.append(0x80) for _ in 0..<(newLength - originalLength - 1) { bytes.append(0x00) } // Length let bitsLength = UInt64(truncatingIfNeeded: originalLength * 8) for i: UInt64 in 0..<8 { bytes.append(UInt8(truncatingIfNeeded: (bitsLength & 0xFF << ((7 - i) * 8)) >> ((7 - i) * 8))) } for i in stride(from: 0, to: bytes.count, by: 64) { var w = Array(repeating: 0 as UInt32, count: 64) for j in 0..<16 { var word = 0 as UInt32 for k: UInt32 in 0..<4 { word += UInt32(truncatingIfNeeded: bytes[i + j * 4 + k.toInt()]) << ((3 - k) * 8) } w[j] = word } for i in 16..<64 { let s0 = (w[i - 15] >>> 7) ^ (w[i - 15] >>> 18) ^ (w[i - 15] >> 3) let s1 = (w[i - 2] >>> 17) ^ (w[i - 2] >>> 19) ^ (w[i - 2] >> 10) w[i] = w[i - 16] &+ s0 &+ w[i - 7] &+ s1 } var a = h0 var b = h1 var c = h2 var d = h3 var e = h4 var f = h5 var g = h6 var h = h7 for i in 0..<64 { let s1 = (e >>> 6) ^ (e >>> 11) ^ (e >>> 25) let ch = (e & f) ^ ((~e) & g) let temp1 = h &+ s1 &+ ch &+ k[i] &+ w[i] let s0 = (a >>> 2) ^ (a >>> 13) ^ (a >>> 22) let maj = (a & b) ^ (a & c) ^ (b & c) let temp2 = s0 &+ maj h = g g = f f = e e = d &+ temp1 d = c c = b b = a a = temp1 &+ temp2 } h0 = h0 &+ a h1 = h1 &+ b h2 = h2 &+ c h3 = h3 &+ d h4 = h4 &+ e h5 = h5 &+ f h6 = h6 &+ g h7 = h7 &+ h } var result = [UInt8]() result.reserveCapacity(32) for i: UInt32 in 0..<4 { result.append(UInt8(truncatingIfNeeded: (h0 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8))) } for i: UInt32 in 0..<4 { result.append(UInt8(truncatingIfNeeded: (h1 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8))) } for i: UInt32 in 0..<4 { result.append(UInt8(truncatingIfNeeded: (h2 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8))) } for i: UInt32 in 0..<4 { result.append(UInt8(truncatingIfNeeded: (h3 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8))) } for i: UInt32 in 0..<4 { result.append(UInt8(truncatingIfNeeded: (h4 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8))) } for i: UInt32 in 0..<4 { result.append(UInt8(truncatingIfNeeded: (h5 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8))) } for i: UInt32 in 0..<4 { result.append(UInt8(truncatingIfNeeded: (h6 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8))) } for i: UInt32 in 0..<4 { result.append(UInt8(truncatingIfNeeded: (h7 & 0xFF << ((3 - i) * 8)) >> ((3 - i) * 8))) } return result } }
mit
4ba78de16e266f6e4a559b24c90ea684
34.5
116
0.472809
2.886505
false
false
false
false
almazrafi/Metatron
Tests/MetatronTests/MPEG/MPEGXingHeaderTest.swift
1
7541
// // MPEGXingHeaderTest.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import XCTest @testable import Metatron extension MPEGXingHeader { // MARK: Initializers fileprivate init?(fromData data: [UInt8], range: inout Range<UInt64>) { let stream = MemoryStream(data: data) guard stream.openForReading() else { return nil } self.init(fromStream: stream, range: &range) } } class MPEGXingHeaderTest: XCTestCase { // MARK: Instance Methods func testCaseA() { var header = MPEGXingHeader() XCTAssert(!header.isValid) header.bitRateMode = MPEGBitRateMode.variable header.framesCount = 123 header.bytesCount = 123 header.tableOfContent = Array<UInt8>(repeating: 123, count: 100) header.quality = 123 XCTAssert(header.isValid) guard let data = header.toData() else { return XCTFail() } XCTAssert(!data.isEmpty) let prefixData = Array<UInt8>(repeating: 123, count: 123) let suffixData = Array<UInt8>(repeating: 231, count: 231) var range = Range<UInt64>(123..<(123 + UInt64(data.count))) guard let otherHeader = MPEGXingHeader(fromData: prefixData + data + suffixData, range: &range) else { return XCTFail() } XCTAssert(range.lowerBound == 123) XCTAssert(range.upperBound == 123 + UInt64(data.count)) XCTAssert(otherHeader.isValid) XCTAssert(otherHeader.bitRateMode == header.bitRateMode) XCTAssert(otherHeader.framesCount == header.framesCount!) XCTAssert(otherHeader.bytesCount == header.bytesCount!) guard let otherTableOfContent = otherHeader.tableOfContent else { return XCTFail() } XCTAssert(otherTableOfContent == header.tableOfContent!) XCTAssert(otherHeader.quality == header.quality!) } func testCaseB() { var header = MPEGXingHeader() XCTAssert(!header.isValid) header.bitRateMode = MPEGBitRateMode.constant header.framesCount = 123 header.bytesCount = 123 header.tableOfContent = Array<UInt8>(repeating: 123, count: 100) header.quality = 0 XCTAssert(header.isValid) guard let data = header.toData() else { return XCTFail() } XCTAssert(!data.isEmpty) let prefixData = Array<UInt8>(repeating: 123, count: 123) let suffixData = Array<UInt8>(repeating: 231, count: 231) var range = Range<UInt64>(123..<(354 + UInt64(data.count))) guard let otherHeader = MPEGXingHeader(fromData: prefixData + data + suffixData, range: &range) else { return XCTFail() } XCTAssert(range.lowerBound == 123) XCTAssert(range.upperBound == 123 + UInt64(data.count)) XCTAssert(otherHeader.isValid) XCTAssert(otherHeader.bitRateMode == header.bitRateMode) XCTAssert(otherHeader.framesCount == header.framesCount!) XCTAssert(otherHeader.bytesCount == header.bytesCount!) guard let otherTableOfContent = otherHeader.tableOfContent else { return XCTFail() } XCTAssert(otherTableOfContent == header.tableOfContent!) XCTAssert(otherHeader.quality == header.quality!) } func testCaseC() { var header = MPEGXingHeader() XCTAssert(!header.isValid) header.bitRateMode = MPEGBitRateMode.variable header.framesCount = 1 header.bytesCount = 1 header.tableOfContent = Array<UInt8>(repeating: 123, count: 100) header.quality = 123 XCTAssert(header.isValid) guard let data = header.toData() else { return XCTFail() } XCTAssert(!data.isEmpty) guard let otherHeader = MPEGXingHeader(fromData: data) else { return XCTFail() } XCTAssert(otherHeader.isValid) XCTAssert(otherHeader.bitRateMode == header.bitRateMode) XCTAssert(otherHeader.framesCount == header.framesCount!) XCTAssert(otherHeader.bytesCount == header.bytesCount!) guard let otherTableOfContent = otherHeader.tableOfContent else { return XCTFail() } XCTAssert(otherTableOfContent == header.tableOfContent!) XCTAssert(otherHeader.quality == header.quality!) } func testCaseD() { var header = MPEGXingHeader() XCTAssert(!header.isValid) header.bitRateMode = MPEGBitRateMode.variable header.framesCount = nil header.bytesCount = nil header.tableOfContent = nil header.quality = nil XCTAssert(header.isValid) guard let data = header.toData() else { return XCTFail() } XCTAssert(!data.isEmpty) guard let otherHeader = MPEGXingHeader(fromData: data) else { return XCTFail() } XCTAssert(otherHeader.isValid) XCTAssert(otherHeader.bitRateMode == header.bitRateMode) XCTAssert(otherHeader.framesCount == nil) XCTAssert(otherHeader.bytesCount == nil) XCTAssert(otherHeader.tableOfContent == nil) XCTAssert(otherHeader.quality == nil) } func testCaseE() { var header = MPEGXingHeader() XCTAssert(!header.isValid) header.bitRateMode = MPEGBitRateMode.constant header.framesCount = nil header.bytesCount = nil header.tableOfContent = nil header.quality = nil XCTAssert(!header.isValid) XCTAssert(header.toData() == nil) } func testCaseF() { var header = MPEGXingHeader() XCTAssert(!header.isValid) header.bitRateMode = MPEGBitRateMode.variable header.framesCount = 123 header.bytesCount = 123 header.tableOfContent = [1, 2, 3] header.quality = 123 XCTAssert(!header.isValid) XCTAssert(header.toData() == nil) } func testCaseG() { var header = MPEGXingHeader() XCTAssert(!header.isValid) header.bitRateMode = MPEGBitRateMode.variable header.framesCount = 0 header.bytesCount = 0 header.tableOfContent = Array<UInt8>(repeating: 123, count: 100) header.quality = 123 XCTAssert(!header.isValid) XCTAssert(header.toData() == nil) } }
mit
3ba182e63f06c43171f81726c946d31c
25.459649
110
0.643018
4.56477
false
false
false
false
LeoMobileDeveloper/MDTable
MDTableExample/Footer.swift
1
2294
// // Footer.swift // MDTableExample // // Created by Leo on 2017/7/11. // Copyright © 2017年 Leo Huang. All rights reserved. // import Foundation import UIKit class MNThemeButton: UIButton{ override var isHighlighted: Bool { didSet{ if isHighlighted { self.backgroundColor = UIColor.theme }else{ self.backgroundColor = UIColor.white } } } } class NMFooterView: UIView{ var describleLabel: UILabel! var sortButton: MNThemeButton! private var separatorView: UIView! override init(frame: CGRect) { super.init(frame: frame) describleLabel = UILabel.subTitle().added(to: self) describleLabel.text = "现在可以根据个人喜好,自由调整首页栏目顺序啦~" describleLabel.textAlignment = .center sortButton = MNThemeButton(type: .custom).added(to: self) sortButton.setTitle("调整栏目顺序", for: .normal) sortButton.setTitleColor(UIColor.theme, for: .normal) sortButton.setTitleColor(UIColor.white, for: .highlighted) sortButton.imageView?.contentMode = .scaleToFill sortButton.layer.borderWidth = 1.0 sortButton.layer.borderColor = UIColor.theme.cgColor sortButton.titleLabel?.font = UIFont.systemFont(ofSize: 12) separatorView = UIView().added(to: self) separatorView.backgroundColor = UIColor.groupTableViewBackground } override func layoutSubviews() { super.layoutSubviews() describleLabel.sizeToFit() sortButton.sizeToFit() separatorView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 1.0) describleLabel.frame = CGRect(x: 0, y: 16.0, width: self.frame.width, height: describleLabel.frame.height) let height = sortButton.frame.height let width = sortButton.frame.width + height let x = (self.frame.width - width) / 2.0 let y = describleLabel.maxY + 8.0 sortButton.frame = CGRect(x: x, y: y, width: width, height: height) sortButton.layer.cornerRadius = height / 2.0 sortButton.layer.masksToBounds = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
61d05ed262ad075b0f64ba2168afc5a6
35.672131
114
0.649084
4.001789
false
false
false
false
MdBee/BusStops
BusStops/ViewController.swift
1
4646
// // ViewController.swift // BusStops // // Created by Bearson, Matt D. on 12/3/16. // Copyright © 2016 Bearson, Matt D. All rights reserved. // import UIKit import Bond import ReactiveKit typealias SectionMetadata = (header: String, footer: String) let zeroState = "\nno results" var sectionOne = Observable2DArraySection<SectionMetadata,String>(metadata: ("Southbound", ""), items: [zeroState,zeroState]) var sectionTwo = Observable2DArraySection<SectionMetadata,String>(metadata: ("Northbound", ""), items: [zeroState,zeroState,zeroState]) let stopIdsArray : [[String]] = [["40303","40110"],["40036","40024","40069"]] let namesArray : [[String]] = [["Magnolia Ave & Ward St","Hwy 101 @ Spencer Ave Bus Pad"],["Richardson Ave & Francisco St","San Francisco Civic Ctr-McAllister St & Polk St","Pine St & Battery St"]] var array = MutableObservable2DArray([sectionOne]) let rowHeight : CGFloat = 120 let tableView = UITableView(frame: CGRect(), style:UITableViewStyle.grouped) let refreshControl = UIRefreshControl() struct MyBond: TableViewBond { func cellForRow(at indexPath: IndexPath, tableView: UITableView, dataSource: Observable2DArray<SectionMetadata, String>) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let stopId = stopIdsArray[indexPath.section][indexPath.row] let str = NSMutableAttributedString() let attribute1 = [NSForegroundColorAttributeName: UIColor.green] let attrString1 = NSAttributedString(string: stopId, attributes: attribute1) let attribute2: [String : Any] = [ NSForegroundColorAttributeName: UIColor.blue, NSFontAttributeName: UIFont(name: "Avenir-Heavy", size: 14.0)! ] let attrString2 = NSAttributedString(string: " "+namesArray[indexPath.section][indexPath.row], attributes: attribute2) let predictions = array[indexPath] let attribute3: [String : Any] = [ NSForegroundColorAttributeName: UIColor.orange, NSFontAttributeName: UIFont(name: "Avenir-Roman", size: 12.0)! ] let attrString3 = NSAttributedString(string: " "+predictions, attributes: attribute3) str.append(attrString1) str.append(attrString2) str.append(attrString3) let frame = cell.contentView.frame let tV = UITextView(frame: frame) tV.isEditable = false tV.attributedText = str cell.addSubview(tV) return cell } func titleForHeader(in section: Int, dataSource: Observable2DArray<SectionMetadata, String>) -> String? { return dataSource[section].metadata.header } func titleForFooter(in section: Int, dataSource: Observable2DArray<SectionMetadata, String>) -> String? { return dataSource[section].metadata.footer } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() array.appendSection(sectionTwo) refreshControl.attributedTitle = NSAttributedString(string: "") refreshControl.addTarget(self, action: #selector(refreshData), for: .valueChanged) tableView.refreshControl = refreshControl let frame = self.view.frame tableView.frame = frame tableView.rowHeight = rowHeight tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") self.view.addSubview(tableView) array.bind(to: tableView, using: MyBond()) NotificationCenter.default.addObserver(self, selector: #selector(refreshData), name: .refreshData_notif, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refreshData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func refreshData() { print("refreshing") var sectionCounter = 0 var itemsCounter = 0 stopIdsArray.map({ $0.map({ let indexPath = IndexPath(item:itemsCounter,section:sectionCounter) NetworkManager.sharedInstance.getData(stop:$0,indexPath:indexPath) itemsCounter += 1 }) itemsCounter = 0 sectionCounter += 1 }) //should be in callback? refreshControl.endRefreshing() } }
mit
40d4837891dc6b6aa52c33eb4ec5f518
35.865079
197
0.658342
4.793602
false
false
false
false
vimeo/VimeoUpload
VimeoUpload/Upload/Descriptor System/New Upload (Private)/UploadStrategy.swift
1
4504
// // UploadStrategy.swift // VimeoUpload // // Created by Nguyen, Van on 11/13/18. // Copyright © 2018 Vimeo. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import VimeoNetworking /// An error enum related to any problem with an upload link. /// /// - unavailable: Thrown when an upload link is not available. /// - wrongType: Thrown when attempting to get an upload link with a /// wrong upload approach i.e using `StreamingUploadStrategy` to get a /// tus upload link. public enum UploadLinkError: Error { case unavailable case wrongType } /// An interface to assist `UploadDescriptor` in getting an upload task /// and an upload link. public protocol UploadStrategy { /// Returns the appropriate upload request parameters for creating a video on Vimeo's server /// /// - Returns: A dictionary of upload parameters static func createVideoUploadParameters() -> UploadParameters /// Creates an upload request for the upload descriptor. /// /// - Parameters: /// - requestSerializer: A request serializer. /// - fileUrl: A URL to a video file. /// - uploadLink: A destination URL to send the video file to. /// - Returns: An upload request. /// - Throws: An `NSError` that describes why an upload request cannot be /// created. static func uploadRequest(requestSerializer: VimeoRequestSerializer?, fileUrl: URL, uploadLink: String) throws -> URLRequest /// Returns an appropriate upload link. /// /// - Parameter video: A video object returned by `CreateVideoOperation`. /// - Returns: An upload link if it exists in the video object. /// - Throws: One of the values of `UploadLinkError` if there is a problem /// with the upload link. static func uploadLink(from video: VIMVideo) throws -> String /// Determines if an upload task should retry. /// /// - Parameter urlResponse: A HTTP server response. /// - Returns: `true` if the task should retry; `false` otherwise. static func shouldRetry(urlResponse: URLResponse?) -> Bool } /// An upload strategy that supports the streaming upload approach. public struct StreamingUploadStrategy: UploadStrategy { public enum ErrorCode: Error { case requestSerializerUnavailable } public static func createVideoUploadParameters() -> UploadParameters { return [VimeoSessionManager.Constants.ApproachKey : VimeoSessionManager.Constants.StreamingApproachValue] } public static func uploadRequest(requestSerializer: VimeoRequestSerializer?, fileUrl: URL, uploadLink: String) throws -> URLRequest { guard let requestSerializer = requestSerializer else { throw ErrorCode.requestSerializerUnavailable } return try requestSerializer.uploadVideoRequest(with: fileUrl, destination: uploadLink) as URLRequest } public static func uploadLink(from video: VIMVideo) throws -> String { guard let approach = video.upload?.uploadApproach, approach == .Streaming else { throw UploadLinkError.wrongType } guard let uploadLink = video.upload?.uploadLink else { throw UploadLinkError.unavailable } return uploadLink } public static func shouldRetry(urlResponse: URLResponse?) -> Bool { return false } }
mit
ac295d44f8b07a841b1b35064ef7c496
36.840336
135
0.698867
4.831545
false
false
false
false
devroo/onTodo
Swift/CollectionTypes.playground/section-1.swift
1
6472
// Playground - noun: a place where people can play import UIKit /* * 컬렉션 타입 (Collection Types) */ // 배열 표현식 (Array Literals) // beta4부터 String[] -> [String] 으로 문법이 변겨됨 var shoppingList: [String] = ["Eggs", "Mink"] // shoppingList has been initialized with two initial items // var shoppingList = ["Eggs", "Mink"] 으로도 가능 // 배열의 접근 및 수정 Accessing and Modifying an Array println("The shopping list contains \(shoppingList.count) items.") // prints "The shopping list contains 2 items." if shoppingList.isEmpty { println("The shopping list is empty.") } else { println("The shopping list is not empty.") } // prints "The shopping list is not empty." // count를 isEmpty로 처리할 수 있음 // 항목추가 shoppingList.append("Flour") // shoppingList now contains 3 items, and someone is making pancakes //shoppingList += "Baking Powder" // shoppingList now contains 4 items shoppingList += ["Chocolate Spread", "Cheese", "Butter"] // shoppingList now contains 7 items var firstItem = shoppingList[0] // firstItem is equal to "Eggs" shoppingList[0] = "Six eggs" shoppingList // the first item in the list is now equal to "Six eggs" rather than "Eggs" ///shoppingList[3...6] = ["Bananas", "Apples"] shoppingList // shoppingList now contains 6 items shoppingList.insert("Maple Syrup", atIndex: 0) shoppingList // shoppingList now contains 7 items // "Maple Syrup" is now the first item in the list let mapleSyrup = shoppingList.removeAtIndex(0) shoppingList // the item that was at index 0 has just been removed // shoppingList now contains 6 items, and no Maple Syrup // the mapleSyrup constant is now equal to the removed "Maple Syrup" string firstItem = shoppingList[0] shoppingList // firstItem is now equal to "Six eggs" let apples = shoppingList.removeLast() shoppingList // the last item in the array has just been removed // shoppingList now contains 5 items, and no cheese // the apples constant is now equal to the removed "Apples" string // 배열에서 반복문 사용하기 Iterating Over an Array for item in shoppingList { println(item) } // Six eggs // Milk // Flour // Baking Powder // Bananas // enumerate 함수는 배열내 각각의 값에 대해 인덱스와 결합한 튜플 값을 반환한다. 반복문을 돌리는 도중 이 튜플을 변수나 상수로 분리하여 사용할 수 있다 for (index, value) in enumerate(shoppingList) { println("Item \(index + 1): \(value)") } // Item 1: Six eggs // Item 2: Milk // Item 3: Flour // Item 4: Baking Powder // Item 5: Bananas // 배열의 생성과 초기화 Creating and Initializing an Array var someInts = [Int]() println("someInts is of type Int[] with \(someInts.count) items.") // prints "someInts is of type Int[] with 0 items." someInts.append(3) someInts // someInts now contains 1 value of type Int someInts = [] // someInts is now an empty array, but is still of type Int[] var threeDoubles = [Double](count: 3, repeatedValue: 0.0) // threeDoubles is of type Double[], and equals [0.0, 0.0, 0.0] var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5) // anotherThreeDoubles is inferred as Double[], and equals [2.5, 2.5, 2.5] // 타입 추정을 이용할 수 있으므로 굳이 타입 지정을 필요없음 var sixDoubles = threeDoubles + anotherThreeDoubles // sixDoubles is inferred as Double[], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5] // 딕셔너리 Dictionaries // 주의점 : KeyType은 해시 가능한 타입이어야 한다. 그외적으로는 모두 가능 // 딕셔너리 표현식 Dictionary Literals var airports: Dictionary<String, String> = ["TYO": "Tokyo", "DUB": "Dublin"] // var airports = ["TYO": "Tokyo", "DUB": "Dublin"] // 축약표현 // 딕셔너리의 접근 및 수정 Accessing and Modifying a Dictionary println("The dictionary of airports contains \(airports.count) items.") // prints "The dictionary of airports contains 2 items." airports["LHR"] = "London" airports // the airports dictionary now contains 3 items airports["LHR"] = "London Heathrow" airports // the value for "LHR" has been changed to "London Heathrow" // updateValue(forKey:)는 특정키의 값을 변경시키는 함수 // updateValue(forKey:) 메소드는 업데이트를 하고난 뒤 이전 값을 반환 // 딕셔너리의 밸류 타입에 해당하는 Optional 값을 반환 if let oldValue = airports.updateValue("Dublin International", forKey: "DUB") { println("The old value for DUB was \(oldValue).") } // prints "The old value for DUB was Dublin." if let airportName = airports["DUB"] { airportName println("The name of the airport is \(airportName).") } else { // airportName 여기선 접근이 불가능... println("That airport is not in the airports dictionary.") } // prints "The name of the airport is Dublin International." airports["APL"] = "Apple International" // "Apple International" is not the real airport for APL, so delete it airports airports["APL"] = nil // APL has now been removed from the dictionary // key/value 쌍으로 삭제하는 방법 airports // removeValueForKey 로 삭제하는 방법 : 값이 없으면 return nil; if let removedValue = airports.removeValueForKey("DUB") { println("The removed airport's name is \(removedValue).") } else { println("The airports dictionary does not contain a value for DUB.") } // prints "The removed airport's name is Dublin International." airports // 딕셔너리에서 반복문 사용하기 Iterating Over a Dictionary for (airportCode, airportName) in airports { println("\(airportCode): \(airportName)") } // TYO: Tokyo // LHR: London Heathrow for airportCode in airports.keys { println("Airport code: \(airportCode)") } // Airport code: TYO // Airport code: LHR for airportName in airports.values { println("Airport name: \(airportName)") } // Airport name: Tokyo // Airport name: London Heathrow let airportCodes = Array(airports.keys) // airportCodes is ["TYO", "LHR"] let airportNames = Array(airports.values) // airportNames is ["Tokyo", "London Heathrow"] // 빈 딕셔너리 만들기 Creating an Empty Dictionary var namesOfIntegers = Dictionary<Int, String>() // namesOfIntegers is an empty Dictionary<Int, String> namesOfIntegers[16] = "sixteen" namesOfIntegers // namesOfIntegers now contains 1 key-value pair namesOfIntegers = [:] // namesOfIntegers is once again an empty dictionary of type Int, String
gpl-2.0
ce81901983288115f765c3cb42955602
27.794118
91
0.715696
3.106293
false
false
false
false
Ahmed-Ali/RealmObjectEditor
Realm Object Editor/LangModel.swift
1
3376
// // LangModel.swift // // Create by Ahmed Ali on 24/1/2015 // Copyright © 2015 Ahmed Ali Individual Mobile Developer. All rights reserved. // Model file Generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport import Foundation class LangModel : NSObject{ var attributeDefination : String! var attributeDefinationWithDefaultValue : String! var dataTypes : DataType! var defaultSuperClass: String! var fileExtension : String! var firstLineStatement : Bool! var forEachIgnoredProperty : String! var forEachIndexedAttribute : String! var primaryKeyAnnotation: String! var getter : String! var ignoredProperties : String! var ignoreAnnotaion : String! var implementation : Implementation! var indexedAttributesDefination : String! var indexAnnotaion: String! var modelDefinition : String! var modelDefineInConstructor: Bool! var modelEnd : String! var modelStart : String! var primaryKeyDefination : String! var relationsipImports : String! var setter: String! var staticImports : String! var toManyRelationshipDefination : String! var toManyRelationType : String! var toOneRelationshipDefination : String! var package: String! /** * Instantiate the instance using the passed dictionary values to set the properties values */ init(fromDictionary dictionary: NSDictionary){ attributeDefination = dictionary["attributeDefination"] as? String attributeDefinationWithDefaultValue = dictionary["attributeDefinationWithDefaultValue"] as? String if let dataTypesData = dictionary["dataTypes"] as? NSDictionary{ dataTypes = DataType(fromDictionary: dataTypesData) } defaultSuperClass = dictionary["defaultSuperClass"] as? String fileExtension = dictionary["fileExtension"] as? String firstLineStatement = dictionary["firstLineStatement"] as? Bool forEachIgnoredProperty = dictionary["forEachIgnoredProperty"] as? String forEachIndexedAttribute = dictionary["forEachIndexedAttribute"] as? String getter = dictionary["getter"] as? String primaryKeyAnnotation = dictionary["primaryKeyAnnotation"] as? String ignoreAnnotaion = dictionary["ignoreAnnotaion"] as? String ignoredProperties = dictionary["ignoredProperties"] as? String if let implementationData = dictionary["implementation"] as? NSDictionary{ implementation = Implementation(fromDictionary: implementationData) } indexedAttributesDefination = dictionary["indexedAttributesDefination"] as? String indexAnnotaion = dictionary["indexAnnotaion"] as? String modelDefineInConstructor = dictionary["modelDefineInConstructor"] as? Bool modelDefinition = dictionary["modelDefinition"] as? String modelEnd = dictionary["modelEnd"] as? String modelStart = dictionary["modelStart"] as? String primaryKeyDefination = dictionary["primaryKeyDefination"] as? String relationsipImports = dictionary["relationsipImports"] as? String setter = dictionary["setter"] as? String staticImports = dictionary["staticImports"] as? String toManyRelationshipDefination = dictionary["toManyRelationshipDefination"] as? String toManyRelationType = dictionary["toManyRelationType"] as? String toOneRelationshipDefination = dictionary["toOneRelationshipDefination"] as? String package = dictionary["package"] as? String } }
mit
58f2c4488ebd60f84fb2d123cb11fcd0
39.190476
100
0.762963
4.674515
false
false
false
false
GitHubStuff/SwiftDateTimePicker
SwiftDateTimePicker/Localization.swift
2
2127
// // Localization.swift // PickerOnly // // Created by Steven Smith on 6/3/17. // Copyright © 2017 LTMM. All rights reserved. // import Foundation /// Localization extension String { /// Items related to calendar (months, display formats) public var calendar: String { return LocalizeCalendar.sharedInstance.localize(self) } /// Text for buttons and lables public var label: String { return LocalizeLabel.sharedInstance.localize(self) } private class Constants { static let LabelRootName = "Labels" static let CalendarRootName = "Calendar" } private class LocalizeCalendar { static let sharedInstance = LocalizeCalendar() lazy var localizableDictionary: NSDictionary! = { if let path = Bundle.main.path(forResource: Constants.CalendarRootName, ofType: "plist") { return NSDictionary(contentsOfFile: path) } fatalError("Localizable file NOT found") }() func localize(_ string: String) -> String { guard let localizedString = ((localizableDictionary.value(forKey: string) as Any) as AnyObject).value(forKey: "value") as? String else { fatalError("\n......Missing translation for: \(string)\n") } return localizedString } } private class LocalizeLabel { static let sharedInstance = LocalizeLabel() lazy var localizableDictionary: NSDictionary! = { if let path = Bundle.main.path(forResource: String.Constants.LabelRootName, ofType: "plist") { return NSDictionary(contentsOfFile: path) } fatalError("Localizable file NOT found") }() func localize(_ string: String) -> String { guard let localizedString = ((localizableDictionary.value(forKey: string) as Any) as AnyObject).value(forKey: "value") as? String else { fatalError("\n......Missing translation for: \(string)\n") } return localizedString } } }
mit
9085eb88d8e759aca2beb0cf7f53c505
33.290323
148
0.607714
5.110577
false
false
false
false
zsheikh-systango/WordPower
Skeleton/Pods/NotificationBannerSwift/NotificationBanner/Classes/NotificationBanner.swift
1
7261
/* The MIT License (MIT) Copyright (c) 2017 Dalton Hinterscher Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import SnapKit #if CARTHAGE_CONFIG import MarqueeLabelSwift #else import MarqueeLabel #endif public class NotificationBanner: BaseNotificationBanner { /// Notification that will be posted when a notification banner will appear public static let BannerWillAppear: Notification.Name = Notification.Name(rawValue: "NotificationBannerWillAppear") /// Notification that will be posted when a notification banner did appear public static let BannerDidAppear: Notification.Name = Notification.Name(rawValue: "NotificationBannerDidAppear") /// Notification that will be posted when a notification banner will appear public static let BannerWillDisappear: Notification.Name = Notification.Name(rawValue: "NotificationBannerWillDisappear") /// Notification that will be posted when a notification banner did appear public static let BannerDidDisappear: Notification.Name = Notification.Name(rawValue: "NotificationBannerDidDisappear") /// Notification banner object key that is included with each Notification public static let BannerObjectKey: String = "NotificationBannerObjectKey" /// The bottom most label of the notification if a subtitle is provided public private(set) var subtitleLabel: MarqueeLabel? /// The view that is presented on the left side of the notification private var leftView: UIView? /// The view that is presented on the right side of the notification private var rightView: UIView? public init(title: String, subtitle: String? = nil, leftView: UIView? = nil, rightView: UIView? = nil, style: BannerStyle = .info, colors: BannerColorsProtocol? = nil) { super.init(style: style, colors: colors) if let leftView = leftView { contentView.addSubview(leftView) leftView.snp.makeConstraints({ (make) in make.top.equalToSuperview().offset(10) make.left.equalToSuperview().offset(10) make.bottom.equalToSuperview().offset(-10) make.width.equalTo(leftView.snp.height) }) } if let rightView = rightView { contentView.addSubview(rightView) rightView.snp.makeConstraints({ (make) in make.top.equalToSuperview().offset(10) make.right.equalToSuperview().offset(-10) make.bottom.equalToSuperview().offset(-10) make.width.equalTo(rightView.snp.height) }) } let labelsView = UIView() contentView.addSubview(labelsView) titleLabel = MarqueeLabel() titleLabel!.type = .left titleLabel!.font = UIFont.systemFont(ofSize: 17.5, weight: UIFontWeightBold) titleLabel!.textColor = .white titleLabel!.text = title labelsView.addSubview(titleLabel!) titleLabel!.snp.makeConstraints { (make) in make.top.equalToSuperview() make.left.equalToSuperview() make.right.equalToSuperview() if let _ = subtitle { titleLabel!.numberOfLines = 1 } else { titleLabel!.numberOfLines = 2 } } if let subtitle = subtitle { subtitleLabel = MarqueeLabel() subtitleLabel!.type = .left subtitleLabel!.font = UIFont.systemFont(ofSize: 15.0) subtitleLabel!.numberOfLines = 1 subtitleLabel!.textColor = .white subtitleLabel!.text = subtitle labelsView.addSubview(subtitleLabel!) subtitleLabel!.snp.makeConstraints { (make) in make.top.equalTo(titleLabel!.snp.bottom).offset(2.5) make.left.equalTo(titleLabel!) make.right.equalTo(titleLabel!) } } labelsView.snp.makeConstraints { (make) in make.centerY.equalToSuperview() if let leftView = leftView { make.left.equalTo(leftView.snp.right).offset(padding) } else { make.left.equalToSuperview().offset(padding) } if let rightView = rightView { make.right.equalTo(rightView.snp.left).offset(-padding) } else { make.right.equalToSuperview().offset(-padding) } if let subtitleLabel = subtitleLabel { make.bottom.equalTo(subtitleLabel) } else { make.bottom.equalTo(titleLabel!) } } updateMarqueeLabelsDurations() } public convenience init(attributedTitle: NSAttributedString, attributedSubtitle: NSAttributedString? = nil, leftView: UIView? = nil, rightView: UIView? = nil, style: BannerStyle = .info, colors: BannerColorsProtocol? = nil) { let subtitle: String? = (attributedSubtitle != nil) ? "" : nil self.init(title: "", subtitle: subtitle, leftView: leftView, rightView: rightView, style: style, colors: colors) titleLabel!.attributedText = attributedTitle subtitleLabel?.attributedText = attributedSubtitle } public init(customView: UIView) { super.init(style: .none) contentView.addSubview(customView) customView.snp.makeConstraints { (make) in make.edges.equalTo(contentView) } spacerView.backgroundColor = customView.backgroundColor } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal override func updateMarqueeLabelsDurations() { super.updateMarqueeLabelsDurations() subtitleLabel?.speed = .duration(CGFloat(duration - 3)) } }
mit
f3e2718b28565a117915cc2b79705982
39.338889
147
0.624845
5.530084
false
false
false
false
huangboju/AsyncDisplay_Study
AsyncDisplay/SocialAppLayout/SocialController.swift
1
4716
// // SocialController.swift // AsyncDisplay // // Created by 伯驹 黄 on 2017/4/26. // Copyright © 2017年 伯驹 黄. All rights reserved. // import AsyncDisplayKit class SocialController: ASDKViewController<ASTableNode> { var tableNode: ASTableNode! var data: [Post] = [] override init() { tableNode = ASTableNode(style: .plain) tableNode.inverted = true super.init(node: tableNode) tableNode.delegate = self tableNode.dataSource = self tableNode.autoresizingMask = [.flexibleWidth, .flexibleHeight] title = "Timeline" createSocialAppDataSource() } override func viewDidLoad() { super.viewDidLoad() tableNode.view.separatorStyle = .none } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let inset: CGFloat = 64 tableNode.contentInset = UIEdgeInsets.init(top: -inset, left: 0, bottom: inset, right: 0) tableNode.view.scrollIndicatorInsets = UIEdgeInsets.init(top: -inset, left: 0, bottom: inset, right: 0) } func createSocialAppDataSource() { let post1 = Post( username: "@appleguy", name: "Apple Guy", photo: "https://avatars1.githubusercontent.com/u/565251?v=3&s=96", post: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", time: "3s", media: "", via: 0, likes: Int(arc4random_uniform(74)), comments: Int(arc4random_uniform(40)) ) let post2 = Post( username: "@nguyenhuy", name: "Huy Nguyen", photo: "https://avatars2.githubusercontent.com/u/587874?v=3&s=96", post: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", time: "1m", media: "", via: 1, likes: Int(arc4random_uniform(74)), comments: Int(arc4random_uniform(40)) ) let post3 = Post( username: "@veryyyylongusername", name: "Alex Long Name", photo: "https://avatars1.githubusercontent.com/u/8086633?v=3&s=96", post: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", time: "3:02", media: "http://www.ngmag.ru/upload/iblock/f93/f9390efc34151456598077c1ba44a94d.jpg", via: 2, likes: Int(arc4random_uniform(74)), comments: Int(arc4random_uniform(40)) ) let post4 = Post( username: "@vitalybaev", name: "Vitaly Baev", photo: "https://avatars0.githubusercontent.com/u/724423?v=3&s=96", post: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. https://github.com/facebook/AsyncDisplayKit Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", time: "yesterday", media: "", via: 1, likes: Int(arc4random_uniform(74)), comments: Int(arc4random_uniform(40)) ) let posts = [post1, post2, post3, post4] for _ in 0 ..< 100 { let j = Int(arc4random_uniform(74)) % 4 data.append(posts[j]) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension SocialController: ASTableDataSource { func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int { return data.count } func tableNode(_ tableNode: ASTableNode, nodeBlockForRowAt indexPath: IndexPath) -> ASCellNodeBlock { let post = data[indexPath.row] return { return PostNode(post: post) } } } extension SocialController: ASTableDelegate { func tableNode(_ tableNode: ASTableNode, didSelectRowAt indexPath: IndexPath) { print(indexPath) } }
mit
a762dba1b26de46926c223e9ce562442
34.08209
312
0.60987
4.426554
false
false
false
false
ahoppen/swift
test/decl/protocol/special/coding/class_codable_simple_conditional.swift
22
1926
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown -swift-version 4 class Conditional<T> { var x: T var y: T? init() { // expected-note@-1 2 {{did you mean 'init'}} fatalError() } func foo() { // They should receive a synthesized CodingKeys enum. let _ = Conditional.CodingKeys.self // The enum should have a case for each of the vars. let _ = Conditional.CodingKeys.x let _ = Conditional.CodingKeys.y // Static vars should not be part of the CodingKeys enum. let _ = Conditional.CodingKeys.z // expected-error {{type 'Conditional<T>.CodingKeys' has no member 'z'}} } } extension Conditional: Codable where T: Codable { // expected-note 2 {{where 'T' = 'Nonconforming'}} // expected-error@-1 2 {{implementation of 'Decodable' for non-final class cannot be automatically synthesized in extension because initializer requirement 'init(from:)' can only be satisfied by a 'required' initializer in the class definition}} } // They should receive synthesized init(from:) and an encode(to:). let _ = Conditional<Int>.init(from:) // expected-error {{type 'Conditional<Int>' has no member 'init(from:)'}} let _ = Conditional<Int>.encode(to:) // but only for Codable parameters. struct Nonconforming {} let _ = Conditional<Nonconforming>.init(from:) // expected-error {{type 'Conditional<Nonconforming>' has no member 'init(from:)'}} let _ = Conditional<Nonconforming>.encode(to:) // expected-error {{referencing instance method 'encode(to:)' on 'Conditional' requires that 'Nonconforming' conform to 'Decodable'}} // expected-error@-1 {{referencing instance method 'encode(to:)' on 'Conditional' requires that 'Nonconforming' conform to 'Encodable'}} // The synthesized CodingKeys type should not be accessible from outside the // struct. let _ = Conditional<Int>.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
apache-2.0
6f66194527d81dd4607ebee37f37985b
47.15
249
0.715472
4.115385
false
false
false
false
JGiola/swift
stdlib/public/core/SequenceAlgorithms.swift
5
31732
//===--- SequenceAlgorithms.swift -----------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // enumerated() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a sequence of pairs (*n*, *x*), where *n* represents a /// consecutive integer starting at zero and *x* represents an element of /// the sequence. /// /// This example enumerates the characters of the string "Swift" and prints /// each character along with its place in the string. /// /// for (n, c) in "Swift".enumerated() { /// print("\(n): '\(c)'") /// } /// // Prints "0: 'S'" /// // Prints "1: 'w'" /// // Prints "2: 'i'" /// // Prints "3: 'f'" /// // Prints "4: 't'" /// /// When you enumerate a collection, the integer part of each pair is a counter /// for the enumeration, but is not necessarily the index of the paired value. /// These counters can be used as indices only in instances of zero-based, /// integer-indexed collections, such as `Array` and `ContiguousArray`. For /// other collections the counters may be out of range or of the wrong type /// to use as an index. To iterate over the elements of a collection with its /// indices, use the `zip(_:_:)` function. /// /// This example iterates over the indices and elements of a set, building a /// list consisting of indices of names with five or fewer letters. /// /// let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"] /// var shorterIndices: [Set<String>.Index] = [] /// for (i, name) in zip(names.indices, names) { /// if name.count <= 5 { /// shorterIndices.append(i) /// } /// } /// /// Now that the `shorterIndices` array holds the indices of the shorter /// names in the `names` set, you can use those indices to access elements in /// the set. /// /// for i in shorterIndices { /// print(names[i]) /// } /// // Prints "Sofia" /// // Prints "Mateo" /// /// - Returns: A sequence of pairs enumerating the sequence. /// /// - Complexity: O(1) @inlinable // protocol-only public func enumerated() -> EnumeratedSequence<Self> { return EnumeratedSequence(_base: self) } } //===----------------------------------------------------------------------===// // min(), max() //===----------------------------------------------------------------------===// extension Sequence { /// Returns the minimum element in the sequence, using the given predicate as /// the comparison between elements. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// This example shows how to use the `min(by:)` method on a /// dictionary to find the key-value pair with the lowest value. /// /// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] /// let leastHue = hues.min { a, b in a.value < b.value } /// print(leastHue) /// // Prints "Optional((key: "Coral", value: 16))" /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` /// if its first argument should be ordered before its second /// argument; otherwise, `false`. /// - Returns: The sequence's minimum element, according to /// `areInIncreasingOrder`. If the sequence has no elements, returns /// `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable // protocol-only @warn_unqualified_access public func min( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Element? { var it = makeIterator() guard var result = it.next() else { return nil } while let e = it.next() { if try areInIncreasingOrder(e, result) { result = e } } return result } /// Returns the maximum element in the sequence, using the given predicate /// as the comparison between elements. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// This example shows how to use the `max(by:)` method on a /// dictionary to find the key-value pair with the highest value. /// /// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] /// let greatestHue = hues.max { a, b in a.value < b.value } /// print(greatestHue) /// // Prints "Optional((key: "Heliotrope", value: 296))" /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; /// otherwise, `false`. /// - Returns: The sequence's maximum element if the sequence is not empty; /// otherwise, `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable // protocol-only @warn_unqualified_access public func max( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Element? { var it = makeIterator() guard var result = it.next() else { return nil } while let e = it.next() { if try areInIncreasingOrder(result, e) { result = e } } return result } } extension Sequence where Element: Comparable { /// Returns the minimum element in the sequence. /// /// This example finds the smallest value in an array of height measurements. /// /// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9] /// let lowestHeight = heights.min() /// print(lowestHeight) /// // Prints "Optional(58.5)" /// /// - Returns: The sequence's minimum element. If the sequence has no /// elements, returns `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable @warn_unqualified_access public func min() -> Element? { return self.min(by: <) } /// Returns the maximum element in the sequence. /// /// This example finds the largest value in an array of height measurements. /// /// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9] /// let greatestHeight = heights.max() /// print(greatestHeight) /// // Prints "Optional(67.5)" /// /// - Returns: The sequence's maximum element. If the sequence has no /// elements, returns `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable @warn_unqualified_access public func max() -> Element? { return self.max(by: <) } } //===----------------------------------------------------------------------===// // starts(with:) //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether the initial elements of the /// sequence are equivalent to the elements in another sequence, using /// the given predicate as the equivalence test. /// /// The predicate must be a *equivalence relation* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areEquivalent(a, a)` is always `true`. (Reflexivity) /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry) /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then /// `areEquivalent(a, c)` is also `true`. (Transitivity) /// /// - Parameters: /// - possiblePrefix: A sequence to compare to this sequence. /// - areEquivalent: A predicate that returns `true` if its two arguments /// are equivalent; otherwise, `false`. /// - Returns: `true` if the initial elements of the sequence are equivalent /// to the elements of `possiblePrefix`; otherwise, `false`. If /// `possiblePrefix` has no elements, the return value is `true`. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `possiblePrefix`. @inlinable public func starts<PossiblePrefix: Sequence>( with possiblePrefix: PossiblePrefix, by areEquivalent: (Element, PossiblePrefix.Element) throws -> Bool ) rethrows -> Bool { var possiblePrefixIterator = possiblePrefix.makeIterator() for e0 in self { if let e1 = possiblePrefixIterator.next() { if try !areEquivalent(e0, e1) { return false } } else { return true } } return possiblePrefixIterator.next() == nil } } extension Sequence where Element: Equatable { /// Returns a Boolean value indicating whether the initial elements of the /// sequence are the same as the elements in another sequence. /// /// This example tests whether one countable range begins with the elements /// of another countable range. /// /// let a = 1...3 /// let b = 1...10 /// /// print(b.starts(with: a)) /// // Prints "true" /// /// Passing a sequence with no elements or an empty collection as /// `possiblePrefix` always results in `true`. /// /// print(b.starts(with: [])) /// // Prints "true" /// /// - Parameter possiblePrefix: A sequence to compare to this sequence. /// - Returns: `true` if the initial elements of the sequence are the same as /// the elements of `possiblePrefix`; otherwise, `false`. If /// `possiblePrefix` has no elements, the return value is `true`. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `possiblePrefix`. @inlinable public func starts<PossiblePrefix: Sequence>( with possiblePrefix: PossiblePrefix ) -> Bool where PossiblePrefix.Element == Element { return self.starts(with: possiblePrefix, by: ==) } } //===----------------------------------------------------------------------===// // elementsEqual() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether this sequence and another /// sequence contain equivalent elements in the same order, using the given /// predicate as the equivalence test. /// /// At least one of the sequences must be finite. /// /// The predicate must be a *equivalence relation* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areEquivalent(a, a)` is always `true`. (Reflexivity) /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry) /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then /// `areEquivalent(a, c)` is also `true`. (Transitivity) /// /// - Parameters: /// - other: A sequence to compare to this sequence. /// - areEquivalent: A predicate that returns `true` if its two arguments /// are equivalent; otherwise, `false`. /// - Returns: `true` if this sequence and `other` contain equivalent items, /// using `areEquivalent` as the equivalence test; otherwise, `false.` /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func elementsEqual<OtherSequence: Sequence>( _ other: OtherSequence, by areEquivalent: (Element, OtherSequence.Element) throws -> Bool ) rethrows -> Bool { var iter1 = self.makeIterator() var iter2 = other.makeIterator() while true { switch (iter1.next(), iter2.next()) { case let (e1?, e2?): if try !areEquivalent(e1, e2) { return false } case (_?, nil), (nil, _?): return false case (nil, nil): return true } } } } extension Sequence where Element: Equatable { /// Returns a Boolean value indicating whether this sequence and another /// sequence contain the same elements in the same order. /// /// At least one of the sequences must be finite. /// /// This example tests whether one countable range shares the same elements /// as another countable range and an array. /// /// let a = 1...3 /// let b = 1...10 /// /// print(a.elementsEqual(b)) /// // Prints "false" /// print(a.elementsEqual([1, 2, 3])) /// // Prints "true" /// /// - Parameter other: A sequence to compare to this sequence. /// - Returns: `true` if this sequence and `other` contain the same elements /// in the same order. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func elementsEqual<OtherSequence: Sequence>( _ other: OtherSequence ) -> Bool where OtherSequence.Element == Element { return self.elementsEqual(other, by: ==) } } //===----------------------------------------------------------------------===// // lexicographicallyPrecedes() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether the sequence precedes another /// sequence in a lexicographical (dictionary) ordering, using the given /// predicate to compare elements. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// - Parameters: /// - other: A sequence to compare to this sequence. /// - areInIncreasingOrder: A predicate that returns `true` if its first /// argument should be ordered before its second argument; otherwise, /// `false`. /// - Returns: `true` if this sequence precedes `other` in a dictionary /// ordering as ordered by `areInIncreasingOrder`; otherwise, `false`. /// /// - Note: This method implements the mathematical notion of lexicographical /// ordering, which has no connection to Unicode. If you are sorting /// strings to present to the end user, use `String` APIs that perform /// localized comparison instead. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func lexicographicallyPrecedes<OtherSequence: Sequence>( _ other: OtherSequence, by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Bool where OtherSequence.Element == Element { var iter1 = self.makeIterator() var iter2 = other.makeIterator() while true { if let e1 = iter1.next() { if let e2 = iter2.next() { if try areInIncreasingOrder(e1, e2) { return true } if try areInIncreasingOrder(e2, e1) { return false } continue // Equivalent } return false } return iter2.next() != nil } } } extension Sequence where Element: Comparable { /// Returns a Boolean value indicating whether the sequence precedes another /// sequence in a lexicographical (dictionary) ordering, using the /// less-than operator (`<`) to compare elements. /// /// This example uses the `lexicographicallyPrecedes` method to test which /// array of integers comes first in a lexicographical ordering. /// /// let a = [1, 2, 2, 2] /// let b = [1, 2, 3, 4] /// /// print(a.lexicographicallyPrecedes(b)) /// // Prints "true" /// print(b.lexicographicallyPrecedes(b)) /// // Prints "false" /// /// - Parameter other: A sequence to compare to this sequence. /// - Returns: `true` if this sequence precedes `other` in a dictionary /// ordering; otherwise, `false`. /// /// - Note: This method implements the mathematical notion of lexicographical /// ordering, which has no connection to Unicode. If you are sorting /// strings to present to the end user, use `String` APIs that /// perform localized comparison. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func lexicographicallyPrecedes<OtherSequence: Sequence>( _ other: OtherSequence ) -> Bool where OtherSequence.Element == Element { return self.lexicographicallyPrecedes(other, by: <) } } //===----------------------------------------------------------------------===// // contains() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether the sequence contains an /// element that satisfies the given predicate. /// /// You can use the predicate to check for an element of a type that /// doesn't conform to the `Equatable` protocol, such as the /// `HTTPResponse` enumeration in this example. /// /// enum HTTPResponse { /// case ok /// case error(Int) /// } /// /// let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)] /// let hadError = lastThreeResponses.contains { element in /// if case .error = element { /// return true /// } else { /// return false /// } /// } /// // 'hadError' == true /// /// Alternatively, a predicate can be satisfied by a range of `Equatable` /// elements or a general condition. This example shows how you can check an /// array for an expense greater than $100. /// /// let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41] /// let hasBigPurchase = expenses.contains { $0 > 100 } /// // 'hasBigPurchase' == true /// /// - Parameter predicate: A closure that takes an element of the sequence /// as its argument and returns a Boolean value that indicates whether /// the passed element represents a match. /// - Returns: `true` if the sequence contains an element that satisfies /// `predicate`; otherwise, `false`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func contains( where predicate: (Element) throws -> Bool ) rethrows -> Bool { for e in self { if try predicate(e) { return true } } return false } /// Returns a Boolean value indicating whether every element of a sequence /// satisfies a given predicate. /// /// The following code uses this method to test whether all the names in an /// array have at least five characters: /// /// let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"] /// let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 }) /// // allHaveAtLeastFive == true /// /// If the sequence is empty, this method returns `true`. /// /// - Parameter predicate: A closure that takes an element of the sequence /// as its argument and returns a Boolean value that indicates whether /// the passed element satisfies a condition. /// - Returns: `true` if the sequence contains only elements that satisfy /// `predicate`; otherwise, `false`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func allSatisfy( _ predicate: (Element) throws -> Bool ) rethrows -> Bool { return try !contains { try !predicate($0) } } } extension Sequence where Element: Equatable { /// Returns a Boolean value indicating whether the sequence contains the /// given element. /// /// This example checks to see whether a favorite actor is in an array /// storing a movie's cast. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// print(cast.contains("Marlon")) /// // Prints "true" /// print(cast.contains("James")) /// // Prints "false" /// /// - Parameter element: The element to find in the sequence. /// - Returns: `true` if the element was found in the sequence; otherwise, /// `false`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func contains(_ element: Element) -> Bool { if let result = _customContainsEquatableElement(element) { return result } else { return self.contains { $0 == element } } } } //===----------------------------------------------------------------------===// // reduce() //===----------------------------------------------------------------------===// extension Sequence { /// Returns the result of combining the elements of the sequence using the /// given closure. /// /// Use the `reduce(_:_:)` method to produce a single value from the elements /// of an entire sequence. For example, you can use this method on an array /// of numbers to find their sum or product. /// /// The `nextPartialResult` closure is called sequentially with an /// accumulating value initialized to `initialResult` and each element of /// the sequence. This example shows how to find the sum of an array of /// numbers. /// /// let numbers = [1, 2, 3, 4] /// let numberSum = numbers.reduce(0, { x, y in /// x + y /// }) /// // numberSum == 10 /// /// When `numbers.reduce(_:_:)` is called, the following steps occur: /// /// 1. The `nextPartialResult` closure is called with `initialResult`---`0` /// in this case---and the first element of `numbers`, returning the sum: /// `1`. /// 2. The closure is called again repeatedly with the previous call's return /// value and each element of the sequence. /// 3. When the sequence is exhausted, the last value returned from the /// closure is returned to the caller. /// /// If the sequence has no elements, `nextPartialResult` is never executed /// and `initialResult` is the result of the call to `reduce(_:_:)`. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// `initialResult` is passed to `nextPartialResult` the first time the /// closure is executed. /// - nextPartialResult: A closure that combines an accumulating value and /// an element of the sequence into a new accumulating value, to be used /// in the next call of the `nextPartialResult` closure or returned to /// the caller. /// - Returns: The final accumulated value. If the sequence has no elements, /// the result is `initialResult`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func reduce<Result>( _ initialResult: Result, _ nextPartialResult: (_ partialResult: Result, Element) throws -> Result ) rethrows -> Result { var accumulator = initialResult for element in self { accumulator = try nextPartialResult(accumulator, element) } return accumulator } /// Returns the result of combining the elements of the sequence using the /// given closure. /// /// Use the `reduce(into:_:)` method to produce a single value from the /// elements of an entire sequence. For example, you can use this method on an /// array of integers to filter adjacent equal entries or count frequencies. /// /// This method is preferred over `reduce(_:_:)` for efficiency when the /// result is a copy-on-write type, for example an Array or a Dictionary. /// /// The `updateAccumulatingResult` closure is called sequentially with a /// mutable accumulating value initialized to `initialResult` and each element /// of the sequence. This example shows how to build a dictionary of letter /// frequencies of a string. /// /// let letters = "abracadabra" /// let letterCount = letters.reduce(into: [:]) { counts, letter in /// counts[letter, default: 0] += 1 /// } /// // letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1] /// /// When `letters.reduce(into:_:)` is called, the following steps occur: /// /// 1. The `updateAccumulatingResult` closure is called with the initial /// accumulating value---`[:]` in this case---and the first character of /// `letters`, modifying the accumulating value by setting `1` for the key /// `"a"`. /// 2. The closure is called again repeatedly with the updated accumulating /// value and each element of the sequence. /// 3. When the sequence is exhausted, the accumulating value is returned to /// the caller. /// /// If the sequence has no elements, `updateAccumulatingResult` is never /// executed and `initialResult` is the result of the call to /// `reduce(into:_:)`. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// - updateAccumulatingResult: A closure that updates the accumulating /// value with an element of the sequence. /// - Returns: The final accumulated value. If the sequence has no elements, /// the result is `initialResult`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func reduce<Result>( into initialResult: __owned Result, _ updateAccumulatingResult: (_ partialResult: inout Result, Element) throws -> () ) rethrows -> Result { var accumulator = initialResult for element in self { try updateAccumulatingResult(&accumulator, element) } return accumulator } } //===----------------------------------------------------------------------===// // reversed() //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the elements of this sequence in reverse /// order. /// /// The sequence must be finite. /// /// - Returns: An array containing the elements of this sequence in /// reverse order. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func reversed() -> [Element] { // FIXME(performance): optimize to 1 pass? But Array(self) can be // optimized to a memcpy() sometimes. Those cases are usually collections, // though. var result = Array(self) let count = result.count for i in 0..<count/2 { result.swapAt(i, count - ((i + 1) as Int)) } return result } } //===----------------------------------------------------------------------===// // flatMap() //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the concatenated results of calling the /// given transformation with each element of this sequence. /// /// Use this method to receive a single-level collection when your /// transformation produces a sequence or collection for each element. /// /// In this example, note the difference in the result of using `map` and /// `flatMap` with a transformation that returns an array. /// /// let numbers = [1, 2, 3, 4] /// /// let mapped = numbers.map { Array(repeating: $0, count: $0) } /// // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]] /// /// let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) } /// // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] /// /// In fact, `s.flatMap(transform)` is equivalent to /// `Array(s.map(transform).joined())`. /// /// - Parameter transform: A closure that accepts an element of this /// sequence as its argument and returns a sequence or collection. /// - Returns: The resulting flattened array. /// /// - Complexity: O(*m* + *n*), where *n* is the length of this sequence /// and *m* is the length of the result. @inlinable public func flatMap<SegmentOfResult: Sequence>( _ transform: (Element) throws -> SegmentOfResult ) rethrows -> [SegmentOfResult.Element] { var result: [SegmentOfResult.Element] = [] for element in self { result.append(contentsOf: try transform(element)) } return result } } extension Sequence { /// Returns an array containing the non-`nil` results of calling the given /// transformation with each element of this sequence. /// /// Use this method to receive an array of non-optional values when your /// transformation produces an optional value. /// /// In this example, note the difference in the result of using `map` and /// `compactMap` with a transformation that returns an optional `Int` value. /// /// let possibleNumbers = ["1", "2", "three", "///4///", "5"] /// /// let mapped: [Int?] = possibleNumbers.map { str in Int(str) } /// // [1, 2, nil, nil, 5] /// /// let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) } /// // [1, 2, 5] /// /// - Parameter transform: A closure that accepts an element of this /// sequence as its argument and returns an optional value. /// - Returns: An array of the non-`nil` results of calling `transform` /// with each element of the sequence. /// /// - Complexity: O(*n*), where *n* is the length of this sequence. @inlinable // protocol-only public func compactMap<ElementOfResult>( _ transform: (Element) throws -> ElementOfResult? ) rethrows -> [ElementOfResult] { return try _compactMap(transform) } // The implementation of compactMap accepting a closure with an optional result. // Factored out into a separate function in order to be used in multiple // overloads. @inlinable // protocol-only @inline(__always) public func _compactMap<ElementOfResult>( _ transform: (Element) throws -> ElementOfResult? ) rethrows -> [ElementOfResult] { var result: [ElementOfResult] = [] for element in self { if let newElement = try transform(element) { result.append(newElement) } } return result } }
apache-2.0
68c84ed5e66ee6798572d02d0a59d89b
37.980344
83
0.603057
4.359714
false
false
false
false
JoeLago/MHGDB-iOS
MHGDB/Common/Tree/TreeSection.swift
1
3705
// // MIT License // Copyright (c) Gathering Hall Studios // import UIKit class TreeSection<T, U: TreeCellView<T>>: DetailSection { let tree: Tree<T> var selectedNode: Node<T>? var nodeArray: [Node<T>] var collapsedNodes = [Node<T>]() var selectionBlock: ((T) -> Void)? init(tree: Tree<T>, selectionBlock: ((T) -> Void)? = nil) { self.tree = tree self.nodeArray = tree.nodeArray self.selectionBlock = selectionBlock super.init() self.numberOfRows = self.nodeArray.count } override func initialize() { super.initialize() register(TreeCell<T, U>.self, identifier: "TREECELL") } override func cell(row: Int) -> UITableViewCell? { return dequeueCell(identifier: "TREECELL") ?? TreeCell<T, U>() } override func populate(cell: UITableViewCell, row: Int) { if let cell = cell as? TreeCell<T, U> { cell.node = nodeArray[row] cell.treeView.isSelected = cell.node === selectedNode } cell.selectionStyle = selectionBlock == nil ? .none : .default } override func selected(row: Int, navigationController: UINavigationController?) { selected(model: nodeArray[row].object) } func selected(model: T) { if let selectionBlock = selectionBlock { selectionBlock(model) } } override func longPress(row: Int) { //collapse(row: row) } } // MARK: Collapse/Expand // Maybe this would look better if we kept the collapsed state in the node? extension TreeSection { func indexPathsFor(section: Int, startRow: Int, count: Int) -> [IndexPath] { return indexPathsFor(section: section, startRow: startRow, endRow: startRow + count) } func indexPathsFor(section: Int, startRow: Int, endRow: Int) -> [IndexPath] { var indexPaths = [IndexPath]() for i in startRow ... endRow { indexPaths.append(IndexPath(item: i, section: section)) } return indexPaths } func collapse(row: Int) { let node = nodeArray[row] if collapsedNodes.contains(node) { return } let children = node.childArray if children.count < 1 { return } let oldCount = numberOfRows collapsedNodes.append(node) nodeArray.remove(objects: children) numberOfRows = nodeArray.count let difference = oldCount - numberOfRows if difference > 0 { let indexPaths = indexPathsFor(section: 0, startRow: row + 1, count: difference - 1) tableView?.beginUpdates() tableView?.reloadRows(at: [IndexPath(item: row, section: 0)], with: .automatic) tableView?.deleteRows(at: indexPaths, with: .automatic) tableView?.endUpdates() } } func expand(row: Int) { let node = nodeArray[row] // TODO: account for already collapsed var children = node.childArray collapsedNodes.remove(object: node) for childNode in children { if collapsedNodes.contains(childNode) { children.remove(object: childNode) } } nodeArray.insert(contentsOf: children, at: row + 1) let indexPaths = indexPathsFor(section: 0, startRow: row + 1, count: children.count - 1) tableView?.beginUpdates() tableView?.reloadRows(at: [IndexPath(item: row, section: 0)], with: .automatic) tableView?.insertRows(at: indexPaths, with: .automatic) tableView?.endUpdates() } }
mit
373919229c3278d23145c8a250780c0b
29.121951
96
0.588664
4.518293
false
false
false
false
CybercomPoland/ViperSideDrawer
ViperSideDrawer/SwipeInteractionController.swift
1
1160
// // SwipeInteractionController.swift // ViperSideDrawer // // Created by Adrian Ziemecki on 25/10/2017. // Copyright © 2017 Aleksander Maj. All rights reserved. // import Foundation public class SwipeInteractionController { let swipeDirection: SideDrawerPresentationDirection let transitionThresholdPercent: CGFloat public let percentInteractiveTransition = PercentInteractiveTransition() public init(swipeDirection: SideDrawerPresentationDirection, transitionThreshold: CGFloat) { self.transitionThresholdPercent = transitionThreshold self.swipeDirection = swipeDirection } public func handleScreenEdgePanGesture (gesture: UIScreenEdgePanGestureRecognizer, view: UIView, triggerSegue: () -> ()) { let translation = gesture.translation(in: view) let progress = TransitionHelper.calculateProgress(translation, viewBounds: view.bounds, direction: swipeDirection) TransitionHelper.translateGestureToInteractor(gesture.state, progress: progress, percentThreshold: transitionThresholdPercent, percentInteractiveTransition: percentInteractiveTransition, triggerSegue: triggerSegue) } }
mit
e4c2a36bd1ef32720b941849a11dd2c4
41.925926
222
0.787748
5.341014
false
false
false
false
eoger/firefox-ios
Client/Frontend/Browser/TabTrayButtonExtensions.swift
12
1797
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit class PrivateModeButton: ToggleButton, PrivateModeUI { var offTint = UIColor.black var onTint = UIColor.black override init(frame: CGRect) { super.init(frame: frame) accessibilityLabel = PrivateModeStrings.toggleAccessibilityLabel accessibilityHint = PrivateModeStrings.toggleAccessibilityHint let maskImage = UIImage(named: "smallPrivateMask")?.withRenderingMode(.alwaysTemplate) setImage(maskImage, for: []) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func applyUIMode(isPrivate: Bool) { isSelected = isPrivate tintColor = isPrivate ? onTint : offTint imageView?.tintColor = tintColor accessibilityValue = isSelected ? PrivateModeStrings.toggleAccessibilityValueOn : PrivateModeStrings.toggleAccessibilityValueOff } } extension UIButton { static func newTabButton() -> UIButton { let newTab = UIButton() newTab.setImage(UIImage.templateImageNamed("quick_action_new_tab"), for: .normal) newTab.accessibilityLabel = NSLocalizedString("New Tab", comment: "Accessibility label for the New Tab button in the tab toolbar.") return newTab } } extension TabsButton { static func tabTrayButton() -> TabsButton { let tabsButton = TabsButton() tabsButton.countLabel.text = "0" tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility Label for the tabs button in the tab toolbar") return tabsButton } }
mpl-2.0
5a421d8b60bcef8d265c4e69f24ce28e
35.673469
141
0.702282
5.105114
false
false
false
false
rnystrom/GitHawk
Classes/View Controllers/TabBarControllerDelegate.swift
1
1821
// // TabBarControllerDelegate.swift // Freetime // // Created by Ryan Nystrom on 9/26/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit final class TabBarControllerDelegate: NSObject, UITabBarControllerDelegate { private var tapCount = 0 private weak var previousSelectedViewController: UIViewController? func tabBarController( _ tabBarController: UITabBarController, didSelect viewController: UIViewController ) { // will be nil on first start let tabDidNotChange = previousSelectedViewController == nil || previousSelectedViewController == viewController // confirm at root VC if tabBarController.selectedViewController == viewController, let nav = viewController as? UINavigationController, // don't handle taps when the nav is popping nav.transitionCoordinator?.viewController(forKey: UITransitionContextViewControllerKey.from) == nil, let root = nav.viewControllers.first as? TabNavRootViewControllerType { tapCount += 1 DispatchQueue.main.asyncAfter(deadline: .now() + 0.27, execute: { let count = self.tapCount // make sure that on the same VC that queued the tap-check if tabBarController.selectedViewController == viewController { if count == 1 && tabDidNotChange { root.didSingleTapTab() } else if count > 1 { root.didDoubleTapTab() } } self.resetTaps() }) } else { resetTaps() } previousSelectedViewController = viewController } func resetTaps() { tapCount = 0 } }
mit
5fcffc6d7947123e8125d5ac2021e7bd
31.5
112
0.607143
5.705329
false
false
false
false
OrdnanceSurvey/search-swift
OSSearchTests/ResponseParsingTests.swift
1
8691
// // SearchTests.swift // SearchTests // // Created by David Haynes on 25/02/2016. // Copyright © 2016 Ordnance Survey. All rights reserved. // import XCTest import Nimble import OSAPIResponse @testable import Search class ResponseParsingTests: XCTestCase { func testItIsPossibleToParseAResponse() { let data = NSData(contentsOfURL: Bundle().URLForResource("test-response", withExtension: "json")!)! let result = SearchResponse.parse(fromData: data, withStatus: 200) switch result { case .Success(let response): validateResponse(response) default: fail("Unexpected result") } } private func validateResponse(response: SearchResponse) { validateResults(response.results) } private func validateResults(results: [SearchResult]) { expect(results.count).to(equal(1)) expect(results.first).toNot(beNil()) let result = results.first! expect(result.language).to(equal("EN")) expect(result.uprn).to(equal("200010019924")) expect(result.address).to(equal("ORDNANCE SURVEY, 4, ADANAC DRIVE, NURSLING, SOUTHAMPTON, SO16 0AS")) expect(result.organisationName).to(equal("ORDNANCE SURVEY")) expect(result.buildingNumber).to(equal("4")) expect(result.thoroughfareName).to(equal("ADANAC DRIVE")) expect(result.dependentLocality).to(equal("NURSLING")) expect(result.postTown).to(equal("SOUTHAMPTON")) expect(result.postcode).to(equal("SO16 0AS")) expect(result.rpc).to(equal("2")) expect(result.xCoordinate).to(equal(437318.0)) expect(result.yCoordinate).to(equal(115539.0)) expect(result.status).to(equal("APPROVED")) expect(result.logicalStatusCode).to(equal("1")) expect(result.classificationCode).to(equal("CO01GV")) expect(result.classificationCodeDescription).to(equal("Central Government Service")) expect(result.localCustodianCode).to(equal(1760)) expect(result.localCustodianCodeDescription).to(equal("TEST VALLEY")) expect(result.postalAddressCode).to(equal("S")) expect(result.postalAddressCodeDescription).to(equal("A single address")) expect(result.blpuStateCode).to(equal("2")) expect(result.blpuStateCodeDescription).to(equal("In use")) expect(result.topographyLayerToid).to(equal("osgb1000002682081995")) expect(result.lastUpdateDate).to(equal("01/09/2010")) expect(result.entryDate).to(equal("01/09/2010")) expect(result.blpuStateDate).to(equal("01/09/2010")) expect(result.match).to(equal(0.6)) expect(result.matchDescription).to(equal("NO MATCH")) } func testNoDataReturnsCorrectError() { let data: NSData? = nil let result = SearchResponse.parse(fromData: data, withStatus: 200) switch result { case .Failure(let error as ResponseError): switch error { case .NoDataReceived: break default: fail("No data in response should raise correct error.") } default: fail("No data in response should raise an error.") } } func testNon200HttpResponseReturnsCorrectError() { let data: NSData? = NSData(contentsOfURL: Bundle().URLForResource("test-response", withExtension: "json")!)! let result = SearchResponse.parse(fromData: data, withStatus: 404) switch result { case .Failure(let error as ResponseError): switch error { case .NotFound: break default: fail("Non 200 response should raise correct error.") } default: fail("Non 200 response should raise an error.") } } func testInvalidHeaderJsonReturnsDeserialiseError() { let data: NSData? = NSData(contentsOfURL: Bundle().URLForResource("test-response-bad-header", withExtension: "json")!)! let result = SearchResponse.parse(fromData: data, withStatus: 200) switch result { case .Failure(let error as ResponseError): switch error { case .FailedToDeserialiseJSON: break default: fail("Invalid header JSON should raise correct error.") } default: fail("Invalid header JSON should raise an error.") } } func testInvalidResultsJsonReturnsDeserialiseError() { let data: NSData? = NSData(contentsOfURL: Bundle().URLForResource("test-response-bad-results", withExtension: "json")!)! let result = SearchResponse.parse(fromData: data, withStatus: 200) switch result { case .Failure(let error as ResponseError): switch error { case .FailedToDeserialiseJSON: break default: fail("Invalid results JSON should raise correct error.") } default: fail("Invalid results JSON should raise an error.") } } func testInvalidJsonReturnsParseError() { let data: NSData? = NSData(base64EncodedString: "<!:@", options: .IgnoreUnknownCharacters) let result = SearchResponse.parse(fromData: data, withStatus: 200) switch result { case .Failure(let error as ResponseError): switch error { case .FailedToParseJSON: break default: fail("Invalid JSON should raise correct error.") } default: fail("Invalid JSON should raise an error.") } } func testResponseWithOptionalFieldsParsesCorrectly() { let data: NSData? = NSData(contentsOfURL: Bundle().URLForResource("test-response-optional-fields", withExtension: "json")!)! let result = SearchResponse.parse(fromData: data, withStatus: 200) switch result { case .Success(let response): expect(response.results.count).to(equal(3)) default: fail("Unexpected result") } } func testItIsPossibleToParseAnOpenNamesResponse() { let data = NSData(contentsOfURL: Bundle().URLForResource("opennamesresponse", withExtension: "json")!)! let result = OpenNamesResponse.parse(fromData: data, withStatus: 200) switch result { case .Success(let response): expect(response.results).to(haveCount(1)) let result = response.results.first! expect(result.id).to(equal("osgb4000000023852685")) expect(result.namesUri).to(equal("http://data.ordnancesurvey.co.uk/id/osgb4000000023852685")) expect(result.name1).to(equal("Adanac Drive")) expect(result.type).to(equal("transportNetwork")) expect(result.localType).to(equal("Named Road")) expect(result.geometryX).to(equal(437283.534)) expect(result.geometryY).to(equal(115391.881)) expect(result.mostDetailViewRes).to(equal(4000)) expect(result.leastDetailViewRes).to(equal(20000)) expect(result.mbrXmin).to(equal(437157.31)) expect(result.mbrYmin).to(equal(115103.252)) expect(result.mbrXmax).to(equal(437400.826)) expect(result.mbrYmax).to(equal(115647.684)) expect(result.postcodeDistrict).to(equal("SO16")) expect(result.postcodeDistrictUri).to(equal("http://data.ordnancesurvey.co.uk/id/postcodedistrict/SO16")) expect(result.populatedPlace).to(equal("Nursling")) expect(result.populatedPlaceUri).to(equal("http://data.ordnancesurvey.co.uk/id/4000000074566646")) expect(result.districtBorough).to(equal("Test Valley")) expect(result.districtBoroughUri).to(equal("http://data.ordnancesurvey.co.uk/id/7000000000043511")) expect(result.districtBoroughType).to(equal("http://data.ordnancesurvey.co.uk/ontology/admingeo/District")) expect(result.countyUnitary).to(equal("Hampshire")) expect(result.countyUnitaryUri).to(equal("http://data.ordnancesurvey.co.uk/id/7000000000017765")) expect(result.countyUnitaryType).to(equal("http://data.ordnancesurvey.co.uk/ontology/admingeo/County")) expect(result.region).to(equal("South East")) expect(result.regionUri).to(equal("http://data.ordnancesurvey.co.uk/id/7000000000041421")) expect(result.country).to(equal("England")) expect(result.countryUri).to(equal("http://data.ordnancesurvey.co.uk/id/country/england")) default: fail("Unexpected result") } } }
apache-2.0
a17134e27d52f7a861fa2ce1ea62da13
43.336735
132
0.636709
4.187952
false
true
false
false
mentrena/SyncKit
SyncKit/Classes/CoreData/QSSyncedEntity+CoreDataProperties.swift
1
1986
// // QSSyncedEntity+CoreDataProperties.swift // // // Created by Manuel Entrena on 02/06/2019. // // import Foundation import CoreData extension QSSyncedEntity { @nonobjc class func fetchRequest() -> NSFetchRequest<QSSyncedEntity> { return NSFetchRequest<QSSyncedEntity>(entityName: "QSSyncedEntity") } @NSManaged var changedKeys: String? @NSManaged var entityType: String? @NSManaged var identifier: String? @NSManaged var originObjectID: String? @NSManaged var state: NSNumber? @NSManaged var updatedDate: NSDate? @NSManaged var pendingRelationships: NSSet? @NSManaged var record: QSRecord? @NSManaged var share: QSSyncedEntity? @NSManaged var shareForEntity: QSSyncedEntity? } // MARK: Generated accessors for pendingRelationships extension QSSyncedEntity { @objc(addPendingRelationshipsObject:) @NSManaged func addToPendingRelationships(_ value: QSPendingRelationship) @objc(removePendingRelationshipsObject:) @NSManaged func removeFromPendingRelationships(_ value: QSPendingRelationship) @objc(addPendingRelationships:) @NSManaged func addToPendingRelationships(_ values: NSSet) @objc(removePendingRelationships:) @NSManaged func removeFromPendingRelationships(_ values: NSSet) var entityState: SyncedEntityState { set { state = newValue.rawValue as NSNumber } get { return SyncedEntityState(rawValue: state?.intValue ?? 0)! } } var isShare: Bool { return entityType == "CKShare" } var changedKeysArray: [String] { get { guard let keys = changedKeys, !keys.isEmpty else { return [] } return keys.components(separatedBy: ",") } set { if newValue.count > 0 { changedKeys = newValue.joined(separator: ",") } else { changedKeys = nil } } } }
mit
e419bb748aabf60d7e4bbe905b1e8430
25.837838
82
0.652064
4.651054
false
false
false
false
KrishMunot/swift
test/DebugInfo/generic_arg2.swift
6
893
// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s // CHECK: define hidden void @_TFC12generic_arg25Class3foo{{.*}}, %swift.type* %U // CHECK: [[Y:%.*]] = getelementptr inbounds %C12generic_arg25Class, %C12generic_arg25Class* %2, i32 0, i32 0, i32 0 // store %swift.opaque* %[[Y]], %swift.opaque** %[[Y_SHADOW:.*]], align // CHECK: call void @llvm.dbg.declare(metadata %swift.opaque** %y.addr, metadata ![[U:.*]], metadata !{{[0-9]+}}) // Make sure there is no conflicting dbg.value for this variable.x // CHECK-NOT: dbg.value{{.*}}metadata ![[U]] class Class <T> { // CHECK: ![[U]] = !DILocalVariable(name: "y", arg: 2{{.*}} line: [[@LINE+1]], func foo<U>(_ x: T, y: U) {} func bar(_ x: String, y: Int64) {} init() {} } func main() { var object: Class<String> = Class() var x = "hello" var y : Int64 = 1234 object.bar(x, y: y) object.foo(x, y: y) } main()
apache-2.0
293b421a36086a79dc02296490c4c781
33.346154
116
0.597984
2.899351
false
false
false
false
qds-hoi/suracare
suracare/suracare/Core/Library/SwiftValidator/Rules/FloatRule.swift
1
1604
// // FloatRule.swift // Validator // // Created by Cameron McCord on 5/5/15. // Copyright (c) 2015 jpotts18. All rights reserved. // import Foundation /** `FloatRule` is a subclass of Rule that defines how check if a value is a floating point value. */ public class FloatRule:Rule { /// Error message to be displayed if validation fails. private var message : String /** Initializes a `FloatRule` object to validate that the text of a field is a floating point number. - parameter message: String of error message. - returns: An initialized object, or nil if an object could not be created for some reason that would not result in an exception. */ public init(message : String = "This must be a number with or without a decimal"){ self.message = message } /** Used to validate field. - parameter value: String to checked for validation. - returns: Boolean value. True if validation is successful; False if validation fails. */ public func validate(value: String) -> Bool { let regex = try? NSRegularExpression(pattern: "^[-+]?(\\d*[.])?\\d+$", options: []) if let regex = regex { let match = regex.numberOfMatchesInString(value, options: [], range: NSRange(location: 0, length: value.characters.count)) return match == 1 } return false } /** Displays error message when field fails validation. - returns: String of error message. */ public func errorMessage() -> String { return message } }
mit
91fa2ac88f79fd636b1caa6aa0b0fe25
30.45098
134
0.634663
4.467967
false
false
false
false
karthik-ios-dev/MySwiftExtension
Pod/Classes/Device-Extension.swift
1
7258
// // Device.swift // imHome // // Created by Kevin Xu on 2/9/15. Updated on 6/20/15. // Copyright (c) 2015 Alpha Labs, Inc. All rights reserved. // import Foundation import UIKit public extension NSBundle { var applicationVersionNumber: String { if let version = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String { return version } return "Version Number Not Available" } var applicationBuildNumber: String { if let build = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String { return build } return "Build Number Not Available" } } // MARK: - Device Structure struct Device { // MARK: - Singletons static var CurrentDevice: UIDevice { struct Singleton { static let device = UIDevice.currentDevice() } return Singleton.device } static var CurrentDeviceVersion: Float { struct Singleton { static let version = Float(UIDevice.currentDevice().systemVersion) } return Singleton.version! } static var CurrentDeviceHeight: CGFloat { struct Singleton { static let height = UIScreen.mainScreen().bounds.size.height } return Singleton.height } // MARK: - Device Idiom Checks static var PHONE_OR_PAD: String { if isPhone() { return "iPhone" } else if isPad() { return "iPad" } return "Not iPhone nor iPad" } static var DEBUG_OR_RELEASE: String { #if DEBUG return "Debug" #else return "Release" #endif } static var SIMULATOR_OR_DEVICE: String { #if (arch(i386) || arch(x86_64)) && os(iOS) return "Simulator" #else return "Device" #endif } static func isPhone() -> Bool { return CurrentDevice.userInterfaceIdiom == .Phone } static func isPad() -> Bool { return CurrentDevice.userInterfaceIdiom == .Pad } static func isDebug() -> Bool { return DEBUG_OR_RELEASE == "Debug" } static func isRelease() -> Bool { return DEBUG_OR_RELEASE == "Release" } static func isSimulator() -> Bool { return SIMULATOR_OR_DEVICE == "Simulator" } static func isDevice() -> Bool { return SIMULATOR_OR_DEVICE == "Device" } // MARK: - Device Version Checks enum Versions: Float { case Five = 5.0 case Six = 6.0 case Seven = 7.0 case Eight = 8.0 case Nine = 9.0 } static func isVersion(version: Versions) -> Bool { return CurrentDeviceVersion >= version.rawValue && CurrentDeviceVersion < (version.rawValue + 1.0) } static func isVersionOrLater(version: Versions) -> Bool { return CurrentDeviceVersion >= version.rawValue } static func isVersionOrEarlier(version: Versions) -> Bool { return CurrentDeviceVersion < (version.rawValue + 1.0) } static var CURRENT_VERSION: String { return "\(CurrentDeviceVersion)" } // MARK: iOS 5 Checks static func IS_OS_5() -> Bool { return isVersion(.Five) } static func IS_OS_5_OR_LATER() -> Bool { return isVersionOrLater(.Five) } static func IS_OS_5_OR_EARLIER() -> Bool { return isVersionOrEarlier(.Five) } // MARK: iOS 6 Checks static func IS_OS_6() -> Bool { return isVersion(.Six) } static func IS_OS_6_OR_LATER() -> Bool { return isVersionOrLater(.Six) } static func IS_OS_6_OR_EARLIER() -> Bool { return isVersionOrEarlier(.Six) } // MARK: iOS 7 Checks static func IS_OS_7() -> Bool { return isVersion(.Seven) } static func IS_OS_7_OR_LATER() -> Bool { return isVersionOrLater(.Seven) } static func IS_OS_7_OR_EARLIER() -> Bool { return isVersionOrEarlier(.Seven) } // MARK: iOS 8 Checks static func IS_OS_8() -> Bool { return isVersion(.Eight) } static func IS_OS_8_OR_LATER() -> Bool { return isVersionOrLater(.Eight) } static func IS_OS_8_OR_EARLIER() -> Bool { return isVersionOrEarlier(.Eight) } // MARK: iOS 9 Checks static func IS_OS_9() -> Bool { return isVersion(.Nine) } static func IS_OS_9_OR_LATER() -> Bool { return isVersionOrLater(.Nine) } static func IS_OS_9_OR_EARLIER() -> Bool { return isVersionOrEarlier(.Nine) } // MARK: - Device Size Checks enum Heights: CGFloat { case Inches_3_5 = 480 case Inches_4 = 568 case Inches_4_7 = 667 case Inches_5_5 = 736 } static func isSize(height: Heights) -> Bool { return CurrentDeviceHeight == height.rawValue } static func isSizeOrLarger(height: Heights) -> Bool { return CurrentDeviceHeight >= height.rawValue } static func isSizeOrSmaller(height: Heights) -> Bool { return CurrentDeviceHeight <= height.rawValue } static var CURRENT_SIZE: String { if IS_3_5_INCHES() { return "3.5 Inches" } else if IS_4_INCHES() { return "4 Inches" } else if IS_4_7_INCHES() { return "4.7 Inches" } else if IS_5_5_INCHES() { return "5.5 Inches" } return "\(CurrentDeviceHeight) Points" } // MARK: Retina Check static func IS_RETINA() -> Bool { return UIScreen.mainScreen().respondsToSelector("scale") } // MARK: 3.5 Inch Checks static func IS_3_5_INCHES() -> Bool { return isPhone() && isSize(.Inches_3_5) } static func IS_3_5_INCHES_OR_LARGER() -> Bool { return isPhone() && isSizeOrLarger(.Inches_3_5) } static func IS_3_5_INCHES_OR_SMALLER() -> Bool { return isPhone() && isSizeOrSmaller(.Inches_3_5) } // MARK: 4 Inch Checks static func IS_4_INCHES() -> Bool { return isPhone() && isSize(.Inches_4) } static func IS_4_INCHES_OR_LARGER() -> Bool { return isPhone() && isSizeOrLarger(.Inches_4) } static func IS_4_INCHES_OR_SMALLER() -> Bool { return isPhone() && isSizeOrSmaller(.Inches_4) } // MARK: 4.7 Inch Checks static func IS_4_7_INCHES() -> Bool { return isPhone() && isSize(.Inches_4_7) } static func IS_4_7_INCHES_OR_LARGER() -> Bool { return isPhone() && isSizeOrLarger(.Inches_4_7) } static func IS_4_7_INCHES_OR_SMALLER() -> Bool { return isPhone() && isSizeOrLarger(.Inches_4_7) } // MARK: 5.5 Inch Checks static func IS_5_5_INCHES() -> Bool { return isPhone() && isSize(.Inches_5_5) } static func IS_5_5_INCHES_OR_LARGER() -> Bool { return isPhone() && isSizeOrLarger(.Inches_5_5) } static func IS_5_5_INCHES_OR_SMALLER() -> Bool { return isPhone() && isSizeOrLarger(.Inches_5_5) } // MARK: - International Checks static var CURRENT_REGION: String { return NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String } }
mit
46b2116de1f78f33c7a240186a3815c1
22.644951
106
0.574952
3.860638
false
false
false
false
xwu/swift
test/Generics/sr10532.swift
1
1349
// RUN: %target-typecheck-verify-swift -debug-generic-signatures -requirement-machine-protocol-signatures=on 2>&1 | %FileCheck %s // CHECK: sr10532.(file).ScalarProtocol@ // CHECK-NEXT: Requirement signature: <Self where Self : ScalarMultiplicative, Self == Self.Scalar> public protocol ScalarProtocol: ScalarMultiplicative where Self == Scalar { } // CHECK: sr10532.(file).ScalarMultiplicative@ // CHECK-NEXT: Requirement signature: <Self where Self.Scalar : ScalarProtocol> public protocol ScalarMultiplicative { associatedtype Scalar : ScalarProtocol } // CHECK: sr10532.(file).MapReduceArithmetic@ // CHECK-NEXT: Requirement signature: <Self where Self : Collection, Self : ScalarMultiplicative, Self.Element : ScalarMultiplicative, Self.Scalar == Self.Element.Scalar> public protocol MapReduceArithmetic : ScalarMultiplicative, Collection where Element : ScalarMultiplicative, Scalar == Element.Scalar { } // CHECK: sr10532.(file).Tensor@ // CHECK-NEXT: Requirement signature: <Self where Self : MapReduceArithmetic, Self.Element : BinaryFloatingPoint, Self.Element : ScalarProtocol> public protocol Tensor : MapReduceArithmetic where Scalar : BinaryFloatingPoint, Element == Scalar { var magnitude: Scalar { get set } } extension Tensor { public var magnitude: Scalar { return self.reduce(0) { $0 + $1 * $1 }.squareRoot() } }
apache-2.0
b7366ee83ac32d7964612ace6a648505
48.962963
170
0.765011
4.452145
false
false
false
false
gyro-n/PaymentsIos
Example/Tests/BaseTest.swift
1
4442
// // BaseTest.swift // GyronPayments // // Created by Ye David on 11/15/16. // Copyright © 2016 gyron. All rights reserved. // import XCTest @testable import GyronPayments class BaseTest: XCTestCase, ResourceDelegate { var endPoint = defaultEndPoint var apiId = "" var apiSecret = "" var username = "" var password = "" var loginToken = "" var testmode = "" var api: SDK? = nil var mockServer: MockApiServer? override func setUp() { sleep(6) super.setUp() self.endPoint = ProcessInfo.processInfo.environment["API_ENDPOINT"] ?? self.getEnvironmentVariable(key: "API_END_POINT") print("end point: \(self.endPoint)") self.apiId = self.getEnvironmentVariable(key: "API_APP_ID") self.apiSecret = self.getEnvironmentVariable(key: "API_APP_SECRET") self.username = self.getEnvironmentVariable(key: "API_USERNAME") self.password = self.getEnvironmentVariable(key: "API_PASSWORD") self.api = SDK(options: Options(endPoint: endPoint, apiId: apiId, secret: apiSecret)) // Set up mock server self.testmode = ProcessInfo.processInfo.environment["API_TEST_MODE"] ?? "STAGING" print("mode: \(testmode)") if (testmode == "MOCK") { self.mockServer = MockApiServer(port: 9000) self.mockServer?.run() print("debug mode") } else { // Get login token let asyncExpectation = self.expectation(description: "longRunningFunction") self.api?.authenticationResource?.authenticate(email: self.username, password: self.password, callback: nil).then(execute: { a -> Void in self.loginToken = a.token asyncExpectation.fulfill() }).catch(execute: { e -> Void in print(e.localizedDescription) asyncExpectation.fulfill() }) self.waitForExpectations(timeout: 5) { error in XCTAssertNil(error, "Something went horribly wrong") XCTAssert(self.loginToken != "", "Login token does not exist") } } } override func tearDown() { if (self.testmode == "MOCK") { self.mockServer?.stop() self.testmode = "" self.api = nil self.endPoint = "" self.apiId = "" self.apiSecret = "" super.tearDown() } else { let asyncExpectation = self.expectation(description: "longRunningFunction") var err: ErrorResponse? let api = SDK(options: Options(endPoint: self.endPoint, loginToken: self.loginToken)) api.authenticationResource?.logout(callback: { a, e in err = e asyncExpectation.fulfill() }) self.waitForExpectations(timeout: 5) { error in XCTAssertNil(error, "Something went horribly wrong") XCTAssertNil(err, "Logout went wrong: \(String(describing: err?.status))") self.loginToken = "" self.testmode = "" self.api = nil self.endPoint = "" self.apiId = "" self.apiSecret = "" super.tearDown() } } } func getEnvironmentVariable(key: String) -> String { var result = "" let testBundle = Bundle(for: type(of: self)) let envDictionary: [String:String] = testBundle.infoDictionary!["LSEnvironment"] as! [String:String] if (envDictionary.index(forKey: key) != nil) { if let e = envDictionary[key] { let unwrapped = e if (unwrapped != "") { result = unwrapped } } } return result } func onSendFailure(error: ErrorResponse) { print(error) } func onSendSuccess<BaseModel>(responseData: BaseModel) { print(responseData) } func onError(error: Error) { print(error) } func getErrorString(error: Error?) -> String { if let e = error { let f = e as! WrappedError switch (f) { case .ResponseError(let d): return ErrorUtils.convertErrorArrayToString(values: d.errors) } } else { return "" } } }
mit
4f935a18fda1631a4a08d8fc6583a3ce
33.968504
149
0.550777
4.664916
false
true
false
false
suragch/Chimee-iOS
Chimee/HistoryDataHelper.swift
1
5080
import SQLite class HistoryDataHelper: DataHelperProtocol { static let HISTORY_MESSAGE_TABLE_NAME = "history" // history table static let historyMessageTable = Table(HISTORY_MESSAGE_TABLE_NAME) static let historyId = Expression<Int64>("_id") static let historyDate = Expression<Int64>("datetime") static let historyMessage = Expression<String>("message") typealias T = Message static func createTable() throws { guard let db = SQLiteDataStore.sharedInstance.ChimeeDB else { throw DataAccessError.datastore_Connection_Error } // create table do { let _ = try db.run( historyMessageTable.create(ifNotExists: false) {t in t.column(historyId, primaryKey: true) t.column(historyDate) t.column(historyMessage) }) } catch _ { // Error throw if table already exists // FIXME: This is relying on throwing an error every time. Perhaps not the best. http://stackoverflow.com/q/37185087 return } } static func insert(_ item: T) throws -> Int64 { // error checking guard let db = SQLiteDataStore.sharedInstance.ChimeeDB else { throw DataAccessError.datastore_Connection_Error } guard let dateToInsert = item.dateTime, let messageToInsert = item.messageText else { throw DataAccessError.nil_In_Data } // do the insert let insert = historyMessageTable.insert(historyDate <- dateToInsert, historyMessage <- messageToInsert) do { let rowId = try db.run(insert) guard rowId > 0 else { throw DataAccessError.insert_Error } return rowId } catch _ { throw DataAccessError.insert_Error } } static func insertMessage(_ messageToInsert: String) throws -> Int64 { // error checking guard let db = SQLiteDataStore.sharedInstance.ChimeeDB else { throw DataAccessError.datastore_Connection_Error } // do the insert let dateToInsert = Int64(NSDate().timeIntervalSince1970) let insert = historyMessageTable.insert(historyDate <- dateToInsert, historyMessage <- messageToInsert) do { let rowId = try db.run(insert) guard rowId > 0 else { throw DataAccessError.insert_Error } return rowId } catch _ { throw DataAccessError.insert_Error } } static func delete(_ item: T) throws -> Void { guard let db = SQLiteDataStore.sharedInstance.ChimeeDB else { throw DataAccessError.datastore_Connection_Error } if let id = item.messageId { let query = historyMessageTable.filter(historyId == id) do { let tmp = try db.run(query.delete()) guard tmp == 1 else { throw DataAccessError.delete_Error } } catch _ { throw DataAccessError.delete_Error } } } static func deleteAll() throws -> Void { guard let db = SQLiteDataStore.sharedInstance.ChimeeDB else { throw DataAccessError.datastore_Connection_Error } do { _ = try db.run(historyMessageTable.delete()) } catch _ { throw DataAccessError.delete_Error } } static func findAll() throws -> [T]? { guard let db = SQLiteDataStore.sharedInstance.ChimeeDB else { throw DataAccessError.datastore_Connection_Error } var retArray = [T]() do { let items = try db.prepare(historyMessageTable) for item in items { retArray.append(Message(messageId: item[historyId], dateTime: item[historyDate], messageText: item[historyMessage])) } } catch _ { throw DataAccessError.search_Error } return retArray } static func findRange(_ rangeOfRows: Range<Int>) throws -> [T]? { guard let db = SQLiteDataStore.sharedInstance.ChimeeDB else { throw DataAccessError.datastore_Connection_Error } var retArray = [T]() do { let query = historyMessageTable.order(historyDate.desc).limit(rangeOfRows.upperBound - rangeOfRows.lowerBound, offset: rangeOfRows.lowerBound) let items = try db.prepare(query) for item in items { retArray.append(Message(messageId: item[historyId], dateTime: item[historyDate], messageText: item[historyMessage])) } } catch _ { throw DataAccessError.search_Error } return retArray } }
mit
0f52408b7f4e4d73b0eaee441056cdf0
31.564103
154
0.56063
5.034688
false
false
false
false
hejeffery/Animation
Animation/Animation/Main/View/MainTableViewCell.swift
1
2016
// // MainTableViewCell.swift // Animation // // Created by jhe.jeffery on 2017/9/7. // Copyright © 2017年 JefferyHe. All rights reserved. // import UIKit class MainTableViewCell: UITableViewCell { // subviews private var titleLabel: UILabel! // model var item: Item? { didSet { guard let content = item?.title else { titleLabel.text = "----" return } titleLabel.text = content } } // init override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let marginX: CGFloat = 15.0 let titleLabelX = marginX let titleLabelY: CGFloat = 0.0 let titleLabelW = bounds.width - marginX * 2 let titleLabelH = bounds.height titleLabel.frame = CGRect(x: titleLabelX, y: titleLabelY, width: titleLabelW, height: titleLabelH) } // setup subviews private func setupViews() { let titleLabel = UILabel.init() titleLabel.frame = CGRect.zero titleLabel.font = UIFont.systemFont(ofSize: 16.0) titleLabel.textColor = UIColor.black titleLabel.textAlignment = .left contentView.addSubview(titleLabel) self.titleLabel = titleLabel } } // MARK: - extension Cell的类方法 extension MainTableViewCell { // 类方法 class func mainTableViewCell(_ tableView: UITableView) -> MainTableViewCell { let cellID = "MainTableViewCell" var cell = tableView.dequeueReusableCell(withIdentifier: cellID) if cell == nil { cell = MainTableViewCell.init(style: .default, reuseIdentifier: cellID) } return cell as! MainTableViewCell } }
mit
02ece88b89907c6aae8cdf1c65133d34
27.557143
106
0.618309
4.748219
false
false
false
false
eleks/digital-travel-book
src/Swift/Weekend In Lviv/ViewControllers/Timeline/WLTopTimelineViewSw.swift
1
1113
// // WLTopTimelineViewSw.swift // Weekend In Lviv // // Created by Admin on 13.06.14. // Copyright (c) 2014 rnd. All rights reserved. // import UIKit class WLTopTimelineViewSw: UIView { // Outlets @IBOutlet weak var yearsView:UIView? // Instance methods override func awakeFromNib() { super.awakeFromNib() for i:Int in 1...24 { var lbl = self.viewWithTag(i) as UILabel if lbl.isKindOfClass(UILabel) { lbl.font = WLFontManager.sharedManager.bebasRegular22 } } } func setHeight(height:CGFloat) { let ratio:CGFloat = self.frame.size.width / self.frame.size.height self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, height * ratio, height) self.yearsView!.frame = CGRectMake(0, (self.frame.size.height + 10) * 0.88, self.frame.size.width, self.yearsView!.frame.size.height); } }
mit
770380e98244c951cc3ee56a00ac4e57
25.5
104
0.527403
4.280769
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/View/Search/SearchModel/SESearchRepoModel.swift
1
3618
// // SESearchRepoModel.swift // BeeFun // // Created by WengHengcong on 09/09/2017. // Copyright © 2017 JungleSong. All rights reserved. // import UIKit public enum SearchReposQueryPrefix: String { case In = "in" case Size = "size" case Forks = "forks" //The second way is to specify whether forked repositories should be included in results at all. By default, forked repositories are not shown. You can choose to include forked repositories by adding fork:true to your search. Or, if you only want forked repositories, add fork:only to your search. case Fork = "fork" case User = "user" case Language = "language" case Stars = "stars" case Created = "created" case Pushed = "pushed" } public enum ReposInField: String { //Without the qualifier, only the name and description are searched. //jquery in:name,description case Default = "" case Name = "name" case Description = "description" case Readme = "readme" } open class SESearchRepoModel: SESearchBaseModel { //ccombine all parameters to q //now support only one to one,but github api support one to many //such as,type:org type:user,but now support only type:user or type:org override var languagePara: String? { didSet { q = combineQuery() } } override var keyword: String? { didSet { q = combineQuery() } } var inPara: ReposInField? { didSet { q = combineQuery() } } var sizePara: String? { didSet { q = combineQuery() } } var forksPara: String? { didSet { q = combineQuery() } } var forkPara: Bool? { didSet { q = combineQuery() } } var userPara: String? { didSet { q = combineQuery() } } var starsPara: String? { didSet { q = combineQuery() } } var createdPara: String? { didSet { q = combineQuery() } } var pushedPara: String? { didSet { q = combineQuery() } } override func combineQuery() -> String { var query = "" if keyword != nil { query += "\(keyword!)" } //in:email if inPara != nil { let inStr = inPara!.rawValue query += " in:\(inStr)" } //size:50..120 if sizePara != nil { query += " size:\(sizePara!)" } //forks:>=205 if forksPara != nil { query += " forks:\(forksPara!)" } //forks:>=205 if forkPara != nil { query += " fork:\(forksPara!)" } //user:github if userPara != nil { query += " user:\(userPara!)" } //language:javascript if languagePara != nil { query += " language:\(languagePara!)" } //created:<2011-01-01 if createdPara != nil { query += " created:\(createdPara!)" } //pushed:<2011-01-01 if pushedPara != nil { query += " pushed:\(pushedPara!)" } //stars:10..20 if starsPara != nil { query += " stars:\(starsPara!)" } if query.isEmpty || (query == "") { query = "in:name,description" } return query } }
mit
6585ea8bc347ec806d5d567b313ac964
20.921212
301
0.490738
4.459926
false
false
false
false
moltin/ios-sdk
Examples/moltin tvOS Example/CategoriesViewController.swift
1
5330
// // ProductsViewController.swift // moltin tvOS Example // // Created by Craig Tweedy on 21/03/2018. // import UIKit import moltin extension UIImageView { func load(urlString string: String?) { guard let imageUrl = string, let url = URL(string: imageUrl) else { return } URLSession.shared.dataTask(with: url) { data, _, _ in if let data = data { DispatchQueue.main.async { self.image = UIImage(data: data) } } }.resume() } } extension UIColor { convenience init(hexString: String, alpha: CGFloat = 1.0) { let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let scanner = Scanner(string: hexString) if hexString.hasPrefix("#") { scanner.scanLocation = 1 } var color: UInt32 = 0 scanner.scanHexInt32(&color) let mask = 0x000000FF let r = Int(color >> 16) & mask let g = Int(color >> 8) & mask let b = Int(color) & mask let red = CGFloat(r) / 255.0 let green = CGFloat(g) / 255.0 let blue = CGFloat(b) / 255.0 self.init(red: red, green: green, blue: blue, alpha: alpha) } func toHexString() -> String { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) let rgb: Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0 return String(format: "#%06x", rgb) } } class ProductCategory: moltin.Category { var backgroundColor: UIColor? var backgroundImage: String? enum ProductCategoryCodingKeys: String, CodingKey { case backgroundColor = "background_colour" case backgroundImage = "background_image" } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: ProductCategoryCodingKeys.self) if let color: String = try container.decodeIfPresent(String.self, forKey: .backgroundColor) { self.backgroundColor = UIColor(hexString: color) } self.backgroundImage = try container.decodeIfPresent(String.self, forKey: .backgroundImage) try super.init(from: decoder) } } class CategoriesViewController: UICollectionViewController { var data: [ProductCategory] = [] let moltin: Moltin = Moltin(withClientID: "j6hSilXRQfxKohTndUuVrErLcSJWP15P347L6Im0M4", withLocale: Locale(identifier: "en_US")) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.collectionView?.register(UINib(nibName: "ProductCategoryCollectionViewCell", bundle: Bundle.main), forCellWithReuseIdentifier: "Cell") let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = CGSize(width: self.view.frame.width, height: self.view.frame.height * 0.8) flowLayout.minimumLineSpacing = 0 flowLayout.minimumInteritemSpacing = 0 self.collectionView?.setCollectionViewLayout(flowLayout, animated: false) self.moltin.category.all { (response: Result<PaginatedResponse<[ProductCategory]>>) in switch response { case .success(let categories): DispatchQueue.main.async { self.view.backgroundColor = categories.data?.first?.backgroundColor self.data = categories.data ?? [] self.collectionView?.reloadData() } case .failure(let error): print(error) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "CategoryToProducts", let viewController = segue.destination as? ProductsCollectionViewController, let category = sender as? ProductCategory { viewController.category = category } } } // MARK: - Data Source extension CategoriesViewController { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.data.count } } // MARK: - Delegate extension CategoriesViewController { override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell: ProductCategoryCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? ProductCategoryCollectionViewCell else { return UICollectionViewCell() } let product = self.data[indexPath.row] cell.backgroundColor = product.backgroundColor cell.image.load(urlString: product.backgroundImage) cell.label.text = product.name return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let category = self.data[indexPath.row] self.performSegue(withIdentifier: "CategoryToProducts", sender: category) } }
mit
405dd6b8831f3520607261fce274d68d
35.258503
147
0.642402
4.741993
false
false
false
false
Raizlabs/ios-template
PRODUCTNAME/app/Pods/BonMot/Sources/UIKit/AdaptableTextContainer.swift
1
11329
// // AdaptableTextContainer.swift // BonMot // // Created by Brian King on 7/19/16. // Copyright © 2016 Raizlabs. All rights reserved. // import UIKit /// A protocol to update the text style contained by the object. This can be /// triggered manually in `traitCollectionDidChange(_:)`. Any `UIViewController` /// or `UIView` that conforms to this protocol will be informed of content size /// category changes if `UIApplication.enableAdaptiveContentSizeMonitor()` is called. /// - Note: We don't conform UI elements to this protocol due to a [bug in Xcode](http://www.openradar.me/30001713). /// The protocol still exists as a container for selectors. @objc(BONAdaptableTextContainer) public protocol AdaptableTextContainer { /// Update the text style contained by the object in response to a trait /// collection change. /// /// - parameter traitCollection: The new trait collection. @objc(bon_updateTextForTraitCollection:) func adaptText(forTraitCollection traitCollection: UITraitCollection) } // MARK: - AdaptableTextContainer for UILabel extension UILabel { /// Adapt `attributedText` to the specified trait collection. /// /// - parameter traitCollection: The new trait collection. @objc(bon_updateTextForTraitCollection:) public func adaptText(forTraitCollection traitCollection: UITraitCollection) { // Update the font, then the attributed string. If the font doesn't keep in sync when // not using attributedText, weird things happen so update it first. // See UIKitTests.testLabelFontPropertyBehavior for interesting behavior. if let bonMotStyle = bonMotStyle { let attributes = NSAttributedString.adapt(attributes: bonMotStyle.attributes, to: traitCollection) font = attributes[.font] as? BONFont } if let attributedText = attributedText { self.attributedText = attributedText.adapted(to: traitCollection) } } } // MARK: - AdaptableTextContainer for UITextView extension UITextView { /// Adapt `attributedText` and `typingAttributes` to the specified trait collection. /// /// - parameter traitCollection: The updated trait collection @objc(bon_updateTextForTraitCollection:) public func adaptText(forTraitCollection traitCollection: UITraitCollection) { if let attributedText = attributedText { self.attributedText = attributedText.adapted(to: traitCollection) } #if swift(>=4.2) typingAttributes = NSAttributedString.adapt(attributes: typingAttributes, to: traitCollection) #else typingAttributes = NSAttributedString.adapt(attributes: typingAttributes.withTypedKeys(), to: traitCollection).withStringKeys #endif } } // MARK: - AdaptableTextContainer for UITextField extension UITextField { /// Adapt `attributedText`, `attributedPlaceholder`, and /// `defaultTextAttributes` to the specified trait collection. /// /// - note: Do not modify `typingAttributes`, as they are relevant only /// while the text field has first responder status, and they are /// reset as new text is entered. /// /// - parameter traitCollection: The new trait collection. @objc(bon_updateTextForTraitCollection:) public func adaptText(forTraitCollection traitCollection: UITraitCollection) { if let attributedText = attributedText?.adapted(to: traitCollection) { if attributedText.length > 0 { font = attributedText.attribute(.font, at: 0, effectiveRange: nil) as? UIFont } self.attributedText = attributedText } if let attributedPlaceholder = attributedPlaceholder { self.attributedPlaceholder = attributedPlaceholder.adapted(to: traitCollection) } #if swift(>=4.2) defaultTextAttributes = NSAttributedString.adapt(attributes: defaultTextAttributes, to: traitCollection) #else defaultTextAttributes = NSAttributedString.adapt(attributes: defaultTextAttributes.withTypedKeys(), to: traitCollection).withStringKeys #endif // Fix an issue where shrinking or growing text would stay the same width, but add whitespace. setNeedsDisplay() } } // Extension is here to work around [SR-631](https://bugs.swift.org/browse/SR-631), // which requires new types declared in extensions to be built before they can // themselves be extended. This is fixed in Xcode 10, so we can revert this when // we stop supporting Xcode 9. (Another workaround is to reorder the files in // the Compile Sources build phase, but since this is a library, we do not own // that build phase in all projects that we are used in. We could have renamed // Compatibility.swift to _Compatibility.swift and trusted CocoaPods to sort // built files alphabetically, but we're opting to use the more reliable method // of just putting the extension in the file where it's used. #if os(iOS) || os(tvOS) #if swift(>=4.2) #else extension UIControl { typealias State = UIControlState } #endif #endif // MARK: - AdaptableTextContainer for UIButton extension UIButton { /// Adapt `attributedTitle`, for all control states, to the specified trait collection. /// /// - parameter traitCollection: The new trait collection. @objc(bon_updateTextForTraitCollection:) public func adaptText(forTraitCollection traitCollection: UITraitCollection) { for state in UIControl.State.commonStates { let attributedText = attributedTitle(for: state)?.adapted(to: traitCollection) setAttributedTitle(attributedText, for: state) } } } // MARK: - AdaptableTextContainer for UISegmentedControl extension UISegmentedControl { // `UISegmentedControl` has terrible generics ([NSObject: AnyObject]? or [AnyHashable: Any]?) on /// `titleTextAttributes`, so use a helper in Swift 3+ @nonobjc final func bon_titleTextAttributes(for state: UIControl.State) -> StyleAttributes { let attributes = titleTextAttributes(for: state) ?? [:] var result: StyleAttributes = [:] for value in attributes { #if swift(>=4.2) result[value.key] = value #else guard let string = value.key as? StyleAttributes.Key else { fatalError("Can not convert key \(value.key) to String") } result[string] = value #endif } return result } /// Adapt `attributedTitle`, for all control states, to the specified trait collection. /// /// - parameter traitCollection: The new trait collection. @objc(bon_updateTextForTraitCollection:) public func adaptText(forTraitCollection traitCollection: UITraitCollection) { for state in UIControl.State.commonStates { let attributes = bon_titleTextAttributes(for: state) let newAttributes = NSAttributedString.adapt(attributes: attributes, to: traitCollection) setTitleTextAttributes(newAttributes, for: state) } } } // MARK: - AdaptableTextContainer for UINavigationBar extension UINavigationBar { /// Adapt `titleTextAttributes` to the specified trait collection. /// /// - note: This does not update the bar button items. These should be /// updated by the containing view controller. /// /// - parameter traitCollection: The new trait collection. @objc(bon_updateTextForTraitCollection:) public func adaptText(forTraitCollection traitCollection: UITraitCollection) { if let titleTextAttributes = titleTextAttributes { self.titleTextAttributes = NSAttributedString.adapt(attributes: titleTextAttributes, to: traitCollection) } } } #if os(tvOS) #else // MARK: - AdaptableTextContainer for UIToolbar extension UIToolbar { /// Adapt all bar items's attributed text to the specified trait collection. /// /// - note: This will update only bar items that are contained on the screen /// at the time that it is called. /// /// - parameter traitCollection: The updated trait collection @objc(bon_updateTextForTraitCollection:) public func adaptText(forTraitCollection traitCollection: UITraitCollection) { for item in items ?? [] { item.adaptText(forTraitCollection: traitCollection) } } } #endif // MARK: - AdaptableTextContainer for UIViewController extension UIViewController { /// Adapt the attributed text of teh bar items in the navigation item or in /// the toolbar to the specified trait collection. /// /// - parameter traitCollection: The new trait collection. @objc(bon_updateTextForTraitCollection:) public func adaptText(forTraitCollection traitCollection: UITraitCollection) { for item in navigationItem.allBarItems { item.adaptText(forTraitCollection: traitCollection) } #if os(tvOS) #else for item in toolbarItems ?? [] { item.adaptText(forTraitCollection: traitCollection) } if let backBarButtonItem = navigationItem.backBarButtonItem { backBarButtonItem.adaptText(forTraitCollection: traitCollection) } #endif } } // MARK: - AdaptableTextContainer for UIBarItem extension UIBarItem { /// Adapt `titleTextAttributes` to the specified trait collection. /// /// - note: This extension does not conform to `AdaptableTextContainer` /// because `UIBarIterm` is not a view or view controller. /// - parameter traitCollection: the new trait collection. @objc(bon_updateTextForTraitCollection:) public func adaptText(forTraitCollection traitCollection: UITraitCollection) { for state in UIControl.State.commonStates { let attributes = titleTextAttributes(for: state) ?? [:] #if swift(>=4.2) let newAttributes = NSAttributedString.adapt(attributes: attributes, to: traitCollection) setTitleTextAttributes(newAttributes, for: state) #else let newAttributes = NSAttributedString.adapt(attributes: attributes.withTypedKeys(), to: traitCollection) setTitleTextAttributes(newAttributes, for: state) #endif } } } extension UIControl.State { /// The most common states that are used in apps. Using this defined set of /// attributes is far simpler than trying to build a system that will /// iterate through only the permutations that are currently configured. If /// you use a valid `UIControlState` in your app that is not represented /// here, please open a pull request to add it. @nonobjc static var commonStates: [UIControl.State] { return [.normal, .highlighted, .disabled, .selected, [.highlighted, .selected]] } } extension UINavigationItem { /// Convenience getter comprising `leftBarButtonItems` and `rightBarButtonItems`. final var allBarItems: [UIBarButtonItem] { var allBarItems = leftBarButtonItems ?? [] allBarItems.append(contentsOf: rightBarButtonItems ?? []) return allBarItems } }
mit
5ffb55c3db71f5fa3132007515aef096
38.333333
147
0.687765
5.144414
false
false
false
false
jacobwhite/firefox-ios
Client/Frontend/Widgets/AutocompleteTextField.swift
1
11913
/* 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/. */ // This code is loosely based on https://github.com/Antol/APAutocompleteTextField import UIKit import Shared /// Delegate for the text field events. Since AutocompleteTextField owns the UITextFieldDelegate, /// callers must use this instead. protocol AutocompleteTextFieldDelegate: class { func autocompleteTextField(_ autocompleteTextField: AutocompleteTextField, didEnterText text: String) func autocompleteTextFieldShouldReturn(_ autocompleteTextField: AutocompleteTextField) -> Bool func autocompleteTextFieldShouldClear(_ autocompleteTextField: AutocompleteTextField) -> Bool func autocompleteTextFieldDidBeginEditing(_ autocompleteTextField: AutocompleteTextField) func autocompleteTextFieldDidCancel(_ autocompleteTextField: AutocompleteTextField) } private struct AutocompleteTextFieldUX { static let HighlightColor = UIColor(rgb: 0xccdded) } class AutocompleteTextField: UITextField, UITextFieldDelegate { var autocompleteDelegate: AutocompleteTextFieldDelegate? // AutocompleteTextLabel repersents the actual autocomplete text. // The textfields "text" property only contains the entered text, while this label holds the autocomplete text // This makes sure that the autocomplete doesnt mess with keyboard suggestions provided by third party keyboards. private var autocompleteTextLabel: UILabel? private var hideCursor: Bool = false var isSelectionActive: Bool { return autocompleteTextLabel != nil } // This variable is a solution to get the right behavior for refocusing // the AutocompleteTextField. The initial transition into Overlay Mode // doesn't involve the user interacting with AutocompleteTextField. // Thus, we update shouldApplyCompletion in touchesBegin() to reflect whether // the highlight is active and then the text field is updated accordingly // in touchesEnd() (eg. applyCompletion() is called or not) fileprivate var notifyTextChanged: (() -> Void)? private var lastReplacement: String? var highlightColor = AutocompleteTextFieldUX.HighlightColor override var text: String? { didSet { super.text = text self.textDidChange(self) } } override var accessibilityValue: String? { get { return (self.text ?? "") + (self.autocompleteTextLabel?.text ?? "") } set(value) { super.accessibilityValue = value } } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { super.delegate = self super.addTarget(self, action: #selector(AutocompleteTextField.textDidChange), for: .editingChanged) notifyTextChanged = debounce(0.1, action: { if self.isEditing { self.autocompleteDelegate?.autocompleteTextField(self, didEnterText: self.normalizeString(self.text ?? "")) } }) } override var keyCommands: [UIKeyCommand]? { return [ UIKeyCommand(input: UIKeyInputLeftArrow, modifierFlags: [], action: #selector(self.handleKeyCommand(sender:))), UIKeyCommand(input: UIKeyInputRightArrow, modifierFlags: [], action: #selector(self.handleKeyCommand(sender:))), UIKeyCommand(input: UIKeyInputEscape, modifierFlags: [], action: #selector(self.handleKeyCommand(sender:))), ] } @objc func handleKeyCommand(sender: UIKeyCommand) { guard let input = sender.input else { return } switch input { case UIKeyInputLeftArrow: UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "autocomplete-left-arrow"]) if isSelectionActive { applyCompletion() // Set the current position to the beginning of the text. selectedTextRange = textRange(from: beginningOfDocument, to: beginningOfDocument) } else if let range = selectedTextRange { if range.start == beginningOfDocument { break } guard let cursorPosition = position(from: range.start, offset: -1) else { break } selectedTextRange = textRange(from: cursorPosition, to: cursorPosition) } case UIKeyInputRightArrow: UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "autocomplete-right-arrow"]) if isSelectionActive { applyCompletion() // Set the current position to the end of the text. selectedTextRange = textRange(from: endOfDocument, to: endOfDocument) } else if let range = selectedTextRange { if range.end == endOfDocument { break } guard let cursorPosition = position(from: range.end, offset: 1) else { break } selectedTextRange = textRange(from: cursorPosition, to: cursorPosition) } case UIKeyInputEscape: UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "autocomplete-cancel"]) autocompleteDelegate?.autocompleteTextFieldDidCancel(self) default: break } } func highlightAll() { let text = self.text self.text = "" setAutocompleteSuggestion(text ?? "") selectedTextRange = textRange(from: endOfDocument, to: endOfDocument) } fileprivate func normalizeString(_ string: String) -> String { return string.lowercased().stringByTrimmingLeadingCharactersInSet(CharacterSet.whitespaces) } /// Commits the completion by setting the text and removing the highlight. fileprivate func applyCompletion() { // Clear the current completion, then set the text without the attributed style. let text = (self.text ?? "") + (self.autocompleteTextLabel?.text ?? "") removeCompletion() self.text = text hideCursor = false // Move the cursor to the end of the completion. selectedTextRange = textRange(from: endOfDocument, to: endOfDocument) } /// Removes the autocomplete-highlighted fileprivate func removeCompletion() { autocompleteTextLabel?.removeFromSuperview() autocompleteTextLabel = nil } // `shouldChangeCharactersInRange` is called before the text changes, and textDidChange is called after. // Since the text has changed, remove the completion here, and textDidChange will fire the callback to // get the new autocompletion. func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { lastReplacement = string return true } func setAutocompleteSuggestion(_ suggestion: String?) { let text = self.text ?? "" guard let suggestion = suggestion, isEditing && markedTextRange == nil else { hideCursor = false return } let normalized = normalizeString(text) guard suggestion.hasPrefix(normalized) && normalized.count < suggestion.count else { hideCursor = false return } let suggestionText = suggestion.substring(from: suggestion.index(suggestion.startIndex, offsetBy: normalized.count)) let autocompleteText = NSMutableAttributedString(string: suggestionText) autocompleteText.addAttribute(NSAttributedStringKey.backgroundColor, value: highlightColor, range: NSRange(location: 0, length: suggestionText.count)) autocompleteTextLabel?.removeFromSuperview() // should be nil. But just in case autocompleteTextLabel = createAutocompleteLabelWith(autocompleteText) if let l = autocompleteTextLabel { addSubview(l) hideCursor = true forceResetCursor() } } override func caretRect(for position: UITextPosition) -> CGRect { return hideCursor ? CGRect.zero : super.caretRect(for: position) } private func createAutocompleteLabelWith(_ autocompleteText: NSAttributedString) -> UILabel { let label = UILabel() var frame = self.bounds label.attributedText = autocompleteText label.font = self.font label.accessibilityIdentifier = "autocomplete" label.backgroundColor = self.backgroundColor label.textColor = self.textColor label.textAlignment = .left let enteredTextSize = self.attributedText?.boundingRect(with: self.frame.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil) frame.origin.x = (enteredTextSize?.width.rounded() ?? 0) frame.size.width = self.frame.size.width - frame.origin.x frame.size.height = self.frame.size.height - 1 label.frame = frame return label } func textFieldDidBeginEditing(_ textField: UITextField) { autocompleteDelegate?.autocompleteTextFieldDidBeginEditing(self) } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { applyCompletion() return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { applyCompletion() return autocompleteDelegate?.autocompleteTextFieldShouldReturn(self) ?? true } func textFieldShouldClear(_ textField: UITextField) -> Bool { removeCompletion() return autocompleteDelegate?.autocompleteTextFieldShouldClear(self) ?? true } override func setMarkedText(_ markedText: String?, selectedRange: NSRange) { // Clear the autocompletion if any provisionally inserted text has been // entered (e.g., a partial composition from a Japanese keyboard). removeCompletion() super.setMarkedText(markedText, selectedRange: selectedRange) } func setTextWithoutSearching(_ text: String) { super.text = text hideCursor = autocompleteTextLabel != nil removeCompletion() } @objc func textDidChange(_ textField: UITextField) { hideCursor = autocompleteTextLabel != nil removeCompletion() let isAtEnd = selectedTextRange?.start == endOfDocument let isKeyboardReplacingText = lastReplacement != nil if isKeyboardReplacingText, isAtEnd, markedTextRange == nil { notifyTextChanged?() } else { hideCursor = false } } // Reset the cursor to the end of the text field. // This forces `caretRect(for position: UITextPosition)` to be called which will decide if we should show the cursor // This exists because ` caretRect(for position: UITextPosition)` is not called after we apply an autocompletion. private func forceResetCursor() { selectedTextRange = nil selectedTextRange = textRange(from: endOfDocument, to: endOfDocument) } override func deleteBackward() { lastReplacement = "" hideCursor = false if isSelectionActive { removeCompletion() forceResetCursor() } else { super.deleteBackward() } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { applyCompletion() super.touchesBegan(touches, with: event) } }
mpl-2.0
31d2ca08e27b04455f99d4f569323174
39.383051
158
0.661882
5.517832
false
false
false
false
cao903775389/OLNetwork
OLNetwork/Classes/HttpNetwork/OLHttpChainRequest.swift
1
4049
// // OLHttpChainRequest.swift // Beauty // 带有依赖的请求 // Created by 逢阳曹 on 2016/12/9. // Copyright © 2016年 CBSi. All rights reserved. // import UIKit @objc protocol OLHttpChainRequestDelegate { //请求发送成功 @objc optional func ol_chainRequestFinished(request: OLHttpChainRequest) //请求发送失败 @objc optional func ol_chainRequestFailed(request: OLHttpChainRequest, failedRequest: OLHttpRequest) } //请求回调 typealias OLHttpChainCallBack = @convention(block) (OLHttpChainRequest, OLHttpRequest) -> Void public class OLHttpChainRequest: NSObject, OLHttpRequestDelegate { //delegate weak var delegate: OLHttpChainRequestDelegate? //所有请求数组 private var requestArray: [OLHttpRequest]! //所有请求回调 private var requestCallBackArray: [OLHttpChainCallBack]! //下一个请求的索引 private var nextRequestIndex: Int! //emptyCallBack private var emptyCallBack: OLHttpChainCallBack! //MARK: - init deinit { //取消所有请求 self.delegate = nil self.stop() } convenience init(requestArray: [OLHttpRequest]) { self.init() self.requestArray = requestArray } override init() { super.init() self.requestArray = [] self.requestCallBackArray = [] self.nextRequestIndex = 0 //当没有回调时使用 self.emptyCallBack = {chainRequest, request in } } //MARK: - Public func start() { if nextRequestIndex > 0 { print("Error: 依赖请求已经开启! 无法再次开启!!") return } if requestArray.count > 0 { _ = self.startNextRequest() OLHttpChainRequestManager.sharedOLHttpChainRequestManager.addChainRequest(request: self) }else { print("Error: 请求数组为空!!") } } func stop() { self.clearRequest() OLHttpChainRequestManager.sharedOLHttpChainRequestManager.removeChainRequest(request: self) } //需要依赖传值时调用此方法发送请求 func addRequest(request: OLHttpRequest, callback: OLHttpChainCallBack?) { requestArray.append(request) if callback != nil { requestCallBackArray.append(callback!) }else { requestCallBackArray.append(self.emptyCallBack) } } //MARK: - Private private func startNextRequest() -> Bool { if nextRequestIndex < requestArray.count { let request = requestArray[nextRequestIndex] nextRequestIndex = nextRequestIndex + 1 request.delegate = self OLHttpRequestManager.sharedOLHttpRequestManager.sendHttpRequest(request: request) return true }else { return false } } private func clearRequest() { let currentRequestIndex = nextRequestIndex - 1 if currentRequestIndex < requestArray.count { let request = requestArray[currentRequestIndex] request.cancleDelegateAndRequest() } requestArray.removeAll() requestCallBackArray.removeAll() } //MARK: - OLHttpRequestDelegate public func ol_requestFinished(request: OLHttpRequest) { let currentRequestIndex = nextRequestIndex - 1 let callBack = requestCallBackArray[currentRequestIndex] callBack(self, request) //请求已完成 if !self.startNextRequest() { self.delegate?.ol_chainRequestFinished?(request: self) OLHttpChainRequestManager.sharedOLHttpChainRequestManager.removeChainRequest(request: self) } } public func ol_requestFailed(request: OLHttpRequest) { self.delegate?.ol_chainRequestFailed?(request: self, failedRequest: request) OLHttpChainRequestManager.sharedOLHttpChainRequestManager.removeChainRequest(request: self) } }
mit
458572e80edcdc4ae2d00593d801797f
27.902256
103
0.640219
4.428571
false
false
false
false
sqlpro/swift03-basic
MyMovieChart/MyMovieChart/DetailViewController.swift
1
3910
import UIKit class DetailViewController : UIViewController, UIWebViewDelegate { @IBOutlet var wv: UIWebView! // 목록 화면에서 전달하는 영화 정보를 받을 변수 var mvo : MovieVO! // 로딩 상태를 표시할 인디케이터 뷰 @IBOutlet var spinner: UIActivityIndicatorView! override func viewDidLoad() { NSLog("linkurl = \(self.mvo?.detail), title=\(self.mvo?.title)") // 내비게이션 바의 타이틀에 영화명을 출력한다. let navibar = self.navigationItem navibar.title = self.mvo?.title if let url = self.mvo?.detail { if let urlObj = URL(string: url) { let req = URLRequest(url:urlObj) self.wv.loadRequest(req) } else { // URL 형식이 잘못되었을 경우에 대한 예외처리 // 경고창 형식으로 오류 메시지를 표시해준다. let alert = UIAlertController(title: "오류", message: "잘못된 URL입니다", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "확인", style: .cancel) { (_) in // 이전 페이지로 되돌려보낸다. _ = self.navigationController?.popViewController(animated: true) } alert.addAction(cancelAction) self.present(alert, animated: false, completion: nil) } } else { // URL 값이 전달되지 않았을 경우에 대한 예외처리 // 경고창 형식으로 오류 메시지를 표시해준다. let alert = UIAlertController(title: "오류", message: "필수 파라미터가 누락되었습니다.", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "확인", style: .cancel) { (_) in // 이전 페이지로 되돌려보낸다. _ = self.navigationController?.popViewController(animated: true) } alert.addAction(cancelAction) self.present(alert, animated: false, completion: nil) } } // 웹 뷰가 웹페이지를 로드하기 시작할 때 func webViewDidStartLoad(_ webView: UIWebView) { self.spinner.startAnimating() // 인디케이터 뷰의 애니메이션을 실행 } // 웹 뷰가 웹페이지 로드를 완료했을 때 func webViewDidFinishLoad(_ webView: UIWebView) { self.spinner.stopAnimating( ) // 인디케이터 뷰의 애니메이션을 중지 } // 웹 뷰가 웹페이지 로드를 실패했을 때 func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { self.spinner.stopAnimating( ) // 인디케이터 뷰의 애니메이션을 중지 // 경고창 형식으로 오류 메시지를 표시해준다. let alert = UIAlertController(title: "오류", message: "상세페이지를 읽어오지 못했습니다", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "확인", style: .cancel) { (_) in // 이전 페이지로 되돌려보낸다. _ = self.navigationController?.popViewController(animated: true) } alert.addAction(cancelAction) self.present(alert, animated: false, completion: nil) } func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { return true } }
gpl-3.0
9553d00c1c957b0c8b1d4e044e959198
34.652174
130
0.510671
3.470899
false
false
false
false
whiteshadow-gr/HatForIOS
HAT/Objects/Phatav2/HATProfileEmergencyContact.swift
1
3402
/** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * 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 SwiftyJSON // MARK: Struct public struct HATProfileEmergencyContact: HATObject, HatApiType { // MARK: - Coding Keys /** The JSON fields used by the hat The Fields are the following: * `relationship` in JSON is `relationship` * `lastName` in JSON is `lastName` * `mobile` in JSON is `mobile` * `firstName` in JSON is `firstName` */ private enum CodingKeys: String, CodingKey { case relationship case lastName case mobile case firstName } // MARK: - Variables /// The type of relationship with the user public var relationship: String = "" /// The last name of the emergency contact public var lastName: String = "" /// The mobile number of the emergency contact public var mobile: String = "" /// The first name of the emergency contact public var firstName: String = "" // MARK: - Initialisers /** The default initialiser. Initialises everything to default values. */ public init() { } /** It initialises everything from the received JSON file from the HAT - dict: The JSON file received from the HAT */ public init(dict: Dictionary<String, JSON>) { self.init() self.initialize(dict: dict) } /** It initialises everything from the received JSON file from the HAT - dict: The JSON file received from the HAT */ public mutating func initialize(dict: Dictionary<String, JSON>) { if let tempRelationship: String = (dict[CodingKeys.relationship.rawValue]?.stringValue) { relationship = tempRelationship } if let tempLastName: String = (dict[CodingKeys.lastName.rawValue]?.stringValue) { lastName = tempLastName } if let tempMobile: String = (dict[CodingKeys.mobile.rawValue]?.stringValue) { mobile = tempMobile } if let tempFirstName: String = (dict[CodingKeys.firstName.rawValue]?.stringValue) { firstName = tempFirstName } } // MARK: - HatApiType protocol /** Returns the object as Dictionary, JSON - returns: Dictionary<String, String> */ public func toJSON() -> Dictionary<String, Any> { return [ CodingKeys.relationship.rawValue: self.relationship, CodingKeys.lastName.rawValue: self.lastName, CodingKeys.mobile.rawValue: self.mobile, CodingKeys.firstName.rawValue: self.firstName ] } /** It initialises everything from the received Dictionary file from the cache - fromCache: The dictionary file received from the cache */ public mutating func initialize(fromCache: Dictionary<String, Any>) { let json: JSON = JSON(fromCache) self.initialize(dict: json.dictionaryValue) } }
mpl-2.0
5a774bb0a06a326272692ca494f30ceb
26.885246
97
0.604056
4.9233
false
false
false
false
Gaea-iOS/FoundationExtension
FoundationExtension/Classes/Component/DownCounter.swift
1
1408
// // DownCounter.swift // Pods // // Created by 王小涛 on 2017/6/26. // // import Foundation public class DownCounter { private let step: Int private var left: Int = 60 var isCounting: Bool = false private weak var target: AnyObject? private var timer: Timer? public var down: ((Int) -> Void)? = nil public var done: (() -> Void)? = nil public init(step: Int = 1, target: AnyObject?) { self.step = step self.target = target } public func start(count: Int) { self.stop() guard let target = target else { return } isCounting = true left = count timer = Timer.every(interval: TimeInterval(step), target: target) { [weak self] timer in guard let `self` = self else {return} guard self.target != nil else { self.stop() return } self.left -= 1 self.down?(self.left) if self.left <= 0 { self.done?() self.stop() } } } public func resume() { start(count: left) } public func pause() { stop() } public func stop() { isCounting = false timer?.invalidate() } }
mit
515a794e3fa81f6a6ddf30e2f37a9c71
18.205479
96
0.461484
4.436709
false
false
false
false
facetdigital/QuiltView
QuiltView/Classes/QuiltView.swift
1
19083
// // QuiltView.swift // QuiltView // // Created by Jeremy Groh on 01/09/17 // Copyright © 2017 Facet Digital, LLC. All rights reserved. // import UIKit // NOTE: Even though we are not interoperating with Objective-C, we // need to mark our protocol with the @objc attribute since we are // specifying optional requirements. @objc public protocol QuiltViewDelegate : UICollectionViewDelegate { @objc optional func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, blockSizeForItemAtIndexPath indexPath: IndexPath) -> CGSize @objc optional func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetsForItemAtIndexPath indexPath: IndexPath) -> UIEdgeInsets } public class QuiltView : UICollectionViewLayout { // MARK: Public Properties public var itemBlockSize = CGSize(width: Constants.ImageCollection.ImageWidth, height: Constants.ImageCollection.ImageHeight) { didSet { self.invalidateLayout() } } public var scrollDirection = UICollectionViewScrollDirection.vertical { didSet { self.invalidateLayout() } } public var cellIndexPaths = [Int:IndexPath]() // MARK: Private Properties private weak var delegate: QuiltViewDelegate? { get { return collectionView?.delegate as? QuiltViewDelegate } } private static var didShowMessage = false // Set the class name for debug purposes only private var className = "QuiltView" private var blockPoint = CGPoint.zero private var furthestBlockPoint: CGPoint { get { return self.blockPoint } set(newFurthestBlockPoint) { self.blockPoint = CGPoint( x: max(self.blockPoint.x, newFurthestBlockPoint.x), y: max(self.blockPoint.y, newFurthestBlockPoint.y) ) } } // Only use this if we have less than 1000 or so items. This will give // the correct size from the start and improve scrolling speed, // but cause increased loading times at the beginning private var preLayoutEverything = false private var firstpublicSpace = CGPoint.zero private var hasPositionsCached = false private var previousLayoutRect = CGRect.zero private var cellLayoutInfo = [IndexPath:UICollectionViewLayoutAttributes]() // This will be a 2x2 dictionary storing IndexPaths which // indicates the available/filled spaces in our layout private var indexPathByPosition = [Int:[Int:IndexPath]]() // Indexed by "section, row". This will serve as the // rapid lookup of block position by indexpath. private var positionByIndexPath = [Int:[Int:CGPoint]]() // Previous layout cache. This is to prevent choppiness when scrolling // to the bottom of the screen. UICollectionView will repeatedly call // layoutattributesforelementinrect on each scroll event. private var previousLayoutAttributes: [AnyObject]? = nil // Remember the last indexpath placed so that we do not // re-layout the same indexpaths while scrolling private var lastIndexPathPlaced: IndexPath? = nil // MARK: UICollectionViewLayoutDelegate override public var collectionViewContentSize : CGSize { let contentRect = UIEdgeInsetsInsetRect(self.collectionView!.frame, self.collectionView!.contentInset) var size = CGSize(width: contentRect.width, height: (self.furthestBlockPoint.y + 1) * self.itemBlockSize.height) if !self.isVertical() { size = CGSize(width: (self.furthestBlockPoint.x + 1) * self.itemBlockSize.width, height: contentRect.height) } return size } override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { if (self.delegate == nil) { return [] } if rect.equalTo(self.previousLayoutRect) { return self.previousLayoutAttributes as? [UICollectionViewLayoutAttributes] } self.previousLayoutRect = rect let isVertical = self.isVertical() let unrestrictedDimensionStart = Int(isVertical ? rect.origin.y / self.itemBlockSize.height : rect.origin.x / self.itemBlockSize.width) let unrestrictedDimensionLength = Int(isVertical ? rect.size.height / self.itemBlockSize.height : rect.size.width / self.itemBlockSize.width) + 1 let unrestrictedDimensionEnd = unrestrictedDimensionStart + unrestrictedDimensionLength self.fillInBlocksToUnrestrictedRow(endRow: self.preLayoutEverything ? Int.max : unrestrictedDimensionEnd) // find the indexPaths between those rows let attributes = NSMutableSet() self.traverseTilesBetweenUnrestrictedDimension(begin: unrestrictedDimensionStart, and: unrestrictedDimensionEnd, block: { point in let indexPath: IndexPath? = self.indexPathForPosition(point: point) if (indexPath != nil) { attributes.add(self.layoutAttributesForItem(at: indexPath!)) } return true }) self.previousLayoutAttributes = attributes.allObjects as? [UICollectionViewLayoutAttributes] return self.previousLayoutAttributes as? [UICollectionViewLayoutAttributes] } override public func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes { var insets = UIEdgeInsets.zero if self.delegate?.responds(to: Selector(Constants.String.CollectionViewInsetsForItem)) != nil { insets = self.delegate!.collectionView!(collectionView: self.collectionView!, layout: self, insetsForItemAtIndexPath: indexPath) } let frame = self.frameForIndexPath(path: indexPath) let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) attributes.frame = UIEdgeInsetsInsetRect(frame, insets) if let preCalcAttributes = self.cellLayoutInfo[indexPath] { attributes.zIndex = preCalcAttributes.zIndex attributes.transform3D = preCalcAttributes.transform3D } return attributes } override public func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return !(newBounds.size.equalTo(self.collectionView!.frame.size)) } override public func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) { super.prepare(forCollectionViewUpdates: updateItems) for item in updateItems { if (item.updateAction == UICollectionUpdateAction.insert || item.updateAction == UICollectionUpdateAction.move) { self.fillInBlocksToIndexPath(path: item.indexPathAfterUpdate!) } } } override public func invalidateLayout() { super.invalidateLayout() self.furthestBlockPoint = CGPoint.zero self.firstpublicSpace = CGPoint.zero self.previousLayoutRect = CGRect.zero self.previousLayoutAttributes = nil self.lastIndexPathPlaced = nil self.clearPositions() } override public func prepare() { super.prepare() if (self.delegate == nil) { return } let cv = self.collectionView! let scrollFrame = CGRect(x: cv.contentOffset.x, y: cv.contentOffset.y, width: cv.frame.size.width, height: cv.frame.size.height) var unrestrictedRow = Int(scrollFrame.maxY / self.itemBlockSize.height) + 1 if !self.isVertical() { unrestrictedRow = Int(scrollFrame.maxX / self.itemBlockSize.width) + 1 } self.fillInBlocksToUnrestrictedRow(endRow: self.preLayoutEverything ? Int.max : unrestrictedRow) } // MARK: Private Methods private func fillInBlocksToUnrestrictedRow(endRow: Int) { let isVertical = self.isVertical() // we'll have our data structure as if we're planning // a vertical layout, then when we assign positions to // the items we'll invert the axis let numSections: Int = self.collectionView!.numberOfSections for section in Int(self.lastIndexPathPlaced?.section ?? 0)..<numSections { let numRows: Int = self.collectionView!.numberOfItems(inSection: section) for row in (self.lastIndexPathPlaced == nil ? 0 : Int(self.lastIndexPathPlaced?.row ?? 0) + 1)..<numRows { let indexPath: IndexPath = IndexPath(row: row, section: section) if self.placeBlockAtIndex(indexPath: indexPath) { self.lastIndexPathPlaced = indexPath } // Determine the initial z-index value for each image let itemAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) let zIndex = Constants.Int.BaseZIndex + numRows - row itemAttributes.zIndex = zIndex itemAttributes.transform3D = CATransform3DMakeTranslation(CGFloat(0), CGFloat(0), CGFloat(zIndex)) self.cellLayoutInfo[indexPath] = itemAttributes if (Int(isVertical ? self.firstpublicSpace.y : self.firstpublicSpace.x) >= endRow) { return } } } } private func fillInBlocksToIndexPath(path: IndexPath) { // we'll have our data structure as if we're planning // a vertical layout, then when we assign positions to // the items we'll invert the axis let numSections = self.collectionView!.numberOfSections for section in Int(self.lastIndexPathPlaced?.section ?? 0)..<numSections { let numRows: Int = self.collectionView!.numberOfItems(inSection: section) for row in (self.lastIndexPathPlaced == nil ? 0 : Int(self.lastIndexPathPlaced?.row ?? 0) + 1)..<numRows { if section >= path.section && row > path.row { return } let indexPath: IndexPath = IndexPath(row: row, section: section) if self.placeBlockAtIndex(indexPath: indexPath) { self.lastIndexPathPlaced = indexPath } } } } private func placeBlockAtIndex(indexPath: IndexPath) -> Bool { let blockSize = self.getBlockSizeForItemAtIndexPath(indexPath: indexPath) let isVertical = self.isVertical() return !self.traversepublicTiles(block: { blockOrigin in let didTraverseAllBlocks = self.traverseTilesForPoint(point: blockOrigin, withSize: blockSize, block: { point in let indexPath: IndexPath? = self.indexPathForPosition(point: point) let spaceAvailable = indexPath == nil let inBounds = Int(isVertical ? point.x : point.y) < self.restrictedDimensionBlockSize() let maximumRestrictedBoundSize = Int(isVertical ? blockOrigin.x : blockOrigin.y) == 0 if spaceAvailable && maximumRestrictedBoundSize && !inBounds { #if DEBUG let text = isVertical ? "wide" : "tall" print("\(self.className): layout is not \(text) enough for this piece size: \(NSStringFromCGSize(blockSize))! Adding anyway...") #endif return true } return (spaceAvailable && inBounds) }) if (!didTraverseAllBlocks) { return true } // because we have determined that the space is all available, lets fill it in as taken. self.setIndexPath(path: indexPath, forPosition: blockOrigin) self.traverseTilesForPoint(point: blockOrigin, withSize: blockSize, block: { point in self.setPosition(point: point, forIndexPath: indexPath) self.furthestBlockPoint = point return true }) return false }) } // returning false in the callback will terminate the iterations early private func traverseTilesBetweenUnrestrictedDimension(begin: Int, and end: Int, block: ((CGPoint) -> Bool)) -> Bool { let isVertical = self.isVertical() for unrestrictedDimension in begin..<end { for restrictedDimension in 0..<self.restrictedDimensionBlockSize() { let x = isVertical ? restrictedDimension : unrestrictedDimension let y = isVertical ? unrestrictedDimension : restrictedDimension let point = CGPoint(x: x, y: y) if !block(point) { return false } } } return true } // returning false in the callback will terminate the iterations early private func traverseTilesForPoint(point: CGPoint, withSize size: CGSize, block: ((CGPoint) -> Bool)) -> Bool { for col in stride(from: point.x, to: point.x + size.width, by: 1) { for row in stride(from: point.y, to: point.y + size.height, by: 1) { let point = CGPoint(x: col, y: row) if !block(point) { return false } } } return true } // returning false in the callback will terminate the iterations early private func traversepublicTiles(block: (CGPoint) -> (Bool)) -> Bool { var allTakenBefore = true let isVertical = self.isVertical() var unrestrictedDimension = Int(isVertical ? self.firstpublicSpace.y : self.firstpublicSpace.x) // the unrestricted dimension should iterate indefinitely. the >= to 0 is intentional while unrestrictedDimension >= 0 { for restrictedDimension in 0..<self.restrictedDimensionBlockSize() { let x = Int(isVertical ? restrictedDimension : unrestrictedDimension) let y = Int(isVertical ? unrestrictedDimension : restrictedDimension) let point = CGPoint(x: x, y: y) let indexPath = self.indexPathForPosition(point: point) if (indexPath != nil) { continue } if allTakenBefore { self.firstpublicSpace = point allTakenBefore = false } let blockResult = block(point) if !blockResult { return false } } // increment unrestrictedDimension unrestrictedDimension += 1 } #if DEBUG print("Unable to find a place for a block!") #endif return true } private func clearPositions() { self.indexPathByPosition = [Int:[Int:IndexPath]]() self.positionByIndexPath = [Int:[Int:CGPoint]]() } private func indexPathForPosition(point: CGPoint) -> IndexPath? { let isVertical = self.isVertical() // To avoid creating unbounded NSMutableDictionaries we should // have the inner dictionary be the unrestricted dimension let unrestrictedPoint = Int(isVertical ? point.y : point.x) let restrictedPoint = Int(isVertical ? point.x : point.y) return self.indexPathByPosition[restrictedPoint]?[unrestrictedPoint] } private func setPosition(point: CGPoint, forIndexPath indexPath: IndexPath) { let isVertical = self.isVertical() // To avoid creating unbounded NSMutableDictionaries we should // have the innerdict be the unrestricted dimension let unrestrictedPoint = Int(isVertical ? point.y : point.x) let restrictedPoint = Int(isVertical ? point.x : point.y) let dictionary = self.indexPathByPosition[restrictedPoint] if dictionary == nil { self.indexPathByPosition[restrictedPoint] = [Int:IndexPath]() } self.indexPathByPosition[restrictedPoint]?[unrestrictedPoint] = indexPath } private func setIndexPath(path: IndexPath, forPosition point: CGPoint) { let innerDict = self.positionByIndexPath[path.section] if innerDict == nil { self.positionByIndexPath[path.section] = [Int:CGPoint]() } self.positionByIndexPath[path.section]?[path.row] = point // Store the index path so we can use it later on for selecting random cell's to scroll to self.cellIndexPaths[self.cellIndexPaths.count] = path } private func positionForIndexPath(path: IndexPath) -> CGPoint { // if item does not have a position, make one let sectionIndex = self.positionByIndexPath[path.section]?[path.row] if sectionIndex == nil { self.fillInBlocksToIndexPath(path: path) } return self.positionByIndexPath[path.section]?[path.row] ?? CGPoint.zero } private func frameForIndexPath(path: IndexPath) -> CGRect { let position = self.positionForIndexPath(path: path) let elementSize = self.getBlockSizeForItemAtIndexPath(indexPath: path) let contentRect = UIEdgeInsetsInsetRect(self.collectionView!.frame, self.collectionView!.contentInset) if self.isVertical() { // Definitions: // self.restrictedDimensionBlockSize() - The number of columns in the collection view // self.itemBlockSize.width - The width of one column/block including it's margin let initialPaddingForConstraintedDimension = (Int(contentRect.width) - self.restrictedDimensionBlockSize() * Int(self.itemBlockSize.width)) / 2 let rect = CGRect( x: Int(position.x * self.itemBlockSize.width) + initialPaddingForConstraintedDimension, y: Int(position.y * self.itemBlockSize.height), width: Int(elementSize.width * self.itemBlockSize.width), height: Int(elementSize.height * self.itemBlockSize.height) ) return rect } else { let initialPaddingForConstraintedDimension = (Int(contentRect.height) - self.restrictedDimensionBlockSize() * Int(self.itemBlockSize.height)) / 2 let rect = CGRect( x: Int(position.x * self.itemBlockSize.width), y: Int(position.y * self.itemBlockSize.height) + initialPaddingForConstraintedDimension, width: Int(elementSize.width * self.itemBlockSize.width), height: Int(elementSize.height * self.itemBlockSize.height) ) return rect } } // This method is prefixed with get because it may return its value indirectly private func getBlockSizeForItemAtIndexPath(indexPath: IndexPath) -> CGSize { var blockSize = CGSize(width: 1, height: 1) if self.delegate?.responds(to: Selector(Constants.String.CollectionViewBlockSizeForItem)) != nil { blockSize = self.delegate!.collectionView!(collectionView: self.collectionView!, layout: self, blockSizeForItemAtIndexPath: indexPath) } return blockSize } // this will return the maximum width or height the layout can // take, depending on if we are growing horizontally or vertically private func restrictedDimensionBlockSize() -> Int { let isVertical = self.isVertical() let contentRect = UIEdgeInsetsInsetRect(self.collectionView!.frame, self.collectionView!.contentInset) let size = Int(isVertical ? contentRect.width / self.itemBlockSize.width : contentRect.height / self.itemBlockSize.height) if size == 0 { struct Temp { static var didShowMessage = false } if (Temp.didShowMessage == false) { #if DEBUG print("\(self.className): cannot fit block of size: \(NSStringFromCGSize(self.itemBlockSize)) in content rect \(NSStringFromCGRect(contentRect))! Defaulting to 1") #endif Temp.didShowMessage = true } return 1 } return size } private func isVertical() -> Bool { return self.scrollDirection == UICollectionViewScrollDirection.vertical } }
mit
c7c460e72f353bce217a6f060a12b734
37.863544
186
0.68562
4.825999
false
false
false
false
stephentyrone/swift
test/Profiler/pgo_switchenum.swift
5
4819
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_switchenum -o %t/main // This unusual use of 'sh' allows the path of the profraw file to be // substituted by %target-run. // RUN: %target-run sh -c 'env LLVM_PROFILE_FILE=$1 $2' -- %t/default.profraw %t/main // RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata // need to move counts attached to expr for this // RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-sorted-sil -emit-sil -module-name pgo_switchenum -o - | %FileCheck %s --check-prefix=SIL // need to lower switch_enum(addr) into IR for this // %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-ir -module-name pgo_switchenum -o - | %FileCheck %s --check-prefix=IR // need to check Opt support // %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-sorted-sil -emit-sil -module-name pgo_switchenum -o - | %FileCheck %s --check-prefix=SIL-OPT // need to lower switch_enum(addr) into IR for this // %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-ir -module-name pgo_switchenum -o - | %FileCheck %s --check-prefix=IR-OPT // REQUIRES: profile_runtime // REQUIRES: executable_test // REQUIRES: OS=macosx public enum MaybePair { case Neither case Left(Int32) case Right(String) case Both(Int32, String) } // SIL-LABEL: // pgo_switchenum.guess1 // SIL-LABEL: sil @$s14pgo_switchenum6guess11xs5Int32VAA9MaybePairO_tF : $@convention(thin) (@guaranteed MaybePair) -> Int32 !function_entry_count(5011) { // IR-LABEL: define swiftcc i32 @$s9pgo_switchenum6guess1s5Int32VAD1x_tF // IR-OPT-LABEL: define swiftcc i32 @$s9pgo_switchenum6guess1s5Int32VAD1x_tF public func guess1(x: MaybePair) -> Int32 { // SIL: switch_enum {{.*}} : $MaybePair, case #MaybePair.Neither!enumelt: {{.*}} !case_count(2), case #MaybePair.Left!enumelt: {{.*}} !case_count(5001), case #MaybePair.Right!enumelt: {{.*}} !case_count(3), case #MaybePair.Both!enumelt: {{.*}} !case_count(5) // SIL-OPT: switch_enum {{.*}} : $MaybePair, case #MaybePair.Neither!enumelt: {{.*}} !case_count(2), case #MaybePair.Left!enumelt: {{.*}} !case_count(5001), case #MaybePair.Right!enumelt: {{.*}} !case_count(3), case #MaybePair.Both!enumelt: {{.*}} !case_count(5) switch x { case .Neither: return 1 case let .Left(val): return val*2 case let .Right(val): return Int32(val.count) case let .Both(valNum, valStr): return valNum + Int32(valStr.count) } } // SIL-LABEL: // pgo_switchenum.guess2 // SIL-LABEL: sil @$s14pgo_switchenum6guess21xs5Int32VAA9MaybePairO_tF : $@convention(thin) (@guaranteed MaybePair) -> Int32 !function_entry_count(5011) { public func guess2(x: MaybePair) -> Int32 { // SIL: switch_enum {{.*}} : $MaybePair, case #MaybePair.Neither!enumelt: {{.*}} !case_count(2), case #MaybePair.Left!enumelt: {{.*}} !case_count(5001), default {{.*}} !default_count(8) // SIL-OPT: switch_enum {{.*}} : $MaybePair, case #MaybePair.Neither!enumelt: {{.*}} !case_count(2), case #MaybePair.Left!enumelt: {{.*}} !case_count(5001), default {{.*}} !default_count(8) switch x { case .Neither: return 1 case let .Left(val): return val*2 default: return 42; } } func main() { var guesses : Int32 = 0; guesses += guess1(x: MaybePair.Neither) guesses += guess1(x: MaybePair.Neither) guesses += guess1(x: MaybePair.Left(42)) guesses += guess1(x: MaybePair.Right("The Answer")) guesses += guess1(x: MaybePair.Right("The Answer")) guesses += guess1(x: MaybePair.Right("The Answer")) guesses += guess1(x: MaybePair.Both(42, "The Answer")) guesses += guess1(x: MaybePair.Both(42, "The Answer")) guesses += guess1(x: MaybePair.Both(42, "The Answer")) guesses += guess1(x: MaybePair.Both(42, "The Answer")) guesses += guess1(x: MaybePair.Both(42, "The Answer")) for _ in 1...5000 { guesses += guess1(x: MaybePair.Left(10)) } guesses += guess2(x: MaybePair.Neither) guesses += guess2(x: MaybePair.Neither) guesses += guess2(x: MaybePair.Left(42)) guesses += guess2(x: MaybePair.Right("The Answer")) guesses += guess2(x: MaybePair.Right("The Answer")) guesses += guess2(x: MaybePair.Right("The Answer")) guesses += guess2(x: MaybePair.Both(42, "The Answer")) guesses += guess2(x: MaybePair.Both(42, "The Answer")) guesses += guess2(x: MaybePair.Both(42, "The Answer")) guesses += guess2(x: MaybePair.Both(42, "The Answer")) guesses += guess2(x: MaybePair.Both(42, "The Answer")) for _ in 1...5000 { guesses += guess2(x: MaybePair.Left(10)) } } main() // IR: !{!"branch_weights", i32 5001, i32 3} // IR-OPT: !{!"branch_weights", i32 5001, i32 3}
apache-2.0
2ca95237c8fbe030d564b03a636fbd81
44.895238
264
0.678564
3.071383
false
false
false
false
1000copy/fin
Common/UserListKeychain.swift
1
2935
// // V2Keychain.swift // V2ex-Swift // // Created by huangfeng on 2/11/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit let USERKEY = "USERKEY" class UserListKeychain { static let shared = UserListKeychain() fileprivate(set) var users:[String:LoginUser] = [:] fileprivate init() { let _ = loadUsersDict() } func addUser(_ user:LoginUser){ if let username = user.username , let _ = user.password { self.users[username] = user self.saveUsersDict() } else { assert(false, "username & password must not be 'nil'") } } func addUser(_ username:String,password:String,avata:String? = nil) { let user = LoginUser() user.username = username user.password = password user.avatar = avata self.addUser(user) } func saveUsersDict(){ let data = NSMutableData() let archiver = NSKeyedArchiver(forWritingWith: data) archiver.encode(self.users) archiver.finishEncoding() let _ = Keychain.save(USERKEY,data as Data) } func loadUsersDict() -> [String:LoginUser]{ if users.count <= 0 { let data = Keychain.load(USERKEY) if let data = data{ let archiver = NSKeyedUnarchiver(forReadingWith: data) let usersDict = archiver.decodeObject() archiver.finishDecoding() if let usersDict = usersDict as? [String : LoginUser] { self.users = usersDict } } } return self.users } func removeUser(_ username:String){ self.users.removeValue(forKey: username) self.saveUsersDict() } func removeAll(){ self.users = [:] self.saveUsersDict() } func update(_ username:String,password:String? = nil,avatar:String? = nil){ if let user = self.users[username] { if let password = password { user.password = password } if let avatar = avatar { user.avatar = avatar } self.saveUsersDict() } } } /// 将会序列化后保存进keychain中的 账户model class LoginUser :NSObject, NSCoding { var username:String? var password:String? var avatar:String? override init(){ } required init?(coder aDecoder: NSCoder){ self.username = aDecoder.decodeObject(forKey: "username") as? String self.password = aDecoder.decodeObject(forKey: "password") as? String self.avatar = aDecoder.decodeObject(forKey: "avatar") as? String } func encode(with aCoder: NSCoder){ aCoder.encode(self.username, forKey: "username") aCoder.encode(self.password, forKey: "password") aCoder.encode(self.avatar, forKey: "avatar") } }
mit
89799fa14ffcc98978d3c147dfa47000
27.509804
79
0.572215
4.35982
false
false
false
false
milseman/swift
test/SILGen/class_bound_protocols.swift
4
13029
// RUN: %target-swift-frontend -parse-stdlib -parse-as-library -module-name Swift -emit-silgen %s | %FileCheck %s enum Optional<T> { case some(T) case none } precedencegroup AssignmentPrecedence {} // -- Class-bound archetypes and existentials are *not* address-only and can // be manipulated using normal reference type value semantics. protocol NotClassBound { func notClassBoundMethod() } protocol ClassBound : class { func classBoundMethod() } protocol ClassBound2 : class { func classBound2Method() } class ConcreteClass : NotClassBound, ClassBound, ClassBound2 { func notClassBoundMethod() {} func classBoundMethod() {} func classBound2Method() {} } class ConcreteSubclass : ConcreteClass { } // CHECK-LABEL: sil hidden @_T0s19class_bound_generic{{[_0-9a-zA-Z]*}}F func class_bound_generic<T : ClassBound>(x: T) -> T { var x = x // CHECK: bb0([[X:%.*]] : $T): // CHECK: [[X_ADDR:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ClassBound> { var τ_0_0 } <T> // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]] // CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]] // CHECK: store [[X_COPY]] to [init] [[PB]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: destroy_value [[X_ADDR]] // CHECK: destroy_value [[X]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @_T0s21class_bound_generic_2{{[_0-9a-zA-Z]*}}F func class_bound_generic_2<T : ClassBound & NotClassBound>(x: T) -> T { var x = x // CHECK: bb0([[X:%.*]] : $T): // CHECK: [[X_ADDR:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ClassBound, τ_0_0 : NotClassBound> { var τ_0_0 } <T> // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]] // CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]] // CHECK: store [[X_COPY]] to [init] [[PB]] // CHECK: end_borrow [[BORROWED_X]] from [[X]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @_T0s20class_bound_protocol{{[_0-9a-zA-Z]*}}F func class_bound_protocol(x: ClassBound) -> ClassBound { var x = x // CHECK: bb0([[X:%.*]] : $ClassBound): // CHECK: [[X_ADDR:%.*]] = alloc_box ${ var ClassBound } // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]] // CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]] // CHECK: store [[X_COPY]] to [init] [[PB]] // CHECK: end_borrow [[BORROWED_X]] from [[X]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*ClassBound // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @_T0s32class_bound_protocol_composition{{[_0-9a-zA-Z]*}}F func class_bound_protocol_composition(x: ClassBound & NotClassBound) -> ClassBound & NotClassBound { var x = x // CHECK: bb0([[X:%.*]] : $ClassBound & NotClassBound): // CHECK: [[X_ADDR:%.*]] = alloc_box ${ var ClassBound & NotClassBound } // CHECK: [[PB:%.*]] = project_box [[X_ADDR]] // CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]] // CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]] // CHECK: store [[X_COPY]] to [init] [[PB]] // CHECK: end_borrow [[BORROWED_X]] from [[X]] return x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*ClassBound & NotClassBound // CHECK: [[X1:%.*]] = load [copy] [[READ]] // CHECK: return [[X1]] } // CHECK-LABEL: sil hidden @_T0s19class_bound_erasure{{[_0-9a-zA-Z]*}}F func class_bound_erasure(x: ConcreteClass) -> ClassBound { return x // CHECK: [[PROTO:%.*]] = init_existential_ref {{%.*}} : $ConcreteClass, $ClassBound // CHECK: return [[PROTO]] } // CHECK-LABEL: sil hidden @_T0s30class_bound_existential_upcasts10ClassBound_psAB_s0E6Bound2p1x_tF : func class_bound_existential_upcast(x: ClassBound & ClassBound2) -> ClassBound { return x // CHECK: bb0([[ARG:%.*]] : $ClassBound & ClassBound2): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[OPENED:%.*]] = open_existential_ref [[BORROWED_ARG]] : $ClassBound & ClassBound2 to [[OPENED_TYPE:\$@opened(.*) ClassBound & ClassBound2]] // CHECK: [[OPENED_COPY:%.*]] = copy_value [[OPENED]] // CHECK: [[PROTO:%.*]] = init_existential_ref [[OPENED_COPY]] : [[OPENED_TYPE]] : [[OPENED_TYPE]], $ClassBound // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[PROTO]] } // CHECK: } // end sil function '_T0s30class_bound_existential_upcasts10ClassBound_psAB_s0E6Bound2p1x_tF' // CHECK-LABEL: sil hidden @_T0s41class_bound_to_unbound_existential_upcasts13NotClassBound_ps0hI0_sABp1x_tF : // CHECK: bb0([[ARG0:%.*]] : $*NotClassBound, [[ARG1:%.*]] : $ClassBound & NotClassBound): // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: [[X_OPENED:%.*]] = open_existential_ref [[BORROWED_ARG1]] : $ClassBound & NotClassBound to [[OPENED_TYPE:\$@opened(.*) ClassBound & NotClassBound]] // CHECK: [[PAYLOAD_ADDR:%.*]] = init_existential_addr [[ARG0]] : $*NotClassBound, [[OPENED_TYPE]] // CHECK: [[X_OPENED_COPY:%.*]] = copy_value [[X_OPENED]] // CHECK: store [[X_OPENED_COPY]] to [init] [[PAYLOAD_ADDR]] // CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]] // CHECK: destroy_value [[ARG1]] func class_bound_to_unbound_existential_upcast (x: ClassBound & NotClassBound) -> NotClassBound { return x } // CHECK-LABEL: sil hidden @_T0s18class_bound_methodys10ClassBound_p1x_tF : // CHECK: bb0([[ARG:%.*]] : $ClassBound): func class_bound_method(x: ClassBound) { var x = x x.classBoundMethod() // CHECK: [[XBOX:%.*]] = alloc_box ${ var ClassBound }, var, name "x" // CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: store [[ARG_COPY]] to [init] [[XBOX_PB]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[XBOX_PB]] : $*ClassBound // CHECK: [[X:%.*]] = load [copy] [[READ]] : $*ClassBound // CHECK: [[PROJ:%.*]] = open_existential_ref [[X]] : $ClassBound to $[[OPENED:@opened(.*) ClassBound]] // CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #ClassBound.classBoundMethod!1 // CHECK: apply [[METHOD]]<[[OPENED]]>([[PROJ]]) // CHECK: destroy_value [[PROJ]] // CHECK: destroy_value [[XBOX]] // CHECK: destroy_value [[ARG]] } // CHECK: } // end sil function '_T0s18class_bound_methodys10ClassBound_p1x_tF' // rdar://problem/31858378 struct Value {} protocol HasMutatingMethod { mutating func mutateMe() var mutatingCounter: Value { get set } var nonMutatingCounter: Value { get nonmutating set } } protocol InheritsMutatingMethod : class, HasMutatingMethod {} func takesInOut<T>(_: inout T) {} // CHECK-LABEL: sil hidden @_T0s27takesInheritsMutatingMethodys0bcD0_pz1x_s5ValueV1ytF : $@convention(thin) (@inout InheritsMutatingMethod, Value) -> () { func takesInheritsMutatingMethod(x: inout InheritsMutatingMethod, y: Value) { // CHECK: [[X_ADDR:%.*]] = begin_access [modify] [unknown] %0 : $*InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") InheritsMutatingMethod, #HasMutatingMethod.mutateMe!1 : <Self where Self : HasMutatingMethod> (inout Self) -> () -> (), [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@inout τ_0_0) -> () // CHECK-NEXT: apply [[METHOD]]<@opened("{{.*}}") InheritsMutatingMethod>([[TEMPORARY]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@inout τ_0_0) -> () // CHECK-NEXT: [[X_PAYLOAD:%.*]] = load [take] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = init_existential_ref [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@opened("{{.*}}") InheritsMutatingMethod, $InheritsMutatingMethod // CHECK-NEXT: assign [[X_VALUE]] to [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod x.mutateMe() // CHECK-NEXT: [[RESULT_BOX:%.*]] = alloc_stack $Value // CHECK-NEXT: [[RESULT:%.*]] = mark_uninitialized [var] [[RESULT_BOX]] : $*Value // CHECK-NEXT: [[X_ADDR:%.*]] = begin_access [read] [unknown] %0 : $*InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[X_PAYLOAD_RELOADED:%.*]] = load [take] [[TEMPORARY]] // CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") InheritsMutatingMethod, #HasMutatingMethod.mutatingCounter!getter.1 : <Self where Self : HasMutatingMethod> (Self) -> () -> Value, [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@in_guaranteed τ_0_0) -> Value // // ** *NOTE* This extra copy is here since RValue invariants enforce that all // ** loadable objects are actually loaded. So we form the RValue and // ** load... only to then need to store the value back in a stack location to // ** pass to an in_guaranteed method. PredictableMemOpts is able to handle this // ** type of temporary codegen successfully. // CHECK-NEXT: [[TEMPORARY_2:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: store [[X_PAYLOAD_RELOADED:%.*]] to [init] [[TEMPORARY_2]] // // CHECK-NEXT: [[RESULT_VALUE:%.*]] = apply [[METHOD]]<@opened("{{.*}}") InheritsMutatingMethod>([[TEMPORARY_2]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@in_guaranteed τ_0_0) -> Value // CHECK-NEXT: [[X_VALUE:%.*]] = load [take] [[TEMPORARY_2]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: destroy_value [[X_VALUE]] : $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: dealloc_stack [[TEMPORARY_2]] // CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: assign [[RESULT_VALUE]] to [[RESULT]] : $*Value // CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: dealloc_stack [[RESULT_BOX]] : $*Value _ = x.mutatingCounter // CHECK-NEXT: [[X_ADDR:%.*]] = begin_access [modify] [unknown] %0 : $*InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") InheritsMutatingMethod, #HasMutatingMethod.mutatingCounter!setter.1 : <Self where Self : HasMutatingMethod> (inout Self) -> (Value) -> (), [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasMutatingMethod> (Value, @inout τ_0_0) -> () // CHECK-NEXT: apply [[METHOD]]<@opened("{{.*}}") InheritsMutatingMethod>(%1, [[TEMPORARY]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : HasMutatingMethod> (Value, @inout τ_0_0) -> () // CHECK-NEXT: [[X_PAYLOAD:%.*]] = load [take] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod // CHECK-NEXT: [[X_VALUE:%.*]] = init_existential_ref [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@opened("{{.*}}") InheritsMutatingMethod, $InheritsMutatingMethod // CHECK-NEXT: assign [[X_VALUE]] to [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod // CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod x.mutatingCounter = y takesInOut(&x.mutatingCounter) _ = x.nonMutatingCounter x.nonMutatingCounter = y takesInOut(&x.nonMutatingCounter) }
apache-2.0
6c3e6513f23c101149897aa4a8e0cecc
54.811159
363
0.620963
3.594251
false
false
false
false
duycao2506/SASCoffeeIOS
SAS Coffee/Extension/UIImage+Extension.swift
1
1406
// // UIImage+Extension.swift // SAS Coffee // // Created by Duy Cao on 9/2/17. // Copyright © 2017 Duy Cao. All rights reserved. // import UIKit import Foundation extension UIImage { func resizeImage(scale: CGFloat) -> UIImage { let newSize = CGSize(width: self.size.width*scale, height: self.size.height*scale) UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) self.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } func changeTint(color : UIColor) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) guard let context = UIGraphicsGetCurrentContext() else { return nil } context.scaleBy(x: 1.0, y: -1.0) context.translateBy(x: 0.0, y: -size.height) context.setBlendMode(.multiply) let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) context.clip(to: rect, mask: cgImage!) color.setFill() context.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image?.withRenderingMode(.alwaysOriginal) } }
gpl-3.0
570ae71414ffd81b3dc7fb86d922bb42
30.222222
90
0.631317
4.517685
false
false
false
false
lastObject/ZYCalendar
ZYCalendar/ZYCalendar/Classes/Main/Controllers/MainViewController.swift
1
6201
// // MainViewController.swift // ZYCalendar // // Created by jiangdianyi on 11/8/2016. // Copyright © 2016 dianyi jiang. All rights reserved. // import UIKit class MainViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource { let heightOfHeader: CGFloat = 80.0 let heightOfToolBar: CGFloat = 60.0 let tableView: UITableView = UITableView() private var didSetupConstraints = false private var toolBar: MainToolBar = MainToolBar(frame: CGRectZero) //------------------------------------------------------------------------------ // MARK: - lifecycle //------------------------------------------------------------------------------ override func viewDidLoad() { super.viewDidLoad() self.registers() self.setupUIElements() self.setupDataSource() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) print(#function) } override func prefersStatusBarHidden() -> Bool { return true } //------------------------------------------------------------------------------ // MARK: setup after view did load //------------------------------------------------------------------------------ func registers() { self.registeClasses() self.registeNotifications() } func setupUIElements() { self.setupNavigationItems() self.setupControllerView() self.setupMainUIs() self.view.setNeedsUpdateConstraints() } func setupDataSource() { } //------------------------------------------------------------------------------ // MARK: setup register //------------------------------------------------------------------------------ func registeClasses() { tableView.registerClass(MainCell.self, forCellReuseIdentifier:MainCell.reuseIdentifier()) tableView.registerClass(EmptyMainCell.self, forCellReuseIdentifier:EmptyMainCell.reuseIdentifier()) } func registeNotifications() { } //------------------------------------------------------------------------------ // MARK: setup UI Elements //------------------------------------------------------------------------------ func setupControllerView() { tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 50 tableView.tableFooterView = UIView() tableView.allowsSelection = false tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.contentInset = UIEdgeInsetsMake(-heightOfHeader, 0, 0, 0); tableView.showsVerticalScrollIndicator = false tableView.showsHorizontalScrollIndicator = false tableView.backgroundColor = backgroundColor self.automaticallyAdjustsScrollViewInsets = false } func setupNavigationItems() { } func setupMainUIs() { tableView.delegate = self; tableView.dataSource = self; self.view.addSubview(tableView) self.view.addSubview(toolBar) } override func updateViewConstraints() { if !didSetupConstraints { didSetupConstraints = true tableView.snp_makeConstraints(closure: { (make) in make.top.leading.trailing.equalTo(self.view) make.bottom.equalTo(toolBar.snp_top) }) toolBar.snp_makeConstraints(closure: { (make) in make.leading.bottom.trailing.equalTo(self.view) make.height.equalTo(heightOfHeader) }) } super.updateViewConstraints() } //------------------------------------------------------------------------------ // MARK: setup data source //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // MARK: - tableview //------------------------------------------------------------------------------ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Int(NSDate().day) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // // 如果当天有数据 不显示小点 // 周末显示别的颜色 // 最后一天应该是大的today // let cell: EmptyMainCell = tableView.dequeueReusableCellWithIdentifier(EmptyMainCell.reuseIdentifier(), forIndexPath: indexPath) as! EmptyMainCell cell.weekday = indexPath.row % 2 == 0; return cell } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header: UITableViewHeaderFooterView = UITableViewHeaderFooterView(reuseIdentifier: TodayHeader.reuseIdentifier()); let todayHeader: TodayHeader = TodayHeader(frame:CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, heightOfHeader)) header.addSubview(todayHeader) return header } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return heightOfHeader; } //------------------------------------------------------------------------------ // MARK: main tool bar delegate //------------------------------------------------------------------------------ func mainToolBarDidClickAddButton() { } }
mit
7278c36a6b56fc541d0c527117844139
30.659794
153
0.511397
6.583065
false
false
false
false
berzniz/Sequencer.swift
Sequencer/Sequencer.swift
1
814
// // Sequencer.swift // Sequencer // // Created by Tal Bereznitskey on 6/4/14. // Copyright (c) 2014 ketacode. All rights reserved. // import Foundation class Sequencer { typealias SequencerNext = (AnyObject? -> Void) typealias SequencerStep = (AnyObject?, SequencerNext) -> Void var steps: [SequencerStep] = [] func run() { runNextStepWithResult(nil) } func enqueueStep(step: SequencerStep) { steps.append(step) } func dequeueNextStep() -> (SequencerStep) { return steps.removeAtIndex(0) } func runNextStepWithResult(result: AnyObject?) { if (steps.count <= 0) { return } var step = dequeueNextStep() step(result, { self.runNextStepWithResult($0) }) } }
mit
a078388c8e59e36956f36f444e93ddb5
19.897436
65
0.587224
3.87619
false
false
false
false
soso1617/iCalendar
Calendar/ViewControllers/Home/HomeViewController.swift
1
5081
// // HomeViewController.swift // Calendar // // Created by Zhang, Eric X. on 4/30/17. // Copyright © 2017 ShangHe. All rights reserved. // import UIKit /********************************************************************* * * class HomeViewController * *********************************************************************/ class HomeViewController: BaseViewController { var calendarViewController = CalendarViewController() var agendaViewController = AgendaViewController() var selectedDate = UILabel.init() private let dateStringFormat = " %@, %@" deinit { // // remove observing for day changed event // NotificationCenter.default.removeObserver(self, name: .init(CalendarViewDefinition.kNotificationNameDayChanged), object: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nil, bundle: nil) // // register observing for day changed event // NotificationCenter.default.addObserver(forName: .init(CalendarViewDefinition.kNotificationNameDayChanged), object: nil, queue: OperationQueue.init()) { (notification) in debugPrint("Day changed") if let day = notification.object as? Day { // // change agenda view in main queue // DispatchQueue.main.async { // // set date string // self.selectedDate.text = String.init(format: self.dateStringFormat, day.nameInWeek!, DateConversion.date2LongStringFromDate(day.date! as Date)) // // get new agenda view // self.agendaViewController.setNewDayAndReload(day) } } } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func initialFromLoad() { self.title = "Home_Title".localized // // init calendar view frame // self.calendarViewController.view.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: kHeaderTitleViewHeight + CalendarViewDefinition.monthViewFrame().height) self.calendarViewController.view.autoresizingMask = [.flexibleBottomMargin, .flexibleWidth] self.view.addSubview(self.calendarViewController.view) // // init selected date // let selectedDateHeight: CGFloat = 18.0 self.selectedDate.textColor = UIColor.icWhite self.selectedDate.font = UIFont.icFont2 self.selectedDate.frame = CGRect(x: 0, y: self.calendarViewController.view.frame.origin.y + self.calendarViewController.view.frame.height, width: self.view.bounds.width, height: selectedDateHeight) self.selectedDate.backgroundColor = UIColor.icGrayishBlue // // set default date string // if let day = DayManager.sharedManager.today() { self.selectedDate.text = String.init(format: self.dateStringFormat, day.nameInWeek!, DateConversion.date2LongStringFromDate(day.date! as Date)) } self.view.addSubview(self.selectedDate) // // init agenda view frame // self.agendaViewController.view.frame = CGRect(x: 0, y: self.calendarViewController.view.frame.origin.y + self.calendarViewController.view.frame.height + selectedDateHeight, width: self.view.bounds.size.width, height: self.view.bounds.height - (kHeaderTitleViewHeight + CalendarViewDefinition.monthViewFrame().height + selectedDateHeight)) self.agendaViewController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] self.agendaViewController.setNewDayAndReload(DayManager.sharedManager.today()!) self.view.addSubview(self.agendaViewController.view) // // add cancel button // self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "Btn_Today".localized, style: .done, target: self, action: #selector(self.go2Today)) } @objc private func go2Today() { self.calendarViewController.go2Today() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
40cca8d5a04ad83e228562318699a945
35.546763
346
0.60315
5.120968
false
false
false
false
kirkvogen/masterdetail-j2objc-swift
masterdetail-ios/masterdetail-ios/DetailViewController.swift
1
2829
// // Copyright 2014-2015 Kirk C. Vogen // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // import UIKit class DetailViewController: UIViewController, JavaBeansPropertyChangeListener { @IBOutlet weak var listTitle: UITextField! @IBOutlet weak var words: UITextView! let detailService: DetailService let viewModel: DetailViewModel required init?(coder decoder: NSCoder) { detailService = FlatFileDetailService(storageService: LocalStorageService()) viewModel = DetailViewModel(detailService: detailService) super.init(coder: decoder) } var listId: CInt? func configureView() { if let id = self.listId { viewModel.init__WithInt(id) // No need to set field values as the PropertyChangeListener given to the view model will set the fields } } override func viewDidLoad() { super.viewDidLoad() viewModel.addPropertyChangeListenerWithJavaBeansPropertyChangeListener(self) // Do any additional setup after loading the view, typically from a nib. self.configureView() } override func viewWillDisappear(animated:Bool) { // This method will need to change if there is another view to forward to in addition to the // view to go back to. viewModel.saveWithNSString(self.listTitle.text, withNSString: self.words.text) super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func propertyChangeWithJavaBeansPropertyChangeEvent(event: JavaBeansPropertyChangeEvent!) { switch event.getPropertyName() { case DetailViewModel_TITLE: if let textfield = listTitle { if let newValue: AnyObject = event.getNewValue() { textfield.text = newValue as? String } } case DetailViewModel_WORDS: if let textfield = words { if let newValue: AnyObject = event.getNewValue() { textfield.text = newValue as! String } } default: break } } }
apache-2.0
dd681c922bdf4bb4a33d90b04be96b04
32.282353
116
0.645104
5.106498
false
false
false
false
GrandCentralBoard/GrandCentralBoard
Pods/Operations/Sources/Core/Shared/BlockCondition.swift
2
2451
// // BlockCondition.swift // Operations // // Created by Daniel Thorpe on 22/07/2015. // Copyright (c) 2015 Daniel Thorpe. All rights reserved. // import Foundation /** An `OperationCondition` which will be satisfied if the block returns true. */ public struct BlockCondition: OperationCondition { /// The block type which returns a Bool. public typealias ConditionBlockType = () throws -> Bool /// The error used to indicate failure, in the case /// of a false return, without a thrown error. public enum Error: ErrorType { /** If the block returns false, the operation to which it is attached will fail with this error. */ case BlockConditionFailed } /** The name of the condition. - parameter name: a constant String `Block Condition`. */ public let name = "Block Condition" /** The mutual exclusivity of the condition, which is false. - parameter isMutuallyExclusive: a constant Bool, false. */ public let isMutuallyExclusive = false let condition: ConditionBlockType /** Creates a `BlockCondition` with the supplied block. Example like this.. operation.addCondition(BlockCondition { true }) Alternatively func checkFlag() -> Bool { return toDoSomethingOrNot } operation.addCondition(BlockCondition(block: checkFlag)) - parameter block: a `ConditionBlockType`. */ public init(block: ConditionBlockType) { condition = block } /// Conforms to `OperationCondition`, but there are no dependencies, so it returns .None. public func dependencyForOperation(operation: Operation) -> NSOperation? { return .None } /** Evaluates the condition, it will execute the block. - parameter operation: the attached `Operation` - parameter completion: the evaulation completion block, it is given the result. */ public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) { do { let result = try condition() completion(result ? .Satisfied : .Failed(Error.BlockConditionFailed)) } catch { completion(.Failed(error)) } } } extension BlockCondition.Error: Equatable { } public func == (_: BlockCondition.Error, _: BlockCondition.Error) -> Bool { return true // Only one case in the enum }
gpl-3.0
064e4b55cda6177d3243a5d26d21b918
25.354839
106
0.655651
4.88247
false
false
false
false
attackFromCat/LivingTVDemo
LivingTVDemo/LivingTVDemo/Classes/Home/Controller/RecommendViewController.swift
1
3643
// // RecommendViewController.swift // LivingTVDemo // // Created by 李翔 on 2017/1/9. // Copyright © 2017年 Lee Xiang. All rights reserved. // import UIKit // MARK: - 基本常量 fileprivate let kCycleViewH = kScreenW * 3 / 8 fileprivate let kGameViewH : CGFloat = 90 class RecommendViewController: BaseAnchorViewController { // MARK:- 懒加载属性 fileprivate lazy var recommendVM : RecommendViewModel = RecommendViewModel() fileprivate lazy var cycleView : RecommendCycleView = { let cycleView = RecommendCycleView.recommendCycleView() cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH) return cycleView }() fileprivate lazy var gameView : RecommendGameView = { let gameView = RecommendGameView.recommendGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) return gameView }() } extension RecommendViewController { override func setupUI() { // 1.先调用super.setupUI() super.setupUI() // 2.将CycleView添加到UICollectionView中 collectionView.addSubview(cycleView) // 3.将gameView添加collectionView中 collectionView.addSubview(gameView) // 4.设置collectionView的内边距 collectionView.contentInset = UIEdgeInsets(top: kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0) } } extension RecommendViewController{ override func loadData() { // 0.给父类中的ViewModel进行赋值 baseVM = recommendVM // 1.请求推荐数据 recommendVM.requestData { // 1.展示推荐数据 self.collectionView.reloadData() // 2.将数据传递给GameView var groups = self.recommendVM.anchorGroups // 2.1.移除前两组数据 groups.removeFirst() groups.removeFirst() // 2.2.添加更多组 let moreGroup = AnchorGroup() moreGroup.tag_name = "更多" groups.append(moreGroup) self.gameView.groups = groups // 3.数据请求完成 self.loadDataFinished() } // 2.请求轮播数据 recommendVM.requestCycleData { self.cycleView.cycleModels = self.recommendVM.cycleModels } } } // MARK: - UICollectionViewDelegateFlowLayout extension RecommendViewController : UICollectionViewDelegateFlowLayout{ override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == 1 { // 1.取出PrettyCell let prettyCell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPretyCell // 2.设置数据 prettyCell.anchor = recommendVM.anchorGroups[indexPath.section].anchors[indexPath.item] return prettyCell } else { return super.collectionView(collectionView, cellForItemAt: indexPath) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kNormalItemW, height: kPrettyItemH) } return CGSize(width: kNormalItemW, height: kNormalItemH) } }
mit
82f1e52a3b7150ae5a5da865129e3952
30.779817
160
0.626443
5.560193
false
false
false
false
CoderZZF/DYZB
DYZB/DYZB/Classes/Main/Controller/CustomNavigationController.swift
1
1774
// // CustomNavigationController.swift // DYZB // // Created by zhangzhifu on 2017/3/20. // Copyright © 2017年 seemygo. All rights reserved. // import UIKit class CustomNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() // 1. 获取系统的pop手势 guard let systemGes = interactivePopGestureRecognizer else { return } // 2. 获取手势添加到的View中 guard let gesView = systemGes.view else { return } // 3. 获取target/action // 3.1 利用运行时机制查看所有的属性名称 /* var count : UInt32 = 0 let ivars = class_copyIvarList(UIGestureRecognizer.self, &count)! for i in 0..<count { let ivar = ivars[Int(i)] let name = ivar_getName(ivar) print(String(cString: name!)) } */ let targets = systemGes.value(forKey: "_targets") as? [NSObject] guard let targetObject = targets?.first else { return } // print(targetObject) // 3.2 取出target guard let target = targetObject.value(forKey: "target") else { return } // 3.3 取出action let action = Selector(("handleNavigationTransition:")) // 4. 创建自己的手势 let panGes = UIPanGestureRecognizer() gesView.addGestureRecognizer(panGes) panGes.addTarget(target, action: action) } override func pushViewController(_ viewController: UIViewController, animated: Bool) { // 1. 隐藏要push的控制器的tabBar viewController.hidesBottomBarWhenPushed = true super.pushViewController(viewController, animated: animated) } }
apache-2.0
d30e476191f2a99bb5ceedbb81d788fa
29.272727
90
0.607207
4.663866
false
false
false
false
practicalswift/swift
test/Index/index_keypaths.swift
18
741
// RUN: %target-swift-ide-test -print-indexed-symbols -source-filename %s | %FileCheck %s // REQUIRES: objc_interop struct MyStruct { struct Inner { let myProp = 1 } } class MyClass { class Inner { @objc var myProp = 1 } } let a = \MyStruct.Inner.myProp // CHECK: [[@LINE-1]]:25 | {{.*}} | myProp // CHECK: [[@LINE-2]]:10 | {{.*}} | MyStruct // CHECK: [[@LINE-3]]:19 | {{.*}} | Inner let b: KeyPath<MyStruct.Inner, Int> = \.myProp // CHECK: [[@LINE-1]]:41 | {{.*}} | myProp let c = \MyClass.Inner.myProp // CHECK: [[@LINE-1]]:24 | {{.*}} | myProp // CHECK: [[@LINE-2]]:10 | {{.*}} | MyClass // CHECK: [[@LINE-3]]:18 | {{.*}} | Inner let d: KeyPath<MyClass.Inner, Int> = \.myProp // CHECK: [[@LINE-1]]:40 | {{.*}} | myProp
apache-2.0
818ece243ced082007a0014775e03227
26.444444
89
0.553306
3
false
false
false
false
josephkhawly/CalendarView
CalendarViewDemo/CalendarViewDemo/ViewController.swift
1
705
// // ViewController.swift // CalendarViewDemo // // Created by Nate Armstrong on 5/7/15. // Copyright (c) 2015 Nate Armstrong. All rights reserved. // import UIKit import CalendarView import SwiftMoment class ViewController: UIViewController { @IBOutlet weak var calendar: CalendarView! var date: Moment! { didSet { title = date.format(dateFormat: "MMMM d, yyyy") } } override func viewDidLoad() { super.viewDidLoad() date = moment() calendar.delegate = self } } extension ViewController: CalendarViewDelegate { func calendarDidSelectDate(date: Moment) { self.date = date } func calendarDidPageToDate(date: Moment) { self.date = date } }
mit
ab66806e904c951ad0004ccbe2610b19
16.195122
59
0.683688
3.960674
false
false
false
false
fitpay/fitpay-ios-sdk
FitpaySDK/Rest/Models/ResourceLink.swift
1
617
import Foundation open class ResourceLink: CustomStringConvertible { open var target: String? open var href: String? open var description: String { return "\(ResourceLink.self)(\(target ?? "target nil"):\(href ?? "href nil"))" } // MARK: - Lifecycle init() { } init(target: String, href: String?) { self.target = target self.href = href } } extension ResourceLink: Equatable { public static func == (lhs: ResourceLink, rhs: ResourceLink) -> Bool { return lhs.target == rhs.target && lhs.href == rhs.href } }
mit
5e9b4087616a94f23cb0c50c8a57deba
21.035714
86
0.578606
4.255172
false
false
false
false
teambition/SwipeableTableViewCell
SwipeableTableViewCellExample/StylesExampleViewController.swift
1
9892
// // StylesExampleViewController.swift // SwipeableTableViewCellExample // // Created by 洪鑫 on 15/12/15. // Copyright © 2015年 Teambition. All rights reserved. // import UIKit import SwipeableTableViewCell let kCellID = "SwipeableTableViewCell" let kCustomCellID = "CustomSwipeableTableViewCell" class StylesExampleViewController: UITableViewController, SwipeableTableViewCellDelegate { // MARK: - View life cycle override func viewDidLoad() { super.viewDidLoad() setupUI() } // MARK: - Helper fileprivate func setupUI() { navigationItem.title = "Styles" tableView.separatorColor = UIColor(white: 0.1, alpha: 0.1) } fileprivate func showAlert(_ message: String, dismissHandler: @escaping () -> ()) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) let cancelAction = UIAlertAction(title: "OK", style: .cancel) { _ in dismissHandler() } alert.addAction(cancelAction) present(alert, animated: true, completion: nil) } // MARK: - TableView data source and delegate override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 70 } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 75 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row % 7 == 5 { let cell = tableView.dequeueReusableCell(withIdentifier: kCustomCellID, for: indexPath) as! SwipeableTableViewCell cell.accessoryType = accessoryTypeForCellAtIndexPath(indexPath) cell.actions = actionsForCell(cell, indexPath: indexPath) return cell } else { var cell = tableView.dequeueReusableCell(withIdentifier: kCellID) as? SwipeableTableViewCell if cell == nil { cell = SwipeableTableViewCell(style: .default, reuseIdentifier: kCellID) } cell!.delegate = self if indexPath.row % 7 == 1 { let customAccessory = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) customAccessory.textAlignment = .center customAccessory.text = "❤️" customAccessory.backgroundColor = .clear cell!.accessoryView = customAccessory } else { cell!.accessoryView = nil cell!.accessoryType = accessoryTypeForCellAtIndexPath(indexPath) } cell!.actions = actionsForCell(cell!, indexPath: indexPath) if indexPath.row % 7 == 6 { cell!.textLabel?.text = "Cell \(indexPath.row) - No Swipe Action" } else { cell!.textLabel?.text = "Cell \(indexPath.row)" } cell!.textLabel?.font = .systemFont(ofSize: 18) return cell! } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let message = indexPath.row % 7 == 5 ? "Did select custom cell" : "Did select cell \(indexPath.row)" showAlert(message) { } } fileprivate func accessoryTypeForCellAtIndexPath(_ indexPath: IndexPath) -> UITableViewCell.AccessoryType { switch indexPath.row % 7 { case 0: return .none case 1: return .none case 2, 5: return .disclosureIndicator case 3: return .detailDisclosureButton case 4: return .checkmark default: return .none } } fileprivate func actionsForCell(_ cell: SwipeableTableViewCell, indexPath: IndexPath) -> [SwipeableCellAction]? { switch indexPath.row % 7 { case 0, 5: let delete = NSAttributedString(string: "删除", attributes: [.foregroundColor: UIColor.white]) var deleteAction = SwipeableCellAction(title: delete, image: nil, backgroundColor: .red) { let message = indexPath.row % 7 == 5 ? "Did click “\(delete.string)” on custom cell" : "Did click “\(delete.string)” on cell \(indexPath.row)" self.showAlert(message, dismissHandler: { cell.hideActions(animated: true) }) } let more = NSAttributedString(string: "更多", attributes: [.foregroundColor: UIColor.white]) var moreAction = SwipeableCellAction(title: more, image: nil, backgroundColor: .lightGray) { let message = indexPath.row % 7 == 5 ? "Did click “\(more.string)” on custom cell" : "Did click “\(more.string)” on cell \(indexPath.row)" self.showAlert(message, dismissHandler: { cell.hideActions(animated: true) }) } moreAction.width = 100 deleteAction.width = 100 return [deleteAction, moreAction] case 1: var deleteAction = SwipeableCellAction(title: NSAttributedString(string: "Delete"), image: nil, backgroundColor: .red) { let message = "Did click “Delete” at cell \(indexPath.row)" self.showAlert(message, dismissHandler: { cell.hideActions(animated: true) }) } var moreAction = SwipeableCellAction(title: NSAttributedString(string: "More"), image: nil, backgroundColor: .lightGray) { let message = "Did click “More” at cell \(indexPath.row)" self.showAlert(message, dismissHandler: { cell.hideActions(animated: true) }) } moreAction.width = 100 deleteAction.width = 100 return [deleteAction, moreAction] case 2: let delete = NSAttributedString(string: "删除", attributes: [.foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 15)]) var deleteAction = SwipeableCellAction(title: delete, image: UIImage(named: "delete-icon"), backgroundColor: UIColor(red: 255 / 255, green: 90 / 255, blue: 29 / 255, alpha: 1)) { let message = "Did click “\(delete.string)” at cell \(indexPath.row)" self.showAlert(message, dismissHandler: { cell.hideActions(animated: true) }) } let later = NSAttributedString(string: "稍后处理", attributes: [.foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 15)]) var laterAction = SwipeableCellAction(title: later, image: UIImage(named: "later-icon"), backgroundColor: UIColor(red: 3 / 255, green: 169 / 255, blue: 244 / 255, alpha: 1)) { let message = "Did click “\(later.string)” at cell \(indexPath.row)" self.showAlert(message, dismissHandler: { cell.hideActions(animated: true) }) } deleteAction.width = 100 deleteAction.verticalSpace = 6 laterAction.width = 100 laterAction.verticalSpace = 6 return [deleteAction, laterAction] case 3: let crossAction = SwipeableCellAction(title: nil, image: UIImage(named: "cross-icon"), backgroundColor: UIColor(red: 18 / 255, green: 191 / 255, blue: 41 / 255, alpha: 1)) { let message = "Did click “Cross” at cell \(indexPath.row)" self.showAlert(message, dismissHandler: { cell.hideActions(animated: true) }) } let clockAction = SwipeableCellAction(title: nil, image: UIImage(named: "clock-icon"), backgroundColor: UIColor(red: 255 / 255, green: 255 / 255, blue: 89 / 255, alpha: 1)) { let message = "Did click “Clock” at cell \(indexPath.row)" self.showAlert(message, dismissHandler: { cell.hideActions(animated: true) }) } let checkAction = SwipeableCellAction(title: nil, image: UIImage(named: "check-icon"), backgroundColor: UIColor(red: 255 / 255, green: 59 / 255, blue: 48 / 255, alpha: 1)) { let message = "Did click “Check” at cell \(indexPath.row)" self.showAlert(message, dismissHandler: { cell.hideActions(animated: true) }) } return [crossAction, clockAction, checkAction] case 4: let favorite = NSAttributedString(string: "收藏", attributes: [.foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 16)]) var favoriteAction = SwipeableCellAction(title: favorite, image: nil, backgroundColor: UIColor(red: 3 / 255, green: 169 / 255, blue: 244 / 255, alpha: 1)) { let message = "Did click “\(favorite.string)” at cell \(indexPath.row)" self.showAlert(message, dismissHandler: { cell.hideActions(animated: true) }) } favoriteAction.width = 120 return [favoriteAction] default: return nil } } // MARK: - SwipeableTableViewCell delegate func swipeableCell(_ cell: SwipeableTableViewCell, isScrollingToState state: SwipeableCellState) { let cellState = state == .closed ? "closing" : "opening" let cellName = (cell.textLabel?.text)! print("“\(cellName)” is \(cellState)...") } func swipeableCellDidEndScroll(_ cell: SwipeableTableViewCell) { let cellName = (cell.textLabel?.text)! print("“\(cellName)” did end scroll!") } }
mit
2c417a9c74404e00d5eccdf9716d854a
44.586047
191
0.592184
4.883408
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/Sensors/BluetoothSensor.swift
1
2971
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import CoreBluetooth import Foundation /// A sensor that fetches data from any BLE device with a corresponding implementation /// of BLESensorInterface. class BluetoothSensor: Sensor, BLEServiceScannerDelegate { var peripheralInterface: BLEPeripheralInterface? let sensorInterafce: BLESensorInterface let serviceScanner = BLEServiceScanner() private var currentValue: Double? /// Designated initializer. /// /// - Parameters: /// - sensorInterface: The sensor interface. /// - sensorTimer: The sensor timer to use for this sensor. init(sensorInterface: BLESensorInterface, sensorTimer: SensorTimer) { self.sensorInterafce = sensorInterface let animatingIconView = RelativeScaleAnimationView(iconName: sensorInterface.animatingIconName) super.init(sensorId: sensorInterface.identifier, name: sensorInterface.name, textDescription: sensorInterface.textDescription, iconName: sensorInterface.iconName, animatingIconView: animatingIconView, unitDescription: sensorInterface.unitDescription, learnMore: sensorInterafce.learnMoreInformation, sensorTimer: sensorTimer) displaysLoadingState = true // There is a delay in receiving bluetooth state. Optimistically assume it is supported. isSupported = true } override func start() { state = .loading sensorInterafce.connect { (success) in guard success else { self.state = .failed(.unavailableHardware) return } self.state = .ready self.sensorInterafce.startObserving({ [weak self] (dataPoint) in self?.currentValue = dataPoint.y }) } } override func retry() { start() } override func pause() { sensorInterafce.stopObserving() state = .paused } override func callListenerBlocksWithData(atMilliseconds milliseconds: Int64) { guard let currentValue = currentValue else { return } callListenerBlocksWithDataPoint(DataPoint(x: milliseconds, y: currentValue)) } // MARK: - BLEServiceScannerDelegate func serviceScannerDiscoveredNewPeripherals(_ serviceScanner: BLEServiceScanner) {} func serviceScannerBluetoothAvailabilityChanged(_ serviceScanner: BLEServiceScanner) { isSupported = serviceScanner.isBluetoothAvailable } }
apache-2.0
cea5e6e2c49eed7a5c070e1a44da6fdb
32.011111
99
0.720969
4.68612
false
false
false
false
y-hryk/MVVM_Demo
Carthage/Checkouts/RxSwift/RxExample/Extensions/CLLocationManager+Rx.swift
2
7521
// // CLLocationManager+Rx.swift // RxCocoa // // Created by Carlos García on 8/7/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import CoreLocation #if !RX_NO_MODULE import RxSwift import RxCocoa #endif extension Reactive where Base: CLLocationManager { /** Reactive wrapper for `delegate`. For more information take a look at `DelegateProxyType` protocol documentation. */ public var delegate: DelegateProxy { return RxCLLocationManagerDelegateProxy.proxyForObject(base) } // MARK: Responding to Location Events /** Reactive wrapper for `delegate` message. */ public var didUpdateLocations: Observable<[CLLocation]> { return delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didUpdateLocations:))) .map { a in return try castOrThrow([CLLocation].self, a[1]) } } /** Reactive wrapper for `delegate` message. */ public var didFailWithError: Observable<NSError> { return delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didFailWithError:))) .map { a in return try castOrThrow(NSError.self, a[1]) } } #if os(iOS) || os(OSX) /** Reactive wrapper for `delegate` message. */ public var didFinishDeferredUpdatesWithError: Observable<NSError?> { return delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didFinishDeferredUpdatesWithError:))) .map { a in return try castOptionalOrThrow(NSError.self, a[1]) } } #endif #if os(iOS) // MARK: Pausing Location Updates /** Reactive wrapper for `delegate` message. */ public var didPauseLocationUpdates: Observable<Void> { return delegate.observe(#selector(CLLocationManagerDelegate.locationManagerDidPauseLocationUpdates(_:))) .map { _ in return () } } /** Reactive wrapper for `delegate` message. */ public var didResumeLocationUpdates: Observable<Void> { return delegate.observe( #selector(CLLocationManagerDelegate.locationManagerDidResumeLocationUpdates(_:))) .map { _ in return () } } // MARK: Responding to Heading Events /** Reactive wrapper for `delegate` message. */ public var didUpdateHeading: Observable<CLHeading> { return delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didUpdateHeading:))) .map { a in return try castOrThrow(CLHeading.self, a[1]) } } // MARK: Responding to Region Events /** Reactive wrapper for `delegate` message. */ public var didEnterRegion: Observable<CLRegion> { return delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didEnterRegion:))) .map { a in return try castOrThrow(CLRegion.self, a[1]) } } /** Reactive wrapper for `delegate` message. */ public var didExitRegion: Observable<CLRegion> { return delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didExitRegion:))) .map { a in return try castOrThrow(CLRegion.self, a[1]) } } #endif #if os(iOS) || os(OSX) /** Reactive wrapper for `delegate` message. */ @available(OSX 10.10, *) public var didDetermineStateForRegion: Observable<(state: CLRegionState, region: CLRegion)> { return delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didDetermineState:for:))) .map { a in let stateNumber = try castOrThrow(NSNumber.self, a[1]) let state = CLRegionState(rawValue: stateNumber.intValue) ?? CLRegionState.unknown let region = try castOrThrow(CLRegion.self, a[2]) return (state: state, region: region) } } /** Reactive wrapper for `delegate` message. */ public var monitoringDidFailForRegionWithError: Observable<(region: CLRegion?, error: NSError)> { return delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:monitoringDidFailFor:withError:))) .map { a in let region = try castOptionalOrThrow(CLRegion.self, a[1]) let error = try castOrThrow(NSError.self, a[2]) return (region: region, error: error) } } /** Reactive wrapper for `delegate` message. */ public var didStartMonitoringForRegion: Observable<CLRegion> { return delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didStartMonitoringFor:))) .map { a in return try castOrThrow(CLRegion.self, a[1]) } } #endif #if os(iOS) // MARK: Responding to Ranging Events /** Reactive wrapper for `delegate` message. */ public var didRangeBeaconsInRegion: Observable<(beacons: [CLBeacon], region: CLBeaconRegion)> { return delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didRangeBeacons:in:))) .map { a in let beacons = try castOrThrow([CLBeacon].self, a[1]) let region = try castOrThrow(CLBeaconRegion.self, a[2]) return (beacons: beacons, region: region) } } /** Reactive wrapper for `delegate` message. */ public var rangingBeaconsDidFailForRegionWithError: Observable<(region: CLBeaconRegion, error: NSError)> { return delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:rangingBeaconsDidFailFor:withError:))) .map { a in let region = try castOrThrow(CLBeaconRegion.self, a[1]) let error = try castOrThrow(NSError.self, a[2]) return (region: region, error: error) } } // MARK: Responding to Visit Events /** Reactive wrapper for `delegate` message. */ @available(iOS 8.0, *) public var didVisit: Observable<CLVisit> { return delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didVisit:))) .map { a in return try castOrThrow(CLVisit.self, a[1]) } } #endif // MARK: Responding to Authorization Changes /** Reactive wrapper for `delegate` message. */ public var didChangeAuthorizationStatus: Observable<CLAuthorizationStatus> { return delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didChangeAuthorization:))) .map { a in let number = try castOrThrow(NSNumber.self, a[1]) return CLAuthorizationStatus(rawValue: Int32(number.intValue)) ?? .notDetermined } } } fileprivate func castOrThrow<T>(_ resultType: T.Type, _ object: AnyObject) throws -> T { guard let returnValue = object as? T else { throw RxCocoaError.castingError(object: object, targetType: resultType) } return returnValue } fileprivate func castOptionalOrThrow<T>(_ resultType: T.Type, _ object: AnyObject) throws -> T? { if NSNull().isEqual(object) { return nil } guard let returnValue = object as? T else { throw RxCocoaError.castingError(object: object, targetType: resultType) } return returnValue }
mit
9eed4403d1eec785759feec155cf9186
30.460251
124
0.629472
5.142955
false
false
false
false
SteveBarnegren/SwiftChess
SwiftChess/Source/ASCIIBoard.swift
1
5226
// // File.swift // SwiftChess // // Created by Steve Barnegren on 08/10/2016. // Copyright © 2016 Steve Barnegren. All rights reserved. // import Foundation func transformASCIIBoardInput(_ input: String) -> String { let boardArt = input.replacingOccurrences(of: " ", with: "") var transformedArt = String() for y in (0...7).reversed() { for x in 0...7 { let index = y*8 + x transformedArt.append(boardArt[boardArt.index(boardArt.startIndex, offsetBy: index)]) } } return transformedArt } public struct ASCIIBoard { let artString: String var stringContainsColors: Bool! public init(pieces artString: String) { var artString = artString // Transform artString = transformASCIIBoardInput(artString) // Check string format #if swift(>=3.2) assert(artString.count == 64, "ASCII board art must be 128 characters long") #else assert(artString.characters.count == 64, "ASCII board art must be 128 characters long") #endif self.artString = artString self.stringContainsColors = false } public init(colors artString: String) { self.init(pieces: artString) self.stringContainsColors = true } public var board: Board { var boardArt = artString // We only care about colours, not piece types, so just make pawns if stringContainsColors == true { boardArt = boardArt.replacingOccurrences(of: "B", with: "p") boardArt = boardArt.replacingOccurrences(of: "W", with: "P") } var board = Board(state: .empty) // Clear all pieces on the board BoardLocation.all.forEach { board.removePiece(at: $0) } // Setup pieces from ascii art (0..<64).forEach { #if swift(>=3.2) let character = boardArt[boardArt.index(boardArt.startIndex, offsetBy: $0)] #else let character = boardArt[boardArt.characters.index(boardArt.startIndex, offsetBy: $0)] #endif if let piece = piece(from: character) { board.setPiece(piece, at: BoardLocation(index: $0)) } } return board } func piece(from character: Character) -> Piece? { var piece: Piece? switch character { case "R": piece = Piece(type: .rook, color: .white) case "K": piece = Piece(type: .knight, color: .white) case "B": piece = Piece(type: .bishop, color: .white) case "Q": piece = Piece(type: .queen, color: .white) case "G": piece = Piece(type: .king, color: .white) case "P": piece = Piece(type: .pawn, color: .white) case "r": piece = Piece(type: .rook, color: .black) case "k": piece = Piece(type: .knight, color: .black) case "b": piece = Piece(type: .bishop, color: .black) case "q": piece = Piece(type: .queen, color: .black) case "g": piece = Piece(type: .king, color: .black) case "p": piece = Piece(type: .pawn, color: .black) default: piece = nil } return piece } public func indexOfCharacter(_ character: Character) -> Int { var index: Int? #if swift(>=3.2) if let idx = artString.firstIndex(of: character) { index = artString.distance(from: artString.startIndex, to: idx) } #else if let idx = artString.characters.index(of: character) { index = artString.characters.distance(from: artString.startIndex, to: idx) } #endif assert(index != nil, "Unable to find index of character: \(character)") return index! } public func locationOfCharacter(_ character: Character) -> BoardLocation { let index = indexOfCharacter(character) return BoardLocation(index: index) } public func indexesWithCharacter(_ character: Character) -> [Int] { var indexes = [Int]() (0..<64).forEach { #if swift(>=3.2) let aCharacter = artString[artString.index(artString.startIndex, offsetBy: $0)] #else let aCharacter = artString[artString.characters.index(artString.startIndex, offsetBy: $0)] #endif if character == aCharacter { indexes.append($0) } } return indexes } public func locationsWithCharacter(_ character: Character) -> [BoardLocation] { let indexes = indexesWithCharacter(character) var locations = [BoardLocation]() indexes.forEach { let location = BoardLocation(index: $0) locations.append(location) } return locations } }
mit
402748b1abd7feab077e2ef89c39b1a4
27.551913
102
0.535502
4.420474
false
false
false
false
kotalab/NotificationBarSample
NotificationBarSample/TSViewController.swift
1
2157
// // TSViewController.swift // NotificationBarSample // // Created by kotala tetsuya on 2015/11/05. // Copyright © 2015年 kotalab. All rights reserved. // import UIKit import TSMessages // https://github.com/KrauseFx/TSMessages class TSViewController: UIViewController { @IBOutlet weak var notificationType: UISegmentedControl! @IBOutlet weak var notificationPosition: UISegmentedControl! @IBOutlet weak var durationLabel: UILabel! @IBOutlet weak var titleText: UITextField! @IBOutlet weak var subtitleText: UITextField! @IBOutlet weak var durationSlider: UISlider! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.navigationItem.title = "TSMessage" durationLabel.text = "Duration: \(durationSlider.value)" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension TSViewController { @IBAction func slideDuration(sender: AnyObject) { guard let slider = sender as? UISlider else { return } durationLabel.text = "Duration: \(slider.value)" } @IBAction func pushNotificationButton(sender: AnyObject) { let type = TSMessageNotificationType(rawValue: notificationType.selectedSegmentIndex) ?? .Message let position = TSMessageNotificationPosition(rawValue: notificationPosition.selectedSegmentIndex) ?? .Top TSMessage.showNotificationInViewController(self.navigationController, title: titleText.text, subtitle: subtitleText.text, image: nil, type: type, duration: Double(durationSlider.value), callback: nil, buttonTitle: nil, buttonCallback: nil, atPosition: position, canBeDismissedByUser: true) } } extension TSViewController : UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
f794af1499c95703aa343f836bdc5571
29.785714
113
0.671773
5.292383
false
false
false
false
volendavidov/NagBar
NagBar/CheckMKHTTPClient.swift
1
5514
// // CheckMKHTTPClient.swift // NagBar // // Created by Volen Davidov on 03.07.16. // Copyright © 2016 Volen Davidov. All rights reserved. // import Foundation import PromiseKit class CheckMKHTTPClient : MonitoringProcessorBase, HTTPClient { func get(_ url: String) -> Promise<Data> { return Promise{ seal in var promise: Promise<Void> = Promise<Void>.value(Void()) promise = promise .then { _ -> Promise<Bool> in // check if Check_MK is set to use basic auth or cookie auth return self.checkBasicAuth(self.monitoringInstance!.url) } .then { basicAuth -> Promise<Bool> in // if Check_MK is not using basic auth, then we have to log in if !basicAuth { if ConnectionManager.sharedInstance.cookies.cookies!.isEmpty { // try to log in and return the result of the login return self.login(self.monitoringInstance!) } else { return Promise<Bool>.value(true) } } else { return Promise<Bool>.value(true) } } .then { shouldProceed -> Promise<Data> in // if the login was successfull, proceeed; // otherwise reject the Promise with error for wrong password if shouldProceed { return self.getBasicAuth(url, monitoringInstance: self.monitoringInstance!) } else { return Promise<Data>.value(Data()) } } .done { data -> Void in if data == Data() { seal.reject(NSError(domain: "", code: -999, userInfo: nil)) } else { seal.fulfill(data) } } } } private func login(_ monitoringInstance: MonitoringInstance) -> Promise<Bool> { return Promise{ seal in let params = ["_username": monitoringInstance.username, "_password": monitoringInstance.password, "_login": "1"] ConnectionManager.sharedInstance.manager!.request(monitoringInstance.url + "login.py", method: .post, parameters: params).response { response in if response.error != nil { seal.reject(response.error!) } var failed: Bool = true // if there are cookies, we check if one of them contains the domain for our monitoring instance for cookie in ConnectionManager.sharedInstance.cookies.cookies! { if monitoringInstance.url.range(of: cookie.domain) != nil { failed = false } } if failed == false { seal.fulfill(true) } else { seal.fulfill(false) } } } } private func checkBasicAuth(_ url: String) -> Promise<Bool> { return Promise{ seal in ConnectionManager.sharedInstance.manager!.request(url, method: .head).response { response in if response.error != nil { seal.reject(response.error!) } // if the response is 401, then we have basic auth // otherwise we have cookie auth enabled if response.response!.statusCode == 401 { seal.fulfill(true) } else { seal.fulfill(false) } } } } func getBasicAuth(_ url: String, monitoringInstance: MonitoringInstance) -> Promise<Data> { return Promise{ seal in ConnectionManager.sharedInstance.manager!.request(url).authenticate(user: monitoringInstance.username, password: monitoringInstance.password).response { response in // if the response is 401, then we have basic auth // otherwise we have cookie auth enabled if response.response!.statusCode == 401 { seal.fulfill(Data()) } if response.error == nil { seal.fulfill(response.data!) } else { seal.reject(response.error!) } } } } // TODO: complete this func checkConnection() -> Promise<Bool> { return Promise{ seal in ConnectionManager.sharedInstance.manager!.request(self.monitoringInstance!.url).authenticate(user: self.monitoringInstance!.username, password: self.monitoringInstance!.password).response { response in seal.fulfill(true) } } } // TODO: implement Check_MK commands func post(_ url: String, postData: Dictionary<String, String>) -> Promise<Data> { return Promise { seal in seal.fulfill(Data()) } } }
apache-2.0
83e49c94e64353f4bb34a794cc4200ea
36
213
0.481589
5.707039
false
false
false
false
NeilNie/Done-
Pods/Eureka/Source/Rows/CheckRow.swift
1
2595
// CheckRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: CheckCell public final class CheckCell: Cell<Bool>, CellType { required public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func update() { super.update() accessoryType = row.value == true ? .checkmark : .none editingAccessoryType = accessoryType selectionStyle = .default if row.isDisabled { tintAdjustmentMode = .dimmed selectionStyle = .none } else { tintAdjustmentMode = .automatic } } public override func setup() { super.setup() accessoryType = .checkmark editingAccessoryType = accessoryType } public override func didSelect() { row.value = row.value ?? false ? false : true row.deselect() row.updateCell() } } // MARK: CheckRow open class _CheckRow: Row<CheckCell> { required public init(tag: String?) { super.init(tag: tag) displayValueFor = nil } } ///// Boolean row that has a checkmark as accessoryType public final class CheckRow: _CheckRow, RowType { required public init(tag: String?) { super.init(tag: tag) } }
apache-2.0
c9586490a24a70783711267a2060b9c7
30.646341
86
0.682466
4.584806
false
false
false
false
BBRick/wp
wp/General/Extension/BaseMode+Extension.swift
3
802
// // BaseMode+Extension.swift // wp // // Created by 木柳 on 2017/1/6. // Copyright © 2017年 com.yundian. All rights reserved. // import Foundation extension NSObject{ func convertToTargetObject(_ object: AnyObject) { let r = Mirror.init(reflecting: object) for rChild in r.children { let value = valueFrom(self, key: rChild.label!) if !(value is NSNull) && value != nil { object.setValue(value, forKey: rChild.label!) } } } func valueFrom(_ object: Any, key: String) -> Any? { let mirror = Mirror.init(reflecting: object) for child in mirror.children { if child.label == key { return child.value } } return nil } }
apache-2.0
634a7b94352be7e44829377776f8da44
23.84375
61
0.545912
4.035533
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Widget Updaters/EventWidgetUpdaterTests.swift
1
2428
import EurofurenceApplication import EurofurenceModel import XCTest import XCTEurofurenceModel class EventWidgetUpdaterTests: XCTestCase { private var widgetService: CapturingWidgetService! private var refreshService: CapturingRefreshService! private var eventsService: FakeScheduleRepository! override func setUpWithError() throws { try super.setUpWithError() widgetService = CapturingWidgetService() refreshService = CapturingRefreshService() eventsService = FakeScheduleRepository() } private func setupUpdater() { _ = EventWidgetUpdater( widgetService: widgetService, refreshService: refreshService, eventsService: eventsService ) } func testRequestsUpdateWhenContentIsRefreshed() { setupUpdater() XCTAssertEqual(.unset, widgetService.reloadState, "No widgets should be refreshed when no events have occurred") refreshService.simulateRefreshBegan() assertReloadsEventsWidget(afterAction: { refreshService.simulateRefreshFinished() }) } func testRequestsUpdateWhenAnyEventTransitionsFromUnfavouriteToFavourite() { let event = FakeEvent.random event.unfavourite() eventsService.allEvents = [event] setupUpdater() assertReloadsEventsWidget(afterAction: { event.favourite() }) } func testRequestsUpdateWhenAnyEventTransitionsFromFavouriteToUnfavourite() { let event = FakeEvent.random event.favourite() eventsService.allEvents = [event] setupUpdater() assertReloadsEventsWidget(afterAction: { event.unfavourite() }) } private func assertReloadsEventsWidget(afterAction action: () -> Void, line: UInt = #line) { XCTAssertEqual( .unset, widgetService.reloadState, "No widgets should be refreshed before performing the action", line: line ) action() let expectedWidgetsToBeRefreshed = Set(["org.eurofurence.EventsWidget"]) XCTAssertEqual( .reloadRequested(widgets: expectedWidgetsToBeRefreshed), widgetService.reloadState, "Widgets should be refreshed after performing the action", line: line ) } }
mit
617677d88f32aca781015dec36b4cd01
30.128205
120
0.650329
5.767221
false
true
false
false
mofneko/swift-layout
swift-layout/sampleViewControllers/HorizontalEvenSpaceViewController.swift
1
2770
// // HorizontalEvenSpaceViewController.swift // swift-layout // // Created by grachro on 2014/09/07. // Copyright (c) 2014年 grachro. All rights reserved. // import UIKit class HorizontalEvenSpaceViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() coverSpace() nonCoverSpace() //戻るボタン addReturnBtn() } private func coverSpace() { let l1 = UILabel() l1.text = "l1" l1.backgroundColor = UIColor.redColor() Layout.addSubView(l1, superview: self.view) .top(30).fromSuperviewTop() .width(30) .height(50) let l2 = UILabel() l2.text = "l2" l2.backgroundColor = UIColor.greenColor() Layout.addSubView(l2, superview: self.view) .verticalCenterIsSame(l1) .widthIsSame(l1) .height(60) let l3 = UILabel() l3.text = "l3" l3.backgroundColor = UIColor.blueColor() Layout.addSubView(l3, superview: self.view) .verticalCenterIsSame(l1) .widthIsSame(l1) .height(60) Layout.horizontalEvenSpaceInCotainer(superview: self.view, views: [l1,l2,l3], coverSpace: true) } private func nonCoverSpace() { let l1 = UILabel() l1.text = "l1" l1.backgroundColor = UIColor.redColor() Layout.addSubView(l1, superview: self.view) .bottom(30).fromSuperviewBottom() .width(30) .height(50) let l2 = UILabel() l2.text = "l2" l2.backgroundColor = UIColor.greenColor() Layout.addSubView(l2, superview: self.view) .verticalCenterIsSame(l1) .widthIsSame(l1) .height(60) let l3 = UILabel() l3.text = "l3" l3.backgroundColor = UIColor.blueColor() Layout.addSubView(l3, superview: self.view) .verticalCenterIsSame(l1) .widthIsSame(l1) .height(60) Layout.horizontalEvenSpaceInCotainer(superview: self.view, views: [l1,l2,l3], coverSpace: false) } private func addReturnBtn() { let btn = Layout.createSystemTypeBtn("return") Layout.addSubView(btn, superview: self.view) .bottomIsSameSuperview() .rightIsSameSuperview() TouchBlocks.append(btn){ self.dismissViewControllerAnimated(true, completion:nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
d92eddeb781feb436504224995822a0c
26.039216
104
0.560551
4.085926
false
false
false
false
esttorhe/RxSwift
RxTests/RxSwiftTests/TestImplementations/Schedulers/VirtualTimeSchedulerBase.swift
2
4747
// // VirtualTimeSchedulerBase.swift // Rx // // Created by Krunoslav Zaher on 2/14/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift protocol ScheduledItemProtocol : Cancelable { var time: Int { get } func invoke() } class ScheduledItem<T> : ScheduledItemProtocol { typealias Action = (/*Scheduler<Int, Int>,*/ T) -> RxResult<Disposable> let action: Action let state: T let time: Int var disposed: Bool { get { return disposable.disposed } } var disposable = SingleAssignmentDisposable() init(action: Action, state: T, time: Int) { self.action = action self.state = state self.time = time } func invoke() { self.disposable.disposable = (action(/*scheduler,*/ state).get()) } func dispose() { self.disposable.dispose() } } class VirtualTimeSchedulerBase : Scheduler, CustomStringConvertible { typealias TimeInterval = Int typealias Time = Int var clock : Time var enabled : Bool var now: Time { get { return self.clock } } var description: String { get { return self.schedulerQueue.description } } private var schedulerQueue : [ScheduledItemProtocol] = [] init(initialClock: Time) { self.clock = initialClock self.enabled = false } func schedule<StateType>(state: StateType, action: (/*ImmediateScheduler,*/ StateType) -> RxResult<Disposable>) -> RxResult<Disposable> { return self.scheduleRelative(state, dueTime: 0) { /*s,*/ a in return action(/*s,*/ a) } } func scheduleRelative<StateType>(state: StateType, dueTime: Int, action: (/*Scheduler<Int, Int>,*/ StateType) -> RxResult<Disposable>) -> RxResult<Disposable> { return schedule(state, time: now + dueTime, action: action) } func schedule<StateType>(state: StateType, time: Int, action: (/*Scheduler<Int, Int>,*/ StateType) -> RxResult<Disposable>) -> RxResult<Disposable> { let compositeDisposable = CompositeDisposable() let scheduleTime: Int if time <= self.now { scheduleTime = self.now + 1 } else { scheduleTime = time } let item = ScheduledItem(action: action, state: state, time: scheduleTime) schedulerQueue.append(item) compositeDisposable.addDisposable(item) return success(compositeDisposable) } func schedulePeriodic<StateType>(state: StateType, startAfter: TimeInterval, period: TimeInterval, action: (StateType) -> StateType) -> RxResult<Disposable> { let compositeDisposable = CompositeDisposable() let scheduleTime: Int if startAfter <= 0 { scheduleTime = self.now + 1 } else { scheduleTime = self.now + startAfter } let item = ScheduledItem(action: { [unowned self] state in if compositeDisposable.disposed { return NopDisposableResult } let nextState = action(state) return self.schedulePeriodic(nextState, startAfter: period, period: period, action: action) }, state: state, time: scheduleTime) schedulerQueue.append(item) compositeDisposable.addDisposable(item) return success(compositeDisposable) } func start() { if !enabled { enabled = true repeat { if let next = getNext() { if next.disposed { continue } if next.time > self.now { self.clock = next.time } next.invoke() } else { enabled = false; } } while enabled } } func getNext() -> ScheduledItemProtocol? { var minDate = Time.max var minElement : ScheduledItemProtocol? = nil var minIndex = -1 var index = 0 for item in self.schedulerQueue { if item.time < minDate { minDate = item.time minElement = item minIndex = index } index++ } if minElement != nil { self.schedulerQueue.removeAtIndex(minIndex) } return minElement } }
mit
e81a860ca1b09f8e5f7517048d01bd4c
25.674157
164
0.53676
5.210757
false
false
false
false
scotlandyard/expocity
expocity/Model/Rooms/MRoomsItem.swift
1
1043
import Foundation class MRoomsItem { let roomId:String var roomName:String? weak var cell:VRoomsCell? init(roomId:String) { self.roomId = roomId DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.loadRoom() } } //MARK: private private func loadRoom() { let roomRerence:String = FDatabase.Parent.room.rawValue let path:String = String( format:"%@/%@", roomRerence, roomId) FMain.sharedInstance.database.listenOnce( path:path, modelType:FDatabaseModelRoom.self) { [weak self] (object:FDatabaseModelRoom) in self?.roomName = object.name self?.roomLoaded() } } private func roomLoaded() { DispatchQueue.main.async { [weak self] in self?.cell?.label.text = self?.roomName } } }
mit
4b89ae322cb9ed4540d4e6b2b71388a4
20.729167
71
0.518696
4.67713
false
false
false
false
Ahti/sauce
Sources/Sauce/SauceCollectionViewController.swift
1
2180
// // SauceCollectionViewController.swift // TabTool // // Created by Lukas Stabe on 12.04.16. // Copyright © 2016 2C. All rights reserved. // import UIKit open class SauceCollectionViewController: UICollectionViewController, DataSourceContainer { let dataSource: DataSource public init(collectionViewLayout layout: UICollectionViewLayout, dataSource: DataSource) { self.dataSource = dataSource super.init(collectionViewLayout: layout) dataSource.container = self } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func viewDidLoad() { super.viewDidLoad() guard let collectionView = self.collectionView else { fatalError("can't deal with no collection view in collection vc") } collectionView.dataSource = dataSource dataSource.registerReusableViewsWith(collectionView) } public func containingViewController() -> UIViewController? { return self } public var collectionViewIfLoaded: UICollectionView? { guard isViewLoaded else { return nil } return collectionView } public func dataSource(_ dataSource: DataSource, performed action: DataSourceAction) { guard isViewLoaded, let c = collectionView else { return } switch action { case .insert(let p): c.insertItems(at: p) case .delete(let p): c.deleteItems(at: p) case .reload(let p): c.reloadItems(at: p) case .move(from: let f, to: let t): c.moveItem(at: f, to: t) case .reloadSections(let s): let i = NSMutableIndexSet() s.forEach(i.add(_:)) c.reloadSections(i as IndexSet) case .insertSection(let i): c.insertSections(IndexSet(integer: i)) case .deleteSection(let i): c.deleteSections(IndexSet(integer: i)) case .moveSection(from: let f, to: let t): c.moveSection(f, toSection: t) case .batch(let changes): c.performBatchUpdates(changes, completion: nil) } } }
mit
378f3985aae0c3c6f42401514892283e
29.263889
94
0.634236
4.789011
false
false
false
false
liuCodeBoy/Ant
Ant/Ant/Main/NewsDetailVCViewController.swift
1
26756
// // NewsDetailVCViewController.swift // Ant // // Created by LiuXinQiang on 2017/7/19. // Copyright © 2017年 LiuXinQiang. All rights reserved. // import UIKit import WebKit import SDWebImage import SVProgressHUD class NewsDetailVCViewController: UIViewController,UITableViewDelegate, UITableViewDataSource, WKUIDelegate, WKNavigationDelegate,UITextFieldDelegate{ let NewsTopTitleCell = "NewsTopTitleCell" let newsDetailSharedCell = "newsDetailSharedCell" let hotCommandCell = "hotCommandCell" let hotNewsCell = "hotNewsCell" lazy var tableView = UITableView() lazy var scrollView = UIScrollView() lazy var webView = WKWebView() var webViewHeight : CGFloat = 0 var textField : UITextField? var detailView : UIView? var collectionBtn : UIButton? var modelView : UIView? var valueLabel : UILabel? var silderView : UISlider? var webFont = 100 //新闻url var url : NSURL? //接受新闻id值 var newsID = "" //newsmodel var newsModel : NewsDetailModel? //commentModel var commentModelArr = [NewsComment]() //hot_newsModel lazy var hot_newsModelArr = [NewsHotModel]() override func viewDidLoad() { super.viewDidLoad() loadNewsDetail() createTableView() //初始化底部发布视图 creatBottomView() //注册cell self.tableView.register(UINib.init(nibName: "NewsDetailSharedCell", bundle: nil), forCellReuseIdentifier: newsDetailSharedCell) self.tableView.register(UINib.init(nibName: "NewsHotCommondCell", bundle: nil), forCellReuseIdentifier: hotCommandCell) self.tableView.register(UINib.init(nibName: "HotNewsCell", bundle: nil), forCellReuseIdentifier: hotNewsCell) self.tableView.register(UINib.init(nibName: "NewsTopTitleCell", bundle: nil), forCellReuseIdentifier: NewsTopTitleCell) //注册微评论cell self.tableView.register(UINib.init(nibName: "NoCommandCell", bundle: nil), forCellReuseIdentifier: "NoCommandCell") //接受键盘输入通知 NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(notific:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) //接受键盘收回通知 NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHidden(note:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } //请求新闻信息 func loadNewsDetail(){ NetWorkTool.shareInstance.newsDet(self.newsID, finished: { (newsInfo, error) in if newsInfo?["code"] as? String == "200"{ let result = newsInfo?["result"] as? NSDictionary let newsDetail = result?["news_info"] as? NSDictionary let commentArray = result?["comment"] as? NSArray let hot_newsArray = result?["hot_news"] as? NSArray //创建newsDetail模型 let newsDetailModel = NewsDetailModel.mj_object(withKeyValues: newsDetail) self.newsModel = newsDetailModel //创建comment模型 for commentModel in commentArray!{ let commentModel = NewsComment.mj_object(withKeyValues: commentModel) self.commentModelArr.append(commentModel!) } //创建hot_news模型 for hotModel in hot_newsArray!{ let hot_newsModel = NewsHotModel.mj_object(withKeyValues: hotModel) self.hot_newsModelArr.append(hot_newsModel!) } self.tableView.reloadData() } }) } func collectionFunc(){ self.collectionBtn?.isSelected = !((self.collectionBtn?.isSelected)!) } func createTableView() -> () { self.webViewHeight = 0.0; self.createWebView(); self.tableView = UITableView.init(frame:CGRect.init(x: 0, y: 0, width: screenWidth, height: screenHeight - 44), style: .grouped) self.tableView.delegate = self; self.tableView.dataSource = self; self.tableView.showsVerticalScrollIndicator = false; self.tableView.showsHorizontalScrollIndicator = false; self.tableView.separatorStyle = .none self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "WebViewCell") self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "DefaultCell") self.view.addSubview(self.tableView) } override func viewWillAppear(_ animated: Bool) { self.tabBarController?.tabBar.isHidden = true } override func viewWillDisappear(_ animated: Bool) { self.tabBarController?.tabBar.isHidden = false } deinit { self.webView.scrollView.removeObserver(self, forKeyPath: "contentSize") NotificationCenter.default.removeObserver(self) } func createWebView() { let wkWebConfig = WKWebViewConfiguration() let wkUController = WKUserContentController() wkWebConfig.userContentController = wkUController // 自适应屏幕宽度js let jSString = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"; let wkUserScript = WKUserScript.init(source: jSString, injectionTime: .atDocumentEnd, forMainFrameOnly: true) // 添加js调用 wkUController.addUserScript(wkUserScript) self.webView = WKWebView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: 1), configuration: wkWebConfig) self.webView.backgroundColor = UIColor.clear self.webView.isOpaque = false; self.webView.isUserInteractionEnabled = false; self.webView.scrollView.bounces = false; self.webView.uiDelegate = self; self.webView.navigationDelegate = self; // self.webView.sizeToFit() self.webView.scrollView .addObserver(self, forKeyPath: "contentSize", options: .new, context: nil) let urlRequest = NSURLRequest(url: self.url! as URL) self.webView.load(urlRequest as URLRequest) self.scrollView = UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth , height: 1)) self.scrollView.addSubview(self.webView) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { self.webView.evaluateJavaScript("document.body.clientHeight") { (anyreult, error) in if (error == nil) { let height = anyreult as! CGFloat + 50 self.webViewHeight = height self.webView.frame = CGRect.init(x: 15, y: 0, width: screenWidth - 30, height: height) self.scrollView.frame = CGRect.init(x: 0, y: 0, width: screenWidth, height: height) self.scrollView.contentSize = CGSize.init(width: screenWidth, height: height) let indexArr = NSArray(array: [NSIndexPath.init(row: 0, section: 0)]) as? [IndexPath] self.tableView.reloadRows(at: indexArr!, with: .none) }else { SVProgressHUD.show() self.webView.reload() SVProgressHUD.showError(withStatus: "请求有误") } } } func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { SVProgressHUD.show() webView.reload() } } //MARK: - 键盘通知方法 extension NewsDetailVCViewController{ //键盘的弹起监控 func keyboardWillChangeFrame(notific: NSNotification) { let info = notific.userInfo let keyBoardBounds = (info?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let duration = (info?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue let deltaY = keyBoardBounds.size.height let animations:(() -> Void) = { //键盘的偏移量 self.detailView?.transform = CGAffineTransform(translationX: 0 , y: -((self.detailView?.frame.height)! + deltaY)) } if duration > 0 { let options = UIViewAnimationOptions(rawValue: UInt((info?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16)) UIView.animate(withDuration: duration, delay: 0, options:options, animations: animations, completion: nil) }else{ animations() } } //键盘的收起监控 func keyboardWillHidden(note: NSNotification) { let userInfo = note.userInfo! let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue let animations:(() -> Void) = { //键盘的偏移量 self.detailView!.transform = .identity } if duration > 0 { let options = UIViewAnimationOptions(rawValue: UInt((userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16)) UIView.animate(withDuration: duration, delay: 0, options:options, animations: animations, completion: nil) }else{ animations() } } } //MARK: - 底部初始化视图与功能 extension NewsDetailVCViewController { //初始化底部发布视图 func creatBottomView() { let bottomView = UIView.init(frame: CGRect.init(x: 0, y: screenHeight - 108 , width: screenWidth, height: 44)) bottomView.backgroundColor = UIColor.init(red: 240 / 255, green: 240 / 255, blue: 240 / 255, alpha: 1.0) //评论按钮 let writeCommentBtn = UIButton.init(frame: CGRect.init(x: 10, y: 7, width: screenWidth * 0.52, height: 30)) writeCommentBtn.addTarget(self, action: #selector(NewsDetailVCViewController.editMessage), for: .touchUpInside) writeCommentBtn.setTitle("发表评论", for: .normal) writeCommentBtn.backgroundColor = UIColor.white writeCommentBtn.setTitleColor(UIColor.lightGray, for: .normal) writeCommentBtn.contentMode = .left writeCommentBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13) bottomView.addSubview(writeCommentBtn) //评论数btn let commandBtn = UIButton.init(frame: CGRect.init(x: writeCommentBtn.frame.maxX + 10 , y: writeCommentBtn.frame.origin.y, width: screenWidth * 0.1, height: 30)) commandBtn.center.y = writeCommentBtn.center.y commandBtn.showBadgOnImage(imageStr: "icon_comment_red") commandBtn.setTitle("30", for: .normal) commandBtn.setTitleColor(UIColor.lightGray, for: .normal) commandBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14) commandBtn.addTarget(self, action: #selector(NewsDetailVCViewController.showAllComment), for: .touchUpInside) bottomView.addSubview(commandBtn) //收藏按钮 let collectionBtn = UIButton.init(frame: CGRect.init(x: commandBtn.frame.maxX + 30 , y: writeCommentBtn.frame.origin.y, width: screenWidth * 0.05, height: 20)) collectionBtn.center.y = writeCommentBtn.center.y collectionBtn.setImage(UIImage.init(named: "icon_collect_white_defalt"), for: .normal) collectionBtn.setImage(UIImage.init(named:"icon_collect_red_highlighted"), for: .selected) collectionBtn.setTitleColor(UIColor.lightGray, for: .normal) collectionBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14) collectionBtn.addTarget(self, action: #selector(NewsDetailVCViewController.collectionFunc), for: .touchUpInside) self.collectionBtn = collectionBtn bottomView.addSubview(self.collectionBtn!) //字体按钮 let fontBtn = UIButton.init(frame: CGRect.init(x: collectionBtn.frame.maxX + 30 , y: writeCommentBtn.frame.origin.y, width: screenWidth * 0.05, height: 20)) fontBtn.center.y = writeCommentBtn.center.y fontBtn.setImage(UIImage.init(named:"icon_fontsize"), for: .normal) fontBtn.setTitleColor(UIColor.lightGray, for: .normal) fontBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14) fontBtn.addTarget(self, action: #selector(NewsDetailVCViewController.addSliderView), for: .touchUpInside) bottomView.addSubview(fontBtn) self.view.addSubview(bottomView) } //定义编辑发送功能 func editMessage() { self.detailView = UIView.init(frame: CGRect.init(x: 0, y: screenHeight - 64, width: screenWidth, height: 180)) self.detailView?.backgroundColor = UIColor.init(red: 245 / 255, green: 245 / 255, blue: 245 / 255, alpha: 1.0) let detailScriptLable = UILabel.init(frame: CGRect.init(x: (screenWidth - 100) / 2 , y: 5, width: 100, height: 20)) detailScriptLable.text = "写评论" detailScriptLable.textAlignment = .center detailScriptLable.textColor = UIColor.lightGray detailScriptLable.font = UIFont.systemFont(ofSize: 15) detailView?.addSubview(detailScriptLable) //定义取消按钮 let cancelBtn = UIButton.init(frame: CGRect.init(x: 0 , y: 5, width: 100, height: 20)) cancelBtn.setTitle("取消", for: .normal) cancelBtn.setTitleColor(UIColor.lightGray, for: .normal) cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15) cancelBtn.addTarget(self, action: #selector(NewsDetailVCViewController.cancelCommandFunc), for: .touchUpInside) detailView?.addSubview(cancelBtn) //定义发送按钮 let sendBtn = UIButton.init(frame: CGRect.init(x: screenWidth - 100 , y: 5, width: 100, height: 20)) sendBtn.setTitle("发送", for: .normal) sendBtn.setTitleColor(UIColor.lightGray, for: .normal) sendBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15) sendBtn.addTarget(self, action: #selector(NewsDetailVCViewController.sendCommandFunc), for: .touchUpInside) detailView?.addSubview(sendBtn) let detailDescriptFiled = CustomTextField.init(frame: CGRect.init(x: 10, y: 30, width: screenWidth - 20 , height: 140), placeholder: "字数在150字以内", clear: true, leftView: nil, fontSize: 12) //创建取消按钮 detailDescriptFiled?.backgroundColor = UIColor.white detailDescriptFiled?.borderStyle = .none self.textField = detailDescriptFiled self.textField?.becomeFirstResponder() detailView?.addSubview(detailDescriptFiled!) self.view.addSubview(detailView!) } //发送评论方法 func sendCommandFunc() { self.textField?.resignFirstResponder() } //取消评论方法 func cancelCommandFunc() { self.textField?.resignFirstResponder() } //添加Slider func addSliderView() { let modelView = UIView.init(frame: CGRect.init(x: 0, y: screenHeight - 64, width: screenWidth, height: 200)) modelView.backgroundColor = UIColor.init(white: 0.9, alpha: 0.5) self.modelView = modelView let silderView = UISlider.init(frame: CGRect.init(x: 20, y: 90, width: screenWidth - 40, height: 20)) silderView.minimumValue = 100 silderView.maximumValue = 200 silderView.isContinuous = false silderView.minimumTrackTintColor = appdelgate?.theme silderView.setValue(Float((self.webFont)),animated:true) //添加当前值label self.valueLabel = UILabel.init(frame: CGRect.init(x: (screenWidth - 200) / 2, y: silderView.frame.maxY + 10 , width: 200, height: 40)) self.valueLabel?.textAlignment = .center self.valueLabel?.text = String(format: "设置字体倍数为百分之%.2fX", silderView.value) self.valueLabel?.font = UIFont.systemFont(ofSize: 13) self.valueLabel?.textColor = appdelgate?.theme self.modelView?.addSubview(self.valueLabel!) silderView.addTarget(self, action: #selector(sliderValueChanged(sender:)), for: .valueChanged) self.modelView?.addSubview(silderView) self.silderView = silderView UIView.animate(withDuration: 0.25, animations: { self.view.addSubview(self.modelView!) self.modelView!.transform = CGAffineTransform(translationX: 0 , y: -((self.modelView?.frame.height)!)) }) } // slider变动时改变label值 func sliderValueChanged(sender : UISlider) { let alterVC = UIAlertController.init(title: "确认修改", message: nil, preferredStyle: .alert) alterVC.addAction(UIAlertAction.init(title: "确认", style: .default, handler: { [weak self](action) in self?.webFont = Int(CGFloat(sender.value)) self?.modelView?.transform = .identity let str1 = "document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '\(Int(CGFloat(sender.value)))%'" self?.webView.evaluateJavaScript(str1, completionHandler: { [weak self](object, error) in }) self?.modelView?.removeFromSuperview() })) alterVC.addAction(UIAlertAction.init(title: "取消", style: .destructive, handler: {[weak self](action) in self?.modelView?.transform = .identity self?.modelView?.removeFromSuperview() })) self.present(alterVC, animated: true, completion: nil) } } //MARK: - tableView代理方法 extension NewsDetailVCViewController { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0{ return 3; }else if(section == 1 ){ let commentNum = self.commentModelArr.count != 0 ? self.commentModelArr.count : 1 return commentNum; }else { return self.hot_newsModelArr.count } } func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { switch section { case 1: return 50 case 2: return 50 default: return 0.001 } } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { switch section { case 1: return 70 default: return 0.001 } } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { //初始化热点评论 let recommendView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: 50)) recommendView.backgroundColor = UIColor.white let topBackView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: 15)) topBackView.backgroundColor = UIColor.init(red: 240 / 255, green: 240 / 255, blue: 240 / 255, alpha: 1.0) recommendView.addSubview(topBackView) let hotCommandImage = UIImageView.init(frame: CGRect.init(x: 10, y: 25, width: 70, height: 25)) hotCommandImage.image = UIImage.init(named: "img_title_hotreviews") recommendView.addSubview(hotCommandImage) //初始化热点新闻 let hotNewsView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: 50)) hotNewsView.backgroundColor = UIColor.white let topView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: 15)) topView.backgroundColor = UIColor.init(red: 240 / 255, green: 240 / 255, blue: 240 / 255, alpha: 1.0) hotNewsView.addSubview(topView) let hotBtn = UIButton.init(frame: CGRect.init(x: 10, y: 25, width: 100, height: 25)) hotBtn.setImage(UIImage.init(named: "img_fire"), for: .normal) hotBtn.setTitle("热点新闻", for: .normal) hotBtn.setTitleColor(UIColor.red, for: .normal) hotBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14) hotNewsView.addSubview(hotBtn) switch section { case 1: return recommendView case 2: return hotNewsView default: return nil } } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let recommendBtnView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: 70)) recommendBtnView.backgroundColor = UIColor.white let commandSearchBtn = UIButton.init(frame: CGRect.init(x: (screenWidth - 160) / 2, y: 25, width: 160, height: 30)) commandSearchBtn.setTitle("查看全部评论", for: .normal) commandSearchBtn.addTarget(self, action: #selector(NewsDetailVCViewController.showAllComment), for: .touchUpInside) commandSearchBtn.layer.borderWidth = 1 commandSearchBtn.layer.borderColor = UIColor.red.cgColor commandSearchBtn.titleLabel?.textAlignment = .center commandSearchBtn.setTitleColor(UIColor.red, for: .normal) recommendBtnView.addSubview(commandSearchBtn) switch section { case 1: return recommendBtnView default: return nil } } //弹出全部评论列表 func showAllComment() { let commentListVC = CommentListVC() commentListVC.title = "评论列表" self.navigationController?.pushViewController(commentListVC, animated: true) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0{ switch (indexPath.row) { case 0: return 80 case 1: return webViewHeight; case 2: return 300; default: return 0; } }else if(indexPath.section == 1 ){ guard self.commentModelArr.count != 0 else { return 800 } let height = self.commentModelArr[indexPath.row].height != nil ? self.commentModelArr[indexPath.row].height : 800 return height!; }else { return 100; } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell : UITableViewCell? if indexPath.section == 0{ switch indexPath.row { case 0: let topCell = (tableView.dequeueReusableCell(withIdentifier: "NewsTopTitleCell", for: indexPath) as? NewsTopTitleCell)! topCell.time.text = self.newsModel?.publish_time topCell.title.text = self.newsModel?.title topCell.source.text = self.newsModel?.source cell = topCell case 1: let webViewCell = tableView.dequeueReusableCell(withIdentifier: "WebViewCell", for: indexPath) webViewCell.contentView.addSubview(self.scrollView) cell = webViewCell case 2: let sharecell = tableView.dequeueReusableCell(withIdentifier: newsDetailSharedCell, for: indexPath) as? NewsDetailSharedCell let statement = self.newsModel?.statement != nil ? self.newsModel?.statement : "" sharecell?.statement.text = " \(String(describing: (statement)!))" let interest = self.newsModel?.interest != nil ? self.newsModel?.interest : 0 sharecell?.interestBtn.setTitle("\(interest!)人喜欢", for: .normal) cell = sharecell // } default: let defaultCell = tableView.dequeueReusableCell(withIdentifier: "DefaultCell", for: indexPath) defaultCell.textLabel?.text = "asdasdasdasdas" return defaultCell; } }else if(indexPath.section == 1 ){ if self.commentModelArr.count != 0{ let commmandCell = tableView.dequeueReusableCell(withIdentifier: hotCommandCell, for: indexPath) as? NewsHotCommondCell if let commentModel = self.commentModelArr[indexPath.row] as? NewsComment { if let picture = commentModel.user_info?.head_portrait{ if let imageURL = URL.init(string: picture) { commmandCell?.userPicImage.sd_setImage(with: imageURL as URL, placeholderImage: #imageLiteral(resourceName: "img_headportrait")) } } commmandCell?.areaLabel.text = commentModel.user_info?.area commmandCell?.nameLabel.text = commentModel.user_info?.name commmandCell?.timeLabel.text = commentModel.time commmandCell?.zanLabel.text = "\((commentModel.msg_id)!)" commmandCell?.commentLabel.text = commentModel.content } cell = commmandCell }else{ let deafultCommentCell = tableView.dequeueReusableCell(withIdentifier: "NoCommandCell", for: indexPath) as? NoCommandCell deafultCommentCell?.designTitle.text = "此新闻暂无评论" cell = deafultCommentCell } }else if(indexPath.section == 2){ let hotNewsCell = tableView.dequeueReusableCell(withIdentifier: "hotNewsCell", for: indexPath) as? HotNewsCell if let hotmodel = self.hot_newsModelArr[indexPath.row] as? NewsHotModel{ hotNewsCell?.hotNewsTitle.text = hotmodel.title hotNewsCell?.hotNewsTime.text = hotmodel.publish_time hotNewsCell?.hotNewsSource.setTitle("\((describing: hotmodel.source!))", for: .normal) hotNewsCell?.hotNewsPic.sd_setImage(with: URL.init(string: hotmodel.picture!), placeholderImage: UIImage.init(named: "moren")) cell = hotNewsCell } } cell?.selectionStyle = .none return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if(indexPath.section == 2){ let newsDetailVC = NewsDetailVCViewController() if let hotmodel = self.hot_newsModelArr[indexPath.row] as? NewsHotModel{ let url = NSURL.init(string: hotmodel.url!) newsDetailVC.newsID = "\(String(describing: hotmodel.id!))" newsDetailVC.url = url self.navigationController?.pushViewController(newsDetailVC, animated: true) } } } }
apache-2.0
903ae0ba4c06a5d48c70e66ac7795bf2
43.265203
215
0.638046
4.481019
false
false
false
false
acsanchezcu/LabelTranslator
LabelTranslator/LabelTranslator/Utils/Extension/UIImage+Extension.swift
1
2790
// // UIImage+Extension.swift // LabelTranslator // // Created by Sanchez Custodio, Abel (Cognizant) on 16/08/2017. // Copyright © 2017 Sanchez Custodio, Abel. All rights reserved. // import UIKit extension UIImage { func fixedOrientation() -> UIImage { if imageOrientation == .up { return self } var transform: CGAffineTransform = CGAffineTransform.identity switch imageOrientation { case .down, .downMirrored: transform = transform.translatedBy(x: size.width, y: size.height) transform = transform.rotated(by: CGFloat.pi) break case .left, .leftMirrored: transform = transform.translatedBy(x: size.width, y: 0) transform = transform.rotated(by: CGFloat.pi / 2.0) break case .right, .rightMirrored: transform = transform.translatedBy(x: 0, y: size.height) transform = transform.rotated(by: CGFloat.pi / -2.0) break case .up, .upMirrored: break } switch imageOrientation { case .upMirrored, .downMirrored: transform.translatedBy(x: size.width, y: 0) transform.scaledBy(x: -1, y: 1) break case .leftMirrored, .rightMirrored: transform.translatedBy(x: size.height, y: 0) transform.scaledBy(x: -1, y: 1) case .up, .down, .left, .right: break } let ctx: CGContext = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: self.cgImage!.bitsPerComponent, bytesPerRow: 0, space: self.cgImage!.colorSpace!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! ctx.concatenate(transform) switch imageOrientation { case .left, .leftMirrored, .right, .rightMirrored: ctx.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width)) default: ctx.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) break } return UIImage(cgImage: ctx.makeImage()!) } class func imageWithCVPixelBuffer(_ cvPixelBuffer: CVPixelBuffer?) -> UIImage? { guard let cvPixelBuffer = cvPixelBuffer else { return nil } let ciImage = CIImage(cvPixelBuffer: cvPixelBuffer).applyingOrientation(6) let ciContext = CIContext() guard let videoImage = ciContext.createCGImage(ciImage, from: CGRect(x: 0, y: 0, width: CVPixelBufferGetWidth(cvPixelBuffer), height: CVPixelBufferGetHeight(cvPixelBuffer))) else { return nil } return UIImage(cgImage: videoImage) } }
mit
e57a5c95bfd15f5e0614279e69487954
35.697368
257
0.601649
4.498387
false
false
false
false
eman6576/FoodTruckAPI
Tests/FoodTruckAPITests/FoodTruckAPITests.swift
1
6200
import XCTest @testable import FoodTruckAPI class FoodTruckAPITests: XCTestCase { static var allTests = [ ("testAddTruck", testAddAndGetTruck), ("testUpdateTruck", testUpdateTruck), ("testClearAll", testClearAll), ("testDeleteTruck", testDeleteTruck), ("testCountTrucks", testCountTrucks) ] var trucks: FoodTruck? override func setUp() { trucks = FoodTruck() super.setUp() } override func tearDown() { guard let trucks = trucks else { return } trucks.clearAll { (error) in guard error == nil else { return } } } // Add and get specific truck func testAddAndGetTruck() { guard let trucks = trucks else { XCTFail() return } let addExpectation = expectation(description: "Add truck item") // First add new truck trucks.addTruck(name: "testAdd", foodType: "testType", avgCost: 0, latitude: 0, longtitude: 0) { (addedTruck, error) in guard error == nil else { XCTFail() return } if let addedTruck = addedTruck { trucks.getTruck(docId: addedTruck.docId, completion: { (returnedTruck, error) in // Assert that the added truck equals the returned truck XCTAssertEqual(addedTruck, returnedTruck) addExpectation.fulfill() }) } } waitForExpectations(timeout: 5) { (error) in XCTAssertNil(error, "addTruck Timeout") } } func testUpdateTruck() { guard let trucks = trucks else { XCTFail() return } let updateExpectation = expectation(description: "Update truck item") trucks.addTruck(name: "testUpdate", foodType: "testUpdate", avgCost: 0, latitude: 0, longtitude: 0) { (addedTruck, error) in guard error == nil else { XCTFail() return } if let addedTruck = addedTruck { // Update the added truck trucks.updateTruck(docId: addedTruck.docId, name: "UpdatedTruck", foodType: nil, avgCost: nil, latitude: nil, longitude: nil, completion: { (updatedTruck, error) in guard error == nil else { XCTFail() return } if let updatedTruck = updatedTruck { // Fetch the truck from the DB trucks.getTruck(docId: addedTruck.docId, completion: { (fetchedTruck, error) in // Assert that the updated truck equals the fetched truck XCTAssertEqual(fetchedTruck, updatedTruck) updateExpectation.fulfill() }) } }) } } waitForExpectations(timeout: 5) { (error) in XCTAssertNil(error, "Uodate truck timeout") } } // Clear all documents func testClearAll() { guard let trucks = trucks else { XCTFail() return } let clearExpectation = expectation(description: "Clear all DB documents") trucks.addTruck(name: "testClearAll", foodType: "testClearAll", avgCost: 0, latitude: 0, longtitude: 0) { (addedTruck, error) in guard error == nil else { XCTFail() return } trucks.clearAll { (error) in } trucks.countTrucks { (count, error) in XCTAssertEqual(count, 0) // TODO: - countReviews clearExpectation.fulfill() } } waitForExpectations(timeout: 5) { (error) in XCTAssertNil(error, "clearAll timeout") } } // Delete truck func testDeleteTruck() { guard let trucks = trucks else { XCTFail() return } let deleteExpectation = expectation(description: "Delete a specific truck") // First add a new truck trucks.addTruck(name: "testDelete", foodType: "testDelete", avgCost: 0, latitude: 0, longtitude: 0) { (addedTruck, error) in guard error == nil else { XCTFail() return } if let addedTruck = addedTruck { // TODO: - Second add a review // Delete the truck trucks.deleteTruck(docId: addedTruck.docId, completion: { (error) in guard error == nil else { XCTFail() return } }) // Count trucks and reviews to assert that count == 0 trucks.countTrucks(completion: { (count, error) in XCTAssertEqual(count, 0) deleteExpectation.fulfill() }) } } waitForExpectations(timeout: 5) { (error) in XCTAssertNil(error, "Delete truck timeout") } } // Count of all trucks func testCountTrucks() { guard let trucks = trucks else { XCTFail() return } let countExpectation = expectation(description: "Test Truck Count") for _ in 0..<5 { trucks.addTruck(name: "testCount", foodType: "testCount", avgCost: 0, latitude: 0, longtitude: 0, completion: { (addedTruck, error) in guard error == nil else { XCTFail() return } }) } // Count should equal 5 trucks.countTrucks { (count, error) in guard error == nil else { XCTFail() return } XCTAssertEqual(count, 5) countExpectation.fulfill() } waitForExpectations(timeout: 5) { (error) in XCTAssertNil(error) } } }
mit
45cb3eb965545d1d826ef80481304b24
33.636872
180
0.499355
5.119736
false
true
false
false
1457792186/JWSwift
SwiftLearn/SwiftLearning/SwiftLearning/Learning/类/自定义类/类与协议/StudentGood.swift
1
1457
// // StudentGood.swift // JSwiftLearnMore // // Created by apple on 17/3/8. // Copyright © 2017年 BP. All rights reserved. // import UIKit //StudentGood继承于Student并且实现了Named协议 class StudentGood: Named { //以下皆为Named协议中内容 //注意从Named协议中并不知道name是存储属性还是计算属性,这里将其作为存储属性实现 var name:String //静态属性 static var className:String{ return "3·2班" } //协议中规定的构造方法,必须使用required关键字声明,除非类使用final修饰 required init(name:String){ self.name = name } //遵循showName方法 func showName() { print("name=\(name)") } //遵循showClassName方法 static func showClassName() { print("Class name is \"Person\"") } } //StudentGood继承于Student并且实现了Commented协议 class StudentBest: StudentGood,Commented{ var commentStu:String init(name:String, commentStu:String){ self.commentStu = commentStu super.init(name: name) } //遵循showName方法 func showComment() { print("comment=\(commentStu)") } //协议中规定的构造方法,必须使用required关键字声明,除非类使用final修饰 required init(name: String) { self.commentStu = "Good" super.init(name: name) } }
apache-2.0
3dba72cc6185af05574e7e94c4344d63
18.683333
49
0.622354
3.525373
false
false
false
false
bigbossstudio-dev/BBSInspector
Library/Classes/BBSInspectorCornerButton.swift
1
5271
// // BBSInspectorCornerButton.swift // BBSInspector // // Created by Cyril Chandelier on 05/03/15. // Copyright (c) 2015 Big Boss Studio. All rights reserved. // import Foundation import UIKit let BBSInspectorCornerButtonEdgeInsets = UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0) internal class BBSInspectorCornerButton: UIButton { /** Current button style */ private var style: BBSInspectorCornerButtonStyle = BBSInspectorCornerButtonStyle.Plus /** Line layers */ private var line1Layer: CAShapeLayer = CAShapeLayer() private var line2Layer: CAShapeLayer = CAShapeLayer() /** Dimension */ private var dimension: CGFloat { let width = CGRectGetWidth(self.bounds) - self.contentEdgeInsets.left - self.contentEdgeInsets.right let height = CGRectGetHeight(self.bounds) - self.contentEdgeInsets.top - self.contentEdgeInsets.bottom return min(width, height) } /** Center point of view */ private var pivot: CGPoint { return CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)) } // MARK: - Initializers override internal init(frame: CGRect) { super.init(frame: frame) setup() } required internal init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } // MARK: - Setup private func setup() { self.backgroundColor = UIColor.blackColor() self.clipsToBounds = true self.contentEdgeInsets = BBSInspectorCornerButtonEdgeInsets // Corner mask let mask = CAShapeLayer() mask.path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: UIRectCorner.TopLeft, cornerRadii: CGSizeMake(5.0, 0.0)).CGPath self.layer.mask = mask // Prepare lines layers for layer in [ line1Layer, line2Layer] { layer.fillColor = UIColor.clearColor().CGColor layer.strokeColor = UIColor.whiteColor().CGColor layer.anchorPoint = CGPointZero layer.lineWidth = 2.0 layer.lineJoin = kCALineJoinRound layer.lineCap = kCALineCapRound layer.contentsScale = self.layer.contentsScale layer.path = CGPathCreateMutable() self.layer.addSublayer(layer) } } // MARK: - Setters /** Update button style with or without animation - parameter style: A registered InspectorCornerButtonStyle - parameter animated: Wether or not the change should be animated */ internal func setStyle(style newStyle: BBSInspectorCornerButtonStyle, animated: Bool) { self.style = newStyle // Prepare paths var line1path: CGPathRef var line2path: CGPathRef switch style { case BBSInspectorCornerButtonStyle.Plus: line1path = self.createCenteredLineWithRadius(dimension / 2.0, angle: CGFloat(M_PI_2), offset: CGPointZero) line2path = self.createCenteredLineWithRadius(dimension / 2.0, angle: 0, offset: CGPointZero) case BBSInspectorCornerButtonStyle.Close: line1path = self.createCenteredLineWithRadius(dimension / 2.0, angle: -CGFloat(M_PI_4), offset: CGPointZero) line2path = self.createCenteredLineWithRadius(dimension / 2.0, angle: CGFloat(M_PI_4), offset: CGPointZero) } // Animate if needed if animated { let duration = 0.3 // Line 1 let line1Animation = CABasicAnimation(keyPath: "path") line1Animation.removedOnCompletion = false line1Animation.duration = duration line1Animation.fromValue = line1Layer.path line1Animation.toValue = line1path line1Animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) line1Layer.addAnimation(line1Animation, forKey: "animateLine1Path") // Line 2 let line2Animation = CABasicAnimation(keyPath: "path") line2Animation.removedOnCompletion = false line2Animation.duration = duration line2Animation.fromValue = line2Layer.path line2Animation.toValue = line2path line2Animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) line2Layer.addAnimation(line2Animation, forKey: "animateLine2Path") } line1Layer.path = line1path line2Layer.path = line2path } // MARK: - Path factory private func createCenteredLineWithRadius(radius: CGFloat, angle: CGFloat, offset: CGPoint) -> CGPathRef { let c = CGFloat(cosf(Float(angle))) let s = CGFloat(sinf(Float(angle))) let path = CGPathCreateMutable() let pivot = self.pivot CGPathMoveToPoint(path, nil, pivot.x + offset.x + radius * c, pivot.y + offset.y + radius * s) CGPathAddLineToPoint(path, nil, pivot.x + offset.x - radius * c, pivot.y + offset.y - radius * s) return path } } enum BBSInspectorCornerButtonStyle { case Plus, Close }
mit
abf9703c1c77d259bf7f718cfd28190c
32.367089
120
0.634225
4.804923
false
false
false
false
ProfileCreator/ProfileCreator
ProfileCreator/ProfileCreator/Profile Editor TableView CellView TableView Items/EditorTableViewCellViewCheckbox.swift
1
2586
// // EditorTableViewCellViewCheckbox.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Cocoa class EditorTableViewCellViewCheckbox: NSTableCellView { // MARK: - // MARK: Variables let checkbox = NSButton() // MARK: - // MARK: Initialization required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(cellView: PayloadCellViewTableView, keyPath: String, value: Bool, row: Int) { super.init(frame: NSRect.zero) self.checkbox.translatesAutoresizingMaskIntoConstraints = false self.checkbox.setButtonType(.switch) self.checkbox.font = NSFont.systemFont(ofSize: NSFont.systemFontSize(for: .regular)) self.checkbox.state = (value) ? .on : .off self.checkbox.target = cellView self.checkbox.action = #selector(cellView.buttonClicked(_:)) self.checkbox.title = "" self.checkbox.identifier = NSUserInterfaceItemIdentifier(rawValue: keyPath) self.checkbox.tag = row self.addSubview(self.checkbox) // --------------------------------------------------------------------- // Setup Variables // --------------------------------------------------------------------- var constraints = [NSLayoutConstraint]() // CenterX constraints.append(NSLayoutConstraint(item: self.checkbox, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0)) // CenterY constraints.append(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: self.checkbox, attribute: .centerY, multiplier: 1.0, constant: 0.0)) // --------------------------------------------------------------------- // Activate Layout Constraints // --------------------------------------------------------------------- NSLayoutConstraint.activate(constraints) } }
mit
1aea4793e89b399653c540bfa038e4e0
37.014706
95
0.447582
6.446384
false
false
false
false
lorentey/swift
test/SILGen/guaranteed_normal_args.swift
6
8448
// RUN: %target-swift-emit-silgen -parse-as-library -module-name Swift -parse-stdlib %s | %FileCheck %s // This test checks specific codegen related to normal arguments being passed at // +0. Eventually, it should be merged into normal SILGen tests. ///////////////// // Fake Stdlib // ///////////////// precedencegroup AssignmentPrecedence { assignment: true } public protocol ExpressibleByNilLiteral { init(nilLiteral: ()) } protocol IteratorProtocol { associatedtype Element mutating func next() -> Element? } protocol Sequence { associatedtype Element associatedtype Iterator : IteratorProtocol where Iterator.Element == Element func makeIterator() -> Iterator } enum Optional<T> { case none case some(T) } extension Optional : ExpressibleByNilLiteral { public init(nilLiteral: ()) { self = .none } } func _diagnoseUnexpectedNilOptional(_filenameStart: Builtin.RawPointer, _filenameLength: Builtin.Word, _filenameIsASCII: Builtin.Int1, _line: Builtin.Word) { // This would usually contain an assert, but we don't need one since we are // just emitting SILGen. } class Klass { init() {} } struct Buffer { var k: Klass init(inK: Klass) { k = inK } } public typealias AnyObject = Builtin.AnyObject protocol Protocol { associatedtype AssocType static func useInput(_ input: Builtin.Int32, into processInput: (AssocType) -> ()) } struct FakeArray<Element> { // Just to make this type non-trivial var k: Klass // We are only interested in this being called. We are not interested in its // implementation. mutating func append(_ t: Element) {} } struct FakeDictionary<Key, Value> { } struct FakeDictionaryIterator<Key, Value> { var dictionary: FakeDictionary<Key, Value>? init(_ newDictionary: FakeDictionary<Key, Value>) { dictionary = newDictionary } } extension FakeDictionaryIterator : IteratorProtocol { public typealias Element = (Key, Value) public mutating func next() -> Element? { return .none } } extension FakeDictionary : Sequence { public typealias Element = (Key, Value) public typealias Iterator = FakeDictionaryIterator<Key, Value> public func makeIterator() -> FakeDictionaryIterator<Key, Value> { return FakeDictionaryIterator(self) } } public struct Unmanaged<Instance : AnyObject> { internal unowned(unsafe) var _value: Instance } /////////// // Tests // /////////// class KlassWithBuffer { var buffer: Buffer // Make sure that the allocating init forwards into the initializing init at +1. // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$ss15KlassWithBufferC3inKABs0A0C_tcfC : $@convention(method) (@owned Klass, @thick KlassWithBuffer.Type) -> @owned KlassWithBuffer { // CHECK: bb0([[ARG:%.*]] : @owned $Klass, // CHECK: [[INITIALIZING_INIT:%.*]] = function_ref @$ss15KlassWithBufferC3inKABs0A0C_tcfc : $@convention(method) (@owned Klass, @owned KlassWithBuffer) -> @owned KlassWithBuffer // CHECK: apply [[INITIALIZING_INIT]]([[ARG]], // CHECK: } // end sil function '$ss15KlassWithBufferC3inKABs0A0C_tcfC' init(inK: Klass = Klass()) { buffer = Buffer(inK: inK) } // This test makes sure that we: // // 1. Are able to propagate a +0 value value buffer.k into a +0 value and that // we then copy that +0 value into a +1 value, before we begin the epilog and // then return that value. // CHECK-LABEL: sil hidden [ossa] @$ss15KlassWithBufferC03getC14AsNativeObjectBoyF : $@convention(method) (@guaranteed KlassWithBuffer) -> @owned Builtin.NativeObject { // CHECK: bb0([[SELF:%.*]] : @guaranteed $KlassWithBuffer): // CHECK: [[METHOD:%.*]] = class_method [[SELF]] : $KlassWithBuffer, #KlassWithBuffer.buffer!getter.1 // CHECK: [[BUF:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: [[BUF_BORROW:%.*]] = begin_borrow [[BUF]] // CHECK: [[K:%.*]] = struct_extract [[BUF_BORROW]] : $Buffer, #Buffer.k // CHECK: [[COPIED_K:%.*]] = copy_value [[K]] // CHECK: end_borrow [[BUF_BORROW]] // CHECK: [[CASTED_COPIED_K:%.*]] = unchecked_ref_cast [[COPIED_K]] // CHECK: destroy_value [[BUF]] // CHECK: return [[CASTED_COPIED_K]] // CHECK: } // end sil function '$ss15KlassWithBufferC03getC14AsNativeObjectBoyF' func getBufferAsNativeObject() -> Builtin.NativeObject { return Builtin.unsafeCastToNativeObject(buffer.k) } } struct StructContainingBridgeObject { var rawValue: Builtin.BridgeObject // CHECK-LABEL: sil hidden [ossa] @$ss28StructContainingBridgeObjectV8swiftObjAByXl_tcfC : $@convention(method) (@owned AnyObject, @thin StructContainingBridgeObject.Type) -> @owned StructContainingBridgeObject { // CHECK: bb0([[ARG:%.*]] : @owned $AnyObject, // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPIED_ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[CASTED_ARG:%.*]] = unchecked_ref_cast [[COPIED_ARG]] : $AnyObject to $Builtin.BridgeObject // CHECK: assign [[CASTED_ARG]] to // CHECK: } // end sil function '$ss28StructContainingBridgeObjectV8swiftObjAByXl_tcfC' init(swiftObj: AnyObject) { rawValue = Builtin.reinterpretCast(swiftObj) } } struct ReabstractionThunkTest : Protocol { typealias AssocType = Builtin.Int32 static func useInput(_ input: Builtin.Int32, into processInput: (AssocType) -> ()) { processInput(input) } } // Make sure that we provide a cleanup to x properly before we pass it to // result. extension FakeDictionary { // CHECK-LABEL: sil hidden [ossa] @$ss14FakeDictionaryV20makeSureToCopyTuplesyyF : $@convention(method) <Key, Value> (FakeDictionary<Key, Value>) -> () { // CHECK: [[X:%.*]] = alloc_stack $(Key, Value), let, name "x" // CHECK: [[INDUCTION_VAR:%.*]] = unchecked_take_enum_data_addr {{%.*}} : $*Optional<(Key, Value)>, #Optional.some!enumelt.1 // CHECK: [[INDUCTION_VAR_0:%.*]] = tuple_element_addr [[INDUCTION_VAR]] : $*(Key, Value), 0 // CHECK: [[INDUCTION_VAR_1:%.*]] = tuple_element_addr [[INDUCTION_VAR]] : $*(Key, Value), 1 // CHECK: [[X_0:%.*]] = tuple_element_addr [[X]] : $*(Key, Value), 0 // CHECK: [[X_1:%.*]] = tuple_element_addr [[X]] : $*(Key, Value), 1 // CHECK: copy_addr [take] [[INDUCTION_VAR_0]] to [initialization] [[X_0]] // CHECK: copy_addr [take] [[INDUCTION_VAR_1]] to [initialization] [[X_1]] // CHECK: [[X_0:%.*]] = tuple_element_addr [[X]] : $*(Key, Value), 0 // CHECK: [[X_1:%.*]] = tuple_element_addr [[X]] : $*(Key, Value), 1 // CHECK: [[TMP_X:%.*]] = alloc_stack $(Key, Value) // CHECK: [[TMP_X_0:%.*]] = tuple_element_addr [[TMP_X]] : $*(Key, Value), 0 // CHECK: [[TMP_X_1:%.*]] = tuple_element_addr [[TMP_X]] : $*(Key, Value), 1 // CHECK: [[TMP_0:%.*]] = alloc_stack $Key // CHECK: copy_addr [[X_0]] to [initialization] [[TMP_0]] // CHECK: copy_addr [take] [[TMP_0]] to [initialization] [[TMP_X_0]] // CHECK: [[TMP_1:%.*]] = alloc_stack $Value // CHECK: copy_addr [[X_1]] to [initialization] [[TMP_1]] // CHECK: copy_addr [take] [[TMP_1]] to [initialization] [[TMP_X_1]] // CHECK: [[FUNC:%.*]] = function_ref @$ss9FakeArrayV6appendyyxF : $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @inout FakeArray<τ_0_0>) -> () // CHECK: apply [[FUNC]]<(Key, Value)>([[TMP_X]], // CHECK: } // end sil function '$ss14FakeDictionaryV20makeSureToCopyTuplesyyF' func makeSureToCopyTuples() { var result = FakeArray<Element>(k: Klass()) for x in self { result.append(x) } } } extension Unmanaged { // Just make sure that we do not crash on this. func unsafeGuaranteedTest<Result>( _ body: (Instance) -> Result ) -> Result { let (guaranteedInstance, token) = Builtin.unsafeGuaranteed(_value) let result = body(guaranteedInstance) Builtin.unsafeGuaranteedEnd(token) return result } } // Make sure that we properly forward x into memory and don't crash. public func forwardIntoMemory(fromNative x: AnyObject, y: Builtin.Word) -> Builtin.BridgeObject { // y would normally be 0._builtinWordValue. We don't want to define that // conformance. let object = Builtin.castToBridgeObject(x, y) return object } public struct StructWithOptionalAddressOnlyField<T> { public let newValue: T? } func useStructWithOptionalAddressOnlyField<T>(t: T) -> StructWithOptionalAddressOnlyField<T> { return StructWithOptionalAddressOnlyField<T>(newValue: t) }
apache-2.0
ca4c86050d310ade1ba3e7b0d2ad47a0
35.877729
214
0.657786
3.741693
false
false
false
false
wfleming/pico-block
pblock/View Controllers/RuleSourcesController.swift
1
4960
// // FirstViewController.swift // pblock // // Created by Will Fleming on 7/9/15. // Copyright © 2015 PBlock. All rights reserved. // import UIKit import CoreData class RuleSourcesController: UITableViewController, NSFetchedResultsControllerDelegate { override func viewDidLoad() { super.viewDidLoad() } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if "showRuleSourceRules" == segue.identifier { if let indexPath = self.tableView.indexPathForSelectedRow { let object = self.fetchedResultsController.objectAtIndexPath(indexPath) let navController = segue.destinationViewController as! UINavigationController let controller = navController.topViewController as! RulesController controller.ruleSource = object as? RuleSource controller.navigationItem.leftBarButtonItem = self.splitViewController? .displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) self.configureCell(cell, atIndexPath: indexPath) return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { Async.background { let context = self.fetchedResultsController.managedObjectContext context.deleteObject( self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject ) CoreDataManager.sharedInstance.saveContext(context) } } } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let ruleSource = self.fetchedResultsController.objectAtIndexPath(indexPath) as? RuleSource cell.textLabel?.text = ruleSource?.name cell.detailTextLabel?.text = ruleSource?.url } // MARK: - Fetched results controller lazy private var fetchedResultsController: NSFetchedResultsController = { var fetchRequest: NSFetchRequest = (CoreDataManager.sharedInstance.managedObjectModel? .fetchRequestTemplateForName("ThirdPartyRuleSources")?.copy() as! NSFetchRequest) fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)] let controller = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: CoreDataManager.sharedInstance.managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil ) controller.delegate = self do { try controller.performFetch() } catch { dlog("Failed fetch \(error)") abort() // crash! } return controller }() var _fetchedResultsController: NSFetchedResultsController? = nil func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) default: return } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!) case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) } } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() } }
mit
4523cd37ae899f38489104a47fcd7c4c
36.568182
209
0.749345
5.759582
false
false
false
false
Candyroot/DesignPattern
template/template/TeaWithHook.swift
1
1084
// // TeaWithHook.swift // template // // Created by Bing Liu on 11/21/14. // Copyright (c) 2014 UnixOSS. All rights reserved. // import Foundation class TeaWithHook: CaffeineBeverageWithHook { override func brew() { println("Steeping the tea") } override func addCondiments() { println("Adding Lemon") } override func customerWantsCondiments() -> Bool { let answer = getUserInput() let range = answer.lowercaseString.rangeOfString("y") if range != nil && range!.startIndex == answer.startIndex { return true } else { return false } } private func getUserInput() -> String { var answer: String? println("Would you like lemon with your tea (y/n)? ") var keyboard = NSFileHandle.fileHandleWithStandardInput() var inputData = keyboard.availableData answer = NSString(data: inputData, encoding: NSUTF8StringEncoding) if let ans = answer { return ans; } return "no" } }
apache-2.0
f6860f1f9c15d53e21de01a30225799d
24.209302
74
0.591328
4.460905
false
false
false
false
diversario/bitfountain-ios-foundations
iOS/Just The Tip/Just The Tip/ViewController.swift
1
1686
// // ViewController.swift // Just The Tip // // Created by Ilya Shaisultanov on 1/2/16. // Copyright © 2016 Ilya Shaisultanov. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var totalBill: UITextField! @IBOutlet weak var tenPercent: UITextField! @IBOutlet weak var fifteenPercent: UITextField! @IBOutlet weak var twentyPercent: UITextField! @IBOutlet weak var customPercentage: UITextField! @IBOutlet weak var customPercent: UITextField! override func viewDidLoad() { super.viewDidLoad() totalBill.delegate = self // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func refreshButtonTapped(sender: UIButton) { calculateTip() } func textFieldDidEndEditing(textField: UITextField) { textField.resignFirstResponder() } func calculateTip () { let billTotal = Double(totalBill.text!) let customTip = Double(customPercentage.text!) if let bill = billTotal { tenPercent.text = String(bill + bill * 0.1) fifteenPercent.text = String(bill + bill * 0.15) twentyPercent.text = String(bill + bill * 0.2) if let custom = customTip { customPercent.text = "\(bill + bill * custom * 0.01)" } } else { totalBill.placeholder = "Enter the total, dumbass" } } }
mit
6a3232d430bab398651620f5a5b1460b
27.559322
80
0.623739
4.786932
false
false
false
false
hollance/YOLO-CoreML-MPSNNGraph
TinyYOLO-NNGraph/TinyYOLO-NNGraph/ViewController.swift
1
5803
import UIKit import Metal import AVFoundation import CoreMedia class ViewController: UIViewController { @IBOutlet weak var videoPreview: UIView! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var debugImageView: UIImageView! var device: MTLDevice! var videoCapture: VideoCapture! var commandQueue: MTLCommandQueue! var yolo: YOLO! var boundingBoxes = [BoundingBox]() var colors: [UIColor] = [] var framesDone = 0 var frameCapturingStartTime: CFTimeInterval = 0 let semaphore = DispatchSemaphore(value: 3) override func viewDidLoad() { super.viewDidLoad() timeLabel.text = "" device = MTLCreateSystemDefaultDevice() if device == nil { print("Error: this device does not support Metal") return } commandQueue = device.makeCommandQueue() yolo = YOLO(commandQueue: commandQueue) setUpBoundingBoxes() setUpCamera() frameCapturingStartTime = CACurrentMediaTime() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() print(#function) } // MARK: - Initialization func setUpBoundingBoxes() { for _ in 0..<YOLO.maxBoundingBoxes { boundingBoxes.append(BoundingBox()) } // Make colors for the bounding boxes. There is one color for each class, // 20 classes in total. for r: CGFloat in [0.2, 0.4, 0.6, 0.8, 1.0] { for g: CGFloat in [0.3, 0.7] { for b: CGFloat in [0.4, 0.8] { let color = UIColor(red: r, green: g, blue: b, alpha: 1) colors.append(color) } } } } func setUpCamera() { videoCapture = VideoCapture(device: device) videoCapture.delegate = self videoCapture.desiredFrameRate = 240 videoCapture.setUp(sessionPreset: AVCaptureSession.Preset.hd1280x720) { success in if success { // Add the video preview into the UI. if let previewLayer = self.videoCapture.previewLayer { self.videoPreview.layer.addSublayer(previewLayer) self.resizePreviewLayer() } // Add the bounding box layers to the UI, on top of the video preview. for box in self.boundingBoxes { box.addToLayer(self.videoPreview.layer) } // Once everything is set up, we can start capturing live video. self.videoCapture.start() } } } // MARK: - UI stuff override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() resizePreviewLayer() } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } func resizePreviewLayer() { videoCapture.previewLayer?.frame = videoPreview.bounds } // MARK: - Doing inference func predict(texture: MTLTexture) { yolo.predict(texture: texture) { result in DispatchQueue.main.async { self.show(predictions: result.predictions) if let texture = result.debugTexture { self.debugImageView.image = UIImage.image(texture: texture) } let fps = self.measureFPS() self.timeLabel.text = String(format: "Elapsed %.5f seconds - %.2f FPS", result.elapsed, fps) self.semaphore.signal() } } } func measureFPS() -> Double { // Measure how many frames were actually delivered per second. framesDone += 1 let frameCapturingElapsed = CACurrentMediaTime() - frameCapturingStartTime let currentFPSDelivered = Double(framesDone) / frameCapturingElapsed if frameCapturingElapsed > 1 { framesDone = 0 frameCapturingStartTime = CACurrentMediaTime() } return currentFPSDelivered } func show(predictions: [YOLO.Prediction]) { for i in 0..<boundingBoxes.count { if i < predictions.count { let prediction = predictions[i] // The predicted bounding box is in the coordinate space of the input // image, which is a square image of 416x416 pixels. We want to show it // on the video preview, which is as wide as the screen and has a 16:9 // aspect ratio. The video preview also may be letterboxed at the top // and bottom. let width = view.bounds.width let height = width * 16 / 9 let scaleX = width / 416 let scaleY = height / 416 let top = (view.bounds.height - height) / 2 // Translate and scale the rectangle to our own coordinate system. var rect = prediction.rect rect.origin.x *= scaleX rect.origin.y *= scaleY rect.origin.y += top rect.size.width *= scaleX rect.size.height *= scaleY // Show the bounding box. let label = String(format: "%@ %.1f", labels[prediction.classIndex], prediction.score * 100) let color = colors[prediction.classIndex] boundingBoxes[i].show(frame: rect, label: label, color: color) } else { boundingBoxes[i].hide() } } } } extension ViewController: VideoCaptureDelegate { func videoCapture(_ capture: VideoCapture, didCaptureVideoTexture texture: MTLTexture?, timestamp: CMTime) { // For debugging. //predict(texture: loadTexture(named: "dog416.png")!); return // The semaphore is necessary because the call to predict() does not block. // If we _would_ be blocking, then AVCapture will automatically drop frames // that come in while we're still busy. But since we don't block, all these // new frames get scheduled to run in the future and we end up with a backlog // of unprocessed frames. So we're using the semaphore to block if predict() // is already processing 2 frames, and we wait until the first of those is // done. Any new frames that come in during that time will simply be dropped. semaphore.wait() if let texture = texture { predict(texture: texture) } } }
mit
47d77976aa869f5e6c0621c7e2705047
29.542105
110
0.659486
4.436544
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/InputBar/WaveFormView.swift
1
4165
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit final class WaveFormView: UIView { fileprivate let visualizationView = SCSiriWaveformView() fileprivate let leftGradient = GradientView() fileprivate let rightGradient = GradientView() fileprivate lazy var leftGradientWidthConstraint: NSLayoutConstraint = leftGradient.widthAnchor.constraint(equalToConstant: gradientWidth) fileprivate lazy var rightGradientWidthConstraint: NSLayoutConstraint = rightGradient.widthAnchor.constraint(equalToConstant: gradientWidth) var gradientWidth: CGFloat = 25 { didSet { leftGradientWidthConstraint.constant = gradientWidth rightGradientWidthConstraint.constant = gradientWidth } } var gradientColor: UIColor = UIColor.from(scheme: .background) { didSet { updateWaveFormColor() } } var color: UIColor = .white { didSet { visualizationView.waveColor = color } } init() { super.init(frame: CGRect.zero) configureViews() updateWaveFormColor() createConstraints() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateWithLevel(_ level: Float) { visualizationView.update(withLevel: level) } fileprivate func configureViews() { [visualizationView, leftGradient, rightGradient].forEach(addSubview) visualizationView.primaryWaveLineWidth = 1 visualizationView.secondaryWaveLineWidth = 0.5 visualizationView.numberOfWaves = 4 visualizationView.waveColor = .accent() visualizationView.backgroundColor = UIColor.clear visualizationView.phaseShift = -0.3 visualizationView.frequency = 1.7 visualizationView.density = 10 visualizationView.update(withLevel: 0) // Make sure we don't show any waveform let (midLeft, midRight) = (CGPoint(x: 0, y: 0.5), CGPoint(x: 1, y: 0.5)) leftGradient.setStartPoint(midLeft, endPoint: midRight, locations: [0, 1]) rightGradient.setStartPoint(midRight, endPoint: midLeft, locations: [0, 1]) } fileprivate func createConstraints() { [visualizationView, leftGradient, rightGradient].prepareForLayout() NSLayoutConstraint.activate([ visualizationView.topAnchor.constraint(equalTo: topAnchor), visualizationView.bottomAnchor.constraint(equalTo: bottomAnchor), visualizationView.leftAnchor.constraint(equalTo: leftAnchor), visualizationView.rightAnchor.constraint(equalTo: rightAnchor), topAnchor.constraint(equalTo: leftGradient.topAnchor), topAnchor.constraint(equalTo: rightGradient.topAnchor), bottomAnchor.constraint(equalTo: leftGradient.bottomAnchor), bottomAnchor.constraint(equalTo: rightGradient.bottomAnchor), leftAnchor.constraint(equalTo: leftGradient.leftAnchor), rightAnchor.constraint(equalTo: rightGradient.rightAnchor), leftGradientWidthConstraint, rightGradientWidthConstraint ]) } fileprivate func updateWaveFormColor() { let clearGradientColor = gradientColor.withAlphaComponent(0) let leftColors = [gradientColor, clearGradientColor].map { $0.cgColor } leftGradient.gradientLayer.colors = leftColors rightGradient.gradientLayer.colors = leftColors } }
gpl-3.0
d1455c870cc2e7f045610b8f50c20971
37.564815
144
0.702761
4.964243
false
false
false
false
seandavidmcgee/HumanKontactBeta
src/keyboardTest/FuzzySearch.swift
1
14669
/* The MIT License (MIT) - FuzzySearch.swift Copyright (c) 2015 Rahul Nadella https://github.com/rahulnadella 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 /* In computer science, approximate string matching (often colloquially referred to as fuzzy string searching) is the technique of finding strings that match a pattern approximately (rather than exactly). The problem of approximate string matching is typically divided into two sub-problems: finding approximate substring matches inside a given string and finding dictionarystrings that match the pattern approximately. The FuzzySearch provides an implementation to search and match a pattern approximately will return whether the character set is found or not by a Boolean or Integer value. :version 1.0 */ public class FuzzySearch { /* The FuzzySearch.search method returns a Boolean of TRUE if the stringToSearch for is found in the originalString otherwise FALSE. This search is not case sensitive. :param originalString The original contents that is going to be searched :param stringToSearch The specific contents to search for :return A Boolean of TRUE if found otherwise FALSE for not found */ public class func search<T : Equatable>(originalString originalString: T, stringToSearch: T) -> Bool { return search(originalString: originalString, stringToSearch: stringToSearch, isCaseSensitive: false) } /* The FuzzySearch.search method returns the number of timees found (Integer) of the set of characters to be searched within the original character set. :param originalString The original contents that is going to be searched :param stringToSearch The specific contents to search for :return A Boolean of TRUE if found otherwise FALSE for not found */ public class func search<T : Equatable>(originalString originalString: T, stringToSearch: T) -> Int { return search(originalString: originalString, stringToSearch: stringToSearch, isCaseSensitive: false) } /* The FuzzySearch.search method returns a Boolean of TRUE if the stringToSearch for is found in the originalString otherwise FALSE. This search does search for case sensitive Strings by using a Boolean value to indicate what kind of search to use. :param originalString The original contents that is going to be searched :param stringToSearch The specific contents to search for :param isCaseSensitive A Boolean value to indicate whether to use case sensitive or case insensitive search parameters :return A Boolean of TRUE if found otherwise FALSE for not found */ public class func search<T : Equatable>(originalString originalString: T, stringToSearch: T, isCaseSensitive: Bool) -> Bool { /* Decipher if the String to be searched for is found */ let searchCount:Int = search(originalString: originalString, stringToSearch: stringToSearch, isCaseSensitive: isCaseSensitive) if searchCount > 0 { return true } else { return false } } /* The FuzzySearch.search method returns the number of instances a specific character set is found with in a String object :param originalString The original contents that is going to be searched :param stringToSearch The specific contents to search for :param isCaseSensitive A Boolean value to indicate whether to use case sensitive or case insensitive search parameters :return An Integer value of the number of instances a character set matches a String */ public class func search<T : Equatable>(originalString originalString: T, stringToSearch: T, isCaseSensitive: Bool) -> Int { var tempOriginalString = String() var tempStringToSearch = String() /* Verify that the variables are Strings */ if originalString is String && stringToSearch is String { tempOriginalString = originalString as! String tempStringToSearch = stringToSearch as! String } else { return 0 } /* Either String is empty return false */ if tempOriginalString.characters.count == 0 || tempStringToSearch.characters.count == 0 { return 0 } /* stringToSearch is greater than the originalString return false */ if tempOriginalString.characters.count < tempStringToSearch.characters.count { return 0 } /* Check isCaseSensitive if true lowercase the contents of both strings */ if isCaseSensitive { tempOriginalString = tempOriginalString.lowercaseString tempStringToSearch = tempStringToSearch.lowercaseString } var searchIndex : Int = 0 var searchCount : Int = 0 /* Search the contents of the originalString to determine if the stringToSearch can be found or not */ for charOut in tempOriginalString.characters { for (indexIn, charIn) in tempStringToSearch.characters.enumerate() { if indexIn == searchIndex { if charOut==charIn { searchIndex++ if searchIndex == tempStringToSearch.characters.count { searchCount++ searchIndex = 0 } else { break } } else { break } } } } return searchCount } /* The FuzzySearch.search method returns the Array of String(s) a specific character approximately matches that String object :param originalString The original contents that is going to be searched :param stringToSearch The specific contents to search for :param isCaseSensitive A Boolean value to indicate whether to use case sensitive or case insensitive search parameters :return The Array of String(s) if any are found otherwise an empty Array of String(s) */ public class func search(var originalString originalString: String, var stringToSearch: String, isCaseSensitive: Bool) -> [String] { /* Either String is empty return false */ if originalString.characters.count == 0 || stringToSearch.characters.count == 0 { return [String]() } /* stringToSearch is greater than the originalString return false */ if originalString.characters.count < stringToSearch.characters.count { return [String]() } /* Check isCaseSensitive if true lowercase the contents of both strings */ if isCaseSensitive { originalString = originalString.lowercaseString stringToSearch = stringToSearch.lowercaseString } var searchIndex : Int = 0 var approximateMatch:Array = [String]() /* Search the contents of the originalString to determine if the stringToSearch can be found or not */ for content in originalString.componentsSeparatedByString(" ") { for charOut in content.characters { for (indexIn, charIn) in stringToSearch.characters.enumerate() { if indexIn == searchIndex { if charOut==charIn { searchIndex++ if searchIndex==stringToSearch.characters.count { approximateMatch.append(content) searchIndex = 0 } else { break } } else { break } } } } } return approximateMatch } /* The score method that provides fast fuzzy string matching and scoring based on the technique of finding strings that match a pattern approximately (rather than exactly). The problem of approximate string matching is typically dived intotwo sub-problems: finding approximate substring matches inside a given string and finding dictionary strings that match the pattern approximately. The design and implementation of this method are based on StringScore_Swift by (Yichi Zhang) and StringScore in Javascript (Joshaven Potter) :param originalString The original contents that is going to be searched :param stringToMatch The specific contents to search for the approximate match :param fuzziness A Double value to indicate a function of distance between two words, which provides a measure of their similarity. The fuzziness value is defaulted to 0. :return The score value of the approximate match between strings. Score of 0 for no match; up to 1 for perfect. */ public class func score(originalString originalString: String, stringToMatch: String, fuzziness: Double? = nil) -> Double { /* Either String objects are empty return score of 0 */ if originalString.isEmpty || stringToMatch.isEmpty { return 0 } /* the stringToMatch is greater than originalString return score of 0 */ if originalString.characters.count < stringToMatch.characters.count { return 0 } /* Either String objects are the same return score of 1 */ if originalString == stringToMatch { return 1 } /* Initialization of the local variables */ var runningScore = 0.0 var charScore = 0.0 var finalScore = 0.0 let lowercaseString = originalString.lowercaseString let strLength = originalString.characters.count let lowercaseStringToMatch = stringToMatch.lowercaseString let wordLength = stringToMatch.characters.count var indexOfString:String.Index! var startAt = lowercaseString.startIndex var fuzzies = 1.0 var fuzzyFactor = 0.0 var fuzzinessIsNil = true /* Cache fuzzyFactor for speed increase */ if let fuzziness = fuzziness { fuzzyFactor = 1 - fuzziness fuzzinessIsNil = false } for i in 0..<wordLength { /* Find next first case-insensitive match of word's i-th character. The search in "string" begins at "startAt". */ if let range = lowercaseString.rangeOfString( String(lowercaseStringToMatch[lowercaseStringToMatch.startIndex.advancedBy(i)] as Character), options: NSStringCompareOptions.CaseInsensitiveSearch, range: Range<String.Index>( start: startAt, end: lowercaseString.endIndex), locale: nil ) { /* start index of word's i-th character in string. */ indexOfString = range.startIndex if startAt == indexOfString { /* Consecutive letter & start-of-string Bonus */ charScore = 0.7 } else { charScore = 0.1 /* Acronym Bonus Weighing Logic: Typing the first character of an acronym is as if you preceded it with two perfect character matches. */ if originalString[indexOfString.advancedBy(-1)] == " " { charScore += 0.8 } } } else { /* Character not found. */ if fuzzinessIsNil { // Fuzziness is nil. Return 0. return 0 } else { fuzzies += fuzzyFactor continue } } /* Same case bonus. */ if (originalString[indexOfString] == stringToMatch[stringToMatch.startIndex.advancedBy(i)]) { charScore += 0.1 } /* Update scores and startAt position for next round of indexOf */ runningScore += charScore startAt = indexOfString.advancedBy(1) } /* Reduce penalty for longer strings. */ finalScore = 0.5 * (runningScore / Double(strLength) + runningScore / Double(wordLength)) / fuzzies if (lowercaseString[lowercaseString.startIndex] == lowercaseString[lowercaseString.startIndex]) && (finalScore < 0.85) { finalScore += 0.15 } return finalScore } }
mit
4ab7bfb6d937abb2372e4ea997c09310
35.675
134
0.595201
5.676858
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/IncursionCell.swift
2
3188
// // IncursionCell.swift // Neocom // // Created by Artem Shimanski on 11/6/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import EVEAPI import TreeController class IncursionCell: RowCell { @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var bossImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var stateLabel: UILabel! @IBOutlet weak var progressLabel: UILabel! @IBOutlet weak var progressView: UIProgressView! override func awakeFromNib() { super.awakeFromNib() let layer = self.progressView.superview?.layer; layer?.borderColor = UIColor(number: 0x3d5866ff).cgColor layer?.borderWidth = 1.0 / UIScreen.main.scale } } extension Prototype { enum IncursionCell { static let `default` = Prototype(nib: UINib(nibName: "IncursionCell", bundle: nil), reuseIdentifier: "IncursionCell") } } extension Tree.Item { class IncursionRow: ExpandableRow<ESI.Incursions.Incursion, Tree.Item.RoutableRow<SDEMapSolarSystem>> { let api: API init(_ content: ESI.Incursions.Incursion, api: API) { self.api = api let context = Services.sde.viewContext //TODO: add route let rows = content.infestedSolarSystems.compactMap { context.mapSolarSystem($0) }.map { Tree.Item.RoutableRow($0) } super.init(content, isExpanded: false, children: rows) } override var prototype: Prototype? { return Prototype.IncursionCell.default } lazy var solaySystem: EVELocation? = { guard let solarSystem = Services.sde.viewContext.mapSolarSystem(content.stagingSolarSystemID) else {return nil} return EVELocation(solarSystem) }() lazy var title: String = { if let constellation = Services.sde.viewContext.mapConstellation(content.constellationID) { return "\(constellation.constellationName ?? "") / \(constellation.region?.regionName ?? "")" } else { return NSLocalizedString("Unknown", comment: "") } }() var image: UIImage? override func configure(cell: UITableViewCell, treeController: TreeController?) { super.configure(cell: cell, treeController: treeController) guard let cell = cell as? IncursionCell else {return} cell.titleLabel.text = title cell.bossImageView.alpha = content.hasBoss ? 1.0 : 0.4 cell.progressView.progress = content.influence cell.progressLabel.text = NSLocalizedString("Warzone Control: ", comment: "") + "\(Int((content.influence * 100).rounded(.down)))%" cell.locationLabel.attributedText = solaySystem?.displayName cell.stateLabel.text = content.state.title cell.iconView.image = image if image == nil { api.image(allianceID: Int64(content.factionID), dimension: Int(cell.iconView.bounds.size.width), cachePolicy: .useProtocolCachePolicy).then(on: .main) { [weak self, weak treeController] result in guard let strongSelf = self else {return} strongSelf.image = result.value if let cell = treeController?.cell(for: strongSelf) as? IncursionCell { cell.iconView.image = strongSelf.image } }.catch(on: .main) { [weak self] _ in self?.image = UIImage() } } } } }
lgpl-2.1
6e4d058eabbf217994703090eb0ebd1b
31.191919
199
0.717603
3.646453
false
false
false
false
obrichak/discounts
discounts/Classes/BarCodeGenerator/RSEANGenerator.swift
1
3783
// // RSEANGenerator.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/11/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit let RSBarcodesTypeISBN13Code = "com.pdq.rsbarcodes.isbn13" let RSBarcodesTypeISSN13Code = "com.pdq.rsbarcodes.issn13" // http://blog.sina.com.cn/s/blog_4015406e0100bsqk.html class RSEANGenerator: RSAbstractCodeGenerator { var length = 0 // 'O' for odd and 'E' for even let lefthandParities = [ "OOOOOO", "OOEOEE", "OOEEOE", "OOEEEO", "OEOOEE", "OEEOOE", "OEEEOO", "OEOEOE", "OEOEEO", "OEEOEO" ] // 'R' for right-hand let parityEncodingTable = [ ["O" : "0001101", "E" : "0100111", "R" : "1110010"], ["O" : "0011001", "E" : "0110011", "R" : "1100110"], ["O" : "0010011", "E" : "0011011", "R" : "1101100"], ["O" : "0111101", "E" : "0100001", "R" : "1000010"], ["O" : "0100011", "E" : "0011101", "R" : "1011100"], ["O" : "0110001", "E" : "0111001", "R" : "1001110"], ["O" : "0101111", "E" : "0000101", "R" : "1010000"], ["O" : "0111011", "E" : "0010001", "R" : "1000100"], ["O" : "0110111", "E" : "0001001", "R" : "1001000"], ["O" : "0001011", "E" : "0010111", "R" : "1110100"] ] init(length:Int) { self.length = length } override func isValid(contents: String) -> Bool { if super.isValid(contents) && self.length == contents.length() { var sum_odd = 0 var sum_even = 0 for i in 0..<(self.length - 1) { let digit = contents[i].toInt()! if i % 2 == (self.length == 13 ? 0 : 1) { sum_even += digit } else { sum_odd += digit } } let checkDigit = (10 - (sum_even + sum_odd * 3) % 10) % 10 return contents[contents.length() - 1].toInt() == checkDigit } return false } override func initiator() -> String { return "101" } override func terminator() -> String { return "101" } func centerGuardPattern() -> String { return "01010" } override func barcode(contents: String) -> String { var lefthandParity = "OOOO" var newContents = contents if self.length == 13 { lefthandParity = self.lefthandParities[contents[0].toInt()!] newContents = contents.substring(1, length: contents.length() - 1) } var barcode = "" for i in 0..<newContents.length() { let digit = newContents[i].toInt()! if i < lefthandParity.length() { barcode += self.parityEncodingTable[digit][lefthandParity[i]]! if i == lefthandParity.length() - 1 { barcode += self.centerGuardPattern() } } else { barcode += self.parityEncodingTable[digit]["R"]! } } return barcode } } class RSEAN8Generator: RSEANGenerator { init() { super.init(length: 8) } } class RSEAN13Generator: RSEANGenerator { init() { super.init(length: 13) } } class RSISBN13Generator: RSEAN13Generator { override func isValid(contents: String) -> Bool { // http://www.appsbarcode.com/ISBN.php return super.isValid(contents) && contents.substring(0, length: 3) == "978" } } class RSISSN13Generator: RSEAN13Generator { override func isValid(contents: String) -> Bool { // http://www.appsbarcode.com/ISSN.php return super.isValid(contents) && contents.substring(0, length: 3) == "977" } }
gpl-3.0
1f5ed9142d0d67923dc85674ae44e9b9
28.795276
83
0.513349
3.493075
false
false
false
false
xwu/swift
test/SILOptimizer/pre_specialize.swift
1
7447
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module-path %t/pre_specialized_module.swiftmodule %S/Inputs/pre_specialized_module.swift // RUN: %target-swift-frontend -I %t -O -emit-sil %s | %FileCheck %s --check-prefix=OPT -check-prefix=OPT-%target-os // RUN: %target-swift-frontend -I %t -Onone -emit-sil %s | %FileCheck %s --check-prefix=NONE -check-prefix=NONE-%target-os // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -O -emit-module-path %t/pre_specialized_module.swiftmodule %S/Inputs/pre_specialized_module.swift // RUN: %target-swift-frontend -I %t -O -emit-sil %s | %FileCheck %s --check-prefix=OPT // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -O -enable-library-evolution -emit-module-path %t/pre_specialized_module.swiftmodule %S/Inputs/pre_specialized_module.swift // RUN: %target-swift-frontend -I %t -O -emit-sil %s | %FileCheck %s --check-prefix=OPT // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -O -swift-version 5 -enable-library-evolution -emit-module -o /dev/null -emit-module-interface-path %t/pre_specialized_module.swiftinterface %S/Inputs/pre_specialized_module.swift -module-name pre_specialized_module // RUN: %target-swift-frontend -I %t -O -emit-sil %s | %FileCheck %s --check-prefix=OPT import pre_specialized_module // Make sure we generate the public pre-specialized entry points. // OPT-DAG: sil @$s14pre_specialize10testPublic1tyx_tlFSf_Ts5 : $@convention(thin) (Float) -> () { // OPT-DAG: sil @$s14pre_specialize10testPublic1tyx_tlFSi_Ts5 : $@convention(thin) (Int) -> () { // OPT-macosx-DAG: sil [available 10.5] @$s14pre_specialize10testPublic1tyx_tlFSd_Ts5 : $@convention(thin) (Double) -> () { // OPT-linux-gnu-DAG: sil @$s14pre_specialize10testPublic1tyx_tlFSd_Ts5 : $@convention(thin) (Double) -> () { // NONE-DAG: sil @$s14pre_specialize10testPublic1tyx_tlFSf_Ts5 : $@convention(thin) (Float) -> () { // NONE-DAG: sil @$s14pre_specialize10testPublic1tyx_tlFSi_Ts5 : $@convention(thin) (Int) -> () { // NONE-macosx-DAG: sil [available 10.5] @$s14pre_specialize10testPublic1tyx_tlFSd_Ts5 : $@convention(thin) (Double) -> () { // NONE-linux-gnu-DAG: sil @$s14pre_specialize10testPublic1tyx_tlFSd_Ts5 : $@convention(thin) (Double) -> () { @_specialize(exported: true, where T == Int) @_specialize(exported: true, where T == Float) @_specialize(exported: true, availability: macOS 10.5, *; where T == Double) public func testPublic<T>(t: T) { print(t) } // OPT-macosx-DAG: sil [available 10.5] @$s14pre_specialize18testEmitIntoClient1tyx_tlFSd_Ts5 : $@convention(thin) (Double) -> () { // OPT-linux-gnu-DAG: sil @$s14pre_specialize18testEmitIntoClient1tyx_tlFSd_Ts5 : $@convention(thin) (Double) -> () { // OPT-DAG: sil @$s14pre_specialize18testEmitIntoClient1tyx_tlFSf_Ts5 : $@convention(thin) (Float) -> () { // OPT-DAG: sil @$s14pre_specialize18testEmitIntoClient1tyx_tlFSi_Ts5 : $@convention(thin) (Int) -> () { // NONE: sil @$s14pre_specialize18testEmitIntoClient1tyx_tlFSf_Ts5 : $@convention(thin) (Float) -> () { // NONE: sil @$s14pre_specialize18testEmitIntoClient1tyx_tlFSi_Ts5 : $@convention(thin) (Int) -> () { @_specialize(exported: true, where T == Int) @_specialize(exported: true, where T == Float) @_specialize(exported: true, availability: macOS 10.5, *; where T == Double) @_alwaysEmitIntoClient internal func testEmitIntoClient<T>(t: T) { print(t) } // OPT: sil @$s14pre_specialize28usePrespecializedEntryPointsyyF : $@convention(thin) () -> () { // OPT: [[F1:%.*]] = function_ref @$s22pre_specialized_module20publicPrespecializedyyxlFSi_Ts5 : $@convention(thin) (Int) -> () // OPT: apply [[F1]] // OPT: [[F2:%.*]] = function_ref @$s22pre_specialized_module20publicPrespecializedyyxlFSd_Ts5 : $@convention(thin) (Double) -> () // OPT: apply [[F2]] // OPT-macosx: [[F6:%.*]] = function_ref @$s22pre_specialized_module20publicPrespecializedyyxlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> () // OPT-macosx: apply [[F6]]<SomeData> // OPT: [[F3:%.*]] = function_ref @$s22pre_specialized_module36internalEmitIntoClientPrespecializedyyxlFSi_Ts5 : $@convention(thin) (Int) -> () // OPT: apply [[F3]] // OPT: [[F4:%.*]] = function_ref @$s22pre_specialized_module36internalEmitIntoClientPrespecializedyyxlFSd_Ts5 : $@convention(thin) (Double) -> () // OPT: apply [[F4]] // OPT: [[F5:%.*]] = function_ref @$s22pre_specialized_module16useInternalThingyyxlFSi_Tg5 // OPT: apply [[F5]]({{.*}}) : $@convention(thin) (Int) -> () // OPT: } // end sil function '$s14pre_specialize28usePrespecializedEntryPointsyyF' // OPT: sil {{.*}} @$s22pre_specialized_module16useInternalThingyyxlFSi_Tg5 : $@convention(thin) (Int) -> () { // OPT: [[F1:%.*]] = function_ref @$s22pre_specialized_module14InternalThing2V7computexyFSi_Ts5 : $@convention(method) (InternalThing2<Int>) -> Int // OPT: apply [[F1]]( // OPT: [[F2:%.*]] = function_ref @$s22pre_specialized_module14InternalThing2V9computedXxvgSi_Ts5 : $@convention(method) (InternalThing2<Int>) -> Int // OPT: apply [[F2]]( // OPT: [[F3:%.*]] = function_ref @$s22pre_specialized_module14InternalThing2V9computedYxvsSi_Ts5 : $@convention(method) (Int, @inout InternalThing2<Int>) -> () // OPT: apply [[F3]]( // OPT: [[F4:%.*]] = function_ref @$s22pre_specialized_module14InternalThing2V9computedYxvgSi_Ts5 : $@convention(method) (InternalThing2<Int>) -> Int // OPT: apply [[F4]]( // OPT: [[F5:%.*]] = function_ref @$s22pre_specialized_module14InternalThing2V9computedZxvMSi_Ts5 : $@yield_once @convention(method) (@inout InternalThing2<Int>) -> @yields @inout Int // OPT: begin_apply [[F5]]( // OPT: [[F6:%.*]] = function_ref @$s22pre_specialized_module14InternalThing2V9computedZxvrSi_Ts5 : $@yield_once @convention(method) (InternalThing2<Int>) -> @yields @in_guaranteed Int // OPT: begin_apply [[F6]]( // OPT: [[F7:%.*]] = function_ref @$s22pre_specialized_module14InternalThing2VyxSicisSi_Ts5 : $@convention(method) (Int, Int, @inout InternalThing2<Int>) -> () // OPT: apply [[F7]]( // OPT: [[F8:%.*]] = function_ref @$s22pre_specialized_module14InternalThing2VyxSicigSi_Ts5 : $@convention(method) (Int, InternalThing2<Int>) -> Int // OPT: apply [[F8]]( // OPT: } // end sil function '$s22pre_specialized_module16useInternalThingyyxlFSi_Tg5' public func usePrespecializedEntryPoints() { publicPrespecialized(1) publicPrespecialized(1.0) publicPrespecialized(SomeData()) useInternalEmitIntoClientPrespecialized(2) useInternalEmitIntoClientPrespecialized(2.0) useInternalThing(2) } // OPT-macosx: sil [available 10.50] @$s14pre_specialize40usePrespecializedEntryPointsAvailabilityyyF : $@convention(thin) () -> () { // OPT-macosx: [[F1:%.*]] = function_ref @$s22pre_specialized_module20publicPrespecializedyyxlFAA8SomeDataV_Ts5 : $@convention(thin) (SomeData) -> () // OPT-macosx: apply [[F1]]( // OPT-macosx: } // end sil function '$s14pre_specialize40usePrespecializedEntryPointsAvailabilityyyF' @available(macOS 10.50, *) public func usePrespecializedEntryPointsAvailability() { publicPrespecialized(SomeData()) } // OPT: sil [signature_optimized_thunk] [always_inline] @$s22pre_specialized_module16publicInlineableyyxlFSd_Ts5 : $@convention(thin) (Double) -> () { // NONE: sil @$s22pre_specialized_module16publicInlineableyyxlFSd_Ts5 : $@convention(thin) (Double) -> () { @_specialize(exported: true, target: publicInlineable(_:), where T == Double) public func specializeTarget<T>(_ t: T) {}
apache-2.0
d1210961c7bf65e41f2eccb810cfc03f
67.302752
246
0.7045
3.147992
false
true
false
false
stripe/stripe-ios
StripeIdentity/StripeIdentityTests/Helpers/VerificationSheetControllerMock.swift
1
4277
// // VerificationSheetControllerMock.swift // StripeIdentityTests // // Created by Mel Ludowise on 11/5/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // import Foundation @_spi(STP) import StripeCore @_spi(STP) import StripeCoreTestUtils import UIKit import XCTest @testable import StripeIdentity final class VerificationSheetControllerMock: VerificationSheetControllerProtocol { var verificationPageResponse: Result<StripeAPI.VerificationPage, Error>? var apiClient: IdentityAPIClient let flowController: VerificationSheetFlowControllerProtocol var collectedData: StripeAPI.VerificationPageCollectedData let mlModelLoader: IdentityMLModelLoaderProtocol let analyticsClient: IdentityAnalyticsClient var delegate: VerificationSheetControllerDelegate? var needBack: Bool = true private(set) var didLoadAndUpdateUI = false private(set) var savedData: StripeAPI.VerificationPageCollectedData? private(set) var uploadedDocumentsResult: Result<DocumentUploaderProtocol.CombinedFileData, Error>? private(set) var frontUploadedDocumentsResult: Result<StripeAPI.VerificationPageDataDocumentFileData, Error>? private(set) var backUploadedDocumentsResult: Result<StripeAPI.VerificationPageDataDocumentFileData, Error>? private(set) var uploadedSelfieResult: Result<SelfieUploader.FileData, Error>? private(set) var didCheckSubmitAndTransition = false private(set) var didSaveDocumentFrontAndDecideBack = false private(set) var didSaveDocumentBackAndTransition = false init( apiClient: IdentityAPIClient = IdentityAPIClientTestMock(), flowController: VerificationSheetFlowControllerProtocol = VerificationSheetFlowControllerMock(), collectedData: StripeAPI.VerificationPageCollectedData = .init(), mlModelLoader: IdentityMLModelLoaderProtocol = IdentityMLModelLoaderMock(), analyticsClient: IdentityAnalyticsClient = .init( verificationSessionId: "", analyticsClient: MockAnalyticsClientV2() ) ) { self.apiClient = apiClient self.flowController = flowController self.collectedData = collectedData self.mlModelLoader = mlModelLoader self.analyticsClient = analyticsClient } func loadAndUpdateUI() { didLoadAndUpdateUI = true } func saveAndTransition( from fromScreen: IdentityAnalyticsClient.ScreenName, collectedData: StripeAPI.VerificationPageCollectedData, completion: @escaping () -> Void ) { savedData = collectedData completion() } func checkSubmitAndTransition( updateDataResult: Result<StripeAPI.VerificationPageData, Error>? = nil, completion: @escaping () -> Void ) { didCheckSubmitAndTransition = true } func saveDocumentFrontAndDecideBack( from fromScreen: IdentityAnalyticsClient.ScreenName, documentUploader: DocumentUploaderProtocol, onCompletion: @escaping (_ isBackRequired: Bool) -> Void ) { didSaveDocumentFrontAndDecideBack = true documentUploader.frontUploadFuture?.observe { [self] result in self.frontUploadedDocumentsResult = result if self.needBack { onCompletion(true) } else { onCompletion(false) } } } func saveDocumentBackAndTransition( from fromScreen: IdentityAnalyticsClient.ScreenName, documentUploader: DocumentUploaderProtocol, completion: @escaping () -> Void ) { didSaveDocumentBackAndTransition = true documentUploader.backUploadFuture?.observe { [weak self] result in self?.backUploadedDocumentsResult = result completion() } } func saveSelfieFileDataAndTransition( from fromScreen: IdentityAnalyticsClient.ScreenName, selfieUploader: SelfieUploaderProtocol, capturedImages: FaceCaptureData, trainingConsent: Bool, completion: @escaping () -> Void ) { selfieUploader.uploadFuture?.observe { [weak self] result in self?.uploadedSelfieResult = result completion() } } }
mit
66b1d4067388b22c52c1164f391ff5c2
33.483871
83
0.706735
5.468031
false
false
false
false
JGiola/swift
test/Interop/SwiftToCxx/structs/small-structs-pass-return-direct-in-cxx.swift
1
9934
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend %s -typecheck -module-name Structs -clang-header-expose-public-decls -emit-clang-header-path %t/structs.h // RUN: %FileCheck %s < %t/structs.h // RUN: %check-interop-cxx-header-in-clang(%t/structs.h) // RUN: sed -e 's/^public struct/@frozen public struct/' %s > %t/small-structs-frozen.swift // RUN: %target-swift-frontend %t/small-structs-frozen.swift -enable-library-evolution -typecheck -module-name Structs -clang-header-expose-public-decls -emit-clang-header-path %t/small-structs-frozen.h -D RESILIENT // RUN: %FileCheck --check-prefixes=CHECK,RESILIENT %s < %t/small-structs-frozen.h public struct StructOneI64 { let x: Int64 } public struct StructTwoI32 { let x, y: Int32 } public struct StructOneI16AndOneStruct { var x: Int16 var y: StructTwoI32 } public struct StructU16AndPointer { let x: UInt8 let y: UnsafeMutableRawPointer } public struct StructDoubleAndFloat { var x: Double var y: Float } // CHECK: SWIFT_EXTERN void $s7Structs25inoutStructDoubleAndFloatyyAA0cdeF0VzF(char * _Nonnull s) SWIFT_NOEXCEPT SWIFT_CALL; // inoutStructDoubleAndFloat(_:) // CHECK: SWIFT_EXTERN void $s7Structs020inoutStructOneI16AnddC0yyAA0cdefdC0Vz_AA0C6TwoI32VtF(char * _Nonnull s, struct swift_interop_stub_Structs_StructTwoI32 s2) SWIFT_NOEXCEPT SWIFT_CALL; // inoutStructOneI16AndOneStruct(_:_:) // CHECK: class StructDoubleAndFloat final { // CHECK: class StructOneI16AndOneStruct final { // CHECK: class StructOneI64 final { #if RESILIENT /*not frozen*/ public struct StructOneI64_resilient { let x: Int64 } public func printStructOneI64_resilient(_ x : StructOneI64_resilient) { print(x) } // RESILIENT: class StructOneI64_resilient final { // RESILIENT: swift::_impl::OpaqueStorage _storage; // RESILIENT-NEXT: friend class _impl::_impl_StructOneI64_resilient; // RESILIENT-NEXT: }; #endif // CHECK: class StructTwoI32 final { // CHECK: class StructU16AndPointer final { public func returnNewStructOneI64() -> StructOneI64 { return StructOneI64(x: 42 ) } public func passThroughStructOneI64(_ x: StructOneI64) -> StructOneI64 { return x } public func printStructOneI64(_ x: StructOneI64) { print("StructOneI64.x = \(x.x)") } public func returnNewStructTwoI32(_ x: Int32) -> StructTwoI32 { return StructTwoI32(x: x, y: x * 2) } public func passThroughStructTwoI32(_ i: Int32, _ x: StructTwoI32, _ j: Int32) -> StructTwoI32 { return StructTwoI32(x: x.x + i, y: x.y + j) } public func printStructTwoI32(_ x: StructTwoI32) { print("StructTwoI32.x = \(x.x), y = \(x.y)") } public func returnNewStructOneI16AndOneStruct() -> StructOneI16AndOneStruct { return StructOneI16AndOneStruct(x: 0xFF, y: StructTwoI32(x: 5, y: 72)) } public func printStructStructTwoI32_and_OneI16AndOneStruct(_ y: StructTwoI32, _ x: StructOneI16AndOneStruct) { printStructTwoI32(y) print("StructOneI16AndOneStruct.x = \(x.x), y.x = \(x.y.x), y.y = \(x.y.y)") } public func inoutStructOneI16AndOneStruct(_ s: inout StructOneI16AndOneStruct, _ s2: StructTwoI32) { s.x -= 50 s.y = s2 } public func returnNewStructU16AndPointer(_ x: UnsafeMutableRawPointer) -> StructU16AndPointer { return StructU16AndPointer(x: 55, y: x) } public func getStructU16AndPointer_x(_ x: StructU16AndPointer) -> UInt8 { return x.x } public func getStructU16AndPointer_y(_ x: StructU16AndPointer) -> UnsafeMutableRawPointer { return x.y } public func returnNewStructDoubleAndFloat(_ y: Float, _ x: Double) -> StructDoubleAndFloat { return StructDoubleAndFloat(x: x, y: y) } public func getStructDoubleAndFloat_x(_ x: StructDoubleAndFloat) -> Double { return x.x } public func getStructDoubleAndFloat_y(_ x: StructDoubleAndFloat) -> Float { return x.y } public func inoutStructDoubleAndFloat(_ s: inout StructDoubleAndFloat) { s.x *= Double(s.y) s.y /= 10 } // CHECK: inline double getStructDoubleAndFloat_x(const StructDoubleAndFloat& x) noexcept SWIFT_WARN_UNUSED_RESULT { // CHECK-NEXT: return _impl::$s7Structs25getStructDoubleAndFloat_xySdAA0cdeF0VF(_impl::swift_interop_passDirect_Structs_StructDoubleAndFloat(_impl::_impl_StructDoubleAndFloat::getOpaquePointer(x))); // CHECK-NEXT: } // CHECK: inline float getStructDoubleAndFloat_y(const StructDoubleAndFloat& x) noexcept SWIFT_WARN_UNUSED_RESULT { // CHECK-NEXT: return _impl::$s7Structs25getStructDoubleAndFloat_yySfAA0cdeF0VF(_impl::swift_interop_passDirect_Structs_StructDoubleAndFloat(_impl::_impl_StructDoubleAndFloat::getOpaquePointer(x))); // CHECK-NEXT: } // CHECK: inline uint8_t getStructU16AndPointer_x(const StructU16AndPointer& x) noexcept SWIFT_WARN_UNUSED_RESULT { // CHECK-NEXT: return _impl::$s7Structs24getStructU16AndPointer_xys5UInt8VAA0cdeF0VF(_impl::swift_interop_passDirect_Structs_StructU16AndPointer(_impl::_impl_StructU16AndPointer::getOpaquePointer(x))); // CHECK-NEXT: } // CHECK: inline void * _Nonnull getStructU16AndPointer_y(const StructU16AndPointer& x) noexcept SWIFT_WARN_UNUSED_RESULT { // CHECK-NEXT: return _impl::$s7Structs24getStructU16AndPointer_yySvAA0cdeF0VF(_impl::swift_interop_passDirect_Structs_StructU16AndPointer(_impl::_impl_StructU16AndPointer::getOpaquePointer(x))); // CHECK-NEXT: } // CHECK: inline void inoutStructDoubleAndFloat(StructDoubleAndFloat& s) noexcept { // CHECK-NEXT: return _impl::$s7Structs25inoutStructDoubleAndFloatyyAA0cdeF0VzF(_impl::_impl_StructDoubleAndFloat::getOpaquePointer(s)); // CHECK-NEXT: } // CHECK: inline void inoutStructOneI16AndOneStruct(StructOneI16AndOneStruct& s, const StructTwoI32& s2) noexcept { // CHECK-NEXT: return _impl::$s7Structs020inoutStructOneI16AnddC0yyAA0cdefdC0Vz_AA0C6TwoI32VtF(_impl::_impl_StructOneI16AndOneStruct::getOpaquePointer(s), _impl::swift_interop_passDirect_Structs_StructTwoI32(_impl::_impl_StructTwoI32::getOpaquePointer(s2))); // CHECK-NEXT: } // CHECK: inline StructOneI64 passThroughStructOneI64(const StructOneI64& x) noexcept SWIFT_WARN_UNUSED_RESULT { // CHECK-NEXT: return _impl::_impl_StructOneI64::returnNewValue([&](char * _Nonnull result) { // CHECK-NEXT: _impl::swift_interop_returnDirect_Structs_StructOneI64(result, _impl::$s7Structs23passThroughStructOneI64yAA0deF0VADF(_impl::swift_interop_passDirect_Structs_StructOneI64(_impl::_impl_StructOneI64::getOpaquePointer(x)))); // CHECK-NEXT: }); // CHECK-NEXT: } // CHECK: inline StructTwoI32 passThroughStructTwoI32(int32_t i, const StructTwoI32& x, int32_t j) noexcept SWIFT_WARN_UNUSED_RESULT { // CHECK-NEXT: return _impl::_impl_StructTwoI32::returnNewValue([&](char * _Nonnull result) { // CHECK-NEXT: _impl::swift_interop_returnDirect_Structs_StructTwoI32(result, _impl::$s7Structs23passThroughStructTwoI32yAA0deF0Vs5Int32V_AdFtF(i, _impl::swift_interop_passDirect_Structs_StructTwoI32(_impl::_impl_StructTwoI32::getOpaquePointer(x)), j)); // CHECK-NEXT: }); // CHECK-NEXT: } // CHECK: inline void printStructOneI64(const StructOneI64& x) noexcept { // CHECK-NEXT: return _impl::$s7Structs17printStructOneI64yyAA0cdE0VF(_impl::swift_interop_passDirect_Structs_StructOneI64(_impl::_impl_StructOneI64::getOpaquePointer(x))); // CHECK-NEXT: } // CHECK: inline void printStructStructTwoI32_and_OneI16AndOneStruct(const StructTwoI32& y, const StructOneI16AndOneStruct& x) noexcept { // CHECK-NEXT: return _impl::$s7Structs011printStructc20TwoI32_and_OneI16AndgC0yyAA0cdE0V_AA0cghigC0VtF(_impl::swift_interop_passDirect_Structs_StructTwoI32(_impl::_impl_StructTwoI32::getOpaquePointer(y)), _impl::swift_interop_passDirect_Structs_StructOneI16AndOneStruct(_impl::_impl_StructOneI16AndOneStruct::getOpaquePointer(x))); // CHECK-NEXT: } // CHECK: inline void printStructTwoI32(const StructTwoI32& x) noexcept { // CHECK-NEXT: return _impl::$s7Structs17printStructTwoI32yyAA0cdE0VF(_impl::swift_interop_passDirect_Structs_StructTwoI32(_impl::_impl_StructTwoI32::getOpaquePointer(x))); // CHECK-NEXT: } // CHECK: inline StructDoubleAndFloat returnNewStructDoubleAndFloat(float y, double x) noexcept SWIFT_WARN_UNUSED_RESULT { // CHECK-NEXT: return _impl::_impl_StructDoubleAndFloat::returnNewValue([&](char * _Nonnull result) { // CHECK-NEXT: _impl::swift_interop_returnDirect_Structs_StructDoubleAndFloat(result, _impl::$s7Structs29returnNewStructDoubleAndFloatyAA0defG0VSf_SdtF(y, x)); // CHECK-NEXT: }); // CHECK-NEXT: } // CHECK: inline StructOneI16AndOneStruct returnNewStructOneI16AndOneStruct() noexcept SWIFT_WARN_UNUSED_RESULT { // CHECK-NEXT: return _impl::_impl_StructOneI16AndOneStruct::returnNewValue([&](char * _Nonnull result) { // CHECK-NEXT: _impl::swift_interop_returnDirect_Structs_StructOneI16AndOneStruct(result, _impl::$s7Structs024returnNewStructOneI16AndeD0AA0defgeD0VyF()); // CHECK-NEXT: }); // CHECK-NEXT: } // CHECK: inline StructOneI64 returnNewStructOneI64() noexcept SWIFT_WARN_UNUSED_RESULT { // CHECK-NEXT: return _impl::_impl_StructOneI64::returnNewValue([&](char * _Nonnull result) { // CHECK-NEXT: _impl::swift_interop_returnDirect_Structs_StructOneI64(result, _impl::$s7Structs21returnNewStructOneI64AA0deF0VyF()); // CHECK-NEXT: }); // CHECK-NEXT: } // CHECK: inline StructTwoI32 returnNewStructTwoI32(int32_t x) noexcept SWIFT_WARN_UNUSED_RESULT { // CHECK-NEXT: return _impl::_impl_StructTwoI32::returnNewValue([&](char * _Nonnull result) { // CHECK-NEXT: _impl::swift_interop_returnDirect_Structs_StructTwoI32(result, _impl::$s7Structs21returnNewStructTwoI32yAA0deF0Vs5Int32VF(x)); // CHECK-NEXT: }); // CHECK-NEXT: } // CHECK: inline StructU16AndPointer returnNewStructU16AndPointer(void * _Nonnull x) noexcept SWIFT_WARN_UNUSED_RESULT { // CHECK-NEXT: return _impl::_impl_StructU16AndPointer::returnNewValue([&](char * _Nonnull result) { // CHECK-NEXT: _impl::swift_interop_returnDirect_Structs_StructU16AndPointer(result, _impl::$s7Structs28returnNewStructU16AndPointeryAA0defG0VSvF(x)); // CHECK-NEXT: }); // CHECK-NEXT: }
apache-2.0
559439397f2cc0bd1fffbb2e96c0c747
47.223301
333
0.757097
3.134743
false
false
false
false
NitWitStudios/NWSExtensions
NWSExtensions/Classes/NWSPermissionsController.swift
1
1852
// // NWSPermissionsController.swift // Pods // // Created by James Hickman on 3/14/17. // // import Foundation import CoreLocation public protocol NWSPermissionsControllerDelegate { func permissionsController(_ permissionsController: NWSPermissionsController, didAllowLocationPermission: Bool) } public class NWSPermissionsController: NSObject, CLLocationManagerDelegate { var delegate: NWSPermissionsControllerDelegate? var locationManager: CLLocationManager! var userLocation: CLLocation? var distanceFilter: Double = 1609.34 * 1.0 // Meters x Miles // MARK: - Init override init() { super.init() let locationManager = CLLocationManager() locationManager.delegate = self locationManager.distanceFilter = distanceFilter locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters self.locationManager = locationManager if CLLocationManager.authorizationStatus() == .authorizedAlways || CLLocationManager.authorizationStatus() == .authorizedWhenInUse { locationManager.startUpdatingLocation() } } // MARK: - NWSPermissionsController public func isLocationPermissionAuthorized() -> Bool { return CLLocationManager.authorizationStatus() == .authorizedWhenInUse || CLLocationManager.authorizationStatus() == .authorizedAlways } public func requestLocationPermission() { locationManager.requestWhenInUseAuthorization() } // MARK: CLLocationManagerDelegate public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { locationManager.startUpdatingLocation() delegate?.permissionsController(self, didAllowLocationPermission: status == .authorizedAlways) } }
mit
bcea6ec5c0615e06295c80754c2253c0
32.672727
142
0.722462
6.072131
false
false
false
false
kstaring/swift
benchmark/single-source/ArrayOfPOD.swift
5
1418
//===--- ArrayOfPOD.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This benchmark tests creation and destruction of an array of // trivial static type. It is meant to be a baseline for comparison against // ArrayOfGenericPOD. // // For comparison, we always create three arrays of 200,000 words. class RefArray<T> { var array : [T] init(_ i:T, count:Int = 100_000) { array = [T](repeating: i, count: count) } } @inline(never) func genIntArray() { _ = RefArray<Int>(3, count:200_000) // should be a nop } enum PODEnum { case Some(Int) init(i:Int) { self = .Some(i) } } @inline(never) func genEnumArray() { _ = RefArray<PODEnum>(PODEnum.Some(3)) // should be a nop } struct S { var x: Int var y: Int } @inline(never) func genStructArray() { _ = RefArray<S>(S(x:3, y:4)) // should be a nop } @inline(never) public func run_ArrayOfPOD(_ N: Int) { for _ in 0...N { genIntArray() genEnumArray() genStructArray() } }
apache-2.0
43b30be9f980c7f98b89566694dc9c34
21.870968
80
0.599436
3.509901
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/ChatInputView.swift
1
41609
// // ChatInputView.swift // Telegram-Mac // // Created by keepcoder on 24/09/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import TGUIKit import SwiftSignalKit import TelegramCore import TGModernGrowingTextView import Postbox protocol ChatInputDelegate : AnyObject { func inputChanged(height:CGFloat, animated:Bool); } let yInset:CGFloat = 8; class ChatInputView: View, TGModernGrowingDelegate, Notifable { private let emojiHolderAnimator = EmojiHolderAnimator() private let sendActivityDisposable = MetaDisposable() public let ready = Promise<Bool>() weak var delegate:ChatInputDelegate? let accessoryDispose:MetaDisposable = MetaDisposable() var chatInteraction:ChatInteraction let accessory:ChatInputAccessory private var _ts:View! //containers private var contentView:View! private var bottomView:NSScrollView = NSScrollView() private var messageActionsPanelView:MessageActionsPanelView? private var recordingPanelView:ChatInputRecordingView? private var blockedActionView:TitleButton? private var additionBlockedActionView: ImageButton? private var chatDiscussionView: ChannelDiscussionInputView? private var restrictedView:RestrictionWrappedView? //views private(set) var textView:TGModernGrowingTextView! private var actionsView:ChatInputActionsView! private(set) var attachView:ChatInputAttachView! private let slowModeUntilDisposable = MetaDisposable() private var replyMarkupModel:ReplyMarkupNode? override var isFlipped: Bool { return false } private var standart:CGFloat = 50.0 private var bottomHeight:CGFloat = 0 static let bottomPadding:CGFloat = 10 static let maxBottomHeight = ReplyMarkupNode.rowHeight * 3 + ReplyMarkupNode.buttonHeight / 2 private let rtfAttachmentsDisposable = MetaDisposable() private var botMenuView: ChatInputMenuView? private var sendAsView: ChatInputSendAsView? init(frame frameRect: NSRect, chatInteraction:ChatInteraction) { self.chatInteraction = chatInteraction self.accessory = ChatInputAccessory(chatInteraction:chatInteraction) super.init(frame: frameRect) self.animates = true _ts = View(frame: NSMakeRect(0, 0, NSWidth(frameRect), .borderSize)) _ts.backgroundColor = .border; contentView = View(frame: NSMakeRect(0, 0, NSWidth(frameRect), NSHeight(frameRect))) contentView.flip = false actionsView = ChatInputActionsView(frame: NSMakeRect(contentView.frame.width - 100, 0, 100, contentView.frame.height), chatInteraction:chatInteraction); attachView = ChatInputAttachView(frame: NSMakeRect(0, 0, 60, contentView.frame.height), chatInteraction:chatInteraction) contentView.addSubview(attachView) bottomView.scrollerStyle = .overlay textView = TGModernGrowingTextView(frame: NSMakeRect(attachView.frame.width, yInset, contentView.frame.width - actionsView.frame.width, contentView.frame.height - yInset * 2.0)) textView.textFont = .normal(.text) let context = self.chatInteraction.context textView.installGetAttach({ attachment, size in let rect = size.bounds.insetBy(dx: -1.5, dy: -1.5) let view = ChatInputAnimatedEmojiAttach(frame: rect) view.set(attachment, size: rect.size, context: context) return view }) contentView.addSubview(textView) contentView.addSubview(actionsView) self.background = theme.colors.background self.addSubview(accessory) self.addSubview(contentView) self.addSubview(bottomView) bottomView.documentView = View() self.addSubview(_ts) updateLocalizationAndTheme(theme: theme) } public override var responder:NSResponder? { return textView.inputView } func updateInterface(with interaction:ChatInteraction) -> Void { self.chatInteraction = interaction actionsView.prepare(with: chatInteraction) needUpdateChatState(with: chatState, false) needUpdateReplyMarkup(with: interaction.presentation, false) textView.textColor = theme.colors.text textView.selectedTextColor = theme.colors.selectText textView.linkColor = theme.colors.link textView.textFont = .normal(CGFloat(theme.fontSize)) textView.setPlaceholderAttributedString(.initialize(string: textPlaceholder, color: theme.colors.grayText, font: NSFont.normal(theme.fontSize), coreText: false), update: false) textView.delegate = self self.updateInput(interaction.presentation, prevState: ChatPresentationInterfaceState(chatLocation: interaction.chatLocation, chatMode: interaction.mode), animated: false, initial: true) updateAdditions(interaction.presentation, false) chatInteraction.add(observer: self) ready.set(accessory.nodeReady.get() |> map {_ in return true} |> take(1) ) updateLayout(size: frame.size, transition: .immediate) } private var textPlaceholder: String { if case let .thread(_, mode) = chatInteraction.mode { switch mode { case .comments: return strings().messagesPlaceholderComment case .replies: return strings().messagesPlaceholderReply case .topic: return strings().messagesPlaceholderSentMessage } } if chatInteraction.presentation.interfaceState.editState != nil { return strings().messagePlaceholderEdit } if chatInteraction.mode == .scheduled { return strings().messagesPlaceholderScheduled } if let replyMarkup = chatInteraction.presentation.keyboardButtonsMessage?.replyMarkup { if let placeholder = replyMarkup.placeholder { return placeholder } } if let peer = chatInteraction.presentation.peer { if let peer = peer as? TelegramChannel { if peer.hasPermission(.canBeAnonymous) { return strings().messagesPlaceholderAnonymous } } if peer.isChannel { return FastSettings.isChannelMessagesMuted(peer.id) ? strings().messagesPlaceholderSilentBroadcast : strings().messagesPlaceholderBroadcast } } if !chatInteraction.peerIsAccountPeer { return strings().messagesPlaceholderAnonymous } return strings().messagesPlaceholderSentMessage } override func updateLocalizationAndTheme(theme: PresentationTheme) { super.updateLocalizationAndTheme(theme: theme) let theme = (theme as! TelegramPresentationTheme) textView.setPlaceholderAttributedString(.initialize(string: textPlaceholder, color: theme.colors.grayText, font: NSFont.normal(theme.fontSize), coreText: false), update: false) _ts.backgroundColor = theme.colors.border backgroundColor = theme.colors.background contentView.backgroundColor = theme.colors.background textView.background = theme.colors.background textView.textColor = theme.colors.text textView.selectedTextColor = theme.colors.selectText actionsView.backgroundColor = theme.colors.background blockedActionView?.disableActions() textView.textFont = .normal(theme.fontSize) chatDiscussionView?.updateLocalizationAndTheme(theme: theme) blockedActionView?.style = ControlStyle(font: .normal(.title), foregroundColor: theme.colors.accent,backgroundColor: theme.colors.background, highlightColor: theme.colors.grayBackground) bottomView.backgroundColor = theme.colors.background bottomView.documentView?.background = theme.colors.background self.needUpdateReplyMarkup(with: chatInteraction.presentation, false) accessory.update(with: chatInteraction.presentation, context: chatInteraction.context, animated: false) accessory.backgroundColor = theme.colors.background accessory.container.backgroundColor = theme.colors.background textView.setBackgroundColor(theme.colors.background) } func notify(with value: Any, oldValue:Any, animated:Bool) { let transition: ContainedViewLayoutTransition if animated { transition = .animated(duration: 0.2, curve: .easeOut) } else { transition = .immediate } updateLayout(size: frame.size, transition: transition) self.actionsView.notify(with: value, oldValue: oldValue, animated: animated) if let value = value as? ChatPresentationInterfaceState, let oldValue = oldValue as? ChatPresentationInterfaceState { if value.effectiveInput != oldValue.effectiveInput { updateInput(value, prevState: oldValue, animated: animated) } updateAttachments(value,animated) var urlPreviewChanged:Bool if value.urlPreview?.0 != oldValue.urlPreview?.0 { urlPreviewChanged = true } else if let valuePreview = value.urlPreview?.1, let oldValuePreview = oldValue.urlPreview?.1 { urlPreviewChanged = !valuePreview.isEqual(to: oldValuePreview) } else if (value.urlPreview?.1 == nil) != (oldValue.urlPreview?.1 == nil) { urlPreviewChanged = true } else { urlPreviewChanged = false } urlPreviewChanged = urlPreviewChanged || value.interfaceState.composeDisableUrlPreview != oldValue.interfaceState.composeDisableUrlPreview if !isEqualMessageList(lhs: value.interfaceState.forwardMessages, rhs: oldValue.interfaceState.forwardMessages) || value.interfaceState.forwardMessageIds != oldValue.interfaceState.forwardMessageIds || value.interfaceState.replyMessageId != oldValue.interfaceState.replyMessageId || value.interfaceState.editState != oldValue.interfaceState.editState || urlPreviewChanged || value.interfaceState.hideSendersName != oldValue.interfaceState.hideSendersName || value.interfaceState.hideCaptions != oldValue.interfaceState.hideCaptions { updateAdditions(value,animated) } if value.state != oldValue.state { needUpdateChatState(with:value.state, animated) } var updateReplyMarkup = false if let lhsMessage = value.keyboardButtonsMessage, let rhsMessage = oldValue.keyboardButtonsMessage { if lhsMessage.id != rhsMessage.id || lhsMessage.stableVersion != rhsMessage.stableVersion { updateReplyMarkup = true } } else if (value.keyboardButtonsMessage == nil) != (oldValue.keyboardButtonsMessage == nil) { updateReplyMarkup = true } if !updateReplyMarkup { updateReplyMarkup = value.isKeyboardShown != oldValue.isKeyboardShown } if updateReplyMarkup { needUpdateReplyMarkup(with: value, animated) textViewHeightChanged(defaultContentHeight, animated: animated) } self.updateLayout(size: self.frame.size, transition: animated ? .animated(duration: 0.2, curve: .easeOut) : .immediate) } } func needUpdateReplyMarkup(with state:ChatPresentationInterfaceState, _ animated:Bool) { if let keyboardMessage = state.keyboardButtonsMessage, let attribute = keyboardMessage.replyMarkup, state.isKeyboardShown { replyMarkupModel = ReplyMarkupNode(attribute.rows, attribute.flags, chatInteraction.processBotKeyboard(with: keyboardMessage), theme, bottomView.documentView as? View, true) replyMarkupModel?.measureSize(frame.width - 40) replyMarkupModel?.redraw() replyMarkupModel?.layout() bottomView.contentView.scroll(to: NSZeroPoint) } } func isEqual(to other: Notifable) -> Bool { if let other = other as? ChatInputView { return other == self } return false } var chatState:ChatState { return chatInteraction.presentation.state } var defaultContentHeight:CGFloat { return chatState == .normal || chatState == .editing ? textView.frame.height : CGFloat(textView.min_height) } func needUpdateChatState(with state:ChatState, _ animated:Bool) -> Void { CATransaction.begin() if animated { textViewHeightChanged(defaultContentHeight, animated: animated) } recordingPanelView?.removeFromSuperview() recordingPanelView = nil blockedActionView?.removeFromSuperview() blockedActionView = nil additionBlockedActionView?.removeFromSuperview() additionBlockedActionView = nil chatDiscussionView?.removeFromSuperview() chatDiscussionView = nil restrictedView?.removeFromSuperview() restrictedView = nil messageActionsPanelView?.removeFromSuperview() messageActionsPanelView = nil textView.isHidden = false let chatInteraction = self.chatInteraction switch state { case .normal, .editing: self.contentView.isHidden = false self.contentView.change(opacity: 1.0, animated: animated) self.accessory.change(opacity: 1.0, animated: animated) break case .selecting: self.messageActionsPanelView = MessageActionsPanelView(frame: bounds) self.messageActionsPanelView?.prepare(with: chatInteraction) if animated { self.messageActionsPanelView?.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } self.addSubview(self.messageActionsPanelView!, positioned: .below, relativeTo: _ts) self.contentView.isHidden = true self.contentView.change(opacity: 0.0, animated: animated) self.accessory.change(opacity: 0.0, animated: animated) break case .block(_): break case let .action(text, action, addition): self.messageActionsPanelView?.removeFromSuperview() self.blockedActionView?.removeFromSuperview() self.blockedActionView = TitleButton(frame: bounds) self.blockedActionView?.style = ControlStyle(font: .normal(.title),foregroundColor: theme.colors.accent) self.blockedActionView?.set(text: text, for: .Normal) self.blockedActionView?.set(background: theme.colors.grayBackground, for: .Highlight) if animated { self.blockedActionView?.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } self.blockedActionView?.set(handler: {_ in action(chatInteraction) }, for:.Click) self.addSubview(self.blockedActionView!, positioned: .below, relativeTo: _ts) if let addition = addition { additionBlockedActionView = ImageButton() additionBlockedActionView?.animates = false additionBlockedActionView?.set(image: addition.icon, for: .Normal) additionBlockedActionView?.sizeToFit() addSubview(additionBlockedActionView!, positioned: .above, relativeTo: self.blockedActionView) additionBlockedActionView?.set(handler: { control in addition.action(control) }, for: .Click) } else { additionBlockedActionView?.removeFromSuperview() additionBlockedActionView = nil } self.contentView.isHidden = true self.contentView.change(opacity: 0.0, animated: animated) self.accessory.change(opacity: 0.0, animated: animated) case let .channelWithDiscussion(discussionGroupId, leftAction, rightAction): self.messageActionsPanelView?.removeFromSuperview() self.chatDiscussionView = ChannelDiscussionInputView(frame: bounds) self.chatDiscussionView?.update(with: chatInteraction, discussionGroupId: discussionGroupId, leftAction: leftAction, rightAction: rightAction) self.addSubview(self.chatDiscussionView!, positioned: .below, relativeTo: _ts) self.contentView.isHidden = true self.contentView.change(opacity: 0.0, animated: animated) self.accessory.change(opacity: 0.0, animated: animated) case let .recording(recorder): textView.isHidden = true recordingPanelView = ChatInputRecordingView(frame: NSMakeRect(0,0,frame.width,standart), chatInteraction:chatInteraction, recorder:recorder) addSubview(recordingPanelView!, positioned: .below, relativeTo: _ts) if animated { self.recordingPanelView?.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } case let.restricted( text): self.messageActionsPanelView?.removeFromSuperview() self.restrictedView = RestrictionWrappedView(text) if animated { self.restrictedView?.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } self.addSubview(self.restrictedView!, positioned: .below, relativeTo: _ts) self.contentView.isHidden = true self.contentView.change(opacity: 0.0, animated: animated) self.accessory.change(opacity: 0.0, animated: animated) } CATransaction.commit() } func updateInput(_ state:ChatPresentationInterfaceState, prevState: ChatPresentationInterfaceState, animated:Bool = true, initial: Bool = false) -> Void { if textView.string() != state.effectiveInput.inputText || state.effectiveInput.attributes != prevState.effectiveInput.attributes { let range = NSMakeRange(state.effectiveInput.selectionRange.lowerBound, state.effectiveInput.selectionRange.upperBound - state.effectiveInput.selectionRange.lowerBound) if !state.effectiveInput.attributes.isEmpty { var bp = 0 bp += 1 } let current = textView.attributedString().copy() as! NSAttributedString let currentRange = textView.selectedRange() let item = SimpleUndoItem(attributedString: current, be: state.effectiveInput.attributedString, wasRange: currentRange, be: range) if !initial { self.textView.addSimpleItem(item) } else { self.textView.setAttributedString(state.effectiveInput.attributedString, animated:animated) if textView.selectedRange().location != range.location || textView.selectedRange().length != range.length { textView.setSelectedRange(range) } } } if prevState.effectiveInput.inputText.isEmpty { self.textView.scrollToCursor() } if initial { self.textView.update(true) self.textViewHeightChanged(self.textView.frame.height, animated: animated) } if state.effectiveInput != prevState.effectiveInput { self.emojiHolderAnimator.apply(self.textView, chatInteraction: self.chatInteraction, current: state.effectiveInput) if state.effectiveInput.inputText.count != prevState.effectiveInput.inputText.count { self.textView.scrollToCursor() } } } private var updateFirstTime: Bool = true func updateAdditions(_ state:ChatPresentationInterfaceState, _ animated:Bool = true) -> Void { accessory.update(with: state, context: chatInteraction.context, animated: animated) accessoryDispose.set(accessory.nodeReady.get().start(next: { [weak self] animated in self?.updateAccesory(animated: animated) })) } private func updateAccesory(animated: Bool) { self.accessory.measureSize(self.frame.width - 40.0) self.textViewHeightChanged(self.defaultContentHeight, animated: animated) self.updateLayout(size: self.frame.size, transition: animated ? .animated(duration: 0.2, curve: .easeOut) : .immediate) if self.updateFirstTime { self.updateFirstTime = false self.textView.scrollToCursor() } } override func mouseUp(with event: NSEvent) { super.mouseUp(with: event) textView.setSelectedRange(NSMakeRange(textView.string().length, 0)) } func updateAttachments(_ inputState:ChatPresentationInterfaceState, _ animated:Bool = true) -> Void { if let botMenu = inputState.botMenu, !botMenu.isEmpty, inputState.interfaceState.inputState.inputText.isEmpty { let current: ChatInputMenuView if let view = self.botMenuView { current = view } else { current = ChatInputMenuView(frame: NSMakeRect(0, 0, 60, 50)) self.botMenuView = current contentView.addSubview(current) if animated { current.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) current.layer?.animateScaleSpring(from: 0.1, to: 1, duration: 0.2, bounce: false) } } current.chatInteraction = self.chatInteraction current.update(botMenu, animated: animated) } else { if let view = self.botMenuView { self.botMenuView = nil performSubviewRemoval(view, animated: animated, scale: true) } } var anim = animated if let sendAsPeers = inputState.sendAsPeers, !sendAsPeers.isEmpty && inputState.state == .normal { let current: ChatInputSendAsView if let view = self.sendAsView { current = view } else { current = ChatInputSendAsView(frame: NSMakeRect(0, 0, 50, 50)) self.sendAsView = current contentView.addSubview(current) anim = false } current.update(sendAsPeers, currentPeerId: inputState.currentSendAsPeerId ?? self.chatInteraction.context.peerId, chatInteraction: self.chatInteraction, animated: animated) } else { if let view = self.sendAsView { self.sendAsView = nil performSubviewRemoval(view, animated: animated) } } updateLayout(size: frame.size, transition: anim ? .animated(duration: 0.2, curve: .easeOut) : .immediate) } func updateLayout(size: NSSize, transition: ContainedViewLayoutTransition) { let bottomInset = chatInteraction.presentation.isKeyboardShown ? bottomHeight : 0 let keyboardWidth = frame.width - 40 var leftInset: CGFloat = 0 transition.updateFrame(view: contentView, frame: NSMakeRect(0, bottomInset, frame.width, contentView.frame.height)) transition.updateFrame(view: bottomView, frame: NSMakeRect(20, chatInteraction.presentation.isKeyboardShown ? 0 : -bottomHeight, keyboardWidth, bottomHeight)) let actionsSize = actionsView.size(chatInteraction.presentation) let immediate: ContainedViewLayoutTransition = .immediate immediate.updateFrame(view: actionsView, frame: CGRect(origin: CGPoint(x: size.width - actionsSize.width, y: 0), size: actionsSize)) actionsView.updateLayout(size: actionsSize, transition: immediate) if let view = botMenuView { leftInset += view.frame.width transition.updateFrame(view: view, frame: NSMakeRect(0, 0, view.frame.width, view.frame.height)) } if let view = sendAsView { leftInset += view.frame.width transition.updateFrame(view: view, frame: NSMakeRect(0, 0, view.frame.width, view.frame.height)) } if let markup = replyMarkupModel, markup.hasButtons, let view = markup.view { markup.measureSize(keyboardWidth) transition.updateFrame(view: view, frame: NSMakeRect(0, 0, markup.size.width, markup.size.height)) markup.layout(transition: transition) } transition.updateFrame(view: attachView, frame: NSMakeRect(leftInset, 0, attachView.frame.width, attachView.frame.height)) leftInset += attachView.frame.width let textSize = textViewSize(textView) transition.updateFrame(view: textView, frame: NSMakeRect(leftInset, yInset, textSize.width, textSize.height)) if let view = additionBlockedActionView { transition.updateFrame(view: view, frame: view.centerFrameY(x: size.width - view.frame.width - 22)) } transition.updateFrame(view: _ts, frame: NSMakeRect(0, size.height - .borderSize, size.width, .borderSize)) accessory.measureSize(size.width - 64) transition.updateFrame(view: accessory, frame: NSMakeRect(15, contentView.frame.maxY, size.width - 39, accessory.size.height)) accessory.updateLayout(NSMakeSize(size.width - 39, accessory.size.height), transition: transition) if let view = messageActionsPanelView { transition.updateFrame(view: view, frame: bounds) } if let view = blockedActionView { transition.updateFrame(view: view, frame: bounds) } if let view = chatDiscussionView { transition.updateFrame(view: view, frame: bounds) } if let view = restrictedView { transition.updateFrame(view: view, frame: bounds) } guard let superview = superview else {return} textView.max_height = Int32(superview.frame.height / 2 + 50) } /* if textView.placeholderAttributedString?.string != self.textPlaceholder { textView.setPlaceholderAttributedString(.initialize(string: textPlaceholder, color: theme.colors.grayText, font: NSFont.normal(theme.fontSize), coreText: false), update: false) } */ override func layout() { super.layout() self.updateLayout(size: self.frame.size, transition: .immediate) } var stringValue:String { return textView.string() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } private var previousHeight:CGFloat = 0 func textViewHeightChanged(_ height: CGFloat, animated: Bool) { let contentHeight:CGFloat = defaultContentHeight + yInset * 2.0 var sumHeight:CGFloat = contentHeight + (accessory.isVisibility() ? accessory.size.height + 5 : 0) if let markup = replyMarkupModel { bottomHeight = min( ChatInputView.maxBottomHeight, markup.size.height + ChatInputView.bottomPadding ) } else { bottomHeight = 0 } if chatInteraction.presentation.isKeyboardShown { sumHeight += bottomHeight } if previousHeight != sumHeight { previousHeight = sumHeight let bottomInset = chatInteraction.presentation.isKeyboardShown ? bottomHeight : 0 _ts.change(pos: NSMakePoint(0, sumHeight - .borderSize), animated: animated) contentView.change(size: NSMakeSize(NSWidth(frame), contentHeight), animated: animated) contentView.change(pos: NSMakePoint(0, bottomInset), animated: animated) bottomView._change(size: NSMakeSize(frame.width - 40, bottomHeight), animated: animated) bottomView._change(pos: NSMakePoint(20, chatInteraction.presentation.isKeyboardShown ? 0 : -bottomHeight), animated: animated) accessory.change(opacity: accessory.isVisibility() ? 1.0 : 0.0, animated: animated) accessory.change(pos: NSMakePoint(15, contentHeight + bottomHeight), animated: animated) change(size: NSMakeSize(NSWidth(frame), sumHeight), animated: animated) delegate?.inputChanged(height: sumHeight, animated: animated) } } public func textViewEnterPressed(_ event: NSEvent) -> Bool { if FastSettings.checkSendingAbility(for: event) { let text = textView.string().trimmed let context = chatInteraction.context if text.length > chatInteraction.maxInputCharacters { if context.isPremium || context.premiumIsBlocked { alert(for: context.window, info: strings().chatInputErrorMessageTooLongCountable(text.length - Int(chatInteraction.maxInputCharacters))) } else { confirm(for: context.window, information: strings().chatInputErrorMessageTooLongCountable(text.length - Int(chatInteraction.maxInputCharacters)), okTitle: strings().alertOK, cancelTitle: "", thridTitle: strings().premiumGetPremiumDouble, successHandler: { result in switch result { case .thrid: showPremiumLimit(context: context, type: .caption(text.length)) default: break } }) } return true } if !text.isEmpty || !chatInteraction.presentation.interfaceState.forwardMessageIds.isEmpty || chatInteraction.presentation.state == .editing { chatInteraction.sendMessage(false, nil) if self.chatInteraction.peerIsAccountPeer { chatInteraction.context.account.updateLocalInputActivity(peerId: chatInteraction.activitySpace, activity: .typingText, isPresent: false) } markNextTextChangeToFalseActivity = true } else if text.isEmpty { chatInteraction.scrollToLatest(true) } return true } return false } var currentActionView: NSView { return self.actionsView.currentActionView } var emojiView: NSView { return self.actionsView.entertaiments } func makeSpoiler() { self.textView.spoilerWord() } func makeUnderline() { self.textView.underlineWord() } func makeStrikethrough() { self.textView.strikethroughWord() } func makeBold() { self.textView.boldWord() } func removeAllAttributes() { self.textView.removeAllAttributes() } func makeUrl() { self.makeUrl(of: textView.selectedRange()) } func makeItalic() { self.textView.italicWord() } func makeMonospace() { self.textView.codeWord() } override func becomeFirstResponder() -> Bool { return self.textView.becomeFirstResponder() } func makeFirstResponder() { self.window?.makeFirstResponder(self.textView.inputView) } private var previousString: String = "" func textViewTextDidChange(_ string: String) { let attributed = self.textView.attributedString() let range = self.textView.selectedRange() let state = ChatTextInputState(inputText: attributed.string, selectionRange: range.location ..< range.location + range.length, attributes: chatTextAttributes(from: attributed)) chatInteraction.update({$0.withUpdatedEffectiveInputState(state)}) } func canTransformInputText() -> Bool { return true } private var markNextTextChangeToFalseActivity: Bool = false public func textViewTextDidChangeSelectedRange(_ range: NSRange) { let attributed = self.textView.attributedString() let attrs = chatTextAttributes(from: attributed) let state = ChatTextInputState(inputText: attributed.string, selectionRange: range.min ..< range.max, attributes: attrs) chatInteraction.update({ current in var current = current current = current.withUpdatedEffectiveInputState(state) if let disabledPreview = current.interfaceState.composeDisableUrlPreview { if !current.effectiveInput.inputText.contains(disabledPreview) { var detectedUrl: String? current.effectiveInput.attributedString.enumerateAttribute(NSAttributedString.Key(rawValue: TGCustomLinkAttributeName), in: current.effectiveInput.attributedString.range, options: NSAttributedString.EnumerationOptions(rawValue: 0), using: { (value, range, stop) in if let tag = value as? TGInputTextTag, let url = tag.attachment as? String { detectedUrl = url } let s: ObjCBool = (detectedUrl != nil) ? true : false stop.pointee = s }) if detectedUrl == nil { current = current.updatedUrlPreview(nil).updatedInterfaceState {$0.withUpdatedComposeDisableUrlPreview(nil)} } } } return current }) if chatInteraction.context.peerId != chatInteraction.peerId, let peer = chatInteraction.presentation.peer, !peer.isChannel && !markNextTextChangeToFalseActivity { sendActivityDisposable.set((Signal<Bool, NoError>.single(!state.inputText.isEmpty) |> then(Signal<Bool, NoError>.single(false) |> delay(4.0, queue: Queue.mainQueue()))).start(next: { [weak self] isPresent in if let chatInteraction = self?.chatInteraction, let peer = chatInteraction.presentation.peer, !peer.isChannel && chatInteraction.presentation.state != .editing { if self?.chatInteraction.peerIsAccountPeer == true { chatInteraction.context.account.updateLocalInputActivity(peerId: .init(peerId: peer.id, category: chatInteraction.mode.activityCategory), activity: .typingText, isPresent: isPresent) } } })) } markNextTextChangeToFalseActivity = false } deinit { chatInteraction.remove(observer: self) self.accessoryDispose.dispose() rtfAttachmentsDisposable.dispose() slowModeUntilDisposable.dispose() } func textViewSize(_ textView: TGModernGrowingTextView!) -> NSSize { var leftInset: CGFloat = attachView.frame.width if let botMenu = self.botMenuView { leftInset += botMenu.frame.width } if let sendAsView = self.sendAsView { leftInset += sendAsView.frame.width } let size = NSMakeSize(contentView.frame.width - actionsView.size(chatInteraction.presentation).width - leftInset, textView.frame.height) return size } func textViewIsTypingEnabled() -> Bool { if let editState = chatInteraction.presentation.interfaceState.editState { if editState.loadingState != .none { return false } } return self.chatState == .normal || self.chatState == .editing } func makeUrl(of range: NSRange) { guard range.min != range.max, let window = kitWindow else { return } var effectiveRange:NSRange = NSMakeRange(NSNotFound, 0) let defaultTag: TGInputTextTag? = self.textView.attributedString().attribute(NSAttributedString.Key(rawValue: TGCustomLinkAttributeName), at: range.location, effectiveRange: &effectiveRange) as? TGInputTextTag let defaultUrl = defaultTag?.attachment as? String if effectiveRange.location == NSNotFound || defaultTag == nil { effectiveRange = range } showModal(with: InputURLFormatterModalController(string: self.textView.string().nsstring.substring(with: effectiveRange), defaultUrl: defaultUrl, completion: { [weak self] url in self?.textView.addLink(url, range: effectiveRange) }), for: window) } func maxCharactersLimit(_ textView: TGModernGrowingTextView!) -> Int32 { return ChatInteraction.maxInput } @available(OSX 10.12.2, *) func textView(_ textView: NSTextView!, shouldUpdateTouchBarItemIdentifiers identifiers: [NSTouchBarItem.Identifier]!) -> [NSTouchBarItem.Identifier]! { return inputChatTouchBarItems(presentation: chatInteraction.presentation) } func supportContinuityCamera() -> Bool { return true } func copyText(withRTF rtf: NSAttributedString!) -> Bool { return globalLinkExecutor.copyAttributedString(rtf) } func textViewDidPaste(_ pasteboard: NSPasteboard) -> Bool { if let window = kitWindow, self.chatState == .normal || self.chatState == .editing { if let string = pasteboard.string(forType: .string) { chatInteraction.update { current in if let disabled = current.interfaceState.composeDisableUrlPreview, disabled.lowercased() == string.lowercased() { return current.updatedInterfaceState {$0.withUpdatedComposeDisableUrlPreview(nil)} } return current } } let result = InputPasteboardParser.proccess(pasteboard: pasteboard, chatInteraction:self.chatInteraction, window: window) if result { if let data = pasteboard.data(forType: .kInApp) { let decoder = AdaptedPostboxDecoder() if let decoded = try? decoder.decode(ChatTextInputState.self, from: data) { let attributed = decoded.unique(isPremium: chatInteraction.context.isPremium).attributedString let current = textView.attributedString().copy() as! NSAttributedString let currentRange = textView.selectedRange() let (attributedString, range) = current.appendAttributedString(attributed, selectedRange: currentRange) let item = SimpleUndoItem(attributedString: current, be: attributedString, wasRange: currentRange, be: range) self.textView.addSimpleItem(item) DispatchQueue.main.async { [weak self] in self?.textView.scrollToCursor() } return true } } else if let data = pasteboard.data(forType: .rtf) { if let attributed = (try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtfd], documentAttributes: nil)) ?? (try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)) { let (attributed, attachments) = attributed.applyRtf() if !attachments.isEmpty { rtfAttachmentsDisposable.set((prepareTextAttachments(attachments) |> deliverOnMainQueue).start(next: { [weak self] urls in if !urls.isEmpty, let chatInteraction = self?.chatInteraction { chatInteraction.showPreviewSender(urls, true, attributed) } })) } else { let current = textView.attributedString().copy() as! NSAttributedString let currentRange = textView.selectedRange() let (attributedString, range) = current.appendAttributedString(attributed, selectedRange: currentRange) let item = SimpleUndoItem(attributedString: current, be: attributedString, wasRange: currentRange, be: range) self.textView.addSimpleItem(item) } DispatchQueue.main.async { [weak self] in self?.textView.scrollToCursor() } return true } } } return !result } return self.chatState != .normal } }
gpl-2.0
1a426451f717854502e5a8e9e962b3c6
43.452991
545
0.62947
5.258847
false
false
false
false
jxxcarlson/exploring_swift
stackMachine.playground/Sources/StackMachine.swift
1
3138
public class StackMachine { let ops = ["add", "mul", "sub", "div"] var prog: [String] var instructionPointer = 0 var error = "" var stack = Stack<String>() public init(program: String) { prog = program.componentsSeparatedByString(" ") stack = Stack() } func load(program: String) { prog = program.componentsSeparatedByString(" ") stack = Stack() instructionPointer = 0 error = "" } public func stringValue() -> String { var output = "stack: " if stack.count > 0 { for(var i = 0; i < stack.count - 1; i++) { output += stack[i] + ", " } output += stack[stack.count - 1] } output += " - prog: " for(var i = instructionPointer; i < prog.count; i++) { output += prog[i] + ", " } return output } func executeAdd() { if stack.count >= 2 { let operand1 = stack.pop().doubleValue() let operand2 = stack.pop().doubleValue() let result = operand1 + operand2 stack.push(String(result)) } else { error = "add" } } func executeMul() { if stack.count >= 2 { let operand1 = stack.pop().doubleValue() let operand2 = stack.pop().doubleValue() let result = operand1 * operand2 stack.push(String(result)) } else { error = "mul" } } func executeSub() { if stack.count >= 2 { let operand1 = stack.pop().doubleValue() let operand2 = stack.pop().doubleValue() let result = operand2 - operand1 stack.push(String(result)) } else { error = "sub" } } func executeDiv() { if stack.count >= 2 { let operand1 = stack.pop().doubleValue() let operand2 = stack.pop().doubleValue() if operand1 != 0 { let result = operand2 / operand1 stack.push(String(result)) } else { error = "division by zero" } } else { error = "div" } } func execute(instruction: String) { switch instruction { case "add": executeAdd() case "mul": executeMul() case "sub": executeSub() case "div": executeDiv() default: print("Done") } } public func step() { let item = prog[instructionPointer] if ops.contains(item) { execute(item) } else { stack.push(item) } instructionPointer++ print(stringValue()) } public func run() -> String { while instructionPointer < prog.count && error == "" { step() } return stack.top } }
mit
ca3e9aa823c56bc23f0772dcf200e360
22.073529
63
0.441045
4.79084
false
false
false
false
omarojo/MyC4FW
Pods/C4/C4/UI/Filters/GaussianBlur.swift
2
2147
// Copyright © 2014 C4 // // 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 CoreImage /// Spreads source pixels by an amount specified by a Gaussian distribution. /// /// ```` /// let logo = Image("logo") /// logo.apply(GaussianBlur()) /// canvas.add(logo) /// ```` public struct GaussianBlur: Filter { /// The name of the Core Image filter. public let filterName = "CIGaussianBlur" /// The radius of the blur. Defaults to 10.0 public var radius: Double /// Initializes a new filter /// - parameter radius: a Double value public init(radius: Double = 5.0) { self.radius = radius } /// Applies the properties of the receiver to create a new CIFilter object /// /// - parameter inputImage: The image to use as input to the filter. /// - returns: The new CIFilter object. public func createCoreImageFilter(_ inputImage: CIImage) -> CIFilter { let filter = CIFilter(name: filterName)! filter.setDefaults() filter.setValue(radius, forKey:"inputRadius") filter.setValue(inputImage, forKey: "inputImage") return filter } }
mit
6c4505a6c0cecd96326bf63a0ede8efa
41.078431
79
0.71109
4.527426
false
false
false
false
TimeFaceCoder/FastTableView
FastTableView/Factories.swift
1
6028
// // Factories.swift // FastTableView // // Created by René Cacheaux on 10/11/14. // Copyright (c) 2014 Razeware LLC. All rights reserved. // import Foundation import UIKit extension NSAttributedString { class func attributedStringForNickName(text :String) -> NSAttributedString { let nickNameAttributes = [NSFontAttributeName: UIFont.boldSystemFontOfSize(16), NSForegroundColorAttributeName: UIColor(red: 61/255, green: 176/255, blue: 232/255, alpha: 1), NSBackgroundColorAttributeName: UIColor.clearColor(), NSParagraphStyleAttributeName: NSParagraphStyle.justifiedParagraphStyle()] return NSAttributedString(string: text, attributes: nickNameAttributes) } class func attributedStringForTimeFrom(text :String) -> NSAttributedString { let timeAttributes = [NSFontAttributeName: UIFont.boldSystemFontOfSize(10), NSForegroundColorAttributeName: UIColor(red: 153/255, green: 153/255, blue: 153/255, alpha: 1), NSBackgroundColorAttributeName: UIColor.clearColor()] return NSAttributedString(string: text, attributes: timeAttributes) } class func attributedStringForTitleText(text: String) -> NSAttributedString { let titleAttributes = [NSFontAttributeName: UIFont.boldSystemFontOfSize(16), NSForegroundColorAttributeName: UIColor.blackColor(), NSBackgroundColorAttributeName: UIColor.clearColor(), NSParagraphStyleAttributeName: NSParagraphStyle.justifiedParagraphStyle()] return NSAttributedString(string: text, attributes: titleAttributes) } class func attributedStringForContentText(text: String) -> NSAttributedString { let font = UIFont.systemFontOfSize(16) let descriptionAttributes = [NSFontAttributeName:font, NSForegroundColorAttributeName: UIColor.blackColor(), NSBackgroundColorAttributeName: UIColor.clearColor(), NSParagraphStyleAttributeName: NSParagraphStyle.contentParagraphStyle(font)] return NSAttributedString(string: text, attributes: descriptionAttributes) } class func attributedStringForBookTitle(text :String) -> NSAttributedString { let timeAttributes = [NSFontAttributeName: UIFont.boldSystemFontOfSize(14), NSForegroundColorAttributeName: UIColor(red: 153/255, green: 153/255, blue: 153/255, alpha: 1), NSBackgroundColorAttributeName: UIColor.clearColor()] return NSAttributedString(string: text, attributes: timeAttributes) } class func attributedStringForLikeNode(text :String) -> NSAttributedString { let font = UIFont.systemFontOfSize(14) let likeAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor(red: 153/255, green: 153/255, blue: 153/255, alpha: 1), NSBackgroundColorAttributeName: UIColor.clearColor(), NSParagraphStyleAttributeName: NSParagraphStyle.likeParagraphStyle(font)] let image = UIImage(named: "TimeLineLike") let likeAttributeString = NSMutableAttributedString(string: text, attributes: likeAttributes) let textAttachment = NSTextAttachment() textAttachment.image = image likeAttributeString.replaceCharactersInRange(NSMakeRange(0, 3), withAttributedString: NSAttributedString(attachment: textAttachment)) return likeAttributeString } class func attributedStringForCommentNode(text :String) -> NSAttributedString { let font = UIFont.systemFontOfSize(14) let commentAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor(red: 153/255, green: 153/255, blue: 153/255, alpha: 1), NSBackgroundColorAttributeName: UIColor.clearColor(), NSParagraphStyleAttributeName: NSParagraphStyle.likeParagraphStyle(font)] let image = UIImage(named: "TimeLineComment") let commentAttributeString = NSMutableAttributedString(string: text, attributes: commentAttributes) let textAttachment = NSTextAttachment() textAttachment.image = image commentAttributeString.replaceCharactersInRange(NSMakeRange(0, 3), withAttributedString: NSAttributedString(attachment: textAttachment)) return commentAttributeString } } extension NSParagraphStyle { class func justifiedParagraphStyle() -> NSParagraphStyle { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .Justified return paragraphStyle.copy() as! NSParagraphStyle } class func contentParagraphStyle(font: UIFont) -> NSParagraphStyle { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .Justified paragraphStyle.lineSpacing = 6 paragraphStyle.paragraphSpacing = 6 paragraphStyle.maximumLineHeight = font.lineHeight paragraphStyle.minimumLineHeight = font.lineHeight return paragraphStyle.copy() as! NSParagraphStyle } class func likeParagraphStyle(font: UIFont) -> NSParagraphStyle { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .Justified paragraphStyle.maximumLineHeight = font.lineHeight paragraphStyle.minimumLineHeight = font.lineHeight return paragraphStyle.copy() as! NSParagraphStyle } } extension NSShadow { class func titleTextShadow() -> NSShadow { let shadow = NSShadow() shadow.shadowColor = UIColor(hue: 0, saturation: 0, brightness: 0, alpha: 0.3) shadow.shadowOffset = CGSize(width: 0, height: 2) shadow.shadowBlurRadius = 3.0 return shadow } class func descriptionTextShadow() -> NSShadow { let shadow = NSShadow() shadow.shadowColor = UIColor(white: 0.0, alpha: 0.3) shadow.shadowOffset = CGSize(width: 0, height: 1) shadow.shadowBlurRadius = 3.0 return shadow } }
mit
ae268938074de9655f538232e5ec6dd3
46.456693
144
0.710967
5.789625
false
false
false
false
tinyfool/GoodMorning
GoodMorning/GoodMorning/GoodMorning/BaseViewController.swift
1
1479
// // BaseViewController.swift // GoodMorning // // Created by pei hao on 3/16/15. // Copyright (c) 2015 pei hao. All rights reserved. // import UIKit import AVFoundation class BaseViewController: UIViewController,AVSpeechSynthesizerDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func speak(words:String) { var synthesizer = AVSpeechSynthesizer(); var utterance = AVSpeechUtterance(string: ""); utterance = AVSpeechUtterance(string:words); utterance.voice = AVSpeechSynthesisVoice(language:"zh-CN"); utterance.rate = 0.1; synthesizer.delegate = self synthesizer.speakUtterance(utterance); } func speechSynthesizer(synthesizer: AVSpeechSynthesizer!, didFinishSpeechUtterance utterance: AVSpeechUtterance!) { //self.parentViewController } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
42920cff4e19899c5c6963c6578869c5
27.442308
119
0.676133
5.263345
false
false
false
false
grpc/grpc-swift
Performance/allocations/tests/test_bidi_1k_rpcs.swift
1
2594
/* * Copyright 2021, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Dispatch import GRPC import NIO class BidiPingPongBenchmark: Benchmark { let rpcs: Int let requests: Int let request: Echo_EchoRequest private var group: EventLoopGroup! private var server: Server! private var client: ClientConnection! init(rpcs: Int, requests: Int, request: String) { self.rpcs = rpcs self.requests = requests self.request = .with { $0.text = request } } func setUp() throws { self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1) self.server = try makeEchoServer(group: self.group).wait() self.client = makeClientConnection( group: self.group, port: self.server.channel.localAddress!.port! ) } func tearDown() throws { try self.client.close().wait() try self.server.close().wait() try self.group.syncShutdownGracefully() } func run() throws -> Int { let echo = Echo_EchoNIOClient(channel: self.client) var statusCodeSum = 0 // We'll use this semaphore to make sure we're ping-ponging request-response // pairs on the RPC. Doing so makes the number of allocations much more // stable. let waiter = DispatchSemaphore(value: 1) for _ in 0 ..< self.rpcs { let update = echo.update { _ in waiter.signal() } for _ in 0 ..< self.requests { waiter.wait() update.sendMessage(self.request, promise: nil) } waiter.wait() update.sendEnd(promise: nil) let status = try update.status.wait() statusCodeSum += status.code.rawValue waiter.signal() } return statusCodeSum } } func run(identifier: String) { measure(identifier: identifier + "_10_requests") { let benchmark = BidiPingPongBenchmark(rpcs: 1000, requests: 10, request: "") return try! benchmark.runOnce() } measure(identifier: identifier + "_1_request") { let benchmark = BidiPingPongBenchmark(rpcs: 1000, requests: 1, request: "") return try! benchmark.runOnce() } }
apache-2.0
9597298a88bc0f45f2df45015b5c8e96
27.822222
80
0.679645
4.009274
false
false
false
false
sbanil/VideoBrowser
VideoBrowser/MasterViewController.swift
1
4104
// // MasterViewController.swift // VideoBrowser // // Created by Sanghubattla, Anil on 10/18/15. // Copyright © 2015 teamcakes. All rights reserved. // import UIKit import CoreData class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var managedObjectContext: NSManagedObjectContext? = nil var videos : Array<VideoModel> = [] override func viewDidLoad() { super.viewDidLoad() self.loadDataFromJsonFile() //self.loadDataOverNetwork() } @IBAction func refreshData(sender: AnyObject) { self.loadDataFromJsonFile() //self.loadDataOverNetwork() } func loadDataFromJsonFile() { if let path = NSBundle.mainBundle().pathForResource("VideoData", ofType: "json") { do { if let jsonData = try? NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe) { let jarr = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as! NSArray for obj in jarr { if let v = obj as? NSDictionary { let vbo = VideoModel(json: v) videos.append(vbo!) } } } } catch { //TODO: Add error handling here } } } func loadDataOverNetwork() { let onSuccess: (NSArray) -> Void = { (videolist) in for obj in videolist { if let v = obj as? NSDictionary { let vbo = VideoModel(json: v) self.videos.append(vbo!) } } self.tableView.reloadData() }; let onFailure: (errorDesc: String) -> Void = { (errString) in print(errString) }; ServiceHelper().retrieveVideoList(onSuccess, OnFailure: onFailure); } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } // MARK: - Table View override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return videos.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) self.configureCell(cell, atIndexPath: indexPath) return cell } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let object = videos[indexPath.item] let customCell = cell as! VideoListcell customCell.videoLength.text = (String(object.videoLength) + (object.videoLength > 1 ? " Second" : " Seconds")) customCell.videoName.text = object.videoName customCell.videoPreview.image = object.posterImage } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = videos[indexPath.item] let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } }
apache-2.0
d91f5295117c9e6678c5aeef4074823f
31.054688
145
0.563734
5.861429
false
false
false
false
barteljan/VISPER
VISPER/Classes/Deprecated/Wireframe/RoutingPresenterWrapper.swift
1
3706
// // RoutingPresenterWrapper.swift // // Created by bartel on 28.12.17. // import Foundation import VISPER_Core class RoutingPresenterWrapper: NSObject,IVISPERRoutingPresenter { let presenter: RoutingPresenter? let wireframe: VISPERWireframe init( presenter: RoutingPresenter?, wireframe: VISPERWireframe){ self.presenter = presenter self.wireframe = wireframe } func isResponsible(for routingOption: IVISPERRoutingOption!) -> Bool { guard let presenter = self.presenter else { return false } let option = try! VISPERWireframe.routingOption(visperRoutingOption: routingOption) let result = RouteResultWrapper(routePattern: "", routingOption: option, parameters: [:]) return presenter.isResponsible(routeResult: result) } func route(forPattern routePattern: String!, controller: UIViewController!, options: IVISPERRoutingOption!, parameters: [AnyHashable : Any]!, on wireframe: IVISPERWireframe!, completion: ((String?, UIViewController?, IVISPERRoutingOption?, [AnyHashable : Any]?, IVISPERWireframe?) -> Void)!) { guard let presenter = self.presenter else { completion(routePattern, controller, options, parameters, wireframe) return } let option = try! VISPERWireframe.routingOption(visperRoutingOption: options) let routeResult = RouteResultWrapper(routePattern: routePattern, routingOption: option, parameters: self.convert(dict: parameters)) try! presenter.present(controller: controller, routeResult: routeResult, wireframe: self.wireframe.wireframe.wireframe, delegate: FakeRoutingDelegate(), completion: { completion(routePattern, controller, options, parameters, wireframe) }) } func convert(dict: [AnyHashable : Any]) -> [String : Any] { var result = [String : Any]() for key in dict.keys { if let key = key as? String { result[key] = dict[key] } } return result } struct RouteResultWrapper: RouteResult { var routePattern: String var routingOption: RoutingOption? var parameters: [String : Any] } struct FakeRoutingDelegate: RoutingDelegate { var routingObserver: RoutingObserver? public init(){ self.routingObserver = nil } func willPresent(controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe) throws { } func didPresent(controller: UIViewController, routeResult: RouteResult, routingPresenter: RoutingPresenter?, wireframe: Wireframe) { } } }
mit
0e001df8e4181e5ae896e8e379848909
32.690909
146
0.496492
6.559292
false
false
false
false
austinzheng/swift
test/Interpreter/collection_casts.swift
29
3145
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -o %t/main // RUN: %target-build-swift %s -o %t/main-optimized // RUN: %target-codesign %t/main // RUN: %target-codesign %t/main-optimized // RUN: %target-run %t/main | %FileCheck %s // RUN: %target-run %t/main-optimized | %FileCheck %s // REQUIRES: executable_test protocol Preening { func preen() } struct A : Preening, Hashable, Equatable { private var value: Int init(_ value: Int) { self.value = value } func preen() { print("A\(value)") } static func ==(lhs: A, rhs: A) -> Bool { return lhs.value == rhs.value } func hash(into hasher: inout Hasher) { hasher.combine(value) } } do { print("Arrays.") // CHECK: Arrays. let a_array = [ A(5), A(10), A(20) ] a_array.forEach { $0.preen() } // CHECK-NEXT: A5 // CHECK-NEXT: A10 // CHECK-NEXT: A20 let preening_array_1 = a_array as [Preening] preening_array_1.forEach { $0.preen() } // CHECK-NEXT: A5 // CHECK-NEXT: A10 // CHECK-NEXT: A20 let any_array_1 = preening_array_1 as [Any] print(any_array_1.count) // CHECK-NEXT: 3 let preening_array_2 = any_array_1 as! [Preening] preening_array_2.forEach { $0.preen() } // CHECK-NEXT: A5 // CHECK-NEXT: A10 // CHECK-NEXT: A20 let preening_array_3 = any_array_1 as? [Preening] preening_array_3?.forEach { $0.preen() } // CHECK-NEXT: A5 // CHECK-NEXT: A10 // CHECK-NEXT: A20 let a_array_2 = any_array_1 as! [A] a_array_2.forEach { $0.preen() } // CHECK-NEXT: A5 // CHECK-NEXT: A10 // CHECK-NEXT: A20 let a_array_3 = any_array_1 as? [Preening] a_array_3?.forEach { $0.preen() } // CHECK-NEXT: A5 // CHECK-NEXT: A10 // CHECK-NEXT: A20 } do { print("Dictionaries.") // CHECK-NEXT: Dictionaries. let a_dict = ["one" : A(1), "two" : A(2), "three" : A(3)] print("begin") a_dict.forEach { $0.1.preen() } print("end") // CHECK-NEXT: begin // CHECK-DAG: A1 // CHECK-DAG: A2 // CHECK-DAG: A3 // CHECK-NEXT: end let preening_dict_1 = a_dict as [String: Preening] print("begin") preening_dict_1.forEach { $0.1.preen() } print("end") // CHECK-NEXT: begin // CHECK-DAG: A1 // CHECK-DAG: A2 // CHECK-DAG: A3 // CHECK-NEXT: end let any_dict_1 = preening_dict_1 as [String: Any] print(any_dict_1.count) // CHECK-NEXT: 3 let preening_dict_2 = any_dict_1 as! [String: Preening] print("begin") preening_dict_2.forEach { $0.1.preen() } print("end") // CHECK-NEXT: begin // CHECK-DAG: A1 // CHECK-DAG: A2 // CHECK-DAG: A3 // CHECK-NEXT: end let preening_dict_3 = any_dict_1 as? [String: Preening] print("begin") preening_dict_3?.forEach { $0.1.preen() } print("end") // CHECK-NEXT: begin // CHECK-DAG: A1 // CHECK-DAG: A2 // CHECK-DAG: A3 // CHECK-NEXT: end let a_dict_2 = any_dict_1 as! [String: A] print("begin") a_dict_2.forEach { $0.1.preen() } print("end") // CHECK-NEXT: begin // CHECK-DAG: A1 // CHECK-DAG: A2 // CHECK-DAG: A3 // CHECK-NEXT: end let a_dict_3 = any_dict_1 as? [String: A] print("begin") a_dict_3?.forEach { $0.1.preen() } print("end") // CHECK-NEXT: begin // CHECK-DAG: A1 // CHECK-DAG: A2 // CHECK-DAG: A3 // CHECK-NEXT: end } // TODO: I can't think of any way to do this for sets and dictionary // keys that doesn't involve bridging.
apache-2.0
745c7e14398d97d4b96fd3bc68261b83
19.966667
68
0.634658
2.472484
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Source/CourseGenericBlockTableViewCell.swift
3
2773
// // CourseHTMLTableViewCell.swift // edX // // Created by Ehmad Zubair Chughtai on 14/05/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit class CourseGenericBlockTableViewCell : UITableViewCell, CourseBlockContainerCell { private let content = CourseOutlineItemView() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(content) content.snp_makeConstraints { (make) -> Void in make.edges.equalTo(contentView) } } var block : CourseBlock? = nil { didSet { content.setTitleText(block?.displayName) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class CourseHTMLTableViewCell: CourseGenericBlockTableViewCell { static let identifier = "CourseHTMLTableViewCellIdentifier" override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style : style, reuseIdentifier : reuseIdentifier) content.setContentIcon(Icon.CourseHTMLContent) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class CourseProblemTableViewCell : CourseGenericBlockTableViewCell { static let identifier = "CourseProblemTableViewCellIdentifier" override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style : style, reuseIdentifier : reuseIdentifier) content.setContentIcon(Icon.CourseProblemContent) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class CourseUnknownTableViewCell: CourseGenericBlockTableViewCell { static let identifier = "CourseUnknownTableViewCellIdentifier" override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) content.leadingIconColor = OEXStyles.sharedStyles().neutralBase() content.setContentIcon(Icon.CourseUnknownContent) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class DiscussionTableViewCell: CourseGenericBlockTableViewCell { static let identifier = "DiscussionTableViewCellIdentifier" override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) content.setContentIcon(Icon.Discussions) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
a8b3b68b02966a41d4e528f2930b6846
29.472527
83
0.704652
5.202627
false
false
false
false
Why51982/SLDouYu
SLDouYu/SLDouYu/Classes/Main/Controller/SLBaseAnchorViewController.swift
1
5760
// // SLBaseAnchorViewController.swift // SLDouYu // // Created by CHEUNGYuk Hang Raymond on 2016/10/31. // Copyright © 2016年 CHEUNGYuk Hang Raymond. All rights reserved. // import UIKit //MARK: - 定义常量 private let kItemMargin: CGFloat = 10 private let kItemW: CGFloat = (kScreenW - 3 * kItemMargin) / 2 private let kNormalItemH: CGFloat = kItemW * 3 / 4 private let kPrettyItemH: CGFloat = kItemW * 4 / 3 private let kHeaderViewH: CGFloat = 50 private let kCycleViewH: CGFloat = kScreenW * 3 / 8 private let kGameViewH: CGFloat = 90 private let kNormalCellReuseIdentifier = "kNormalCellReuseIdentifier" private let kPrettyCellReuseIdentifier = "kPrettyCellReuseIdentifier" private let kHeaderViewReuseIdentifier = "kHeaderViewReuseIdentifier" class SLBaseAnchorViewController: SLBaseViewController { //MARK: - 懒加载 var baseVM: SLBaseViewModel! /// 创建collectionView lazy var collectionView: UICollectionView = {[weak self] in //创建布局 let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 10 layout.itemSize = CGSize(width: kItemW, height: kNormalItemH) //设置头部的size layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) //创建UICollectionView let collectionView: UICollectionView = UICollectionView(frame: self!.view.bounds, collectionViewLayout: layout) collectionView.showsVerticalScrollIndicator = false collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self //让collectionView随着父控件的宽高拉升 collectionView.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth] //注册cell collectionView.register(UINib(nibName: "SLCollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellReuseIdentifier) collectionView.register(UINib(nibName: "SLCollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellReuseIdentifier) //注册headerView collectionView.register(UINib(nibName: "SLCollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewReuseIdentifier) return collectionView }() //MARK: - viewDidLoad override func viewDidLoad() { super.viewDidLoad() //设置UI界面 setupUI() //发送网络请求 loadData() } } //MARK: - 发送网络请求 extension SLBaseAnchorViewController { func loadData() { } } //MARK: - 设置UI界面 extension SLBaseAnchorViewController { override func setupUI() { //给父控件的contentView赋值 contentView = collectionView //添加collectionView view.addSubview(collectionView) super.setupUI() } } //MARK: - UICollectionViewDataSource extension SLBaseAnchorViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return baseVM.anchorGroups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return baseVM.anchorGroups[section].anchors.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //获取cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellReuseIdentifier, for: indexPath) as! SLCollectionNormalCell //取出模型 let amuseModel = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item] //给cell赋值 cell.anchor = amuseModel return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { //取出headerView let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewReuseIdentifier, for: indexPath) as! SLCollectionHeaderView //取出模型,并给模型赋值 let group = baseVM.anchorGroups[indexPath.section] group.icon_name = "home_header_normal" headerView.group = group return headerView } } //MARK: - UICollectionViewDelegate extension SLBaseAnchorViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { //取出主播信息 let anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item] //判断是什么房间 anchor.isVertical == 0 ? pushViewController() : presentViewController() } //UINavigationController的形式弹出房间 private func pushViewController() { //创建控制器 let viewController = SLRoomNormalViewController() //push navigationController?.pushViewController(viewController, animated: true) } //以modol的形式弹出房间 private func presentViewController() { //创建控制器 let viewController = SLRoomShowViewController() //present present(viewController, animated: true, completion: nil) } }
mit
8403f01929abe316ff8072e903675e23
32.186747
201
0.688873
5.786765
false
false
false
false
kylefrost/WhatColorIsIt
iOS/WhatColorIsIt/ViewController.swift
1
4225
// // ViewController.swift // WhatColorIsIt // // Created by Kyle Frost on 12/19/14. // Copyright (c) 2014 Kyle Frost. All rights reserved. // import UIKit class ViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet var clockLabel: UILabel! @IBOutlet var colorLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Add Gesture Recognizer for Taps let recognizer = UITapGestureRecognizer(target: self, action:"copyColor") recognizer.delegate = self view.addGestureRecognizer(recognizer) // Set Clock Label Attrs clockLabel.textColor = UIColor.whiteColor() clockLabel.font = UIFont(name: "OpenSans-Light", size: 80.0) // Set Color Label Attrs colorLabel.textColor = UIColor.whiteColor() colorLabel.font = UIFont(name: "OpenSans-Light", size: 20.0) // Start Clock & Add Timer runClock() NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "runClock", userInfo: nil, repeats: true) } override func prefersStatusBarHidden() -> Bool { return true } func runClock() { // Get Date Components let date = NSDate() let calendar = NSCalendar.currentCalendar() let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond, fromDate: date) // Set Strings let currentTime = NSString(format:"%02d : %02d : %02d", components.hour, components.minute, components.second) as String let currentColor = NSString(format:"#%02d%02d%02d", components.hour, components.minute, components.second) as String // Set Clock and Value to Strings clockLabel.text = currentTime colorLabel.text = currentColor view.backgroundColor = UIColor(rgba: currentColor) } func copyColor() { flashWhite() var textToCopy = String() let clipboardPref: Int = NSUserDefaults.standardUserDefaults().integerForKey("clipboardPref") let currentColor = UIColor(rgba: colorLabel.text!).CGColor let colorString = CIColor(CGColor: currentColor).stringRepresentation() let colorParts = colorString.componentsSeparatedByString(" ") let hexColorString = colorLabel.text! let objcColorString = "[UIColor colorWithRed:\(colorParts[0]) green:\(colorParts[1]) blue:\(colorParts[2]) alpha:\(colorParts[3])];" let swiftColorString = "UIColor(red: \(colorParts[0]), green: \(colorParts[1]), blue: \(colorParts[2]), alpha: \(colorParts[3))" // Calculate RGB Color var redColor = colorParts[0].floatValue var greenColor = colorParts[1].floatValue var blueColor = colorParts[2].floatValue redColor = round(redColor * 255) greenColor = round(greenColor * 255) blueColor = round(blueColor * 255) let rgbColorSring = "R: \(redColor) G: \(greenColor) B: \(blueColor)" switch clipboardPref { case 0: textToCopy = hexColorString case 1: textToCopy = rgbColorSring case 2: textToCopy = objcColorString case 3: textToCopy = swiftColorString default: textToCopy = hexColorString } println(textToCopy) UIPasteboard.generalPasteboard().string = textToCopy } let whiteView = UIView() func flashWhite() { whiteView.frame = view.frame whiteView.backgroundColor = UIColor.whiteColor() view.addSubview(whiteView) NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "removeFlash", userInfo: nil, repeats: false) } func removeFlash() { whiteView.removeFromSuperview() } func gestureRecognizer(UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer:UIGestureRecognizer) -> Bool { return true } } extension String { var floatValue: Float { return (self as NSString).floatValue } }
gpl-2.0
e756190ec023986b5ddc5384b8c81f34
32.8
140
0.627456
5.072029
false
false
false
false
IBM-Swift/Kitura-net
Sources/KituraNet/ConnectionUpgrader.swift
1
4893
/* * Copyright IBM Corporation 2016 * * 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 LoggerAPI /// The struct that manages the process of upgrading connections from HTTP 1.1 to other protocols. /// /// - Note: There a single instance of this struct in a server. public struct ConnectionUpgrader { static var instance = ConnectionUpgrader() /// Determine if any upgraders have been registered static var upgradersExist: Bool { return ConnectionUpgrader.instance.registry.count != 0 } private var registry = [String: ConnectionUpgradeFactory]() /// Register a `ConnectionUpgradeFactory` class instances used to create appropriate `IncomingSocketProcessor`s /// for upgraded conections /// /// - Parameter factory: The `ConnectionUpgradeFactory` class instance being registered. public static func register(factory: ConnectionUpgradeFactory) { ConnectionUpgrader.instance.registry[factory.name.lowercased()] = factory } /// Clear the `ConnectionUpgradeFactory` registry. Used in testing. static func clear() { ConnectionUpgrader.instance.registry.removeAll() } /// The function that performs the upgrade. /// /// - Parameter handler: The `IncomingSocketHandler` that is handling the connection being upgraded. /// - Parameter request: The `ServerRequest` object of the incoming "upgrade" request. /// - Parameter response: The `ServerResponse` object that will be used to send the response of the "upgrade" request. func upgradeConnection(handler: IncomingSocketHandler, request: ServerRequest, response: ServerResponse) { guard let protocols = request.headers["Upgrade"] else { do { response.statusCode = HTTPStatusCode.badRequest try response.write(from: "No protocol specified in the Upgrade header") try response.end() } catch { Log.error("Failed to send error response to Upgrade request") } return } let statusCode = response.statusCode var oldProcessor: IncomingSocketProcessor? var processor: IncomingSocketProcessor? var responseBody: Data? var responseBodyMimeType: String? var notFound = true let protocolList = protocols.split(separator: ",") var protocolName: String? for eachProtocol in protocolList { let theProtocol = eachProtocol.first?.trimmingCharacters(in: CharacterSet.whitespaces) ?? "" if theProtocol.count != 0, let factory = registry[theProtocol.lowercased()] { (processor, responseBody, responseBodyMimeType) = factory.upgrade(handler: handler, request: request, response: response) protocolName = theProtocol notFound = false break } } do { if notFound { response.statusCode = HTTPStatusCode.notFound responseBody = "None of the protocols specified in the Upgrade header are registered".data(using: .utf8) responseBodyMimeType = "text/plain" } else { if let theProcessor = processor, let theProtocolName = protocolName { response.statusCode = .switchingProtocols response.headers["Upgrade"] = [theProtocolName] response.headers["Connection"] = ["Upgrade"] oldProcessor = handler.processor handler.processor = theProcessor oldProcessor?.inProgress = false } else { if response.statusCode == statusCode { response.statusCode = .badRequest } } } if let theBody = responseBody { response.headers["Content-Type"] = [responseBodyMimeType ?? "text/plain"] response.headers["Content-Length"] = [String(theBody.count)] try response.write(from: theBody) } try response.end() processor?.handler = handler } catch { Log.error("Failed to send response to Upgrade request") } } }
apache-2.0
fec54ea5d8d33717c6595bc7140e464b
40.820513
137
0.623953
5.26129
false
false
false
false