repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
michael-r-may/CatsAndDogsiOS
CatsAndDogs/RFC3339DateFormatter.swift
1
866
// // Created by Developer on 2017/03/26. // // Note: this is copied straight from the backend service import Foundation public extension TimeZone { static var Polish = TimeZone(identifier: "Europe/Warsaw") static var California = TimeZone(identifier: "US/Pacific") } public extension Locale { static var Polish = Locale(identifier: "pl_PL") static var US = Locale(identifier: "en_US") } public class RFC3339DateFormatter: DateFormatter { static var RFC3339DateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" init(locale: Locale, timezone: TimeZone) { super.init() self.locale = locale self.dateFormat = RFC3339DateFormatter.RFC3339DateFormat self.timeZone = timezone } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
76998b0ce605d19c3e049fae484489ac
26.0625
64
0.676674
4.084906
false
false
false
false
barbosa/clappr-ios
Pod/Classes/Base/Options.swift
1
372
public typealias Options = [String : AnyObject] public let kPosterUrl = "posterUrl" public let kSourceUrl = "sourceUrl" public let kMediaControl = "mediaControl" public let kFullscreen = "fullscreen" public let kStartAt = "startAt" public let kAutoPlay = "autoplay" public let kPlaybackNotSupportedMessage = "playbackNotSupportedMessage" public let kMimeType = "mimeType"
bsd-3-clause
32d495522bf08c107c026706b5587496
36.3
71
0.798387
4.179775
false
false
false
false
ZhaoBingDong/CYPhotosLibrary
CYPhotoKit/Controller/CYPhotoNavigationController.swift
1
4001
// // CYPhotoNavigationController.swift // CYPhotosKit // // Created by 董招兵 on 2017/8/7. // Copyright © 2017年 大兵布莱恩特. All rights reserved. // import UIKit /** * 相册选择器的导航控制器 */ public class CYPhotoNavigationController: UINavigationController { /** * 选取完照片的后的回调 */ public typealias PhotosCompletion = ([CYPhotosAsset]) -> Void public var completionBlock : PhotosCompletion? /** * 最大选择图片的数量 */ public var maxPickerImageCount : Int = maxSelectPhotoCount /** 已经选择过的图片数组 */ public var selectImages : [CYPhotosAsset]? /** * 类方法获取一个 photosNavigationController */ public class func showPhotosViewController() -> CYPhotoNavigationController { let photoGroupViewController = CYPhotoGroupController() let nav = CYPhotoNavigationController(rootViewController: photoGroupViewController) return nav } override public func viewDidLoad() { super.viewDidLoad() self.navigationBar.barTintColor = UIColor.CYColor(34, green: 34, blue: 34) self.navigationBar.tintColor = .white self.navigationBar.titleTextAttributes = [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 17.0),NSAttributedStringKey.foregroundColor : UIColor.white] let attributeds = [NSAttributedStringKey.foregroundColor : UIColor.white,NSAttributedStringKey.font : UIFont.systemFont(ofSize: 15.0)] UIBarButtonItem.appearance(whenContainedInInstancesOf: [CYPhotoNavigationController.self]).setTitleTextAttributes(attributeds, for: .normal) navigationItem.backBarButtonItem?.tintColor = UIColor.white self.navigationController?.interactivePopGestureRecognizer!.delegate = self } override public func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) isEmpty() addObserver() } /** * 判断rootViewController 是否为 CYPhotoGroupController ,实例化方法 showPhotosViewController 不能使用其他 controlller 作为 CYPhotoNavigationController 的 rootViewController */ private func isEmpty() { let rootViewController = self.viewControllers.first guard let rootVC = rootViewController , (rootVC.isKind(of: CYPhotoGroupController.self)) else { fatalError("\n\n请指定 CYPhotoGroupController类型的 rootViewController 或者调用 showPhotosViewController 方法\n") } } private func addObserver() { NotificationCenter.default.addObserver(self, selector: #selector(dismissViewController), name: NSNotification.Name("photosViewControllDismiss"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(didFinished(_:)), name: NSNotification.Name("photosViewControllerDidFinished"), object: nil) } // 选择完相片后点击完成 @objc private func didFinished(_ notification : Notification) { let array = notification.object as! [CYPhotosAsset] completionBlock?(array) dismissViewController() } /// 点击了取消 关闭相册选择器 @objc private func dismissViewController() { self.navigationController?.popToRootViewController(animated: false) self.dismiss(animated: true, completion: nil) } deinit { // NSLog("self deaclloc") } public override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { } } // MARK: - 控制器左侧滑动返回的代理 extension CYPhotoNavigationController : UIGestureRecognizerDelegate { public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return false } }
apache-2.0
4b08539cd599f7fb8969a74afd95a132
36.56
170
0.690096
5.103261
false
false
false
false
KaiCode2/swift-corelibs-foundation
TestFoundation/TestNSPropertyList.swift
2
2097
// 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 // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestNSPropertyList : XCTestCase { static var allTests: [(String, (TestNSPropertyList) -> () throws -> Void)] { return [ ("test_BasicConstruction", test_BasicConstruction ), ("test_decode", test_decode ), ] } func test_BasicConstruction() { let dict = NSMutableDictionary(capacity: 0) // dict["foo"] = "bar" var data: NSData? = nil do { data = try NSPropertyListSerialization.dataWithPropertyList(dict, format: NSPropertyListFormat.BinaryFormat_v1_0, options: 0) } catch { } XCTAssertNotNil(data) XCTAssertEqual(data!.length, 42, "empty dictionary should be 42 bytes") } func test_decode() { var decoded: Any? var fmt = NSPropertyListFormat.BinaryFormat_v1_0 let path = testBundle().pathForResource("Test", ofType: "plist") let data = NSData(contentsOfFile: path!) do { decoded = try withUnsafeMutablePointer(&fmt) { (format: UnsafeMutablePointer<NSPropertyListFormat>) -> Any in return try NSPropertyListSerialization.propertyListWithData(data!, options: [], format: format) } } catch { } XCTAssertNotNil(decoded) let dict = decoded as! Dictionary<String, Any> XCTAssertEqual(dict.count, 3) let val = dict["Foo"] XCTAssertNotNil(val) if let str = val as? String { XCTAssertEqual(str, "Bar") } else { XCTFail("value stored is not a string") } } }
apache-2.0
865c5f961598c2b88de1668a2e108467
30.772727
137
0.62041
4.71236
false
true
false
false
soapyigu/LeetCode_Swift
Sort/MergeSortedArray.swift
1
605
/** * Question Link: https://leetcode.com/problems/merge-sorted-array/ * Primary idea: Merge from tail to head to avoid override * Time Complexity: O(n), Space Complexity: O(1) */ class MergeSortedArray { func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) { var i = m - 1, j = n - 1 while i >= 0 || j >= 0 { if j < 0 || (i >= 0 && nums1[i] > nums2[j]) { nums1[i + j + 1] = nums1[i] i -= 1 } else { nums1[i + j + 1] = nums2[j] j -= 1 } } } }
mit
f7a2f6be277beed62928666a5b39db1a
27.857143
74
0.431405
3.306011
false
false
false
false
Andruschenko/SeatTreat
SeatTreat/BackendAPI.swift
1
3692
// // BackendAPI.swift // SeatTreat // // Created by Jan Erik Herrmann on 17.10.15. // Copyright © 2015 André Kovac. All rights reserved. // import Foundation import Alamofire import SwiftyJSON class BackendAPI { class func loadAvailableSeats(completionHandler: (seatArray: [Seat]) -> Void){ print("run loadAVailableSeats") Alamofire.request(.GET, "http://seattreat.eu-gb.mybluemix.net/availableSeats") .responseJSON { response in //print(response.request) // original URL request //print(response.response) // URL response //print(response.data) // server data //print(response.result) // result of response serialization var seatList = [Seat]() if let json = response.result.value { let jsonObj = JSON(json) //If json is .Dictionary for (key,subJson):(String, JSON) in jsonObj { let seat = Seat(column: subJson["column"].stringValue, row: subJson["row"].intValue, minutesLeft: subJson["minutesLeft"].intValue, secondsLeft: subJson["secondsLeft"].intValue, temperature: subJson["temperature"].intValue, sold: false, seatPosition: subJson["seatPosition"].stringValue, currentBidder: subJson["currentBidder"].stringValue, compartment: subJson["compartment"].stringValue, price: subJson["price"].intValue) seatList.append(seat) } } completionHandler(seatArray: seatList) } } class func getSeat(key: String, completionHandler: (seat: Seat) -> Void){ print("run getSeat") Alamofire.request(.GET, "http://seattreat.eu-gb.mybluemix.net/seat/"+key) .responseJSON { response in var seat: Seat! if let json = response.result.value { let jsonObj = JSON(json) seat = Seat(column: jsonObj["column"].stringValue, row: jsonObj["row"].intValue, minutesLeft: jsonObj["minutesLeft"].intValue, secondsLeft: jsonObj["secondsLeft"].intValue, temperature: jsonObj["temperature"].intValue, sold: false, seatPosition: jsonObj["seatPosition"].stringValue, currentBidder: jsonObj["currentBidder"].stringValue, compartment: jsonObj["compartment"].stringValue, price: jsonObj["price"].intValue) } completionHandler(seat: seat) } } class func bidSeat(seatkey: String, bid: Int, user: String, completionHandler: (seat: Seat) -> Void){ print("run bidSeat") Alamofire.request(.GET, "http://seattreat.eu-gb.mybluemix.net/bidOnSeat", parameters: ["key": seatkey, "bid": bid, "user": user]) .responseJSON { response in var seat: Seat! if let json = response.result.value { let jsonObj = JSON(json) seat = Seat(column: jsonObj["column"].stringValue, row: jsonObj["row"].intValue, minutesLeft: jsonObj["minutesLeft"].intValue, secondsLeft: jsonObj["secondsLeft"].intValue, temperature: jsonObj["temperature"].intValue, sold: false, seatPosition: jsonObj["seatPosition"].stringValue, currentBidder: jsonObj["currentBidder"].stringValue, compartment: jsonObj["compartment"].stringValue, price: jsonObj["price"].intValue) } completionHandler(seat: seat) } } }
gpl-2.0
f34c3e549d181ca86c01b45a90a25d99
44
442
0.580488
4.836173
false
false
false
false
miracl/amcl
version3/swift/hash256.swift
2
5699
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ // // hash256.swift - Implementation of SHA-256 // // Created by Michael Scott on 17/06/2015. // Copyright (c) 2015 Michael Scott. All rights reserved. // SHA256 Implementation // public struct HASH256{ private var length=[UInt32](repeating: 0,count: 2) private var h=[UInt32](repeating: 0,count: 8) private var w=[UInt32](repeating: 0,count: 64) static let H0:UInt32=0x6A09E667 static let H1:UInt32=0xBB67AE85 static let H2:UInt32=0x3C6EF372 static let H3:UInt32=0xA54FF53A static let H4:UInt32=0x510E527F static let H5:UInt32=0x9B05688C static let H6:UInt32=0x1F83D9AB static let H7:UInt32=0x5BE0CD19 static let len:Int=32 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] private static func S(_ n: UInt32,_ x: UInt32) -> UInt32 { return ((x>>n)|(x<<(32-n))) } private static func R(_ n: UInt32,_ x: UInt32) -> UInt32 { return (x>>n) } private static func Ch(_ x: UInt32,_ y: UInt32,_ z:UInt32) -> UInt32 { return ((x&y)^(~(x)&z)) } private static func Maj(_ x: UInt32,_ y: UInt32,_ z:UInt32) -> UInt32 { return ((x&y)^(x&z)^(y&z)) } private static func Sig0(_ x: UInt32) -> UInt32 { return (S(2,x)^S(13,x)^S(22,x)) } private static func Sig1(_ x: UInt32) -> UInt32 { return (S(6,x)^S(11,x)^S(25,x)) } private static func theta0(_ x: UInt32) -> UInt32 { return (S(7,x)^S(18,x)^R(3,x)) } private static func theta1(_ x: UInt32) -> UInt32 { return (S(17,x)^S(19,x)^R(10,x)) } private mutating func transform() { /* basic transformation step */ var a,b,c,d,e,f,g,hh,t1,t2 :UInt32 for j in 16 ..< 64 { w[j]=HASH256.theta1(w[j-2])&+w[j-7]&+HASH256.theta0(w[j-15])&+w[j-16] } a=h[0]; b=h[1]; c=h[2]; d=h[3] e=h[4]; f=h[5]; g=h[6]; hh=h[7] for j in 0 ..< 64 { /* 64 times - mush it up */ t1=hh&+HASH256.Sig1(e)&+HASH256.Ch(e,f,g)&+HASH256.K[j]&+w[j] t2=HASH256.Sig0(a)&+HASH256.Maj(a,b,c) hh=g; g=f; f=e; e=d&+t1; d=c; c=b; b=a; a=t1&+t2; } h[0]=h[0]&+a; h[1]=h[1]&+b; h[2]=h[2]&+c; h[3]=h[3]&+d h[4]=h[4]&+e; h[5]=h[5]&+f; h[6]=h[6]&+g; h[7]=h[7]&+hh; } /* Re-Initialise Hash function */ mutating func init_it() { /* initialise */ for i in 0 ..< 64 {w[i]=0} length[0]=0; length[1]=0 h[0]=HASH256.H0; h[1]=HASH256.H1; h[2]=HASH256.H2; h[3]=HASH256.H3; h[4]=HASH256.H4; h[5]=HASH256.H5; h[6]=HASH256.H6; h[7]=HASH256.H7; } public init() { init_it() } /* process a single byte */ public mutating func process(_ byt: UInt8) { /* process the next message byte */ let cnt=Int((length[0]/32)%16) w[cnt]<<=8; w[cnt]|=(UInt32(byt)&0xFF); length[0]+=8; if (length[0]==0) { length[1] += 1; length[0]=0 } if ((length[0]%512)==0) {transform()} } /* process an array of bytes */ public mutating func process_array(_ b: [UInt8]) { for i in 0 ..< b.count {process((b[i]))} } /* process a 32-bit integer */ public mutating func process_num(_ n:Int32) { process(UInt8((n>>24)&0xff)) process(UInt8((n>>16)&0xff)) process(UInt8((n>>8)&0xff)) process(UInt8(n&0xff)) } /* Generate 32-byte Hash */ public mutating func hash() -> [UInt8] { /* pad message and finish - supply digest */ var digest=[UInt8](repeating: 0,count: 32) let len0=length[0] let len1=length[1] process(0x80); while ((length[0]%512) != 448) {process(0)} w[14]=len1 w[15]=len0; transform() for i in 0 ..< HASH256.len { /* convert to bytes */ let r=(8*(3-UInt32(i)%4)); digest[i]=UInt8((h[i/4]>>r) & 0xff); } init_it(); return digest; } }
apache-2.0
5719d36b8399ce14748c06357e2c8bf6
29.31383
92
0.581155
2.655638
false
false
false
false
J3D1-WARR10R/WikiRaces
WKRKit/WKRKit/Players/Single/WKRPlayer.swift
2
1587
// // WKRPlayer.swift // WKRKit // // Created by Andrew Finke on 8/5/17. // Copyright © 2017 Andrew Finke. All rights reserved. // import WKRUIKit final public class WKRPlayer: Codable, Hashable { // MARK: - Properties [Must not break] internal let isHost: Bool internal var hasReceivedPointsForCurrentRace = false public internal(set) var raceHistory: WKRHistory? public internal(set) var state: WKRPlayerState = .connecting public let profile: WKRPlayerProfile public var name: String { return profile.name } // MARK: - Stat Properties public private(set) var stats = WKRPlayerRaceStats() // MARK: - Initialization init(profile: WKRPlayerProfile, isHost: Bool) { self.isHost = isHost self.profile = profile } // MARK: - Race Actions func startedNewRace(on page: WKRPage) { state = .racing raceHistory = WKRHistory(firstPage: page) stats.reset() } func nowViewing(page: WKRPage, linkHere: Bool) { raceHistory?.append(page, linkHere: linkHere) } func finishedViewingLastPage(pixelsScrolled: Int) { raceHistory?.finishedViewingLastPage() stats.update(history: raceHistory, state: state, pixels: pixelsScrolled) } func neededHelp() { stats.neededHelp() } // MARK: - Hashable public func hash(into hasher: inout Hasher) { return profile.hash(into: &hasher) } public static func ==(lhs: WKRPlayer, rhs: WKRPlayer) -> Bool { return lhs.profile == rhs.profile } }
mit
7658f5830470541c6cc0e436a4465b89
21.985507
80
0.647541
4.056266
false
false
false
false
drumnart/Papyrus
Papyrus/Reusable.swift
1
10207
// // Reusable.swift // Papyrus // // Created by Sergey Gorin on 31.03.17. // Copyright © 2017 Drumnart. All rights reserved. // public protocol Reusable: class { static var reuseIdentifier: String { get } } extension Reusable { public static var reuseIdentifier: String { return String(describing: self) } } public protocol NibReusable: Reusable, NibInstantiable {} extension UITableViewCell: Reusable {} extension UITableViewHeaderFooterView: Reusable {} extension UICollectionReusableView: Reusable {} public protocol ReusableItemsManager { associatedtype ListView var listView: ListView { get } } public struct ReuseId: RawRepresentable { public var rawValue: String public init(rawValue: String) { self.rawValue = rawValue } public init(_ rawValue: String) { self.rawValue = rawValue } } extension ReusableItemsManager where ListView: CollectionView { // Use one of these methods to register collectionView's cell without using a UINib or // dequeue cell without using string literals in reuseIdentifiers. // Every method uses class's name as an identifier and a nibName by default // if parameter `reuseId` was not set explicitly. /// Register class-based UICollectioniewCell /// Example: collectionView.register(CustomCollectionViewCell.self) @discardableResult public func register<T: UICollectionViewCell>(_: T.Type, withReuseId reuseId: ReuseId? = nil) -> Self { listView.register(T.self, forCellWithReuseIdentifier: reuseId?.rawValue ?? T.reuseIdentifier) return self } /// Register nib-based UICollectioniewCell /// Example: collectionView.register(CustomCollectionViewCell.self) @discardableResult public func register<T: UICollectionViewCell>(_: T.Type, withReuseId reuseId: ReuseId? = nil) -> Self where T: NibReusable { listView.register(T.nib, forCellWithReuseIdentifier: reuseId?.rawValue ?? T.reuseIdentifier) return self } /// Register a bunch of nib-based or class-based cells of type/subtype UICollectionViewCell /// - Parameters: types - array of cells' classes /// - Returns: UICollectionView.self /// - Example: collectionView.register([CustomCollectionViewCell.self]) @discardableResult public func register<T: UICollectionViewCell>(_ types: [T.Type]) -> Self { types.forEach { if let cellClass = $0 as? NibReusable.Type { listView.register(cellClass.nib, forCellWithReuseIdentifier: $0.reuseIdentifier) } else { listView.register($0.self, forCellWithReuseIdentifier: $0.reuseIdentifier) } } return self } /// Dequeue custom UICollectionViewCell /// Example: let cell: CustomCollectionViewCell = collectionView.dequeueReusableCell(for: indexPath) public func dequeueCell<T: UICollectionViewCell>(_: T.Type = T.self, withReuseId reuseId: ReuseId? = nil, for indexPath: IndexPath) -> T { let reuseId = reuseId?.rawValue ?? T.reuseIdentifier guard let cell = listView.dequeueReusableCell(withReuseIdentifier: reuseId, for: indexPath) as? T else { fatalError("Failed to dequeue cell with reuse identifier \(reuseId). Verify id in XIB/Storyboard.") } return cell } /// Register class-based UICollectionReusableView @discardableResult public func register<T: UICollectionReusableView>(_: T.Type, kind: String, withReuseId reuseId: ReuseId? = nil) -> Self { listView.register(T.self, forSupplementaryViewOfKind: kind, withReuseIdentifier: reuseId?.rawValue ?? T.reuseIdentifier) return self } /// Register nib-based UICollectionReusableView @discardableResult public func register<T: UICollectionReusableView>(_: T.Type, kind: String, withReuseId reuseId: ReuseId? = nil) -> Self where T: NibReusable { listView.register(T.nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: reuseId?.rawValue ?? T.reuseIdentifier) return self } /// Register a bunch of nib-based and/or class-based reusable views subclassed from UICollectionReusableView @discardableResult public func register<T: UICollectionReusableView>(_ types: [T.Type], kind: String) -> Self { types.forEach { if let cellClass = $0 as? NibReusable.Type { listView.register(cellClass.nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: $0.reuseIdentifier) } else { listView.register($0.self, forSupplementaryViewOfKind: kind, withReuseIdentifier: $0.reuseIdentifier) } } return self } /// Dequeue custom UICollectionReusableView instance public func dequeueView<T: UICollectionReusableView>(_: T.Type = T.self, ofKind kind: String, withReuseId reuseId: ReuseId? = nil, for indexPath: IndexPath) -> T { let reuseId = reuseId?.rawValue ?? T.reuseIdentifier guard let cell = listView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: reuseId, for: indexPath) as? T else { fatalError("Failed to dequeue supplementary view with reuse identifier \(reuseId). Verify id in XIB/Storyboard.") } return cell } /// Get cell by indexPath through subscript public subscript(indexPath: IndexPath) -> UICollectionViewCell? { return listView.cellForItem(at: indexPath) } } extension ReusableItemsManager where ListView: TableView { // Use one of these methods to register tableView's cell without using a UINib or // dequeue cell without using string literals in reuseIdentifiers. // Every method uses class's name as an identifier and a nibName by default // if parameter `reuseId` was not set explicitly. /// Register class-based UITableViewCell /// Example: tableView.registerCell(CustomTableViewCell) @discardableResult public func register<T: UITableViewCell>(_: T.Type, withReuseId reuseId: ReuseId? = nil) -> Self { listView.register(T.self, forCellReuseIdentifier: reuseId?.rawValue ?? T.reuseIdentifier) return self } /// Register nib-based UITableViewCell /// Example: tableView.registerCell(CustomTableViewCell) @discardableResult public func register<T: UITableViewCell>(_: T.Type, withReuseId reuseId: ReuseId? = nil) -> Self where T: NibReusable { listView.register(T.nib, forCellReuseIdentifier: reuseId?.rawValue ?? T.reuseIdentifier) return self } /// Register a bunch of nib-based or class-based cells of type UITableViewCell /// - Parameters: types - array of cells' classes /// - Returns: UITableViewView.self /// - Example: tableView.registerCells([CustomCollectionViewCell.self]) @discardableResult public func register<T: UITableViewCell>(_ types: [T.Type]) -> Self { types.forEach { if let cellClass = $0 as? NibReusable.Type { listView.register(cellClass.nib, forCellReuseIdentifier: $0.reuseIdentifier) } else { listView.register($0.self, forCellReuseIdentifier: $0.reuseIdentifier) } } return self } /// Dequeue custom UITableViewCell /// Example: let cell: CustomTableViewCell = tableView.dequeueReusableCell(for: indexPath) public func dequeueCell<T: UITableViewCell>(_: T.Type = T.self, withReuseId reuseId: ReuseId? = nil, for indexPath: IndexPath) -> T { let reuseId = reuseId?.rawValue ?? T.reuseIdentifier guard let cell = listView.dequeueReusableCell(withIdentifier: reuseId, for: indexPath) as? T else { fatalError("Failed to dequeue cell with reuse identifier \(reuseId). Verify id in XIB/Storyboard.") } return cell } /// Register class-based UITableViewHeaderFooterView class @discardableResult public func register<T: UITableViewHeaderFooterView>(_: T.Type, withReuseId reuseId: ReuseId? = nil) -> Self { listView.register(T.self, forHeaderFooterViewReuseIdentifier: reuseId?.rawValue ?? T.reuseIdentifier) return self } /// Register nib-based UITableViewHeaderFooterView class @discardableResult public func register<T: UITableViewHeaderFooterView>(_: T.Type, withReuseId reuseId: ReuseId? = nil) -> Self where T: NibReusable { listView.register(T.nib, forHeaderFooterViewReuseIdentifier: reuseId?.rawValue ?? T.reuseIdentifier) return self } /// Register a bunch of nib-based and/or class-based views subclassed from UITableViewHeaderFooterView @discardableResult public func register<T: UITableViewHeaderFooterView>(_ types: [T.Type]) -> Self { types.forEach { if let cellClass = $0 as? NibReusable.Type { listView.register(cellClass.nib, forHeaderFooterViewReuseIdentifier: $0.reuseIdentifier) } else { listView.register($0.self, forHeaderFooterViewReuseIdentifier: $0.reuseIdentifier) } } return self } /// Dequeue custom UITableViewHeaderFooterView instance public func dequeueView<T: UITableViewHeaderFooterView>(_: T.Type = T.self, withReuseId reuseId: ReuseId? = nil) -> T? { let reuseId = reuseId?.rawValue ?? T.reuseIdentifier guard let cell = listView.dequeueReusableHeaderFooterView(withIdentifier: reuseId) as? T? else { fatalError("Failed to dequeue reusable view with reuse identifier \(reuseId). Verify id in XIB/Storyboard.") } return cell } /// Get cell by indexPath through subscript public subscript(indexPath: IndexPath) -> UITableViewCell? { return listView.cellForRow(at: indexPath) } } extension CollectionView: ReusableItemsManager { public var listView: CollectionView { return self } } extension TableView: ReusableItemsManager { public var listView: TableView { return self } }
mit
6ac809e3232db4ac16001896684f2b9d
41.525
121
0.68009
5.23922
false
false
false
false
russbishop/swift
test/SILGen/expressions.swift
1
16388
// RUN: rm -rf %t // RUN: mkdir %t // RUN: echo "public var x = Int()" | %target-swift-frontend -module-name FooBar -emit-module -o %t - // RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s -I%t -disable-access-control | FileCheck %s import Swift import FooBar struct SillyString : _BuiltinStringLiteralConvertible, StringLiteralConvertible { init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {} init(unicodeScalarLiteral value: SillyString) { } init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { } init(extendedGraphemeClusterLiteral value: SillyString) { } init( _builtinStringLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) { } init(stringLiteral value: SillyString) { } } struct SillyUTF16String : _BuiltinUTF16StringLiteralConvertible, StringLiteralConvertible { init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { } init(unicodeScalarLiteral value: SillyString) { } init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { } init(extendedGraphemeClusterLiteral value: SillyString) { } init( _builtinStringLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { } init( _builtinUTF16StringLiteral start: Builtin.RawPointer, utf16CodeUnitCount: Builtin.Word ) { } init(stringLiteral value: SillyUTF16String) { } } func literals() { var a = 1 var b = 1.25 var d = "foö" var e:SillyString = "foo" } // CHECK-LABEL: sil hidden @_TF11expressions8literalsFT_T_ // CHECK: integer_literal $Builtin.Int2048, 1 // CHECK: float_literal $Builtin.FPIEEE{{64|80}}, {{0x3FF4000000000000|0x3FFFA000000000000000}} // CHECK: string_literal utf16 "foö" // CHECK: string_literal utf8 "foo" func bar(_ x: Int) {} func bar(_ x: Int, _ y: Int) {} func call_one() { bar(42); } // CHECK-LABEL: sil hidden @_TF11expressions8call_oneFT_T_ // CHECK: [[BAR:%[0-9]+]] = function_ref @_TF11expressions3bar{{.*}} : $@convention(thin) (Int) -> () // CHECK: [[FORTYTWO:%[0-9]+]] = integer_literal {{.*}} 42 // CHECK: [[FORTYTWO_CONVERTED:%[0-9]+]] = apply {{.*}}([[FORTYTWO]], {{.*}}) // CHECK: apply [[BAR]]([[FORTYTWO_CONVERTED]]) func call_two() { bar(42, 219) } // CHECK-LABEL: sil hidden @_TF11expressions8call_twoFT_T_ // CHECK: [[BAR:%[0-9]+]] = function_ref @_TF11expressions3bar{{.*}} : $@convention(thin) (Int, Int) -> () // CHECK: [[FORTYTWO:%[0-9]+]] = integer_literal {{.*}} 42 // CHECK: [[FORTYTWO_CONVERTED:%[0-9]+]] = apply {{.*}}([[FORTYTWO]], {{.*}}) // CHECK: [[TWONINETEEN:%[0-9]+]] = integer_literal {{.*}} 219 // CHECK: [[TWONINETEEN_CONVERTED:%[0-9]+]] = apply {{.*}}([[TWONINETEEN]], {{.*}}) // CHECK: apply [[BAR]]([[FORTYTWO_CONVERTED]], [[TWONINETEEN_CONVERTED]]) func tuples() { bar((4, 5).1) var T1 : (a: Int16, b: Int) = (b : 42, a : 777) } // CHECK-LABEL: sil hidden @_TF11expressions6tuplesFT_T_ class C { var chi:Int init() { chi = 219 } init(x:Int) { chi = x } } // CHECK-LABEL: sil hidden @_TF11expressions7classesFT_T_ func classes() { // CHECK: function_ref @_TFC11expressions1CC{{.*}} : $@convention(method) (@thick C.Type) -> @owned C var a = C() // CHECK: function_ref @_TFC11expressions1CC{{.*}} : $@convention(method) (Int, @thick C.Type) -> @owned C var b = C(x: 0) } struct S { var x:Int init() { x = 219 } init(x: Int) { self.x = x } } // CHECK-LABEL: sil hidden @_TF11expressions7structsFT_T_ func structs() { // CHECK: function_ref @_TFV11expressions1SC{{.*}} : $@convention(method) (@thin S.Type) -> S var a = S() // CHECK: function_ref @_TFV11expressions1SC{{.*}} : $@convention(method) (Int, @thin S.Type) -> S var b = S(x: 0) } func inoutcallee(_ x: inout Int) {} func address_of_expr() { var x: Int = 4 inoutcallee(&x) } func identity<T>(_ x: T) -> T {} struct SomeStruct { mutating func a() {} } // CHECK-LABEL: sil hidden @_TF11expressions5callsFT_T_ // CHECK: [[METHOD:%[0-9]+]] = function_ref @_TFV11expressions10SomeStruct1a{{.*}} : $@convention(method) (@inout SomeStruct) -> () // CHECK: apply [[METHOD]]({{.*}}) func calls() { var a : SomeStruct a.a() } // CHECK-LABEL: sil hidden @_TF11expressions11module_path func module_path() -> Int { return FooBar.x // CHECK: [[x_GET:%[0-9]+]] = function_ref @_TF6FooBarau1xSi // CHECK-NEXT: apply [[x_GET]]() } func default_args(_ x: Int, y: Int = 219, z: Int = 20721) {} // CHECK-LABEL: sil hidden @_TF11expressions19call_default_args_1 func call_default_args_1(_ x: Int) { default_args(x) // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF11expressions12default_args // CHECK: [[YFUNC:%[0-9]+]] = function_ref @_TIF11expressions12default_args // CHECK: [[Y:%[0-9]+]] = apply [[YFUNC]]() // CHECK: [[ZFUNC:%[0-9]+]] = function_ref @_TIF11expressions12default_args // CHECK: [[Z:%[0-9]+]] = apply [[ZFUNC]]() // CHECK: apply [[FUNC]]({{.*}}, [[Y]], [[Z]]) } // CHECK-LABEL: sil hidden @_TF11expressions19call_default_args_2 func call_default_args_2(_ x: Int, z: Int) { default_args(x, z:z) // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF11expressions12default_args // CHECK: [[DEFFN:%[0-9]+]] = function_ref @_TIF11expressions12default_args // CHECK-NEXT: [[C219:%[0-9]+]] = apply [[DEFFN]]() // CHECK: apply [[FUNC]]({{.*}}, [[C219]], {{.*}}) } struct Generic<T> { var mono_member:Int var typevar_member:T // CHECK-LABEL: sil hidden @_TFV11expressions7Generic13type_variable mutating func type_variable() -> T.Type { return T.self // CHECK: [[METATYPE:%[0-9]+]] = metatype $@thick T.Type // CHECK: return [[METATYPE]] } // CHECK-LABEL: sil hidden @_TFV11expressions7Generic19copy_typevar_member mutating func copy_typevar_member(_ x: Generic<T>) { typevar_member = x.typevar_member } // CHECK-LABEL: sil hidden @_TZFV11expressions7Generic12class_method static func class_method() {} } // CHECK-LABEL: sil hidden @_TF11expressions18generic_member_ref func generic_member_ref<T>(_ x: Generic<T>) -> Int { // CHECK: bb0([[XADDR:%[0-9]+]] : $*Generic<T>): return x.mono_member // CHECK: [[MEMBER_ADDR:%[0-9]+]] = struct_element_addr {{.*}}, #Generic.mono_member // CHECK: load [[MEMBER_ADDR]] } // CHECK-LABEL: sil hidden @_TF11expressions24bound_generic_member_ref func bound_generic_member_ref(_ x: Generic<UnicodeScalar>) -> Int { var x = x // CHECK: bb0([[XADDR:%[0-9]+]] : $Generic<UnicodeScalar>): return x.mono_member // CHECK: [[MEMBER_ADDR:%[0-9]+]] = struct_element_addr {{.*}}, #Generic.mono_member // CHECK: load [[MEMBER_ADDR]] } // CHECK-LABEL: sil hidden @_TF11expressions6coerce func coerce(_ x: Int32) -> Int64 { return 0 } class B { } class D : B { } // CHECK-LABEL: sil hidden @_TF11expressions8downcast func downcast(_ x: B) -> D { return x as! D // CHECK: unconditional_checked_cast %{{[0-9]+}} : {{.*}} to $D } // CHECK-LABEL: sil hidden @_TF11expressions6upcast func upcast(_ x: D) -> B { return x // CHECK: upcast %{{[0-9]+}} : ${{.*}} to $B } // CHECK-LABEL: sil hidden @_TF11expressions14generic_upcast func generic_upcast<T : B>(_ x: T) -> B { return x // CHECK: upcast %{{.*}} to $B // CHECK: return } // CHECK-LABEL: sil hidden @_TF11expressions16generic_downcast func generic_downcast<T : B>(_ x: T, y: B) -> T { return y as! T // CHECK: unconditional_checked_cast %{{[0-9]+}} : {{.*}} to $T // CHECK: return } // TODO: generic_downcast // CHECK-LABEL: sil hidden @_TF11expressions15metatype_upcast func metatype_upcast() -> B.Type { return D.self // CHECK: metatype $@thick D // CHECK-NEXT: upcast } // CHECK-LABEL: sil hidden @_TF11expressions19interpolated_string func interpolated_string(_ x: Int, y: String) -> String { return "The \(x) Million Dollar \(y)" } protocol Runcible { associatedtype U var free:Int { get } var associated:U { get } func free_method() -> Int mutating func associated_method() -> U.Type static func static_method() } protocol Mincible { var free:Int { get } func free_method() -> Int static func static_method() } protocol Bendable { } protocol Wibbleable { } // CHECK-LABEL: sil hidden @_TF11expressions20archetype_member_ref func archetype_member_ref<T : Runcible>(_ x: T) { var x = x x.free_method() // CHECK: witness_method $T, #Runcible.free_method!1 // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $T // CHECK-NEXT: copy_addr [[X:%.*]] to [initialization] [[TEMP]] // CHECK-NEXT: apply // CHECK-NEXT: destroy_addr [[TEMP]] var u = x.associated_method() // CHECK: witness_method $T, #Runcible.associated_method!1 // CHECK-NEXT: apply T.static_method() // CHECK: witness_method $T, #Runcible.static_method!1 // CHECK-NEXT: metatype $@thick T.Type // CHECK-NEXT: apply } // CHECK-LABEL: sil hidden @_TF11expressions22existential_member_ref func existential_member_ref(_ x: Mincible) { x.free_method() // CHECK: open_existential_addr // CHECK-NEXT: witness_method // CHECK-NEXT: apply } /*TODO archetype and existential properties and subscripts func archetype_property_ref<T : Runcible>(_ x: T) -> (Int, T.U) { x.free = x.free_method() x.associated = x.associated_method() return (x.free, x.associated) } func existential_property_ref<T : Runcible>(_ x: T) -> Int { x.free = x.free_method() return x.free } also archetype/existential subscripts */ struct Spoon : Runcible, Mincible { typealias U = Float var free: Int { return 4 } var associated: Float { return 12 } func free_method() -> Int {} func associated_method() -> Float.Type {} static func static_method() {} } struct Hat<T> : Runcible { typealias U = [T] var free: Int { return 1 } var associated: U { get {} } func free_method() -> Int {} // CHECK-LABEL: sil hidden @_TFV11expressions3Hat17associated_method mutating func associated_method() -> U.Type { return U.self // CHECK: [[META:%[0-9]+]] = metatype $@thin Array<T>.Type // CHECK: return [[META]] } static func static_method() {} } // CHECK-LABEL: sil hidden @_TF11expressions7erasure func erasure(_ x: Spoon) -> Mincible { return x // CHECK: init_existential_addr // CHECK: return } // CHECK-LABEL: sil hidden @_TF11expressions19declref_to_metatypeFT_MVS_5Spoon func declref_to_metatype() -> Spoon.Type { return Spoon.self // CHECK: metatype $@thin Spoon.Type } // CHECK-LABEL: sil hidden @_TF11expressions27declref_to_generic_metatype func declref_to_generic_metatype() -> Generic<UnicodeScalar>.Type { // FIXME parsing of T<U> in expression context typealias GenericChar = Generic<UnicodeScalar> return GenericChar.self // CHECK: metatype $@thin Generic<UnicodeScalar>.Type } func int(_ x: Int) {} func float(_ x: Float) {} func tuple() -> (Int, Float) { return (1, 1.0) } // CHECK-LABEL: sil hidden @_TF11expressions13tuple_element func tuple_element(_ x: (Int, Float)) { var x = x // CHECK: [[XADDR:%.*]] = alloc_box $(Int, Float) // CHECK: [[PB:%.*]] = project_box [[XADDR]] int(x.0) // CHECK: tuple_element_addr [[PB]] : {{.*}}, 0 // CHECK: apply float(x.1) // CHECK: tuple_element_addr [[PB]] : {{.*}}, 1 // CHECK: apply int(tuple().0) // CHECK: [[ZERO:%.*]] = tuple_extract {{%.*}} : {{.*}}, 0 // CHECK: apply {{.*}}([[ZERO]]) float(tuple().1) // CHECK: [[ONE:%.*]] = tuple_extract {{%.*}} : {{.*}}, 1 // CHECK: apply {{.*}}([[ONE]]) } // CHECK-LABEL: sil hidden @_TF11expressions10containers func containers() -> ([Int], Dictionary<String, Int>) { return ([1, 2, 3], ["Ankeny": 1, "Burnside": 2, "Couch": 3]) } // CHECK-LABEL: sil hidden @_TF11expressions7if_expr func if_expr(_ a: Bool, b: Bool, x: Int, y: Int, z: Int) -> Int { var a = a var b = b var x = x var y = y var z = z // CHECK: bb0({{.*}}): // CHECK: [[AB:%[0-9]+]] = alloc_box $Bool // CHECK: [[PBA:%.*]] = project_box [[AB]] // CHECK: [[BB:%[0-9]+]] = alloc_box $Bool // CHECK: [[PBB:%.*]] = project_box [[BB]] // CHECK: [[XB:%[0-9]+]] = alloc_box $Int // CHECK: [[PBX:%.*]] = project_box [[XB]] // CHECK: [[YB:%[0-9]+]] = alloc_box $Int // CHECK: [[PBY:%.*]] = project_box [[YB]] // CHECK: [[ZB:%[0-9]+]] = alloc_box $Int // CHECK: [[PBZ:%.*]] = project_box [[ZB]] return a ? x : b ? y : z // CHECK: [[A:%[0-9]+]] = load [[PBA]] // CHECK: [[ACOND:%[0-9]+]] = apply {{.*}}([[A]]) // CHECK: cond_br [[ACOND]], [[IF_A:bb[0-9]+]], [[ELSE_A:bb[0-9]+]] // CHECK: [[IF_A]]: // CHECK: [[XVAL:%[0-9]+]] = load [[PBX]] // CHECK: br [[CONT_A:bb[0-9]+]]([[XVAL]] : $Int) // CHECK: [[ELSE_A]]: // CHECK: [[B:%[0-9]+]] = load [[PBB]] // CHECK: [[BCOND:%[0-9]+]] = apply {{.*}}([[B]]) // CHECK: cond_br [[BCOND]], [[IF_B:bb[0-9]+]], [[ELSE_B:bb[0-9]+]] // CHECK: [[IF_B]]: // CHECK: [[YVAL:%[0-9]+]] = load [[PBY]] // CHECK: br [[CONT_B:bb[0-9]+]]([[YVAL]] : $Int) // CHECK: [[ELSE_B]]: // CHECK: [[ZVAL:%[0-9]+]] = load [[PBZ]] // CHECK: br [[CONT_B:bb[0-9]+]]([[ZVAL]] : $Int) // CHECK: [[CONT_B]]([[B_RES:%[0-9]+]] : $Int): // CHECK: br [[CONT_A:bb[0-9]+]]([[B_RES]] : $Int) // CHECK: [[CONT_A]]([[A_RES:%[0-9]+]] : $Int): // CHECK: return [[A_RES]] } // Test that magic identifiers expand properly. We test #column here because // it isn't affected as this testcase slides up and down the file over time. func magic_identifier_expansion(_ a: Int = #column) { // CHECK-LABEL: sil hidden @{{.*}}magic_identifier_expansion // This should expand to the column number of the first _. var tmp = #column // CHECK: integer_literal $Builtin.Int2048, 13 // This should expand to the column number of the (, not to the column number // of #column in the default argument list of this function. // rdar://14315674 magic_identifier_expansion() // CHECK: integer_literal $Builtin.Int2048, 29 } func print_string() { // CHECK-LABEL: print_string var str = "\u{08}\u{09}\thello\r\n\0wörld\u{1e}\u{7f}" // CHECK: string_literal utf16 "\u{08}\t\thello\r\n\0wörld\u{1E}\u{7F}" } // Test that we can silgen superclass calls that go farther than the immediate // superclass. class Super1 { func funge() {} } class Super2 : Super1 {} class Super3 : Super2 { override func funge() { super.funge() } } // <rdar://problem/16880240> SILGen crash assigning to _ func testDiscardLValue() { var a = 42 _ = a } func dynamicTypePlusZero(_ a : Super1) -> Super1.Type { return a.dynamicType } // CHECK-LABEL: dynamicTypePlusZero // CHECK: bb0(%0 : $Super1): // CHECK-NOT: retain // CHECK: value_metatype $@thick Super1.Type, %0 : $Super1 struct NonTrivialStruct { var c : Super1 } func dontEmitIgnoredLoadExpr(_ a : NonTrivialStruct) -> NonTrivialStruct.Type { return a.dynamicType } // CHECK-LABEL: dontEmitIgnoredLoadExpr // CHECK: bb0(%0 : $NonTrivialStruct): // CHECK-NEXT: debug_value // CHECK-NEXT: %2 = metatype $@thin NonTrivialStruct.Type // CHECK-NEXT: release_value %0 // CHECK-NEXT: return %2 : $@thin NonTrivialStruct.Type // <rdar://problem/18851497> Swiftc fails to compile nested destructuring tuple binding // CHECK-LABEL: sil hidden @_TF11expressions21implodeRecursiveTupleFGSqTTSiSi_Si__T_ // CHECK: bb0(%0 : $Optional<((Int, Int), Int)>): func implodeRecursiveTuple(_ expr: ((Int, Int), Int)?) { // CHECK: [[WHOLE:%[0-9]+]] = unchecked_enum_data {{.*}} : $Optional<((Int, Int), Int)> // CHECK-NEXT: [[X:%[0-9]+]] = tuple_extract [[WHOLE]] : $((Int, Int), Int), 0 // CHECK-NEXT: [[X0:%[0-9]+]] = tuple_extract [[X]] : $(Int, Int), 0 // CHECK-NEXT: [[X1:%[0-9]+]] = tuple_extract [[X]] : $(Int, Int), 1 // CHECK-NEXT: [[Y:%[0-9]+]] = tuple_extract [[WHOLE]] : $((Int, Int), Int), 1 // CHECK-NEXT: [[X:%[0-9]+]] = tuple ([[X0]] : $Int, [[X1]] : $Int) // CHECK-NEXT: debug_value [[X]] : $(Int, Int), let, name "x" // CHECK-NEXT: debug_value [[Y]] : $Int, let, name "y" let (x, y) = expr! } func test20087517() { class Color { static func greenColor() -> Color { return Color() } } let x: (Color?, Int) = (.greenColor(), 1) } func test20596042() { enum E { case thing1 case thing2 } func f() -> (E?, Int)? { return (.thing1, 1) } } func test21886435() { () = () }
apache-2.0
730468bdeeb7eb8f89bae074a605e363
27.395147
131
0.617188
3.177657
false
false
false
false
gerardogrisolini/Webretail
Sources/Webretail/Models/Amazon.swift
1
1735
// // Amazon.swift // Webretail // // Created by Gerardo Grisolini on 07/05/18. // import Foundation class Amazon : Codable { public var endpoint: String = "mws-eu.amazonservices.com" public var marketplaceId: String = "" public var sellerId: String = "" public var accessKey: String = "" public var secretKey: String = "" public var authToken: String = "" public var userAgent: String = "Webretail/1.0 (Language=Swift/4.1)" func setup() throws { let settings = Settings() try settings.query() if settings.results.rows.count == 30 { let mirror = Mirror(reflecting: self) for case let (label?, value) in mirror.children { let setting = Settings() setting.key = label setting.value = "\(value)" try setting.save() } } } func save() throws { let settings = Settings() let mirror = Mirror(reflecting: self) for case let (label?, value) in mirror.children { try settings.update(data: [("value", value)], idName: "key", idValue: label) } } func query() throws { let settings = Settings() try settings.query() let rows = settings.rows() let data = rows.reduce(into: [String: String]()) { $0[$1.key] = $1.value } endpoint = data["endpoint"] ?? "" marketplaceId = data["marketplaceId"] ?? "" sellerId = data["sellerId"] ?? "" accessKey = data["accessKey"] ?? "" secretKey = data["secretKey"] ?? "" authToken = data["authToken"] ?? "" userAgent = data["userAgent"] ?? "" } }
apache-2.0
6bb28d3b9694d0a4c5e4a57ab096ff9b
28.913793
88
0.537752
4.294554
false
false
false
false
andykkt/BFWControls
BFWControls/Modules/NibView/View/NibCellView.swift
1
2174
// // NibCellView.swift // // Created by Tom Brodhurst-Hill on 18/03/2016. // Copyright © 2016 BareFeetWare. Free to use and modify, without warranty. // import UIKit open class NibCellView: NibView, TextLabelProvider { // MARK: - IBOutlets @IBOutlet open weak var textLabel: UILabel? @IBOutlet open weak var detailTextLabel: UILabel? @IBOutlet open weak var iconView: UIView? @IBOutlet open weak var accessoryView: UIView? @IBOutlet open weak var separatorView: UIView? // MARK: - Variables and functions @IBInspectable open var text: String? { get { return textLabel?.text } set { textLabel?.text = newValue } } @IBInspectable open var detailText: String? { get { return detailTextLabel?.text } set { detailTextLabel?.text = newValue } } fileprivate var accessoryConstraints = [NSLayoutConstraint]() @IBInspectable open var showAccessory: Bool { get { return !(accessoryView?.isHidden ?? true) } set { guard let accessoryView = accessoryView else { return } accessoryView.isHidden = !newValue if newValue { NSLayoutConstraint.activate(accessoryConstraints) } else { if let siblingAndSuperviewConstraints = accessoryView.siblingAndSuperviewConstraints, !siblingAndSuperviewConstraints.isEmpty { accessoryConstraints = siblingAndSuperviewConstraints NSLayoutConstraint.deactivate(accessoryConstraints) } } } } // Deprecated. Use table view separators instead. @IBInspectable open var showSeparator: Bool { get { return !(separatorView?.isHidden ?? true) } set { separatorView?.isHidden = !newValue } } // MARK: - NibReplaceable open override var placeholderViews: [UIView] { return [textLabel, detailTextLabel].compactMap { $0 } } }
mit
3425d3e2a18f64ea0f160212151496b8
26.858974
101
0.583065
5.515228
false
false
false
false
Nana-Muthuswamy/AadhuEats
AadhuEats/Model/LogSummary.swift
1
2476
// // LogSummary.swift // AadhuEats // // Created by Nana on 10/26/17. // Copyright © 2017 Nana. All rights reserved. // import Foundation struct LogSummary: Exportable, DateFormatable { var date: Date var logs: Array<Log> var totalFeedVolume: Int { return logs.filter{$0.type != LogType.pumpSession}.reduce(0){$0 + $1.volume} } var totalBreastFeedVolume: Int { return logs.filter{$0.type == LogType.breastFeed || ($0.type == LogType.bottleFeed && $0.milkType == MilkType.breast)}.reduce(0){$0 + $1.volume} } var totalBreastPumpVolume: Int { return logs.filter{$0.type == LogType.pumpSession}.reduce(0){$0 + $1.volume} } var totalDuration: Int { return logs.filter{$0.type == LogType.breastFeed}.reduce(0){$0 + $1.duration} } var displayDate: String { return Log.dateFormatter.string(from: date) } var displayTotalFeedVolume: String { return "\(totalFeedVolume) ml" } var displayTotalBreastFeedVolume: String { return "\(totalBreastFeedVolume) ml" } var displayTotalBreastPumpVolume: String { return "\(totalBreastPumpVolume) ml" } var displayTotalDuration: String { return "\(totalDuration) mins" } init(date: Date, logs: Array<Log>) { self.date = date self.logs = logs.sorted{$0.date > $1.date} // store logs in descending order of logged dates } init?(source:Dictionary<String, Any>) { guard let logSummaryDateStr = source[kDate] as? String, let logSummaryDate = LogSummary.dateFormatter.date(from: logSummaryDateStr), let summaryLogs = source[kLogs] as? Array<Dictionary<String,Any>> else { return nil } date = logSummaryDate var logList = Array<Log>() for logDict in summaryLogs { if let log = Log(source: logDict) { logList.append(log) } } logs = logList.sorted{$0.date > $1.date} // store logs in descending order of logged dates } func export() -> Dictionary<String,Any> { var exportDict = Dictionary<String,Any>() exportDict.updateValue(Log.dateFormatter.string(from: date), forKey: kDate) var exportLogs = Array<Dictionary<String,Any>>() for log in logs { exportLogs.append(log.export()) } exportDict.updateValue(exportLogs, forKey: kLogs) return exportDict } }
mit
67cb8308e20d9a92f3753f2b369cfe1f
29.182927
152
0.620202
3.807692
false
false
false
false
JGiola/swift-package-manager
Sources/Utility/Version.swift
1
8748
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic /// A struct representing a semver version. public struct Version: Hashable { /// The major version. public let major: Int /// The minor version. public let minor: Int /// The patch version. public let patch: Int /// The pre-release identifier. public let prereleaseIdentifiers: [String] /// The build metadata. public let buildMetadataIdentifiers: [String] /// Create a version object. public init( _ major: Int, _ minor: Int, _ patch: Int, prereleaseIdentifiers: [String] = [], buildMetadataIdentifiers: [String] = [] ) { precondition(major >= 0 && minor >= 0 && patch >= 0, "Negative versioning is invalid.") self.major = major self.minor = minor self.patch = patch self.prereleaseIdentifiers = prereleaseIdentifiers self.buildMetadataIdentifiers = buildMetadataIdentifiers } } extension Version: Comparable { func isEqualWithoutPrerelease(_ other: Version) -> Bool { return major == other.major && minor == other.minor && patch == other.patch } public static func < (lhs: Version, rhs: Version) -> Bool { let lhsComparators = [lhs.major, lhs.minor, lhs.patch] let rhsComparators = [rhs.major, rhs.minor, rhs.patch] if lhsComparators != rhsComparators { return lhsComparators.lexicographicallyPrecedes(rhsComparators) } guard lhs.prereleaseIdentifiers.count > 0 else { return false // Non-prerelease lhs >= potentially prerelease rhs } guard rhs.prereleaseIdentifiers.count > 0 else { return true // Prerelease lhs < non-prerelease rhs } let zippedIdentifiers = zip(lhs.prereleaseIdentifiers, rhs.prereleaseIdentifiers) for (lhsPrereleaseIdentifier, rhsPrereleaseIdentifier) in zippedIdentifiers { if lhsPrereleaseIdentifier == rhsPrereleaseIdentifier { continue } let typedLhsIdentifier: Any = Int(lhsPrereleaseIdentifier) ?? lhsPrereleaseIdentifier let typedRhsIdentifier: Any = Int(rhsPrereleaseIdentifier) ?? rhsPrereleaseIdentifier switch (typedLhsIdentifier, typedRhsIdentifier) { case let (int1 as Int, int2 as Int): return int1 < int2 case let (string1 as String, string2 as String): return string1 < string2 case (is Int, is String): return true // Int prereleases < String prereleases case (is String, is Int): return false default: return false } } return lhs.prereleaseIdentifiers.count < rhs.prereleaseIdentifiers.count } } extension Version: CustomStringConvertible { public var description: String { var base = "\(major).\(minor).\(patch)" if !prereleaseIdentifiers.isEmpty { base += "-" + prereleaseIdentifiers.joined(separator: ".") } if !buildMetadataIdentifiers.isEmpty { base += "+" + buildMetadataIdentifiers.joined(separator: ".") } return base } } public extension Version { /// Create a version object from string. /// /// - Parameters: /// - string: The string to parse. init?(string: String) { let prereleaseStartIndex = string.index(of: "-") let metadataStartIndex = string.index(of: "+") let requiredEndIndex = prereleaseStartIndex ?? metadataStartIndex ?? string.endIndex let requiredCharacters = string.prefix(upTo: requiredEndIndex) let requiredComponents = requiredCharacters .split(separator: ".", maxSplits: 2, omittingEmptySubsequences: false) .map(String.init).compactMap({ Int($0) }).filter({ $0 >= 0 }) guard requiredComponents.count == 3 else { return nil } self.major = requiredComponents[0] self.minor = requiredComponents[1] self.patch = requiredComponents[2] func identifiers(start: String.Index?, end: String.Index) -> [String] { guard let start = start else { return [] } let identifiers = string[string.index(after: start)..<end] return identifiers.split(separator: ".").map(String.init) } self.prereleaseIdentifiers = identifiers( start: prereleaseStartIndex, end: metadataStartIndex ?? string.endIndex) self.buildMetadataIdentifiers = identifiers( start: metadataStartIndex, end: string.endIndex) } } extension Version: ExpressibleByStringLiteral { public init(stringLiteral value: String) { guard let version = Version(string: value) else { fatalError("\(value) is not a valid version") } self = version } public init(extendedGraphemeClusterLiteral value: String) { self.init(stringLiteral: value) } public init(unicodeScalarLiteral value: String) { self.init(stringLiteral: value) } } extension Version: JSONMappable, JSONSerializable { public init(json: JSON) throws { guard case .string(let string) = json else { throw JSON.MapError.custom(key: nil, message: "expected string, got \(json)") } guard let version = Version(string: string) else { throw JSON.MapError.custom(key: nil, message: "Invalid version string \(string)") } self.init(version) } public func toJSON() -> JSON { return .string(description) } init(_ version: Version) { self.init( version.major, version.minor, version.patch, prereleaseIdentifiers: version.prereleaseIdentifiers, buildMetadataIdentifiers: version.buildMetadataIdentifiers ) } } extension Version: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(description) } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let string = try container.decode(String.self) guard let version = Version(string: string) else { throw DecodingError.dataCorrupted(.init( codingPath: decoder.codingPath, debugDescription: "Invalid version string \(string)")) } self.init(version) } } // MARK:- Range operations extension ClosedRange where Bound == Version { /// Marked as unavailable because we have custom rules for contains. public func contains(_ element: Version) -> Bool { // Unfortunately, we can't use unavailable here. fatalError("contains(_:) is unavailable, use contains(version:)") } } // Disabled because compiler hits an assertion https://bugs.swift.org/browse/SR-5014 #if false extension CountableRange where Bound == Version { /// Marked as unavailable because we have custom rules for contains. public func contains(_ element: Version) -> Bool { // Unfortunately, we can't use unavailable here. fatalError("contains(_:) is unavailable, use contains(version:)") } } #endif extension Range where Bound == Version { /// Marked as unavailable because we have custom rules for contains. public func contains(_ element: Version) -> Bool { // Unfortunately, we can't use unavailable here. fatalError("contains(_:) is unavailable, use contains(version:)") } } extension Range where Bound == Version { public func contains(version: Version) -> Bool { // Special cases if version contains prerelease identifiers. if !version.prereleaseIdentifiers.isEmpty { // If the ranage does not contain prerelease identifiers, return false. if lowerBound.prereleaseIdentifiers.isEmpty && upperBound.prereleaseIdentifiers.isEmpty { return false } // At this point, one of the bounds contains prerelease identifiers. // // Reject 2.0.0-alpha when upper bound is 2.0.0. if upperBound.prereleaseIdentifiers.isEmpty && upperBound.isEqualWithoutPrerelease(version) { return false } } // Otherwise, apply normal contains rules. return version >= lowerBound && version < upperBound } }
apache-2.0
4e8b10cb74d51ea1b79d484f7dc75516
33.305882
105
0.639118
4.93401
false
false
false
false
keyOfVv/KEYUI
Demo/ViewController.swift
1
3320
// // ViewController.swift // Demo // // Created by Ke Yang on 23/03/2017. // Copyright © 2017 com.keyofvv. All rights reserved. // import UIKit import KEYUI let margin = CGFloat(10.0) class ViewController: UIViewController, UITextFieldDelegate { lazy var clearNeverTextField: KEYAutoResizeTextField = { let textField = KEYAutoResizeTextField(marginInsets: UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)) textField.clearButtonMode = .never textField.placeholder = "clearMode: never" textField.delegate = self return textField }() lazy var clearWhileEditingTextField: KEYAutoResizeTextField = { let textField = KEYAutoResizeTextField(marginInsets: UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)) textField.backgroundColor = .green textField.clearButtonMode = .whileEditing textField.placeholder = "clearMode: whileEditing" textField.delegate = self return textField }() lazy var clearUnlessEditingTextField: KEYAutoResizeTextField = { let textField = KEYAutoResizeTextField(marginInsets: UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)) textField.backgroundColor = .green textField.clearButtonMode = .unlessEditing textField.placeholder = "clearMode: unlessEditing" textField.delegate = self return textField }() lazy var clearAlwaysTextField: KEYAutoResizeTextField = { let textField = KEYAutoResizeTextField(marginInsets: UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)) textField.backgroundColor = .clear textField.clearButtonMode = .always textField.placeholder = "clearMode: always" textField.delegate = self textField.borderColor = .blue textField.borderWidth = 1.0 textField.fillColor = .clear textField.roundingCorners = [UIRectCorner.bottomLeft, UIRectCorner.bottomRight] textField.layer.cornerRadius = 10.0 return textField }() lazy var separatorView: UIView = { let view = UIView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false let rgb = CGFloat(74.0/255.0) view.backgroundColor = UIColor(red: rgb, green: rgb, blue: rgb, alpha: 1.0) return view }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white view.addSubview(clearNeverTextField) view.addSubview(clearWhileEditingTextField) view.addSubview(clearUnlessEditingTextField) view.addSubview(clearAlwaysTextField) view.addSubview(separatorView) let views = [ "never": clearNeverTextField, "while": clearWhileEditingTextField, "unless": clearUnlessEditingTextField, "always": clearAlwaysTextField, "sep": separatorView ] view.addConstraint(NSLayoutConstraint(item: clearNeverTextField, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0.0)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-84-[never]-10-[while]-10-[unless]-10-[always]-10-[sep(1)]", options: [.alignAllCenterX], metrics: nil, views: views)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[sep]-0-|", options: [], metrics: nil, views: views)) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
9ff29ba7c3b326f837f9684e6a36ff09
37.149425
193
0.75113
4.082411
false
false
false
false
JyerZ/BeiDou-iOS
BeiDou/ApplicationViewController.swift
1
3882
// // ApplicationViewController.swift // BeiDou // // Created by Jyer on 2017/1/22. // Copyright © 2017年 zjyzbfxgxzh. All rights reserved. // import UIKit class ApplicationViewController: UITableViewController { private let applicationCell = "ApplicationCell" var titles: [[String:String]]! var contents: [[String:String]]! override func viewDidLoad() { super.viewDidLoad() let path = Bundle.main.path(forResource: "Application", ofType: "plist") let Info = NSDictionary.init(contentsOfFile: path!) titles = Info?["times"]! as! [NSDictionary] as! [[String:String]] contents = Info?["applications"]! as! [NSDictionary] as! [[String:String]] // 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. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return titles.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... let cell = tableView.dequeueReusableCell(withIdentifier: applicationCell, for: indexPath) as UITableViewCell cell.textLabel?.text = titles[indexPath.row]["title"] cell.detailTextLabel?.text = titles[indexPath.row]["time"] return cell } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return false } /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. let detailVC = segue.destination as! DetailViewController let indexPath = tableView.indexPath(for: sender as! UITableViewCell)! let titleName = contents[indexPath.row]["title"] detailVC.navigationItem.title = titleName detailVC.content = contents[indexPath.row]["content"]! } }
unlicense
79b820c15230df55dd607badfa8c644e
35.942857
137
0.668729
5.117414
false
false
false
false
benlangmuir/swift
test/stdlib/Strideable.swift
7
9253
//===--- Strideable.swift - Tests for strided iteration -------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 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 // //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // import StdlibUnittest // Check that the generic parameter is called 'Element'. protocol TestProtocol1 {} extension StrideToIterator where Element : TestProtocol1 { var _elementIsTestProtocol1: Bool { fatalError("not implemented") } } extension StrideTo where Element : TestProtocol1 { var _elementIsTestProtocol1: Bool { fatalError("not implemented") } } extension StrideThroughIterator where Element : TestProtocol1 { var _elementIsTestProtocol1: Bool { fatalError("not implemented") } } extension StrideThrough where Element : TestProtocol1 { var _elementIsTestProtocol1: Bool { fatalError("not implemented") } } var StrideTestSuite = TestSuite("Strideable") struct R : Strideable { typealias Distance = Int var x: Int init(_ x: Int) { self.x = x } func distance(to rhs: R) -> Int { return rhs.x - x } func advanced(by n: Int) -> R { return R(x + n) } } StrideTestSuite.test("Double") { func checkOpen(from start: Double, to end: Double, by stepSize: Double, sum: Double) { // Work on Doubles expectEqual( sum, stride(from: start, to: end, by: stepSize).reduce(0.0, +)) } func checkClosed(from start: Double, through end: Double, by stepSize: Double, sum: Double) { // Work on Doubles expectEqual( sum, stride(from: start, through: end, by: stepSize).reduce(0.0, +)) } checkOpen(from: 1.0, to: 15.0, by: 3.0, sum: 35.0) checkOpen(from: 1.0, to: 16.0, by: 3.0, sum: 35.0) checkOpen(from: 1.0, to: 17.0, by: 3.0, sum: 51.0) checkOpen(from: 1.0, to: -13.0, by: -3.0, sum: -25.0) checkOpen(from: 1.0, to: -14.0, by: -3.0, sum: -25.0) checkOpen(from: 1.0, to: -15.0, by: -3.0, sum: -39.0) checkOpen(from: 4.0, to: 16.0, by: -3.0, sum: 0.0) checkOpen(from: 1.0, to: -16.0, by: 3.0, sum: 0.0) checkClosed(from: 1.0, through: 15.0, by: 3.0, sum: 35.0) checkClosed(from: 1.0, through: 16.0, by: 3.0, sum: 51.0) checkClosed(from: 1.0, through: 17.0, by: 3.0, sum: 51.0) checkClosed(from: 1.0, through: -13.0, by: -3.0, sum: -25.0) checkClosed(from: 1.0, through: -14.0, by: -3.0, sum: -39.0) checkClosed(from: 1.0, through: -15.0, by: -3.0, sum: -39.0) checkClosed(from: 4.0, through: 16.0, by: -3.0, sum: 0.0) checkClosed(from: 1.0, through: -16.0, by: 3.0, sum: 0.0) } StrideTestSuite.test("HalfOpen") { func check(from start: Int, to end: Int, by stepSize: Int, sum: Int) { // Work on Ints expectEqual( sum, stride(from: start, to: end, by: stepSize).reduce( 0, +)) // Work on an arbitrary RandomAccessIndex expectEqual( sum, stride(from: R(start), to: R(end), by: stepSize).reduce(0) { $0 + $1.x }) } check(from: 1, to: 15, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13 check(from: 1, to: 16, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13 check(from: 1, to: 17, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16 check(from: 1, to: -13, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11 check(from: 1, to: -14, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11 check(from: 1, to: -15, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14 check(from: 4, to: 16, by: -3, sum: 0) check(from: 1, to: -16, by: 3, sum: 0) } StrideTestSuite.test("Closed") { func check(from start: Int, through end: Int, by stepSize: Int, sum: Int) { // Work on Ints expectEqual( sum, stride(from: start, through: end, by: stepSize).reduce( 0, +)) // Work on an arbitrary RandomAccessIndex expectEqual( sum, stride(from: R(start), through: R(end), by: stepSize).reduce( 0, { $0 + $1.x }) ) } check(from: 1, through: 15, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13 check(from: 1, through: 16, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16 check(from: 1, through: 17, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16 check(from: 1, through: -13, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11 check(from: 1, through: -14, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14 check(from: 1, through: -15, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14 check(from: 4, through: 16, by: -3, sum: 0) check(from: 1, through: -16, by: 3, sum: 0) } StrideTestSuite.test("OperatorOverloads") { var r1 = R(50) var r2 = R(70) var stride: Int = 5 do { var result = r1.advanced(by: stride) expectType(R.self, &result) expectEqual(55, result.x) } do { var result = r1.advanced(by: stride) expectType(R.self, &result) expectEqual(55, result.x) } do { var result = r1.advanced(by: -stride) expectType(R.self, &result) expectEqual(45, result.x) } do { var result = r2.distance(to: r1) expectType(Int.self, &result) expectEqual(-20, result) } } StrideTestSuite.test("FloatingPointStride") { var result = [Double]() for i in stride(from: 1.4, through: 3.4, by: 1) { result.append(i) } expectEqual([ 1.4, 2.4, 3.4 ], result) } StrideTestSuite.test("FloatingPointStride/rounding error") { // Ensure that there is no error accumulation let a = Array(stride(from: 1 as Float, through: 2, by: 0.1)) expectEqual(11, a.count) expectEqual(2 as Float, a.last) let b = Array(stride(from: 1 as Float, to: 10, by: 0.9)) expectEqual(10, b.count) // Ensure that there is no intermediate rounding error on supported platforms if (-0.2).addingProduct(0.2, 6) == 1 { let c = Array(stride(from: -0.2, through: 1, by: 0.2)) expectEqual(7, c.count) expectEqual(1 as Double, c.last) } if (1 as Float).addingProduct(0.9, 6) == 6.3999996 { let d = Array(stride(from: 1 as Float, through: 6.3999996, by: 0.9)) expectEqual(7, d.count) // The reason that `d` has seven elements and not six is that the fused // multiply-add operation `(1 as Float).addingProduct(0.9, 6)` gives the // result `6.3999996`. This is nonetheless the desired behavior because // avoiding error accumulation and intermediate rounding error wherever // possible will produce better results more often than not (see SR-6377). // // If checking of end bounds has been inadvertently modified such that we're // computing the distance from the penultimate element to the end (in this // case, `6.3999996 - (1 as Float).addingProduct(0.9, 5)`), then the last // element will be omitted here. // // Therefore, if the test has failed, there may have been a regression in // the bounds-checking logic of `Stride*Iterator`. Restore the expected // behavior here by ensuring that floating-point strides are opted out of // any bounds checking that performs arithmetic with values other than the // bounds themselves and the stride. } } func strideIteratorTest< Stride : Sequence >(_ stride: Stride, nonNilResults: Int) { var i = stride.makeIterator() for _ in 0..<nonNilResults { expectNotNil(i.next()) } for _ in 0..<10 { expectNil(i.next()) } } StrideTestSuite.test("StrideThroughIterator/past end") { strideIteratorTest(stride(from: 0, through: 3, by: 1), nonNilResults: 4) strideIteratorTest( stride(from: UInt8(0), through: 255, by: 5), nonNilResults: 52) } StrideTestSuite.test("StrideThroughIterator/past end/backward") { strideIteratorTest(stride(from: 3, through: 0, by: -1), nonNilResults: 4) } StrideTestSuite.test("StrideToIterator/past end") { strideIteratorTest(stride(from: 0, to: 3, by: 1), nonNilResults: 3) } StrideTestSuite.test("StrideToIterator/past end/backward") { strideIteratorTest(stride(from: 3, to: 0, by: -1), nonNilResults: 3) } if #available(SwiftStdlib 5.6, *) { StrideTestSuite.test("Contains") { expectTrue(stride(from: 1, through: 5, by: 1).contains(3)) expectTrue(stride(from: 1, to: 5, by: 1).contains(3)) expectTrue(stride(from: 1, through: 5, by: 1).contains(5)) expectFalse(stride(from: 1, to: 5, by: 1).contains(5)) expectFalse(stride(from: 1, through: 5, by: -1).contains(3)) expectFalse(stride(from: 1, to: 5, by: -1).contains(3)) expectFalse(stride(from: 1, through: 5, by: -1).contains(1)) expectFalse(stride(from: 1, to: 5, by: -1).contains(1)) expectTrue(stride(from: 5, through: 1, by: -1).contains(3)) expectTrue(stride(from: 5, to: 1, by: -1).contains(3)) expectTrue(stride(from: 5, through: 1, by: -1).contains(1)) expectFalse(stride(from: 5, to: 1, by: -1).contains(1)) expectFalse(stride(from: 5, through: 1, by: 1).contains(3)) expectFalse(stride(from: 5, to: 1, by: 1).contains(3)) expectFalse(stride(from: 5, through: 1, by: 1).contains(5)) expectFalse(stride(from: 5, to: 1, by: 1).contains(5)) } } runAllTests()
apache-2.0
79b07a081469740ca6913af4a0f8d87f
31.928826
95
0.619475
3.031782
false
true
false
false
PokeMapCommunity/PokeMap-iOS
Pods/Permission/Source/PermissionTypes/Notifications.swift
1
2908
// // Notifications.swift // // Copyright (c) 2015-2016 Damien (http://delba.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // private var notificationTimer: NSTimer? internal extension Permission { var statusNotifications: PermissionStatus { guard case .Notifications(let settings) = type else { fatalError() } if let types = Application.currentUserNotificationSettings()?.types where types.contains(settings.types) { return .Authorized } return Defaults.requestedNotifications ? .Denied : .NotDetermined } func requestNotifications(callback: Callback) { guard case .Notifications(let settings) = type else { fatalError() } NotificationCenter.addObserver(self, selector: .requestingNotifications, name: UIApplicationWillResignActiveNotification) notificationTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: .finishedRequestingNotifications, userInfo: nil, repeats: false) Application.registerUserNotificationSettings(settings) } @objc func requestingNotifications() { NotificationCenter.removeObserver(self, name: UIApplicationWillResignActiveNotification) NotificationCenter.addObserver(self, selector: .finishedRequestingNotifications, name: UIApplicationDidBecomeActiveNotification) notificationTimer?.invalidate() } @objc func finishedRequestingNotifications() { NotificationCenter.removeObserver(self, name: UIApplicationWillResignActiveNotification) NotificationCenter.removeObserver(self, name: UIApplicationDidBecomeActiveNotification) notificationTimer?.invalidate() Defaults.requestedNotifications = true Queue.main(after: 0.1) { self.callbacks(self.statusNotifications) } } }
mit
259c5ec6f406e7bddd63148a592989e2
44.4375
158
0.733838
5.486792
false
false
false
false
EasySwift/EasySwift
EasySwift_iOS/Core/EZPrintln.swift
2
496
// // EZPrintln.swift // EasySwift // // Created by YXJ on 16/7/3. // Copyright (c) 2016年 YXJ. All rights reserved. // import Foundation public var DEBUG = true public func EZPrintln<T>(_ message: T, fileName: String = #file, methodName: String = #function, lineNumber: Int = #line) { if DEBUG { let file: String = (fileName as NSString).pathComponents.last!.replacingOccurrences(of: "swift", with: "") print("\(file)\(methodName)[\(lineNumber)]:\(message)") } }
apache-2.0
e28d5250ad3082858bd94d91cdb5aece
26.444444
123
0.647773
3.503546
false
false
false
false
L550312242/SinaWeiBo-Switf
weibo 1/Class/Model(全局模型)/CZStatus.swift
1
10459
import UIKit import SDWebImage class CZStatus: NSObject { /// 微博创建时间 var created_at: String? /// 微博ID var id: Int = 0 /// 微博信息内容 var text: String? /// 微博来源 var source: String? // 通过分析微博返回的数据 是一个数组,数组里面是一个字典["thumbnail_pic": url] /// 微博的配图 var pic_urls: [[String: AnyObject]]?{ didSet { // 当字典转模型,给pic_urls赋值的时候,将数组里面的url转成NSURL赋值给storePictureURLs // 判断有没有图片 let count = pic_urls?.count ?? 0 // 没有图片,直接返回 if count == 0 { return } // 创建storePictureURLs 属性 storePictureURLs = [NSURL]() for dict in pic_urls! { if let urlString = dict["thumbnail_pic"] as? String { // 有url地址 storePictureURLs?.append(NSURL(string: urlString)!) } } } } /// 返回 微博的配图 对应的URL数组 var storePictureURLs: [NSURL]? /// 如果是原创微博,就返回原创微博的图片,如果是转发微博就返回被转发微博的图片 /// 计算型属性, var pictureURLs: [NSURL]? { get { // 判断: // 1.原创微博: 返回 storePictureURLs // 2.转发微博: 返回 retweeted_status.storePictureURLs return retweeted_status == nil ? storePictureURLs : retweeted_status!.storePictureURLs } } //用户模型 var user: CZUser? /// 缓存行高 var rowHeight: CGFloat? /// 被转发微博 var retweeted_status: CZStatus? // 根据模型里面的retweeted_status来判断是原创微博还是转发微博 /// 返回微博cell对应的Identifier func cellID() -> String { // retweeted_status == nil表示原创微博 return retweeted_status == nil ? CZStatusCellIdentifier.NormalCell.rawValue : CZStatusCellIdentifier.ForwardCell.rawValue } // 字典转模型 init(dict:[String: AnyObject]){ super.init() setValuesForKeysWithDictionary(dict) } //KVC赋值每个属性的时候都会调用 override func setValue(value: AnyObject?, forKey key: String) { //判断user赋值时,自己字典转模型 if key == "user" { if let dict = value as? [String: AnyObject]{ //字典转模型 //赋值 user = CZUser(dict: dict) //一定要记得return,不加就会调用父类 return } }else if key == "retweeted_status" { if let dict = value as? [String: AnyObject] { // 字典转模型 // 被转发的微博 retweeted_status = CZStatus(dict: dict) } // 千万要记住 return return } return super.setValue(value, forKey: key) } //字典的key在模型里面找不到对应的属性 override func setValue(value: AnyObject?, forUndefinedKey key: String) { } override var description: String{ let p = ["created_at", "idstr", "text", "source", "pic_urls","user"] //数组里面的每个元素,找到对应的Value,平成字典 // dictionaryWithValuesForKeys(p) // 数组里面的每个元素,找到对应的value,拼接成字典 // \n 换行, \t table return "\n\t微博模型:\(dictionaryWithValuesForKeys(p))" } //加载微博数据 class func loadStatus(since_id: Int, max_id: Int, finished: (statuses: [CZStatus]?, error: NSError?) -> ()) { // sharedInstance CZNetworkTools.sharedInstance.loadStatus(since_id, max_id: max_id) { (result, error) -> () in // class func loadSyatus(finished: (statuses: [CZStatus]?, error: NSError?) -> ()) { // 尾随闭包,当尾随闭包前面没有参数的时候()可以省略 // CZNetworkTools.sharedInstance.loadStatus { (result, error) -> () in if error != nil{ print("error:\(error)") //通知调用者 return } // 判断是否有数据 if let array = result?["statuses"] as? [[String:AnyObject]]{ // 有数据 //创建模型数组 var statuses = [CZStatus]() for dict in array{ //字典转模型 statuses.append(CZStatus(dict: dict)) } //字典转模型完成 //print("statuses:\(statuses)") //通知调用者 finished(statuses: statuses, error: nil) }else { // 没有数据,通知调用者 finished(statuses: nil, error: nil) } } } class func cacheWebImage(statuses: [CZStatus]?, finished: (statuses: [CZStatus]?, error: NSError?) -> ()) { // 创建任务组 let group = dispatch_group_create() // 判断是否有模型 guard let list = statuses else { // 没有模型 return } // 记录缓存图片的大小 var length = 0 // 遍历模型 for status in list { // 如果没有图片需要下载,接着遍历下一个 let count = status.pictureURLs?.count ?? 0 if count == 0 { // 没有图片,遍历下一个模型 continue } // 判断是否有图片需要下载 if let urls = status.pictureURLs { // 有需要缓存的图片,遍历,一张-张缓存 // for url in urls { if urls.count == 1 { let url = urls[0] print(url) // 缓存图片 // 在缓存之前放到任务组里面 dispatch_group_enter(group) SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in // 离开组 dispatch_group_leave(group) // 判断有没有错误 if error != nil { print("下载图片出错:\(url)") return } // 没有出错 print("下载图片完成:\(url)") // 记录下载图片的大小 if let data = UIImagePNGRepresentation(image) { length += data.length } }) } } } // 所有图片都下载完,在通知调用者 dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in print("所有图片下载完成,告诉调用者获取到了微博数据: 大小:\(length / 1024)") // 通知调用者,已经有数据 finished(statuses: statuses, error: nil) } } } // class func cacheWebImage(statuses: [CZStatus]?, finished: (statuses: [CZStatus]?, error: NSError?) -> ()) { // //创建任务组 // let group = dispatch_group_create() // //判断是否有模型 // guard let list = statuses else{ // return // } // //记录缓存图片大小 // var length = 0 // // //遍历模型 // for status in list{ // // 如果没有图片需要下载,接着遍历下一个 // let count = status.pictureURLs?.count ?? 0 // if count == 0 { // //没有图片,遍历下一个 // continue // } //判断是否有图片需要下载 // if let urls = status.pictureURLs{ // // // 判断是否有图片需要下载 // if let urls = status.pictureURLs // { // // 有需要缓存的图片,遍历,一张-张缓存 // if urls.count == 1 { // let url = urls[0] // print(url) // 缓存图片 // // 在缓存之前放到任务组里面 // 在缓存之前放到任务组里面 // dispatch_group_enter(group) // SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in // // 离开组 // dispatch_group_leave(group) // // // 判断有没有错误 //// if error != nil { //// print("下载图片出错:\(url)") //// return //// } //// // // 没有出错 // print("下载图片完成:\(url)") // //// // 记录下载图片的大小 //// if let data = UIImagePNGRepresentation(image) { //// length += data.length //// } // }) // } // } // } // // 所有图片都下载完,在通知调用者 // dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in // print("所有图片下载完成,告诉调用者获取到了微博数据: 大小:\(length / 1024)") // // 通知调用者,已经有数据 // finished(statuses: statuses, error: nil) // } // // } //}
apache-2.0
9d739c0e2e2957f079ef263df2775f8b
31.072202
189
0.428234
4.638642
false
false
false
false
eTilbudsavis/native-ios-eta-sdk
Sources/EventsTracker/LegacyEventsPool/EventsCache_v1.swift
1
7625
// // ┌────┬─┐ ┌─────┐ // │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐ // ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │ // └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘ // └─┘ // // Copyright (c) 2018 ShopGun. All rights reserved. import Foundation /// A class that handles the Caching of the events to disk class EventsCache_v1: PoolCache_v1Protocol { let diskCachePath: String? init(fileName: String) { self.diskCachePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first as NSString?)?.appendingPathComponent(fileName) } /// Note - this property is syncronized with memory writes, so may not be instantaneous var objectCount: Int { var count: Int = 0 cacheInMemoryQueue.sync { count = allObjects.count } return count } let maxCount: Int = 1000 /// Lazily initialize from the disk. this may take a while, so the beware the first call to allObjects lazy fileprivate var allObjects: [SerializedV1PoolObject] = { let start = Date().timeIntervalSinceReferenceDate var objs: [SerializedV1PoolObject] = [] objs.reserveCapacity(self.maxCount) self.cacheOnDiskQueue.sync { objs = self.retreiveFromDisk() ?? [] } //print("[CACHE] INIT \(objs.count) objs: \(String(format:"%.4f", Date().timeIntervalSinceReferenceDate - start)) secs") return objs }() func write(toTail objects: [SerializedV1PoolObject]) { guard objects.count > 0 else { return } //let start = Date().timeIntervalSinceReferenceDate cacheInMemoryQueue.async { // remove from head of array to maintain a max size let currentCount = self.allObjects.count + objects.count if currentCount > self.maxCount { self.allObjects.removeFirst(currentCount - self.maxCount) } // update in-memory version self.allObjects.append(contentsOf: objects) //print("[CACHE] WRITE [\(self.writeRequestCount+1)] \(self.allObjects.count) objs: \(String(format:"%.4f", Date().timeIntervalSinceReferenceDate - start)) secs") self.requestWriteToDisk() } } func read(fromHead count: Int) -> [SerializedV1PoolObject] { var objs: [SerializedV1PoolObject] = [] cacheInMemoryQueue.sync { let lastIndex = min(self.allObjects.endIndex, count) - 1 if lastIndex > 0 { objs = Array(self.allObjects[0 ... lastIndex]) } } return objs } func remove(poolIds: [String]) { guard poolIds.count > 0 else { return } //let start = Date().timeIntervalSinceReferenceDate cacheInMemoryQueue.async { var idsToRemove = poolIds var trimmedObjs: [SerializedV1PoolObject] = [] trimmedObjs.reserveCapacity(self.maxCount) for (index, obj) in self.allObjects.enumerated() { // it should be ignored, skip this object if let idx = idsToRemove.firstIndex(of: obj.poolId) { idsToRemove.remove(at: idx) // it was the last id to remove, so just append all the rest if idsToRemove.count == 0 { let allObjCount = self.allObjects.count if (index+1) < allObjCount { trimmedObjs.append(contentsOf: self.allObjects[index+1 ..< allObjCount]) } break } } else { trimmedObjs.append(obj) } } self.allObjects = trimmedObjs //print("[CACHE] REMOVE [\(self.writeRequestCount+1)] \(poolIds.count) objs: \(String(format:"%.4f", Date().timeIntervalSinceReferenceDate - start)) secs") self.requestWriteToDisk() } } var writeToDiskTimer: Timer? var writeRequestCount: Int = 0 fileprivate let cacheInMemoryQueue: DispatchQueue = DispatchQueue(label: "com.shopgun.ios.sdk.events_cache.memory_queue", attributes: []) fileprivate let cacheOnDiskQueue: DispatchQueue = DispatchQueue(label: "com.shopgun.ios.sdk.events_cache.disk_queue", attributes: []) fileprivate func requestWriteToDisk() { writeRequestCount += 1 if writeToDiskTimer == nil { //print ("[CACHE] request write to disk [\(writeRequestCount)]") writeToDiskTimer = Timer(timeInterval: 0.2, target: self, selector: #selector(writeToDiskTimerTick(_:)), userInfo: nil, repeats: false) RunLoop.main.add(writeToDiskTimer!, forMode: RunLoop.Mode.common) } } @objc fileprivate func writeToDiskTimerTick(_ timer: Timer) { writeCurrentStateToDisk() } fileprivate func writeCurrentStateToDisk() { //let start = Date().timeIntervalSinceReferenceDate cacheInMemoryQueue.async { let objsToSave = self.allObjects let currentWriteRequestCount = self.writeRequestCount //print("[CACHE] SAVING [\(currentWriteRequestCount)] \(objsToSave.count) objs to disk") self.cacheOnDiskQueue.async { self.saveToDisk(objects: objsToSave) //print("[CACHE] SAVED [\(currentWriteRequestCount)] \(objsToSave.count) objs to disk: \(String(format:"%.4f", Date().timeIntervalSinceReferenceDate - start)) secs") // something has changed while we were writing to disk - write again! if currentWriteRequestCount != self.writeRequestCount { self.writeCurrentStateToDisk() } else { // reset timer so that another request can be made self.writeToDiskTimer = nil //print("[CACHE] no pending write requests") } } } } fileprivate func retreiveFromDisk() -> [SerializedV1PoolObject]? { guard let path = diskCachePath else { return nil } if let objDicts = NSArray(contentsOfFile: path) { // map [[String:AnyObject]] -> [(poolId, jsonData)] var serializedObjs: [SerializedV1PoolObject] = [] for arrData in objDicts { if let objDict = (arrData as? [String: AnyObject])?.first, let jsonData = objDict.value as? Data { serializedObjs.append((objDict.key, jsonData)) } } return serializedObjs } return nil } fileprivate func saveToDisk(objects: [SerializedV1PoolObject]) { guard let path = diskCachePath else { return } // map [(poolId, jsonData)] -> [[String:AnyObject]] let objDicts: [[String: AnyObject]] = objects.map { (object: SerializedV1PoolObject) in return [object.poolId: object.jsonData as AnyObject] } (objDicts as NSArray).write(toFile: path, atomically: true) } }
mit
3ec1376adaa5771925cfcf0df56f866e
37.564767
181
0.554749
4.985265
false
false
false
false
BeezleLabs/HackerTracker-iOS
hackertracker/PongScene.swift
1
4063
// // PongScene.swift // hackertracker // // Created by Benjamin Humphries on 7/20/17. // Copyright © 2017 Beezle Labs. All rights reserved. // import SpriteKit class PongScene: SKScene, SKPhysicsContactDelegate { let xPos: CGFloat = 135.0 var left: SKSpriteNode? var right: SKSpriteNode? var skull: SKSpriteNode? var skullPhysicsBody: SKPhysicsBody? override func didMove(to view: SKView) { super.didMove(to: view) left = childNode(withName: "left") as? SKSpriteNode right = childNode(withName: "right") as? SKSpriteNode skull = childNode(withName: "skull") as? SKSpriteNode createFrameCollision() skullPhysicsBody = skull?.physicsBody skullPhysicsBody?.usesPreciseCollisionDetection = true } override func didChangeSize(_ oldSize: CGSize) { super.didChangeSize(oldSize) createFrameCollision() } func createFrameCollision() { physicsBody = SKPhysicsBody(edgeLoopFrom: frame) physicsBody?.usesPreciseCollisionDetection = true physicsBody?.categoryBitMask = .max physicsBody?.collisionBitMask = .max physicsBody?.restitution = 1 physicsBody?.friction = 0 } func play() { reset() startingAnimations { self.startGame() } } func reset() { skull?.physicsBody?.isDynamic = false left?.removeAllActions() right?.removeAllActions() left?.position = CGPoint(x: -1, y: 1) left?.zRotation = CGFloat(1.04719758 * 8.0 * .pi) right?.position = CGPoint(x: 1, y: 1) right?.zRotation = CGFloat(-1.04719758 * 8.0 * .pi) skull?.position = CGPoint(x: 0, y: 12) skull?.zRotation = 0.0 } private func startingAnimations(completion: @escaping () -> Swift.Void) { let leftAction = SKAction.sequence([ .wait(forDuration: 0.2), .group([ .move(to: CGPoint(x: -xPos, y: 0), duration: 0.4), .rotate(toAngle: 0.0, duration: 0.5), ]), ]) left?.run(leftAction) let rightAction = SKAction.sequence([ .wait(forDuration: 0.2), .group([ .move(to: CGPoint(x: xPos, y: 0), duration: 0.4), .rotate(toAngle: 0.0, duration: 0.5), ]), ]) right?.run(rightAction) { self.skull?.physicsBody?.isDynamic = true completion() } } private func startGame() { guard let skull = skull else { print("skull is nil") return } let duration = 0.5 let leftPlay = SKAction.repeatForever( .sequence([ .wait(forDuration: 0.05), .run { let xPos = self.skull?.position.x ?? 0 if xPos < 0 { self.left?.run( .move(to: CGPoint(x: -self.xPos, y: skull.position.y), duration: duration / 8)) } else { self.left?.run( .move(to: CGPoint(x: -self.xPos, y: -skull.position.y), duration: duration)) } }, ]) ) left?.run(leftPlay, withKey: "leftPlay") let rightPlay = SKAction.repeatForever( .sequence([ .wait(forDuration: 0.05), .run { let xPos = self.skull?.position.x ?? 0 if xPos < 0 { self.right?.run( .move(to: CGPoint(x: self.xPos, y: -skull.position.y), duration: duration)) } else { self.right?.run( .move(to: CGPoint(x: self.xPos, y: skull.position.y), duration: duration / 8)) } }, ]) ) right?.run(rightPlay, withKey: "rightPlay") let sign = Double.random(in: 0...1) - 0.5 > 0 ? 1.0 : -1.0 skull.physicsBody?.applyImpulse(CGVector(dx: sign * 0.9, dy: sign * 0.9)) } }
gpl-2.0
8e9816d8d1fe640feba8dea3233ab2e0
29.088889
119
0.526588
4.174717
false
false
false
false
Wolox/wolmo-core-ios
WolmoCore/Extensions/Foundation/String.swift
1
7120
// // String.swift // WolmoCore // // Created by Guido Marucci Blas on 5/7/16. // Copyright © 2016 Wolox. All rights reserved. // import Foundation public extension String { /** Returns a localized representation of the string. - parameter bundle: Bundle were to search for localization. - parameter arguments: Formatting arguments. - seealso: `NSLocalizedString. */ func localized(withArguments arguments: CVarArg..., bundle: Bundle = Bundle.main) -> String { let localized = NSLocalizedString(self, tableName: .none, bundle: bundle, value: "", comment: "") if arguments.isNotEmpty { // Can't call .format(with:): https://stackoverflow.com/a/24024724 // Once inside the function, a CVarArg... becomes a [CVarArg] // and when passing it on to another function that receives CVarArg, // it interprets that you are passing only one CVarArg which is an array. return String(format: localized, arguments: arguments) } return localized } /** Returns a the formatted string. - parameter arguments: Formatting arguments. - seealso: `String.init(format:arguments:)`. */ func format(with arguments: CVarArg...) -> String { return String(format: self, arguments: arguments) } /** Returns an NSAttributedString with the same content as self but with the attributes specified for each first appearance of substrings passed. - parameter attributes: A dictionary that specifies the attributes to add to the substring specified. The attributes should be specified with a dictionary itself in the same format required by the NSAttributedString. The possible keys are specified in `NSAttributedString.h` (like `NSFontAttributeName`). - seealso: NSMutableAttributedString.addAttributes(_:range:) */ func format(withAttributes attrs: [String: [NSAttributedString.Key: Any]]) -> NSAttributedString { let attributedString = NSMutableAttributedString(string: self) let nSStringWithFormat = self as NSString for (substring, attributes) in attrs { attributedString.addAttributes(attributes, range: nSStringWithFormat.range(of: substring)) } return attributedString } /** Builds an NSURL from a string. */ var url: URL? { return URL(string: self) } /** Checks if the string has spaces or not. */ var hasSpaces: Bool { let whitespace = CharacterSet.whitespaces let range = rangeOfCharacter(from: whitespace) return range != .none } /** Checks if a string is a valid email or not. */ func isValidEmail() -> Bool { let emailRegEx = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: self) } /** Returns a copy of the string without its leading and trailing whitespace and newlines. */ var trimmed: String { return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } /** Returns a new string in which all occurrences of a target string in a specified range of the String are replaced by another given string. - parameter target: The string to replace. - parameter with: The replacement. - parameter options: The comparing options. Default: LiteralSearch - parameter range: The range of the string to search. - seealso: stringByReplacingOccurrencesOfString(). */ func replacing(_ target: String, with replacement: String, options: NSString.CompareOptions = .literal, range: Range<Index>? = .none) -> String { return replacingOccurrences(of: target, with: replacement, options: .literal, range: range) } /** Returns a new string without whitespaces. */ var withoutWhiteSpaces: String { return replacing(" ", with: "") } /** Returns true if the string is not empty, false if not. */ var isNotEmpty: Bool { return !isEmpty } /** Returns a new string that contains the same as self except for the given `suffix`. If it doesn't have the suffix, it returns the same as self. If it has the suffix more than one time, it just removes the last occurence of it. The comparison is both case sensitive and Unicode safe. - seealso: hasSuffix. */ func remove(suffix: String) -> String { if hasSuffix(suffix) { return String(self.dropLast(suffix.count)) } return self } /** Returns a new string that contains the same as self except for the given `prefix`. If it doesn't have the prefix, it returns the same as self. If it has the prefix more than one time, it just removes the first occurence of it. The comparison is both case sensitive and Unicode safe. - seealso: hasPrefix. */ func remove(prefix: String) -> String { if hasPrefix(prefix) { return String(self.dropFirst(prefix.count)) } return self } /** Returns UIImage drawing of the string, it's recomended for using emojis as images, but it can be used with any string. - parameter fontSize: CGFloat, size of the font to use on the represented string. */ func toImage(fontSize: CGFloat) -> UIImage? { return toImage(font: UIFont.systemFont(ofSize: fontSize)) } /** Returns UIImage drawing of the string, it's recomended for using emojis as images, but it can be used with any string. - parameter font: UIFont to apply to the drawn string. */ func toImage(font: UIFont) -> UIImage? { let label = UILabel() label.text = self label.font = font label.sizeToFit() UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0) UIColor.clear.set() let paragraph = NSMutableParagraphStyle() paragraph.alignment = .center self.draw(in: label.bounds, withAttributes: [NSAttributedString.Key.font: font, NSAttributedString.Key.paragraphStyle: paragraph]) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } /** Repeats a string multiple times. - parameter lhs: string to repeat. - parameter rhs: number of times to repeat string. */ static func * (lhs: String, rhs: Int) -> String { return String(repeating: lhs, count: rhs) } /** Repeats a string multiple times. - parameter lhs: number of times to repeat string. - parameter rhs: string to repeat. */ static func * (lhs: Int, rhs: String) -> String { return String(repeating: rhs, count: lhs) } }
mit
fd011ae053b9ae102ffc3691d1aaf9fa
33.726829
160
0.633235
4.781061
false
false
false
false
RemyDCF/tpg-offline
tpg offline/Routes/FavoriteRouteTableViewCell.swift
1
2583
// // FavoriteRouteTableViewCell.swift // tpg offline // // Created by Rémy Da Costa Faro on 24/09/2017. // Copyright © 2018 Rémy Da Costa Faro. All rights reserved. // import UIKit class FavoriteRouteTableViewCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let route = self.route else { return 0 } return (route.via ?? []).count + 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "favoriteCell", for: indexPath) as? FavoriteRouteSubTableViewCell else { return UITableViewCell() } if indexPath.row == 0 { cell.label.text = route?.from?.name ?? "" cell.icon.image = #imageLiteral(resourceName: "firstStep").maskWith(color: App.textColor) } else if indexPath.row == (route?.via ?? []).count + 1 { cell.label.text = route?.to?.name ?? "" cell.icon.image = #imageLiteral(resourceName: "endStep").maskWith(color: App.textColor) } else { cell.icon.image = #imageLiteral(resourceName: "middleStep").maskWith(color: App.textColor) if let via = (route?.via ?? [])[safe: indexPath.row - 1] { cell.label.text = via.name } } cell.label.textColor = App.textColor cell.backgroundColor = .clear return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 30 } @IBOutlet weak var tableView: UITableView! @IBOutlet weak var heightConstraint: NSLayoutConstraint! var route: Route? = nil { didSet { guard let route = route else { return } self.tableView.reloadData() if App.darkMode { let selectedView = UIView() selectedView.backgroundColor = .black self.selectedBackgroundView = selectedView } else { let selectedView = UIView() selectedView.backgroundColor = UIColor.white.darken(by: 0.1) self.selectedBackgroundView = selectedView } heightConstraint.constant = CGFloat(60 + ((route.via ?? []).count * 30)) } } override func awakeFromNib() { super.awakeFromNib() } } class FavoriteRouteSubTableViewCell: UITableViewCell { @IBOutlet weak var icon: UIImageView! @IBOutlet weak var label: UILabel! }
mit
f8ef41f450c5107a04cb7453720051c6
30.851852
96
0.63062
4.708029
false
false
false
false
ztyjr888/WeChat
WeChat/Discover/ScanViewController.swift
1
13702
// // DiscoverScanViewController.swift // WeChat // // Created by Smile on 16/7/19. // Copyright © 2016年 [email protected]. All rights reserved. // import UIKit import AVFoundation //扫一扫功能,使用AVFoundation框架,需要实现AVCaptureMetadataOutputObjectsDelegate协议 class ScanViewController: UIViewController,AVCaptureMetadataOutputObjectsDelegate { //MARKS: 会话 var captureSession:AVCaptureSession! //MARKS: 扑捉图像 var videoPreviewLayer:AVCaptureVideoPreviewLayer! //MARKS: 二维码图层 var qrCodeFrameView:UIView? //MARKS: 设备 var captureDevice:AVCaptureDevice! //MARKS: 输入设备 var captureInput:AVCaptureInput! //MARKS: 输出设备 var captureMetaOutput:AVCaptureMetadataOutput! //MARKS: 扫描滚动条 var line: UIImageView! let screenWidth = UIScreen.mainScreen().bounds.size.width let screenHeight = UIScreen.mainScreen().bounds.size.height let screenSize = UIScreen.mainScreen().bounds.size var traceNumber = 0 var upORdown = false var timer:NSTimer! var isSecurity:Bool = true override func viewDidLoad() { super.viewDidLoad() //设置标题 self.title = "二维码扫描" if !initSetting() { isSecurity = false return } if !initCamera() { return } initScanLine() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if isSecurity { captureSession.startRunning()//调用视频捕获回话的startRunning方法来启动 timer = NSTimer(timeInterval: 0.02, target: self, selector: #selector(ScanViewController.scanLineAnimation), userInfo: nil, repeats: true) NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode) } } override func viewWillDisappear(animated: Bool) { if isSecurity { traceNumber = 0 upORdown = false captureSession.stopRunning() timer.invalidate() timer = nil } super.viewWillDisappear(animated) } //MARKS: 初始化相机设备 //MARKS: 二维码的读取完全是基于视频捕获的,那么为了实时捕获视频,我们只需要以合适的AVCaptureDevice对象作为输入参数去实例化一个AVCaptureSession对象 func initCamera() -> Bool{ //捕获视频数据 captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) //以视频设备为输入参数去实例化了一个AVCaptureSession会话,用它来实现实时视频捕获 do { captureInput = try AVCaptureDeviceInput(device: captureDevice) } catch let error as NSError { print(error.localizedDescription) return false } //输出端 captureMetaOutput = AVCaptureMetadataOutput() //设置代理,GCD的串行执行队列 captureMetaOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) captureMetaOutput.rectOfInterest = makeScanReaderInterestRect() //AVCaptureSession会话是用来管理视频数据流从输入设备传送到输出端的会话过程的。 captureSession = AVCaptureSession() captureSession.sessionPreset = AVCaptureSessionPresetHigh//高质量采集率 //添加输入输出设备 if captureSession.canAddInput(captureInput){ captureSession.addInput(captureInput) } if captureSession.canAddOutput(captureMetaOutput){ captureSession.addOutput(captureMetaOutput) } //metadataObjectTypes属性也非常重要,因为它的值会被用来判定整个应用程序对哪类元数据感兴趣 captureMetaOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code] //显示摄像头捕获到的图像 videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill videoPreviewLayer.frame = view.bounds //设置扫描区域界面 self.view.layer.insertSublayer(videoPreviewLayer, atIndex: 0) self.view.addSubview(makeScanCameraShadowView(makeScanReaderRect())) self.view.addSubview(makeScanView()) return true } func makeScanView() -> UIView{ let rect:CGRect = makeScanReaderRect() let labelTotalHeight:CGFloat = 50 let rectView = UIView() rectView.frame = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height + labelTotalHeight) let labelTopPadding:CGFloat = 20 let labelView = makeView(CGRectMake(0, rect.size.height + labelTopPadding, rect.size.width, labelTotalHeight), labelTopPadding: labelTopPadding) rectView.addSubview(labelView) return rectView } func makeView(rect:CGRect,labelTopPadding:CGFloat) -> UIView{ let view = UIView(frame: rect) let labelHeight:CGFloat = 10 let label1 = createLabel(CGRectMake(0, 0, rect.width, labelHeight), string: "将二维码/条码放入框内,即可自动扫描", color: UIColor.whiteColor(), fontName: "AlNile", fontSize: 16) view.addSubview(label1) let label2 = createLabel(CGRectMake(0, labelHeight + labelTopPadding, rect.width, labelHeight), string: "我的二维码", color: UIColor.greenColor(), fontName: "AlNile", fontSize: 16) view.addSubview(label2) return view } func createLabel(frame:CGRect,string:String,color:UIColor,fontName:String,fontSize:CGFloat) -> UILabel{ let label = UILabel(frame: frame) label.textAlignment = .Center label.font = UIFont(name: fontName, size: fontSize) label.textColor = color label.numberOfLines = 1 label.text = string return label } //MARKS: 设置扫描线条 func initScanLine(){ let rect = makeScanReaderRect() var imageSize: CGFloat = 20.0 let imageX = rect.origin.x let imageY = rect.origin.y let width = rect.size.width let height = rect.size.height + 2 /// 四个边角 let imageViewTL = UIImageView(frame: CGRectMake(imageX, imageY, imageSize, imageSize)) imageViewTL.image = UIImage(named: "scan_tl") //imageSize = (imageViewTL.image?.size.width)! self.view.addSubview(imageViewTL) let imageViewTR = UIImageView(frame: CGRectMake(imageX + width - imageSize, imageY, imageSize, imageSize)) imageViewTR.image = UIImage(named: "scan_tr") self.view.addSubview(imageViewTR) let imageViewBL = UIImageView(frame: CGRectMake(imageX, imageY + height - imageSize, imageSize, imageSize)) imageViewBL.image = UIImage(named: "scan_bl") self.view.addSubview(imageViewBL) let imageViewBR = UIImageView(frame: CGRectMake(imageX + width - imageSize, imageY + height - imageSize, imageSize, imageSize)) imageViewBR.image = UIImage(named: "scan_br") self.view.addSubview(imageViewBR) line = UIImageView(frame: CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 2)) line.image = UIImage(named: "scan_line") self.view.addSubview(line) } //MARKS: 设置扫描区域界面 func makeScanCameraShadowView(innerRect: CGRect) -> UIView { let referenceImage = UIImageView(frame: self.view.bounds) UIGraphicsBeginImageContext(referenceImage.frame.size) let context = UIGraphicsGetCurrentContext() CGContextSetRGBFillColor(context, 0, 0, 0, 0.5) var drawRect = CGRectMake(0, 0, screenWidth, screenHeight) CGContextFillRect(context, drawRect) drawRect = CGRectMake(innerRect.origin.x - referenceImage.frame.origin.x, innerRect.origin.y - referenceImage.frame.origin.y, innerRect.size.width, innerRect.size.height) CGContextClearRect(context, drawRect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() referenceImage.image = image return referenceImage } // MARK: Rect func makeScanReaderRect() -> CGRect { let scanSize = (min(screenWidth, screenHeight) * 3) / 4 var scanRect = CGRectMake(0, 0, scanSize, scanSize) scanRect.origin.x += (screenWidth / 2) - (scanRect.size.width / 2) scanRect.origin.y += (screenHeight / 2) - (scanRect.size.height / 2) return scanRect } //MARKS: 设置AVCaptureMetadataOutput 的rectOfInterest 属性来配置解析范围 //MARKS: iPhone4s屏幕,大小640x960 func makeScanReaderInterestRect2(captureMetaOutput:AVCaptureMetadataOutput){ let cropRect = makeScanReaderRect() let size:CGSize = self.view.bounds.size let bounds:CGRect = self.view.bounds let p1:CGFloat = size.height/size.width let p2:CGFloat = 1920/1080; //使用了1080p的图像输出 if (p1 < p2) { let fixHeight:CGFloat = bounds.size.width * 1920 / 1080 let fixPadding:CGFloat = (fixHeight - size.height)/2 captureMetaOutput.rectOfInterest = CGRectMake((cropRect.origin.y + fixPadding)/fixHeight, cropRect.origin.x/size.width, cropRect.size.height/fixHeight, cropRect.size.width/size.width) } else { let fixWidth:CGFloat = bounds.size.height * 1080 / 1920 let fixPadding:CGFloat = (fixWidth - size.width)/2 captureMetaOutput.rectOfInterest = CGRectMake(cropRect.origin.y/size.height, (cropRect.origin.x + fixPadding)/fixWidth, cropRect.size.height/size.height, cropRect.size.width/fixWidth) } } func makeScanReaderInterestRect() -> CGRect { let rect = makeScanReaderRect() let x = rect.origin.x / screenWidth let y = rect.origin.y / screenHeight let width = rect.size.width / screenWidth let height = rect.size.height / screenHeight return CGRectMake(x, y, width, height) } //MARKS: 是否打开权限 func initSecutry() -> Bool{ //获取相机权限 let status:AVAuthorizationStatus = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) //判断摄像头是否打开 /*if !UIImagePickerController.isSourceTypeAvailable(.Camera) { return false }*/ if(status == .Restricted || status == .Denied){ return false } return true } //MARKS: 初始化权限 func initSetting() -> Bool{ if !initSecutry() { let alertController = UIAlertController(title: "二维码扫描", message: "请在iPhone的“设置”-“隐私”-“相机”功能中,找到“WeChat”打开相机访问权限", preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil) alertController.addAction(okAction) self.presentViewController(alertController, animated: true, completion: nil) return false } return true } // MARKS: 定时器 func scanLineAnimation() { let rect = makeScanReaderRect() let lineFrameX = rect.origin.x let lineFrameY = rect.origin.y let downHeight = rect.size.height if upORdown == false { traceNumber += 1 line.frame = CGRectMake(lineFrameX, lineFrameY + CGFloat(2 * traceNumber), downHeight, 2) if CGFloat(2 * traceNumber) > downHeight - 2 { upORdown = true } } else { traceNumber -= 1 line.frame = CGRectMake(lineFrameX, lineFrameY + CGFloat(2 * traceNumber), downHeight, 2) if traceNumber == 0 { upORdown = false } } } //MARKS: 解码二维码 func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { if metadataObjects == nil || metadataObjects.count == 0 { return } if metadataObjects.count == 0 { return } let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject let alertController = UIAlertController(title: "扫描结果", message: metadataObj.stringValue, preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil) alertController.addAction(okAction) self.presentViewController(alertController, animated: true, completion: nil) } }
apache-2.0
e27c694447b47aa590b710a2030753f2
36.092219
183
0.621941
4.820599
false
false
false
false
Fenrikur/ef-app_ios
Eurofurence/Modules/Dealers/Presenter/DealersPresenter.swift
1
6218
import Foundation class DealersPresenter: DealersSceneDelegate, DealersViewModelDelegate, DealersSearchViewModelDelegate { private struct AllDealersBinder: DealersBinder { var binder: DealerGroupsBinder func bind(_ component: DealerGroupHeader, toDealerGroupAt index: Int) { binder.bind(component, toDealerGroupAt: index) } func bind(_ component: DealerComponent, toDealerAt indexPath: IndexPath) { binder.bind(component, toDealerAt: indexPath) } } private struct SearchResultsBindingAdapter: DealersSearchResultsBinder { var binder: DealerGroupsBinder func bind(_ component: DealerGroupHeader, toDealerSearchResultGroupAt index: Int) { binder.bind(component, toDealerGroupAt: index) } func bind(_ component: DealerComponent, toDealerSearchResultAt indexPath: IndexPath) { binder.bind(component, toDealerAt: indexPath) } } private struct DealerGroupsBinder { var viewModels: [DealersGroupViewModel] func bind(_ component: DealerGroupHeader, toDealerGroupAt index: Int) { let group = viewModels[index] component.setDealersGroupTitle(group.title) } func bind(_ component: DealerComponent, toDealerAt indexPath: IndexPath) { let group = viewModels[indexPath.section] let dealer = group.dealers[indexPath.item] component.setDealerTitle(dealer.title) component.setDealerSubtitle(dealer.subtitle) dealer.fetchIconPNGData(completionHandler: component.setDealerIconPNGData) if dealer.isPresentForAllDays { component.hideNotPresentOnAllDaysWarning() } else { component.showNotPresentOnAllDaysWarning() } if dealer.isAfterDarkContentPresent { component.showAfterDarkContentWarning() } else { component.hideAfterDarkContentWarning() } } } private struct CategoriesBinder: DealerCategoriesBinder { var viewModel: DealerCategoriesViewModel func bindCategoryComponent(_ component: DealerCategoryComponentScene, at index: Int) { let categoryViewModel = viewModel.categoryViewModel(at: index) categoryViewModel.add(CategoryBinder(viewModel: categoryViewModel, component: component)) } } private struct CategoryBinder: DealerCategoryViewModelObserver { private let viewModel: DealerCategoryViewModel private let component: DealerCategoryComponentScene init(viewModel: DealerCategoryViewModel, component: DealerCategoryComponentScene) { self.viewModel = viewModel self.component = component component.setCategoryTitle(viewModel.title) component.setSelectionHandler(viewModel.toggleCategoryActiveState) viewModel.add(self) } func categoryDidEnterActiveState() { component.showActiveCategoryIndicator() } func categoryDidEnterInactiveState() { component.hideActiveCategoryIndicator() } } private let scene: DealersScene private let interactor: DealersInteractor private let delegate: DealersModuleDelegate private var viewModel: DealersViewModel? private var searchViewModel: DealersSearchViewModel? init(scene: DealersScene, interactor: DealersInteractor, delegate: DealersModuleDelegate) { self.scene = scene self.interactor = interactor self.delegate = delegate scene.setDelegate(self) scene.setDealersTitle(.dealers) } func dealersSceneDidLoad() { interactor.makeDealersViewModel { (viewModel) in self.viewModel = viewModel viewModel.setDelegate(self) } interactor.makeDealersSearchViewModel { (viewModel) in self.searchViewModel = viewModel viewModel.setSearchResultsDelegate(self) } } func dealersSceneDidChangeSearchQuery(to query: String) { searchViewModel?.updateSearchResults(with: query) } func dealersSceneDidSelectDealer(at indexPath: IndexPath) { scene.deselectDealer(at: indexPath) guard let identifier = viewModel?.identifierForDealer(at: indexPath) else { return } delegate.dealersModuleDidSelectDealer(identifier: identifier) } func dealersSceneDidSelectDealerSearchResult(at indexPath: IndexPath) { guard let identifier = searchViewModel?.identifierForDealer(at: indexPath) else { return } delegate.dealersModuleDidSelectDealer(identifier: identifier) } func dealersSceneDidPerformRefreshAction() { viewModel?.refresh() } func dealersSceneDidRevealCategoryFiltersScene(_ filtersScene: DealerCategoriesFilterScene) { interactor.makeDealerCategoriesViewModel { (viewModel) in filtersScene.bind(viewModel.numberOfCategories, using: CategoriesBinder(viewModel: viewModel)) } } func dealersRefreshDidBegin() { scene.showRefreshIndicator() } func dealersRefreshDidFinish() { scene.hideRefreshIndicator() } func dealerGroupsDidChange(_ groups: [DealersGroupViewModel], indexTitles: [String]) { let itemsPerSection = groups.map({ $0.dealers.count }) let binder = DealerGroupsBinder(viewModels: groups) scene.bind(numberOfDealersPerSection: itemsPerSection, sectionIndexTitles: indexTitles, using: AllDealersBinder(binder: binder)) } func dealerSearchResultsDidChange(_ groups: [DealersGroupViewModel], indexTitles: [String]) { let itemsPerSection = groups.map({ $0.dealers.count }) let binder = DealerGroupsBinder(viewModels: groups) scene.bindSearchResults(numberOfDealersPerSection: itemsPerSection, sectionIndexTitles: indexTitles, using: SearchResultsBindingAdapter(binder: binder)) } }
mit
f3abf29958505113f7e2cd8de5fffeca
34.129944
106
0.671116
5.444834
false
false
false
false
mitsuaki1229/BeaconDetection
BeaconDetection/Simulator/SimulatorView.swift
1
4540
// // SimulatorView.swift // BeaconDetection // // Created by Mitsuaki Ihara on 2017/08/01. // Copyright © 2017年 Mitsuaki Ihara. All rights reserved. // import SnapKit import UIKit class SimulatorView: UIView, CustomView { let backgroundScrollView = UIScrollView() private let contentView = UIView() private let uuidItemNameLabel = { () -> UILabel in let label = UILabel() label.text = "UUID:" label.adjustsFontSizeToFitWidth = true return label }() private let majorItemNameLabel = { () -> UILabel in let label = UILabel() label.text = "major:" label.adjustsFontSizeToFitWidth = true return label }() private let minorItemNameLabel = { () -> UILabel in let label = UILabel() label.text = "minor:" label.adjustsFontSizeToFitWidth = true return label }() private let itemNameStackView = { () -> UIStackView in let stackView = UIStackView() stackView.axis = .vertical stackView.alignment = .leading stackView.distribution = .fillEqually stackView.spacing = 2 return stackView }() let uuidLabel = { () -> UILabel in let label = UILabel() label.lineBreakMode = .byWordWrapping label.numberOfLines = 2 return label }() let majorLabel = UILabel() let minorLabel = UILabel() let backgroundImageView = { () -> UIImageView in let imageView = UIImageView() imageView.image = #imageLiteral(resourceName: "SimulatorBackground") return imageView }() private let simulatorTerminalImageView = { () -> UIImageView in let imageView = UIImageView() imageView.image = #imageLiteral(resourceName: "SimulatorTerminal") return imageView }() private let itemStackView = { () -> UIStackView in let stackView = UIStackView() stackView.axis = .vertical stackView.alignment = .leading stackView.distribution = .fillEqually stackView.spacing = 2 return stackView }() override init(frame: CGRect) { super.init(frame: frame) if #available(iOS 13.0, *), UITraitCollection.current.userInterfaceStyle == .dark { } else { backgroundColor = .white } addSubviews() installConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addSubviews() { addSubview(backgroundScrollView) backgroundScrollView.addSubview(contentView) contentView.addSubview(backgroundImageView) contentView.addSubview(simulatorTerminalImageView) contentView.addSubview(itemNameStackView) itemNameStackView.addArrangedSubview(uuidItemNameLabel) itemNameStackView.addArrangedSubview(majorItemNameLabel) itemNameStackView.addArrangedSubview(minorItemNameLabel) contentView.addSubview(itemStackView) itemStackView.addArrangedSubview(uuidLabel) itemStackView.addArrangedSubview(majorLabel) itemStackView.addArrangedSubview(minorLabel) } func installConstraints() { backgroundScrollView.snp.makeConstraints { make in make.edges.equalToSuperview() } contentView.snp.makeConstraints { make in make.edges.equalToSuperview() make.width.equalTo(snp.width) } backgroundImageView.snp.makeConstraints { make in make.centerX.equalToSuperview() make.centerY.equalToSuperview().multipliedBy(0.8) make.width.height.equalTo(contentView.snp.width).multipliedBy(0.7) } simulatorTerminalImageView.snp.makeConstraints { make in make.centerX.centerY.equalTo(backgroundImageView) make.width.height.equalTo(backgroundImageView.snp.width).multipliedBy(0.7) } itemNameStackView.snp.makeConstraints { make in make.top.equalTo(backgroundImageView.snp.bottom) make.left.bottom.equalToSuperview().inset(20) } itemStackView.snp.makeConstraints { make in make.top.equalTo(itemNameStackView) make.bottom.right.equalToSuperview().inset(20) make.left.equalTo(itemNameStackView.snp.right) } } }
mit
def8d78708234a4b2e16fa396ff0df93
30.075342
91
0.623981
5.440048
false
false
false
false
kitasuke/SwiftProtobufSample
Client/Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobuf/TextFormatEncodingVisitor.swift
1
20408
// Sources/SwiftProtobuf/TextFormatEncodingVisitor.swift - Text format encoding support // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Text format serialization engine. /// // ----------------------------------------------------------------------------- import Foundation private let mapNameResolver: [Int:StaticString] = [1: "key", 2: "value"] /// Visitor that serializes a message into protobuf text format. internal struct TextFormatEncodingVisitor: Visitor { private var encoder: TextFormatEncoder private var nameMap: _NameMap? private var nameResolver: [Int:StaticString] private var extensions: ExtensionFieldValueSet? /// The protobuf text produced by the visitor. var result: String { return encoder.stringResult } /// Creates a new visitor that serializes the given message to protobuf text /// format. init(message: Message) { self.init(message: message, encoder: TextFormatEncoder()) } /// Creates a new visitor that serializes the given message to protobuf text /// format, using an existing encoder. private init(message: Message, encoder: TextFormatEncoder) { let nameMap: _NameMap? if let nameProviding = message as? _ProtoNameProviding { nameMap = type(of: nameProviding)._protobuf_nameMap } else { nameMap = nil } let extensions = (message as? ExtensibleMessage)?._protobuf_extensionFieldValues self.init(nameMap: nameMap, nameResolver: [:], extensions: extensions, encoder: encoder) } private init(nameMap: _NameMap?, nameResolver: [Int:StaticString], extensions: ExtensionFieldValueSet?, encoder: TextFormatEncoder) { self.nameMap = nameMap self.nameResolver = nameResolver self.extensions = extensions self.encoder = encoder } private mutating func emitFieldName(lookingUp fieldNumber: Int) { if let protoName = nameMap?.names(for: fieldNumber)?.proto { encoder.emitFieldName(name: protoName.utf8Buffer) } else if let protoName = nameResolver[fieldNumber] { encoder.emitFieldName(name: protoName) } else if let extensionName = extensions?[fieldNumber]?.protobufExtension.fieldName { encoder.emitExtensionFieldName(name: extensionName) } else { encoder.emitFieldNumber(number: fieldNumber) } } mutating func visitUnknown(bytes: Data) throws { try bytes.withUnsafeBytes { (p: UnsafePointer<UInt8>) -> () in var decoder = BinaryDecoder(forReadingFrom: p, count: bytes.count) try visitUnknown(decoder: &decoder, groupFieldNumber: nil) } } private mutating func visitUnknown(decoder: inout BinaryDecoder, groupFieldNumber: Int?) throws { while let tag = try decoder.getTag() { switch tag.wireFormat { case .varint: encoder.emitFieldNumber(number: tag.fieldNumber) var value: UInt64 = 0 encoder.startRegularField() try decoder.decodeSingularUInt64Field(value: &value) encoder.putUInt64(value: value) encoder.endRegularField() case .fixed64: encoder.emitFieldNumber(number: tag.fieldNumber) var value: UInt64 = 0 encoder.startRegularField() try decoder.decodeSingularFixed64Field(value: &value) encoder.putUInt64Hex(value: value, digits: 16) encoder.endRegularField() case .lengthDelimited: encoder.emitFieldNumber(number: tag.fieldNumber) var bytes = Internal.emptyData try decoder.decodeSingularBytesField(value: &bytes) bytes.withUnsafeBytes { (p: UnsafePointer<UInt8>) -> () in var testDecoder = BinaryDecoder(forReadingFrom: p, count: bytes.count) do { // Skip all the fields to test if it looks like a message while let _ = try testDecoder.nextFieldNumber() { } // No error? Output the message body. var subDecoder = BinaryDecoder(forReadingFrom: p, count: bytes.count) encoder.startMessageField() try visitUnknown(decoder: &subDecoder, groupFieldNumber: nil) encoder.endMessageField() } catch { // Field scan threw an error, so just dump it as a string. encoder.startRegularField() encoder.putBytesValue(value: bytes) encoder.endRegularField() } } case .startGroup: encoder.emitFieldNumber(number: tag.fieldNumber) encoder.startMessageField() try visitUnknown(decoder: &decoder, groupFieldNumber: tag.fieldNumber) encoder.endMessageField() case .endGroup: // Unknown data is scanned and verified by the // binary parser, so this can never fail. assert(tag.fieldNumber == groupFieldNumber) return case .fixed32: encoder.emitFieldNumber(number: tag.fieldNumber) var value: UInt32 = 0 encoder.startRegularField() try decoder.decodeSingularFixed32Field(value: &value) encoder.putUInt64Hex(value: UInt64(value), digits: 8) encoder.endRegularField() } } } // Visitor.swift defines default versions for other singular field types // that simply widen and dispatch to one of the following. Since Text format // does not distinguish e.g., Fixed64 vs. UInt64, this is sufficient. mutating func visitSingularFloatField(value: Float, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putFloatValue(value: value) encoder.endRegularField() } mutating func visitSingularDoubleField(value: Double, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putDoubleValue(value: value) encoder.endRegularField() } mutating func visitSingularInt64Field(value: Int64, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putInt64(value: value) encoder.endRegularField() } mutating func visitSingularUInt64Field(value: UInt64, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putUInt64(value: value) encoder.endRegularField() } mutating func visitSingularBoolField(value: Bool, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putBoolValue(value: value) encoder.endRegularField() } mutating func visitSingularStringField(value: String, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putStringValue(value: value) encoder.endRegularField() } mutating func visitSingularBytesField(value: Data, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putBytesValue(value: value) encoder.endRegularField() } mutating func visitSingularEnumField<E: Enum>(value: E, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putEnumValue(value: value) encoder.endRegularField() } mutating func visitSingularMessageField<M: Message>(value: M, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startMessageField() var visitor = TextFormatEncodingVisitor(message: value, encoder: encoder) if let any = value as? Google_Protobuf_Any { any.textTraverse(visitor: &visitor) } else { try! value.traverse(visitor: &visitor) } encoder = visitor.encoder encoder.endMessageField() } // Emit the full "verbose" form of an Any. This writes the typeURL // as a field name in `[...]` followed by the fields of the // contained message. internal mutating func visitAnyVerbose(value: Message, typeURL: String) { encoder.emitExtensionFieldName(name: typeURL) encoder.startMessageField() var visitor = TextFormatEncodingVisitor(message: value, encoder: encoder) if let any = value as? Google_Protobuf_Any { any.textTraverse(visitor: &visitor) } else { try! value.traverse(visitor: &visitor) } encoder = visitor.encoder encoder.endMessageField() } // Write a single special field called "#json". This // is used for Any objects with undecoded JSON contents. internal mutating func visitAnyJSONDataField(value: Data) { encoder.indent() encoder.append(staticText: "#json: ") encoder.putBytesValue(value: value) encoder.append(staticText: "\n") } // The default implementations in Visitor.swift provide the correct // results, but we get significantly better performance by only doing // the name lookup once for the array, rather than once for each element: mutating func visitRepeatedFloatField(value: [Float], fieldNumber: Int) throws { for v in value { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putFloatValue(value: v) encoder.endRegularField() } } mutating func visitRepeatedDoubleField(value: [Double], fieldNumber: Int) throws { for v in value { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putDoubleValue(value: v) encoder.endRegularField() } } mutating func visitRepeatedInt32Field(value: [Int32], fieldNumber: Int) throws { for v in value { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putInt64(value: Int64(v)) encoder.endRegularField() } } mutating func visitRepeatedInt64Field(value: [Int64], fieldNumber: Int) throws { for v in value { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putInt64(value: v) encoder.endRegularField() } } mutating func visitRepeatedUInt32Field(value: [UInt32], fieldNumber: Int) throws { for v in value { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putUInt64(value: UInt64(v)) encoder.endRegularField() } } mutating func visitRepeatedUInt64Field(value: [UInt64], fieldNumber: Int) throws { for v in value { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putUInt64(value: v) encoder.endRegularField() } } mutating func visitRepeatedSInt32Field(value: [Int32], fieldNumber: Int) throws { try visitRepeatedInt32Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedSInt64Field(value: [Int64], fieldNumber: Int) throws { try visitRepeatedInt64Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedFixed32Field(value: [UInt32], fieldNumber: Int) throws { try visitRepeatedUInt32Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedFixed64Field(value: [UInt64], fieldNumber: Int) throws { try visitRepeatedUInt64Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedSFixed32Field(value: [Int32], fieldNumber: Int) throws { try visitRepeatedInt32Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedSFixed64Field(value: [Int64], fieldNumber: Int) throws { try visitRepeatedInt64Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedBoolField(value: [Bool], fieldNumber: Int) throws { for v in value { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putBoolValue(value: v) encoder.endRegularField() } } mutating func visitRepeatedStringField(value: [String], fieldNumber: Int) throws { for v in value { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putStringValue(value: v) encoder.endRegularField() } } mutating func visitRepeatedBytesField(value: [Data], fieldNumber: Int) throws { for v in value { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putBytesValue(value: v) encoder.endRegularField() } } mutating func visitRepeatedEnumField<E: Enum>(value: [E], fieldNumber: Int) throws { for v in value { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putEnumValue(value: v) encoder.endRegularField() } } // Messages and groups mutating func visitRepeatedMessageField<M: Message>(value: [M], fieldNumber: Int) throws { for v in value { emitFieldName(lookingUp: fieldNumber) encoder.startMessageField() var visitor = TextFormatEncodingVisitor(message: v, encoder: encoder) if let any = v as? Google_Protobuf_Any { any.textTraverse(visitor: &visitor) } else { try! v.traverse(visitor: &visitor) } encoder = visitor.encoder encoder.endMessageField() } } // Google's C++ implementation of Text format supports two formats // for repeated numeric fields: "short" format writes the list as a // single field with values enclosed in `[...]`, "long" format // writes a separate field name/value for each item. They provide // an option for callers to select which output version they prefer. // Since this distinction mirrors the difference in Protobuf Binary // between "packed" and "non-packed", I've chosen to use the short // format for packed fields and the long version for repeated // fields. This provides a clear visual distinction between these // fields (including proto3's default use of packed) without // introducing the baggage of a separate option. private mutating func _visitPacked<T>(value: [T], fieldNumber: Int, encode: (T) -> ()) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() var firstItem = true encoder.startArray() for v in value { if !firstItem { encoder.arraySeparator() } encode(v) firstItem = false } encoder.endArray() encoder.endRegularField() } mutating func visitPackedFloatField(value: [Float], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: Float) in encoder.putFloatValue(value: v) } } mutating func visitPackedDoubleField(value: [Double], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: Double) in encoder.putDoubleValue(value: v) } } mutating func visitPackedInt32Field(value: [Int32], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: Int32) in encoder.putInt64(value: Int64(v)) } } mutating func visitPackedInt64Field(value: [Int64], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: Int64) in encoder.putInt64(value: v) } } mutating func visitPackedUInt32Field(value: [UInt32], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: UInt32) in encoder.putUInt64(value: UInt64(v)) } } mutating func visitPackedUInt64Field(value: [UInt64], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: UInt64) in encoder.putUInt64(value: v) } } mutating func visitPackedSInt32Field(value: [Int32], fieldNumber: Int) throws { try visitPackedInt32Field(value: value, fieldNumber: fieldNumber) } mutating func visitPackedSInt64Field(value: [Int64], fieldNumber: Int) throws { try visitPackedInt64Field(value: value, fieldNumber: fieldNumber) } mutating func visitPackedFixed32Field(value: [UInt32], fieldNumber: Int) throws { try visitPackedUInt32Field(value: value, fieldNumber: fieldNumber) } mutating func visitPackedFixed64Field(value: [UInt64], fieldNumber: Int) throws { try visitPackedUInt64Field(value: value, fieldNumber: fieldNumber) } mutating func visitPackedSFixed32Field(value: [Int32], fieldNumber: Int) throws { try visitPackedInt32Field(value: value, fieldNumber: fieldNumber) } mutating func visitPackedSFixed64Field(value: [Int64], fieldNumber: Int) throws { try visitPackedInt64Field(value: value, fieldNumber: fieldNumber) } mutating func visitPackedBoolField(value: [Bool], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: Bool) in encoder.putBoolValue(value: v) } } mutating func visitPackedEnumField<E: Enum>(value: [E], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: E) in encoder.putEnumValue(value: v) } } /// Helper to encapsulate the common structure of iterating over a map /// and encoding the keys and values. private mutating func _visitMap<K, V>( map: Dictionary<K, V>, fieldNumber: Int, coder: (inout TextFormatEncodingVisitor, K, V) throws -> () ) throws { for (k,v) in map { emitFieldName(lookingUp: fieldNumber) encoder.startMessageField() var visitor = TextFormatEncodingVisitor(nameMap: nil, nameResolver: mapNameResolver, extensions: nil, encoder: encoder) try coder(&visitor, k, v) encoder = visitor.encoder encoder.endMessageField() } } mutating func visitMapField<KeyType: MapKeyType, ValueType: MapValueType>( fieldType: _ProtobufMap<KeyType, ValueType>.Type, value: _ProtobufMap<KeyType, ValueType>.BaseType, fieldNumber: Int ) throws where KeyType.BaseType: Hashable { try _visitMap(map: value, fieldNumber: fieldNumber) { (visitor: inout TextFormatEncodingVisitor, key, value) throws -> () in try KeyType.visitSingular(value: key, fieldNumber: 1, with: &visitor) try ValueType.visitSingular(value: value, fieldNumber: 2, with: &visitor) } } mutating func visitMapField<KeyType: MapKeyType, ValueType: Enum>( fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type, value: _ProtobufEnumMap<KeyType, ValueType>.BaseType, fieldNumber: Int ) throws where KeyType.BaseType: Hashable, ValueType.RawValue == Int { try _visitMap(map: value, fieldNumber: fieldNumber) { (visitor: inout TextFormatEncodingVisitor, key, value) throws -> () in try KeyType.visitSingular(value: key, fieldNumber: 1, with: &visitor) try visitor.visitSingularEnumField(value: value, fieldNumber: 2) } } mutating func visitMapField<KeyType: MapKeyType, ValueType: Message & Hashable>( fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type, value: _ProtobufMessageMap<KeyType, ValueType>.BaseType, fieldNumber: Int ) throws where KeyType.BaseType: Hashable { try _visitMap(map: value, fieldNumber: fieldNumber) { (visitor: inout TextFormatEncodingVisitor, key, value) throws -> () in try KeyType.visitSingular(value: key, fieldNumber: 1, with: &visitor) try visitor.visitSingularMessageField(value: value, fieldNumber: 2) } } /// Called for each extension range. mutating func visitExtensionFields(fields: ExtensionFieldValueSet, start: Int, end: Int) throws { try fields.traverse(visitor: &self, start: start, end: end) } }
mit
5c3afcea27d1cc192473f869b7736673
37.946565
135
0.666797
4.715342
false
false
false
false
hilen/TSWeChat
TSWeChat/Classes/Chat/ChatHelper/UIScrollView+ChatAdditions.swift
1
3566
// // UIScrollView+ChatAdditions.swift // TSWeChat // // Created by Hilen on 12/16/15. // Copyright © 2015 Hilen. All rights reserved. // import Foundation extension UIScrollView { fileprivate struct AssociatedKeys { static var kKeyScrollViewVerticalIndicator = "_verticalScrollIndicator" static var kKeyScrollViewHorizontalIndicator = "_horizontalScrollIndicator" } /// YES if the scrollView's offset is at the very top. public var isAtTop: Bool { get { return self.contentOffset.y == 0.0 ? true : false } } /// YES if the scrollView's offset is at the very bottom. public var isAtBottom: Bool { get { let bottomOffset = self.contentSize.height - self.bounds.size.height return self.contentOffset.y == bottomOffset ? true : false } } /// YES if the scrollView can scroll from it's current offset position to the bottom. public var canScrollToBottom: Bool { get { return self.contentSize.height > self.bounds.size.height ? true : false } } /// The vertical scroll indicator view. public var verticalScroller: UIView { get { if (objc_getAssociatedObject(self, #function) == nil) { objc_setAssociatedObject(self, #function, self.safeValueForKey(AssociatedKeys.kKeyScrollViewVerticalIndicator), objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN); } return objc_getAssociatedObject(self, #function) as! UIView } } /// The horizontal scroll indicator view. public var horizontalScroller: UIView { get { if (objc_getAssociatedObject(self, #function) == nil) { objc_setAssociatedObject(self, #function, self.safeValueForKey(AssociatedKeys.kKeyScrollViewHorizontalIndicator), objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN); } return objc_getAssociatedObject(self, #function) as! UIView } } fileprivate func safeValueForKey(_ key: String) -> AnyObject{ let instanceVariable: Ivar = class_getInstanceVariable(type(of: self), key.cString(using: String.Encoding.utf8)!)! return object_getIvar(self, instanceVariable) as AnyObject; } /** Sets the content offset to the top. - parameter animated: animated YES to animate the transition at a constant velocity to the new offset, NO to make the transition immediate. */ public func scrollToTopAnimated(_ animated: Bool) { if !self.isAtTop { let bottomOffset = CGPoint.zero; self.setContentOffset(bottomOffset, animated: animated) } } /** Sets the content offset to the bottom. - parameter animated: animated YES to animate the transition at a constant velocity to the new offset, NO to make the transition immediate. */ public func scrollToBottomAnimated(_ animated: Bool) { if self.canScrollToBottom && !self.isAtBottom { let bottomOffset = CGPoint(x: 0.0, y: self.contentSize.height - self.bounds.size.height) self.setContentOffset(bottomOffset, animated: animated) } } /** Stops scrolling, if it was scrolling. */ public func stopScrolling() { guard self.isDragging else { return } var offset = self.contentOffset offset.y -= 1.0 self.setContentOffset(offset, animated: false) offset.y += 1.0 self.setContentOffset(offset, animated: false) } }
mit
a8d607a3bba336d4e378aba6974b767a
33.61165
178
0.647686
4.798116
false
false
false
false
KeithPiTsui/Pavers
Pavers/Sources/FRP/Guitar/Guitar.swift
2
3269
// // Guitar.swift // GuitarExample // // Created by Sabintsev, Arthur on 3/9/17. // Copyright © 2017 Arthur Ariel Sabintsev. All rights reserved. // import Foundation // MARK: - Guitar public struct Guitar { /// Regular expression pattern that will be used to evaluate a specific string. let pattern: String /// `fatalError` occurs when using this empty initializer as Guitar must be initialized using `init(pattern:)` or `init(chord:)`. public init() { fatalError("Guitar must be initialized using `init(pattern:)` or `init(chord:)`.") } /// Designated Initializer for `Guitar` /// /// - Parameters: /// - pattern: The pattern that will be used to perform the match. public init(pattern: String) { self.pattern = pattern } /// Delegating Initializer for `Guitar` /// /// - Parameters: /// - chord: A `chord`, or built-in regex pattern that will be used to perform the match. public init(chord: Chord) { self.init(pattern: chord.rawValue) } /// Evaluates a string for all instances of a regular expression pattern and returns a list of matched ranges for that string. /// /// - Parameters: /// - string: The string that will be evaluated. /// - options: Regular expression options that are applied to the string during matching. Defaults to []. /// /// - Returns: A list of matches. public func evaluateForRanges(from string: String, with options: NSRegularExpression.Options = []) -> [Range<String.Index>] { let range = NSRange(location: 0, length: string.count) guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else { return [] } let matches = regex.matches(in: string, options: [], range: range) let ranges = matches.compactMap { (match) -> Range<String.Index>? in let nsRange = match.range return nsRange.range(for: string) } return ranges } /// Evaluates a string for all instances of a regular expression pattern and returns a list of matched strings for that string. /// /// - Parameters: /// - string: The string that will be evaluated. /// - options: Regular expression options that are applied to the string during matching. Defaults to []. /// /// - Returns: A list of matches. public func evaluateForStrings(from string: String, with options: NSRegularExpression.Options = []) -> [String] { let ranges = evaluateForRanges(from: string) var strings: [String] = [] for range in ranges { strings.append(String(string[range])) } return strings } /// Tests a string to see if it matches the regular expression pattern. /// /// - Parameters: /// - string: The string that will be evaluated. /// - options: Regular expression options that are applied to the string during matching. Defaults to []. /// /// - Returns: `true` if string passes the test, otherwise, `false`. public func test(string: String, with options: NSRegularExpression.Options = []) -> Bool { return evaluateForRanges(from: string, with: options).count > 0 } }
mit
33fde33134c9a0c7199b0951cabf8009
35.311111
133
0.634027
4.501377
false
false
false
false
jay18001/brickkit-ios
Example/Source/Examples/Sticking/StackingFooterViewController.swift
1
2987
// // StackingFooterViewController.swift // BrickKit // // Created by Ruben Cagnie on 9/23/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import BrickKit private let StickySection = "Sticky Section" private let BuyButton = "BuyButton" private let BuySection = "BuySection" private let TotalLabel = "TotalLabel" class StackingFooterViewController: BrickApp.BaseBrickController { override class var brickTitle: String { return "Stacking Footers" } override class var subTitle: String { return "Example how to stack footers" } let numberOfLabels = 50 var repeatLabel: LabelBrick! var titleLabelModel: LabelBrickCellModel! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .brickBackground let layout = self.brickCollectionView.layout layout.zIndexBehavior = .bottomUp self.brickCollectionView.registerBrickClass(ButtonBrick.self) self.brickCollectionView.registerBrickClass(LabelBrick.self) let sticky = StickyFooterLayoutBehavior(dataSource: self) sticky.canStackWithOtherSections = true behavior = sticky let buyButton = ButtonBrick(BuyButton, backgroundColor: .brickGray1, title: "BUY") { cell in cell.configure() } let totalLabel = LabelBrick(TotalLabel, backgroundColor: .brickGray2, text: "TOTAL") { cell in cell.configure() } let section = BrickSection(bricks: [ BrickSection(bricks: [ LabelBrick(BrickIdentifiers.repeatLabel, width: .ratio(ratio: 0.5), height: .auto(estimate: .fixed(size: 200)), backgroundColor: UIColor.lightGray, dataSource: self), totalLabel ], inset: 10, edgeInsets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)), BrickSection(BuySection, bricks: [ buyButton ]) ]) section.repeatCountDataSource = self self.setSection(section) } } extension StackingFooterViewController: BrickRepeatCountDataSource { func repeatCount(for identifier: String, with collectionIndex: Int, collectionIdentifier: String) -> Int { if identifier == BrickIdentifiers.repeatLabel { return numberOfLabels } else { return 1 } } } extension StackingFooterViewController: LabelBrickCellDataSource { func configureLabelBrickCell(_ cell: LabelBrickCell) { cell.label.text = "BRICK \(cell.index + 1)" cell.configure() } } extension StackingFooterViewController: StickyLayoutBehaviorDataSource { func stickyLayoutBehavior(_ stickyLayoutBehavior: StickyLayoutBehavior, shouldStickItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> Bool { return identifier == BuySection || identifier == TotalLabel } }
apache-2.0
f23b9674f7f8c1ec00cfcbf8cdc95380
32.177778
238
0.681514
5.018487
false
false
false
false
Diuit/DUMessagingUIKit-iOS
DUMessagingUIKit/DUChatSettingViewController.swift
1
7612
// // DUChatSettingViewController.swift // DUMessagingUI // // Created by Pofat Diuit on 2016/5/30. // Copyright © 2016年 duolC. All rights reserved. // import UIKit import DUMessaging import DTTableViewManager // global constant public let DUTableViewCellReuseIdentifier = "DUTableViewCellReuseIdentifier" /** The `DUChatSettingViewController` class is an abstract class for displaying information of a chat room and configuring chat data with customize methods. */ open class DUChatSettingViewController: UIViewController, DUChatSettingUIProtocol, DTTableViewManageable, DUBlockDelegate { @IBOutlet weak var chatAvatarImageView: DUAvatarImageView! { didSet { chatAvatarImageView.image = chatDataForSetting?.avatarPlaceholderImage ?? UIImage.DUDefaultPersonAvatarImage() // XXX(Pofat) set image path will load the image chatAvatarImageView.imagePath = chatDataForSetting?.imagePath } } @IBOutlet weak var chatNameLabel: UILabel! { didSet { // set text chatNameLabel.text = chatDataForSetting?.chatTitle ?? "Chat room" // add tap listener let recognizer = UITapGestureRecognizer(target: self, action: #selector(DUChatSettingViewController.didTapChatTitleLabel(sender:))) chatNameLabel.addGestureRecognizer(recognizer) chatNameLabel.isUserInteractionEnabled = true } } @IBOutlet weak var leaveChatButton: UIButton! { didSet { leaveChatButton.addTarget(self, action: #selector(self.didPressLeaveChatButton(_:)), for: .touchUpInside) if chatDataForSetting?.chatSettingPageType == .direct { leaveChatButton.isHidden = true } } } @IBOutlet weak public var tableView: UITableView! public var chatDataForSetting: DUChatData? = nil static var nib: UINib { return UINib.init(nibName: String(describing: DUChatSettingViewController.self), bundle: Bundle.du_messagingUIKitBundle) } // MARK: life cycle override open func viewDidLoad() { super.viewDidLoad() DUChatSettingViewController.nib.instantiate(withOwner: self, options: nil) // adopt ui protocol adoptProtocolUIApperance() // setup tableView manager.startManaging(withDelegate: self) if self.chatDataForSetting?.chatSettingPageType == .direct { manager.register(DUBlockCell.self) manager.registerNibNamed("DUBlockCell", for: DUBlockCell.self) manager.memoryStorage.setItems([chatDataForSetting?.isBlocked ?? false], forSection: 0) let c: DUBlockCell = manager.tableView(tableView, cellForRowAt: IndexPath(row: 0, section: 0)) as! DUBlockCell //manager.itemForCellClass(DUBlockCell.self, atIndexPath: NSIndexPath(forRow: 0, inSection: 0)) c.delegate = self } else { manager.register(DUUserCell.self) manager.registerNibNamed("DUUserCell", for: DUUserCell.self) var addUser: UserData = UserData.init(name: "Add People", imagePath: nil) addUser.placeholderImage = UIImage.DUAddUserImage() manager.memoryStorage.setItems([addUser], forSection: 0) var membersArray: [UserData] = [] for member in self.chatDataForSetting!.chatMembers { membersArray.append(UserData.init(name: member, imagePath: nil)) } manager.memoryStorage.setItems(membersArray, forSection: 1) } tableView.tableFooterView = UIView() tableView.backgroundColor = UIColor.clear } open func tableView(_ tableView: UITableView, editActionsForRowAtIndexPath indexPath: IndexPath) -> [UITableViewRowAction]? { guard self.chatDataForSetting?.chatSettingPageType == .group && indexPath.section == 1 else { return nil } let block = UITableViewRowAction(style: .normal, title: "Block") { [weak self] action, index in // TODO: protocol function here self?.didPressCellBlockAction(atIndexPath: indexPath) } block.backgroundColor = UIColor.lightGray let remove = UITableViewRowAction(style: .normal, title: "Remove") { [weak self] action, index in // TODO: function here self?.didPressCellRemoveAction(atIndexPath: indexPath) } remove.backgroundColor = UIColor.red return [remove, block] } open func tableView(_ tableView: UITableView, canEditRowAtIndexPath indexPath: IndexPath) -> Bool { guard self.chatDataForSetting?.chatSettingPageType == .group && indexPath.section == 1 else { return false } return true } // MARK: Chat Setting view controller events /// Click event of Leave Group button open func didPressLeaveChatButton(_ sender: UIButton) { assert(false, "Error! You must override this function : \(#function)") } /// Block action of user tableViewCell in a group chat room open func didPressCellBlockAction(atIndexPath indexPath: IndexPath) { assert(false, "Error! You must override this function : \(#function)") } /// Remove action of user tableViewCell in a group chat room open func didPressCellRemoveAction(atIndexPath indexPath: IndexPath) { assert(false, "Error! You must override this function : \(#function)") } /// OK alertAction in chat-title-changing AlertController open func didPressOKForChangingChatTitle() { assert(false, "Error! You must override this function : \(#function)") } /// Implement how to block this user open func block() { assert(false, "Error! You must override this function : \(#function)") } /// Implement how to unblock this user open func unblock() { assert(false, "Error! You must override this function : \(#function)") } /// Tap gesture handler of chat title label open func didTapChatTitleLabel(sender: UITapGestureRecognizer) { if sender.state == .ended { let alertController = UIAlertController(title: "Change Name", message: "Enter a name for this chat", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) // FIXME: replace with protocol let okAction = UIAlertAction(title: "OK", style: .default, handler: { [weak self] alerAction in self?.didPressOKForChangingChatTitle() }) alertController.addAction(cancelAction) alertController.addAction(okAction) alertController.addTextField(configurationHandler: { textField in textField.placeholder = "New name" textField.text = self.chatDataForSetting?.chatTitle ?? "" }) self.present(alertController, animated: true, completion: nil) } } } // MARK: UI protocol for self public protocol DUChatSettingUIProtocol: GlobalUIProtocol, UIProtocolAdoption, NavigationBarTitle { var chatDataForSetting: DUChatData? { get set } } public extension DUChatSettingUIProtocol where Self: DUChatSettingViewController { var myBarTitle: String { if self.chatDataForSetting?.chatSettingPageType == .direct { return "Detail" } else { return "Group" } } func adoptProtocolUIApperance() { // setup all inherited UI protocols setupInheritedProtocolUI() } }
mit
666a1110b1c1cdf86d8d16f6ff989c4a
41.988701
156
0.662768
4.986239
false
false
false
false
jasnig/DouYuTVMutate
DouYuTVMutate/DouYuTV/Live/Controller/AllListController.swift
1
3972
// // AllListController.swift // DouYuTVMutate // // Created by ZeroJ on 16/7/16. // Copyright © 2016年 ZeroJ. All rights reserved. // import UIKit class AllListController: BaseViewController { struct ConstantValue { static let sectionHeaderHeight = CGFloat(44.0) static let anchorCellHeight = CGFloat(150.0) static let anchorCellMargin = CGFloat(10.0) } lazy var layout: UICollectionViewFlowLayout = { let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = ConstantValue.anchorCellMargin layout.minimumInteritemSpacing = ConstantValue.anchorCellMargin // 每一排显示两个cell layout.itemSize = CGSize(width: (self.view.bounds.width - 3*layout.minimumInteritemSpacing)/2, height: ConstantValue.anchorCellHeight) layout.scrollDirection = .Vertical // 间距 layout.sectionInset = UIEdgeInsets(top: ConstantValue.anchorCellMargin, left: ConstantValue.anchorCellMargin, bottom: ConstantValue.anchorCellMargin, right: ConstantValue.anchorCellMargin) return layout }() lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: self.layout) collectionView.registerNib(UINib(nibName: String(AnchorCell), bundle: nil), forCellWithReuseIdentifier: self.anchorCell) collectionView.backgroundColor = UIColor.whiteColor() collectionView.delegate = self collectionView.dataSource = self return collectionView }() let anchorCell = "anchorCell" private let viewModel: AllListViewModel init(viewModel: AllListViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // var dataModel: TagModel = TagModel() // 这里面获取到的view.bounds 不是最终的(ContentView里面设置之后才是准确的frame) override func viewDidLoad() { super.viewDidLoad() view.addSubview(collectionView) viewModel.loadDataWithHandler {[weak self] (loadState) in guard let `self` = self else { return } switch loadState { case .success: self.collectionView.reloadData() default: break } } } override func addConstraints() { collectionView.snp_makeConstraints { (make) in make.leading.equalTo(view) make.trailing.equalTo(view) make.top.equalTo(view) make.bottom.equalTo(view) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension AllListController: UICollectionViewDelegate, UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewModel.data.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(anchorCell, forIndexPath: indexPath) as! AnchorCell // 设置数据 cell.configCell(viewModel.data[indexPath.row]) return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let playerVc = PlayerController() playerVc.roomID = viewModel.data[indexPath.row].room_id playerVc.title = "播放" showViewController(playerVc, sender: nil) } }
mit
a0e63a5b800a897b8b491688404da732
29.896825
196
0.659132
5.325581
false
false
false
false
takecian/SwiftRoutes
Sources/SwiftRoutes.swift
1
4948
// // SwiftRoutes.swift // SwiftRoutes // // Created by FUJIKI TAKESHI on 2016/08/27. // Copyright © 2016年 takecian. All rights reserved. // import UIKit public typealias SwiftRoutesHandler = ((Dictionary<String, String>) -> Bool) let globalScheme = "SwiftRoutesGlobalScheme" let keyAbsoluteString = "absoluteString" /** SwiftRoutes manages URL as route pattern and corresponding handler. */ open class SwiftRoutes { /** Array of SwiftRoutes. Each SwiftRoutes is responsible for a specified scheme such as "http://", "myapp://". */ fileprivate static var routesControllers = [SwiftRoutes]() /** Responsible scheme */ fileprivate var scheme: String /** Array of SwiftRoute, each SwiftRoute has routing rule and handler. */ fileprivate var routes = [SwiftRoute]() // Create SwiftRoutes with scheme init(scheme: String) { self.scheme = scheme } /** Add route pattern and handler. SwiftRoutes is instantiated for each scheme. For example, SwiftRoutes instance for 'http://'. If developer does not specify scheme, SwiftRoutes for `globalRoutes` is instantiated. - parameter routePattern: Url to be added. - Parameter handler: Block called when route passed in `routeUrl(_)` matches routePattern. */ open class func addRoute(_ routePattern: URL, handler: @escaping SwiftRoutesHandler) { if let scheme = routePattern.scheme, scheme.count > 0 { SwiftRoutes.routesForScheme(routePattern.scheme!).addRoute(routePattern, priority: 0, handler: handler) } else { SwiftRoutes.globalRoutes().addRoute(routePattern, priority: 0, handler: handler) } } /** Remove route that matches `routePattern` - parameter routePattern: NSURL to be removed from SwiftRoutes. */ open class func removeRoute(_ routePattern: URL) { if let scheme = routePattern.scheme, scheme.count > 0 { SwiftRoutes.routesForScheme(routePattern.scheme!).removeRoute(routePattern) } else { SwiftRoutes.globalRoutes().removeRoute(routePattern) } } /** Remove all routes. */ open class func removeAllRoutes() { for controller in routesControllers { controller.removeAllRoutes() } } /** Routing url. SwiftRoutes will fire a handler that matches url. - parameter route: NSURL to be routed. - Returns: The results of routing. when handled, return true, when not handled, return false. */ open class func routeUrl(_ route: URL) -> Bool { var handled = false if let scheme = route.scheme, scheme.count > 0 { let routes = SwiftRoutes.routesForScheme(scheme) handled = routes.routeUrl(route) } if !handled { let routes = SwiftRoutes.globalRoutes() handled = routes.routeUrl(route) } return handled } fileprivate class func routesForScheme(_ scheme: String) -> SwiftRoutes { if let route = SwiftRoutes.routesControllers.filter({ (r) -> Bool in r.scheme == scheme }).first { return route } else { let route = SwiftRoutes(scheme: scheme) SwiftRoutes.routesControllers.append(route) return route } } /** Returns default SwiftRoutes. This instance is used when routePattern does not have scheme. */ fileprivate class func globalRoutes() -> SwiftRoutes { return SwiftRoutes.routesForScheme(globalScheme) } func addRoute(_ routePattern: URL, priority: Int, handler: @escaping SwiftRoutesHandler) { let route = SwiftRoute(pattern: routePattern, priority: priority, handler: handler) routes.append(route) } func removeRoute(_ routePattern: URL) { let removeTargets = routes.filter( { r -> Bool in routePattern == r.routePattern as URL }) for target in removeTargets { routes.remove(target) } } func removeAllRoutes() { routes.removeAll() } func routeUrl(_ url: URL) -> Bool { #if DEBUG print("trying to route \(url.absoluteString), scheme = \(scheme)") #endif var didRoute = false for route in routes { let matched = route.isMatchUrl(url) if matched.isMatched { didRoute = route.handler(matched.params) } if didRoute { break } } #if DEBUG if didRoute { print("matched, scheme = \(scheme), \(url.absoluteString)") } else { print("not matched, scheme = \(scheme), \(url.absoluteString)") } #endif return didRoute } }
mit
02eba1cb9dbf8f4083ccf755b60a0e8f
27.918129
184
0.603033
4.73659
false
false
false
false
haskellswift/swift-package-manager
Sources/Get/Fetcher.swift
2
3743
/* This source file is part of the Swift.org open source project Copyright 2015 - 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Utility /** Testable protocol to recursively fetch versioned resources. Our usage fetches remote packages by having Sandbox conform. */ protocol Fetcher { associatedtype T: Fetchable func find(url: String) throws -> Fetchable? func fetch(url: String) throws -> Fetchable func finalize(_ fetchable: Fetchable) throws -> T func recursivelyFetch(_ urls: [(String, Range<Version>)]) throws -> [T] } extension Fetcher { /** Recursively fetch remote, versioned resources. This is our standard implementation that we override when testing. */ func recursivelyFetch(_ urls: [(String, Range<Version>)]) throws -> [T] { var graph = [String: (Fetchable, Range<Version>)]() func recurse(_ urls: [(String, Range<Version>)]) throws -> [String] { return try urls.flatMap { url, specifiedVersionRange -> [String] in func adjust(_ pkg: Fetchable, _ versionRange: Range<Version>) throws { guard let v = pkg.constrain(to: versionRange) else { throw Error.invalidDependencyGraphMissingTag(package: url, requestedTag: "\(versionRange)", existingTags: "\(pkg.availableVersions)") } try pkg.setCurrentVersion(v) } if let (pkg, cumulativeVersionRange) = graph[url] { // this package has already been checked out this instantiation // verify that it satisfies the requested version range guard let updatedRange = cumulativeVersionRange.constrain(to: specifiedVersionRange) else { throw Error.invalidDependencyGraph(url) } if updatedRange ~= pkg.currentVersion { // the current checked-out version is within the requested range graph[url] = (pkg, updatedRange) return [] } else { // we cloned this package this instantiation, let’s attempt to // modify its checkout try adjust(pkg, updatedRange) graph[url] = (pkg, updatedRange) //FIXME we need to rewind and re-read this manifest and start again from there return [] } } else if let pkg = try self.find(url: url) { // this package was already installed from a previous instantiation // of the package manager. Verify it is within the required version // range. guard specifiedVersionRange ~= pkg.currentVersion else { throw Error.updateRequired(url) } graph[url] = (pkg, specifiedVersionRange) return try recurse(pkg.children) + [url] } else { // clone the package let clone = try self.fetch(url: url) try adjust(clone, specifiedVersionRange) graph[url] = (clone, specifiedVersionRange) return try recurse(clone.children) + [url] } } } return try recurse(urls).map{ graph[$0]!.0 }.map{ try self.finalize($0) } } }
apache-2.0
0df83f5d08dd9c6cd4cc8ab394eae1bb
35.676471
157
0.560011
5.375
false
false
false
false
chenzilu1990/Who
who/who/Classes/M/SBPlayer.swift
1
1201
// // SBPalyer.swift // who // // Created by chenzilu on 16/7/16. // Copyright © 2016年 chenzilu. All rights reserved. // import UIKit class SBPlayer: NSObject { var name : String? var word : String? var isWD : Bool? var isRead : Bool? init(name : String?, word : String?) { self.name = name self.word = word super.init() } // func encode(with aCoder: NSCoder) { // // aCoder.encode(name, forKey: "name") // aCoder.encode(word, forKey: "word") // if let iswd = isWD { // aCoder.encode(iswd, forKey: "isWD") // } // // if let isread = isRead { // aCoder.encode(isread, forKey: "isRead") // } //// aCoder.encodeBool(isWD!, forKey: "isWD") //// aCoder.encodeBool(isRead!, forKey: "isRead") // } // required init?(coder aDecoder: NSCoder) { // name = aDecoder.decodeObject(forKey: "name") as? String // word = aDecoder.decodeObject(forKey: "word") as? String // isWD = aDecoder.decodeBool(forKey: "isWD") // isRead = aDecoder.decodeBool(forKey: "isRead") // super.init() // // } }
mit
418b5695ab284bf9389bc898f6ff07ed
23.958333
65
0.534224
3.374648
false
false
false
false
instacrate/Subber-api
Sources/App/Controllers/OrderController.swift
2
6482
// // OrderController.swift // subber-api // // Created by Hakon Hanesand on 11/15/16. // // import Foundation import HTTP import Vapor import Fluent // TODO : Change to how stripe does it by just having one parameter that specifies to and from enum OrderTimeRange: String, TypesafeOptionsParameter, QueryModifiable { case day case week case month static var key = "period" static var values = [OrderTimeRange.day.rawValue, OrderTimeRange.week.rawValue, OrderTimeRange.month.rawValue] static var defaultValue: OrderTimeRange? = .day func apply<T : Entity>(_ query: Query<T>) throws -> Query<T> { switch self { case .month: let date = Date() let calendar = Calendar.current guard let startOfMonth = calendar.date(byAdding: .month, value: -1, to: date) else { throw Abort.serverError } try query.filter("date", .greaterThanOrEquals, startOfMonth) try query.filter("date", .lessThanOrEquals, date) return query case .week: let date = Date() let calendar = Calendar.current guard let startOfWeek = calendar.date(byAdding: .weekOfMonth, value: -1, to: date) else { throw Abort.serverError } try query.filter("date", .greaterThanOrEquals, startOfWeek) try query.filter("date", .lessThanOrEquals, date) return query case .day: let date = Date() let calendar = Calendar.current guard let startDay = calendar.date(byAdding: .day, value: -1, to: date) else { throw Abort.serverError } try query.filter("date", .greaterThanOrEquals, startDay) try query.filter("date", .lessThanOrEquals, date) return query } } } extension Model { static func find(id _id: NodeRepresentable?) throws -> Self? { guard let id = _id else { return nil } return try find(id as NodeRepresentable) } } extension Order { enum Format: String, TypesafeOptionsParameter { case long case short static let key = "format" static let values = ["long", "short"] static let defaultValue: Format? = .short func apply(on order: Order) throws -> Node { switch self { case .long: return try createLongView(for: order) case .short: return try createTerseView(for: order) } } func apply(on orders: [Order]) throws -> Node { return try .array(orders.map { return try self.apply(on: $0) }) } } } fileprivate func createTerseView(for order: Order) throws -> Node { let customer = try order.customer().first() let box = try order.box().first() return try Node(node: [ "id" : "\(order.throwableId())", "date" : "\(order.date.timeIntervalSince1970)" ]).add(objects: [ "customerName" : customer?.name, "boxName" : box?.name, "price" : box?.price ]) } fileprivate func createLongView(for order: Order) throws -> Node { let customer = try order.customer().first() let box = try order.box().first() let shipping = try order.shippingAddress().first() var billing: Node? if let stripe_id = customer?.stripe_id, let payment = try order.subscription().first()?.payment { let cards = try Stripe.shared.paymentInformation(for: stripe_id) billing = try cards.filter { $0.id == payment }.first?.makeNode() } return try Node(node: [ "id" : "\(order.throwableId())", "date" : String(Int(order.date.timeIntervalSince1970)) ]).add(objects: [ "customerName" : customer?.name, "boxName" : box?.name, "price" : box?.price, "customerEmail" : customer?.email, "shipping" : shipping, "billing" : billing ]) } extension Order { // TODO : make sure this works static func orders(for request: Request) throws -> Query<Order> { let type = try request.extract() as SessionType switch type { case .vendor: let vendor = try request.vendor() return try Order.query().filter("vendor_id", vendor.throwableId()) case .none: fallthrough case .customer: let customer = try request.customer() return try Order.query().filter("customer_id", customer.throwableId()) } } static func orders(for request: Request, with range: OrderTimeRange? = nil, fulfilled: Bool? = nil, for box: Box? = nil) throws -> Query<Order> { var query = try Order.orders(for: request) if let box = box { query = try query.filter("box_id", box.throwableId()) } if let fulfilled = fulfilled { query = try query.filter("fulfilled", fulfilled) } return try query.apply(range) } } final class OrderController: ResourceRepresentable { func index(_ request: Request) throws -> ResponseRepresentable { let period = try? request.extract() as OrderTimeRange let fulfilled = request.query?["fulfilled"]?.bool let format = try request.extract() as Order.Format let orders = try Order.orders(for: request, with: period, fulfilled: fulfilled).all() return try format.apply(on: orders).makeJSON() } func create(_ request: Request) throws -> ResponseRepresentable { var order: Order = try request.extractModel(injecting: request.customerInjectable()) try order.save() return order } func delete(_ request: Request, order: Order) throws -> ResponseRepresentable { try order.delete() return Response(status: .noContent) } func modify(_ request: Request, order: Order) throws -> ResponseRepresentable { var order: Order = try request.patchModel(order) try order.save() return try Response(status: .ok, json: order.makeJSON()) } func makeResource() -> Resource<Order> { return Resource( index: index, store: create, modify: modify, destroy: delete ) } }
mit
e48b35ac983404775f05058de27a3bbc
28.330317
149
0.579142
4.467264
false
false
false
false
fingerco/neural-net-swift-snake-2
NeuralNetwork/NeuralNet.swift
1
2930
// // NeuralNet.swift // NeuralNetwork // // Created by Cory Finger on 9/21/15. // Copyright © 2015 Cory Finger. All rights reserved. // import Foundation class NeuralNet { var inputLayer : NeuralNetLayer var hiddenLayer : NeuralNetLayer var outputLayer : NeuralNetLayer init(nNodesInput : Int, nNodesHidden : Int, nNodesOutput : Int) { hiddenLayer = NeuralNetLayer(numNodes: nNodesHidden, parent: nil, child: nil) inputLayer = NeuralNetLayer(numNodes: nNodesInput, parent: nil, child: hiddenLayer) outputLayer = NeuralNetLayer(numNodes: nNodesOutput, parent: hiddenLayer, child: nil) hiddenLayer.setParent(inputLayer) hiddenLayer.setChild(outputLayer) inputLayer.randomizeWeights() hiddenLayer.randomizeWeights() } func setLearningRate(rate : Double) { inputLayer.learningRate = rate hiddenLayer.learningRate = rate outputLayer.learningRate = rate } func setLinearOutput(linearOutput : Bool) { inputLayer.linearOutput = linearOutput hiddenLayer.linearOutput = linearOutput outputLayer.linearOutput = linearOutput } func setMomentum(useMomentum : Bool, factor : Double) { inputLayer.useMomentum = useMomentum hiddenLayer.useMomentum = useMomentum outputLayer.useMomentum = useMomentum inputLayer.momentumFactor = factor hiddenLayer.momentumFactor = factor outputLayer.momentumFactor = factor } func setInput(inputNum : Int, value : Double) { inputLayer.neuronValues[inputNum] = value } func getOutput(outputNum : Int) -> Double { return outputLayer.neuronValues[outputNum] } func getMaxOutputID() -> Int { var maxVal : Double? var maxID = 0 for (index, neuronValue) in outputLayer.neuronValues.enumerate() { if(maxVal == nil || neuronValue > maxVal!) { maxVal = neuronValue maxID = index } } return maxID } func setDesiredOutput(outputNum : Int, value : Double) { outputLayer.desiredValues[outputNum] = value } func feedForward() { inputLayer.calculateNeuronValues() hiddenLayer.calculateNeuronValues() outputLayer.calculateNeuronValues() } func backPropagate() { outputLayer.calculateErrors() hiddenLayer.calculateErrors() hiddenLayer.adjustWeights() inputLayer.adjustWeights() } func calculateError() -> Double { var error = 0.0 for (index, neuronValue) in outputLayer.neuronValues.enumerate() { error += pow(neuronValue - outputLayer.desiredValues[index], 2) } error = error / Double(outputLayer.numNodes) return error } }
apache-2.0
b78e3bea65231a618a48409859e8a09a
28.59596
93
0.627518
4.464939
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/AssetsSearchResultsPresenter.swift
2
2671
// // AssetsSearchResultsPresenter.swift // Neocom // // Created by Artem Shimanski on 11/8/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import Futures import CloudData import TreeController class AssetsSearchResultsPresenter: TreePresenter { typealias View = AssetsSearchResultsViewController typealias Interactor = AssetsSearchResultsInteractor typealias Presentation = [Tree.Item.Section<EVELocation, Tree.Item.AssetRow>] weak var view: View? lazy var interactor: Interactor! = Interactor(presenter: self) var content: Interactor.Content? var presentation: Presentation? var loading: Future<Presentation>? required init(view: View) { self.view = view } func configure() { view?.tableView.register([Prototype.TreeSectionCell.default, Prototype.TreeDefaultCell.default]) interactor.configure() applicationWillEnterForegroundObserver = NotificationCenter.default.addNotificationObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (note) in self?.applicationWillEnterForeground() } } private var applicationWillEnterForegroundObserver: NotificationObserver? func presentation(for content: Interactor.Content) -> Future<Presentation> { guard let string = searchManager.pop()?.lowercased(), !string.isEmpty else {return .init([])} let treeController = view?.treeController return DispatchQueue.global(qos: .utility).async { content.index.compactMap { i -> Tree.Item.Section<EVELocation, Tree.Item.AssetRow>? in let rows: Set<Tree.Item.AssetRow> if i.0.displayName.string.lowercased().contains(string) { rows = Set(i.1.values.joined()) } else { rows = Set(i.1.filter {$0.key.contains(string)}.values.joined()) } guard !rows.isEmpty else { return nil } let isExpanded = rows.count < 100 return Tree.Item.Section(i.0, isExpanded: isExpanded, diffIdentifier: i.0, treeController: treeController, children: rows.sorted {$0.typeName < $1.typeName}) } } } lazy var searchManager = SearchManager(presenter: self) func updateSearchResults(with string: String?) { searchManager.updateSearchResults(with: string ?? "") if let content = content, let prefix = string?.lowercased(), !prefix.isEmpty { let suggestions = content.suggestions.filter({$0.0.hasPrefix(prefix)}).prefix(3).map{$0.1} if !suggestions.isEmpty { view?.suggestions = suggestions } else { view?.suggestions = content.suggestions.filter({$0.0.contains(prefix)}).prefix(3).map{$0.1} } } else { view?.suggestions = nil } } }
lgpl-2.1
d05e6d3f0acb46981a7dee79185c0f2a
30.785714
200
0.720225
3.979136
false
false
false
false
kusl/swift
validation-test/compiler_crashers_fixed/1141-swift-parser-parseexprcallsuffix.swift
12
863
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func j<f: l: e -> e = { { l) { m } } protocol k { } class e: k{ class func j protocol d : b { func b func d(e: = { (g: h, f: h -> h) -> h in } enum S<T> : P { func f<T>() -> T -> T { } } protocol P { } } struct c<d : SequenceType> { var b: [c<d>] { } protocol a { } class b: a { } func f<T : BooleanType>(b: T) { } func e() { } } protocol c : b { func b otocol A { } struct } } func c<i>() -> (i, i -> i) -> i { k b k.i = { } { i) { k } } protoch) -> b { f) -> j) -> > j { } } protocol h : e { func e func r(d: t, k: t) -> (((t, t) -> t) -i g { } struct e<j> : g { func e( h s: n -> n = { } l o: n = { (d: n, o: n -> n) -> n q return o(d) }
apache-2.0
1160260c11cae01397e77f74773f9788
12.698413
87
0.507532
2.229974
false
false
false
false
BrobotDubstep/BurningNut
BurningNut/BurningNut/Scenes/GameSceneLocal.swift
1
15721
// // GameScene.swift // BurningNut // // Created by Tim Olbrich on 21.09.17. // Copyright © 2017 Tim Olbrich. All rights reserved. // import SpriteKit import GameplayKit class GameSceneLocal: SKScene, SKPhysicsContactDelegate { var bombCounter = 0 var rightPointLbl = SKLabelNode() var leftPointLbl = SKLabelNode() let leftSquirrel = SKSpriteNode(imageNamed: "minisquirrelRight") let rightSquirrel = SKSpriteNode(imageNamed: "minisquirrel") let middleTree = SKSpriteNode(imageNamed: "tree-2") let leftTree = SKSpriteNode(imageNamed: "tree-1") let rightTree = SKSpriteNode(imageNamed: "tree-1") let explosionSound = SKAction.playSoundFileNamed("explosion.mp3", waitForCompletion: true) var playerTurn = 1 var playerTurnLbl = SKLabelNode() var flugbahnCalc = CalcFlugbahn() var direction = SKShapeNode() override func didMove(to view: SKView) { self.setupMatchfield() playerTurnLbl.text = "Spieler 1 ist dran" leftPointLbl.text = String(GameState.shared.leftScore) rightPointLbl.text = String(GameState.shared.rightScore) self.physicsWorld.gravity = CGVector.init(dx: 0.0, dy: -6) self.physicsWorld.contactDelegate = self self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame) self.physicsBody?.categoryBitMask = PhysicsCategory.Frame self.physicsBody?.contactTestBitMask = PhysicsCategory.LeftSquirrel | PhysicsCategory.RightSquirrel } @objc func bombAttack(notification: NSNotification) { guard let text = notification.userInfo?["position"] as? String else { return } var squirrel = SKSpriteNode() if(playerTurn == 1) { squirrel = leftSquirrel } else { squirrel = rightSquirrel } addBomb(player: squirrel, position: CGPointFromString(text)) } func didBegin(_ contact: SKPhysicsContact) { if contact.bodyA.categoryBitMask == PhysicsCategory.Frame || contact.bodyB.categoryBitMask == PhysicsCategory.Frame { if(contact.bodyA.node == leftSquirrel || contact.bodyB.node == leftSquirrel) { bombCounter = 1 GameState.shared.rightScore += 1 rightPointLbl.text = String(GameState.shared.rightScore) DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { self.resetGameScene() }) } else if(contact.bodyA.node == rightSquirrel || contact.bodyB.node == rightSquirrel) { bombCounter = 1 GameState.shared.leftScore += 1 leftPointLbl.text = String(GameState.shared.leftScore) DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { self.resetGameScene() }) } if( GameState.shared.leftScore == 3 || GameState.shared.rightScore == 3) { gameOver() } } else if let bodyOne = contact.bodyA.node as? SKSpriteNode, let bodyTwo = contact.bodyB.node as? SKSpriteNode { bombExplode(bodyOne: bodyOne, bodyTwo: bodyTwo) if contact.bodyA.node == leftSquirrel || contact.bodyB.node == leftSquirrel || contact.bodyA.node == rightSquirrel || contact.bodyB.node == rightSquirrel { if(contact.bodyA.node == leftSquirrel || contact.bodyB.node == leftSquirrel) { bombCounter = 1 GameState.shared.rightScore += 1 rightPointLbl.text = String(GameState.shared.rightScore) DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { self.resetGameScene() }) } else if(contact.bodyA.node == rightSquirrel || contact.bodyB.node == rightSquirrel) { bombCounter = 1 GameState.shared.leftScore += 1 leftPointLbl.text = String(GameState.shared.leftScore) DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: { self.resetGameScene() }) } if( GameState.shared.leftScore == 3 || GameState.shared.rightScore == 3) { gameOver() } } } } func gameOver(){ let loseAction = SKAction.run() { var playerBool: Bool let reveal = SKTransition.flipHorizontal(withDuration: 0.5) if(self.playerTurn == 1) { playerBool = true } else { playerBool = false } let gameOverScene = LocalGameOver(size: self.size, won: playerBool) self.view?.presentScene(gameOverScene, transition: reveal) } run(loseAction) } func bombExplode(bodyOne: SKSpriteNode, bodyTwo: SKSpriteNode) { let explosion = SKSpriteNode(imageNamed: "explosion") explosion.position = bodyOne.position explosion.size = CGSize(width: 60, height: 60) explosion.zPosition = 1 addChild(explosion) run(explosionSound) explosion.run( SKAction.sequence([ SKAction.wait(forDuration: 1.0), SKAction.removeFromParent() ]) ) bodyOne.removeFromParent() bodyTwo.removeFromParent() bombCounter = 0 if(self.playerTurn == 1) { self.playerTurn = 2 self.playerTurnLbl.text = "Spieler 2 ist dran!" } else { self.playerTurn = 1 self.playerTurnLbl.text = "Spieler 1 ist dran!" } } func bombDidNotHit(leBomb: SKSpriteNode) -> SKAction { return SKAction.run { let explosion = SKSpriteNode(imageNamed: "explosion") explosion.position = leBomb.position explosion.size = CGSize(width: 60, height: 60) explosion.zPosition = 1 self.addChild(explosion) self.run(self.explosionSound) explosion.run( SKAction.sequence([ SKAction.wait(forDuration: 1.0), SKAction.removeFromParent() ]) ) leBomb.removeFromParent() self.bombCounter = 0 if(self.playerTurn == 1) { self.playerTurn = 2 self.playerTurnLbl.text = "Spieler 2 ist dran!" } else { self.playerTurn = 1 self.playerTurnLbl.text = "Spieler 1 ist dran!" } } } func addBomb(player: SKSpriteNode, position: CGPoint) { var physicsCategory: UInt32 var bombCategory: UInt32 var loopFrom, loopTo: CGFloat var loopStep: CGFloat if(player == leftSquirrel) { physicsCategory = PhysicsCategory.RightSquirrel bombCategory = PhysicsCategory.LeftBomb loopFrom = leftSquirrel.position.x loopTo = rightSquirrel.position.x loopStep = 1 } else { physicsCategory = PhysicsCategory.LeftSquirrel bombCategory = PhysicsCategory.RightBomb loopFrom = rightSquirrel.position.x loopTo = leftSquirrel.position.x loopStep = -1 } if(bombCounter == 0) { let bomb = SKSpriteNode(imageNamed: "bomb") bomb.position = CGPoint(x: player.position.x, y: player.position.y) bomb.size = CGSize(width: 15, height: 30) bomb.zPosition = 1 bomb.physicsBody = SKPhysicsBody(rectangleOf: bomb.size) bomb.physicsBody?.categoryBitMask = bombCategory bomb.physicsBody?.contactTestBitMask = physicsCategory | PhysicsCategory.Environment //bomb.physicsBody?.collisionBitMask = physicsCategory bomb.physicsBody?.affectedByGravity = false addChild(bomb) bombCounter += 1 //let moveBomb = SKAction.move(to: CGPoint(x: position.x, y: position.y), duration: 4) let bezierPath = UIBezierPath() bezierPath.move(to: player.position) for i in stride(from: loopFrom, to: loopTo, by: loopStep) { let nextPoint = flugbahnCalc.flugkurve(t: CGFloat(i), x: player.position.x, y: player.position.y, x_in: position.x, y_in: position.y, player: loopStep) bezierPath.addLine(to: CGPoint(x: CGFloat(i), y: nextPoint)) } //bezierPath.close() let moveBomb = SKAction.follow(bezierPath.cgPath, asOffset: false, orientToPath: false, duration: 3) let rotateBomb = SKAction.rotate(byAngle: -20, duration: 3) let removeBomb = bombDidNotHit(leBomb: bomb) let groupBomb = SKAction.group([moveBomb, rotateBomb]) bomb.run(SKAction.sequence([groupBomb, removeBomb])) } } func resetGameScene() { if let view = self.view as SKView? { if let scene = SKScene(fileNamed: "GameSceneLocal") { scene.scaleMode = .aspectFill view.presentScene(scene) } view.ignoresSiblingOrder = true } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { direction.removeFromParent() var currentPlayer: SKSpriteNode guard let touch = touches.first else { return } let touchLocation = touch.location(in: self) if(playerTurn == 1) { currentPlayer = leftSquirrel } else { currentPlayer = rightSquirrel } addBomb(player: currentPlayer, position: touchLocation) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { direction.removeFromParent() var currentPlayer: SKSpriteNode guard let touch = touches.first else { return } let touchLocation = touch.location(in: self) let bezierPath = UIBezierPath() if(playerTurn == 1) { currentPlayer = leftSquirrel let a = atan((touchLocation.y - currentPlayer.position.y) / (touchLocation.x - currentPlayer.position.x)) let x = currentPlayer.position.x + 160 * cos(a) let y = currentPlayer.position.y + 160 * sin(a) bezierPath.move(to: currentPlayer.position) bezierPath.addLine(to: CGPoint(x: x, y: y)) } else { currentPlayer = rightSquirrel let a = atan((touchLocation.y - currentPlayer.position.y) / (touchLocation.x - currentPlayer.position.x)) let x = currentPlayer.position.x - 160 * cos(a) let y = currentPlayer.position.y - 160 * sin(a) bezierPath.move(to: currentPlayer.position) bezierPath.addLine(to: CGPoint(x: x, y: y)) } direction.path = bezierPath.cgPath direction.fillColor = .white direction.lineWidth = 2 direction.zPosition = 0 addChild(direction) } func setupMatchfield() { playerTurnLbl.position = CGPoint(x: 0, y: 135) playerTurnLbl.zPosition = 7 playerTurnLbl.fontColor = UIColor.black addChild(playerTurnLbl) leftPointLbl.position = CGPoint(x: -310, y: 135) leftPointLbl.zPosition = 7 leftPointLbl.fontColor = UIColor.black addChild(leftPointLbl) rightPointLbl.position = CGPoint(x: 310, y: 135) rightPointLbl.zPosition = 7 rightPointLbl.fontColor = UIColor.black addChild(rightPointLbl) leftSquirrel.position = CGPoint(x: -300.839, y: -89.305) leftSquirrel.size = CGSize(width: 51.321, height: 59.464) leftSquirrel.anchorPoint.x = 0.5 leftSquirrel.anchorPoint.y = 0.5 leftSquirrel.zPosition = 1 leftSquirrel.physicsBody = SKPhysicsBody(rectangleOf: leftSquirrel.size) leftSquirrel.physicsBody?.categoryBitMask = PhysicsCategory.LeftSquirrel leftSquirrel.physicsBody?.contactTestBitMask = PhysicsCategory.RightBomb | PhysicsCategory.Frame leftSquirrel.physicsBody?.collisionBitMask = PhysicsCategory.Environment addChild(leftSquirrel) rightSquirrel.position = CGPoint(x: 300.839, y: -89.305) rightSquirrel.size = CGSize(width: 51.321, height: 59.464) rightSquirrel.anchorPoint.x = 0.5 rightSquirrel.anchorPoint.y = 0.5 rightSquirrel.zPosition = 1 rightSquirrel.physicsBody = SKPhysicsBody(rectangleOf: rightSquirrel.size) rightSquirrel.physicsBody?.categoryBitMask = PhysicsCategory.RightSquirrel rightSquirrel.physicsBody?.contactTestBitMask = PhysicsCategory.LeftBomb | PhysicsCategory.Frame rightSquirrel.physicsBody?.collisionBitMask = PhysicsCategory.Environment addChild(rightSquirrel) middleTree.position = CGPoint(x: 0, y: -4.238) middleTree.size = CGSize(width: 124.354, height: 221.849) middleTree.anchorPoint.x = 0.5 middleTree.anchorPoint.y = 0.5 middleTree.zPosition = 1 middleTree.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 10, height: middleTree.size.height)) middleTree.physicsBody?.categoryBitMask = PhysicsCategory.Environment middleTree.physicsBody?.contactTestBitMask = PhysicsCategory.LeftBomb | PhysicsCategory.RightBomb middleTree.physicsBody?.collisionBitMask = PhysicsCategory.Environment addChild(middleTree) leftTree.position = CGPoint(x: -147.94, y: -62.205) leftTree.size = CGSize(width: 119.261, height: 173.357) leftTree.anchorPoint.x = 0.5 leftTree.anchorPoint.y = 0.5 leftTree.zPosition = 1 leftTree.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 10, height: leftTree.size.height)) leftTree.physicsBody?.categoryBitMask = PhysicsCategory.Environment leftTree.physicsBody?.contactTestBitMask = PhysicsCategory.LeftBomb | PhysicsCategory.RightBomb leftTree.physicsBody?.collisionBitMask = PhysicsCategory.None leftTree.physicsBody?.affectedByGravity = false addChild(leftTree) rightTree.position = CGPoint(x: 147.94, y: -62.205) rightTree.size = CGSize(width: 119.261, height: 173.357) rightTree.anchorPoint.x = 0.5 rightTree.anchorPoint.y = 0.5 rightTree.zPosition = 1 rightTree.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 10, height: rightTree.size.height)) rightTree.physicsBody?.categoryBitMask = PhysicsCategory.Environment rightTree.physicsBody?.contactTestBitMask = PhysicsCategory.LeftBomb | PhysicsCategory.RightBomb rightTree.physicsBody?.collisionBitMask = PhysicsCategory.None rightTree.physicsBody?.affectedByGravity = false addChild(rightTree) } }
mit
6d3a381bba5aeff230b9f0f29d1e0a2b
38.898477
168
0.588422
4.914036
false
false
false
false
joerocca/GitHawk
Classes/Models/Authorization.swift
1
4872
import Foundation final class Authorization: NSObject, NSCoding { enum Keys { static let note = "note" static let updated_at = "updated_at" static let id = "id" static let app = "app" static let token = "token" static let scopes = "scopes" static let created_at = "created_at" static let fingerprint = "fingerprint" static let hashed_token = "hashed_token" static let token_last_eight = "token_last_eight" static let note_url = "note_url" static let url = "url" } let note: String let updated_at: String let id: NSNumber let app: App let token: String let scopes: [String] let created_at: String let fingerprint: String? let hashed_token: String let token_last_eight: String let note_url: String? let url: String convenience init?(json: [String: Any]?) { guard let note = json?[Keys.note] as? String else { return nil } guard let updated_at = json?[Keys.updated_at] as? String else { return nil } guard let id = json?[Keys.id] as? NSNumber else { return nil } guard let appJSON = json?[Keys.app] as? [String: Any] else { return nil } guard let app = App(json: appJSON) else { return nil } guard let token = json?[Keys.token] as? String else { return nil } guard let scopes = json?[Keys.scopes] as? [String] else { return nil } guard let created_at = json?[Keys.created_at] as? String else { return nil } let fingerprint = json?[Keys.fingerprint] as? String guard let hashed_token = json?[Keys.hashed_token] as? String else { return nil } guard let token_last_eight = json?[Keys.token_last_eight] as? String else { return nil } let note_url = json?[Keys.note_url] as? String guard let url = json?[Keys.url] as? String else { return nil } self.init( note: note, updated_at: updated_at, id: id, app: app, token: token, scopes: scopes, created_at: created_at, fingerprint: fingerprint, hashed_token: hashed_token, token_last_eight: token_last_eight, note_url: note_url, url: url ) } init( note: String, updated_at: String, id: NSNumber, app: App, token: String, scopes: [String], created_at: String, fingerprint: String?, hashed_token: String, token_last_eight: String, note_url: String?, url: String ) { self.note = note self.updated_at = updated_at self.id = id self.app = app self.token = token self.scopes = scopes self.created_at = created_at self.fingerprint = fingerprint self.hashed_token = hashed_token self.token_last_eight = token_last_eight self.note_url = note_url self.url = url } convenience init?(coder aDecoder: NSCoder) { guard let note = aDecoder.decodeObject(forKey: Keys.note) as? String else { return nil } guard let updated_at = aDecoder.decodeObject(forKey: Keys.updated_at) as? String else { return nil } guard let id = aDecoder.decodeObject(forKey: Keys.id) as? NSNumber else { return nil } guard let app = aDecoder.decodeObject(forKey: Keys.app) as? App else { return nil } guard let token = aDecoder.decodeObject(forKey: Keys.token) as? String else { return nil } guard let scopes = aDecoder.decodeObject(forKey: Keys.scopes) as? [String] else { return nil } guard let created_at = aDecoder.decodeObject(forKey: Keys.created_at) as? String else { return nil } let fingerprint = aDecoder.decodeObject(forKey: Keys.fingerprint) as? String guard let hashed_token = aDecoder.decodeObject(forKey: Keys.hashed_token) as? String else { return nil } guard let token_last_eight = aDecoder.decodeObject(forKey: Keys.token_last_eight) as? String else { return nil } let note_url = aDecoder.decodeObject(forKey: Keys.note_url) as? String guard let url = aDecoder.decodeObject(forKey: Keys.url) as? String else { return nil } self.init( note: note, updated_at: updated_at, id: id, app: app, token: token, scopes: scopes, created_at: created_at, fingerprint: fingerprint, hashed_token: hashed_token, token_last_eight: token_last_eight, note_url: note_url, url: url ) } func encode(with aCoder: NSCoder) { aCoder.encode(note, forKey: Keys.note) aCoder.encode(updated_at, forKey: Keys.updated_at) aCoder.encode(id, forKey: Keys.id) aCoder.encode(app, forKey: Keys.app) aCoder.encode(token, forKey: Keys.token) aCoder.encode(scopes, forKey: Keys.scopes) aCoder.encode(created_at, forKey: Keys.created_at) aCoder.encode(fingerprint, forKey: Keys.fingerprint) aCoder.encode(hashed_token, forKey: Keys.hashed_token) aCoder.encode(token_last_eight, forKey: Keys.token_last_eight) aCoder.encode(note_url, forKey: Keys.note_url) aCoder.encode(url, forKey: Keys.url) } }
mit
0f95fd9b2e6127aedb797303c2ef110c
37.0625
116
0.66523
3.622305
false
false
false
false
Aquaware/LaSwift
iOS/LaSwift/RMatrix.swift
1
13074
// // RMatrix.swift // LaSwift // // Created by Ikuo Kudo on March,16,2016 // Copyright © 2016 Aquaware. All rights reserved. // import Accelerate public let EPS: Double = 1e-50 public class RMatrix { public var la: la_object_t! = nil private var rows_: Int = 0 private var cols_: Int = 0 init() { } init(array: [[Double]]) { self.rows_ = array.count self.cols_ = array.first!.count assert(self.rows > 0 && self.cols > 0) var buffer = [Double](count: self.rows * self.cols, repeatedValue: 0.0) for i in 0 ..< self.rows { let begin = i * self.cols let end = begin + self.cols let item = array[i] buffer[begin..<end] = item[0..<self.cols] } self.la = toLaObject(buffer, rows: self.rows, cols: self.cols) } init(array: [Double], rows: Int, cols: Int) { self.rows_ = rows self.cols_ = cols self.la = toLaObject(array, rows: self.rows, cols: self.cols) } init(value: Double, rows: Int, cols: Int) { self.rows_ = rows self.cols_ = cols let array = [Double](count: rows * cols, repeatedValue: value) self.la = toLaObject(array, rows: self.rows, cols: self.cols) } init(la: la_object_t) { self.rows_ = Int(la_matrix_rows(la)) self.cols_ = Int(la_matrix_cols(la)) self.la = la } public var shape: (Int, Int) { return (self.rows, self.cols) } public var rows: Int { return self.rows_ } public var cols: Int { return self.cols_ } public var flat: [Double] { var array = [Double](count: self.rows * self.cols, repeatedValue: 0.0) la_matrix_to_double_buffer(&array, la_count_t(self.cols), self.la) return array } public var array: [[Double]] { let flat = self.flat var array = [[Double]]() for i in 0 ..< self.rows { let begin = i * self.cols let end = begin + self.cols - 1 let item = Array(flat[begin...end]) array.append(item) } return array } public var isOneElement: Bool { return (self.rows == 1 && self.cols == 1) } public var isNone: Bool { return (self.rows == 0 || self.cols == 0 || self.la == nil) } public var isRowVector: Bool { return (self.rows == 1 && self.cols > 1) } public var isColVector: Bool { return (self.cols == 1 && self.rows > 1) } public final var T: RMatrix { return RMatrix(la: la_transpose(self.la)) } public final var first: Double { return self[0, 0] } public final func reshape(rows: Int, cols: Int) -> RMatrix { assert(rows * cols == self.rows * self.cols) let flat = self.flat self.rows_ = rows self.cols_ = cols self.la = toLaObject( flat, rows: self.rows, cols: self.cols) return RMatrix(la: la) } public func len() -> Int { if isNone { return 0 } else if isOneElement { return 1 } else if isRowVector { return self.cols } else if isColVector { return self.rows } else { return self.rows } } public func slice(rowRange: Range<Int>, colRange: Range<Int>) -> RMatrix { assert(rowRange.startIndex >= 0 && rowRange.endIndex <= self.rows && rowRange.endIndex >= rowRange.startIndex) assert(colRange.startIndex >= 0 && colRange.endIndex <= self.cols && colRange.endIndex >= colRange.startIndex) let la = la_matrix_slice( self.la, la_index_t(rowRange.startIndex), la_index_t(colRange.startIndex), 1, 1, la_count_t(rowRange.endIndex - rowRange.startIndex), la_count_t(colRange.endIndex - colRange.startIndex) ) return RMatrix(la: la) } public func insert(array: [[Double]], axis: Int = 0) { let rows = array.count let cols = array.first!.count if axis == 0 { assert(self.cols == cols) self.rows_ += rows var flat = self.flat flat += array.flatten() self.la = toLaObject(flat, rows: self.rows, cols: self.cols) } else { assert(self.rows == rows) self.cols_ += cols var buffer = [Double](count: self.cols * self.rows, repeatedValue: 0.0) var index: Int = 0 for row in 0 ..< self.rows { for col in 0 ..< self.cols { buffer[index] = self[row, col] index += 1 } for col in 0 ..< cols { buffer[index] = array[row][col] index += 1 } } self.la = toLaObject(flat, rows: self.rows, cols: self.cols) } } public func invert() -> RMatrix { var flat = self.flat for i in 0 ..< self.rows * self.cols { let value:Double = flat[i] if abs(value) > EPS { flat[i] = 1.0 / value } else { flat[i] = 0.0 } } return RMatrix(array: flat, rows: self.rows, cols: self.cols) } // (axis : 0) shift > 0 : shift to down, shift < 0 : shift to up // (axis : 1) shift > 0 : shift to right, shift < 0 : shift to left public func shift(shift: Int, padding: Double = 0.0, axis: Int = 1) -> RMatrix { if axis == 0 { assert(abs(shift) < self.rows) var newArray = [[Double]](count: self.rows, repeatedValue: [Double](count: self.cols, repeatedValue: padding)) for col in 0 ..< self.cols { for row in 0 ..< self.rows { let newRow = row + shift if newRow >= 0 && newRow < self.rows { newArray[newRow][col] = self.array[row][col] } } } return RMatrix(array: newArray) } else { assert(abs(shift) < self.cols) var array = [[Double]](count: self.rows, repeatedValue: [Double](count: self.cols, repeatedValue: padding)) for row in 0 ..< self.rows { for col in 0 ..< self.cols { let newCol = col + shift if newCol >= 0 && newCol < self.cols { array[row][newCol] = self.array[row][col] } } } return RMatrix(array: array) } } public func roll (shift: Int, axis: Int = 0, padding: Double = 0) -> RMatrix { if axis == 0 { assert(abs(shift) < self.rows) var newArray = [[Double]](count: self.rows, repeatedValue: [Double](count: self.cols, repeatedValue: padding)) for col in 0 ..< self.cols { for row in 0 ..< self.rows { var newRow = row + shift if newRow >= self.rows { newRow -= self.rows } else if newRow < 0 { newRow += self.rows } newArray[newRow][col] = self.array[row][col] } } return RMatrix(array: newArray) } else { assert(abs(shift) < self.cols) var newArray = [[Double]](count: self.rows, repeatedValue: [Double](count: self.cols, repeatedValue: padding)) for row in 0 ..< self.rows { for col in 0 ..< self.cols { var newCol = col + shift if newCol >= self.cols { newCol -= self.cols } else if newCol < 0 { newCol += self.cols } if newCol >= 0 && newCol < self.cols { newArray[row][newCol] = self.array[row][col] } } } return RMatrix(array: newArray) } } public static func identity(dimension: Int = 1) -> RMatrix { let la = la_identity_matrix( la_count_t(dimension), la_scalar_type_t(LA_SCALAR_TYPE_DOUBLE), la_attribute_t(LA_DEFAULT_ATTRIBUTES)) return RMatrix(la: la) } public static func ones(rows: Int, cols: Int) -> RMatrix { return arange(rows, cols: cols, value: 1.0) } public static func zeros(rows: Int, cols: Int) -> RMatrix { return arange(rows, cols: cols, value: 0.0) } public static func arange(rows: Int = 1, cols: Int = 1, value: Double) ->RMatrix { let array = Array(count: rows * cols, repeatedValue: value) return RMatrix(array: array, rows: rows, cols: cols) } public static func linspace(start: Double, end: Double, num: Int, endpoint: Bool = true) -> RMatrix { var step = 0.0 if endpoint { assert(num > 1) step = (end - start) / Double(num - 1) } else { assert(num > 0) step = (end - start) / Double(num) } var array = [Double](count: num, repeatedValue: 0) var value = start for i in 0 ..< num { array[i] = value value += step } return RMatrix(array: array, rows: 1, cols: num) } subscript (row: Int, col: Int) -> Double { get { let theRow = checkRow(row) let theCol = checkCol(col) var array = [0.0] let slice = la_matrix_slice( self.la, la_index_t(theRow), la_index_t(theCol), 1, 1, 1, 1) la_matrix_to_double_buffer(&array, 1, slice) return array.first! } set(value) { var buffer = self.flat let index = col + row * self.cols assert(index >= 0 && index < self.cols * self.rows) buffer[index] = value self.la = toLaObject(buffer, rows: self.rows, cols: self.cols) } } subscript (rowOrColumn: Int) -> RMatrix { get { if self.isRowVector { let col = checkCol(rowOrColumn) var array: [Double] = [0.0] array[0] = self[0, col] return RMatrix(array: array, rows: 1, cols: 1) } else if self.isColVector { let row = checkRow(rowOrColumn) var array: [Double] = [0.0] array[0] = self[row, 0] return RMatrix(array: array, rows: 1, cols: 1) } else { let row = checkRow(rowOrColumn) let slice = la_matrix_slice( self.la, la_index_t(row), 0, 1, 1, 1, la_count_t(self.cols)) return RMatrix(la: slice) } } } public var description: String { let array = self.array return array.reduce("") { (acc, rowVals) in acc + rowVals.reduce("") { (ac, colVals) in ac + "\(colVals) " } + "\n" } } public func toLaObject(array: [Double], rows: Int, cols: Int) -> la_object_t { let laObject = la_matrix_from_double_buffer( array, la_count_t(rows), la_count_t(cols), la_count_t(cols), la_hint_t(LA_NO_HINT), la_attribute_t(LA_DEFAULT_ATTRIBUTES)) return laObject } private func checkRow(row: Int) -> Int { assert(row >= 0 && row < self.rows) return (row >= 0) ? row : self.rows + row } private func checkCol(col: Int) -> Int { assert(col >= 0 && col < self.cols) return (col >= 0) ? col : self.cols + col } }
apache-2.0
673d12b5ae5b68886f06e2075ced2a26
33.13577
122
0.446187
4.233484
false
false
false
false
spinach/GDImage
Source/GDImage/UIImageView+GDImage.swift
1
1197
// // UIImageView+GDImage.swift // GDImage // // Created by Guy Daher on 10/23/16. // Copyright © 2016 guydaher. All rights reserved. // import Foundation private var gdImageAssociationKey: UInt8 = 0 extension UIImageView { var gdImage: GDImage? { get { return objc_getAssociatedObject(self, &gdImageAssociationKey) as? GDImage } set(newValue) { objc_setAssociatedObject(self, &gdImageAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } public func setImage(withUrl url: URL, andCompletionHandler completionHandler: CompletionHandler? = nil) { if (gdImage == nil) { gdImage = GDImage()} gdImage?.setImage(ofImageView: self, withUrl: url, andCompletionHandler: completionHandler) } public func setImage(withLink link: String, andCompletionHandler completionHandler: CompletionHandler? = nil) { if (gdImage == nil) { gdImage = GDImage()} gdImage?.setImage(ofImageView: self, withLink: link, andCompletionHandler: completionHandler) } public func cancelImageDownload() { gdImage?.cancelDownload(ofImageView: self) } }
mit
a775175e7e9713a58f80ec521c7fd228
31.324324
124
0.67893
4.226148
false
false
false
false
vazexqi/ScrollViewExample
ScrollViewExample/ViewController.swift
1
4186
// // ViewController.swift // ScrollViewExample // // Created by Nick Chen on 9/19/15. // Copyright © 2015 Nick Chen. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var contentView: UIView! var activeTextField: UITextField? var keyboardShowing = false var keyboardHeight: CGFloat = 0.0 var animationDuration: Double = 0.5 var animationCurve: UInt = 0 override func viewWillAppear(animated: Bool) { super.viewDidLoad() registerForKeyboardNotifications() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK - Positioning override func viewDidLayoutSubviews() { // This deliberately moves the keyboard to the bottom of the screen let scrollViewBounds = scrollView.bounds let contentViewBounds = contentView.bounds var scrollViewInsets = UIEdgeInsetsZero scrollViewInsets.top = scrollViewBounds.size.height scrollViewInsets.top -= contentViewBounds.size.height // http://stackoverflow.com/questions/18837166/how-to-mimic-keyboard-animation-on-ios-7-to-add-done-button-to-numeric-keyboar/19235995#19235995 if(keyboardShowing) { scrollViewInsets.top -= keyboardHeight UIView.animateWithDuration(animationDuration, delay: animationDuration, options: UIViewAnimationOptions(rawValue: animationCurve), animations: { () -> Void in }, completion: { (completed) -> Void in }) UIView.animateWithDuration(animationDuration) { self.scrollView.contentInset = scrollViewInsets } } else { self.scrollView.contentInset = scrollViewInsets } } // MARK - UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textFieldDidBeginEditing(textField: UITextField) { activeTextField = textField } func textFieldDidEndEditing(textField: UITextField) { activeTextField = nil } // MARK - Handle keyboard // https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html#//apple_ref/doc/uid/TP40009542-CH5-SW7 // We can't use the code directly because we are messing with viewDidLayoutSubviews to position the forms at the bottom of the screen // So, unlike the link above, we do the animation in the func registerForKeyboardNotifications() { let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "keyboardWillBeShown:", name: UIKeyboardWillShowNotification, object: nil) notificationCenter.addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil) } func keyboardWillBeShown(notification: NSNotification) { if let userInfo = notification.userInfo { // Grab the keyboard height (may vary depending on which keyboard is selected) if let keyboardSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue(){ keyboardShowing = true keyboardHeight = keyboardSize.height } // Grab the animation style to match the duration and rate if let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double { animationDuration = duration } if let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? UInt { animationCurve = curve } } } func keyboardWillBeHidden(notification: NSNotification) { keyboardShowing = false keyboardHeight = 0.0 } }
bsd-3-clause
9ec1385f768beaade61a8d4dff28ab84
33.875
189
0.67503
5.725034
false
false
false
false
mparrish91/gifRecipes
application/SearchController.swift
1
9923
// // SearchController.swift // reddift // // Created by sonson on 2016/03/23. // Copyright © 2016年 sonson. All rights reserved. // import reddift import UIKit let SearchControllerDidOpenSubredditName = Notification.Name(rawValue: "SearchControllerDidOpenSubredditName") let SearchControllerDidSearchSubredditName = Notification.Name(rawValue: "SearchControllerDidSearchSubredditName") enum SearchCandidateSection: Int { case name = 1 case topic = 2 case suggest = 0 } func sectionFromSection(_ section: Int) -> SearchCandidateSection? { switch section { case SearchCandidateSection.name.rawValue: return .name case SearchCandidateSection.topic.rawValue: return .topic case SearchCandidateSection.suggest.rawValue: return .suggest default: return nil } } class SearchController: UITableViewController { static let subredditKey = "subreddit" static let queryKey = "query" var subredditNames: [String] = [] var subredditSearch: [String] = [] var suggests: [String] = [] var loadingSubredditNames = false var loadingSubredditSearch = false var loadingSuggests = false var subreddit: Subreddit? var timer: Timer? /// Shared session configuration var sessionConfiguration: URLSessionConfiguration { get { let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = 30 configuration.timeoutIntervalForResource = 30 return configuration } } func searchSubredditNames(text: String) { do { loadingSubredditNames = true try UIApplication.appDelegate()?.session?.searchRedditNames(text, exact: false, includeOver18: false, completion: { (result) in switch result { case .failure(let error): /// Callback print(error) case .success(let array): DispatchQueue.main.async(execute: { self.subredditNames.removeAll() self.subredditNames.append(contentsOf: array) self.tableView.reloadData() }) } self.loadingSubredditNames = false }) } catch { self.loadingSubredditNames = false } } func searchSubredditSearch(text: String) { do { loadingSubredditSearch = true try UIApplication.appDelegate()?.session?.searchSubredditsByTopic(text, completion: { (result) -> Void in switch result { case .failure(let error): print(error) case .success(let names): DispatchQueue.main.async(execute: { self.subredditSearch.removeAll() self.subredditSearch.append(contentsOf: names) self.tableView.reloadData() }) } self.loadingSubredditSearch = false }) } catch { self.loadingSubredditSearch = false } } func loadGoogleSuggest(text: String) { let queryEscaped = text.addPercentEncoding if let url = URL(string: "https://www.google.com/complete/search?hl=en&output=toolbar&q=" + queryEscaped) { var request = URLRequest(url: url) request.addValue("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/601.1.56 (KHTML, like Gecko) Version/9.0 Safari/601.1.56", forHTTPHeaderField: "User-Agent") let session: URLSession = URLSession(configuration: self.sessionConfiguration) let task = session.dataTask(with: request, completionHandler: { (data, _, _) -> Void in self.loadingSuggests = false if let data = data, let string = String(data: data, encoding: .utf8) { do { let regex = try NSRegularExpression(pattern: "<suggestion data=\"(.+?)\"/>", options: NSRegularExpression.Options.caseInsensitive) let results = regex.matches(in: string, options: [], range: NSRange(location: 0, length: string.characters.count)) let incomming: [String] = results.flatMap({ if $0.numberOfRanges == 2 { return (string as NSString).substring(with: $0.rangeAt( 1)) } return nil }) DispatchQueue.main.async(execute: { self.suggests.removeAll() self.suggests.append(contentsOf: incomming) self.tableView.reloadData() }) } catch { } } }) task.resume() loadingSuggests = true } } func didChangeQuery(text: String) { if let timer = timer { timer.invalidate() self.timer = nil } timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false, block: { (timer) in if !self.loadingSubredditNames && !self.loadingSubredditSearch && !self.loadingSuggests { self.searchSubredditNames(text: text) self.searchSubredditSearch(text: text) self.loadGoogleSuggest(text: text) } self.timer = nil }) } func close(sender: AnyObject) { UIView.animate(withDuration: 0.3, animations: { self.view.alpha = 0 }) { (_) in self.view.removeFromSuperview() } } required init?(coder: NSCoder) { super.init(coder: coder) self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") self.automaticallyAdjustsScrollViewInsets = false } override init(nibName: String?, bundle: Bundle?) { super.init(nibName: nibName, bundle: bundle) self.automaticallyAdjustsScrollViewInsets = false } override init(style: UITableViewStyle) { super.init(style: style) self.automaticallyAdjustsScrollViewInsets = false } override func viewDidLoad() { super.viewDidLoad() self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let section = sectionFromSection(indexPath.section) else { return } switch section { case .name: if 0..<subredditNames.count ~= indexPath.row { let subreddit = subredditNames[indexPath.row] NotificationCenter.default.post(name: SearchControllerDidOpenSubredditName, object: nil, userInfo: [SearchController.subredditKey: subreddit]) } case .topic: if 0..<subredditSearch.count ~= indexPath.row { let subreddit = subredditSearch[indexPath.row] NotificationCenter.default.post(name: SearchControllerDidOpenSubredditName, object: nil, userInfo: [SearchController.subredditKey: subreddit]) } case .suggest: if 0..<suggests.count ~= indexPath.row { let query = suggests[indexPath.row] NotificationCenter.default.post(name: SearchControllerDidSearchSubredditName, object: nil, userInfo: [SearchController.queryKey: query]) } } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let section = sectionFromSection(section) else { return 0 } switch section { case .name: return subredditNames.count case .topic: return subredditSearch.count case .suggest: return suggests.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath) guard let section = sectionFromSection(indexPath.section) else { return cell } switch section { case .name: if 0..<subredditNames.count ~= indexPath.row { cell.textLabel?.text = "/r/" + subredditNames[indexPath.row] } case .topic: if 0..<subredditSearch.count ~= indexPath.row { cell.textLabel?.text = "/r/" + subredditSearch[indexPath.row] } case .suggest: if 0..<suggests.count ~= indexPath.row { cell.textLabel?.text = suggests[indexPath.row] } } return cell } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard let section = sectionFromSection(section) else { return nil } switch section { case .name: if subredditNames.count > 0 { return "Matched subreddit names" } case .topic: if subredditSearch.count > 0 { return "Matched subreddit topics" } case .suggest: if suggests.count > 0 { return "Search links from all of reddit.com." } } return nil } }
mit
e710b104a8668ba7f122d54024ea5913
36.718631
182
0.579335
5.204617
false
false
false
false
andrewBatutin/tripmemories
TravelMemories/TravelMemories/WikiLocationSearchEngine.swift
1
933
// // WikiLocationSearchEngine.swift // TravelMemories // // Created by Batutin, Andriy on 1/5/15. // Copyright (c) 2015 Batutin, Andriy. All rights reserved. // import Foundation public class WikiLocationSearchEngine : NSObject{ public func makeRequestToWikiByLocation(location:String) -> NSDictionary{ let urlPath: String = location var url: NSURL = NSURL(string: urlPath)! var request1: NSURLRequest = NSURLRequest(URL: url) var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil var error: NSErrorPointer = nil var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)! var err: NSError var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary return jsonResult } }
mit
f70d46b05ac04f983a3ebfe35db23430
36.36
163
0.722401
4.962766
false
false
false
false
stephentyrone/swift
test/Incremental/PrivateDependencies/reference-dependencies-members-fine.swift
5
3794
// REQUIRES: shell // Also uses awk: // XFAIL OS=windows // RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // Need -fine-grained-dependency-include-intrafile to be invarient wrt type-body-fingerprints enabled/disabled // RUN: %target-swift-frontend -fine-grained-dependency-include-intrafile -typecheck -primary-file %t/main.swift %S/../Inputs/reference-dependencies-members-helper.swift -emit-reference-dependencies-path - -enable-direct-intramodule-dependencies > %t.swiftdeps // RUN: %target-swift-frontend -fine-grained-dependency-include-intrafile -typecheck -primary-file %t/main.swift %S/../Inputs/reference-dependencies-members-helper.swift -emit-reference-dependencies-path - -enable-direct-intramodule-dependencies > %t-2.swiftdeps // RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t.swiftdeps %t-processed.swiftdeps // RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t-2.swiftdeps %t-2-processed.swiftdeps // RUN: diff %t-processed.swiftdeps %t-2-processed.swiftdeps // RUN: %FileCheck -check-prefix=PROVIDES-NOMINAL %s < %t-processed.swiftdeps // RUN: %FileCheck -check-prefix=PROVIDES-NOMINAL-2 %s < %t-processed.swiftdeps // RUN: %FileCheck -check-prefix=PROVIDES-MEMBER %s < %t-processed.swiftdeps // RUN: %FileCheck -check-prefix=PROVIDES-MEMBER-NEGATIVE %s < %t-processed.swiftdeps // RUN: %FileCheck -check-prefix=DEPENDS-NOMINAL %s < %t-processed.swiftdeps // RUN: %FileCheck -check-prefix=DEPENDS-MEMBER %s < %t-processed.swiftdeps // PROVIDES-NOMINAL-DAG: nominal implementation 4main4BaseC '' true // PROVIDES-NOMINAL-DAG: nominal interface 4main4BaseC '' true class Base { // PROVIDES-MEMBER-DAG: potentialMember implementation 4main4BaseC '' true // PROVIDES-MEMBER-DAG: potentialMember interface 4main4BaseC '' true // PROVIDES-MEMBER-NEGATIVE-NOT: member {{.*}} 4main4BaseC {{[^']]+}} true func foo() {} } // PROVIDES-NOMINAL-DAG: nominal implementation 4main3SubC '' true // PROVIDES-NOMINAL-DAG: nominal interface 4main3SubC '' true // DEPENDS-NOMINAL-DAG: nominal interface 4main9OtherBaseC '' false class Sub : OtherBase { // PROVIDES-MEMBER-DAG: potentialMember implementation 4main3SubC '' true // PROVIDES-MEMBER-NEGATIVE-NOT: {{potentialM|m}}}}ember implementation 4main3SubC {{.+}} true // DEPENDS-MEMBER-DAG: potentialMember interface 4main9OtherBaseC '' false // DEPENDS-MEMBER-DAG: member interface 4main9OtherBaseC foo false // DEPENDS-MEMBER-DAG: member interface 4main9OtherBaseC init false func foo() {} } // PROVIDES-NOMINAL-DAG: nominal implementation 4main9SomeProtoP '' true // PROVIDES-NOMINAL-DAG: nominal interface 4main9SomeProtoP '' true // PROVIDES-MEMBER-DAG: potentialMember interface 4main9SomeProtoP '' true protocol SomeProto {} // PROVIDES-NOMINAL-DAG: nominal implementation 4main10OtherClassC '' true // PROVIDES-NOMINAL-2-DAG: nominal interface 4main10OtherClassC '' true // PROVIDES-MEMBER-DAG: potentialMember interface 4main10OtherClassC '' true // DEPENDS-MEMBER-DAG: potentialMember interface 4main10OtherClassC '' true extension OtherClass : SomeProto {} // PROVIDES-NOMINAL-DAG: nominal implementation 4main11OtherStructV '' true // PROVIDES-NOMINAL-DAG: nominal interface 4main11OtherStructV '' true extension OtherStruct { // PROVIDES-MEMBER-DAG: potentialMember interface 4main11OtherStructV '' true // PROVIDES-MEMBER-DAG: member interface 4main11OtherStructV foo true // PROVIDES-MEMBER-DAG: member interface 4main11OtherStructV bar true // PROVIDES-MEMBER-DAG: member interface 4main11OtherStructV baz true // DEPENDS-MEMBER-DAG: potentialMember interface 4main11OtherStructV '' true func foo() {} var bar: () { return () } private func baz() {} }
apache-2.0
531ed023b82a1e407d96baa3a7e68421
55.626866
262
0.75224
3.658631
false
false
false
false
radvansky-tomas/NutriFacts
nutri-facts/nutri-facts/Helpers/Theme.swift
1
1826
// // Theme.swift // nutri-facts // Theme file -> global colors // Created by Tomas Radvansky on 23/05/2015. // Copyright (c) 2015 Tomas Radvansky. All rights reserved. // import UIKit let AppBaseColor:UIColor = UIColor(red: 74.0/255, green: 217.0/255, blue: 242.0/255, alpha: 1.0) let ControlBcgSolidColor:UIColor = UIColor(red: 170.0/255, green: 170.0/255, blue: 170.0/255, alpha: 0.2) let ControlBcgColor:UIColor = UIColor(red: 255.0/255, green: 255.0/255, blue: 255.0/255, alpha: 0.2) let ControlBcgHighlightedColor:UIColor = UIColor(red: 255.0/255, green: 255.0/255, blue: 255.0/255, alpha: 0.6) let MaleColor:UIColor = UIColor(red: 28.0/255, green: 116.0/255, blue: 255.0/255, alpha: 1.0) let FemaleColor:UIColor = UIColor(red: 240.0/255, green: 123.0/255, blue: 210.0/255, alpha: 1.0) let WeightSliderColors:[UIColor] = [UIColor.redColor(),UIColor.orangeColor(),UIColor.yellowColor(),UIColor.greenColor(),UIColor.yellowColor(),UIColor.orangeColor(),UIColor.redColor(),UIColor.purpleColor()] let MenuItemBcgColor:UIColor = UIColor(red: 255.0/255, green: 255.0/255, blue: 255.0/255, alpha: 0.1) let SugarFreeColor:UIColor = UIColor(red: 254.0/255, green: 159.0/255, blue: 95.0/255, alpha: 1.0) let FatFreeColor:UIColor = UIColor(red: 254.0/255, green: 159.0/255, blue: 95.0/255, alpha: 1.0) let MineralsColor:UIColor = UIColor(red: 158.0/255, green: 159.0/255, blue: 157.0/255, alpha: 1.0) let OilsColor:UIColor = UIColor(red: 206.0/255, green: 178.0/255, blue: 255.0/255, alpha: 1.0) let FatBaseColor:UIColor = UIColor(red: 255.0/255, green: 253.0/255, blue: 169.0/255, alpha: 1.0) let ProtBaseColor:UIColor = UIColor(red: 255.0/255, green: 151.0/255, blue: 149.0/255, alpha: 1.0) let CarbBaseColor:UIColor = UIColor(red: 200.0/255, green: 253.0/255, blue: 255.0/255, alpha: 1.0) class Theme: NSObject { }
gpl-2.0
ceb2bed68b5183c4e0165dd2344c7920
56.0625
205
0.713034
2.705185
false
false
false
false
swipesight/BWWalkthrough
BWWalkthrough/BWWalkthroughViewController.swift
1
12564
/* The MIT License (MIT) Copyright (c) 2015 Yari D'areglia @bitwaker 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 // MARK: - Protocols - /// Walkthrough Delegate: /// This delegate performs basic operations such as dismissing the Walkthrough or call whatever action on page change. /// Probably the Walkthrough is presented by this delegate. @objc public protocol BWWalkthroughViewControllerDelegate{ @objc optional func walkthroughCloseButtonPressed() // If the skipRequest(sender:) action is connected to a button, this function is called when that button is pressed. @objc optional func walkthroughNextButtonPressed() // Called when the "next page" button is pressed @objc optional func walkthroughPrevButtonPressed() // Called when the "previous page" button is pressed @objc optional func walkthroughPageDidChange(_ pageNumber:Int) // Called when current page changes } /// Walkthrough Page: /// The walkthrough page represents any page added to the Walkthrough. @objc public protocol BWWalkthroughPage{ /// While sliding to the "next" slide (from right to left), the "current" slide changes its offset from 1.0 to 2.0 while the "next" slide changes it from 0.0 to 1.0 /// While sliding to the "previous" slide (left to right), the current slide changes its offset from 1.0 to 0.0 while the "previous" slide changes it from 2.0 to 1.0 /// The other pages update their offsets whith values like 2.0, 3.0, -2.0... depending on their positions and on the status of the walkthrough /// This value can be used on the previous, current and next page to perform custom animations on page's subviews. @objc func walkthroughDidScroll(to:CGFloat, offset:CGFloat) // Called when the main Scrollview...scrolls } @objc open class BWWalkthroughViewController: UIViewController, UIScrollViewDelegate{ // MARK: - Public properties - weak open var delegate:BWWalkthroughViewControllerDelegate? // If you need a page control, next or prev buttons, add them via IB and connect with these Outlets @IBOutlet open var pageControl:UIPageControl? @IBOutlet open var nextButton:UIButton? @IBOutlet open var prevButton:UIButton? @IBOutlet open var closeButton:UIButton? open var currentPage: Int { // The index of the current page (readonly) get{ let page = Int((scrollview.contentOffset.x / view.bounds.size.width)) return page } } open var currentViewController:UIViewController{ //the controller for the currently visible page get{ let currentPage = self.currentPage; return controllers[currentPage]; } } open var numberOfPages:Int{ //the total number of pages in the walkthrough get { return self.controllers.count } } // MARK: - Private properties - open let scrollview = UIScrollView() private var controllers = [UIViewController]() private var lastViewConstraint: [NSLayoutConstraint]? // MARK: - Overrides - required public init?(coder aDecoder: NSCoder) { // Setup the scrollview scrollview.showsHorizontalScrollIndicator = false scrollview.showsVerticalScrollIndicator = false scrollview.isPagingEnabled = true super.init(coder: aDecoder) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override open func viewDidLoad() { super.viewDidLoad() // Initialize UI Elements pageControl?.addTarget(self, action: #selector(BWWalkthroughViewController.pageControlDidTouch), for: UIControlEvents.touchUpInside) // Scrollview scrollview.delegate = self scrollview.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(scrollview, at: 0) //scrollview is inserted as first view of the hierarchy // Set scrollview related constraints view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[scrollview]-0-|", options:[], metrics: nil, views: ["scrollview":scrollview] as [String: UIView])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[scrollview]-0-|", options:[], metrics: nil, views: ["scrollview":scrollview] as [String: UIView])) } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); updateUI() pageControl?.numberOfPages = controllers.count pageControl?.currentPage = 0 } // MARK: - Internal methods - @IBAction open func nextPage(){ if (currentPage + 1) < controllers.count { delegate?.walkthroughNextButtonPressed?() gotoPage(currentPage + 1) } } @IBAction open func prevPage(){ if currentPage > 0 { delegate?.walkthroughPrevButtonPressed?() gotoPage(currentPage - 1) } } /// If you want to implement a "skip" button /// connect the button to this IBAction and implement the delegate with the skipWalkthrough @IBAction open func close(_ sender: AnyObject) { delegate?.walkthroughCloseButtonPressed?() } func pageControlDidTouch(){ if let pc = pageControl{ gotoPage(pc.currentPage) } } fileprivate func gotoPage(_ page:Int){ if page < controllers.count{ var frame = scrollview.frame frame.origin.x = CGFloat(page) * frame.size.width scrollview.scrollRectToVisible(frame, animated: true) } } /// Add a new page to the walkthrough. /// To have information about the current position of the page in the walkthrough add a UIViewController which implements BWWalkthroughPage /// - viewController: The view controller that will be added at the end of the view controllers list. open func add(viewController:UIViewController)->Void{ controllers.append(viewController) // Make children aware of the parent addChildViewController(viewController) viewController.didMove(toParentViewController: self) // Setup the viewController view viewController.view.translatesAutoresizingMaskIntoConstraints = false scrollview.addSubview(viewController.view) // Constraints let metricDict = ["w":viewController.view.bounds.size.width,"h":viewController.view.bounds.size.height] // Generic cnst let viewsDict: [String: UIView] = ["view":viewController.view, "container": scrollview] scrollview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[view(==container)]", options:[], metrics: metricDict, views: viewsDict)) scrollview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[view(==container)]", options:[], metrics: metricDict, views: viewsDict)) scrollview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]|", options:[], metrics: nil, views: viewsDict)) // cnst for position: 1st element if controllers.count == 1{ scrollview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]", options:[], metrics: nil, views: ["view":viewController.view])) // cnst for position: other elements } else { let previousVC = controllers[controllers.count-2] if let previousView = previousVC.view { // For this constraint to work, previousView can not be optional scrollview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[previousView]-0-[view]", options:[], metrics: nil, views: ["previousView":previousView,"view":viewController.view])) } if let cst = lastViewConstraint { scrollview.removeConstraints(cst) } lastViewConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:[view]-0-|", options:[], metrics: nil, views: ["view":viewController.view]) scrollview.addConstraints(lastViewConstraint!) } } /// Update the UI to reflect the current walkthrough status fileprivate func updateUI(){ pageControl?.currentPage = currentPage delegate?.walkthroughPageDidChange?(currentPage) // Hide/Show navigation buttons if currentPage == controllers.count - 1{ nextButton?.isHidden = true }else{ nextButton?.isHidden = false } if currentPage == 0{ prevButton?.isHidden = true }else{ prevButton?.isHidden = false } } // MARK: - Scrollview Delegate - open func scrollViewDidScroll(_ sv: UIScrollView) { for i in 0 ..< controllers.count { if let vc = controllers[i] as? BWWalkthroughPage{ let mx = ((scrollview.contentOffset.x + view.bounds.size.width) - (view.bounds.size.width * CGFloat(i))) / view.bounds.size.width // While sliding to the "next" slide (from right to left), the "current" slide changes its offset from 1.0 to 2.0 while the "next" slide changes it from 0.0 to 1.0 // While sliding to the "previous" slide (left to right), the current slide changes its offset from 1.0 to 0.0 while the "previous" slide changes it from 2.0 to 1.0 // The other pages update their offsets whith values like 2.0, 3.0, -2.0... depending on their positions and on the status of the walkthrough // This value can be used on the previous, current and next page to perform custom animations on page's subviews. // print the mx value to get more info. // println("\(i):\(mx)") // We animate only the previous, current and next page if(mx < 2 && mx > -2.0){ vc.walkthroughDidScroll(to:scrollview.contentOffset.x, offset: mx) } } } } open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { updateUI() } open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { updateUI() } fileprivate func adjustOffsetForTransition() { // Get the current page before the transition occurs, otherwise the new size of content will change the index let currentPage = self.currentPage let popTime = DispatchTime.now() + Double(Int64( Double(NSEC_PER_SEC) * 0.1 )) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: popTime) { [weak self] in self?.gotoPage(currentPage) } } override open func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { adjustOffsetForTransition() } override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { adjustOffsetForTransition() } }
mit
3e3de5f2589a7719738d71302ee306dc
40.88
211
0.655922
5.29903
false
false
false
false
lkzhao/Hero
Sources/HeroPlugin.swift
1
6067
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if canImport(UIKit) import UIKit open class HeroPlugin: NSObject, HeroPreprocessor, HeroAnimator { weak public var hero: HeroTransition! public var context: HeroContext! { return hero.context } /** Determines whether or not to receive `seekTo` callback on every frame. Default is false. When **requirePerFrameCallback** is **false**, the plugin needs to start its own animations inside `animate` & `resume` The `seekTo` method is only being called during an interactive transition. When **requirePerFrameCallback** is **true**, the plugin will receive `seekTo` callback on every animation frame. Hence it is possible for the plugin to do per-frame animations without implementing `animate` & `resume` */ open var requirePerFrameCallback = false public override required init() {} /** Called before any animation. Override this method when you want to preprocess modifiers for views - Parameters: - context: object holding all parsed and changed modifiers, - fromViews: A flattened list of all views from source ViewController - toViews: A flattened list of all views from destination ViewController To check a view's modifiers: context[view] context[view, "modifierName"] To set a view's modifiers: context[view] = [("modifier1", ["parameter1"]), ("modifier2", [])] context[view, "modifier1"] = ["parameter1", "parameter2"] */ open func process(fromViews: [UIView], toViews: [UIView]) {} /** - Returns: return true if the plugin can handle animating the view. - Parameters: - context: object holding all parsed and changed modifiers, - view: the view to check whether or not the plugin can handle the animation - appearing: true if the view is appearing(i.e. a view in destination ViewController) If return true, Hero won't animate and won't let any other plugins animate this view. The view will also be hidden automatically during the animation. */ open func canAnimate(view: UIView, appearing: Bool) -> Bool { return false } /** Perform the animation. Note: views in `fromViews` & `toViews` are hidden already. Unhide then if you need to take snapshots. - Parameters: - context: object holding all parsed and changed modifiers, - fromViews: A flattened list of all views from source ViewController (filtered by `canAnimate`) - toViews: A flattened list of all views from destination ViewController (filtered by `canAnimate`) - Returns: The duration needed to complete the animation */ open func animate(fromViews: [UIView], toViews: [UIView]) -> TimeInterval { return 0 } /** Called when all animations are completed. Should perform cleanup and release any reference */ open func clean() {} /** For supporting interactive animation only. This method is called when an interactive animation is in place The plugin should pause the animation, and seek to the given progress - Parameters: - timePassed: time of the animation to seek to. */ open func seekTo(timePassed: TimeInterval) {} /** For supporting interactive animation only. This method is called when an interactive animation is ended The plugin should resume the animation. - Parameters: - timePassed: will be the same value since last `seekTo` - reverse: a boolean value indicating whether or not the animation should reverse */ open func resume(timePassed: TimeInterval, reverse: Bool) -> TimeInterval { return 0 } /** For supporting interactive animation only. This method is called when user wants to override animation modifiers during an interactive animation - Parameters: - state: the target state to override - view: the view to override */ open func apply(state: HeroTargetState, to view: UIView) {} open func changeTarget(state: HeroTargetState, isDestination: Bool, to view: UIView) {} } // methods for enable/disable the current plugin extension HeroPlugin { public static var isEnabled: Bool { get { return HeroTransition.isEnabled(plugin: self) } set { if newValue { enable() } else { disable() } } } public static func enable() { HeroTransition.enable(plugin: self) } public static func disable() { HeroTransition.disable(plugin: self) } } // MARK: Plugin Support internal extension HeroTransition { static func isEnabled(plugin: HeroPlugin.Type) -> Bool { return enabledPlugins.firstIndex(where: { return $0 == plugin}) != nil } static func enable(plugin: HeroPlugin.Type) { disable(plugin: plugin) enabledPlugins.append(plugin) } static func disable(plugin: HeroPlugin.Type) { if let index = enabledPlugins.firstIndex(where: { return $0 == plugin}) { enabledPlugins.remove(at: index) } } } #endif
mit
9ec1b374b41c7b3d6a0d71b682b6a721
33.668571
222
0.709906
4.624238
false
false
false
false
shajrawi/swift
test/Sema/implementation-only-import-library-evolution.swift
1
5425
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -o %t/NormalLibrary.swiftmodule %S/Inputs/implementation-only-import-in-decls-public-helper.swift // RUN: %target-swift-frontend -emit-module -o %t/BADLibrary.swiftmodule %S/Inputs/implementation-only-import-in-decls-helper.swift -I %t // RUN: %target-typecheck-verify-swift -I %t -enable-library-evolution @_implementationOnly import BADLibrary public struct PublicStructStoredProperties { public var publiclyBad: BadStruct? // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} internal var internallyBad: BadStruct? // okay private var privatelyBad: BadStruct? // okay private let letIsLikeVar = [BadStruct]() // okay private var computedIsOkay: BadStruct? { return nil } // okay private static var staticIsOkay: BadStruct? // okay @usableFromInline internal var computedUFIIsNot: BadStruct? { return nil } // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} } @usableFromInline internal struct UFIStructStoredProperties { @usableFromInline var publiclyBad: BadStruct? // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} internal var internallyBad: BadStruct? // okay private var privatelyBad: BadStruct? // okay private let letIsLikeVar = [BadStruct]() // okay private var computedIsOkay: BadStruct? { return nil } // okay private static var staticIsOkay: BadStruct? // okay @usableFromInline internal var computedUFIIsNot: BadStruct? { return nil } // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} } public class PublicClassStoredProperties { public var publiclyBad: BadStruct? // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} internal var internallyBad: BadStruct? // okay private var privatelyBad: BadStruct? // okay private let letIsLikeVar = [BadStruct]() // okay private var computedIsOkay: BadStruct? { return nil } // okay private static var staticIsOkay: BadStruct? // okay @usableFromInline internal var computedUFIIsNot: BadStruct? { return nil } // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} } // MARK: Frozen types @_fixed_layout public struct FrozenPublicStructStoredProperties { public var publiclyBad: BadStruct? // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} internal var internallyBad: BadStruct? // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} private var privatelyBad: BadStruct? // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} private let letIsLikeVar: [BadStruct] = [] // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} private var computedIsOkay: BadStruct? { return nil } // okay private static var staticIsOkay: BadStruct? // okay @usableFromInline internal var computedUFIIsNot: BadStruct? { return nil } // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} } @_fixed_layout @usableFromInline internal struct FrozenUFIStructStoredProperties { @usableFromInline var publiclyBad: BadStruct? // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} internal var internallyBad: BadStruct? // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} private var privatelyBad: BadStruct? // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} private let letIsLikeVar: [BadStruct] = [] // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} private var computedIsOkay: BadStruct? { return nil } // okay private static var staticIsOkay: BadStruct? // okay @usableFromInline internal var computedUFIIsNot: BadStruct? { return nil } // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} } @_fixed_layout public class FrozenPublicClassStoredProperties { public var publiclyBad: BadStruct? // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} internal var internallyBad: BadStruct? // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} private var privatelyBad: BadStruct? // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} private let letIsLikeVar: [BadStruct] = [] // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} private var computedIsOkay: BadStruct? { return nil } // okay private static var staticIsOkay: BadStruct? // okay @usableFromInline internal var computedUFIIsNot: BadStruct? { return nil } // expected-error {{cannot use struct 'BadStruct' here; 'BADLibrary' has been imported as implementation-only}} }
apache-2.0
4a671f5b329a539d253496e202c4bf6c
68.551282
188
0.764977
4.144385
false
false
false
false
evermeer/EVWordPressAPI
EVWordPressAPI/EVWordPressAPI_Comments.swift
1
3717
// // EVWordpressAPI_Comments.swift // EVWordPressAPI // // Created by Edwin Vermeer on 9/21/15. // Copyright © 2015 evict. All rights reserved. // import Alamofire import AlamofireOauth2 import AlamofireJsonToObjects import EVReflection public extension EVWordPressAPI { // MARK: - Comments /** Get a list of recent comments. See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/comments/ :param: parameters an array of postsParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Posts object :return: No return value */ public func comments(_ parameters:[commentsParameters]? = nil, completionHandler: @escaping (Comments?) -> Void) { genericCall("/sites/\(self.site)/comments/", parameters:parameters, completionHandler: completionHandler) } /** Get a list of recent comments. See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/comments/ :param: postId The postId where you want the replies for. :param: parameters an array of postsParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Posts object :return: No return value */ public func replies(postId: String, parameters:[commentsParameters]? = nil, completionHandler: @escaping (Comments?) -> Void) { genericCall("/sites/\(self.site)/posts/\(postId)/replies/", parameters:parameters, completionHandler: completionHandler) } /** Get a single comments. See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/comments/%24comment_ID/ :param: commentId The comment id :param: parameters an array of postsParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Posts object :return: No return value */ public func comment(commentId: String, parameters:[basicContextParameters]? = nil, completionHandler: @escaping (Comment?) -> Void) { genericCall("/sites/\(self.site)/comments/", parameters:parameters, completionHandler: completionHandler) } /** Get the likes for a comment See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/comments/%24comment_ID/likes/ :param: commentId The comment ID :param: parameters an array of basicParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Likes object :return: No return value */ public func commentLikes(commentId:String, parameters:[basicParameters]? = nil, completionHandler: @escaping (Likes?) -> Void) { genericCall("/sites/\(self.site)/comments/\(commentId)/likes/", parameters:parameters, completionHandler: completionHandler) } /** Get the current user's like status for a post. See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/posts/%24post_ID/likes/mine/ :param: commentId The comment ID :param: parameters an array of basicParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Likes object :return: No return value */ public func commentsLikesMine(commentId:String, parameters:[basicParameters]? = nil, completionHandler: @escaping (Likes?) -> Void) { genericCall("/sites/\(self.site)/comments/\(commentId)/likes/mine/", parameters:parameters, completionHandler: completionHandler) } }
bsd-3-clause
2e779e7c37b9e54cf8c1efeda7a6571d
43.238095
137
0.717438
4.520681
false
false
false
false
hirohisa/ImageLoaderSwift
Example/ImageLoaderExample/BlockingMainThreadPerfomanceTestViewController.swift
1
2260
// // BlockingMainThreadPerfomanceTestViewController.swift // ImageLoaderExample // // Created by Hirohisa Kawasaki on 11/23/15. // Copyright © 2015 Hirohisa Kawasaki. All rights reserved. // import UIKit import ImageLoader class BlockingMainThreadPerfomanceTestViewController: CollectionViewController { var watchdog: Watchdog? func report() { let delegate = UIApplication.shared.delegate as! AppDelegate delegate.report() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) Disk().cleanUp() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) watchdog = Watchdog(threshold: 0.1, handler: { duration in print("👮 Main thread was blocked for " + String(format:"%.2f", duration) + "s 👮") }) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) watchdog = nil } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell let url = String.imageURL(indexPath.row % 100) let startDate = Date() cell.imageView.contentMode = contentMode cell.imageView.image = UIImage(color: UIColor.black) cell.imageView.load.request(with: url, onCompletion: { _, _, operation in switch operation { case .network: let diff = Date().timeIntervalSince(startDate) print("loading time: \(diff)") if let image = cell.imageView.image { print("from network, image size: \(image.size)") } case .disk: if let image = cell.imageView.image { print("from cache, image size: \(image.size)") } case .error: print("error") } }) return cell } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 200 } }
mit
520b4a902611d563edb4751215ef984b
31.185714
135
0.62095
5.085779
false
false
false
false
DumbDuck/VecodeKit
iOS_Mac/QuartzPicture/swift/ext/VKQuartzPictureImage.swift
1
2735
import Foundation #if os(iOS) import UIKit private func createImageWithSize(_ size: CGSize, drawer: (CGContext) -> Void) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) defer { UIGraphicsEndImageContext() } let context = UIGraphicsGetCurrentContext()! drawer(context) return UIGraphicsGetImageFromCurrentImageContext()! } public extension VKQuartzPicture { func transToImage() -> UIImage { return transToImage(self.bounds.size, .scaleAspectFit) } func transToImage(_ size: CGSize, _ color: UIColor, _ mode: VKPictureContentMode = .scaleAspectFit) -> UIImage { return createImageWithSize(size) { context in context.setStrokeColor(color.cgColor) context.setFillColor(color.cgColor) let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) VKQuartzPictureDrawInRect(self, rect, context, mode) } } func transToImage(_ size: CGSize, _ mode: VKPictureContentMode = .scaleAspectFit) -> UIImage { return createImageWithSize(size) { context in let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) VKQuartzPictureDrawInRect(self, rect, context, mode) } } } #else import AppKit private func createImageWithSize(_ size: CGSize, drawer: (CGContext) -> Void) -> NSImage { let newImage = NSImage(size: size) newImage.lockFocusFlipped(true) let context = NSGraphicsContext.current()!.cgContext drawer(context) newImage.unlockFocus() return newImage } public extension VKQuartzPicture { func transToImage() -> NSImage { return transToImage(self.bounds.size, .scaleAspectFit) } func transToImage(_ size: CGSize, _ color: NSColor, _ mode: VKPictureContentMode = .scaleAspectFit) -> NSImage { return createImageWithSize(size) { context in context.setStrokeColor(color.cgColor) context.setFillColor(color.cgColor) let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) VKQuartzPictureDrawInRect(self, rect, context, mode) } } func transToImage(_ size: CGSize, _ mode: VKPictureContentMode = .scaleAspectFit) -> NSImage { return createImageWithSize(size) { context in let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) VKQuartzPictureDrawInRect(self, rect, context, mode) } } } #endif
mit
4672c782b84f2258e346d2e26f35a3dc
35.466667
120
0.610969
4.781469
false
false
false
false
practicalswift/swift
test/SILGen/availability_query.swift
15
3592
// RUN: %target-swift-emit-sil %s -target x86_64-apple-macosx10.50 -verify // RUN: %target-swift-emit-silgen %s -target x86_64-apple-macosx10.50 | %FileCheck %s // REQUIRES: OS=macosx // CHECK-LABEL: sil{{.+}}@main{{.*}} { // CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10 // CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 53 // CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 8 // CHECK: [[FUNC:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 // CHECK: [[QUERY_RESULT:%.*]] = apply [[FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 if #available(OSX 10.53.8, iOS 7.1, *) { } // CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK: cond_br [[TRUE]] // Since we are compiling for an unmentioned platform (OS X), we check against the minimum // deployment target, which is 10.50 if #available(iOS 7.1, *) { } // CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10 // CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52 // CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0 // CHECK: [[QUERY_FUNC:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 // CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 if #available(OSX 10.52, *) { } // CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10 // CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52 // CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0 // CHECK: [[QUERY_FUNC:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 // CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 if #available(macOS 10.52, *) { } // CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10 // CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 0 // CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0 // CHECK: [[QUERY_FUNC:%.*]] = function_ref @$ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 // CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1 if #available(OSX 10, *) { } // CHECK: } func doThing() {} func testUnreachableVersionAvailable(condition: Bool) { if #available(OSX 10.0, *) { doThing() // no-warning return } else { doThing() // FIXME-warning {{will never be executed}} } if true { doThing() // no-warning } if false { // expected-note {{condition always evaluates to false}} doThing() // expected-warning {{will never be executed}} } } func testUnreachablePlatformAvailable(condition: Bool) { if #available(iOS 7.1, *) { doThing() // no-warning return } else { doThing() // no-warning } if true { doThing() // no-warning } if false { // expected-note {{condition always evaluates to false}} doThing() // expected-warning {{will never be executed}} } } func testUnreachablePlatformAvailableGuard() { guard #available(iOS 7.1, *) else { doThing() // no-warning return } doThing() // no-warning }
apache-2.0
b79947be0b811b0edd0a59858448b058
38.472527
170
0.640869
3.417697
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Components/SelectionScreen/TableHeaderView/SelectionScreenTableHeaderView.swift
1
1764
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RxSwift public final class SelectionScreenTableHeaderView: UIView { private static let verticalPadding: CGFloat = 32.0 private static let horizontalPadding: CGFloat = 64.0 private var disposeBag = DisposeBag() // MARK: - Public Properties var viewModel: SelectionScreenTableHeaderViewModel! { willSet { disposeBag = DisposeBag() } didSet { guard let viewModel = viewModel else { return } titleLabel.font = viewModel.font // Bind label text viewModel.text .drive(titleLabel.rx.text) .disposed(by: disposeBag) // Bind label text color viewModel.contentColor .drive(titleLabel.rx.textColor) .disposed(by: disposeBag) } } // MARK: - Private IBOutlets @IBOutlet private var titleLabel: UILabel! // MARK: - Setup override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { fromNib(in: .module) clipsToBounds = true } } extension SelectionScreenTableHeaderView { static func estimatedHeight(for width: CGFloat, model: SelectionScreenTableHeaderViewModel) -> CGFloat { let adjustedWidth = width - horizontalPadding let textHeight = NSAttributedString( string: model.textRelay.value, attributes: [ .font: model.font ] ).heightForWidth(width: adjustedWidth) return textHeight + verticalPadding } }
lgpl-3.0
1a35e7bd707715739067c1c8ba5e69c9
24.926471
108
0.604651
5.185294
false
false
false
false
fitpay/fitpay-ios-sdk
FitpaySDK/Notifications/EventStream/UserEventStreamManager.swift
1
1439
import Foundation public class UserEventStreamManager { public static let sharedInstance = UserEventStreamManager() public var client: RestClient? private var userEventStreams: [String: UserEventStream] = [:] public typealias userEventStreamHandler = (_ event: StreamEvent) -> Void public func subscribe(userId: String, sessionData: SessionData?, completion: @escaping userEventStreamHandler) { let session = RestSession(sessionData: sessionData) client = RestClient(session: session) client!.getPlatformConfig { (platformConfig, _) in guard let isUserEventStreamsEnabled = platformConfig?.isUserEventStreamsEnabled, isUserEventStreamsEnabled else { log.debug("USER_EVENT_STREAM: userEventStreamsEnabled has been disabled at the platform level, skipping user event stream subscription") return } self.client!.user(id: userId) { (user, _) in guard let user = user else { return } if self.userEventStreams[userId] == nil { self.userEventStreams[userId] = UserEventStream(user: user, client: self.client!, completion: completion) } } } } public func unsubscribe(userId: String) { userEventStreams[userId]?.close() userEventStreams[userId] = nil } }
mit
48edb8fdb80c013a6608afd712963f5d
38.972222
152
0.632384
5.290441
false
true
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/ZDOpenSourceSwiftDemo/ViewModels/ZDMovieViewModel.swift
1
1193
// // ZDMovieViewModel.swift // ZDOpenSourceSwiftDemo // // Created by Zero.D.Saber on 2018/6/14. // Copyright © 2018年 Zero.D.Saber. All rights reserved. // import Foundation class ZDMovieViewModel { // 没有自定义初始化的类,其属性需要设置为option var dataTask: URLSessionDataTask? func fetchMovieList(completaion: @escaping ([ZDMovieModel]?) -> Void) { dataTask = URLSession.shared.dataTask(with: URL(string: ZDAPI.ShowingMovies.rawValue)!, completionHandler: { (data, response, error) in guard let data = data else { completaion(nil) return } let jsonDecoder = JSONDecoder(); var wrapModel: ZDMovieWrapModel? do { wrapModel = try jsonDecoder.decode(ZDMovieWrapModel.self, from: data) } catch let error as NSError { print("Error ---> : \(error.localizedDescription)") } guard let dataSource = wrapModel?.ms else { completaion(nil) return } completaion(dataSource) }) dataTask?.resume() } }
mit
b4931f9b2a89111dd87a604c2c3af043
30.135135
143
0.571181
4.55336
false
false
false
false
zmian/xcore.swift
Sources/Xcore/Cocoa/Components/AnimationRunLoop.swift
1
1707
// // Xcore // Copyright © 2019 Xcore // MIT license, see LICENSE file for details // import UIKit /// A class to report in-flight animation progress. /// /// `UIView.animate(withDuration:)` doesn't provide any way for us to observe /// "in-flight" animation value for the animated properties. Without "in-flight" /// animation values we are unable to observe content inset to make adjustments /// to UI. public final class AnimationRunLoop { private var displayLink: CADisplayLink? private var beginTime: CFTimeInterval = 0 private var endTime: CFTimeInterval = 0 private var duration: TimeInterval = 0.25 private var animations: ((_ progress: Double) -> Void)? private var completion: (() -> Void)? public init() {} public func start( duration: TimeInterval, animations: @escaping (_ progress: Double) -> Void, completion: @escaping () -> Void ) { self.duration = duration self.animations = animations self.completion = completion stop() let displayLink = CADisplayLink(target: self, selector: #selector(step)) displayLink.add(to: .main, forMode: .common) self.displayLink = displayLink } public func stop() { displayLink?.invalidate() displayLink = nil beginTime = CACurrentMediaTime() endTime = duration + beginTime } @objc private func step(_ displayLink: CADisplayLink) { let now = CACurrentMediaTime() var percent = (now - beginTime) / duration percent = min(1, max(0, percent)) animations?(percent) if now >= endTime { stop() completion?() } } }
mit
abf87863978619df8bcce458a3d11cc9
27.915254
80
0.629543
4.805634
false
false
false
false
ldt25290/MyInstaMap
ThirdParty/AlamofireImage/Tests/ImageDownloaderTests.swift
4
36922
// // ImageDownloaderTests.swift // // Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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. // @testable import Alamofire @testable import AlamofireImage import Foundation import XCTest private class ThreadCheckFilter: ImageFilter { var calledOnMainQueue = false init() {} var filter: (Image) -> Image { return { image in self.calledOnMainQueue = Thread.isMainThread return image } } } // MARK: - #if os(iOS) || os(tvOS) private class TestCircleFilter: ImageFilter { var filterOperationCompleted = false var filter: (Image) -> Image { return { image in self.filterOperationCompleted = true return image.af_imageRoundedIntoCircle() } } } #endif // MARK: - class ImageDownloaderTestCase: BaseTestCase { // MARK: - Setup and Teardown override func setUp() { super.setUp() ImageDownloader.defaultURLCache().removeAllCachedResponses() } // MARK: - Initialization Tests func testThatImageDownloaderSingletonCanBeInitialized() { // Given, When let downloader = ImageDownloader.default // Then XCTAssertNotNil(downloader, "downloader should not be nil") } func testThatImageDownloaderCanBeInitializedAndDeinitialized() { // Given var downloader: ImageDownloader? = ImageDownloader() // When downloader = nil // Then XCTAssertNil(downloader, "downloader should be nil") } func testThatImageDownloaderCanBeInitializedWithManagerInstanceAndDeinitialized() { // Given var downloader: ImageDownloader? = ImageDownloader(sessionManager: SessionManager()) // When downloader = nil // Then XCTAssertNil(downloader, "downloader should be nil") } func testThatImageDownloaderCanBeInitializedAndDeinitializedWithActiveDownloads() { // Given let urlRequest = try! URLRequest(url: "https://httpbin.org/image/png", method: .get) var downloader: ImageDownloader? = ImageDownloader() // When let _ = downloader?.download(urlRequest) { _ in // No-op } downloader = nil // Then XCTAssertNil(downloader, "downloader should be nil") } // MARK: - Image Download Tests func testThatItCanDownloadAnImage() { // Given let downloader = ImageDownloader() let urlRequest = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let expectation = self.expectation(description: "image download should succeed") var response: DataResponse<Image>? // When downloader.download(urlRequest) { closureResponse in response = closureResponse expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request, "request should not be nil") XCTAssertNotNil(response?.response, "response should not be nil") XCTAssertNotNil(response?.result, "result should not be nil") XCTAssertTrue(response?.result.isSuccess ?? false, "result should be a success case") } func testThatItCanDownloadMultipleImagesSimultaneously() { // Given let downloader = ImageDownloader() let urlRequest1 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let urlRequest2 = try! URLRequest(url: "https://httpbin.org/image/png", method: .get) let expectation1 = expectation(description: "download 1 should succeed") let expectation2 = expectation(description: "download 2 should succeed") var result1: Result<Image>? var result2: Result<Image>? // When downloader.download(urlRequest1) { closureResponse in result1 = closureResponse.result expectation1.fulfill() } downloader.download(urlRequest2) { closureResponse in result2 = closureResponse.result expectation2.fulfill() } let activeRequestCount = downloader.activeRequestCount waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertEqual(activeRequestCount, 2, "active request count should be 2") XCTAssertNotNil(result1, "result 1 should not be nil") XCTAssertNotNil(result2, "result 2 should not be nil") XCTAssertTrue(result1?.isSuccess ?? false, "result 1 should be a success case") XCTAssertTrue(result2?.isSuccess ?? false, "result 2 should be a success case") } func testThatItCanEnqueueMultipleImages() { // Given let downloader = ImageDownloader() let urlRequest1 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let urlRequest2 = try! URLRequest(url: "https://httpbin.org/image/png", method: .get) let expectation = self.expectation(description: "both downloads should succeed") var completedDownloads = 0 var results: [Result<Image>] = [] // When downloader.download([urlRequest1, urlRequest2], filter: nil) { closureResponse in results.append(closureResponse.result) completedDownloads += 1 if completedDownloads == 2 { expectation.fulfill() } } let activeRequestCount = downloader.activeRequestCount waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertEqual(activeRequestCount, 2, "active request count should be 2") XCTAssertTrue(results[0].isSuccess, "the first result should be a success case") XCTAssertTrue(results[1].isSuccess, "the second result should be a success case") } func testThatItDoesNotExceedTheMaximumActiveDownloadsLimit() { // Given let downloader = ImageDownloader(maximumActiveDownloads: 1) let urlRequest1 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let urlRequest2 = try! URLRequest(url: "https://httpbin.org/image/png", method: .get) // When let requestReceipt1 = downloader.download(urlRequest1) { _ in // No-op } let requestReceipt2 = downloader.download(urlRequest2) { _ in // No-op } let activeRequestCount = downloader.activeRequestCount requestReceipt1?.request.cancel() requestReceipt2?.request.cancel() // Then XCTAssertEqual(activeRequestCount, 1, "active request count should be 1") } func testThatItCallsTheCompletionHandlerEvenWhenDownloadFails() { // Given let downloader = ImageDownloader() let urlRequest = try! URLRequest(url: "https://httpbin.org/get", method: .get) let expectation = self.expectation(description: "download request should fail") var response: DataResponse<Image>? // When downloader.download(urlRequest) { closureResponse in response = closureResponse expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request, "request should not be nil") XCTAssertNotNil(response?.response, "response should not be nil") XCTAssertTrue(response?.result.isFailure ?? false, "result should be a failure case") } func testThatItCanDownloadImagesWithDisabledURLCacheInSessionConfiguration() { // Given let downloader: ImageDownloader = { let configuration: URLSessionConfiguration = { let configuration = URLSessionConfiguration.default configuration.urlCache = nil return configuration }() let downloader = ImageDownloader(configuration: configuration) return downloader }() let urlRequest = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let expectation = self.expectation(description: "image download should succeed") var response: DataResponse<Image>? // When downloader.download(urlRequest) { closureResponse in response = closureResponse expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request, "request should not be nil") XCTAssertNotNil(response?.response, "response should not be nil") XCTAssertTrue(response?.result.isSuccess ?? false, "result should be a success case") } #if os(iOS) || os(tvOS) // MARK: - Image Download Tests (iOS and tvOS Only) func testThatItCanDownloadImageAndApplyImageFilter() { // Given let downloader = ImageDownloader() let urlRequest = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let scaledSize = CGSize(width: 100, height: 60) let filter = ScaledToSizeFilter(size: scaledSize) let expectation = self.expectation(description: "image download should succeed") var response: DataResponse<Image>? // When downloader.download(urlRequest, filter: filter) { closureResponse in response = closureResponse expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request, "request should not be nil") XCTAssertNotNil(response?.response, "response should not be nil") XCTAssertTrue(response?.result.isSuccess ?? false, "result should be a success case") if let image = response?.result.value { XCTAssertEqual(image.size, scaledSize, "image size does not match expected value") } } func testThatItCanAppendFilterAndCompletionHandlerToExistingDownload() { // Given let downloader = ImageDownloader() let urlRequest1 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let urlRequest2 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let filter1 = ScaledToSizeFilter(size: CGSize(width: 50, height: 50)) let filter2 = ScaledToSizeFilter(size: CGSize(width: 75, height: 75)) let expectation1 = expectation(description: "download request 1 should succeed") let expectation2 = expectation(description: "download request 2 should succeed") var result1: Result<Image>? var result2: Result<Image>? // When let requestReceipt1 = downloader.download(urlRequest1, filter: filter1) { closureResponse in result1 = closureResponse.result expectation1.fulfill() } let requestReceipt2 = downloader.download(urlRequest2, filter: filter2) { closureResponse in result2 = closureResponse.result expectation2.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertEqual(requestReceipt1?.request.task, requestReceipt2?.request.task, "request 1 and 2 should be equal") XCTAssertNotNil(result1, "result 1 should not be nil") XCTAssertNotNil(result2, "result 2 should not be nil") XCTAssertTrue(result1?.isSuccess ?? false, "result 1 should be a success case") XCTAssertTrue(result2?.isSuccess ?? false, "result 2 should be a success case") if let image = result1?.value { XCTAssertEqual(image.size, CGSize(width: 50, height: 50), "image size does not match expected value") } if let image = result2?.value { XCTAssertEqual(image.size, CGSize(width: 75, height: 75), "image size does not match expected value") } } func testThatDownloadsWithMultipleResponseHandlersOnlyRunDuplicateImageFiltersOnce() { // Given let downloader = ImageDownloader() let urlRequest1 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let urlRequest2 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let filter1 = TestCircleFilter() let filter2 = TestCircleFilter() let expectation1 = expectation(description: "download request 1 should succeed") let expectation2 = expectation(description: "download request 2 should succeed") var result1: Result<Image>? var result2: Result<Image>? // When let requestReceipt1 = downloader.download(urlRequest1, filter: filter1) { closureResponse in result1 = closureResponse.result expectation1.fulfill() } let requestReceipt2 = downloader.download(urlRequest2, filter: filter2) { closureResponse in result2 = closureResponse.result expectation2.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertEqual(requestReceipt1?.request.task, requestReceipt2?.request.task, "tasks 1 and 2 should be equal") XCTAssertNotNil(result1, "result 1 should not be nil") XCTAssertNotNil(result2, "result 2 should not be nil") XCTAssertTrue(result1?.isSuccess ?? false, "result 1 should be a success case") XCTAssertTrue(result2?.isSuccess ?? false, "result 2 should be a success case") XCTAssertTrue(filter1.filterOperationCompleted, "the filter 1 filter operation completed flag should be true") XCTAssertFalse(filter2.filterOperationCompleted, "the filter 2 filter operation completed flag should be false") } #endif // MARK: - Progress Closure Tests func testThatItCallsTheProgressHandlerOnTheMainQueueByDefault() { // Given let downloader = ImageDownloader() let urlRequest = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let progressExpectation = expectation(description: "progress closure should be called") let completedExpectation = expectation(description: "download request should succeed") var progressCalled = false var calledOnMainQueue = false // When downloader.download( urlRequest, progress: { _ in if progressCalled == false { progressCalled = true calledOnMainQueue = Thread.isMainThread progressExpectation.fulfill() } }, completion: { _ in completedExpectation.fulfill() } ) waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertTrue(calledOnMainQueue, "progress handler should be called on main queue") } func testThatItCallsTheProgressHandlerOnTheProgressQueue() { // Given let downloader = ImageDownloader() let urlRequest = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let progressExpectation = expectation(description: "progress closure should be called") let completedExpectation = expectation(description: "download request should succeed") var progressCalled = false var calledOnExpectedQueue = false // When downloader.download( urlRequest, progress: { _ in if progressCalled == false { progressCalled = true calledOnExpectedQueue = !Thread.isMainThread progressExpectation.fulfill() } }, progressQueue: DispatchQueue.global(qos: .utility), completion: { _ in completedExpectation.fulfill() } ) waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertTrue(calledOnExpectedQueue, "progress handler should be called on expected queue") } // MARK: - Cancellation Tests func testThatCancellingDownloadCallsCompletionWithCancellationError() { // Given let downloader = ImageDownloader() let urlRequest = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let expectation = self.expectation(description: "download request should succeed") var response: DataResponse<Image>? // When let requestReceipt = downloader.download(urlRequest) { closureResponse in response = closureResponse expectation.fulfill() } downloader.cancelRequest(with: requestReceipt!) waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(response?.request, "request should not be nil") XCTAssertNil(response?.response, "response should be nil") XCTAssertNil(response?.data, "data should be nil") XCTAssertTrue(response?.result.isFailure ?? false, "result should be a failure case") if let error = response?.result.error as? AFIError { XCTAssertTrue(error.isRequestCancelledError) } else { XCTFail("error should not be nil") } } func testThatCancellingDownloadWithMultipleResponseHandlersCancelsFirstYetAllowsSecondToComplete() { // Given let downloader = ImageDownloader() let urlRequest1 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let urlRequest2 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let expectation1 = expectation(description: "download request 1 should succeed") let expectation2 = expectation(description: "download request 2 should succeed") var response1: DataResponse<Image>? var response2: DataResponse<Image>? // When let requestReceipt1 = downloader.download(urlRequest1) { closureResponse in response1 = closureResponse expectation1.fulfill() } let requestReceipt2 = downloader.download(urlRequest2) { closureResponse in response2 = closureResponse expectation2.fulfill() } downloader.cancelRequest(with: requestReceipt1!) waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertEqual(requestReceipt1?.request.task, requestReceipt2?.request.task, "tasks 1 and 2 should be equal") XCTAssertNotNil(response1, "response 1 should not be nil") XCTAssertNotNil(response1?.request, "response 1 request should not be nil") XCTAssertNil(response1?.response, "response 1 response should be nil") XCTAssertNil(response1?.data, "response 1 data should be nil") XCTAssertTrue(response1?.result.isFailure ?? false, "response 1 result should be a failure case") if let error = response1?.result.error as? AFIError { XCTAssertTrue(error.isRequestCancelledError) } else { XCTFail("error should not be nil") } XCTAssertNotNil(response2, "response 2 should not be nil") XCTAssertNotNil(response2?.request, "response 2 request should not be nil") XCTAssertNotNil(response2?.response, "response 2 response should not be nil") XCTAssertNotNil(response2?.data, "response 2 data should not be nil") XCTAssertTrue(response2?.result.isSuccess ?? false, "response 2 result should be a success case") } func testThatItCanDownloadAndCancelAndDownloadAgain() { // Given let downloader = ImageDownloader() let imageRequests: [URLRequest] = [ "https://secure.gravatar.com/avatar/5a105e8b9d40e1329780d62ea2265d8a?d=identicon", "https://secure.gravatar.com/avatar/6a105e8b9d40e1329780d62ea2265d8a?d=identicon", "https://secure.gravatar.com/avatar/7a105e8b9d40e1329780d62ea2265d8a?d=identicon", "https://secure.gravatar.com/avatar/8a105e8b9d40e1329780d62ea2265d8a?d=identicon", "https://secure.gravatar.com/avatar/9a105e8b9d40e1329780d62ea2265d8a?d=identicon" ].map { URLRequest(url: URL(string: $0)!) } var initialResults: [Result<Image>] = [] var finalResults: [Result<Image>] = [] // When for (index, imageRequest) in imageRequests.enumerated() { let expectation = self.expectation(description: "Download \(index) should be cancelled: \(imageRequest)") let receipt = downloader.download(imageRequest) { response in switch response.result { case .success: initialResults.append(response.result) expectation.fulfill() case .failure: initialResults.append(response.result) expectation.fulfill() } } if let receipt = receipt { downloader.cancelRequest(with: receipt) } } for (index, imageRequest) in imageRequests.enumerated() { let expectation = self.expectation(description: "Download \(index) should complete: \(imageRequest)") downloader.download(imageRequest) { response in switch response.result { case .success: finalResults.append(response.result) expectation.fulfill() case .failure: finalResults.append(response.result) expectation.fulfill() } } } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertEqual(initialResults.count, 5) XCTAssertEqual(finalResults.count, 5) for result in initialResults { XCTAssertTrue(result.isFailure) if case let .failure(error) = result, let afiError = error as? AFIError { XCTAssertTrue(afiError.isRequestCancelledError) } else { XCTFail("error should not be nil") } } for result in finalResults { XCTAssertTrue(result.isSuccess) } } // MARK: - Authentication Tests func testThatItDoesNotAttachAuthenticationCredentialToRequestIfItDoesNotExist() { // Given let downloader = ImageDownloader() let urlRequest = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) // When let requestReceipt = downloader.download(urlRequest) { _ in // No-op } let credential = requestReceipt?.request.delegate.credential requestReceipt?.request.cancel() // Then XCTAssertNil(credential, "credential should be nil") } func testThatItAttachsUsernamePasswordCredentialToRequestIfItExists() { // Given let downloader = ImageDownloader() let urlRequest = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) // When downloader.addAuthentication(user: "foo", password: "bar") let requestReceipt = downloader.download(urlRequest) { _ in // No-op } let credential = requestReceipt?.request.delegate.credential requestReceipt?.request.cancel() // Then XCTAssertNotNil(credential, "credential should not be nil") } func testThatItAttachsAuthenticationCredentialToRequestIfItExists() { // Given let downloader = ImageDownloader() let urlRequest = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) // When let credential = URLCredential(user: "foo", password: "bar", persistence: .forSession) downloader.addAuthentication(usingCredential: credential) let requestReceipt = downloader.download(urlRequest) { _ in // No-op } let requestCredential = requestReceipt?.request.delegate.credential requestReceipt?.request.cancel() // Then XCTAssertNotNil(requestCredential, "request credential should not be nil") } // MARK: - Threading Tests func testThatItAlwaysCallsTheCompletionHandlerOnTheMainQueue() { // Given let downloader = ImageDownloader() let urlRequest = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let expectation = self.expectation(description: "download request should succeed") var calledOnMainQueue = false // When downloader.download(urlRequest) { _ in calledOnMainQueue = Thread.isMainThread expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertTrue(calledOnMainQueue, "completion handler should be called on main queue") } func testThatItNeverCallsTheImageFilterOnTheMainQueue() { // Given let downloader = ImageDownloader() let urlRequest = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let filter = ThreadCheckFilter() let expectation = self.expectation(description: "download request should succeed") // When downloader.download(urlRequest, filter: filter) { _ in expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertFalse(filter.calledOnMainQueue, "filter should not be called on main queue") } // MARK: - Image Caching Tests func testThatCachedImageIsReturnedIfAllowedByCachePolicy() { // Given let downloader = ImageDownloader() let urlRequest1 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let expectation1 = expectation(description: "image download should succeed") // When let requestReceipt1 = downloader.download(urlRequest1) { _ in expectation1.fulfill() } waitForExpectations(timeout: timeout, handler: nil) var urlRequest2 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) urlRequest2.cachePolicy = .returnCacheDataElseLoad let expectation2 = expectation(description: "image download should succeed") let requestReceipt2 = downloader.download(urlRequest2) { _ in expectation2.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(requestReceipt1, "request receipt 1 should not be nil") XCTAssertNil(requestReceipt2, "request receipt 2 should be nil") } func testThatCachedImageIsNotReturnedIfNotAllowedByCachePolicy() { // Given let downloader = ImageDownloader() let urlRequest1 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let expectation1 = expectation(description: "image download should succeed") // When let requestReceipt1 = downloader.download(urlRequest1) { _ in expectation1.fulfill() } waitForExpectations(timeout: timeout, handler: nil) var urlRequest2 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) urlRequest2.cachePolicy = .reloadIgnoringLocalCacheData let expectation2 = expectation(description: "image download should succeed") let requestReceipt2 = downloader.download(urlRequest2) { _ in expectation2.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(requestReceipt1, "request receipt 1 should not be nil") XCTAssertNotNil(requestReceipt2, "request receipt 2 should not be nil") } func testThatItCanDownloadImagesWhenNoImageCacheIsAvailable() { // Given let downloader = ImageDownloader(imageCache: nil) let urlRequest = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let expectation = self.expectation(description: "image download should succeed") var response: DataResponse<Image>? // When downloader.download(urlRequest) { closureResponse in response = closureResponse expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request, "request should not be nil") XCTAssertNotNil(response?.response, "response should not be nil") XCTAssertTrue(response?.result.isSuccess ?? false, "result should be a success case") } func testThatItAutomaticallyCachesDownloadedImageIfCacheIsAvailable() { // Given let downloader = ImageDownloader() let urlRequest = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let expectation1 = expectation(description: "image download should succeed") var result1: Result<Image>? var result2: Result<Image>? // When let requestReceipt1 = downloader.download(urlRequest) { closureResponse in result1 = closureResponse.result expectation1.fulfill() } waitForExpectations(timeout: timeout, handler: nil) let expectation2 = expectation(description: "image download should succeed") let requestReceipt2 = downloader.download(urlRequest) { closureResponse in result2 = closureResponse.result expectation2.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(requestReceipt1, "request receipt 1 should not be nil") XCTAssertNil(requestReceipt2, "request receipt 2 should be nil") XCTAssertNotNil(result1, "result 1 should not be nil") XCTAssertNotNil(result2, "result 2 should not be nil") XCTAssertTrue(result1?.isSuccess ?? false, "result 1 should be a success case") XCTAssertTrue(result2?.isSuccess ?? false, "result 2 should be a success case") if let image1 = result1?.value, let image2 = result2?.value { XCTAssertEqual(image1, image2, "images 1 and 2 should be equal") } } #if os(iOS) || os(tvOS) func testThatFilteredImageIsStoredInCacheIfCacheIsAvailable() { // Given let downloader = ImageDownloader() let urlRequest = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let size = CGSize(width: 20, height: 20) let filter = ScaledToSizeFilter(size: size) let expectation1 = expectation(description: "image download should succeed") var result1: Result<Image>? var result2: Result<Image>? // When let requestReceipt1 = downloader.download(urlRequest, filter: filter) { closureResponse in result1 = closureResponse.result expectation1.fulfill() } waitForExpectations(timeout: timeout, handler: nil) let expectation2 = expectation(description: "image download should succeed") let requestReceipt2 = downloader.download(urlRequest, filter: filter) { closureResponse in result2 = closureResponse.result expectation2.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(requestReceipt1, "request receipt 1 should not be nil") XCTAssertNil(requestReceipt2, "request receipt 2 should be nil") XCTAssertNotNil(result1, "result 1 should not be nil") XCTAssertNotNil(result2, "result 2 should not be nil") XCTAssertTrue(result1?.isSuccess ?? false, "result 1 should be a success case") XCTAssertTrue(result2?.isSuccess ?? false, "result 2 should be a success case") if let image1 = result1?.value, let image2 = result2?.value { XCTAssertEqual(image1, image2, "images 1 and 2 should be equal") XCTAssertEqual(image1.size, size, "image size should match expected size") XCTAssertEqual(image2.size, size, "image size should match expected size") } else { XCTFail("images should not be nil") } } #endif // MARK: - Internal Logic Tests func testThatStartingRequestIncrementsActiveRequestCount() { // Given let downloader = ImageDownloader() let urlRequest = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let request = downloader.sessionManager.request(urlRequest) // When let activeRequestCountBefore = downloader.activeRequestCount downloader.start(request) let activeRequestCountAfter = downloader.activeRequestCount request.cancel() // Then XCTAssertEqual(activeRequestCountBefore, 0, "active request count before should be 0") XCTAssertEqual(activeRequestCountAfter, 1, "active request count after should be 1") } func testThatEnqueueRequestInsertsRequestAtTheBackOfTheQueueWithFIFODownloadPrioritization() { // Given let downloader = ImageDownloader() let urlRequest1 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let urlRequest2 = try! URLRequest(url: "https://httpbin.org/image/png", method: .get) let request1 = downloader.sessionManager.request(urlRequest1) let request2 = downloader.sessionManager.request(urlRequest2) // When downloader.enqueue(request1) downloader.enqueue(request2) let queuedRequests = downloader.queuedRequests // Then XCTAssertEqual(queuedRequests.count, 2, "queued requests count should be 1") XCTAssertEqual(queuedRequests[0].task, request1.task, "first queued request should be request 1") XCTAssertEqual(queuedRequests[1].task, request2.task, "second queued request should be request 2") } func testThatEnqueueRequestInsertsRequestAtTheFrontOfTheQueueWithLIFODownloadPrioritization() { // Given let downloader = ImageDownloader(downloadPrioritization: .lifo) let urlRequest1 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let urlRequest2 = try! URLRequest(url: "https://httpbin.org/image/png", method: .get) let request1 = downloader.sessionManager.request(urlRequest1) let request2 = downloader.sessionManager.request(urlRequest2) // When downloader.enqueue(request1) downloader.enqueue(request2) let queuedRequests = downloader.queuedRequests // Then XCTAssertEqual(queuedRequests.count, 2, "queued requests count should be 1") XCTAssertEqual(queuedRequests[0].task, request2.task, "first queued request should be request 2") XCTAssertEqual(queuedRequests[1].task, request1.task, "second queued request should be request 1") } func testThatDequeueRequestAlwaysRemovesRequestFromTheFrontOfTheQueue() { // Given let downloader = ImageDownloader(downloadPrioritization: .fifo) let urlRequest1 = try! URLRequest(url: "https://httpbin.org/image/jpeg", method: .get) let urlRequest2 = try! URLRequest(url: "https://httpbin.org/image/png", method: .get) let request1 = downloader.sessionManager.request(urlRequest1) let request2 = downloader.sessionManager.request(urlRequest2) // When downloader.enqueue(request1) downloader.enqueue(request2) downloader.dequeue() let queuedRequests = downloader.queuedRequests // Then XCTAssertEqual(queuedRequests.count, 1, "queued requests count should be 1") XCTAssertEqual(queuedRequests[0].task, request2.task, "queued request should be request 2") } }
mit
48c6bd176987a559803396451f7dc29b
35.811565
120
0.654434
4.997564
false
false
false
false
devxoul/Drrrible
Drrrible/Sources/Models/Comment.swift
1
479
// // Comment.swift // Drrrible // // Created by Suyeol Jeon on 21/03/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import Foundation struct Comment: ModelType { enum Event { } var id: Int var body: String var createdAt: Date var likeCount: Int var user: User enum CodingKeys: String, CodingKey { case id = "id" case body = "body" case createdAt = "created_at" case likeCount = "likes_count" case user = "user" } }
mit
de600db84231061f086e7f9cded2ff7e
16.071429
54
0.638075
3.489051
false
false
false
false
Alexiuce/Tip-for-day
iFeiBo/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift
8
14753
// // ImageView+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif // MARK: - Extension methods. /** * Set image to use from web. */ extension Kingfisher where Base: ImageView { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. If `resource` is `nil`, the `placeholder` image will be set and `completionHandler` will be called with both `error` and `image` being `nil`. */ @discardableResult public func setImage(with resource: Resource?, placeholder: Placeholder? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { guard let resource = resource else { self.placeholder = placeholder setWebURL(nil) completionHandler?(nil, nil, .none, nil) return .empty } var options = KingfisherManager.shared.defaultOptions + (options ?? KingfisherEmptyOptionsInfo) let noImageOrPlaceholderSet = base.image == nil && self.placeholder == nil if !options.keepCurrentImageWhileLoading || noImageOrPlaceholderSet { // Always set placeholder while there is no image/placehoer yet. self.placeholder = placeholder } let maybeIndicator = indicator maybeIndicator?.startAnimatingView() setWebURL(resource.downloadURL) if base.shouldPreloadAllAnimation() { options.append(.preloadAllAnimationData) } let task = KingfisherManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in guard resource.downloadURL == self.webURL else { return } if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: {[weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { maybeIndicator?.stopAnimatingView() guard let strongBase = base, imageURL == self.webURL else { completionHandler?(image, error, cacheType, imageURL) return } self.setImageTask(nil) guard let image = image else { completionHandler?(nil, error, cacheType, imageURL) return } guard let transitionItem = options.lastMatchIgnoringAssociatedValue(.transition(.none)), case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else { self.placeholder = nil strongBase.image = image completionHandler?(image, error, cacheType, imageURL) return } #if !os(macOS) UIView.transition(with: strongBase, duration: 0.0, options: [], animations: { maybeIndicator?.stopAnimatingView() }, completion: { _ in self.placeholder = nil UIView.transition(with: strongBase, duration: transition.duration, options: [transition.animationOptions, .allowUserInteraction], animations: { // Set image property in the animation. transition.animations?(strongBase, image) }, completion: { finished in transition.completion?(finished) completionHandler?(image, error, cacheType, imageURL) }) }) #endif } }) setImageTask(task) return task } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func cancelDownloadTask() { imageTask?.cancel() } } // MARK: - Associated Object private var lastURLKey: Void? private var indicatorKey: Void? private var indicatorTypeKey: Void? private var placeholderKey: Void? private var imageTaskKey: Void? extension Kingfisher where Base: ImageView { /// Get the image URL binded to this image view. public var webURL: URL? { return objc_getAssociatedObject(base, &lastURLKey) as? URL } fileprivate func setWebURL(_ url: URL?) { objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } /// Holds which indicator type is going to be used. /// Default is .none, means no indicator will be shown. public var indicatorType: IndicatorType { get { let indicator = (objc_getAssociatedObject(base, &indicatorTypeKey) as? Box<IndicatorType?>)?.value return indicator ?? .none } set { switch newValue { case .none: indicator = nil case .activity: indicator = ActivityIndicator() case .image(let data): indicator = ImageIndicator(imageData: data) case .custom(let anIndicator): indicator = anIndicator } objc_setAssociatedObject(base, &indicatorTypeKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Holds any type that conforms to the protocol `Indicator`. /// The protocol `Indicator` has a `view` property that will be shown when loading an image. /// It will be `nil` if `indicatorType` is `.none`. public fileprivate(set) var indicator: Indicator? { get { return (objc_getAssociatedObject(base, &indicatorKey) as? Box<Indicator?>)?.value } set { // Remove previous if let previousIndicator = indicator { previousIndicator.view.removeFromSuperview() } // Add new if var newIndicator = newValue { // Set default indicator frame if the view's frame not set. if newIndicator.view.frame != .zero { newIndicator.view.frame = base.frame } newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY) newIndicator.view.isHidden = true base.addSubview(newIndicator.view) } // Save in associated object objc_setAssociatedObject(base, &indicatorKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate var imageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask } fileprivate func setImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } public fileprivate(set) var placeholder: Placeholder? { get { return (objc_getAssociatedObject(base, &placeholderKey) as? Box<Placeholder?>)?.value } set { if let previousPlaceholder = placeholder { previousPlaceholder.remove(from: base) } if let newPlaceholder = newValue { newPlaceholder.add(to: base) } else { base.image = nil } objc_setAssociatedObject(base, &placeholderKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } // MARK: - Deprecated. Only for back compatibility. /** * Set image to use from web. Deprecated. Use `kf` namespacing instead. */ extension ImageView { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.setImage` instead.", renamed: "kf.setImage") @discardableResult public func kf_setImage(with resource: Resource?, placeholder: Placeholder? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.cancelDownloadTask` instead.", renamed: "kf.cancelDownloadTask") public func kf_cancelDownloadTask() { kf.cancelDownloadTask() } /// Get the image URL binded to this image view. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.webURL` instead.", renamed: "kf.webURL") public var kf_webURL: URL? { return kf.webURL } /// Holds which indicator type is going to be used. /// Default is .none, means no indicator will be shown. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicatorType` instead.", renamed: "kf.indicatorType") public var kf_indicatorType: IndicatorType { get { return kf.indicatorType } set { kf.indicatorType = newValue } } @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicator` instead.", renamed: "kf.indicator") /// Holds any type that conforms to the protocol `Indicator`. /// The protocol `Indicator` has a `view` property that will be shown when loading an image. /// It will be `nil` if `kf_indicatorType` is `.none`. public private(set) var kf_indicator: Indicator? { get { return kf.indicator } set { kf.indicator = newValue } } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.imageTask") fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setImageTask") fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setWebURL") fileprivate func kf_setWebURL(_ url: URL) { kf.setWebURL(url) } func shouldPreloadAllAnimation() -> Bool { return true } @available(*, deprecated, renamed: "shouldPreloadAllAnimation") func shouldPreloadAllGIF() -> Bool { return true } }
mit
c68a049bf017b8bd9c4de53e402d6779
44.393846
173
0.598861
5.584027
false
false
false
false
LiulietLee/Pick-Color
Pick Color/MKActivityIndicator.swift
1
4540
// // MKProgressView.swift // Cityflo // // Created by Rahul Iyer on 03/11/15. // Copyright © 2015 Cityflo. All rights reserved. // import UIKit @IBDesignable open class MKActivityIndicator: UIView { fileprivate let drawableLayer = CAShapeLayer() fileprivate var animating = false @IBInspectable open var color: UIColor = UIColor.MKColor.Blue.P500 { didSet { drawableLayer.strokeColor = self.color.cgColor } } @IBInspectable open var lineWidth: CGFloat = 6 { didSet { drawableLayer.lineWidth = self.lineWidth self.updatePath() } } public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } open override var bounds: CGRect { didSet { updateFrame() updatePath() } } open override func layoutSubviews() { super.layoutSubviews() updateFrame() updatePath() } open func startAnimating() { if self.animating { return } self.animating = true self.isHidden = false self.resetAnimations() } open func stopAnimating() { self.drawableLayer.removeAllAnimations() self.animating = false self.isHidden = true } fileprivate func setup() { self.isHidden = true self.layer.addSublayer(self.drawableLayer) self.drawableLayer.strokeColor = self.color.cgColor self.drawableLayer.lineWidth = self.lineWidth self.drawableLayer.fillColor = UIColor.clear.cgColor self.drawableLayer.lineCap = kCALineJoinRound self.drawableLayer.strokeStart = 0.99 self.drawableLayer.strokeEnd = 1 updateFrame() updatePath() } fileprivate func updateFrame() { self.drawableLayer.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height) } fileprivate func updatePath() { let center = CGPoint(x: self.bounds.midX, y: self.bounds.midY) let radius = min(self.bounds.width, self.bounds.height) / 2 - self.lineWidth self.drawableLayer.path = UIBezierPath( arcCenter: center, radius: radius, startAngle: 0, endAngle: CGFloat(2 * Double.pi), clockwise: true) .cgPath } fileprivate func resetAnimations() { drawableLayer.removeAllAnimations() let rotationAnim = CABasicAnimation(keyPath: "transform.rotation") rotationAnim.fromValue = 0 rotationAnim.duration = 4 rotationAnim.toValue = 2 * Double.pi rotationAnim.repeatCount = Float.infinity rotationAnim.isRemovedOnCompletion = false let startHeadAnim = CABasicAnimation(keyPath: "strokeStart") startHeadAnim.beginTime = 0.1 startHeadAnim.fromValue = 0 startHeadAnim.toValue = 0.25 startHeadAnim.duration = 1 startHeadAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let startTailAnim = CABasicAnimation(keyPath: "strokeEnd") startTailAnim.beginTime = 0.1 startTailAnim.fromValue = 0 startTailAnim.toValue = 1 startTailAnim.duration = 1 startTailAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let endHeadAnim = CABasicAnimation(keyPath: "strokeStart") endHeadAnim.beginTime = 1 endHeadAnim.fromValue = 0.25 endHeadAnim.toValue = 0.99 endHeadAnim.duration = 0.5 endHeadAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let endTailAnim = CABasicAnimation(keyPath: "strokeEnd") endTailAnim.beginTime = 1 endTailAnim.fromValue = 1 endTailAnim.toValue = 1 endTailAnim.duration = 0.5 endTailAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let strokeAnimGroup = CAAnimationGroup() strokeAnimGroup.duration = 1.5 strokeAnimGroup.animations = [startHeadAnim, startTailAnim, endHeadAnim, endTailAnim] strokeAnimGroup.repeatCount = Float.infinity strokeAnimGroup.isRemovedOnCompletion = false self.drawableLayer.add(rotationAnim, forKey: "rotation") self.drawableLayer.add(strokeAnimGroup, forKey: "stroke") } }
mit
7bafcf566bc2333b6edf86eb338c5b17
30.303448
107
0.649703
4.891164
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Seller/views/SLVUserProductCell.swift
1
6111
// // SLVUserProductCell.swift // selluv-ios // // Created by 조백근 on 2017. 1. 31.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import Foundation import UIKit class SLVUserProductCell: UICollectionViewCell, NTTansitionWaterfallGridViewProtocol { static let infoHeight:CGFloat = 95.0 static let humanHeight:CGFloat = 45.0 var imageName : String? var info: SLVDetailProduct? var isMainTab: Bool = false weak var delegate: SLVCollectionLinesDelegate? @IBOutlet weak var imageViewContent: UIImageView? { didSet { } } @IBOutlet weak var styleButton: UIButton? @IBOutlet weak var likeButton: UIButton? @IBOutlet weak var contentsInfoView: UIView? @IBOutlet weak var contentName: UILabel? @IBOutlet weak var contentInfo: UILabel? @IBOutlet weak var contentPirce: UILabel? @IBOutlet weak var contentFeature: UILabel? @IBOutlet weak var personInfoView: UIView? @IBOutlet weak var personName: UILabel? @IBOutlet weak var updateTime: UILabel? @IBOutlet weak var thumbnail: UIImageView? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear setup() } override func layoutSubviews() { super.layoutSubviews() let w = frame.size.width let h = frame.size.height - SLVUserProductCell.infoHeight - SLVUserProductCell.humanHeight self.imageViewContent!.frame = CGRect(x: 0, y: 0, width: w, height: h) // self.imageViewContent!.image = UIImage(named: imageName!) var imgName = "" var host = dnProduct if self.info?.photos != nil { if (self.info?.photos?.count)! > 0 { imgName = (self.info?.photos?.first)! } } if self.isMainTab == true { if SelluvHomeTabModel.shared.isOnlyStyles == true { imgName = (self.info?.styles?.first)! host = dnStyle } } if imgName != "" { let dnModel = SLVDnImageModel.shared dnModel.setupProcessingImageView(view: (self.imageViewContent)!, from: URL(string: "\(host)\(imgName)")!, size: CGSize(width:w, height: h)) } } func snapShotForTransition() -> UIView! { let snapShotView = UIImageView(image: self.imageViewContent!.image) snapShotView.frame = self.imageViewContent!.frame return snapShotView } override func awakeFromNib() { super.awakeFromNib() setup() } func setup() { } func updateHiddenStyle() { //스타일 var isStyleHidden = true if self.info?.styles != nil { if (self.info?.styles!.count)! > 0 { isStyleHidden = false } } if self.isMainTab == true { if SelluvHomeTabModel.shared.isOnlyStyles == true { isStyleHidden = true } } self.styleButton?.isHidden = isStyleHidden } func setupData(item: SLVDetailProduct) { self.info = item // var imgName = "" // if (self.info?.photos?.count)! > 0 { // imgName = (self.info?.photos?.first)! // } // // if imgName != "" { // let dnModel = SLVDnImageModel.shared // dnModel.setupImageView(view: (self.imageViewContent)!, from: URL(string: "\(dnProduct)\(imgName)")!) // } self.isMainTab = false //좋아요. let likes = self.info?.likesCount ?? 0 self.likeButton?.setTitle("\(likes)", for: .normal) self.updateHiddenStyle() let en = self.info?.brand?.english ?? "" let ko = self.info?.brand?.korean ?? "" let color = self.info?.color ?? "" let model = self.info?.model ?? "" let cate3 = self.info?.category3?.name ?? "" let cate4 = self.info?.category4?.name ?? "" let price = self.info?.price?.original ?? 0 let comma = String.decimalAmountWithForm(value: price, pointCount: 0) //상품정보 self.contentName?.text = en self.contentInfo?.text = "\(ko) \(color) \(model) \(cate3) \(cate4)" self.contentPirce?.text = "₩ \(comma)" if (self.info?.size?.count)! > 0 { let index = self.info?.sizeIndex ?? 0 if (info?.size?.count)! >= index + 1 { let value = self.info?.size?[index] self.contentFeature?.text = value } } //판매자 정보 let user = self.info?.userInfo if let user = user { let name = user.nickname ?? "" let thumb = user.avatar ?? "" self.personName?.text = name if thumb != "" { let dnModel = SLVDnImageModel.shared dnModel.setupImageView(view: (self.thumbnail)!, from: URL(string: "\(dnAvatar)\(thumb)")!) } } var time = self.info?.createdAt if self.info?.updatedAt != nil { time = self.info?.updatedAt } let ago = Date.timeAgoSince(time!) self.updateTime?.text = ago self.setNeedsLayout() } @IBAction func touchStyleThumnail(sender: AnyObject) { delegate?.didTouchedStyleThumbnail(info: [ "item": self.info, "image": self.imageViewContent?.image] as AnyObject) } @IBAction func touchLikeSymbol(sender: AnyObject) { delegate?.didTouchedLikeButton(info: [:] as AnyObject) } @IBAction func touchItemLines(sender: AnyObject) { delegate?.didTouchedItemDescription(info: [:] as AnyObject) } @IBAction func touchUserLines(sender: AnyObject) { delegate?.didTouchedUserDescription(info: [:] as AnyObject) } }
mit
d9f6c98f0f1f64dd936d8ab57774a215
29.502513
151
0.560132
4.469809
false
false
false
false
rocketmade/rockauth-ios
RockauthiOS/Providers/InstagramProvider.swift
1
6333
// // InstagramProvider.swift // Pods // // Created by Daniel Gubler on 10/29/15. // // import UIKit public class InstagramProvider :SocialProvider, IGViewControllerDelegate { public static var sharedProvider: SocialProvider? public var name: String = "instagram" public var secret :String? public var token :String? public var iconName: String? = "instagramIcon" public var userName: String? = nil public var email: String? = nil public var firstName: String? = nil public var lastName: String? = nil public var color = UIColor(colorLiteralRed: 117/255.0, green: 111/255.0, blue: 103/255.0, alpha: 1.0) var igAppId :String? var igRedirectUri :String? var successBlock: loginSuccess? var failureBlock: loginFailure? private var webViewController = IGViewController() public init(instagramAppId :String, registeredRedirectUri :String) { igAppId = instagramAppId igRedirectUri = registeredRedirectUri } public func login(fromViewController viewController: UIViewController, success: loginSuccess, failure: loginFailure) { self.successBlock = success self.failureBlock = failure webViewController = IGViewController(delegate: self, callbackUrl: self.igRedirectUri) if let navController = viewController.navigationController { navController.pushViewController(webViewController, animated: true) } else { viewController.presentViewController(webViewController, animated: true, completion: nil) } let urlStr = "https://api.instagram.com/oauth/authorize/?client_id=\(igAppId!)&redirect_uri=\(igRedirectUri!.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!)&response_type=token&scope=basic" let authUrl = NSURL(string: urlStr)! webViewController.webView.loadRequest(NSURLRequest(URL: authUrl)) } public func logout() { //Instagram has a different sign in model so we have to delete the cached response from the webview. if let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies { for c in cookies where c.domain == ".instagram.com"{ NSHTTPCookieStorage.sharedHTTPCookieStorage().deleteCookie(c) } } } // MARK: helper methods // MARK: IGViewControllerDelegate methods func success(token: String) { NSLog("token:\(token)") self.token = token if let sharedClient = RockauthClient.sharedClient { sharedClient.login(self, success: { (user) -> Void in if let successBlock = self.successBlock { successBlock(session: user) } }, failure: { (error) -> Void in if let failureBlock = self.failureBlock { failureBlock(error: error) } }) } } func failure(error: String) { webViewController.dismissViewControllerAnimated(true, completion: nil) if let failureBlock = self.failureBlock { failureBlock(error: RockauthError(title: "Twitter Authentication Error", message: error)) } } } // MARK: IGViewController class IGViewController :UIViewController, UIWebViewDelegate { let webView = UIWebView() var callbackUrl :String? var delegate :IGViewControllerDelegate? required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init() { super.init(nibName: nil, bundle: nil) setup() } init(delegate :IGViewControllerDelegate, callbackUrl :String?) { super.init(nibName: nil, bundle: nil) self.delegate = delegate self.callbackUrl = callbackUrl setup() } override func viewDidLoad() { applyConstraints() } override func loadView() { super.loadView() self.view = UIView() self.view.backgroundColor = UIColor.whiteColor() // webView.backgroundColor = UIColor.whiteColor() self.view.addSubview(webView) applyConstraints() } func setup() { webView.translatesAutoresizingMaskIntoConstraints = false webView.delegate = self } func applyConstraints() { if let _ = self.navigationController { view.addConstraint(NSLayoutConstraint(item: webView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 0)) } else { view.addConstraint(NSLayoutConstraint(item: webView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 20)) } view.addConstraint(NSLayoutConstraint(item: webView, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: webView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: webView, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1, constant: 0)) } // MARK: webView delegate methods func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { let url = request.URL!.absoluteString if url.startsWith(callbackUrl!) { let token = extractToken(url) delegate?.success(token) return false } return true } func extractToken(url :String) -> String { let b = url.split("=") return b[1] } } // MARK: IGViewControllerDelegate protocol protocol IGViewControllerDelegate { func success(token :String) func failure(error :String) } // MARK: String extensions extension String { func startsWith(string :String) -> Bool { return self.rangeOfString("^\(string)", options: NSStringCompareOptions.RegularExpressionSearch, range: nil, locale: nil) != nil } func split(char :Character) -> Array<String> { return self.characters.split(char).map(String.init) } }
mit
ec07e22ff612bb8c478c78ce31780e08
34.58427
233
0.652455
4.909302
false
false
false
false
tkester/swift-algorithm-club
Rabin-Karp/Rabin-Karp.playground/Contents.swift
1
2821
//: Taking our rabin-karp algorithm for a walk // last checked with Xcode 9.0b4 #if swift(>=4.0) print("Hello, Swift 4!") #endif import UIKit struct Constants { static let hashMultiplier = 69069 } precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence } infix operator ** : PowerPrecedence func ** (radix: Int, power: Int) -> Int { return Int(pow(Double(radix), Double(power))) } func ** (radix: Double, power: Int) -> Double { return pow(radix, Double(power)) } extension Character { var asInt: Int { let s = String(self).unicodeScalars return Int(s[s.startIndex].value) } } // Find first position of pattern in the text using Rabin Karp algorithm public func search(text: String, pattern: String) -> Int { // convert to array of ints let patternArray = pattern.characters.flatMap { $0.asInt } let textArray = text.characters.flatMap { $0.asInt } if textArray.count < patternArray.count { return -1 } let patternHash = hash(array: patternArray) var endIdx = patternArray.count - 1 let firstChars = Array(textArray[0...endIdx]) let firstHash = hash(array: firstChars) if patternHash == firstHash { // Verify this was not a hash collison if firstChars == patternArray { return 0 } } var prevHash = firstHash // Now slide the window across the text to be searched for idx in 1...(textArray.count - patternArray.count) { endIdx = idx + (patternArray.count - 1) let window = Array(textArray[idx...endIdx]) let windowHash = nextHash( prevHash: prevHash, dropped: textArray[idx - 1], added: textArray[endIdx], patternSize: patternArray.count - 1 ) if windowHash == patternHash { if patternArray == window { return idx } } prevHash = windowHash } return -1 } public func hash(array: Array<Int>) -> Double { var total: Double = 0 var exponent = array.count - 1 for i in array { total += Double(i) * (Double(Constants.hashMultiplier) ** exponent) exponent -= 1 } return Double(total) } public func nextHash(prevHash: Double, dropped: Int, added: Int, patternSize: Int) -> Double { let oldHash = prevHash - (Double(dropped) * (Double(Constants.hashMultiplier) ** patternSize)) return Double(Constants.hashMultiplier) * oldHash + Double(added) } // TESTS assert(search(text:"The big dog jumped over the fox", pattern:"ump") == 13, "Invalid index returned") assert(search(text:"The big dog jumped over the fox", pattern:"missed") == -1, "Invalid index returned") assert(search(text:"The big dog jumped over the fox", pattern:"T") == 0, "Invalid index returned")
mit
8b60edb08ef2747a6b863aca5a7cbee4
26.930693
94
0.637717
3.88033
false
false
false
false
yisimeng/YSMFactory-swift
YSMFactory-swift/Vendor/YSMCustomFlowLayout/YSMCardFlowLayout.swift
1
1059
// // YSMCardFlowLayout.swift // YSMFactory-swift // // Created by 忆思梦 on 2016/12/20. // Copyright © 2016年 忆思梦. All rights reserved. // import UIKit class YSMCardFlowLayout: UICollectionViewFlowLayout { override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let atts = super.layoutAttributesForElements(in: rect) guard (atts?.count) != nil else { return atts } for att in atts! { recomputeAttributesFrame(att) } return atts } func recomputeAttributesFrame(_ attributes:UICollectionViewLayoutAttributes) { let minY:CGFloat = collectionView!.bounds.minY+collectionView!.contentInset.top+sectionInset.top let finalY = max(minY, attributes.frame.origin.y) attributes.frame.origin.y = finalY attributes.zIndex = attributes.indexPath.row } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } }
mit
8f23c7e6d568cff666eb50f9879ce228
28
104
0.664751
4.578947
false
false
false
false
CatchChat/Yep
Yep/Extensions/UIImageView+Yep.swift
1
7593
// // UIImageView+Yep.swift // Yep // // Created by nixzhu on 15/12/3. // Copyright © 2015年 Catch Inc. All rights reserved. // import UIKit import CoreLocation import YepKit // MARK: - ActivityIndicator private var activityIndicatorAssociatedKey: Void? private var showActivityIndicatorWhenLoadingAssociatedKey: Void? extension UIImageView { private var yep_activityIndicator: UIActivityIndicatorView? { return objc_getAssociatedObject(self, &activityIndicatorAssociatedKey) as? UIActivityIndicatorView } private func yep_setActivityIndicator(activityIndicator: UIActivityIndicatorView?) { objc_setAssociatedObject(self, &activityIndicatorAssociatedKey, activityIndicator, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } public var yep_showActivityIndicatorWhenLoading: Bool { get { guard let result = objc_getAssociatedObject(self, &showActivityIndicatorWhenLoadingAssociatedKey) as? NSNumber else { return false } return result.boolValue } set { if yep_showActivityIndicatorWhenLoading == newValue { return } else { if newValue { let indicatorStyle = UIActivityIndicatorViewStyle.Gray let indicator = UIActivityIndicatorView(activityIndicatorStyle: indicatorStyle) indicator.center = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds)) indicator.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleBottomMargin, .FlexibleTopMargin] indicator.hidden = true indicator.hidesWhenStopped = true self.addSubview(indicator) yep_setActivityIndicator(indicator) } else { yep_activityIndicator?.removeFromSuperview() yep_setActivityIndicator(nil) } objc_setAssociatedObject(self, &showActivityIndicatorWhenLoadingAssociatedKey, NSNumber(bool: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } } // MARK: - Message Image private var messageImageAssociatedKey: Void? extension UIImageView { private var yep_messageImageKey: String? { return objc_getAssociatedObject(self, &messageImageAssociatedKey) as? String } private func yep_setMessageImageKey(messageImageKey: String) { objc_setAssociatedObject(self, &messageImageAssociatedKey, messageImageKey, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } func yep_setImageOfMessage(message: Message, withSize size: CGSize, tailDirection: MessageImageTailDirection, completion: (loadingProgress: Double, image: UIImage?) -> Void) { let imageKey = message.imageKey yep_setMessageImageKey(imageKey) ImageCache.sharedInstance.imageOfMessage(message, withSize: size, tailDirection: tailDirection, completion: { [weak self] progress, image in guard let strongSelf = self, _imageKey = strongSelf.yep_messageImageKey where _imageKey == imageKey else { return } completion(loadingProgress: progress, image: image) }) } } // MARK: - Message Map Image private var messageMapImageAssociatedKey: Void? extension UIImageView { private var yep_messageMapImageKey: String? { return objc_getAssociatedObject(self, &messageMapImageAssociatedKey) as? String } private func yep_setMessageMapImageKey(messageMapImageKey: String) { objc_setAssociatedObject(self, &messageMapImageAssociatedKey, messageMapImageKey, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } func yep_setMapImageOfMessage(message: Message, withSize size: CGSize, tailDirection: MessageImageTailDirection) { let imageKey = message.mapImageKey yep_setMessageMapImageKey(imageKey) let locationName = message.textContent ImageCache.sharedInstance.mapImageOfMessage(message, withSize: size, tailDirection: tailDirection, bottomShadowEnabled: !locationName.isEmpty) { [weak self] mapImage in guard let strongSelf = self, _imageKey = strongSelf.yep_messageMapImageKey where _imageKey == imageKey else { return } SafeDispatch.async { [weak self] in self?.image = mapImage } } } } // MARK: - AttachmentURL private var attachmentURLAssociatedKey: Void? extension UIImageView { private var yep_attachmentURL: NSURL? { return objc_getAssociatedObject(self, &attachmentURLAssociatedKey) as? NSURL } private func yep_setAttachmentURL(URL: NSURL) { objc_setAssociatedObject(self, &attachmentURLAssociatedKey, URL, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } func yep_setImageOfAttachment(attachment: DiscoveredAttachment, withSize size: CGSize) { guard let attachmentURL = NSURL(string: attachment.URLString) else { return } let showActivityIndicatorWhenLoading = yep_showActivityIndicatorWhenLoading var activityIndicator: UIActivityIndicatorView? = nil if showActivityIndicatorWhenLoading { activityIndicator = yep_activityIndicator activityIndicator?.hidden = false activityIndicator?.startAnimating() } yep_setAttachmentURL(attachmentURL) ImageCache.sharedInstance.imageOfAttachment(attachment, withMinSideLength: size.width, completion: { [weak self] (url, image, cacheType) in guard let strongSelf = self, yep_attachmentURL = strongSelf.yep_attachmentURL where yep_attachmentURL == url else { return } if cacheType != .Memory { UIView.transitionWithView(strongSelf, duration: imageFadeTransitionDuration, options: .TransitionCrossDissolve, animations: { [weak self] in self?.image = image }, completion: nil) } else { strongSelf.image = image } activityIndicator?.stopAnimating() }) } } // MARK: - Location private var locationAssociatedKey: Void? extension UIImageView { private var yep_location: CLLocation? { return objc_getAssociatedObject(self, &locationAssociatedKey) as? CLLocation } private func yep_setLocation(location: CLLocation) { objc_setAssociatedObject(self, &locationAssociatedKey, location, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } func yep_setImageOfLocation(location: CLLocation, withSize size: CGSize) { let showActivityIndicatorWhenLoading = yep_showActivityIndicatorWhenLoading var activityIndicator: UIActivityIndicatorView? = nil if showActivityIndicatorWhenLoading { activityIndicator = yep_activityIndicator activityIndicator?.hidden = false activityIndicator?.startAnimating() } yep_setLocation(location) ImageCache.sharedInstance.mapImageOfLocationCoordinate(location.coordinate, withSize: size, completion: { [weak self] image in guard let strongSelf = self, _location = strongSelf.yep_location where _location == location else { return } UIView.transitionWithView(strongSelf, duration: imageFadeTransitionDuration, options: .TransitionCrossDissolve, animations: { [weak self] in self?.image = image }, completion: nil) activityIndicator?.stopAnimating() }) } }
mit
4fa61da3670f7442459af50e69574346
33.035874
179
0.675889
5.511983
false
false
false
false
hweetty/PE-Swift
Solutions/P57.swift
1
376
// // Project Euler Solutions // Problem 56: Powerful digit sum // Jerry Yu // import Foundation func p57() { var num = BigInt(n: 3, precision:390), den = BigInt(n: 2, precision:390), count = 0 for _ in 2...1000 { let newNum = num + den*2 den += num num = newNum if num.numDigits > den.numDigits { count++ } } print(count) // Ans: 153 // 2013 Air 0.88s }
gpl-2.0
5b1f0ad951b186b7ee76e52cd04b8172
16.904762
84
0.611702
2.764706
false
false
false
false
RobertGummesson/BuildTimeAnalyzer-for-Xcode
BuildTimeAnalyzer/DirectoryMonitor.swift
1
2480
// // DirectoryMonitor.swift // BuildTimeAnalyzer // import Foundation protocol DirectoryMonitorDelegate: class { func directoryMonitorDidObserveChange(_ directoryMonitor: DirectoryMonitor, isDerivedData: Bool) } class DirectoryMonitor { var dispatchQueue: DispatchQueue weak var delegate: DirectoryMonitorDelegate? var fileDescriptor: Int32 = -1 var dispatchSource: DispatchSourceFileSystemObject? var isDerivedData: Bool var path: String? var timer: Timer? var lastDerivedDataDate = Date() var isMonitoringDates = false init(isDerivedData: Bool) { self.isDerivedData = isDerivedData let suffix = isDerivedData ? "deriveddata" : "logfolder" dispatchQueue = DispatchQueue(label: "uk.co.canemedia.directorymonitor.\(suffix)", attributes: .concurrent) } func startMonitoring(path: String) { self.path = path guard dispatchSource == nil && fileDescriptor == -1 else { return } fileDescriptor = open(path, O_EVTONLY) guard fileDescriptor != -1 else { return } dispatchSource = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fileDescriptor, eventMask: .all, queue: dispatchQueue) dispatchSource?.setEventHandler { DispatchQueue.main.async { self.delegate?.directoryMonitorDidObserveChange(self, isDerivedData: self.isDerivedData) } } dispatchSource?.setCancelHandler { close(self.fileDescriptor) self.fileDescriptor = -1 self.dispatchSource = nil self.path = nil } dispatchSource?.resume() if isDerivedData && !isMonitoringDates { isMonitoringDates = true monitorModificationDates() } } func stopMonitoring() { dispatchSource?.cancel() path = nil } func monitorModificationDates() { if let date = DerivedDataManager.derivedData().first?.date, date > lastDerivedDataDate { lastDerivedDataDate = date self.delegate?.directoryMonitorDidObserveChange(self, isDerivedData: self.isDerivedData) } if path != nil { DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.monitorModificationDates() } } else { isMonitoringDates = false } } }
mit
5633b9f215adf7c68409bb4209b60e61
30
137
0.62379
5.030426
false
false
false
false
debugsquad/nubecero
nubecero/View/Main/VSpinner.swift
1
1259
import UIKit class VSpinner:UIImageView { private let kAnimationDuration:TimeInterval = 2 init() { super.init(frame:CGRect.zero) let images:[UIImage] = [ #imageLiteral(resourceName: "assetLoader0"), #imageLiteral(resourceName: "assetLoader1"), #imageLiteral(resourceName: "assetLoader2"), #imageLiteral(resourceName: "assetLoader3"), #imageLiteral(resourceName: "assetLoader4"), #imageLiteral(resourceName: "assetLoader5"), #imageLiteral(resourceName: "assetLoader5"), #imageLiteral(resourceName: "assetLoader6"), #imageLiteral(resourceName: "assetLoader7"), #imageLiteral(resourceName: "assetLoader8"), #imageLiteral(resourceName: "assetLoader9"), #imageLiteral(resourceName: "assetLoader0") ] isUserInteractionEnabled = false translatesAutoresizingMaskIntoConstraints = false clipsToBounds = true animationDuration = kAnimationDuration animationImages = images contentMode = UIViewContentMode.center startAnimating() } required init?(coder:NSCoder) { fatalError() } }
mit
22753c535f751eef2ad7a6dfb962a6fe
31.282051
57
0.621128
5.570796
false
false
false
false
dilizarov/realm-cocoa
RealmSwift-swift2.0/List.swift
31
15534
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private /// :nodoc: /// Internal class. Do not use directly. public class ListBase: RLMListBase { // Printable requires a description property defined in Swift (and not obj-c), // and it has to be defined as @objc override, which can't be done in a // generic class. /// Returns a human-readable description of the objects contained in the list. @objc public override var description: String { return descriptionWithMaxDepth(RLMDescriptionMaxDepth) } @objc private func descriptionWithMaxDepth(depth: UInt) -> String { let type = "List<\(_rlmArray.objectClassName)>" return gsub("RLMArray <0x[a-z0-9]+>", template: type, string: _rlmArray.descriptionWithMaxDepth(depth)) ?? type } /// Returns the number of objects in this list. public var count: Int { return Int(_rlmArray.count) } } /** `List<T>` is the container type in Realm used to define to-many relationships. Lists hold a single `Object` subclass (`T`) which defines the "type" of the list. Lists can be filtered and sorted with the same predicates as `Results<T>`. When added as a property on `Object` models, the property must be declared as `let` and cannot be `dynamic`. */ public final class List<T: Object>: ListBase { /// Element type contained in this collection. public typealias Element = T // MARK: Properties /// The Realm the objects in this list belong to, or `nil` if the list's /// owning object does not belong to a realm (the list is standalone). public var realm: Realm? { return _rlmArray.realm.map { Realm($0) } } /// Indicates if the list can no longer be accessed. public var invalidated: Bool { return _rlmArray.invalidated } // MARK: Initializers /// Creates a `List` that holds objects of type `T`. public override init() { // FIXME: use T.className() super.init(array: RLMArray(objectClassName: (T.self as Object.Type).className())) } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the list. - parameter object: The object whose index is being queried. - returns: The index of the given object, or `nil` if the object is not in the list. */ public func indexOf(object: T) -> Int? { return notFoundToNil(_rlmArray.indexOfObject(unsafeBitCast(object, RLMObject.self))) } /** Returns the index of the first object matching the given predicate, or `nil` no objects match. - parameter predicate: The `NSPredicate` used to filter the objects. - returns: The index of the given object, or `nil` if no objects match. */ public func indexOf(predicate: NSPredicate) -> Int? { return notFoundToNil(_rlmArray.indexOfObjectWithPredicate(predicate)) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: The predicate format string, optionally followed by a variable number of arguments. - returns: The index of the given object, or `nil` if no objects match. */ public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { return indexOf(NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Object Retrieval /** Returns the object at the given `index` on get. Replaces the object at the given `index` on set. - warning: You can only set an object during a write transaction. - parameter index: The index. - returns: The object at the given `index`. */ public subscript(index: Int) -> T { get { throwForNegativeIndex(index) return _rlmArray[UInt(index)] as! T } set { throwForNegativeIndex(index) return _rlmArray[UInt(index)] = unsafeBitCast(newValue, RLMObject.self) } } /// Returns the first object in the list, or `nil` if empty. public var first: T? { return _rlmArray.firstObject() as! T? } /// Returns the last object in the list, or `nil` if empty. public var last: T? { return _rlmArray.lastObject() as! T? } // MARK: KVC /** Returns an Array containing the results of invoking `valueForKey:` using key on each of the collection's objects. - parameter key: The name of the property. - returns: Array containing the results of invoking `valueForKey:` using key on each of the collection's objects. */ public override func valueForKey(key: String) -> AnyObject? { return _rlmArray.valueForKey(key) } /** Invokes `setValue:forKey:` on each of the collection's objects using the specified value and key. - warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property. */ public override func setValue(value: AnyObject?, forKey key: String) { return _rlmArray.setValue(value, forKey: key) } // MARK: Filtering /** Returns `Results` containing list elements that match the given predicate. - parameter predicateFormat: The predicate format string which can accept variable arguments. - returns: `Results` containing list elements that match the given predicate. */ public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<T> { return Results<T>(_rlmArray.objectsWithPredicate(NSPredicate(format: predicateFormat, argumentArray: args))) } /** Returns `Results` containing list elements that match the given predicate. - parameter predicate: The predicate to filter the objects. - returns: `Results` containing list elements that match the given predicate. */ public func filter(predicate: NSPredicate) -> Results<T> { return Results<T>(_rlmArray.objectsWithPredicate(predicate)) } // MARK: Sorting /** Returns `Results` containing list elements sorted by the given property. - parameter property: The property name to sort by. - parameter ascending: The direction to sort by. - returns: `Results` containing list elements sorted by the given property. */ public func sorted(property: String, ascending: Bool = true) -> Results<T> { return sorted([SortDescriptor(property: property, ascending: ascending)]) } /** Returns `Results` with elements sorted by the given sort descriptors. - parameter sortDescriptors: `SortDescriptor`s to sort by. - returns: `Results` with elements sorted by the given sort descriptors. */ public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<T> { return Results<T>(_rlmArray.sortedResultsUsingDescriptors(sortDescriptors.map { $0.rlmSortDescriptorValue })) } // MARK: Aggregate Operations /** Returns the minimum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on. - returns: The minimum value for the property amongst objects in the List, or `nil` if the List is empty. */ public func min<U: MinMaxType>(property: String) -> U? { return filter(NSPredicate(value: true)).min(property) } /** Returns the maximum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on. - returns: The maximum value for the property amongst objects in the List, or `nil` if the List is empty. */ public func max<U: MinMaxType>(property: String) -> U? { return filter(NSPredicate(value: true)).max(property) } /** Returns the sum of the given property for objects in the List. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate sum on. - returns: The sum of the given property over all objects in the List. */ public func sum<U: AddableType>(property: String) -> U { return filter(NSPredicate(value: true)).sum(property) } /** Returns the average of the given property for objects in the List. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate average on. - returns: The average of the given property over all objects in the List, or `nil` if the List is empty. */ public func average<U: AddableType>(property: String) -> U? { return filter(NSPredicate(value: true)).average(property) } // MARK: Mutation /** Appends the given object to the end of the list. If the object is from a different Realm it is copied to the List's Realm. - warning: This method can only be called during a write transaction. - parameter object: An object. */ public func append(object: T) { _rlmArray.addObject(unsafeBitCast(object, RLMObject.self)) } /** Appends the objects in the given sequence to the end of the list. - warning: This method can only be called during a write transaction. - parameter objects: A sequence of objects. */ public func appendContentsOf<S: SequenceType where S.Generator.Element == T>(objects: S) { for obj in objects { _rlmArray.addObject(unsafeBitCast(obj, RLMObject.self)) } } /** Inserts the given object at the given index. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the list. - parameter object: An object. - parameter index: The index at which to insert the object. */ public func insert(object: T, atIndex index: Int) { throwForNegativeIndex(index) _rlmArray.insertObject(unsafeBitCast(object, RLMObject.self), atIndex: UInt(index)) } /** Removes the object at the given index from the list. Does not remove the object from the Realm. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the list. - parameter index: The index at which to remove the object. */ public func removeAtIndex(index: Int) { throwForNegativeIndex(index) _rlmArray.removeObjectAtIndex(UInt(index)) } /** Removes the last object in the list. Does not remove the object from the Realm. - warning: This method can only be called during a write transaction. */ public func removeLast() { _rlmArray.removeLastObject() } /** Removes all objects from the List. Does not remove the objects from the Realm. - warning: This method can only be called during a write transaction. */ public func removeAll() { _rlmArray.removeAllObjects() } /** Replaces an object at the given index with a new object. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the list. - parameter index: The list index of the object to be replaced. - parameter object: An object to replace at the specified index. */ public func replace(index: Int, object: T) { throwForNegativeIndex(index) _rlmArray.replaceObjectAtIndex(UInt(index), withObject: unsafeBitCast(object, RLMObject.self)) } /** Moves the object at the given source index to the given destination index. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the list. - parameter from: The index of the object to be moved. - parameter to: index to which the object at `from` should be moved. */ public func move(from from: Int, to: Int) { throwForNegativeIndex(from) throwForNegativeIndex(to) _rlmArray.moveObjectAtIndex(UInt(from), toIndex: UInt(to)) } /** Exchanges the objects in the list at given indexes. - warning: Throws an exception when either index exceeds the bounds of the list. - warning: This method can only be called during a write transaction. - parameter index1: The index of the object with which to replace the object at index `index2`. - parameter index2: The index of the object with which to replace the object at index `index1`. */ public func swap(index1: Int, _ index2: Int) { throwForNegativeIndex(index1, parameterName: "index1") throwForNegativeIndex(index2, parameterName: "index2") _rlmArray.exchangeObjectAtIndex(UInt(index1), withObjectAtIndex: UInt(index2)) } } extension List: RealmCollectionType, RangeReplaceableCollectionType { // MARK: Sequence Support /// Returns a `GeneratorOf<T>` that yields successive elements in the list. public func generate() -> RLMGenerator<T> { return RLMGenerator(collection: _rlmArray) } // MARK: RangeReplaceableCollection Support /** Replace the given `subRange` of elements with `newElements`. - parameter subRange: The range of elements to be replaced. - parameter newElements: The new elements to be inserted into the list. */ public func replaceRange<C: CollectionType where C.Generator.Element == T>(subRange: Range<Int>, with newElements: C) { for _ in subRange { removeAtIndex(subRange.startIndex) } for x in newElements.reverse() { insert(x, atIndex: subRange.startIndex) } } /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by zero or more applications of successor(). public var endIndex: Int { return count } }
apache-2.0
65036660b8ed49c18cc5eea7953a4aac
35.636792
139
0.674456
4.656475
false
false
false
false
Quick/Quick
Sources/Quick/ExampleGroup.swift
2
3175
import Foundation /** Example groups are logical groupings of examples, defined with the `describe` and `context` functions. Example groups can share setup and teardown code. */ final public class ExampleGroup: NSObject { weak internal var parent: ExampleGroup? internal let hooks = ExampleHooks() internal var phase: HooksPhase = .nothingExecuted private let internalDescription: String private let flags: FilterFlags private let isInternalRootExampleGroup: Bool private var childGroups = [ExampleGroup]() private var childExamples = [Example]() internal init(description: String, flags: FilterFlags, isInternalRootExampleGroup: Bool = false) { self.internalDescription = description self.flags = flags self.isInternalRootExampleGroup = isInternalRootExampleGroup } public override var description: String { return internalDescription } /** Returns a list of examples that belong to this example group, or to any of its descendant example groups. */ #if canImport(Darwin) @objc public var examples: [Example] { return childExamples + childGroups.flatMap { $0.examples } } #else public var examples: [Example] { return childExamples + childGroups.flatMap { $0.examples } } #endif internal var name: String? { guard let parent = parent else { return isInternalRootExampleGroup ? nil : description } guard let name = parent.name else { return description } return "\(name), \(description)" } internal var filterFlags: FilterFlags { var aggregateFlags = flags walkUp { group in for (key, value) in group.flags { aggregateFlags[key] = value } } return aggregateFlags } internal var justBeforeEachStatements: [AroundExampleWithMetadataAsyncClosure] { var closures = Array(hooks.justBeforeEachStatements.reversed()) walkUp { group in closures.append(contentsOf: group.hooks.justBeforeEachStatements.reversed()) } return closures } internal var wrappers: [AroundExampleWithMetadataAsyncClosure] { var closures = Array(hooks.wrappers.reversed()) walkUp { group in closures.append(contentsOf: group.hooks.wrappers.reversed()) } return closures } internal func walkDownExamples(_ callback: (_ example: Example) -> Void) { for example in childExamples { callback(example) } for group in childGroups { group.walkDownExamples(callback) } } internal func appendExampleGroup(_ group: ExampleGroup) { group.parent = self childGroups.append(group) } internal func appendExample(_ example: Example) { example.group = self childExamples.append(example) } private func walkUp(_ callback: (_ group: ExampleGroup) -> Void) { var group = self while let parent = group.parent { callback(parent) group = parent } } }
apache-2.0
2530c7d96bd67ca89c9fc0c82659ce4e
28.95283
102
0.640315
5.071885
false
false
false
false
niunaruto/DeDaoAppSwift
DeDaoSwift/DeDaoSwift/Home/View/DDHomeHotAndGustCell.swift
1
3074
// // DDHomeHotAndGustCell.swift // DeDaoSwift // // Created by niuting on 2017/3/15. // Copyright © 2017年 niuNaruto. All rights reserved. // import UIKit class DDHomeHotAndGustCell: DDBaseTableViewCell { //dataMiningAduioOrBook override func setCellsViewModel(_ model: Any?) { if let modelT = model as? DDHomeSliderModel { guard modelT.list?.count ?? 0 >= 3 && contentsArray.count >= 3 else { return } if let list = modelT.list{ for i in 0...2 { contentsArray[i].titleLabel.text = list[i].m_title let img : UIImageView = contentsArray[i].infoImageView img.kf.setImage(with: URL(string: list[i].m_img)) } } } } lazy var contentsArray = Array<DDHomeHotAndGustView>() override func setUI() { let backView = UIView() let backViewH : CGFloat = 200 contentView.addSubview(backView) backView.snp.makeConstraints({ (make) in make.edges.equalToSuperview() make.height.equalTo(backViewH) }) for i in 0...2 { let itemView = DDHomeHotAndGustView() backView.addSubview(itemView) let itemsW = UIView.screenWidth / CGFloat(3) itemView.frame = CGRect(x: CGFloat(i) * itemsW, y: 0, width: itemsW, height: backViewH) contentsArray.append(itemView) } } } class DDHomeHotAndGustView: UIView { lazy var infoImageView : UIImageView = { let infoImageView = UIImageView() infoImageView.contentMode = .scaleAspectFill infoImageView.clipsToBounds = true return infoImageView }() lazy var titleLabel : UILabel = { let titleLabel = UILabel() titleLabel.textColor = UIColor.init("#666666") titleLabel.numberOfLines = 2 titleLabel.font = UIFont.systemFont(ofSize: 11) return titleLabel }() override init(frame: CGRect) { super.init(frame: frame) setUI() let tap = UITapGestureRecognizer(target: self, action: #selector(clickImageView)) addGestureRecognizer(tap) } func clickImageView() { } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setUI() { addSubview(infoImageView) addSubview(titleLabel) infoImageView.snp.makeConstraints { (make) in make.left.top.equalToSuperview().offset(10) make.height.equalTo(140) make.right.equalToSuperview().offset(-10) } titleLabel.snp.makeConstraints { (make) in make.left.right.equalTo(infoImageView) make.right.equalTo(infoImageView) make.top.equalTo(infoImageView.snp.bottom).offset(8) } } }
mit
c153650d80313f44def7803e19aa618b
27.174312
99
0.560729
4.631976
false
false
false
false
kvvzr/Twinkrun-iOS
Twinkrun/Controllers/PlayerSelectViewController.swift
2
6560
// // PlayerSelectViewController.swift // Twinkrun // // Created by Kawazure on 2014/10/14. // Copyright (c) 2014年 Twinkrun. All rights reserved. // import UIKit import CoreBluetooth class PlayerSelectViewController: UITableViewController, CBCentralManagerDelegate, CBPeripheralManagerDelegate { @IBOutlet weak var readyButton: UIBarButtonItem! var player: TWRPlayer? var others: [TWRPlayer]? var centralManager: CBCentralManager? var peripheralManager: CBPeripheralManager? var option: TWROption? var brightness: CGFloat = 1.0 var onMatch = false override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) centralManager = CBCentralManager(delegate: self, queue: nil) peripheralManager = CBPeripheralManager(delegate: self, queue: nil) if let central = centralManager { central.delegate = self } if let peripheral = peripheralManager { peripheral.delegate = self } onMatch = false readyButton.enabled = false option = TWROption.sharedInstance player = TWRPlayer(playerName: option!.playerName, identifier: nil, colorSeed: arc4random()) others = [] brightness = UIScreen.mainScreen().brightness } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let font = UIFont(name: "HelveticaNeue-Light", size: 22) if let font = font { navigationController!.navigationBar.barTintColor = UIColor.twinkrunGreen() navigationController!.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: font ] navigationController!.navigationBar.tintColor = UIColor.whiteColor() } tableView.delegate = self tableView.dataSource = self tableView.backgroundView = nil tableView.backgroundColor = UIColor.twinkrunBlack() tableView.tableFooterView = UIView(frame: CGRectZero) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if !onMatch { if let central = centralManager { if central.state == CBCentralManagerState.PoweredOn { central.stopScan() } } if let peripheral = peripheralManager { if peripheral.state == CBPeripheralManagerState.PoweredOff { peripheral.stopAdvertising() } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let others = others { return others.count } return 0 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 48 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { readyButton.enabled = false for other in others! { if other.playWith { self.readyButton.enabled = true break } } let cell = tableView.dequeueReusableCellWithIdentifier("playerCell")! as UITableViewCell let other = others![indexPath.row] cell.backgroundColor = UIColor.twinkrunBlack() cell.textLabel!.textColor = UIColor.whiteColor() cell.textLabel!.text = other.name as String cell.accessoryType = other.playWith ? .Checkmark : .None return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let other = others![indexPath.row] other.playWith = !other.playWith tableView.reloadData() } func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) { if let localName = advertisementData["kCBAdvDataLocalName"] as AnyObject? as? String { let findPlayer = TWRPlayer(advertisementDataLocalName: localName, identifier: peripheral.identifier) let other = others!.filter { $0 == findPlayer } if other.isEmpty { others!.append(findPlayer) } else { other.first!.name = findPlayer.name other.first!.colorSeed = findPlayer.colorSeed other.first!.createRoleList() } dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() }) } } func centralManagerDidUpdateState(central: CBCentralManager) { if central.state == CBCentralManagerState.PoweredOn { central.scanForPeripheralsWithServices( [CBUUID(string: option!.advertiseUUID)], options: [CBCentralManagerScanOptionAllowDuplicatesKey: true] ) } } func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) { if peripheral.state == CBPeripheralManagerState.PoweredOn { peripheral.startAdvertising( player!.advertisementData(CBUUID(string: option!.advertiseUUID)) ) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "matchSegue" { let controller = segue.destinationViewController as! MatchViewController controller.player = player controller.others = others controller.central = centralManager controller.peripheral = peripheralManager controller.brightness = brightness controller.hidesBottomBarWhenPushed = true onMatch = true navigationController!.setNavigationBarHidden(true, animated: true) } } }
mit
acdde95cfa8323d222e3ce52ff6dc987
34.84153
157
0.622751
5.824156
false
false
false
false
eyaldar/CameraEngine
CameraEngineExample/CameraEngineExample/ViewController.swift
1
7605
// // ViewController.swift // CameraEngineExample // // Created by Remi Robert on 16/09/16. // Copyright © 2016 Remi Robert. All rights reserved. // import UIKit import CameraEngine enum ModeCapture { case Photo case Video } class ViewController: UIViewController { private var cameraEngine = CameraEngine() private var mode: ModeCapture = .Photo @IBOutlet weak var buttonMode: UIButton! @IBOutlet weak var labelMode: UILabel! @IBOutlet weak var buttonTrigger: UIButton! override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard let layer = self.cameraEngine.previewLayer else { return } layer.frame = self.view.bounds self.view.layer.insertSublayer(layer, at: 0) } @IBAction func setModeCapture(_ sender: AnyObject) { let alertController = UIAlertController(title: "set mode capture", message: nil, preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "Photo", style: .default, handler: { _ in self.labelMode.text = "Photo" self.buttonTrigger.setTitle("take picture", for: .normal) self.mode = .Photo })) alertController.addAction(UIAlertAction(title: "Video", style: .default, handler: { _ in self.labelMode.text = "Video" self.buttonTrigger.setTitle("start recording", for: .normal) self.mode = .Video })) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) } @IBAction func encoderSettingsPresset(_ sender: AnyObject) { let alertController = UIAlertController(title: "Encoder settings", message: nil, preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "Preset640x480", style: .default, handler: { _ in self.cameraEngine.videoEncoderPresset = .Preset640x480 })) alertController.addAction(UIAlertAction(title: "Preset960x540", style: .default, handler: { _ in self.cameraEngine.videoEncoderPresset = .Preset960x540 })) alertController.addAction(UIAlertAction(title: "Preset1280x720", style: .default, handler: { _ in self.cameraEngine.videoEncoderPresset = .Preset1280x720 })) alertController.addAction(UIAlertAction(title: "Preset1920x1080", style: .default, handler: { _ in self.cameraEngine.videoEncoderPresset = .Preset1920x1080 })) alertController.addAction(UIAlertAction(title: "Preset3840x2160", style: .default, handler: { _ in self.cameraEngine.videoEncoderPresset = .Preset3840x2160 })) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) } @IBAction func setZoomCamera(_ sender: AnyObject) { let alertController = UIAlertController(title: "set zoom factor", message: nil, preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "X1", style: .default, handler: { _ in self.cameraEngine.cameraZoomFactor = 1 })) alertController.addAction(UIAlertAction(title: "X2", style: .default, handler: { _ in self.cameraEngine.cameraZoomFactor = 2 })) alertController.addAction(UIAlertAction(title: "X3", style: .default, handler: { _ in self.cameraEngine.cameraZoomFactor = 3 })) alertController.addAction(UIAlertAction(title: "X4", style: .default, handler: { _ in self.cameraEngine.cameraZoomFactor = 4 })) alertController.addAction(UIAlertAction(title: "X5", style: .default, handler: { _ in self.cameraEngine.cameraZoomFactor = 5 })) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) } @IBAction func setFocus(_ sender: AnyObject) { let alertController = UIAlertController(title: "set focus settings", message: nil, preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "Locked", style: .default, handler: { _ in self.cameraEngine.cameraFocus = CameraEngineCameraFocus.locked })) alertController.addAction(UIAlertAction(title: "auto focus", style: .default, handler: { _ in self.cameraEngine.cameraFocus = CameraEngineCameraFocus.autoFocus })) alertController.addAction(UIAlertAction(title: "continious auto focus", style: .default, handler: { _ in self.cameraEngine.cameraFocus = CameraEngineCameraFocus.continuousAutoFocus })) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) } @IBAction func switchCamera(_ sender: AnyObject) { self.cameraEngine.switchCurrentDevice() } @IBAction func takePhoto(_ sender: AnyObject) { switch self.mode { case .Photo: self.cameraEngine.capturePhoto { (image , error) -> (Void) in if let image = image { CameraEngineFileManager.savePhoto(image, blockCompletion: { (success, error) -> (Void) in if success { let alertController = UIAlertController(title: "Success, image saved !", message: nil, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alertController, animated: true, completion: nil) } }) } } case .Video: if !self.cameraEngine.isRecording { if let url = CameraEngineFileManager.temporaryPath("video.mp4") { self.buttonTrigger.setTitle("stop recording", for: .normal) self.cameraEngine.startRecordingVideo(url, blockCompletion: { (url: URL?, error: NSError?) -> (Void) in if let url = url { DispatchQueue.main.async { self.buttonTrigger.setTitle("start recording", for: .normal) CameraEngineFileManager.saveVideo(url, blockCompletion: { (success: Bool, error: Error?) -> (Void) in if success { let alertController = UIAlertController(title: "Success, video saved !", message: nil, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alertController, animated: true, completion: nil) } }) } } }) } } else { self.cameraEngine.stopRecordingVideo() } } } override func viewDidAppear(_ animated: Bool) { self.cameraEngine.rotationCamera = true } override func viewDidLoad() { super.viewDidLoad() self.cameraEngine.startSession() } }
mit
0649fc062b789d350981fe6a08667661
44.807229
151
0.604682
4.953746
false
false
false
false
zybug/firefox-ios
Client/Frontend/Widgets/TabsButton.swift
7
4619
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import SnapKit struct TabsButtonUX { static let TitleColor: UIColor = UIColor.blackColor() static let TitleBackgroundColor: UIColor = UIColor.whiteColor() static let CornerRadius: CGFloat = 2 static let TitleFont: UIFont = UIConstants.DefaultSmallFontBold static let BorderStrokeWidth: CGFloat = 0 static let BorderColor: UIColor = UIColor.clearColor() static let TitleInsets = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12) } class TabsButton: UIControl { lazy var titleLabel: UILabel = { let label = UILabel() label.font = TabsButtonUX.TitleFont label.textColor = TabsButtonUX.TitleColor label.layer.cornerRadius = TabsButtonUX.CornerRadius label.textAlignment = NSTextAlignment.Center label.userInteractionEnabled = false return label }() lazy var insideButton: UIView = { let view = UIView() view.clipsToBounds = false view.userInteractionEnabled = false return view }() private lazy var labelBackground: UIView = { let background = UIView() background.backgroundColor = TabsButtonUX.TitleBackgroundColor background.layer.cornerRadius = TabsButtonUX.CornerRadius background.userInteractionEnabled = false return background }() private lazy var borderView: InnerStrokedView = { let border = InnerStrokedView() border.strokeWidth = TabsButtonUX.BorderStrokeWidth border.color = TabsButtonUX.BorderColor border.cornerRadius = TabsButtonUX.CornerRadius border.userInteractionEnabled = false return border }() private var buttonInsets: UIEdgeInsets = TabsButtonUX.TitleInsets override init(frame: CGRect) { super.init(frame: frame) insideButton.addSubview(labelBackground) insideButton.addSubview(borderView) insideButton.addSubview(titleLabel) addSubview(insideButton) } override func updateConstraints() { super.updateConstraints() labelBackground.snp_remakeConstraints { (make) -> Void in make.edges.equalTo(insideButton) } borderView.snp_remakeConstraints { (make) -> Void in make.edges.equalTo(insideButton) } titleLabel.snp_remakeConstraints { (make) -> Void in make.edges.equalTo(insideButton) } insideButton.snp_remakeConstraints { (make) -> Void in make.edges.equalTo(self).inset(insets) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func clone() -> UIView { let button = TabsButton() button.accessibilityLabel = accessibilityLabel button.titleLabel.text = titleLabel.text // Copy all of the styable properties over to the new TabsButton button.titleLabel.font = titleLabel.font button.titleLabel.textColor = titleLabel.textColor button.titleLabel.layer.cornerRadius = titleLabel.layer.cornerRadius button.labelBackground.backgroundColor = labelBackground.backgroundColor button.labelBackground.layer.cornerRadius = labelBackground.layer.cornerRadius button.borderView.strokeWidth = borderView.strokeWidth button.borderView.color = borderView.color button.borderView.cornerRadius = borderView.cornerRadius return button } } // MARK: UIAppearance extension TabsButton { dynamic var borderColor: UIColor { get { return borderView.color } set { borderView.color = newValue } } dynamic var borderWidth: CGFloat { get { return borderView.strokeWidth } set { borderView.strokeWidth = newValue } } dynamic var textColor: UIColor? { get { return titleLabel.textColor } set { titleLabel.textColor = newValue } } dynamic var titleFont: UIFont? { get { return titleLabel.font } set { titleLabel.font = newValue } } dynamic var titleBackgroundColor: UIColor? { get { return labelBackground.backgroundColor } set { labelBackground.backgroundColor = newValue } } dynamic var insets : UIEdgeInsets { get { return buttonInsets } set { buttonInsets = newValue setNeedsUpdateConstraints() } } }
mpl-2.0
e0dba5bd6113a688d3d83ab7c1c28020
32.478261
86
0.67179
5.37093
false
false
false
false
whiteshadow-gr/HatForIOS
HAT/Objects/External Apps/HATApplicationsSetup.swift
1
1616
// /** * 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/ */ // MARK: Struct public struct HATApplicationsSetup: HATObject { // MARK: - Coding Keys /** The JSON fields used by the hat The Fields are the following: * `iosUrl` in JSON is `iosUrl` * `applicationUrl` in JSON is `url` * `kind` in JSON is `kind` * `preferences` in JSON is `preferences` * `onboarding` in JSON is `onboarding` */ private enum CodingKeys: String, CodingKey { case iosUrl = "iosUrl" case applicationUrl = "url" case kind = "kind" case preferences = "preferences" case onboarding = "onboarding" } // MARK: - Variables /// The url needed to launch the app from another app using the URL Scheme. Like appname://something. Optional public var iosUrl: String? /// The url needed to open in safari, in case of an iOS app this will be the App Store url. Optional public var applicationUrl: String? /// The kind of app this is. External or Internal public var kind: String = "" /// Preferences for the app. Optional public var preferences: String? /// The onboarding screens to show for the particular application. Optional public var onboarding: [HATApplicationsOnboarding]? }
mpl-2.0
02a5fcd0ea73576d7b9233f650920e63
30.686275
114
0.649134
4.186528
false
false
false
false
rene-dohan/CS-IOS
Renetik/Renetik/Classes/TableController/CSTablePagerController+CSJsonData.swift
1
1023
// // Created by Rene Dohan on 1/9/20. // import Foundation import RenetikObjc //public extension CSTablePagerController where Row: CSJsonObject, Data: CSListServerJsonData<Row> { // @discardableResult // public func construct(by controller: CSTableController<Row, Data>, // operation: @escaping (Int) -> CSOperation<Data>) -> Self { // self.table = controller // onLoadPage = { index in operation(index).onSuccess { data in self.load(data.list) } } // table.loadData = onLoad // return self // } //} // //public extension CSTablePagerController where Data: CSListData { // @discardableResult // public func construct(using controller: CSTableController<Row, Data>, // request: @escaping (Int) -> CSOperation<Data>) -> Self { // self.table = controller // onLoadPage = { index in request(index).onSuccess { data in self.load(data.list.cast()) } } // table.loadData = onLoad // return self // } //}
mit
da879b54f65d7bdf9e1d8693bb1f294b
35.571429
100
0.627566
4.011765
false
false
false
false
jonnyleeharris/ento
Ento/entoTests/Tests.swift
1
5249
// // Created by Jonathan Harris on 29/06/2015. // Copyright © 2015 Jonathan Harris. All rights reserved. // import XCTest class Tests: XCTestCase { // Tests need work. // Need separating into separate tests etc. override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testFamilyMatching() { let entity:Entity = Entity(); assert(!Family.all(TestComponentA.self).matches(entity)); assert(!Family.all(TestComponentB.self).matches(entity)); assert(Family.none(TestComponentB.self).matches(entity)); entity.add(TestComponentA()); entity.add(TestComponentB()); assert(Family.all(TestComponentA.self, TestComponentB.self).matches(entity)); assert(!Family.any(TestComponentC.self).matches(entity)); assert(Family.any(TestComponentA.self).matches(entity)); } func testEntityComponents() { let entity:Entity = Entity(); assert(entity.numComponents == 0); entity.add(TestComponentB()); assert(entity.numComponents == 1); assert(entity.has(TestComponentB)); assert(!entity.has(TestComponentA)); entity.add(TestComponentA()); assert(entity.has(TestComponentA)); assert(entity.numComponents == 2); entity.add(TestComponentA()); assert(entity.has(TestComponentA)); assert(entity.numComponents == 2); } func testLotsOfEntities() { // Create engine let engine:Engine = Engine(); // Add systems to engine let system:TestSystem = TestSystem(); engine.addSystem(system, priority: 1); // Create entity with inspectable component let component:TestComponentA = TestComponentA(); assert(component.value == 0); var entity:Entity; let numEntities:Int = 1000; for _ in 1...numEntities { entity = Entity(); entity.add(component); // Add entity to engine try! engine.addEntity(entity); } assert(engine.entities.count == numEntities); } func testDocumentation() { // Create engine let engine:Engine = Engine(); // Add systems to engine let system:TestSystem = TestSystem(); engine.addSystem(system, priority: 1); // Create and add components to the entity. let entity:Entity = Entity(); entity.add(TestComponentA()); entity.add(TestComponentB()); entity.add(TestComponentC()); // Add entity to engine try! engine.addEntity(entity); // Tick the engine. // You should usually do this on a frame by frame basis, passing the delta time // since the last tick. let mockDeltaTime:Double = 1.0; engine.update(mockDeltaTime); } func testSystemTick() { // Create engine let engine:Engine = Engine(); // Add systems to engine let system:TestSystem = TestSystem(); engine.addSystem(system, priority: 1); // Create entity with inspectable component let component:TestComponentA = TestComponentA(); assert(component.value == 0); let entity:Entity = Entity(); entity.add(component); // Add entity to engine try! engine.addEntity(entity); // Do some ticking. let deltaTime:Double = 1.0; for index in 1...100 { engine.update(deltaTime); // Expect each delta to increase components value by the delta (thats what the system does). assert(component.value == (deltaTime * Double(index))) } } func testSystemEntitiesCount() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. // Create engine let engine:Engine = Engine(); // Add systems to engine let system:TestSystem = TestSystem(); engine.addSystem(system, priority: 1); // Add entities to engine do { // System entities should be 0 assert(system.numEntities == 0); // Create an entity that conforms to system family var ent:Entity = Entity(); ent.add(TestComponentA()); try engine.addEntity(ent); // Should now have 1 entity in system assert(system.numEntities == 1); // Remove entity from system engine.removeEntity(ent); // Should now have 0 entities in system assert(system.numEntities == 0); // Add a non-family-confirming entity to system ent = Entity(); try engine.addEntity(ent); ent.add(TestComponentB()); // Num entities should still be 0 assert(system.numEntities == 0); // Add component to entity to make the entity // conform to the family. ent.add(TestComponentA()); // Num entities in system should now be 1 assert(system.numEntities == 1); // Remove component from entity so it is no longer conforming ent.remove(TestComponentA.self); // We should no longer have entities in the system. assert(system.numEntities == 0); } catch { } engine.update(1); } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
27e77c14c11f80930cdc0c022e23867d
23.754717
111
0.667302
3.77554
false
true
false
false
hejunbinlan/swiftmi-app
swiftmi/swiftmi/SwiftCodeController.swift
4
8600
// // SwiftCodeController.swift // swiftmi // // Created by yangyin on 15/4/1. // Copyright (c) 2015年 swiftmi. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import Kingfisher let reuseIdentifier = "CodeCell" class SwiftCodeController: UICollectionViewController,UICollectionViewDelegateFlowLayout { let sectionInsets = UIEdgeInsets(top:6, left: 6, bottom: 6, right: 6) internal var data:[AnyObject] = [AnyObject]() var loading:Bool = false private func getDefaultData(){ var dalCode = CodeDal() var result = dalCode.getCodeList() if result != nil { self.data = result! self.collectionView?.reloadData() } } override func viewDidLoad() { super.viewDidLoad() self.collectionViewLayout.collectionView?.backgroundColor = UIColor.whiteColor() self.collectionView?.addHeaderWithCallback{ self.loadData(0, isPullRefresh: true) } // (self.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = CGSize(width: width, height: 380) self.collectionView?.addFooterWithCallback{ if(self.data.count>0) { var maxId = self.data.last!.valueForKey("codeId") as! Int self.loadData(maxId, isPullRefresh: false) } } getDefaultData() self.collectionView?.headerBeginRefreshing() } func loadData(maxId:Int,isPullRefresh:Bool){ if self.loading { return } self.loading = true Alamofire.request(Router.CodeList(maxId: maxId, count: 12)).responseJSON{ (_,_,json,error) in self.loading = false if(isPullRefresh){ self.collectionView?.headerEndRefreshing() } else{ self.collectionView?.footerEndRefreshing() } if error != nil { self.notice("网络异常", type: NoticeType.error, autoClear: true) return } var result = JSON(json!) if result["isSuc"].boolValue { var items = result["result"] if(items.count==0){ return } if(isPullRefresh){ var dalCode = CodeDal() dalCode.deleteAll() dalCode.addList(items) self.data.removeAll(keepCapacity: false) } var objItems = items.arrayObject for it in items { self.data.append(it.1.object); // println("data length \(self.data.count)") } dispatch_async(dispatch_get_main_queue()) { self.collectionView!.reloadData() } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. var item = self.collectionView?.indexPathsForSelectedItems() if item?.count > 0 { var indexPath = item![0] as! NSIndexPath if segue.destinationViewController is CodeDetailViewController { var view = segue.destinationViewController as! CodeDetailViewController var code: AnyObject = self.data[indexPath.row] view.shareCode = code } } } // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { //#warning Incomplete method implementation -- Return the number of sections return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //#warning Incomplete method implementation -- Return the number of items in the section return self.data.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = self.collectionView!.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CodeCell var item: AnyObject = self.data[indexPath.row] // Configure the cell var preview = item.valueForKey("preview") as? String if preview != nil { if (preview!.hasPrefix("http://swiftmi.")){ preview = "\(preview!)-code" } cell.preview.kf_setImageWithURL(NSURL(string: preview!)!, placeholderImage: nil) } var pubTime = item.valueForKey("createTime") as! Double var createDate = NSDate(timeIntervalSince1970: pubTime) cell.timeLabel.text = Utility.formatDate(createDate) cell.title.text = item.valueForKey("title") as? String //cell.addShadow() return cell } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { var frame = self.view.frame; var width = frame.width if (frame.width > frame.height) { width = frame.height } width = CGFloat(Int((width-18)/2)) // println("width....\(width)") return CGSize(width: width, height: 380) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat{ return 6 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 6 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets{ return sectionInsets } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ // Uncomment this method to specify if the specified item should be selected override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { collectionView.layer.shadowOpacity = 0.8 return true } /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { return false } override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { } */ }
mit
c7ca37652b92fac329c63e0fba6a5bea
29.464539
185
0.578463
6.118234
false
false
false
false
sharath-cliqz/browser-ios
Client/Application/WebServer.swift
2
3493
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import GCDWebServers class WebServer { static let WebServerSharedInstance = WebServer() class var sharedInstance: WebServer { return WebServerSharedInstance } let server: GCDWebServer = GCDWebServer() var base: String { return "http://localhost:\(server.port)" } func start() throws -> Bool{ if !server.isRunning { // Cliqz: changed the webserver port so as not to conflict with Firefox one try server.start(options: [GCDWebServerOption_Port: 6572, GCDWebServerOption_BindToLocalhost: true, GCDWebServerOption_AutomaticallySuspendInBackground: true]) } return server.isRunning } /// Convenience method to register a dynamic handler. Will be mounted at $base/$module/$resource func registerHandlerForMethod(_ method: String, module: String, resource: String, handler: @escaping (_ request: GCDWebServerRequest?) -> GCDWebServerResponse!) { // Prevent serving content if the requested host isn't a whitelisted local host. let wrappedHandler = {(request: GCDWebServerRequest!) -> GCDWebServerResponse! in guard request.url.isLocal else { return GCDWebServerResponse(statusCode: 403) } return handler(request) } server.addHandler(forMethod: method, path: "/\(module)/\(resource)", request: GCDWebServerRequest.self, processBlock: wrappedHandler) } /// Convenience method to register a resource in the main bundle. Will be mounted at $base/$module/$resource func registerMainBundleResource(_ resource: String, module: String) { if let path = Bundle.main.path(forResource: resource, ofType: nil) { server.addGETHandler(forPath: "/\(module)/\(resource)", filePath: path, isAttachment: false, cacheAge: UInt.max, allowRangeRequests: true) } } /// Convenience method to register all resources in the main bundle of a specific type. Will be mounted at $base/$module/$resource func registerMainBundleResourcesOfType(_ type: String, module: String) { for path: String in Bundle.paths(forResourcesOfType: type, inDirectory: Bundle.main.bundlePath) { if let resource = NSURL(string: path)?.lastPathComponent { server.addGETHandler(forPath: "/\(module)/\(resource)", filePath: path, isAttachment: false, cacheAge: UInt.max, allowRangeRequests: true) } } } /// Return a full url, as a string, for a resource in a module. No check is done to find out if the resource actually exist. func URLForResource(_ resource: String, module: String) -> String { return "\(base)/\(module)/\(resource)" } /// Return a full url, as an NSURL, for a resource in a module. No check is done to find out if the resource actually exist. func URLForResource(_ resource: String, module: String) -> URL { return URL(string: "\(base)/\(module)/\(resource)")! } func updateLocalURL(_ url: URL) -> URL? { var components = URLComponents(url: url, resolvingAgainstBaseURL: false) if components?.host == "localhost" && components?.scheme == "http" { components?.port = Int(WebServer.sharedInstance.server.port) } return components?.url } }
mpl-2.0
846292797b40008a59d07d68f7c6bb99
44.960526
171
0.679072
4.694892
false
false
false
false
joostholslag/BNRiOS
iOSProgramming6ed/15 - Camera/Solutions/Homepwner/Homepwner/DetailViewController.swift
1
3767
// // Copyright © 2015 Big Nerd Ranch // import UIKit class DetailViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet var nameField: UITextField! @IBOutlet var serialNumberField: UITextField! @IBOutlet var valueField: UITextField! @IBOutlet var dateLabel: UILabel! @IBOutlet var imageView: UIImageView! var item: Item! { didSet { navigationItem.title = item.name } } var imageStore: ImageStore! let numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.minimumFractionDigits = 2 formatter.maximumFractionDigits = 2 return formatter }() let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .none return formatter }() @IBAction func takePicture(_ sender: UIBarButtonItem) { let imagePicker = UIImagePickerController() // If the device has a camera, take a picture, otherwise, // just pick from photo library if UIImagePickerController.isSourceTypeAvailable(.camera) { imagePicker.sourceType = .camera } else { imagePicker.sourceType = .photoLibrary } imagePicker.delegate = self // Place image picker on the screen present(imagePicker, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) { // Get picked image from info dictionary let image = info[UIImagePickerControllerOriginalImage] as! UIImage // Store the image in the ImageStore for the item's key imageStore.setImage(image, forKey: item.itemKey) // Put that image onto the screen in our image view imageView.image = image // Take image picker off the screen - // you must call this dismiss method dismiss(animated: true, completion: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) nameField.text = item.name serialNumberField.text = item.serialNumber valueField.text = numberFormatter.string(from: NSNumber(value: item.valueInDollars)) dateLabel.text = dateFormatter.string(from: item.dateCreated) // Get the item key let key = item.itemKey // If there is an associated image with the item ... if let imageToDisplay = imageStore.image(forKey: key) { // ... display it on the image view imageView.image = imageToDisplay } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Clear first responder view.endEditing(true) // "Save" changes to item item.name = nameField.text ?? "" item.serialNumber = serialNumberField.text if let valueText = valueField.text, let value = numberFormatter.number(from: valueText) { item.valueInDollars = value.intValue } else { item.valueInDollars = 0 } } @IBAction func backgroundTapped(_ sender: UITapGestureRecognizer) { view.endEditing(true) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
gpl-3.0
be2ed94ee26fc46f332cad412604b9d2
31.465517
132
0.612055
5.776074
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Reader/ReaderPostCellActions.swift
1
7940
/// Action commands in Reader cells class ReaderPostCellActions: NSObject, ReaderPostCellDelegate { private let context: NSManagedObjectContext private weak var origin: UIViewController? private let topic: ReaderAbstractTopic? private var followCommentsService: FollowCommentsService? var imageRequestAuthToken: String? = nil var isLoggedIn: Bool = false var visibleConfirmation: Bool { didSet { saveForLaterAction?.visibleConfirmation = visibleConfirmation } } private weak var saveForLaterAction: ReaderSaveForLaterAction? /// Saved posts that have been removed but not yet discarded var removedPosts = ReaderSaveForLaterRemovedPosts() weak var savedPostsDelegate: ReaderSavedPostCellActionsDelegate? init(context: NSManagedObjectContext, origin: UIViewController, topic: ReaderAbstractTopic? = nil, visibleConfirmation: Bool = true) { self.context = context self.origin = origin self.topic = topic self.visibleConfirmation = visibleConfirmation super.init() } func readerCell(_ cell: ReaderPostCardCell, headerActionForProvider provider: ReaderPostContentProvider) { guard let post = provider as? ReaderPost, let origin = origin else { return } ReaderHeaderAction().execute(post: post, origin: origin) } func readerCell(_ cell: ReaderPostCardCell, commentActionForProvider provider: ReaderPostContentProvider) { guard let post = provider as? ReaderPost, let origin = origin else { return } if let controller = origin as? ReaderStreamViewController, let indexPath = controller.tableView.indexPath(for: cell), let topic = controller.readerTopic, ReaderHelpers.topicIsDiscover(topic), controller.shouldShowCommentSpotlight { controller.reloadReaderDiscoverNudgeFlow(at: indexPath) } ReaderCommentAction().execute(post: post, origin: origin, source: .postCard) } func readerCell(_ cell: ReaderPostCardCell, followActionForProvider provider: ReaderPostContentProvider) { guard let post = provider as? ReaderPost else { return } toggleFollowingForPost(post) } func readerCell(_ cell: ReaderPostCardCell, saveActionForProvider provider: ReaderPostContentProvider) { if let origin = origin as? ReaderStreamViewController, origin.contentType == .saved { if let post = provider as? ReaderPost { removedPosts.add(post) } savedPostsDelegate?.willRemove(cell) } else { guard let post = provider as? ReaderPost else { return } toggleSavedForLater(for: post) } } func readerCell(_ cell: ReaderPostCardCell, shareActionForProvider provider: ReaderPostContentProvider, fromView sender: UIView) { guard let post = provider as? ReaderPost else { return } sharePost(post, fromView: sender) } func readerCell(_ cell: ReaderPostCardCell, likeActionForProvider provider: ReaderPostContentProvider) { guard let post = provider as? ReaderPost else { return } ReaderLikeAction().execute(with: post, context: context, completion: { cell.refreshLikeButton() }) } func readerCell(_ cell: ReaderPostCardCell, menuActionForProvider provider: ReaderPostContentProvider, fromView sender: UIView) { guard let post = provider as? ReaderPost, let origin = origin, let followCommentsService = FollowCommentsService(post: post) else { return } self.followCommentsService = followCommentsService ReaderMenuAction(logged: isLoggedIn).execute( post: post, context: context, readerTopic: topic, anchor: sender, vc: origin, source: ReaderPostMenuSource.card, followCommentsService: followCommentsService ) WPAnalytics.trackReader(.postCardMoreTapped) } func readerCell(_ cell: ReaderPostCardCell, attributionActionForProvider provider: ReaderPostContentProvider) { guard let post = provider as? ReaderPost else { return } showAttributionForPost(post) } func readerCell(_ cell: ReaderPostCardCell, reblogActionForProvider provider: ReaderPostContentProvider) { guard let post = provider as? ReaderPost, let origin = origin else { return } ReaderReblogAction().execute(readerPost: post, origin: origin, reblogSource: .list) } func readerCellImageRequestAuthToken(_ cell: ReaderPostCardCell) -> String? { return imageRequestAuthToken } private func toggleFollowingForPost(_ post: ReaderPost) { ReaderFollowAction().execute(with: post, context: context, completion: { follow in ReaderHelpers.dispatchToggleFollowSiteMessage(post: post, follow: follow, success: true) }, failure: { follow, _ in ReaderHelpers.dispatchToggleFollowSiteMessage(post: post, follow: follow, success: false) }) } func toggleSavedForLater(for post: ReaderPost) { let actionOrigin: ReaderSaveForLaterOrigin if let origin = origin as? ReaderStreamViewController, origin.contentType == .saved { actionOrigin = .savedStream } else { actionOrigin = .otherStream } if !post.isSavedForLater { if let origin = origin as? ReaderStreamViewController, origin.contentType != .saved { FancyAlertViewController.presentReaderSavedPostsAlertControllerIfNecessary(from: origin) } } let saveAction = ReaderSaveForLaterAction(visibleConfirmation: visibleConfirmation) saveAction.execute(with: post, context: context, origin: actionOrigin, viewController: origin) saveForLaterAction = saveAction } fileprivate func visitSiteForPost(_ post: ReaderPost) { guard let origin = origin else { return } ReaderVisitSiteAction().execute(with: post, context: ContextManager.sharedInstance().mainContext, origin: origin) } fileprivate func showAttributionForPost(_ post: ReaderPost) { guard let origin = origin else { return } ReaderShowAttributionAction().execute(with: post, context: context, origin: origin) } fileprivate func sharePost(_ post: ReaderPost, fromView anchorView: UIView) { guard let origin = origin else { return } ReaderShareAction().execute(with: post, context: context, anchor: anchorView, vc: origin) } } enum ReaderActionsVisibility: Equatable { case hidden case visible(enabled: Bool) static func == (lhs: ReaderActionsVisibility, rhs: ReaderActionsVisibility) -> Bool { switch (lhs, rhs) { case (.hidden, .hidden): return true case (.visible(let lenabled), .visible(let renabled)): return lenabled == renabled default: return false } } var isEnabled: Bool { switch self { case .hidden: return false case .visible(let enabled): return enabled } } } // MARK: - Saved Posts extension ReaderPostCellActions { func postIsRemoved(_ post: ReaderPost) -> Bool { return removedPosts.contains(post) } func restoreUnsavedPost(_ post: ReaderPost) { removedPosts.remove(post) } func clearRemovedPosts() { removedPosts.all().forEach({ toggleSavedForLater(for: $0) }) removedPosts = ReaderSaveForLaterRemovedPosts() } }
gpl-2.0
f998db2c5fd1fd5b1d7117f173b68a62
34.446429
138
0.65063
5.343203
false
false
false
false
coderQuanjun/PigTV
GYJTV/GYJTV/Classes/Rank/ViewModel/WeeklyRankViewModel.swift
1
1849
// // WeeklyRankViewModel.swift // GYJTV // // Created by zcm_iOS on 2017/6/20. // Copyright © 2017年 Quanjun. All rights reserved. // import UIKit class WeeklyRankViewModel { lazy var weeklyArray : [[WeeklyModel]] = [[WeeklyModel]]() } extension WeeklyRankViewModel{ func loadWeeklyRequestData(_ rankType : RankType, _ complection : @escaping() -> ()){ let signature = rankType.typeNum == 1 ? "b4523db381213dde637a2e407f6737a6" : "d23e92d56b1f1ac6644e5820eb336c3e" let ts = rankType.typeNum == 1 ? "1480399365" : "1480414121" let parameters : [String : Any] = ["imei" : "36301BB0-8BBA-48B0-91F5-33F1517FA056", "pageSize" : 30, "signature" : signature, "ts" : ts, "weekly" : rankType.typeNum - 1] NetworkTool.requestData(.get, URLString: kRankWeeklyListUrl, parameters: parameters) { (result) in //1.清空数据 self.weeklyArray.removeAll() //2.转成字典 guard let resultDic = result as? [String : Any] else { return } //3.取出数据字典 guard let message = resultDic["message"] as? [String : Any] else { return } //3.主播数据 if let anchorRank = message["anchorRank"] as? [[String : Any]] { self.addDataToWeeklyRanks(dataArr: anchorRank) } //4.粉丝数据 if let fansDataArray = message["fansRank"] as? [[String : Any]]{ self.addDataToWeeklyRanks(dataArr: fansDataArray) } //5.回调 complection() } } fileprivate func addDataToWeeklyRanks(dataArr : [[String : Any]]){ var weeklys = [WeeklyModel]() for dict in dataArr{ weeklys.append(WeeklyModel(dic: dict)) } weeklyArray.append(weeklys) } }
mit
a047be69493905929d93fd168b213f07
34.96
177
0.586763
3.603206
false
false
false
false
kstaring/swift
stdlib/public/core/Sequence.swift
1
54871
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A type that supplies the values of a sequence one at a time. /// /// The `IteratorProtocol` protocol is tightly linked with the `Sequence` /// protocol. Sequences provide access to their elements by creating an /// iterator, which keeps track of its iteration process and returns one /// element at a time as it advances through the sequence. /// /// Whenever you use a `for`-`in` loop with an array, set, or any other /// collection or sequence, you're using that type's iterator. Swift uses a /// sequence's or collection's iterator internally to enable the `for`-`in` /// loop language construct. /// /// Using a sequence's iterator directly gives you access to the same elements /// in the same order as iterating over that sequence using a `for`-`in` loop. /// For example, you might typically use a `for`-`in` loop to print each of /// the elements in an array. /// /// let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"] /// for animal in animals { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// Behind the scenes, Swift uses the `animals` array's iterator to loop over /// the contents of the array. /// /// var animalIterator = animals.makeIterator() /// while let animal = animalIterator.next() { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// The call to `animals.makeIterator()` returns an instance of the array's /// iterator. Next, the `while` loop calls the iterator's `next()` method /// repeatedly, binding each element that is returned to `animal` and exiting /// when the `next()` method returns `nil`. /// /// Using Iterators Directly /// ======================== /// /// You rarely need to use iterators directly, because a `for`-`in` loop is the /// more idiomatic approach to traversing a sequence in Swift. Some /// algorithms, however, may call for direct iterator use. /// /// One example is the `reduce1(_:)` method. Similar to the `reduce(_:_:)` /// method defined in the standard library, which takes an initial value and a /// combining closure, `reduce1(_:)` uses the first element of the sequence as /// the initial value. /// /// Here's an implementation of the `reduce1(_:)` method. The sequence's /// iterator is used directly to retrieve the initial value before looping /// over the rest of the sequence. /// /// extension Sequence { /// func reduce1( /// _ nextPartialResult: (Iterator.Element, Iterator.Element) -> Iterator.Element /// ) -> Iterator.Element? /// { /// var i = makeIterator() /// guard var accumulated = i.next() else { /// return nil /// } /// /// while let element = i.next() { /// accumulated = nextPartialResult(accumulated, element) /// } /// return accumulated /// } /// } /// /// The `reduce1(_:)` method makes certain kinds of sequence operations /// simpler. Here's how to find the longest string in a sequence, using the /// `animals` array introduced earlier as an example: /// /// let longestAnimal = animals.reduce1 { current, element in /// if current.characters.count > element.characters.count { /// return current /// } else { /// return element /// } /// } /// print(longestAnimal) /// // Prints "Butterfly" /// /// Using Multiple Iterators /// ======================== /// /// Whenever you use multiple iterators (or `for`-`in` loops) over a single /// sequence, be sure you know that the specific sequence supports repeated /// iteration, either because you know its concrete type or because the /// sequence is also constrained to the `Collection` protocol. /// /// Obtain each separate iterator from separate calls to the sequence's /// `makeIterator()` method rather than by copying. Copying an iterator is /// safe, but advancing one copy of an iterator by calling its `next()` method /// may invalidate other copies of that iterator. `for`-`in` loops are safe in /// this regard. /// /// Adding IteratorProtocol Conformance to Your Type /// ================================================ /// /// Implementing an iterator that conforms to `IteratorProtocol` is simple. /// Declare a `next()` method that advances one step in the related sequence /// and returns the current element. When the sequence has been exhausted, the /// `next()` method returns `nil`. /// /// For example, consider a custom `Countdown` sequence. You can initialize the /// `Countdown` sequence with a starting integer and then iterate over the /// count down to zero. The `Countdown` structure's definition is short: It /// contains only the starting count and the `makeIterator()` method required /// by the `Sequence` protocol. /// /// struct Countdown: Sequence { /// let start: Int /// /// func makeIterator() -> CountdownIterator { /// return CountdownIterator(self) /// } /// } /// /// The `makeIterator()` method returns another custom type, an iterator named /// `CountdownIterator`. The `CountdownIterator` type keeps track of both the /// `Countdown` sequence that it's iterating and the number of times it has /// returned a value. /// /// struct CountdownIterator: IteratorProtocol { /// let countdown: Countdown /// var times = 0 /// /// init(_ countdown: Countdown) { /// self.countdown = countdown /// } /// /// mutating func next() -> Int? { /// let nextNumber = countdown.start - times /// guard nextNumber > 0 /// else { return nil } /// /// times += 1 /// return nextNumber /// } /// } /// /// Each time the `next()` method is called on a `CountdownIterator` instance, /// it calculates the new next value, checks to see whether it has reached /// zero, and then returns either the number, or `nil` if the iterator is /// finished returning elements of the sequence. /// /// Creating and iterating over a `Countdown` sequence uses a /// `CountdownIterator` to handle the iteration. /// /// let threeTwoOne = Countdown(start: 3) /// for count in threeTwoOne { /// print("\(count)...") /// } /// // Prints "3..." /// // Prints "2..." /// // Prints "1..." public protocol IteratorProtocol { /// The type of element traversed by the iterator. associatedtype Element /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Repeatedly calling this method returns, in order, all the elements of the /// underlying sequence. As soon as the sequence has run out of elements, all /// subsequent calls return `nil`. /// /// You must not call this method if any other copy of this iterator has been /// advanced with a call to its `next()` method. /// /// The following example shows how an iterator can be used explicitly to /// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and /// then call the iterator's `next()` method until it returns `nil`. /// /// let numbers = [2, 3, 5, 7] /// var numbersIterator = numbers.makeIterator() /// /// while let num = numbersIterator.next() { /// print(num) /// } /// // Prints "2" /// // Prints "3" /// // Prints "5" /// // Prints "7" /// /// - Returns: The next element in the underlying sequence, if a next element /// exists; otherwise, `nil`. mutating func next() -> Element? } /// A type that provides sequential, iterated access to its elements. /// /// A sequence is a list of values that you can step through one at a time. The /// most common way to iterate over the elements of a sequence is to use a /// `for`-`in` loop: /// /// let oneTwoThree = 1...3 /// for number in oneTwoThree { /// print(number) /// } /// // Prints "1" /// // Prints "2" /// // Prints "3" /// /// While seemingly simple, this capability gives you access to a large number /// of operations that you can perform on any sequence. As an example, to /// check whether a sequence includes a particular value, you can test each /// value sequentially until you've found a match or reached the end of the /// sequence. This example checks to see whether a particular insect is in an /// array. /// /// let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// var hasMosquito = false /// for bug in bugs { /// if bug == "Mosquito" { /// hasMosquito = true /// break /// } /// } /// print("'bugs' has a mosquito: \(hasMosquito)") /// // Prints "'bugs' has a mosquito: false" /// /// The `Sequence` protocol provides default implementations for many common /// operations that depend on sequential access to a sequence's values. For /// clearer, more concise code, the example above could use the array's /// `contains(_:)` method, which every sequence inherits from `Sequence`, /// instead of iterating manually: /// /// if bugs.contains("Mosquito") { /// print("Break out the bug spray.") /// } else { /// print("Whew, no mosquitos!") /// } /// // Prints "Whew, no mosquitos!" /// /// Repeated Access /// =============== /// /// The `Sequence` protocol makes no requirement on conforming types regarding /// whether they will be destructively consumed by iteration. As a /// consequence, don't assume that multiple `for`-`in` loops on a sequence /// will either resume iteration or restart from the beginning: /// /// for element in sequence { /// if ... some condition { break } /// } /// /// for element in sequence { /// // No defined behavior /// } /// /// In this case, you cannot assume either that a sequence will be consumable /// and will resume iteration, or that a sequence is a collection and will /// restart iteration from the first element. A conforming sequence that is /// not a collection is allowed to produce an arbitrary sequence of elements /// in the second `for`-`in` loop. /// /// To establish that a type you've created supports nondestructive iteration, /// add conformance to the `Collection` protocol. /// /// Conforming to the Sequence Protocol /// =================================== /// /// Making your own custom types conform to `Sequence` enables many useful /// operations, like `for`-`in` looping and the `contains` method, without /// much effort. To add `Sequence` conformance to your own custom type, add a /// `makeIterator()` method that returns an iterator. /// /// Alternatively, if your type can act as its own iterator, implementing the /// requirements of the `IteratorProtocol` protocol and declaring conformance /// to both `Sequence` and `IteratorProtocol` are sufficient. /// /// Here's a definition of a `Countdown` sequence that serves as its own /// iterator. The `makeIterator()` method is provided as a default /// implementation. /// /// struct Countdown: Sequence, IteratorProtocol { /// var count: Int /// /// mutating func next() -> Int? { /// if count == 0 { /// return nil /// } else { /// defer { count -= 1 } /// return count /// } /// } /// } /// /// let threeToGo = Countdown(count: 3) /// for i in threeToGo { /// print(i) /// } /// // Prints "3" /// // Prints "2" /// // Prints "1" /// /// Expected Performance /// ==================== /// /// A sequence should provide its iterator in O(1). The `Sequence` protocol /// makes no other requirements about element access, so routines that /// traverse a sequence should be considered O(*n*) unless documented /// otherwise. /// /// - SeeAlso: `IteratorProtocol`, `Collection` public protocol Sequence { //@available(*, unavailable, renamed: "Iterator") //typealias Generator = () /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. associatedtype Iterator : IteratorProtocol /// A type that represents a subsequence of some of the sequence's elements. associatedtype SubSequence // FIXME(ABI)#104 (Recursive Protocol Constraints): // FIXME(ABI)#105 (Associated Types with where clauses): // associatedtype SubSequence : Sequence // where // Iterator.Element == SubSequence.Iterator.Element, // SubSequence.SubSequence == SubSequence // // (<rdar://problem/20715009> Implement recursive protocol // constraints) // // These constraints allow processing collections in generic code by // repeatedly slicing them in a loop. /// Returns an iterator over the elements of this sequence. func makeIterator() -> Iterator /// A value less than or equal to the number of elements in /// the sequence, calculated nondestructively. /// /// - Complexity: O(1) var underestimatedCount: Int { get } /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercaseString } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.characters.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. func map<T>( _ transform: (Iterator.Element) throws -> T ) rethrows -> [T] /// Returns an array containing, in order, the elements of the sequence /// that satisfy the given predicate. /// /// In this example, `filter` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.characters.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `includeElement` allowed. func filter( _ isIncluded: (Iterator.Element) throws -> Bool ) rethrows -> [Iterator.Element] /// Calls the given closure on each element in the sequence in the same order /// as a `for`-`in` loop. /// /// The two loops in the following example produce the same output: /// /// let numberWords = ["one", "two", "three"] /// for word in numberWords { /// print(word) /// } /// // Prints "one" /// // Prints "two" /// // Prints "three" /// /// numberWords.forEach { word in /// print(word) /// } /// // Same as above /// /// Using the `forEach` method is distinct from a `for`-`in` loop in two /// important ways: /// /// 1. You cannot use a `break` or `continue` statement to exit the current /// call of the `body` closure or skip subsequent calls. /// 2. Using the `return` statement in the `body` closure will exit only from /// the current call to `body`, not from any outer scope, and won't skip /// subsequent calls. /// /// - Parameter body: A closure that takes an element of the sequence as a /// parameter. func forEach(_ body: (Iterator.Element) throws -> Void) rethrows // Note: The complexity of Sequence.dropFirst(_:) requirement // is documented as O(n) because Collection.dropFirst(_:) is // implemented in O(n), even though the default // implementation for Sequence.dropFirst(_:) is O(1). /// Returns a subsequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the sequence, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of /// the sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence starting after the specified number of /// elements. /// /// - Complexity: O(*n*), where *n* is the number of elements to drop from /// the beginning of the sequence. func dropFirst(_ n: Int) -> SubSequence /// Returns a subsequence containing all but the specified number of final /// elements. /// /// The sequence must be finite. If the number of elements to drop exceeds /// the number of elements in the sequence, the result is an empty /// subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence leaving off the specified number of elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. func dropLast(_ n: Int) -> SubSequence /// Returns a subsequence by skipping elements while `predicate` returns /// `true` and returning the remaining elements. /// /// - Parameter predicate: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element is a match. /// /// - Complexity: O(*n*), where *n* is the length of the collection. func drop( while predicate: (Iterator.Element) throws -> Bool ) rethrows -> SubSequence /// Returns a subsequence, up to the specified maximum length, containing /// the initial elements of the sequence. /// /// If the maximum length exceeds the number of elements in the sequence, /// the result contains all the elements in the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. /// `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence starting at the beginning of this sequence /// with at most `maxLength` elements. func prefix(_ maxLength: Int) -> SubSequence /// Returns a subsequence containing the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `prefix(while:)` method to find the /// positive numbers at the beginning of the `numbers` array. Every element /// of `numbers` up to, but not including, the first negative value is /// included in the result. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let positivePrefix = numbers.prefix(while: { $0 > 0 }) /// // positivePrefix == [3, 7, 4] /// /// If `predicate` matches every element in the sequence, the resulting /// sequence contains every element of the sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A subsequence of the initial, consecutive elements that /// satisfy `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. func prefix( while predicate: (Iterator.Element) throws -> Bool ) rethrows -> SubSequence /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the sequence. /// /// The sequence must be finite. If the maximum length exceeds the number /// of elements in the sequence, the result contains all the elements in /// the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence terminating at the end of this sequence with /// at most `maxLength` elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. func suffix(_ maxLength: Int) -> SubSequence /// Returns the longest possible subsequences of the sequence, in order, that /// don't contain elements satisfying the given predicate. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.characters.split(whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print( /// line.characters.split(maxSplits: 1, whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print( /// line.characters.split( /// omittingEmptySubsequences: false, /// whereSeparator: { $0 == " " }) /// ).map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the sequence satisfying the `isSeparator` predicate. /// If `true`, only nonempty subsequences are returned. The default /// value is `true`. /// - isSeparator: A closure that returns `true` if its argument should be /// used to split the sequence; otherwise, `false`. /// - Returns: An array of subsequences, split from this sequence's elements. func split( maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator isSeparator: (Iterator.Element) throws -> Bool ) rethrows -> [SubSequence] func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? /// If `self` is multi-pass (i.e., a `Collection`), invoke `preprocess` and /// return its result. Otherwise, return `nil`. func _preprocessingPass<R>( _ preprocess: () throws -> R ) rethrows -> R? /// Create a native array buffer containing the elements of `self`, /// in the same order. func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> /// Copy a Sequence into an array, returning one past the last /// element initialized. @discardableResult func _copyContents(initializing ptr: UnsafeMutablePointer<Iterator.Element>) -> UnsafeMutablePointer<Iterator.Element> } /// A default makeIterator() function for `IteratorProtocol` instances that /// are declared to conform to `Sequence` extension Sequence where Self.Iterator == Self, Self : IteratorProtocol { /// Returns an iterator over the elements of this sequence. public func makeIterator() -> Self { return self } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. /// /// This is a class - we require reference semantics to keep track /// of how many elements we've already dropped from the underlying sequence. internal class _DropFirstSequence<Base : IteratorProtocol> : Sequence, IteratorProtocol { internal var _iterator: Base internal let _limit: Int internal var _dropped: Int internal init(_iterator: Base, limit: Int, dropped: Int = 0) { self._iterator = _iterator self._limit = limit self._dropped = dropped } internal func makeIterator() -> _DropFirstSequence<Base> { return self } internal func next() -> Base.Element? { while _dropped < _limit { if _iterator.next() == nil { _dropped = _limit return nil } _dropped += 1 } return _iterator.next() } internal func dropFirst(_ n: Int) -> AnySequence<Base.Element> { // If this is already a _DropFirstSequence, we need to fold in // the current drop count and drop limit so no data is lost. // // i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to // [1,2,3,4].dropFirst(2). return AnySequence( _DropFirstSequence( _iterator: _iterator, limit: _limit + n, dropped: _dropped)) } } /// A sequence that only consumes up to `n` elements from an underlying /// `Base` iterator. /// /// The underlying iterator's sequence may be infinite. /// /// This is a class - we require reference semantics to keep track /// of how many elements we've already taken from the underlying sequence. internal class _PrefixSequence<Base : IteratorProtocol> : Sequence, IteratorProtocol { internal let _maxLength: Int internal var _iterator: Base internal var _taken: Int internal init(_iterator: Base, maxLength: Int, taken: Int = 0) { self._iterator = _iterator self._maxLength = maxLength self._taken = taken } internal func makeIterator() -> _PrefixSequence<Base> { return self } internal func next() -> Base.Element? { if _taken >= _maxLength { return nil } _taken += 1 if let next = _iterator.next() { return next } _taken = _maxLength return nil } internal func prefix(_ maxLength: Int) -> AnySequence<Base.Element> { return AnySequence( _PrefixSequence( _iterator: _iterator, maxLength: Swift.min(maxLength, self._maxLength), taken: _taken)) } internal func drop( while predicate: (Base.Element) throws -> Bool ) rethrows -> AnySequence<Base.Element> { return try AnySequence( _DropWhileSequence( iterator: _iterator, nextElement: nil, predicate: predicate)) } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. /// /// This is a class - we require reference semantics to keep track /// of how many elements we've already dropped from the underlying sequence. internal class _DropWhileSequence<Base : IteratorProtocol> : Sequence, IteratorProtocol { internal var _iterator: Base internal var _nextElement: Base.Element? internal init( iterator: Base, nextElement: Base.Element?, predicate: (Base.Element) throws -> Bool ) rethrows { self._iterator = iterator self._nextElement = nextElement ?? _iterator.next() while try _nextElement.flatMap(predicate) == true { _nextElement = _iterator.next() } } internal func makeIterator() -> _DropWhileSequence<Base> { return self } internal func next() -> Base.Element? { guard _nextElement != nil else { return _iterator.next() } let next = _nextElement _nextElement = nil return next } internal func drop( while predicate: (Base.Element) throws -> Bool ) rethrows -> AnySequence<Base.Element> { // If this is already a _DropWhileSequence, avoid multiple // layers of wrapping and keep the same iterator. return try AnySequence( _DropWhileSequence( iterator: _iterator, nextElement: _nextElement, predicate: predicate)) } } //===----------------------------------------------------------------------===// // Default implementations for Sequence //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercaseString } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.characters.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. public func map<T>( _ transform: (Iterator.Element) throws -> T ) rethrows -> [T] { let initialCapacity = underestimatedCount var result = ContiguousArray<T>() result.reserveCapacity(initialCapacity) var iterator = self.makeIterator() // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { result.append(try transform(iterator.next()!)) } // Add remaining elements, if any. while let element = iterator.next() { result.append(try transform(element)) } return Array(result) } /// Returns an array containing, in order, the elements of the sequence /// that satisfy the given predicate. /// /// In this example, `filter` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.characters.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `includeElement` allowed. public func filter( _ isIncluded: (Iterator.Element) throws -> Bool ) rethrows -> [Iterator.Element] { var result = ContiguousArray<Iterator.Element>() var iterator = self.makeIterator() while let element = iterator.next() { if try isIncluded(element) { result.append(element) } } return Array(result) } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the sequence. /// /// The sequence must be finite. If the maximum length exceeds the number of /// elements in the sequence, the result contains all the elements in the /// sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Complexity: O(*n*), where *n* is the length of the sequence. public func suffix(_ maxLength: Int) -> AnySequence<Iterator.Element> { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence") if maxLength == 0 { return AnySequence([]) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements into a ring buffer to save space. Once all // elements are consumed, reorder the ring buffer into an `Array` // and return it. This saves memory for sequences particularly longer // than `maxLength`. var ringBuffer: [Iterator.Element] = [] ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount)) var i = ringBuffer.startIndex for element in self { if ringBuffer.count < maxLength { ringBuffer.append(element) } else { ringBuffer[i] = element i += 1 i %= maxLength } } if i != ringBuffer.startIndex { let s0 = ringBuffer[i..<ringBuffer.endIndex] let s1 = ringBuffer[0..<i] return AnySequence([s0, s1].joined()) } return AnySequence(ringBuffer) } /// Returns the longest possible subsequences of the sequence, in order, that /// don't contain elements satisfying the given predicate. Elements that are /// used to split the sequence are not returned as part of any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.characters.split(whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print( /// line.characters.split(maxSplits: 1, whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `true` for the `allowEmptySlices` parameter, so /// the returned array contains empty strings where spaces were repeated. /// /// print( /// line.characters.split( /// omittingEmptySubsequences: false, /// whereSeparator: { $0 == " " } /// ).map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the sequence satisfying the `isSeparator` predicate. /// If `true`, only nonempty subsequences are returned. The default /// value is `true`. /// - isSeparator: A closure that returns `true` if its argument should be /// used to split the sequence; otherwise, `false`. /// - Returns: An array of subsequences, split from this sequence's elements. public func split( maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Iterator.Element) throws -> Bool ) rethrows -> [AnySequence<Iterator.Element>] { _precondition(maxSplits >= 0, "Must take zero or more splits") var result: [AnySequence<Iterator.Element>] = [] var subSequence: [Iterator.Element] = [] @discardableResult func appendSubsequence() -> Bool { if subSequence.isEmpty && omittingEmptySubsequences { return false } result.append(AnySequence(subSequence)) subSequence = [] return true } if maxSplits == 0 { // We aren't really splitting the sequence. Convert `self` into an // `Array` using a fast entry point. subSequence = Array(self) appendSubsequence() return result } var iterator = self.makeIterator() while let element = iterator.next() { if try isSeparator(element) { if !appendSubsequence() { continue } if result.count == maxSplits { break } } else { subSequence.append(element) } } while let element = iterator.next() { subSequence.append(element) } appendSubsequence() return result } /// Returns a value less than or equal to the number of elements in /// the sequence, nondestructively. /// /// - Complexity: O(*n*) public var underestimatedCount: Int { return 0 } public func _preprocessingPass<R>( _ preprocess: () throws -> R ) rethrows -> R? { return nil } public func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? { return nil } /// Calls the given closure on each element in the sequence in the same order /// as a `for`-`in` loop. /// /// The two loops in the following example produce the same output: /// /// let numberWords = ["one", "two", "three"] /// for word in numberWords { /// print(word) /// } /// // Prints "one" /// // Prints "two" /// // Prints "three" /// /// numberWords.forEach { word in /// print(word) /// } /// // Same as above /// /// Using the `forEach` method is distinct from a `for`-`in` loop in two /// important ways: /// /// 1. You cannot use a `break` or `continue` statement to exit the current /// call of the `body` closure or skip subsequent calls. /// 2. Using the `return` statement in the `body` closure will exit only from /// the current call to `body`, not from any outer scope, and won't skip /// subsequent calls. /// /// - Parameter body: A closure that takes an element of the sequence as a /// parameter. public func forEach( _ body: (Iterator.Element) throws -> Void ) rethrows { for element in self { try body(element) } } } internal enum _StopIteration : Error { case stop } extension Sequence { /// Returns the first element of the sequence that satisfies the given /// predicate. /// /// The following example uses the `first(where:)` method to find the first /// negative number in an array of integers: /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// if let firstNegative = numbers.first(where: { $0 < 0 }) { /// print("The first negative number is \(firstNegative).") /// } /// // Prints "The first negative number is -2." /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element is a match. /// - Returns: The first element of the sequence that satisfies `predicate`, /// or `nil` if there is no element that satisfies `predicate`. public func first( where predicate: (Iterator.Element) throws -> Bool ) rethrows -> Iterator.Element? { var foundElement: Iterator.Element? do { try self.forEach { if try predicate($0) { foundElement = $0 throw _StopIteration.stop } } } catch is _StopIteration { } return foundElement } } extension Sequence where Iterator.Element : Equatable { /// Returns the longest possible subsequences of the sequence, in order, /// around elements equal to the given element. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string at each /// space character (" "). The first use of `split` returns each word that /// was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.characters.split(separator: " ") /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print(line.characters.split(separator: " ", maxSplits: 1) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.characters.split(separator: " ", omittingEmptySubsequences: false) /// .map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - separator: The element that should be split upon. /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each consecutive pair of `separator` /// elements in the sequence and for each instance of `separator` at the /// start or end of the sequence. If `true`, only nonempty subsequences /// are returned. The default value is `true`. /// - Returns: An array of subsequences, split from this sequence's elements. public func split( separator: Iterator.Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true ) -> [AnySequence<Iterator.Element>] { return split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: { $0 == separator }) } } extension Sequence where SubSequence : Sequence, SubSequence.Iterator.Element == Iterator.Element, SubSequence.SubSequence == SubSequence { /// Returns a subsequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the sequence, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of /// the sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence starting after the specified number of /// elements. /// /// - Complexity: O(1). public func dropFirst(_ n: Int) -> AnySequence<Iterator.Element> { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } return AnySequence(_DropFirstSequence(_iterator: makeIterator(), limit: n)) } /// Returns a subsequence containing all but the given number of final /// elements. /// /// The sequence must be finite. If the number of elements to drop exceeds /// the number of elements in the sequence, the result is an empty /// subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence leaving off the specified number of elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. public func dropLast(_ n: Int) -> AnySequence<Iterator.Element> { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements from this sequence in a holding tank, a ring buffer // of size <= n. If more elements keep coming in, pull them out of the // holding tank into the result, an `Array`. This saves // `n` * sizeof(Iterator.Element) of memory, because slices keep the entire // memory of an `Array` alive. var result: [Iterator.Element] = [] var ringBuffer: [Iterator.Element] = [] var i = ringBuffer.startIndex for element in self { if ringBuffer.count < n { ringBuffer.append(element) } else { result.append(ringBuffer[i]) ringBuffer[i] = element i = ringBuffer.index(after: i) % n } } return AnySequence(result) } /// Returns a subsequence by skipping the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `drop(while:)` method to skip over the /// positive numbers at the beginning of the `numbers` array. The result /// begins with the first element of `numbers` that does not satisfy /// `predicate`. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let startingWithNegative = numbers.drop(while: { $0 > 0 }) /// // startingWithNegative == [-2, 9, -6, 10, 1] /// /// If `predicate` matches every element in the sequence, the result is an /// empty sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A subsequence starting after the initial, consecutive elements /// that satisfy `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. /// - SeeAlso: `prefix(while:)` public func drop( while predicate: (Iterator.Element) throws -> Bool ) rethrows -> AnySequence<Iterator.Element> { return try AnySequence( _DropWhileSequence( iterator: makeIterator(), nextElement: nil, predicate: predicate)) } /// Returns a subsequence, up to the specified maximum length, containing the /// initial elements of the sequence. /// /// If the maximum length exceeds the number of elements in the sequence, /// the result contains all the elements in the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence starting at the beginning of this sequence /// with at most `maxLength` elements. /// /// - Complexity: O(1) public func prefix(_ maxLength: Int) -> AnySequence<Iterator.Element> { _precondition(maxLength >= 0, "Can't take a prefix of negative length from a sequence") if maxLength == 0 { return AnySequence(EmptyCollection<Iterator.Element>()) } return AnySequence( _PrefixSequence(_iterator: makeIterator(), maxLength: maxLength)) } /// Returns a subsequence containing the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `prefix(while:)` method to find the /// positive numbers at the beginning of the `numbers` array. Every element /// of `numbers` up to, but not including, the first negative value is /// included in the result. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let positivePrefix = numbers.prefix(while: { $0 > 0 }) /// // positivePrefix == [3, 7, 4] /// /// If `predicate` matches every element in the sequence, the resulting /// sequence contains every element of the sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A subsequence of the initial, consecutive elements that /// satisfy `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. /// - SeeAlso: `drop(while:)` public func prefix( while predicate: (Iterator.Element) throws -> Bool ) rethrows -> AnySequence<Iterator.Element> { var result: [Iterator.Element] = [] for element in self { guard try predicate(element) else { break } result.append(element) } return AnySequence(result) } } extension Sequence { /// Returns a subsequence containing all but the first element of the /// sequence. /// /// The following example drops the first element from an array of integers. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst()) /// // Prints "[2, 3, 4, 5]" /// /// If the sequence has no elements, the result is an empty subsequence. /// /// let empty: [Int] = [] /// print(empty.dropFirst()) /// // Prints "[]" /// /// - Returns: A subsequence starting after the first element of the /// sequence. /// /// - Complexity: O(1) public func dropFirst() -> SubSequence { return dropFirst(1) } /// Returns a subsequence containing all but the last element of the /// sequence. /// /// The sequence must be finite. If the sequence has no elements, the result /// is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast()) /// // Prints "[1, 2, 3, 4]" /// /// If the sequence has no elements, the result is an empty subsequence. /// /// let empty: [Int] = [] /// print(empty.dropLast()) /// // Prints "[]" /// /// - Returns: A subsequence leaving off the last element of the sequence. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. public func dropLast() -> SubSequence { return dropLast(1) } } extension Sequence { @discardableResult public func _copyContents( initializing ptr: UnsafeMutablePointer<Iterator.Element> ) -> UnsafeMutablePointer<Iterator.Element> { var p = UnsafeMutablePointer<Iterator.Element>(ptr) for x in IteratorSequence(self.makeIterator()) { p.initialize(to: x) p += 1 } return p } } // Pending <rdar://problem/14011860> and <rdar://problem/14396120>, // pass an IteratorProtocol through IteratorSequence to give it "Sequence-ness" /// A sequence built around an iterator of type `Base`. /// /// Useful mostly to recover the ability to use `for`...`in`, /// given just an iterator `i`: /// /// for x in IteratorSequence(i) { ... } public struct IteratorSequence< Base : IteratorProtocol > : IteratorProtocol, Sequence { /// Creates an instance whose iterator is a copy of `base`. public init(_ base: Base) { _base = base } /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. public mutating func next() -> Base.Element? { return _base.next() } internal var _base: Base } @available(*, unavailable, renamed: "IteratorProtocol") public typealias GeneratorType = IteratorProtocol @available(*, unavailable, renamed: "Sequence") public typealias SequenceType = Sequence extension Sequence { @available(*, unavailable, renamed: "makeIterator()") public func generate() -> Iterator { Builtin.unreachable() } @available(*, unavailable, renamed: "getter:underestimatedCount()") public func underestimateCount() -> Int { Builtin.unreachable() } @available(*, unavailable, message: "call 'split(maxSplits:omittingEmptySubsequences:whereSeparator:)' and invert the 'allowEmptySlices' argument") public func split(_ maxSplit: Int, allowEmptySlices: Bool, isSeparator: (Iterator.Element) throws -> Bool ) rethrows -> [SubSequence] { Builtin.unreachable() } } extension Sequence where Iterator.Element : Equatable { @available(*, unavailable, message: "call 'split(separator:maxSplits:omittingEmptySubsequences:)' and invert the 'allowEmptySlices' argument") public func split( _ separator: Iterator.Element, maxSplit: Int = Int.max, allowEmptySlices: Bool = false ) -> [AnySequence<Iterator.Element>] { Builtin.unreachable() } } @available(*, unavailable, renamed: "IteratorSequence") public struct GeneratorSequence<Base : IteratorProtocol> {}
apache-2.0
20df8b403658d5b35f60bb45f6acf2f9
36.789945
149
0.632629
4.286462
false
false
false
false
iCodeForever/ifanr
ifanr/ifanr/Views/NewsFlashView/NewsFlashTableViewCell.swift
1
5728
// // NewsFlashTableViewCell.swift // ifanr // // Created by sys on 16/6/30. // Copyright © 2016年 ifanrOrg. All rights reserved. // import UIKit class NewsFlashTableViewCell: UITableViewCell, Reusable { //MARK:-----init----- override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.contentView.addSubview(pointView) self.contentView.addSubview(timeLabel) self.contentView.addSubview(contentLable) self.contentView.addSubview(sourceLabel) self.setUpLayout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK:----- var model : CommonModel! { didSet { self.timeLabel.text = Date.getCommonExpressionOfDate(model.pubDate) // 设置行间距 let attrs = NSMutableAttributedString(string: model.title!) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 5.0 attrs.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, ((model.title)!.characters.count))) self.contentLable.attributedText = attrs self.sourceLabel.text = "来源:" + (model.excerpt?.components(separatedBy: "/")[2])! // self.sourceLabel.text = "来源:" } } //MARK:-----Private Function---- class func cellWithTableView(_ tableView : UITableView) -> NewsFlashTableViewCell { var cell: NewsFlashTableViewCell? = tableView.dequeueReusableCell() as NewsFlashTableViewCell? if cell == nil { cell = NewsFlashTableViewCell(style: .default, reuseIdentifier: self.reuseIdentifier) cell?.selectionStyle = .none } return cell! } // 计算内容的高度 class func estimateCellHeight(_ content : String) -> CGFloat { let size = CGSize(width: UIConstant.SCREEN_WIDTH - 64 ,height: 2000) let attrs = NSMutableAttributedString(string: content) let paragphStyle = NSMutableParagraphStyle() paragphStyle.lineSpacing = 5.0; paragphStyle.firstLineHeadIndent = 0.0; paragphStyle.hyphenationFactor = 0.0; paragphStyle.paragraphSpacingBefore = 0.0; let dic = [NSFontAttributeName : UIFont.customFont_FZLTXIHJW(fontSize: 16), NSParagraphStyleAttributeName: paragphStyle, NSKernAttributeName : 1.0] as [String : Any] attrs.addAttribute(NSFontAttributeName, value: UIFont.customFont_FZLTXIHJW(fontSize: 16), range: NSMakeRange(0, (content.characters.count))) attrs.addAttribute(NSParagraphStyleAttributeName, value: paragphStyle, range: NSMakeRange(0, (content.characters.count))) attrs.addAttribute(NSKernAttributeName, value: 1.0, range: NSMakeRange(0, (content.characters.count))) let labelRect : CGRect = content.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as [String : AnyObject], context: nil) // 50为其他控件的高度 return labelRect.height + 50; } func setUpLayout() { self.pointView.snp.makeConstraints { (make) in make.left.equalTo(self).offset(UIConstant.UI_MARGIN_12) make.top.equalTo(self).offset(20) make.height.width.equalTo(8) } self.timeLabel.snp.makeConstraints { (make) in make.left.equalTo(pointView.snp.right).offset(UIConstant.UI_MARGIN_12) make.right.equalTo(self).offset(32) make.centerY.equalTo(self.pointView) make.height.equalTo(20) } self.contentLable.snp.makeConstraints { (make) in make.left.equalTo(self).offset(32) make.right.equalTo(self).offset(-32) make.top.equalTo(self.timeLabel.snp.bottom).offset(5) make.bottom.equalTo(self.sourceLabel.snp.top).offset(-5) } self.sourceLabel.snp.makeConstraints { (make) in make.left.right.equalTo(self).offset(32) make.bottom.equalTo(self).offset(-15) make.height.equalTo(20) } self.pointView.layer.cornerRadius = 4 self.pointView.backgroundColor = UIColor(red: 211/255.0, green: 55/255.0, blue: 38/255.0, alpha: 1.0) } //MARK:-----Getter Setter----- fileprivate lazy var timeLabel : UILabel = { //时间 let timeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 20)) timeLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: 13) timeLabel.textColor = UIColor.lightGray return timeLabel; }() fileprivate lazy var pointView : UIView = { //小红点 let pointView = UIView() return pointView; }() fileprivate lazy var contentLable : UILabel = { let contentLable = UILabel() contentLable.font = UIFont.customFont_FZLTXIHJW(fontSize: 16) contentLable.numberOfLines = 0 contentLable.lineBreakMode = .byWordWrapping return contentLable }() fileprivate lazy var sourceLabel : UILabel = { let sourceLabel = UILabel() sourceLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: 12) sourceLabel.textColor = UIColor.lightGray return sourceLabel }() }
mit
7ba3448ed6ce3ded471295ea455960bb
36.516556
154
0.607237
4.813084
false
false
false
false
Cristian-A/tigress.cli
Tigress/Library/Tigress.swift
1
5350
// + -------------------------------------- + // | Tigress.swift | // | | // | Class Tigress | // | | // | Created by Cristian A. | // | Copyright © cr. All rights reserved. | // + -------------------------------------- + import Foundation /// The class gives the ability to work Fingerprints. /// /// Tigress Stripes Hash /// ==================== /// A class for handling hashes. /// ---------------------------- /// /// - author: Cristian A. /// - copyright: Copyright © cr. All rights reserved. /// class Tigress { /// The current _version_ of the class static let version = 1.0 // MARK: Digest Functions /// Returns the complete form of the Tigress hash. /// - returns: The hash in _hex_ string representation. static func stripeHash(of: String) -> String { var x: Bytes = Bytes() for c in of.unicodeScalars { x.append(Byte(c.value)) } x = normalize(data: x) x = core(data: x) var stripe: String = "" for b in x.values { let z = hexCast(byte: b) stripe += z } return stripe } /// Returns a shorthand form of the Tigress hash. /// - returns: The shorthand string of the hash. static func pawHash(of: String) -> String { var x: Bytes = Bytes() for c in of.unicodeScalars { x.append(Byte(c.value)) } x = normalize(data: x) x = core(data: x) var paw: String = "" for b in x.values { let z = pawCast(byte: b) paw.characters.append(z) } return paw } // MARK: Kernel Functions /// Normalize the given input in /// fixed length output of _128 bits_. /// - parameters: /// - data: The bytes to normalize. /// - returns: The normalized bytes. private static func normalize(data: Bytes) -> Bytes { let x: Bytes = data if x.count == 0 { // Se l'input risulta nullo: for i in 0 ..< 16 { // Inserisco 16 Bytes [0 ... 15]. x.append(Byte(i)) } } else if x.count < 16 { // Se l'input non è sufficientemente lungo: let y = x.count for i in 0 ..< 16 - y { // Allora inserisco dati ricavati con Fibonacci. // fino a raggiungere la lunghezza desiderata. let f: Byte = Byte(fibonacci(n: UInt(i)) % 255) let z: Byte = data[i] ^ f x.append(Byte(z % 255)) } } else if x.count > 16 { // Se l'input risulta soddifacente: while x.count > 16 { // Lo riduco modificando la posizione n // ricavata dal primo elemento, con uno // xor con posizione x. Rimuovo il primo. let s = x[Int(x[0])] x[Int(x[0])] ^= x[0] ^ x[Int(s)] x.removeFirst() } } for i in 0 ... 16 { // Mischio i dati con soluzione analoga. let s = x[Int(x[i + 3])] x[Int(x[i])] ^= x[i + 1] ^ x[Int(s)] } return x } /// Mix the given Bytes. /// - parameters: /// - data: The bytes to mix. /// - returns: The mixed bytes. private static func core(data: Bytes) -> Bytes { var x: Bytes = data // Mixing Bytes for _ in 0 ..< 16 { for i in 0 ..< 4 { for j in 0 ..< 4 { let index = j + i * 4 + 1 let w = ~x[index - 1] x[index] = ~x[index] ^ w } for j in 0 ..< 4 { let w = j + i * 4 x[w] = j % 2 == 0 ? x[w] >>> 1 : x[w] <<< 1 } } let t = x.removeFirst() x.append(t) } // Transform data from bytes to bits var y = Bits(bitCount: 128) for i in 0 ..< 16 { y.append(data[i]) } // Shift bits by N bits to randomize output y = y >>> UInt(Int((y.evenBitsSum() % y.count - 1) + 1)) y = y <<< UInt(Int((y.oddBitsSum() % y.count - 1) + 1)) // Cast the output back to Bytes x = Bytes() for i in 0 ..< 16 { var z: Byte = 0 for j in 0 ..< 8 { z = z <<= y[i * 8 + j] } x.append(z) } return x } // MARK: Low Level functions /// Gets the _nth_ Fibonacci number. /// /// Complexity: O(2^N) /// ------------------ /// Where n is the _nth_ element we want to reach. /// - parameters: /// - n: The wanted element. /// - returns: The _nth_ value in the sequence. private static func fibonacci(n: UInt) -> Int64 { return n < 2 ? Int64(n) : fibonacci(n: n - 1) + fibonacci(n: n - 2) } // MARK: Casting /// Converts a _byte_ into one character. /// /// It's used for getting a shorthand /// version of the hex rappresentation. /// The final string is called **paw**. /// /// Complexity: O(1) /// ---------------- /// - parameters: /// - byte: The _byte_ to convert. /// - returns: The converted _character_. private static func pawCast(byte: Byte) -> Character { if byte > 251 { return "0" } let x: Int = Int(byte) % 36 var y: Character = "A" if x < 26 { let startingValue = Int(("A" as UnicodeScalar).value) y = Character(UnicodeScalar(x + startingValue)!) } else { let startingValue = Int(("0" as UnicodeScalar).value) y = Character(UnicodeScalar(x + startingValue - 26)!) } return y } /// Converts a _byte_ into its hex rappresentation. /// /// It's used for getting the complete hash. /// /// Complexity: O(1) /// ---------------- /// - parameters: /// - byte: The _byte_ to convert. /// - returns: The converted _string_. private static func hexCast(byte: Byte) -> String { let x = Data(bytes: [byte]) let y = x.map { String(format: "%02hhx", $0) }.joined() return y.uppercased() } }
mit
7d7d8dcecfbdae171adc70251987be9b
22.659292
69
0.539555
2.928258
false
false
false
false
MobileToolkit/Tesseract
Tesseract/RestfulClient+PATCH.swift
2
2114
// // RestfulClient+PATCH.swift // Tesseract // // Created by Sebastian Owodzin on 08/09/2015. // Copyright © 2015 mobiletoolkit.org. All rights reserved. // import Foundation extension RestfulClient { public func PATCH<T where T: RestfulCollection, T: RestfulCollectionObject>(objectType: T.Type, objectID: AnyObject, payload: Payload, completionHandler: (Dictionary<String, AnyObject>?, NSError?) -> Void) { let request = NSMutableURLRequest(URL: RestfulClient.buildEndpointURL(objectType.collectionObjectURIPath(), uriParams: URIParams(attributes: [objectType.collectionObjectIDAttribute(): objectID], queryParams: nil))!) request.HTTPMethod = "PATCH" request.HTTPBody = payload.HTTPBody() if payload is FormPayload { request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") } else { request.setValue("application/json", forHTTPHeaderField: "Content-Type") } let dataTask = urlSession.dataTaskWithRequest(request) { (data, response, error) -> Void in if let error = error { completionHandler(nil, error) } else { let httpResponse = response as! NSHTTPURLResponse if 200 == httpResponse.statusCode { if let data = data { do { let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) completionHandler((json as! Dictionary<String, AnyObject>), nil) } catch let error as NSError { completionHandler(nil, error) } } else { completionHandler(nil, nil) } } else { completionHandler(nil, RestfulClient.buildTesseractError(.PATCH, response: httpResponse, responseData: data)) } } } dataTask.resume() } }
mit
ee713ba2839b0bb2c2cac7b1c9530678
41.26
223
0.572646
5.37659
false
false
false
false
brentdax/swift
test/stdlib/Metal.swift
3
11710
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -o %t/a.out4 -swift-version 4 && %target-codesign %t/a.out4 && %target-run %t/a.out4 // REQUIRES: objc_interop // UNSUPPORTED: OS=watchos // REQUIRES: executable_test import StdlibUnittest import Metal var MetalTests = TestSuite("Metal") if #available(OSX 10.13, iOS 11.0, tvOS 11.0, *) { // Call each overlay to ensure nothing explodes MetalTests.test("MTLArgumentEncoder") { func apiAvailabilityTest() { /* Setup */ let device = MTLCreateSystemDefaultDevice()! let buf = device.makeBuffer( length: 64, options: MTLResourceOptions.storageModeShared)! let texDesc = MTLTextureDescriptor() texDesc.usage = MTLTextureUsage.renderTarget let tex = device.makeTexture(descriptor: texDesc)! let smplr = device.makeSamplerState(descriptor: MTLSamplerDescriptor()) var arguments = [MTLArgumentDescriptor]() arguments.append(MTLArgumentDescriptor()) arguments.append(MTLArgumentDescriptor()) arguments.append(MTLArgumentDescriptor()) arguments[0].dataType = MTLDataType.pointer arguments[0].index = 0 arguments[1].dataType = MTLDataType.texture arguments[1].index = 1 arguments[2].dataType = MTLDataType.sampler arguments[2].index = 2 if #available(OSX 10.14, iOS 12.0, tvOS 12.0, *){ arguments.append(MTLArgumentDescriptor()) arguments[3].dataType = MTLDataType.indirectCommandBuffer arguments[3].index = 3 } /* Call APIs */ let argEncoder = device.makeArgumentEncoder(arguments: arguments)! argEncoder.setArgumentBuffer(buf, offset: 0) argEncoder.setBuffers([buf], offsets: [0], range: 0..<1) argEncoder.setTextures([tex], range: 1..<2) argEncoder.setSamplerStates([smplr], range: 2..<3) if #available(OSX 10.14, iOS 12.0, tvOS 12.0, *){ let icbDesc = MTLIndirectCommandBufferDescriptor() icbDesc.commandTypes = [.draw, .drawIndexed] icbDesc.inheritBuffers = false icbDesc.maxVertexBufferBindCount = 1 icbDesc.maxFragmentBufferBindCount = 1 let icb = device.makeIndirectCommandBuffer (descriptor: icbDesc, maxCommandCount: 1, options: MTLResourceOptions.storageModeShared )! argEncoder.setIndirectCommandBuffers([icb], range: 3..<4) } } } MetalTests.test("MTLBlitCommandEncoder") { func apiAvailabilityTest() { /* Setup */ let device = MTLCreateSystemDefaultDevice()! let queue = device.makeCommandQueue()! let cmdBuf = queue.makeCommandBuffer()! let bltCmdEncdr = cmdBuf.makeBlitCommandEncoder()! /* Call APIs */ let buf = device.makeBuffer(length: 4, options: MTLResourceOptions())! bltCmdEncdr.fill(buffer: buf, range: 0..<buf.length, value: 0) if #available(OSX 10.14, iOS 12.0, tvOS 12.0, *){ let icbDesc = MTLIndirectCommandBufferDescriptor() icbDesc.commandTypes = [.draw, .drawIndexed] icbDesc.inheritBuffers = false icbDesc.maxVertexBufferBindCount = 1 icbDesc.maxFragmentBufferBindCount = 1 let icb1 = device.makeIndirectCommandBuffer (descriptor: icbDesc, maxCommandCount: 4, options: MTLResourceOptions.storageModeShared )! let icb2 = device.makeIndirectCommandBuffer (descriptor: icbDesc, maxCommandCount: 4, options: MTLResourceOptions.storageModeShared )! bltCmdEncdr.resetCommandsInBuffer (icb1, range:0..<5) bltCmdEncdr.resetCommandsInBuffer (icb2, range:0..<5) bltCmdEncdr.copyIndirectCommandBuffer (icb1, sourceRange: 0..<5, destination: icb2, destinationIndex:0) bltCmdEncdr.optimizeIndirectCommandBuffer (icb1, range:0..<5) } bltCmdEncdr.endEncoding() } } if #available(OSX 10.14, iOS 12.0, tvOS 12.0, *){ MetalTests.test("MTLIndirectCommandBuffer"){ func apiAvailabilityTest() { /* Setup */ let device = MTLCreateSystemDefaultDevice()! let queue = device.makeCommandQueue()! let cmdBuf = queue.makeCommandBuffer()! let texDesc = MTLTextureDescriptor() texDesc.usage = MTLTextureUsage.renderTarget let tex = device.makeTexture(descriptor: texDesc)! let rpDesc = MTLRenderPassDescriptor() rpDesc.colorAttachments[0].texture = tex let buf = device.makeBuffer(length: 4, options: MTLResourceOptions.storageModeShared)! let icbDesc = MTLIndirectCommandBufferDescriptor() icbDesc.commandTypes = [.draw, .drawIndexed] icbDesc.inheritBuffers = false icbDesc.maxVertexBufferBindCount = 1 icbDesc.maxFragmentBufferBindCount = 1 let icb = device.makeIndirectCommandBuffer(descriptor: icbDesc, maxCommandCount: 4, options: MTLResourceOptions.storageModeShared )! /* Call APIs */ let encoder = cmdBuf.makeRenderCommandEncoder(descriptor: rpDesc)! let cmd = icb.indirectRenderCommandAt(0) cmd.setVertexBuffer(buf, offset: 0, at: 0) cmd.setFragmentBuffer(buf, offset: 0, at: 0) cmd.drawPrimitives(MTLPrimitiveType.triangle, vertexStart: 0, vertexCount: 0, instanceCount: 0, baseInstance: 0) let cmd2 = icb.indirectRenderCommandAt(1) cmd2.drawIndexedPrimitives(MTLPrimitiveType.triangle, indexCount: 0, indexType: MTLIndexType.uint16, indexBuffer: buf, indexBufferOffset: 0, instanceCount: 0, baseVertex: 0, baseInstance: 0) let cmd3 = icb.indirectRenderCommandAt(2) cmd3.reset() icb.reset(0..<5) encoder.executeCommandsInBuffer(icb, range:0..<5) encoder.endEncoding() } } } MetalTests.test("MTLBuffer") { func apiAvailabilityTest() { /* Setup */ let device = MTLCreateSystemDefaultDevice()! #if os(macOS) let options = MTLResourceOptions.storageModeManaged #else let options = MTLResourceOptions.storageModePrivate #endif let buf = device.makeBuffer(length: 4, options: options)! /* Call APIs */ #if os(macOS) buf.didModifyRange(0..<4) #endif buf.addDebugMarker("test marker", range: 0..<4) } } MetalTests.test("MTLComputeCommandEncoder") { func apiAvailabilityTest(heapDesc: MTLHeapDescriptor) { /* Setup */ let device = MTLCreateSystemDefaultDevice()! let queue = device.makeCommandQueue()! let cmdBuf = queue.makeCommandBuffer()! #if os(macOS) let options = MTLResourceOptions.storageModeManaged #else let options = MTLResourceOptions.storageModePrivate #endif let buf = device.makeBuffer(length: 4, options: options)! let tex = device.makeTexture(descriptor: MTLTextureDescriptor())! heapDesc.size = 4 let heap = device.makeHeap(descriptor: heapDesc)! let smplr = device.makeSamplerState(descriptor: MTLSamplerDescriptor()) /* Call APIs */ let encoder = cmdBuf.makeComputeCommandEncoder()! encoder.useResources([buf], usage: MTLResourceUsage.read) encoder.useHeaps([heap]) encoder.setBuffers([buf], offsets: [0], range: 0..<1) encoder.setTextures([tex], range: 0..<1) encoder.setSamplerStates([smplr], range: 0..<1) encoder.setSamplerStates( [smplr], lodMinClamps: [0], lodMaxClamps: [0], range: 0..<1) if #available(macOS 10.14, iOS 12.0, tvOS 12.0, *) { encoder.memoryBarrier(resources: [buf]) /* encoder.memoryBarrier(scope: MTLBarrierScope.buffers) */ } encoder.endEncoding() } } MetalTests.test("MTLDevice") { func apiAvailabilityTest() { /* Setup */ let device = MTLCreateSystemDefaultDevice()! /* Call APIs */ var samplePositions : [MTLSamplePosition] if (device.supportsTextureSampleCount(2)) { samplePositions = device.getDefaultSamplePositions(sampleCount: 2) } else if (device.supportsTextureSampleCount(4)) { samplePositions = device.getDefaultSamplePositions(sampleCount: 4) } else { expectUnreachable("device unexpectedly does not support sample count 2 or 4") } } } MetalTests.test("MTLFunctionConstantValues") { func apiAvailabilityTest() { /* Call APIs */ let vals = MTLFunctionConstantValues() vals.setConstantValues([0], type: MTLDataType.float, range: 0..<1) } } MetalTests.test("MTLRenderCommandEncoder") { func apiAvailabilityTest(heapDesc: MTLHeapDescriptor) { /* Setup */ let device = MTLCreateSystemDefaultDevice()! let queue = device.makeCommandQueue()! let cmdBuf = queue.makeCommandBuffer()! #if os(macOS) let options = MTLResourceOptions.storageModeManaged #else let options = MTLResourceOptions.storageModePrivate #endif let buf = device.makeBuffer(length: 4, options: options)! let texDesc = MTLTextureDescriptor() texDesc.usage = MTLTextureUsage.renderTarget let tex = device.makeTexture(descriptor: texDesc)! heapDesc.size = 4 let heap = device.makeHeap(descriptor: heapDesc)! let smplr = device.makeSamplerState(descriptor: MTLSamplerDescriptor()) let rpDesc = MTLRenderPassDescriptor() rpDesc.colorAttachments[0].texture = tex /* Call APIs */ let encoder = cmdBuf.makeRenderCommandEncoder(descriptor: rpDesc)! encoder.useResources([buf], usage: MTLResourceUsage.read) encoder.useHeaps([heap]) #if os(macOS) encoder.setViewports([MTLViewport()]) encoder.setScissorRects([MTLScissorRect(x:0, y:0, width:1, height:1)]) #endif encoder.setVertexBuffers([buf], offsets: [0], range: 0..<1) encoder.setVertexTextures([tex], range: 0..<1) encoder.setVertexSamplerStates([smplr], range: 0..<1) encoder.setVertexSamplerStates( [smplr], lodMinClamps: [0], lodMaxClamps: [0], range: 0..<1) encoder.setFragmentBuffers([buf], offsets: [0], range: 0..<1) encoder.setFragmentTextures([tex], range: 0..<1) encoder.setFragmentSamplerStates([smplr], range: 0..<1) encoder.setFragmentSamplerStates( [smplr], lodMinClamps: [0], lodMaxClamps: [0], range: 0..<1) #if os(iOS) encoder.setTileBuffers([buf], offsets: [0], range: 0..<1) encoder.setTileTextures([tex], range: 0..<1) encoder.setTileSamplerStates([smplr], range: 0..<1) encoder.setTileSamplerStates( [smplr], lodMinClamps: [0], lodMaxClamps: [0], range: 0..<1) #endif #if os(OSX) if #available(macOS 10.14, *) { encoder.memoryBarrier(resources: [buf], after:MTLRenderStages.fragment, before:MTLRenderStages.vertex) /* encoder.memoryBarrier(scope: MTLBarrierScope.renderTargets, after:MTLRenderStages.fragment, before:MTLRenderStages.vertex) */ } #endif encoder.endEncoding() } } MetalTests.test("MTLRenderPassDescriptor") { func apiAvailabilityTest() { /* Setup */ let rpDesc = MTLRenderPassDescriptor() /* Call APIs */ rpDesc.setSamplePositions( [MTLSamplePosition(x:0.25,y:0.75), MTLSamplePosition(x:0.75, y:0.25)]) _ = rpDesc.getSamplePositions() } } MetalTests.test("MTLTexture") { func apiAvailabilityTest() { /* Setup */ let device = MTLCreateSystemDefaultDevice()! let texDesc = MTLTextureDescriptor() texDesc.usage = MTLTextureUsage.renderTarget let tex = device.makeTexture(descriptor: texDesc)! /* Call APIs */ let _ = tex.makeTextureView( pixelFormat: texDesc.pixelFormat, textureType: texDesc.textureType, levels: 0..<1, slices: 0..<1) } } } runAllTests()
apache-2.0
1f065280c4ff22bb4439e7efe3635470
34.592705
196
0.667378
4.450779
false
true
false
false
badoo/Chatto
ChattoAdditions/Tests/Chat Items/BaseMessage/BaseMessagePresenterTests.swift
1
5039
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. 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 import Chatto @testable import ChattoAdditions class BaseMessagePresenterTests: XCTestCase { // BaseMessagePresenter is generic, let's use the photo one for instance var presenter: PhotoMessagePresenter<PhotoMessageViewModelDefaultBuilder<PhotoMessageModel<MessageModel>>, PhotoMessageTestHandler>! let decorationAttributes = ChatItemDecorationAttributes(bottomMargin: 0, messageDecorationAttributes: BaseMessageDecorationAttributes()) var interactionHandler: PhotoMessageTestHandler! override func setUp() { super.setUp() let viewModelBuilder = PhotoMessageViewModelDefaultBuilder<PhotoMessageModel<MessageModel>>() let sizingCell = PhotoMessageCollectionViewCell.sizingCell() let photoStyle = PhotoMessageCollectionViewCellDefaultStyle() let baseStyle = BaseMessageCollectionViewCellDefaultStyle() let messageModel = MessageModel(uid: "uid", senderId: "senderId", type: "photo-message", isIncoming: true, date: Date(), status: .success) let photoMessageModel = PhotoMessageModel(messageModel: messageModel, imageSize: CGSize(width: 30, height: 30), image: UIImage()) self.interactionHandler = PhotoMessageTestHandler() self.presenter = PhotoMessagePresenter(messageModel: photoMessageModel, viewModelBuilder: viewModelBuilder, interactionHandler: self.interactionHandler, sizingCell: sizingCell, baseCellStyle: baseStyle, photoCellStyle: photoStyle) } func testThat_WhenCellIsTappedOnFailIcon_ThenInteractionHandlerHandlesEvent() { let cell = PhotoMessageCollectionViewCell(frame: CGRect.zero) self.presenter.configureCell(cell, decorationAttributes: self.decorationAttributes) cell.failedButtonTapped() XCTAssertTrue(self.interactionHandler.didHandleTapOnFailIcon) } func testThat_WhenCellIsTappedOnBubble_ThenInteractionHandlerHandlesEvent() { let cell = PhotoMessageCollectionViewCell(frame: CGRect.zero) self.presenter.configureCell(cell, decorationAttributes: self.decorationAttributes) cell.bubbleTapped(UITapGestureRecognizer()) XCTAssertTrue(self.interactionHandler.didHandleTapOnBubble) } func testThat_WhenCellIsDoubleTappedOnBubble_ThenInteractionHandlerHandlesEvent() { let cell = PhotoMessageCollectionViewCell(frame: CGRect.zero) self.presenter.configureCell(cell, decorationAttributes: self.decorationAttributes) cell.bubbleDoubleTapped(UITapGestureRecognizer()) XCTAssertTrue(self.interactionHandler.didHandleDoubleTapOnBubble) } func testThat_WhenCellIsBeginLongPressOnBubble_ThenInteractionHandlerHandlesEvent() { let cell = PhotoMessageCollectionViewCell(frame: CGRect.zero) self.presenter.configureCell(cell, decorationAttributes: self.decorationAttributes) cell.onBubbleLongPressBegan?(cell) XCTAssertTrue(self.interactionHandler.didHandleBeginLongPressOnBubble) } func testThat_WhenCellIsEndLongPressOnBubble_ThenInteractionHandlerHandlesEvent() { let cell = PhotoMessageCollectionViewCell(frame: CGRect.zero) self.presenter.configureCell(cell, decorationAttributes: self.decorationAttributes) cell.onBubbleLongPressEnded?(cell) XCTAssertTrue(self.interactionHandler.didHandleEndLongPressOnBubble) } func testThat_WhenProvideDecorationAttributes_ThenViewModelIsUpdated() { let cell = PhotoMessageCollectionViewCell(frame: CGRect.zero) let messageDecorationAttributes = BaseMessageDecorationAttributes(canShowFailedIcon: false) let decorationAttributes = ChatItemDecorationAttributes(bottomMargin: 0, messageDecorationAttributes: messageDecorationAttributes) self.presenter.configureCell(cell, decorationAttributes: decorationAttributes) XCTAssertFalse(self.presenter.messageViewModel.decorationAttributes.canShowFailedIcon) } }
mit
5c50e6596aba0b1f0c78744229d95b49
55.617978
238
0.789045
5.567956
false
true
false
false
noppoMan/aws-sdk-swift
CodeGenerator/Sources/CodeGenerator/Models/Paginator.swift
1
3575
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // Used to decode model paginators_2.json files struct Paginators: Decodable { struct Paginator: Decodable { var inputTokens: [String]? var outputTokens: [String]? var moreResults: String? var limitKey: String? var resultKey: [String]? init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if let value = try container.decodeArrayIfPresent(String.self, forKey: .inputToken) { self.inputTokens = value } else { self.inputTokens = try container.decodeIfPresent([String].self, forKey: .inputTokens) } if let value = try container.decodeArrayIfPresent(String.self, forKey: .outputToken) { self.outputTokens = value } else { self.outputTokens = try container.decodeIfPresent([String].self, forKey: .outputTokens) } self.moreResults = try container.decodeIfPresent(String.self, forKey: .moreResults) self.limitKey = try container.decodeIfPresent(String.self, forKey: .limitKey) self.resultKey = try container.decodeArrayIfPresent(String.self, forKey: .resultKey) } private enum CodingKeys: String, CodingKey { case inputToken = "input_token" case outputToken = "output_token" case inputTokens = "input_tokens" case outputTokens = "output_tokens" case moreResults = "more_results" case limitKey = "limit_key" case resultKey = "result_key" } } var pagination: [String: Paginator] } extension KeyedDecodingContainer { func decodeArray(_ type: String.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> [String] { do { return [try self.decode(String.self, forKey: key)] } catch { return try self.decode([String].self, forKey: key) } } func decodeArrayIfPresent(_ type: String.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> [String]? { do { if let value = try self.decodeIfPresent(String.self, forKey: key) { return [value] } else { return nil } } catch { return try self.decodeIfPresent([String].self, forKey: key) } } func decodeArray<T>(_ type: T.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> [T] where T: Decodable { do { return [try self.decode(T.self, forKey: key)] } catch { return try self.decode([T].self, forKey: key) } } func decodeArrayIfPresent<T>(_ type: T.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> [T]? where T: Decodable { do { if let value = try self.decodeIfPresent(T.self, forKey: key) { return [value] } else { return nil } } catch { return try self.decodeIfPresent([T].self, forKey: key) } } }
apache-2.0
3e535b4afd901ad76bfaa9c25169c6df
36.239583
127
0.566713
4.654948
false
false
false
false
vector-im/vector-ios
Riot/Modules/Threads/ThreadList/ThreadListViewController.swift
1
14920
// File created from ScreenTemplate // $ createScreen.sh Threads/ThreadList ThreadList /* Copyright 2021 New Vector Ltd 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 final class ThreadListViewController: UIViewController { // MARK: - Properties // MARK: Outlets @IBOutlet private weak var threadsTableView: UITableView! @IBOutlet private weak var emptyView: ThreadListEmptyView! // MARK: Private private var viewModel: ThreadListViewModelProtocol! private var theme: Theme! private var keyboardAvoider: KeyboardAvoider? private var errorPresenter: MXKErrorPresentation! private var activityPresenter: ActivityIndicatorPresenter! private var titleView: ThreadRoomTitleView! // MARK: - Setup class func instantiate(with viewModel: ThreadListViewModelProtocol) -> ThreadListViewController { let viewController = StoryboardScene.ThreadListViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setupViews() self.keyboardAvoider = KeyboardAvoider(scrollViewContainerView: self.view, scrollView: self.threadsTableView) self.activityPresenter = ActivityIndicatorPresenter() self.errorPresenter = MXKErrorAlertPresentation() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.viewDelegate = self self.viewModel.process(viewAction: .loadData) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.keyboardAvoider?.startAvoiding() AnalyticsScreenTracker.trackScreen(.threadList) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.keyboardAvoider?.stopAvoiding() } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { guard let titleView = self.titleView else { return } if UIApplication.shared.statusBarOrientation.isPortrait { titleView.updateLayout(for: .landscapeLeft) } else { titleView.updateLayout(for: .portrait) } } // MARK: - Private private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } emptyView.update(theme: theme) emptyView.backgroundColor = theme.colors.background self.threadsTableView.backgroundColor = theme.backgroundColor self.threadsTableView.separatorColor = theme.colors.separator self.threadsTableView.reloadData() } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { let titleView = ThreadRoomTitleView.loadFromNib() titleView.mode = .allThreads titleView.configure(withModel: viewModel.titleModel) titleView.updateLayout(for: UIApplication.shared.statusBarOrientation) self.titleView = titleView navigationItem.leftItemsSupplementBackButton = true vc_removeBackTitle() navigationItem.leftBarButtonItem = UIBarButtonItem(customView: titleView) navigationItem.rightBarButtonItem = UIBarButtonItem(image: Asset.Images.threadsFilter.image, style: .plain, target: self, action: #selector(filterButtonTapped(_:))) self.threadsTableView.tableFooterView = UIView() self.threadsTableView.register(cellType: ThreadTableViewCell.self) self.threadsTableView.keyboardDismissMode = .interactive } private func render(viewState: ThreadListViewState) { switch viewState { case .idle: break case .loading: renderLoading() case .loaded: renderLoaded() case .empty(let model): renderEmptyView(withModel: model) case .showingFilterTypes: renderShowingFilterTypes() case .showingLongPressActions(let index): renderShowingLongPressActions(index) case .share(let url, let index): renderShare(url, index: index) case .toastForCopyLink: toastForCopyLink() case .error(let error): render(error: error) } } private func renderLoading() { emptyView.isHidden = true threadsTableView.isHidden = true self.activityPresenter.presentActivityIndicator(on: self.view, animated: true) } private func renderLoaded() { self.activityPresenter.removeCurrentActivityIndicator(animated: true) threadsTableView.isHidden = false self.threadsTableView.reloadData() navigationItem.rightBarButtonItem?.isEnabled = true switch viewModel.selectedFilterType { case .all: navigationItem.rightBarButtonItem?.image = Asset.Images.threadsFilter.image case .myThreads: navigationItem.rightBarButtonItem?.image = Asset.Images.threadsFilterApplied.image } } private func renderEmptyView(withModel model: ThreadListEmptyModel) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) emptyView.configure(withModel: model) threadsTableView.isHidden = true emptyView.isHidden = false navigationItem.rightBarButtonItem?.isEnabled = viewModel.selectedFilterType == .myThreads switch viewModel.selectedFilterType { case .all: navigationItem.rightBarButtonItem = nil case .myThreads: navigationItem.rightBarButtonItem?.image = Asset.Images.threadsFilterApplied.image } } private func renderShowingFilterTypes() { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let allThreadsAction = UIAlertAction(title: ThreadListFilterType.all.title, style: .default, handler: { [weak self] action in guard let self = self else { return } self.viewModel.process(viewAction: .selectFilterType(.all)) }) if self.viewModel.selectedFilterType == .all { allThreadsAction.setValue(true, forKey: "checked") } alertController.addAction(allThreadsAction) let myThreadsAction = UIAlertAction(title: ThreadListFilterType.myThreads.title, style: .default, handler: { [weak self] action in guard let self = self else { return } self.viewModel.process(viewAction: .selectFilterType(.myThreads)) }) if self.viewModel.selectedFilterType == .myThreads { myThreadsAction.setValue(true, forKey: "checked") } alertController.addAction(myThreadsAction) alertController.addAction(UIAlertAction(title: VectorL10n.cancel, style: .cancel, handler: nil)) alertController.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem self.present(alertController, animated: true, completion: nil) } private func renderShowingLongPressActions(_ index: Int) { let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) controller.addAction(UIAlertAction(title: VectorL10n.roomEventActionViewInRoom, style: .default, handler: { [weak self] action in guard let self = self else { return } self.viewModel.process(viewAction: .actionViewInRoom) })) controller.addAction(UIAlertAction(title: VectorL10n.threadCopyLinkToThread, style: .default, handler: { [weak self] action in guard let self = self else { return } self.viewModel.process(viewAction: .actionCopyLinkToThread) })) controller.addAction(UIAlertAction(title: VectorL10n.roomEventActionShare, style: .default, handler: { [weak self] action in guard let self = self else { return } self.viewModel.process(viewAction: .actionShare) })) controller.addAction(UIAlertAction(title: VectorL10n.cancel, style: .cancel, handler: nil)) if let cell = threadsTableView.cellForRow(at: IndexPath(row: index, section: 0)) { controller.popoverPresentationController?.sourceView = cell } else { controller.popoverPresentationController?.sourceView = view } self.present(controller, animated: true, completion: nil) } private func renderShare(_ url: URL, index: Int) { let activityVC = UIActivityViewController(activityItems: [url], applicationActivities: nil) activityVC.modalTransitionStyle = .coverVertical if let cell = threadsTableView.cellForRow(at: IndexPath(row: index, section: 0)) { activityVC.popoverPresentationController?.sourceView = cell } else { activityVC.popoverPresentationController?.sourceView = view } present(activityVC, animated: true, completion: nil) } private func toastForCopyLink() { view.vc_toast(message: VectorL10n.roomEventCopyLinkInfo, image: Asset.Images.linkIcon.image) } private func render(error: Error) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil) } // MARK: - Actions @objc private func filterButtonTapped(_ sender: UIBarButtonItem) { self.viewModel.process(viewAction: .showFilterTypes) Analytics.shared.trackInteraction(.threadListFilterItem) } @IBAction private func longPressed(_ sender: UILongPressGestureRecognizer) { guard sender.state == .began else { return } let point = sender.location(in: threadsTableView) guard let indexPath = threadsTableView.indexPathForRow(at: point) else { return } guard let cell = threadsTableView.cellForRow(at: indexPath) else { return } if cell.isHighlighted { viewModel.process(viewAction: .longPressThread(indexPath.row)) } } } // MARK: - ThreadListViewModelViewDelegate extension ThreadListViewController: ThreadListViewModelViewDelegate { func threadListViewModel(_ viewModel: ThreadListViewModelProtocol, didUpdateViewState viewSate: ThreadListViewState) { self.render(viewState: viewSate) } } // MARK: - UITableViewDataSource extension ThreadListViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.numberOfThreads } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: ThreadTableViewCell = tableView.dequeueReusableCell(for: indexPath) cell.update(theme: theme) if let threadModel = viewModel.threadModel(at: indexPath.row) { cell.configure(withModel: threadModel) } return cell } } // MARK: - UITableViewDelegate extension ThreadListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.backgroundColor = theme.backgroundColor cell.selectedBackgroundView = UIView() cell.selectedBackgroundView?.backgroundColor = theme.selectedBackgroundColor } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) viewModel.process(viewAction: .selectThread(indexPath.row)) Analytics.shared.trackInteraction(.threadListThreadItem) } } // MARK: - ThreadListEmptyViewDelegate extension ThreadListViewController: ThreadListEmptyViewDelegate { func threadListEmptyViewTappedShowAllThreads(_ emptyView: ThreadListEmptyView) { viewModel.process(viewAction: .selectFilterType(.all)) } }
apache-2.0
0f47892235b8eea93bde8ce20144c3b6
38.786667
137
0.619303
5.965614
false
false
false
false
RylynnLai/V2EX_sf
V2EXData/RLNodesHelper.swift
1
1566
// // RLNodesHelper.swift // V2EX // // Created by LLZ on 16/5/13. // Copyright © 2016年 LLZ. All rights reserved. // import Foundation import Alamofire class RLNodesHelper: NSObject { static let shareNodesHelper = RLNodesHelper()//单例 private override init() {}//防止外部用init()或者()来初始化这个单例 func nodeWithNodeID(ID:NSNumber, completion:(node:Node?) -> Void) { let path = "/api/nodes/show.json?id=\(ID)" Alamofire.request(.GET, mainURLStr + path).responseJSON { (response) in guard response.result.isSuccess else { print("Error 获取话题失败: \(response.result.error)") completion(node: .None) return } if let responseJSON = response.result.value as? NSDictionary { let node = Node.createNode(fromKeyValues: responseJSON) completion(node: node) } } } func nodesWithCompletion(completion:(nodes:[Node]?) -> Void) { Alamofire.request(.GET, mainURLStr + "/api/nodes/all.json").responseJSON { (response) in guard response.result.isSuccess else { print("Error 获取所有节点数据失败: \(response.result.error)") return } if let responseJSON = response.result.value as? [NSDictionary] { let nodes = Node.createNodesArray(fromKeyValuesArray: responseJSON) completion(nodes: nodes) } } } }
mit
9b85ce9006686c97961df89c3d730f36
32.111111
96
0.580255
4.315942
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Two Pointers/244_Shortest Word Distance II.swift
1
2289
// 244_Shortest Word Distance II // https://leetcode.com/problems/shortest-word-distance-ii/ // // Created by Honghao Zhang on 10/18/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters. // //Example: //Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. // //Input: word1 = “coding”, word2 = “practice” //Output: 3 //Input: word1 = "makes", word2 = "coding" //Output: 1 //Note: //You may assume that word1 does not equal to word2, and word1 and word2 are both in the list. // // 之前那个题目是一次function call,找一次 // 这个题目是设计一个class,function会被call很多次 // 找两个word的最小距离,但是需要初始化一下 // 就是找两个Int array中最小的差值 import Foundation class Num244 { // MARK: - Two Indices class WordDistance { // 每个单词对应的indice list var wordIndices: [String: [Int]] = [:] init(_ words: [String]) { for i in 0..<words.count { wordIndices[words[i]] = (wordIndices[words[i]] ?? []) + [i] } } // 在两个数组中找最小的差值,用双index,每次循环update最小差值 // 然后增加小的那个index func shortest(_ word1: String, _ word2: String) -> Int { let indices1 = wordIndices[word1]! let indices2 = wordIndices[word2]! guard indices1.count > 0, indices2.count > 0 else { return 0 } var i1 = 0 var i2 = 0 var minDistance = Int.max while i1 < indices1.count, i2 < indices2.count { minDistance = min(minDistance, abs(indices1[i1] - indices2[i2])) if minDistance == 0 { return minDistance } if indices1[i1] < indices2[i2] { i1 += 1 } else { i2 += 1 } } return minDistance } } /** * Your WordDistance object will be instantiated and called as such: * let obj = WordDistance(words) * let ret_1: Int = obj.shortest(word1, word2) */ }
mit
25d1ee1ecc95a0ea5e31d2a5212ae03e
28
275
0.630268
3.400651
false
true
false
false
emilletfr/domo-server-vapor
Sources/App/Model/IndoorTempService.swift
2
1312
// // IndoorTempManager.swift // VaporApp // // Created by Eric on 26/09/2016. // // import Dispatch import RxSwift final class IndoorTempService : IndoorTempServicable { let temperatureObserver = PublishSubject<Double>() let humidityObserver = PublishSubject<Int>() let httpClient : HttpClientable init(httpClient:HttpClientable = HttpClient(), refreshPeriod: Int = 60) { self.httpClient = httpClient _ = Observable.merge(secondEmitter, Observable.of(0)) .filter { $0%refreshPeriod == 0 } .flatMap { _ in return httpClient.send(url: IndoorTemp.baseUrl(appendPath: "status") , responseType: IndoorTemp.Response.self) } .subscribe(onNext: { [weak self] (indoorTempResponse) in self?.temperatureObserver.onNext(indoorTempResponse.temperature - 0.2) self?.humidityObserver.onNext(Int(indoorTempResponse.humidity)) }) } } struct IndoorTemp { static func baseUrl(appendPath pathComponent: String = "") -> String { return RollerShutter.livingRoom.baseUrl(appendPath: pathComponent) } struct Response: Decodable //{ "open": 1, "temperature": 21.00, "humidity": 63.10} { let open: Int let temperature: Double let humidity: Double } }
mit
4774d0c6b4c862ea4f34a6691583ec46
30.238095
140
0.655488
4.138801
false
false
false
false
Chantalisima/Spirometry-app
EspiroGame/InstruccionViewController.swift
1
2343
// // InstruccionViewController.swift // BLEgame5 // // Created by Chantal de Leste on 1/4/17. // Copyright © 2017 Universidad de Sevilla. All rights reserved. // import UIKit import CoreBluetooth class InstruccionViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CBPeripheralDelegate { var mainPeripheral: CBPeripheral? var mainView: MainViewController? var number: [String] = ["1.","2.","3.","4."] var instruccions: [String] = [" Breath normally 2 or 3 times"," Breath deep and slowly","Exhale as hard and fast as you can through the mouthpiece","Continue until your lungs are empty (Recommended 6 seconds or more)"] @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = Bundle.main.loadNibNamed("InstruccionTableViewCell", owner: self, options: nil)?.first as! InstruccionTableViewCell cell.textLabel?.numberOfLines = 0 cell.number.text = number[indexPath.row] cell.instruction.text = instruccions[indexPath.row] return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "test-segue"{ let testController: TestViewController = segue.destination as! TestViewController testController.mainperipheral = self.mainPeripheral print("segue to test") if self.mainPeripheral != nil { mainPeripheral?.delegate = testController mainPeripheral?.discoverServices(nil) print("peripheral equal to test peripheral") } } } }
apache-2.0
ac84057ebf7d30b19010e1dab3d4cf66
28.64557
222
0.625107
5.334852
false
true
false
false
shridharmalimca/iOSDev
iOS/Components/ShoppingCart/ShoppingCart/AppDelegate.swift
2
4594
// // AppDelegate.swift // ShoppingCart // // Created by Shridhar Mali on 12/26/16. // Copyright © 2016 TIS. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "ShoppingCart") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
apache-2.0
e44553e63c2a57e0b6c154cb17404f00
48.387097
285
0.686044
5.880922
false
false
false
false
ramki1979/OAuthSDK
OAuthSDK/OAuth2.swift
1
8688
// // OAuth2.swift // OAuthSDK // // Created by RamaKrishna Mallireddy on 18/04/15. // Copyright (c) 2015 VUContacts. All rights reserved. // import UIKit public class OAuth2: OAuthClient { public override init(config: [String : String]) { super.init(config: config) if keychainHelper.checkAndUpdateValueForKey(OAuthServiceName + "access_token") { OAuthState = .AccessToken } session = NSURLSession(configuration: nil, delegate: self, delegateQueue: nil) } public func authenticationRequestURL(webviewParent: UIView) { // Authenticate user URL OAuthState = .AuthenticateUser let webview = OAuthWebView(delegate:self, parent: webviewParent) if let navBar = webviewParent.viewWithTag(Properties.kUINavigationBar.rawValue) as? UINavigationBar { webviewParent.insertSubview(webview, belowSubview: navBar) } OAuthURL = makeURL(OAuthEndPoints[OAuthEndPointKeys.AuthenticateUserURL.rawValue]!) webview.loadRequestURL(OAuthURL) } public func validateAccessToken() -> OAuth2 { if keychainHelper.checkAndUpdateValueForKey(OAuthServiceName + "access_token") { // check for AccessToken Validation..if not valid automatically refresh access_token OAuthState = .ValidateAccessToken createDataTask(OAuthEndPointKeys.ValidateAccessTokenURL.rawValue) } return self } public func createDataTask(endPointKey: String, headers: [String: String]? = nil) { OAuthURL = makeURL(OAuthEndPoints[endPointKey]!) let req = NSMutableURLRequest(URL: NSURL(string: OAuthURL)!) req.HTTPMethod = OAuthMethod if let headerDict = headers { for (key, value) in headerDict { req.setValue(value, forHTTPHeaderField: key) } } println("request: \(req.URL!.host) \(req.URL!.path) \(req.URL!.query)") let dataTask = session.dataTaskWithRequest(req) dataTask.resume() } private func makeURL(dict:[String: String]) -> String { var url: String! var base = String() var start = true for (key, value) in dict { switch key { case "method": OAuthMethod = value case "url": url = value + "?" case "path": url = baseURL + value + "?" default: if !start { if value.isEmpty { base += "&\(key)=\(valueForKey(key))" } else { base += "&\(key)=\(value)" } } else { if value.isEmpty { base += "\(key)=\(valueForKey(key))" } else { base += "\(key)=\(value)" } start = false } } } return url + base } private func valueForKey(key: String) -> String { switch key { case "client_id": return OAuthServiceKey case "client_secret": return OAuthServiceSecret default: return decryptToKeyChain(OAuthServiceName+"\(key)") } } private func processAuthenticateTokenResponse(dict: [String: AnyObject]) { var refresh_token: String! var access_token: String! for (key, val: AnyObject) in dict { switch key { case "access_token": access_token = val as! String case "refresh_token": refresh_token = val as! String default: break } } if access_token != nil { OAuthState = .AccessToken encryptToKeyChain(OAuthServiceName+"access_token", data: access_token, updateIfExist: true) if refresh_token != nil { keychainHelper.deleteKey(OAuthServiceName+"code", serviceId: nil) encryptToKeyChain(OAuthServiceName+"refresh_token", data: refresh_token) } } } private func processValidateAccessTokenResponse(dict: [String: AnyObject]) { /* Google Drive Response: Success: { "access_type" = offline; audience = "577875232180-lu50p0bfec6b1sm1qs4hgkjin7cqdll7.apps.googleusercontent.com"; "expires_in" = 3106; "issued_to" = "577875232180-lu50p0bfec6b1sm1qs4hgkjin7cqdll7.apps.googleusercontent.com"; scope = "https://www.googleapis.com/auth/drive"; } Error: { "error" = "invalid_token"; "error_description" = "Invalid Value"; } */ for (key, val: AnyObject) in dict { switch key { case "error": // Google Drive.. if val as! String == "invalid_token" { OAuthState = .RefreshAccessToken createDataTask(OAuthEndPointKeys.RefreshAccessTokenURL.rawValue) return } case "error_description": break default: break } } // token is valid... OAuthState = .AccessToken } } extension OAuth2: OAuthWebResponse { func responseURL(url: NSURL) { if let path = url.path, query = url.query { switch path { case "/google/drive": fallthrough case "/dropbox": if query.hasPrefix("code=") { // Got oauth_code for google drive service let oauth_code = query.substringWithRange(Range(start: advance(query.startIndex, 5), end: query.endIndex)) encryptToKeyChain(OAuthServiceName+"code", data: oauth_code) // we got the code, lets authenticate the code, to get the access_token... OAuthState = .AuthenticateCode createDataTask(OAuthEndPointKeys.AuthenticateUserCodeForAccessTokenURL.rawValue) } else { println("responseURL: \(url)") } default: println("response: path:\(path) query:\(query)") } } } } extension OAuth2: NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { public override func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { var response: AnyObject? let path = task.originalRequest.URL!.host! + task.originalRequest.URL!.path! if let data = responseData[path] { var error: NSError? response = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(), error: &error) if error != nil || response == nil { println("Json Error: \(error)") return } if OAuthState != .AccessToken { println("\nResponse (bytes: \(task.countOfBytesExpectedToReceive)): \(response)") } else { println("\nResponse (bytes: \(task.countOfBytesExpectedToReceive))") } // Release the NSData response object responseData.removeValueForKey(path) } else { if let delgate = delegate { delgate.requestCompleteWithError(OAuthServiceName, path: path, response: responseError[path]!) } return } switch OAuthState { case .AuthenticateCode: fallthrough case .RefreshAccessToken: processAuthenticateTokenResponse(response! as! [String: AnyObject]) case .ValidateAccessToken: processValidateAccessTokenResponse(response! as! [String: AnyObject]) if let delgate = delegate { delgate.requestComplete(OAuthServiceName, path: path, response: response!) } case .RevokeAccessToken: break case .AccessToken: if let delgate = delegate { delgate.requestComplete(OAuthServiceName, path: path, response: response!) } default: break } } }
mit
d772ebe07bcdaf97c4e17df0bd4d32e8
32.548263
126
0.530502
5.265455
false
false
false
false