repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
kingiol/IBDesignableDemo
refs/heads/master
MyCustomView/CustomView.swift
mit
1
// // CustomView.swift // IBDesignableDemo // // Created by Kingiol on 14-6-11. // Copyright (c) 2014年 Kingiol. All rights reserved. // import UIKit @IBDesignable class CustomView: UIView { @IBInspectable var borderColor: UIColor = UIColor.clearColor() { didSet { layer.borderColor = borderColor.CGColor } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } }
67a8aede4eadd4fb7597b0abb41f6ae4
17.085714
53
0.579779
false
false
false
false
ray3132138/TestKitchen_1606
refs/heads/master
TestKitchen/TestKitchen/classes/cookbook/homePage/controller/CookBookViewController.swift
mit
1
// // CookBookViewController.swift // TestKitchen // // Created by qianfeng on 16/8/15. // Copyright © 2016年 ray. All rights reserved. // import UIKit class CookBookViewController: BaseViewController { //滚动视图 var scrollView: UIScrollView? //食材首页的推荐视图 private var recommendView: CBRecommendView? //首页的食材视图 private var foodView: CBMaterialView? //首页的分类视图 private var categoryView: CBMaterialView? //导航的标题视图 private var segCtrl: KTCSegmentCtrl? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //创建导航 createMyNav() //初始化视图 createHomePageView() //下载推荐的数据 downloadRecommendData() //下载食材的数据 downloadFoodData() //下载分类的数据 downloadCategoryData() } //下载分类的数据 func downloadCategoryData(){ //methodName=CategoryIndex&token=&user_id=&version=4.32 let params = ["methodName":"CategoryIndex"] let downloader = KTCDownloader() downloader.delegate = self downloader.type = .Category downloader.postWithUrl(kHostUrl, params: params) } //下载食材的数据 func downloadFoodData(){ //methodName=MaterialSubtype&token=&user_id=&version=4.5 let dict = ["methodName":"MaterialSubtype"] let downloader = KTCDownloader() downloader.delegate = self downloader.type = .FoodMaterial downloader.postWithUrl(kHostUrl, params: dict) } //初始化视图 func createHomePageView(){ self.automaticallyAdjustsScrollViewInsets = false //1.创建滚动视图 scrollView = UIScrollView() scrollView!.pagingEnabled = true scrollView!.showsHorizontalScrollIndicator = false //设置代理 scrollView?.delegate = self view.addSubview(scrollView!) //约束 scrollView!.snp_makeConstraints { [weak self] (make) in make.edges.equalTo(self!.view).inset(UIEdgeInsetsMake(64, 0, 49, 0)) //添加约束的闭包内使用到 self 的时候才使用: [weak self] } //2.创建容器视图 let containerView = UIView.createView() scrollView!.addSubview(containerView) //约束 containerView.snp_makeConstraints { [weak self] (make) in make.edges.equalTo(self!.scrollView!) make.height.equalTo(self!.scrollView!) } //3.添加子视图 //3.1.推荐 recommendView = CBRecommendView() containerView.addSubview(recommendView!) //约束 recommendView?.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(kScreenWidth) make.left.equalTo(containerView) }) //3.2.食材 foodView = CBMaterialView() foodView?.backgroundColor = UIColor.redColor() containerView.addSubview(foodView!) foodView?.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(kScreenWidth) make.left.equalTo((recommendView?.snp_right)!) }) //3.3.分类 categoryView = CBMaterialView() categoryView?.backgroundColor = UIColor.yellowColor() containerView.addSubview(categoryView!) categoryView?.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(kScreenWidth) make.left.equalTo((foodView?.snp_right)!) }) //4.修改容器视图的大小 containerView.snp_makeConstraints { (make) in make.right.equalTo(categoryView!) } } //下载推荐的数据 func downloadRecommendData(){ //首页推荐参数 //methodName=SceneHome&token=&user_id=&version=4.5 //参数: let dict = ["methodName":"SceneHome"] let downloader = KTCDownloader() downloader.type = .Recommend downloader.delegate = self downloader.postWithUrl(kHostUrl, params: dict) } //创建导航 func createMyNav(){ //标题位置 segCtrl = KTCSegmentCtrl(frame: CGRectMake(80, 0, kScreenWidth-80*2, 44), titleNames: ["推荐","食材","分类"]) //设置代理 segCtrl!.delegate = self navigationItem.titleView = segCtrl //扫一扫 addNavBtn("saoyisao", target: self, action: #selector(scanAction), isLeft: true) addNavBtn("search", target: self, action: #selector(searchAction), isLeft: false) } //扫一扫 func scanAction(){ } //搜索 func searchAction(){ } 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. } */ } //MARK: KTCDownloader代理 extension CookBookViewController:KTCDownloaderDelegate{ func downloader(downloader: KTCDownloader, didFailWithError error: NSError) { print(error) } func downloader(downloader: KTCDownloader, didFinishWithData data: NSData?) { if downloader.type == .Recommend{ //推荐 if let jsonData = data{ let model = CBRecommendModel.parseModel(jsonData) //显示数据 dispatch_async(dispatch_get_main_queue(), { [weak self] in self!.recommendView?.model = model }) } }else if downloader.type == .FoodMaterial{ //食材 // let str = NSString(data: data!, encoding: NSUTF8StringEncoding) // print(str) if let jsonData = data{ let model = CBMaterialModel.parseModelWithData(jsonData) dispatch_async(dispatch_get_main_queue(), { [weak self] in self!.foodView?.model = model }) } }else if downloader.type == .Category{ //分类 if let jsonData = data{ let model = CBMaterialModel.parseModelWithData(jsonData) dispatch_async(dispatch_get_main_queue(), { [weak self] in self!.categoryView?.model = model }) } } } } // extension CookBookViewController: KTCSegmentCtrlDelegate{ func didSelectSegCtrl(segCtrl: KTCSegmentCtrl, atIndex index: Int) { scrollView?.setContentOffset(CGPointMake(kScreenWidth*CGFloat(index), 0), animated: true) //scrollView?.contentOffset = CGPointMake(kScreenWidth*CGFloat(index), 0) } } extension CookBookViewController: UIScrollViewDelegate{ func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let index = Int(scrollView.contentOffset.x / scrollView.bounds.size.width) //修改标题选中的按钮 segCtrl?.selectIndex = index } }
71eb2c0a9c16aab4ad48d4040cacb1ba
23.191176
111
0.528754
false
false
false
false
mlburggr/OverRustleiOS
refs/heads/master
OverRustleiOS/RustleStream.swift
mit
1
// // RustleStream.swift // OverRustleiOS // // Created by Maxwell Burggraf on 8/15/15. // Copyright (c) 2015 Maxwell Burggraf. All rights reserved. // import Foundation public class RustleStream { var platform : Int = 0 var streamURL : NSURL = NSURL( string: "" )! var channel : String = "" func matchesForRegexInText(regex: String!, text: String!) -> [String] { let regex_options:NSRegularExpressionOptions? = NSRegularExpressionOptions.CaseInsensitive let regex = try! NSRegularExpression(pattern: regex, options: regex_options!) let nsString = text as NSString let results = regex.matchesInString(text, options: [], range: NSMakeRange(0, nsString.length)) return results.map { nsString.substringWithRange($0.range)} } func getStreamURL() -> NSURL{ return NSURL(string:"")! } }
39a3d865aced11d7e1c92a3e748f80bc
24.540541
98
0.617585
false
false
false
false
YusukeHosonuma/SwiftCommons
refs/heads/master
SwiftCommons/NSDate+.swift
mit
2
// // NSDate+.swift // SwiftCommons // // Created by Yusuke on 9/10/15. // Copyright © 2015 Yusuke. All rights reserved. // import Foundation public func < (lhs: Date, rhs: Date) -> Bool { return lhs.compare(rhs) == .orderedAscending } public extension Date { /// RFC3339 format for NSDate. fileprivate static var kRFC3339Format: String { return "yyyy'-'MM'-'dd'T'HH:mm:ssZZZZZ" } /** Convert date from RFC3339 string. - parameter string : The string to parse. - returns : A date. */ public static func fromRFC3339String(_ string: String) -> Date? { let formatter = DateFormatter() formatter.dateFormat = kRFC3339Format formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone.current return formatter.date(from: string) } /** Convert RFC3339 string from date. - parameter date : The date to string. - returns : RFC3339 string. (Timezone string is depends to defaultTimeZone) */ public static func toRFC3339String(_ date: Date) -> String? { let formatter = DateFormatter() formatter.dateFormat = kRFC3339Format formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone.current return formatter.string(from: date) } public func unixtime() -> TimeInterval { return self.timeIntervalSince1970 } public static func fromUnixtime(_ unixtime: TimeInterval) -> Date { return Date(timeIntervalSince1970: unixtime) } }
081de1554c33ac9920790ca26b8a5f58
26.754386
79
0.643489
false
false
false
false
kentaiwami/FiNote
refs/heads/master
ios/FiNote/FiNote/Movie/MovieAddSearch/MovieAddSearchCell.swift
mit
1
// // MovieAddSearchCell.swift // FiNote // // Created by 岩見建汰 on 2018/01/27. // Copyright © 2018年 Kenta. All rights reserved. // import UIKit class MovieAddSearchCell: UITableViewCell { var title: UILabel! var overview: UILabel! var poster: UIImageView! var release_date: UILabel! var release_date_icon: UIImageView! var added_icon: UIImageView! var added_msg: UILabel! override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) title = UILabel(frame: CGRect.zero) title.textAlignment = .left title.lineBreakMode = .byTruncatingTail title.font = UIFont(name: Font.helveticaneue_B.rawValue, size: 18) overview = UILabel(frame: CGRect.zero) overview.textAlignment = .left overview.lineBreakMode = .byTruncatingTail overview.numberOfLines = 0 overview.font = UIFont(name: Font.helveticaneue.rawValue, size: 14) release_date = UILabel(frame: CGRect.zero) release_date.textAlignment = .left release_date.lineBreakMode = .byWordWrapping release_date.font = UIFont(name: Font.helveticaneue.rawValue, size: 14) release_date.textColor = UIColor.hex(Color.gray.rawValue, alpha: 1.0) release_date_icon = UIImageView(frame: CGRect.zero) release_date_icon.image = UIImage(named: "tab_movies") release_date_icon.image = release_date_icon.image!.withRenderingMode(.alwaysTemplate) release_date_icon.tintColor = UIColor.hex(Color.gray.rawValue, alpha: 1.0) added_icon = UIImageView(frame: CGRect.zero) added_icon.image = UIImage(named: "icon_circle_check") added_icon.image = added_icon.image!.withRenderingMode(.alwaysTemplate) added_icon.tintColor = UIColor.hex(Color.main.rawValue, alpha: 0.8) added_msg = UILabel(frame: CGRect.zero) added_msg.textAlignment = .left added_msg.text = "追加済み" added_msg.textColor = UIColor.hex(Color.main.rawValue, alpha: 0.8) added_msg.font = UIFont(name: Font.helveticaneue.rawValue, size: 14) contentView.addSubview(title) contentView.addSubview(overview) contentView.addSubview(release_date) contentView.addSubview(release_date_icon) contentView.addSubview(added_icon) contentView.addSubview(added_msg) poster = UIImageView() contentView.addSubview(poster) } required init(coder aDecoder: NSCoder) { fatalError("init(coder: ) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() } override func layoutSubviews() { super.layoutSubviews() let icon_wh = 20 as CGFloat poster.frame = CGRect(x: 0, y: 0, width: contentView.frame.height/1.5, height: contentView.frame.height) title.trailing(to: contentView) title.leadingToTrailing(of: poster, offset: 20) title.top(to: contentView, offset: 5) overview.trailing(to: contentView) overview.topToBottom(of: title, offset: 2) overview.leadingToTrailing(of: poster, offset: 20) overview.bottom(to: contentView, offset: -25) release_date_icon.leadingToTrailing(of: poster, offset: 20) release_date_icon.bottom(to: contentView, offset: -5) release_date_icon.width(icon_wh) release_date_icon.height(icon_wh) release_date.leadingToTrailing(of: release_date_icon, offset: 5) release_date.centerY(to: release_date_icon, offset: 1) added_msg.trailing(to: contentView) added_msg.centerY(to: release_date) added_icon.trailingToLeading(of: added_msg, offset: -5) added_icon.centerY(to: release_date_icon, offset: 1) added_icon.width(icon_wh) added_icon.height(icon_wh) } }
ecacf285f7b7a68722019d23f11bec0c
36.119266
112
0.645082
false
false
false
false
WeirdMath/SwiftyHaru
refs/heads/dev
Sources/SwiftyHaru/Grid/Grid.MinorLineParameters.swift
mit
1
// // Grid.MinorLineParameters.swift // SwiftyHaru // // Created by Sergej Jaskiewicz on 04.11.16. // // extension Grid { /// Represents the properties of a grid's minor lines. public struct MinorLineParameters: Hashable { /// Default parameters, where line width is 0.25, line color is 80% gray and the default /// number of minor segments per one major segment is 2. public static let `default` = MinorLineParameters() /// The width of lines. public var lineWidth: Float /// The number of minor segments per one vertical major segment. /// Setting this property to N means that N-1 minor lines will be drawn between /// two adjacent major lines. Must be positive. public var minorSegmentsPerMajorSegment: Int /// The color of lines. public var lineColor: Color /// Creates a new line parameter set. /// /// - parameter lineWidth: The width of a line. Default value is 0.25 /// - parameter minorSegmentsPerMajorSegment: The number of minor segments per one vertical major segment. /// Must be positive. /// Defaulr value is 2. /// - parameter lineColor: The color of lines. Default is 80% gray. public init(lineWidth: Float = 0.25, minorSegmentsPerMajorSegment: Int = 2, lineColor: Color = Color(gray: 0.8)!) { self.lineWidth = lineWidth self.minorSegmentsPerMajorSegment = minorSegmentsPerMajorSegment > 0 ? minorSegmentsPerMajorSegment : 2 self.lineColor = lineColor } } }
605039a8f22c2488d2d3fa76ac1bcbd2
39.909091
115
0.574444
false
false
false
false
joerocca/GitHawk
refs/heads/master
Playgrounds/ButtonAnimation.playground/Contents.swift
mit
2
//: A UIKit based Playground for presenting user interface import UIKit import PlaygroundSupport class Button: UIView { let emoji = UILabel() let label = UILabel() override init(frame: CGRect) { super.init(frame: frame) emoji.backgroundColor = .clear emoji.textAlignment = .center emoji.font = UIFont.systemFont(ofSize: 36) addSubview(emoji) label.backgroundColor = .clear label.textAlignment = .center label.clipsToBounds = true label.textColor = .black label.font = UIFont.systemFont(ofSize: 30) addSubview(label) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let half = bounds.width/2 emoji.frame = CGRect(x: 0, y: 0, width: half, height: bounds.height) label.frame = CGRect(x: half, y: 0, width: half, height: bounds.height) } } class MyViewController : UIViewController { var val = 0 let button = Button() let add = UIButton() let sub = UIButton() override func loadView() { let view = UIView() view.backgroundColor = .white self.view = view button.frame = CGRect(x: 0, y: 0, width: 90, height: 30) view.addSubview(button) add.setTitle("Add", for: .normal) add.setTitleColor(.blue, for: .normal) add.sizeToFit() add.addTarget(self, action: #selector(MyViewController.onAdd), for: .touchUpInside) view.addSubview(add) sub.setTitle("Sub", for: .normal) sub.setTitleColor(.blue, for: .normal) sub.sizeToFit() sub.addTarget(self, action: #selector(MyViewController.onSub), for: .touchUpInside) view.addSubview(sub) update(.idle) } @objc func onAdd() { update(.add) } @objc func onSub() { update(.sub) } enum Update { case add case sub case idle } func update(_ update: Update) { button.emoji.text = "🤔" enum Action { case remove case add case incr case decr case none } let action: Action switch update { case .add: if val == 0 { action = .add } else if val > 0 { action = .incr } else { action = .none } val += 1 case .sub: if val > 1 { action = .decr } else if val == 1 { action = .remove } else { action = .none } val -= 1 case .idle: action = .none } print(val) switch action { case .add: pop() case .remove: remove() case .incr: iterate(incr: true) case .decr: iterate(incr: false) case .none: if val <= 0 { button.emoji.alpha = 0 button.label.alpha = 0 } else { button.emoji.alpha = 1 button.label.alpha = 1 } default: break } } func pop() { print("pop") button.emoji.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) button.emoji.alpha = 0 UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.2, options: [.curveEaseInOut], animations: { self.button.emoji.transform = .identity self.button.emoji.alpha = 1 }) button.label.alpha = 0 button.label.text = "\(val)" UIView.animate(withDuration: 0.3, delay: 0, options: [], animations: { self.button.label.alpha = 1 }) } func remove() { print("remove") button.label.alpha = 1 button.emoji.transform = .identity button.emoji.alpha = 1 UIView.animate(withDuration: 0.2, delay: 0, options: [], animations: { self.button.label.alpha = 0 self.button.emoji.transform = CGAffineTransform(scaleX: 0.3, y: 0.3) self.button.emoji.alpha = 0 }) } func iterate(incr: Bool) { print("iterate \(incr)") let animation = CATransition() animation.duration = 0.25 animation.type = kCATransitionPush animation.subtype = incr ? kCATransitionFromTop : kCATransitionFromBottom animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) button.label.layer.add(animation, forKey: "text-change") button.label.text = "\(val)" } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() button.center = view.center add.center = CGPoint(x: button.frame.maxX, y: button.frame.maxY + 40) sub.center = CGPoint(x: button.frame.minX, y: button.frame.maxY + 40) } } // Present the view controller in the Live View window PlaygroundPage.current.liveView = MyViewController()
d2a9d3e65989968a905dfbb9dabe5032
27.266304
150
0.546818
false
false
false
false
box/box-ios-sdk
refs/heads/main
Sources/Client/BoxClient.swift
apache-2.0
1
import Foundation import os /// Provides communication with Box APIs. Defines methods for communication with Box APIs public class BoxClient { /// Provides [File](../Structs/File.html) management. public private(set) lazy var files = FilesModule(boxClient: self) /// Provides [Folder](../Structs/Folder.html) management. public private(set) lazy var folders = FoldersModule(boxClient: self) /// Provides [User](../Structs/User.html) management. public private(set) lazy var users = UsersModule(boxClient: self) /// Provides [Group](../Structs/Group.html) management. public private(set) lazy var groups = GroupsModule(boxClient: self) /// Provides [Comment](../Structs/Comment.html) management. public private(set) lazy var comments = CommentsModule(boxClient: self) /// Provides [SharedItem](../Structs/SharedItem.html) management. public private(set) lazy var sharedItems = SharedItemsModule(boxClient: self) /// Web Links management. public private(set) lazy var webLinks = WebLinksModule(boxClient: self) /// Provides search functionality. public private(set) lazy var search = SearchModule(boxClient: self) /// Provides collections functionality. public private(set) lazy var collections = CollectionsModule(boxClient: self) /// Provides collaborations functionality. public private(set) lazy var collaborations = CollaborationsModule(boxClient: self) /// Provides collaborations whitelist functionality public private(set) lazy var collaborationAllowList = CollaborationAllowlistModule(boxClient: self) /// Metadata management. public private(set) lazy var metadata = MetadataModule(boxClient: self) /// Provides [Events](../Structs/Events.html) management. public private(set) lazy var events = EventsModule(boxClient: self) /// Metadata cascade policy. public private(set) lazy var metadataCascadePolicy = MetadataCascadePolicyModule(boxClient: self) /// Trash management. public private(set) lazy var trash = TrashModule(boxClient: self) /// Device Pin management. public private(set) lazy var devicePins = DevicePinsModule(boxClient: self) /// Recent Items management public private(set) lazy var recentItems = RecentItemsModule(boxClient: self) /// Webhooks management public private(set) lazy var webhooks = WebhooksModule(boxClient: self) /// Tasks management. public private(set) lazy var tasks = TasksModule(boxClient: self) /// Retention policy management. public private(set) lazy var retentionPolicy = RetentionPoliciesModule(boxClient: self) /// Provides [TermsOfService](../Structs/TermsOfService.html) public private(set) lazy var termsOfService = TermsOfServicesModule(boxClient: self) /// Legal Hold Policies management public private(set) lazy var legalHolds = LegalHoldsModule(boxClient: self) /// Storage Policies management public private(set) lazy var storagePolicies = StoragePoliciesModule(boxClient: self) /// Provides sign requests functionality. public private(set) lazy var signRequests = SignRequestsModule(boxClient: self) /// Provides file requests functionality. public private(set) lazy var fileRequests = FileRequestsModule(boxClient: self) /// Provides network communication with the Box APIs. private var networkAgent: NetworkAgentProtocol /// Provides authentication session management. public private(set) var session: SessionProtocol /// Requests header. public private(set) var headers: BoxHTTPHeaders? = [:] /// SDK request configuration. public private(set) var configuration: BoxSDKConfiguration /// Indicates whether this BoxClient instance has been destroyed public private(set) var isDestroyed: Bool /// ID of user's favorites collection. public internal(set) var favoritesCollectionId: String? /// Initializer /// /// - Parameters: /// - networkAgent: Provides network communication with the Box APIs. /// - session: Provides authentication session management. /// - configuration: Provides parameters to makes API calls in order to tailor it to their application's specific needs public init(networkAgent: NetworkAgentProtocol, session: SessionProtocol, configuration: BoxSDKConfiguration) { self.networkAgent = networkAgent self.session = session self.configuration = configuration isDestroyed = false } /// Creates BoxClient instance based on shared link URL and password. /// /// - Parameters: /// - url: Shared link URL. /// - password: Shared link password. /// - Returns: Returns new standard BoxClient object. public func withSharedLink(url: URL, password: String?) -> BoxClient { let networkAgent = BoxNetworkAgent(configuration: configuration) let client = BoxClient(networkAgent: networkAgent, session: session, configuration: configuration) client.addSharedLinkHeader(sharedLink: url, sharedLinkPassword: password) return client } /// Creates BoxClient instance based on user identifier. /// /// - Parameter userId: User identifier. /// - Returns: Returns new standard BoxCliennt object. public func asUser(withId userId: String) -> BoxClient { let networkAgent = BoxNetworkAgent(configuration: configuration) let client = BoxClient(networkAgent: networkAgent, session: session, configuration: configuration) client.addAsUserHeader(userId: userId) return client } /// Destroys the client, revoking its access tokens and rendering it inoperable. /// /// - Parameter completion: Called when the operation is complete. public func destroy(completion: @escaping Callback<Void>) { session.revokeTokens(completion: { result in switch result { case let .failure(error): completion(.failure(error)) case .success: self.isDestroyed = true completion(.success(())) } }) } /// Exchange the token. /// /// - Parameters: /// - scope: Scope or scopes that you want to apply to the resulting token. /// - resource: Full url path to the file that the token should be generated for, eg: https://api.box.com/2.0/files/{file_id} /// - sharedLink: Shared link to get a token for. /// - completion: Returns the success or an error. public func exchangeToken( scope: Set<TokenScope>, resource: String? = nil, sharedLink: String? = nil, completion: @escaping TokenInfoClosure ) { session.downscopeToken(scope: scope, resource: resource, sharedLink: sharedLink, completion: completion) } } extension BoxClient { /// Makes a Box SDK request /// /// - Parameters: /// - request: Box SDK request /// - completion: Returns standard BoxResponse object or error. public func send( request: BoxRequest, completion: @escaping Callback<BoxResponse> ) { guard !isDestroyed else { completion(.failure(BoxSDKError(message: .clientDestroyed))) return } session.getAccessToken { (result: Result<String, BoxSDKError>) in switch result { case let .failure(error): completion(.failure(error)) return case let .success(token): let updatedRequest = request updatedRequest.httpHeaders["Authorization"] = "Bearer \(token)" updatedRequest.addBoxAPIRelatedHeaders(self.headers) self.networkAgent.send( request: updatedRequest, completion: { [weak self] (result: Result<BoxResponse, BoxSDKError>) in self?.handleAuthIssues( result: result, completion: completion ) } ) } } } private func handleAuthIssues( result: Result<BoxResponse, BoxSDKError>, completion: @escaping Callback<BoxResponse> ) { switch result { case let .success(resultObj): completion(.success(resultObj)) case let .failure(error): if let apiError = error as? BoxAPIAuthError, apiError.message == .unauthorizedAccess { if let tokenHandlingSession = session as? ExpiredTokenHandling { tokenHandlingSession.handleExpiredToken(completion: { _ in completion(.failure(error)) }) return } } completion(.failure(error)) } } private func addSharedLinkHeader(sharedLink: URL, sharedLinkPassword: String?) { if let sharedLinkPassword = sharedLinkPassword { headers?[BoxHTTPHeaderKey.boxApi] = "\(BoxAPIHeaderKey.sharedLink)=\(sharedLink.absoluteString)&\(BoxAPIHeaderKey.sharedLinkPassword)=\(sharedLinkPassword)" } else { headers?[BoxHTTPHeaderKey.boxApi] = "\(BoxAPIHeaderKey.sharedLink)=\(sharedLink.absoluteString)" } } private func addAsUserHeader(userId: String) { headers?[BoxHTTPHeaderKey.asUser] = userId } } // MARK: - BoxClientProtocol methods extension BoxClient: BoxClientProtocol { /// Performs an HTTP GET method call on an API endpoint and returns a response. /// /// - Parameters: /// - url: The URL of the API endpoint to call. /// - httpHeaders: Additional information to be passed in the HTTP headers of the request. /// - queryParameters: Additional parameters to be passed in the URL that is called. /// - completion: Returns a BoxResponse object or an error if request fails public func get( url: URL, httpHeaders: BoxHTTPHeaders = [:], queryParameters: QueryParameters = [:], completion: @escaping Callback<BoxResponse> ) { send( request: BoxRequest( httpMethod: .get, url: url, httpHeaders: httpHeaders, queryParams: queryParameters, body: .empty ), completion: completion ) } /// Performs an HTTP POST method call on an API endpoint and returns a response. /// /// - Parameters: /// - url: The URL of the API endpoint to call. /// - httpHeaders: Additional information to be passed in the HTTP headers of the request. /// - queryParameters: Additional parameters to be passed in the URL that is called. /// - json: The JSON body of the request /// - completion: Returns a BoxResponse object or an error if request fails public func post( url: URL, httpHeaders: BoxHTTPHeaders = [:], queryParameters: QueryParameters = [:], json: Any? = nil, completion: @escaping Callback<BoxResponse> ) { send( request: BoxRequest( httpMethod: .post, url: url, httpHeaders: httpHeaders, queryParams: queryParameters, body: jsonToBody(json) ), completion: completion ) } /// Performs an HTTP POST method call on an API endpoint and returns a response. /// /// - Parameters: /// - url: The URL of the API endpoint to call. /// - httpHeaders: Additional information to be passed in the HTTP headers of the request. /// - queryParameters: Additional parameters to be passed in the URL that is called. /// - multipartBody: The multipart body of the request /// - completion: Returns a BoxResponse object or an error if request fails /// - Returns: BoxUploadTask @discardableResult public func post( url: URL, httpHeaders: BoxHTTPHeaders = [:], queryParameters: QueryParameters = [:], multipartBody: MultipartForm, progress: @escaping (Progress) -> Void = { _ in }, completion: @escaping Callback<BoxResponse> ) -> BoxUploadTask { let task = BoxUploadTask() send( request: BoxRequest( httpMethod: .post, url: url, httpHeaders: httpHeaders, queryParams: queryParameters, body: .multipart(multipartBody), task: task.receiveTask, progress: progress ), completion: completion ) return task } /// Performs an HTTP PUT method call on an API endpoint and returns a response. /// /// - Parameters: /// - url: The URL of the API endpoint to call. /// - httpHeaders: Additional information to be passed in the HTTP headers of the request. /// - queryParameters: Additional parameters to be passed in the URL that is called. /// - json: The JSON body of the request /// - completion: Returns a BoxResponse object or an error if request fails public func put( url: URL, httpHeaders: BoxHTTPHeaders = [:], queryParameters: QueryParameters = [:], json: Any? = nil, completion: @escaping Callback<BoxResponse> ) { send( request: BoxRequest( httpMethod: .put, url: url, httpHeaders: httpHeaders, queryParams: queryParameters, body: jsonToBody(json) ), completion: completion ) } /// Performs an HTTP PUT method call on an API endpoint and returns a response. /// /// - Parameters: /// - url: The URL of the API endpoint to call. /// - httpHeaders: Additional information to be passed in the HTTP headers of the request. /// - queryParameters: Additional parameters to be passed in the URL that is called. /// - multipartBody: The multipart body of the request /// - completion: Returns a BoxResponse object or an error if request fails /// - Returns: BoxUploadTask @discardableResult public func put( url: URL, httpHeaders: BoxHTTPHeaders = [:], queryParameters: QueryParameters = [:], multipartBody: MultipartForm, progress: @escaping (Progress) -> Void = { _ in }, completion: @escaping Callback<BoxResponse> ) -> BoxUploadTask { let task = BoxUploadTask() send( request: BoxRequest( httpMethod: .put, url: url, httpHeaders: httpHeaders, queryParams: queryParameters, body: .multipart(multipartBody), task: task.receiveTask, progress: progress ), completion: completion ) return task } /// Performs an HTTP PUT method call on an API endpoint and returns a response - variant for chunked upload. /// /// - Parameters: /// - url: The URL of the API endpoint to call. /// - httpHeaders: Additional information to be passed in the HTTP headers of the request. /// - queryParameters: Additional parameters to be passed in the URL that is called. /// - data: Binary body of the request /// - progress: Closure where upload progress will be reported /// - completion: Returns a BoxResponse object or an error if request fails /// - Returns: BoxUploadTask @discardableResult public func put( url: URL, httpHeaders: BoxHTTPHeaders = [:], queryParameters: QueryParameters = [:], data: Data, progress: @escaping (Progress) -> Void = { _ in }, completion: @escaping Callback<BoxResponse> ) -> BoxUploadTask { let task = BoxUploadTask() send( request: BoxRequest( httpMethod: .put, url: url, httpHeaders: httpHeaders, queryParams: queryParameters, body: .data(data), task: task.receiveTask, progress: progress ), completion: completion ) return task } /// Performs an HTTP OPTIONS method call on an API endpoint and returns a response. /// /// - Parameters: /// - url: The URL of the API endpoint to call. /// - httpHeaders: Additional information to be passed in the HTTP headers of the request. /// - queryParameters: Additional parameters to be passed in the URL that is called. /// - json: The JSON body of the request /// - completion: Returns a BoxResponse object or an error if request fails /// - Returns: BoxNetworkTask @discardableResult public func options( url: URL, httpHeaders: BoxHTTPHeaders = [:], queryParameters: QueryParameters = [:], json: Any? = nil, completion: @escaping Callback<BoxResponse> ) -> BoxNetworkTask { let task = BoxNetworkTask() send( request: BoxRequest( httpMethod: .options, url: url, httpHeaders: httpHeaders, queryParams: queryParameters, body: jsonToBody(json), task: task.receiveTask ), completion: completion ) return task } /// Performs an HTTP DELETE method call on an API endpoint and returns a response. /// /// - Parameters: /// - url: The URL of the API endpoint to call. /// - httpHeaders: Additional information to be passed in the HTTP headers of the request. /// - queryParameters: Additional parameters to be passed in the URL that is called. /// - completion: Returns a BoxResponse object or an error if request fails public func delete( url: URL, httpHeaders: BoxHTTPHeaders = [:], queryParameters: QueryParameters = [:], completion: @escaping Callback<BoxResponse> ) { send( request: BoxRequest( httpMethod: .delete, url: url, httpHeaders: httpHeaders, queryParams: queryParameters, body: .empty ), completion: completion ) } /// Performs an HTTP GET method call for downloading on an API endpoint and returns a response. /// /// - Parameters: /// - url: The URL of the API endpoint to call. /// - httpHeaders: Additional information to be passed in the HTTP headers of the request. /// - queryParameters: Additional parameters to be passed in the URL that is called. /// - downloadDestinationURL: The URL on disk where the data will be saved /// - progress: Completion block to track the progress of the request /// - completion: Returns a BoxResponse object or an error if request fails /// - Returns: BoxDownloadTask @discardableResult public func download( url: URL, downloadDestinationURL: URL, httpHeaders: BoxHTTPHeaders = [:], queryParameters: QueryParameters = [:], progress: @escaping (Progress) -> Void = { _ in }, completion: @escaping Callback<BoxResponse> ) -> BoxDownloadTask { let task = BoxDownloadTask() send( request: BoxRequest( httpMethod: .get, url: url, httpHeaders: httpHeaders, queryParams: queryParameters, downloadDestination: downloadDestinationURL, task: task.receiveTask, progress: progress ), completion: completion ) return task } } private extension BoxClient { func jsonToBody(_ json: Any?) -> BoxRequest.BodyType { if let jsonObject = json as? [String: Any] { return .jsonObject(jsonObject) } if let jsonArray = json as? [[String: Any]] { return .jsonArray(jsonArray) } return .empty } }
8b4804cae954b7b99237bcc37ff4e6c4
39.166998
168
0.619135
false
false
false
false
auth0/Auth0.swift
refs/heads/master
Auth0/Auth0.swift
mit
1
import Foundation /** `Result` wrapper for Authentication API operations. */ public typealias AuthenticationResult<T> = Result<T, AuthenticationError> /** `Result` wrapper for Management API operations. */ public typealias ManagementResult<T> = Result<T, ManagementError> #if WEB_AUTH_PLATFORM /** `Result` wrapper for Web Auth operations. */ public typealias WebAuthResult<T> = Result<T, WebAuthError> #endif /** `Result` wrapper for Credentials Manager operations. */ public typealias CredentialsManagerResult<T> = Result<T, CredentialsManagerError> /** Default scope value used across Auth0.swift. Equals to `openid profile email`. */ public let defaultScope = "openid profile email" /** Auth0 [Authentication API](https://auth0.com/docs/api/authentication) client to authenticate your user using Database, Social, Enterprise or Passwordless connections. ## Usage ```swift Auth0.authentication(clientId: "client-id", domain: "samples.us.auth0.com") ``` - Parameters: - clientId: Client ID of your Auth0 application. - domain: Domain of your Auth0 account, for example `samples.us.auth0.com`. - session: `URLSession` instance used for networking. Defaults to `URLSession.shared`. - Returns: Auth0 Authentication API client. */ public func authentication(clientId: String, domain: String, session: URLSession = .shared) -> Authentication { return Auth0Authentication(clientId: clientId, url: .httpsURL(from: domain), session: session) } /** Auth0 [Authentication API](https://auth0.com/docs/api/authentication) client to authenticate your user using Database, Social, Enterprise or Passwordless connections. ## Usage ```swift Auth0.authentication() ``` The Auth0 Client ID & Domain are loaded from the `Auth0.plist` file in your main bundle. It should have the following content: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>ClientId</key> <string>YOUR_AUTH0_CLIENT_ID</string> <key>Domain</key> <string>YOUR_AUTH0_DOMAIN</string> </dict> </plist> ``` - Parameters: - session: `URLSession` instance used for networking. Defaults to `URLSession.shared`. - bundle: Bundle used to locate the `Auth0.plist` file. Defaults to `Bundle.main`. - Returns: Auth0 Authentication API client. - Warning: Calling this method without a valid `Auth0.plist` file will crash your application. */ public func authentication(session: URLSession = .shared, bundle: Bundle = .main) -> Authentication { let values = plistValues(bundle: bundle)! return authentication(clientId: values.clientId, domain: values.domain, session: session) } /** Auth0 [Management API v2](https://auth0.com/docs/api/management/v2) client to perform operations with the Users endpoints. ## Usage ```swift Auth0.users(token: credentials.accessToken) ``` Currently you can only perform the following operations: * Get a user by ID * Update an user, for example by adding `user_metadata` * Link users * Unlink users The Auth0 Domain is loaded from the `Auth0.plist` file in your main bundle. It should have the following content: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>ClientId</key> <string>YOUR_AUTH0_CLIENT_ID</string> <key>Domain</key> <string>YOUR_AUTH0_DOMAIN</string> </dict> </plist> ``` - Parameters: - token: Management API token with the correct allowed scopes to perform the desired action. - session: `URLSession` instance used for networking. Defaults to `URLSession.shared`. - bundle: Bundle used to locate the `Auth0.plist` file. Defaults to `Bundle.main`. - Returns: Auth0 Management API v2 client. - Warning: Calling this method without a valid `Auth0.plist` file will crash your application. */ public func users(token: String, session: URLSession = .shared, bundle: Bundle = .main) -> Users { let values = plistValues(bundle: bundle)! return users(token: token, domain: values.domain, session: session) } /** Auth0 [Management API v2](https://auth0.com/docs/api/management/v2) client to perform operations with the Users endpoints. ## Usage ```swift Auth0.users(token: credentials.accessToken, domain: "samples.us.auth0.com") ``` Currently you can only perform the following operations: * Get a user by ID * Update an user, for example by adding `user_metadata` * Link users * Unlink users - Parameters: - token: Management API token with the correct allowed scopes to perform the desired action. - domain: Domain of your Auth0 account, for example `samples.us.auth0.com`. - session: `URLSession` instance used for networking. Defaults to `URLSession.shared`. - Returns: Auth0 Management API v2 client. */ public func users(token: String, domain: String, session: URLSession = .shared) -> Users { return Management(token: token, url: .httpsURL(from: domain), session: session) } #if WEB_AUTH_PLATFORM /** Auth0 client for performing web-based authentication with [Universal Login](https://auth0.com/docs/authenticate/login/auth0-universal-login). ## Usage ```swift Auth0.webAuth() ``` The Auth0 Domain is loaded from the `Auth0.plist` file in your main bundle. It should have the following content: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>ClientId</key> <string>YOUR_AUTH0_CLIENT_ID</string> <key>Domain</key> <string>YOUR_AUTH0_DOMAIN</string> </dict> </plist> ``` - Parameters: - session: `URLSession` instance used for networking. Defaults to `URLSession.shared`. - bundle: Bundle used to locate the `Auth0.plist` file. Defaults to `Bundle.main`. - Returns: Auth0 Web Auth client. - Warning: Calling this method without a valid `Auth0.plist` file will crash your application. */ public func webAuth(session: URLSession = .shared, bundle: Bundle = Bundle.main) -> WebAuth { let values = plistValues(bundle: bundle)! return webAuth(clientId: values.clientId, domain: values.domain, session: session) } /** Auth0 client for performing web-based authentication with [Universal Login](https://auth0.com/docs/authenticate/login/auth0-universal-login). ## Usage ```swift Auth0.webAuth(clientId: "client-id", domain: "samples.us.auth0.com") ``` - Parameters: - clientId: Client ID of your Auth0 application. - domain: Domain of your Auth0 account, for example `samples.us.auth0.com`. - session: `URLSession` instance used for networking. Defaults to `URLSession.shared`. - Returns: Auth0 Web Auth client. */ public func webAuth(clientId: String, domain: String, session: URLSession = .shared) -> WebAuth { return Auth0WebAuth(clientId: clientId, url: .httpsURL(from: domain), session: session) } #endif func plistValues(bundle: Bundle) -> (clientId: String, domain: String)? { guard let path = bundle.path(forResource: "Auth0", ofType: "plist"), let values = NSDictionary(contentsOfFile: path) as? [String: Any] else { print("Missing Auth0.plist file with 'ClientId' and 'Domain' entries in main bundle!") return nil } guard let clientId = values["ClientId"] as? String, let domain = values["Domain"] as? String else { print("Auth0.plist file at \(path) is missing 'ClientId' and/or 'Domain' entries!") print("File currently has the following entries: \(values)") return nil } return (clientId: clientId, domain: domain) }
f6b210f89a36f6bc8380dd5192539f72
33.495575
167
0.711904
false
false
false
false
takeshineshiro/XLForm
refs/heads/master
Examples/Swift/SwiftExample/DynamicSelector/DynamicSelectorsFormViewController.swift
mit
1
// // DynamicSelectorsFormViewController.swift // XLForm ( https://github.com/xmartlabs/XLForm ) // // Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. class DynamicSelectorsFormViewController : XLFormViewController { override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.initializeForm() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initializeForm() } func initializeForm() { let form = XLFormDescriptor(title: "Selectors") var section : XLFormSectionDescriptor var row : XLFormRowDescriptor // Basic Information section = XLFormSectionDescriptor.formSectionWithTitle("Dynamic Selectors") section.footerTitle = "DynamicSelectorsFormViewController.swift" form.addFormSection(section) // Selector Push row = XLFormRowDescriptor(tag: "selectorUser", rowType:XLFormRowDescriptorTypeSelectorPush, title:"User") row.action.viewControllerClass = UsersTableViewController.self section.addFormRow(row) if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad { // Selector PopOver row = XLFormRowDescriptor(tag: "selectorUserPopover", rowType:XLFormRowDescriptorTypeSelectorPopover, title:"User Popover") row.action.viewControllerClass = UsersTableViewController.self section.addFormRow(row) } self.form = form } }
fda6f2c10160ab5f316df00f92da91b8
41.968254
135
0.712966
false
false
false
false
michikono/how-tos
refs/heads/master
swift-using-typealiases-as-generics/swift-using-typealiases-as-generics.playground/Pages/4-0-constraining-generics-using-where.xcplaygroundpage/Contents.swift
mit
1
//: Constraining Generics using WHERE //: ================================= //: [Previous](@previous) protocol Material {} class Wood: Material {} class Glass: Material {} class Metal: Material {} class Cotton: Material {} protocol HouseholdThing { } protocol Furniture: HouseholdThing { typealias A: Any func label() -> A } class Chair: Furniture { func label() -> Int { return 0 } } class Lamp: Furniture { func label() -> String { return "" } } class FurnitureInspector<C: Furniture where C.A == Int> { func calculateLabel(thing: C) -> C.A { return thing.label() } } let inspector1 = FurnitureInspector<Chair>() //: This now returns C.A (which is constrained to an Int) inspector1.calculateLabel(Chair()) //: And this won't even compile because Lamp.label() is not an Int let inspector2 = FurnitureInspector<Lamp>() //: [Next](@next)
7e6e3031835e6f76f54671c8d20cc9c2
18.673913
66
0.628729
false
false
false
false
GianniCarlo/Audiobook-Player
refs/heads/BKPLY-52-player-redesign
BookPlayer/Library/Containers/MiniPlayerViewController.swift
gpl-3.0
1
// // NowPlayingViewController.swift // BookPlayer // // Created by Florian Pichler on 08.05.18. // Copyright © 2018 Tortuga Power. All rights reserved. // import BookPlayerKit import MarqueeLabel import Themeable import UIKit class MiniPlayerViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet private weak var miniPlayerBlur: UIVisualEffectView! @IBOutlet private weak var miniPlayerContainer: UIView! @IBOutlet private weak var artwork: BPArtworkView! @IBOutlet private weak var titleLabel: BPMarqueeLabel! @IBOutlet private weak var authorLabel: BPMarqueeLabel! @IBOutlet private weak var playPauseButton: UIButton! @IBOutlet private weak var artworkWidth: NSLayoutConstraint! @IBOutlet private weak var artworkHeight: NSLayoutConstraint! private let playImage = UIImage(named: "nowPlayingPlay") private let pauseImage = UIImage(named: "nowPlayingPause") private var tap: UITapGestureRecognizer! var showPlayer: (() -> Void)? var book: Book? { didSet { self.view.setNeedsLayout() guard let book = self.book else { return } self.artwork.image = book.getArtwork(for: themeProvider.currentTheme) self.authorLabel.text = book.author self.titleLabel.text = book.title let ratio = self.artwork.imageRatio self.artworkHeight.constant = ratio > 1 ? 50.0 / ratio : 50.0 self.artworkWidth.constant = ratio < 1 ? 50.0 * ratio : 50.0 setVoiceOverLabels() applyTheme(self.themeProvider.currentTheme) } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .clear setUpTheming() self.miniPlayerBlur.layer.cornerRadius = 13.0 self.miniPlayerBlur.layer.masksToBounds = true self.tap = UITapGestureRecognizer(target: self, action: #selector(self.tapAction)) self.tap.cancelsTouchesInView = true self.view.addGestureRecognizer(self.tap) NotificationCenter.default.addObserver(self, selector: #selector(self.onBookPlay), name: .bookPlayed, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.onBookPause), name: .bookPaused, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.onBookPause), name: .bookEnd, object: nil) } // MARK: Notification handlers @objc private func onBookPlay() { self.playPauseButton.setImage(self.pauseImage, for: UIControl.State()) self.playPauseButton.accessibilityLabel = "pause_title".localized } @objc private func onBookPause() { self.playPauseButton.setImage(self.playImage, for: UIControl.State()) self.playPauseButton.accessibilityLabel = "play_title".localized } // MARK: Actions @IBAction func playPause() { UIImpactFeedbackGenerator(style: .medium).impactOccurred() PlayerManager.shared.playPause() } // MARK: Gesture recognizers @objc func tapAction() { UIImpactFeedbackGenerator(style: .medium).impactOccurred() self.showPlayer?() } // MARK: - Voiceover private func setVoiceOverLabels() { let voiceOverTitle = self.titleLabel.text ?? "voiceover_no_title".localized let voiceOverSubtitle = self.authorLabel.text ?? "voiceover_no_author".localized self.titleLabel.accessibilityLabel = String(describing: String.localizedStringWithFormat("voiceover_currently_playing_title".localized, voiceOverTitle, voiceOverSubtitle)) self.titleLabel.accessibilityHint = "voiceover_miniplayer_hint".localized self.playPauseButton.accessibilityLabel = "play_title".localized self.artwork.isAccessibilityElement = false } } extension MiniPlayerViewController: Themeable { func applyTheme(_ theme: Theme) { self.titleLabel.textColor = theme.primaryColor self.authorLabel.textColor = theme.secondaryColor self.playPauseButton.tintColor = theme.linkColor self.miniPlayerContainer.backgroundColor = theme.secondarySystemBackgroundColor self.miniPlayerBlur.effect = theme.useDarkVariant ? UIBlurEffect(style: .dark) : UIBlurEffect(style: .light) } }
7f756816d03c8fc90ac2331419be839e
34.162602
179
0.70104
false
false
false
false
3ph/SplitSlider
refs/heads/develop
Example/Pods/Nimble/Sources/Nimble/Matchers/BeAnInstanceOf.swift
bsd-3-clause
19
import Foundation /// A Nimble matcher that succeeds when the actual value is an _exact_ instance of the given class. public func beAnInstanceOf<T>(_ expectedType: T.Type) -> Predicate<Any> { let errorMessage = "be an instance of \(String(describing: expectedType))" return Predicate.define { actualExpression in let instance = try actualExpression.evaluate() guard let validInstance = instance else { return PredicateResult( status: .doesNotMatch, message: .expectedActualValueTo(errorMessage) ) } let actualString = "<\(String(describing: type(of: validInstance))) instance>" return PredicateResult( status: PredicateStatus(bool: type(of: validInstance) == expectedType), message: .expectedCustomValueTo(errorMessage, actualString) ) } } /// A Nimble matcher that succeeds when the actual value is an instance of the given class. /// @see beAKindOf if you want to match against subclasses public func beAnInstanceOf(_ expectedClass: AnyClass) -> Predicate<NSObject> { let errorMessage = "be an instance of \(String(describing: expectedClass))" return Predicate.define { actualExpression in let instance = try actualExpression.evaluate() let actualString: String if let validInstance = instance { actualString = "<\(String(describing: type(of: validInstance))) instance>" } else { actualString = "<nil>" } #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) let matches = instance != nil && instance!.isMember(of: expectedClass) #else let matches = instance != nil && type(of: instance!) == expectedClass #endif return PredicateResult( status: PredicateStatus(bool: matches), message: .expectedCustomValueTo(errorMessage, actualString) ) } } #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) extension NMBObjCMatcher { @objc public class func beAnInstanceOfMatcher(_ expected: AnyClass) -> NMBMatcher { return NMBPredicate { actualExpression in return try beAnInstanceOf(expected).satisfies(actualExpression).toObjectiveC() } } } #endif
1dc43ae96ef21f3dfe664b4c22856bfd
39.803571
99
0.649015
false
false
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceModel/Sources/XCTEurofurenceModel/Random Value Generation/Characteristics/ConferenceDayCharacteristics+RandomValueProviding.swift
mit
1
import EurofurenceModel import Foundation import TestUtilities extension ConferenceDayCharacteristics: RandomValueProviding { public static var random: ConferenceDayCharacteristics { let randomDate = Date.random var components = Calendar.current.dateComponents(in: .current, from: randomDate) components.hour = 0 components.minute = 0 components.second = 0 components.nanosecond = 0 let normalizedDate = components.date.unsafelyUnwrapped return ConferenceDayCharacteristics(identifier: .random, date: normalizedDate) } }
b2f6d5eff12e13bbbeebbaadd933fa04
30.1
88
0.702572
false
false
false
false
Shivol/Swift-CS333
refs/heads/master
examples/uiKit/uiKitCatalog/UIKitCatalog/CustomSearchBarViewController.swift
mit
3
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A view controller that demonstrates how to customize a UISearchBar. */ import UIKit class CustomSearchBarViewController: UIViewController, UISearchBarDelegate { // MARK: - Properties @IBOutlet weak var searchBar: UISearchBar! // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() configureSearchBar() } // MARK: - Configuration func configureSearchBar() { searchBar.showsCancelButton = true searchBar.showsBookmarkButton = true searchBar.tintColor = UIColor.applicationPurpleColor searchBar.backgroundImage = UIImage(named: "search_bar_background") // Set the bookmark image for both normal and highlighted states. let bookmarkImage = UIImage(named: "bookmark_icon") searchBar.setImage(bookmarkImage, for: .bookmark, state: UIControlState()) let bookmarkHighlightedImage = UIImage(named: "bookmark_icon_highlighted") searchBar.setImage(bookmarkHighlightedImage, for: .bookmark, state: .highlighted) } // MARK: - UISearchBarDelegate func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { NSLog("The custom search bar keyboard search button was tapped: \(searchBar).") searchBar.resignFirstResponder() } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { NSLog("The custom search bar cancel button was tapped.") searchBar.resignFirstResponder() } func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) { NSLog("The custom bookmark button inside the search bar was tapped.") } }
61b4e0f2040cf967c8212a7e3ebd2d9a
29.288136
89
0.692781
false
true
false
false
LYM-mg/DemoTest
refs/heads/master
其他功能/MGBookViews/MGBookViews/下划线/UIView+ViewFrameGeometry.swift
mit
1
// // UIView+ViewFrameGeometry.swift // SwiftTools // // Created by Tassel on 2017/10/18. // Copyright © 2017年 Tassel. All rights reserved. // import UIKit public extension UIView { // MARK: var x:CGFloat { set { var newFrame = self.frame newFrame.origin.x = _pixelIntergral(newValue) self.frame = newFrame } get { return self.frame.origin.x } } var y:CGFloat { set { var newFrame = self.frame newFrame.origin.y = _pixelIntergral(newValue) self.frame = newFrame } get { return self.frame.origin.y } } var width:CGFloat { set { var newFrame = self.frame newFrame.size.width = _pixelIntergral(newValue) self.frame = newFrame } get { return self.frame.size.width } } var height:CGFloat { set { var newFrame = self.frame newFrame.size.height = _pixelIntergral(newValue) self.frame = newFrame } get { return self.frame.size.height } } var top:CGFloat { set { var newFrame = self.frame newFrame.origin.y = _pixelIntergral(newValue) self.frame = newFrame } get { return self.y } } var bottom:CGFloat { set { var newFrame = self.frame newFrame.origin.y = _pixelIntergral(newValue) - self.height self.frame = newFrame } get { return self.y+self.height } } var left:CGFloat { set { var newFrame = self.frame newFrame.origin.x = _pixelIntergral(newValue) self.frame = newFrame } get { return self.y } } var right:CGFloat { set { var newFrame = self.frame newFrame.origin.x = _pixelIntergral(newValue) - self.width self.frame = newFrame } get { return self.x+self.width } } var origin:CGPoint { set { var newFrame = self.frame newFrame.origin = newValue self.frame = newFrame } get { return self.frame.origin } } var size:CGSize { set { var newFrame = self.frame newFrame.size = newValue self.frame = newFrame } get { return self.frame.size } } // MARK: - Private Methods fileprivate func _pixelIntergral(_ pointValue:CGFloat)->CGFloat { let scale = UIScreen.main.scale return (round(pointValue*scale)/scale) } /// 查找一个视图的所有子视图 func allSubViewsForView(view: UIView) -> [UIView] { var array = [UIView]() for subView in view.subviews { array.append(subView) if (subView.subviews.count > 0) { // 递归 let childView = self.allSubViewsForView(view: subView) array += childView } } return array } }
470652e01bf7a5cf3db9b09ebb528458
20.301205
72
0.450226
false
false
false
false
ALiOSDev/ALTableView
refs/heads/develop
ALTableViewSwift/Pods/SwipeCellKit/Source/SwipeFeedback.swift
apache-2.0
10
// // SwipeFeedback.swift // // Created by Jeremy Koch // Copyright © 2017 Jeremy Koch. All rights reserved. // import UIKit final class SwipeFeedback { enum Style { case light case medium case heavy } @available(iOS 10.0.1, *) private var feedbackGenerator: UIImpactFeedbackGenerator? { get { return _feedbackGenerator as? UIImpactFeedbackGenerator } set { _feedbackGenerator = newValue } } private var _feedbackGenerator: Any? init(style: Style) { if #available(iOS 10.0.1, *) { switch style { case .light: feedbackGenerator = UIImpactFeedbackGenerator(style: .light) case .medium: feedbackGenerator = UIImpactFeedbackGenerator(style: .medium) case .heavy: feedbackGenerator = UIImpactFeedbackGenerator(style: .heavy) } } else { _feedbackGenerator = nil } } func prepare() { if #available(iOS 10.0.1, *) { feedbackGenerator?.prepare() } } func impactOccurred() { if #available(iOS 10.0.1, *) { feedbackGenerator?.impactOccurred() } } }
5b4b621b94fc24e5978177f2b21c6d34
22.160714
77
0.538936
false
false
false
false
PopcornTimeTV/PopcornTimeTV
refs/heads/master
PopcornTime/UI/tvOS/Views/BufferingBar.swift
gpl-3.0
1
import Foundation class BufferingBar: UIView { var bufferProgress: Float = 1.0 { didSet { setNeedsLayout() } } var elapsedProgress: Float = 0.0 { didSet { setNeedsLayout() } } var bufferColor: UIColor = .clear { didSet { bufferView.contentView.tintColor = bufferColor } } var borderColor: UIColor = UIColor(white: 1.0, alpha: 0.5) { didSet { borderLayer.borderColor = borderColor.cgColor } } var elapsedColor: UIColor = .clear { didSet { elapsedView.contentView.tintColor = elapsedColor } } private let borderLayer = CAShapeLayer() private let borderMaskLayer = CAShapeLayer() private let elapsedView = UIVisualEffectView(effect: UIBlurEffect(style: .light)) private let elapsedMaskLayer = CAShapeLayer() private let bufferView = UIVisualEffectView(effect: UIBlurEffect(style: .light)) private let bufferMaskLayer = CAShapeLayer() override init(frame: CGRect) { super.init(frame: frame) sharedSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) sharedSetup() } func sharedSetup() { borderLayer.borderWidth = 1.0 borderLayer.borderColor = borderColor.cgColor borderLayer.fillColor = UIColor.clear.cgColor borderLayer.mask = borderMaskLayer bufferView.layer.mask = bufferMaskLayer bufferView.contentView.tintColor = bufferColor elapsedView.layer.mask = elapsedMaskLayer elapsedView.contentView.tintColor = elapsedColor layer.addSublayer(borderLayer) addSubview(elapsedView) addSubview(bufferView) } override func layoutSubviews() { super.layoutSubviews() let inset = borderLayer.lineWidth/2.0 let borderRect = bounds.insetBy(dx: inset, dy: inset) let radius = bounds.size.height/2.0 let path = UIBezierPath(roundedRect: borderRect, cornerRadius: radius) borderLayer.path = path.cgPath borderMaskLayer.path = path.cgPath borderMaskLayer.frame = bounds borderLayer.frame = bounds let playerRect = CGRect(origin: .zero, size: CGSize(width: bounds.width * CGFloat(elapsedProgress), height: bounds.height)) elapsedMaskLayer.path = path.cgPath elapsedMaskLayer.frame = bounds elapsedView.frame = playerRect let bufferRect = CGRect(origin: .zero, size: CGSize(width: bounds.width * CGFloat(bufferProgress), height: bounds.height)) bufferMaskLayer.path = path.cgPath bufferMaskLayer.frame = bounds bufferView.frame = bufferRect } }
3bacd877a00cf2699f5885c55439c830
29.631579
131
0.613402
false
false
false
false
loudnate/LoopKit
refs/heads/master
LoopKit/GlucoseKit/GlucoseMath.swift
mit
1
// // GlucoseMath.swift // Naterade // // Created by Nathan Racklyeft on 1/24/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import HealthKit fileprivate extension Collection where Element == (x: Double, y: Double) { /** Calculates slope and intercept using linear regression This implementation is not suited for large datasets. - parameter points: An array of tuples containing x and y values - returns: A tuple of slope and intercept values */ func linearRegression() -> (slope: Double, intercept: Double) { var sumX = 0.0 var sumY = 0.0 var sumXY = 0.0 var sumX² = 0.0 var sumY² = 0.0 let count = Double(self.count) for point in self { sumX += point.x sumY += point.y sumXY += (point.x * point.y) sumX² += (point.x * point.x) sumY² += (point.y * point.y) } let slope = ((count * sumXY) - (sumX * sumY)) / ((count * sumX²) - (sumX * sumX)) let intercept = (sumY * sumX² - (sumX * sumXY)) / (count * sumX² - (sumX * sumX)) return (slope: slope, intercept: intercept) } } extension BidirectionalCollection where Element: GlucoseSampleValue, Index == Int { /// Whether the collection contains no calibration entries /// Runtime: O(n) var isCalibrated: Bool { return filter({ $0.isDisplayOnly }).count == 0 } /// Filters a timeline of glucose samples to only include those after the last calibration. func filterAfterCalibration() -> [Element] { var postCalibration = true return reversed().filter({ (sample) in if sample.isDisplayOnly { postCalibration = false } return postCalibration }).reversed() } /// Whether the collection can be considered continuous /// /// - Parameters: /// - interval: The interval between readings, on average, used to determine if we have a contiguous set of values /// - Returns: True if the samples are continuous func isContinuous(within interval: TimeInterval = TimeInterval(minutes: 5)) -> Bool { if let first = first, let last = last, // Ensure that the entries are contiguous abs(first.startDate.timeIntervalSince(last.startDate)) < interval * TimeInterval(count) { return true } return false } /// Calculates the short-term predicted momentum effect using linear regression /// /// - Parameters: /// - duration: The duration of the effects /// - delta: The time differential for the returned values /// - Returns: An array of glucose effects func linearMomentumEffect( duration: TimeInterval = TimeInterval(minutes: 30), delta: TimeInterval = TimeInterval(minutes: 5) ) -> [GlucoseEffect] { guard self.count > 2, // Linear regression isn't much use without 3 or more entries. isContinuous() && isCalibrated && hasSingleProvenance, let firstSample = self.first, let lastSample = self.last, let (startDate, endDate) = LoopMath.simulationDateRangeForSamples([lastSample], duration: duration, delta: delta) else { return [] } /// Choose a unit to use during raw value calculation let unit = HKUnit.milligramsPerDeciliter let (slope: slope, intercept: _) = self.map { ( x: $0.startDate.timeIntervalSince(firstSample.startDate), y: $0.quantity.doubleValue(for: unit) ) }.linearRegression() guard slope.isFinite else { return [] } var date = startDate var values = [GlucoseEffect]() repeat { let value = Swift.max(0, date.timeIntervalSince(lastSample.startDate)) * slope values.append(GlucoseEffect(startDate: date, quantity: HKQuantity(unit: unit, doubleValue: value))) date = date.addingTimeInterval(delta) } while date <= endDate return values } } extension Collection where Element: GlucoseSampleValue, Index == Int { /// Whether the collection is all from the same source. /// Runtime: O(n) var hasSingleProvenance: Bool { let firstProvenance = self.first?.provenanceIdentifier for sample in self { if sample.provenanceIdentifier != firstProvenance { return false } } return true } /// Calculates a timeline of effect velocity (glucose/time) observed in glucose readings that counteract the specified effects. /// /// - Parameter effects: Glucose effects to be countered, in chronological order /// - Returns: An array of velocities describing the change in glucose samples compared to the specified effects func counteractionEffects(to effects: [GlucoseEffect]) -> [GlucoseEffectVelocity] { let mgdL = HKUnit.milligramsPerDeciliter let velocityUnit = GlucoseEffectVelocity.perSecondUnit var velocities = [GlucoseEffectVelocity]() var effectIndex = 0 var startGlucose: Element! = self.first for endGlucose in self.dropFirst() { // Find a valid change in glucose, requiring identical provenance and no calibration let glucoseChange = endGlucose.quantity.doubleValue(for: mgdL) - startGlucose.quantity.doubleValue(for: mgdL) let timeInterval = endGlucose.startDate.timeIntervalSince(startGlucose.startDate) guard timeInterval > .minutes(4) else { continue } defer { startGlucose = endGlucose } guard startGlucose.provenanceIdentifier == endGlucose.provenanceIdentifier, !startGlucose.isDisplayOnly, !endGlucose.isDisplayOnly else { continue } // Compare that to a change in insulin effects guard effects.count > effectIndex else { break } var startEffect: GlucoseEffect? var endEffect: GlucoseEffect? for effect in effects[effectIndex..<effects.count] { if startEffect == nil && effect.startDate >= startGlucose.startDate { startEffect = effect } else if endEffect == nil && effect.startDate >= endGlucose.startDate { endEffect = effect break } effectIndex += 1 } guard let startEffectValue = startEffect?.quantity.doubleValue(for: mgdL), let endEffectValue = endEffect?.quantity.doubleValue(for: mgdL) else { break } let effectChange = endEffectValue - startEffectValue let discrepancy = glucoseChange - effectChange let averageVelocity = HKQuantity(unit: velocityUnit, doubleValue: discrepancy / timeInterval) let effect = GlucoseEffectVelocity(startDate: startGlucose.startDate, endDate: endGlucose.startDate, quantity: averageVelocity) velocities.append(effect) } return velocities } }
f313acdb217abf33c5905a36efb7c7d4
33.327103
139
0.607678
false
false
false
false
maximkhatskevich/MKHUniFlow
refs/heads/master
Sources/ByTypeStorage/ByTypeStorage+History.swift
mit
1
/* MIT License Copyright (c) 2016 Maxim Khatskevich ([email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation //--- public extension ByTypeStorage { typealias History = [HistoryElement] struct HistoryElement { public let timestamp: Date = .init() public let outcome: MutationAttemptOutcome } } //--- public extension ByTypeStorage.HistoryElement { var key: SomeStateful.Type { switch self.outcome { case .initialization(let key, _), .actualization(let key, _, _), .transition(let key, _, _), .deinitialization(let key, _), .nothingToRemove(let key): return key } } } // MARK: - AnyMutation helpers public extension ByTypeStorage.HistoryElement { struct AnyMutationOutcome { public let timestamp: Date public let key: SomeStateful.Type public let oldValue: SomeStateBase? public let newValue: SomeStateBase? } var asAnyMutation: AnyMutationOutcome? { switch self.outcome { case let .initialization(key, newValue): return .init( timestamp: self.timestamp, key: key, oldValue: nil, newValue: newValue ) case let .actualization(key, oldValue, newValue), let .transition(key, oldValue, newValue): return .init( timestamp: self.timestamp, key: key, oldValue: oldValue, newValue: newValue ) case let .deinitialization(key, oldValue): return .init( timestamp: self.timestamp, key: key, oldValue: oldValue, newValue: nil ) default: return nil } } var isAnyMutation: Bool { asAnyMutation != nil } } // MARK: - Initialization helpers public extension ByTypeStorage.HistoryElement { struct InitializationOutcome { public let timestamp: Date public let key: SomeStateful.Type public let newValue: SomeStateBase } var asInitialization: InitializationOutcome? { switch self.outcome { case let .initialization(key, newValue): return .init( timestamp: self.timestamp, key: key, newValue: newValue ) default: return nil } } var isInitialization: Bool { asInitialization != nil } } // MARK: - Setting helpers public extension ByTypeStorage.HistoryElement { /// Operation that results with given key being present in the storage. struct SettingOutcome { public let timestamp: Date public let key: SomeStateful.Type public let newValue: SomeStateBase } /// Operation that results with given key being present in the storage. var asSetting: SettingOutcome? { switch self.outcome { case let .initialization(key, newValue), let .actualization(key, _, newValue), let .transition(key, _, newValue): return .init( timestamp: self.timestamp, key: key, newValue: newValue ) default: return nil } } /// Operation that results with given key being present in the storage. var isSetting: Bool { asSetting != nil } } // MARK: - Update helpers public extension ByTypeStorage.HistoryElement { /// Operation that has both old and new values. struct UpdateOutcome { public let timestamp: Date public let key: SomeStateful.Type public let oldValue: SomeStateBase public let newValue: SomeStateBase } /// Operation that has both old and new values. var asUpdate: UpdateOutcome? { switch self.outcome { case let .actualization(key, oldValue, newValue), let .transition(key, oldValue, newValue): return .init( timestamp: self.timestamp, key: key, oldValue: oldValue, newValue: newValue ) default: return nil } } /// Operation that has both old and new values. var isUpdate: Bool { asUpdate != nil } } // MARK: - Actualization helpers public extension ByTypeStorage.HistoryElement { struct ActualizationOutcome { public let timestamp: Date public let key: SomeStateful.Type public let oldValue: SomeStateBase public let newValue: SomeStateBase } var asActualization: ActualizationOutcome? { switch self.outcome { case let .actualization(key, oldValue, newValue): return .init( timestamp: self.timestamp, key: key, oldValue: oldValue, newValue: newValue ) default: return nil } } var isActualization: Bool { asActualization != nil } } // MARK: - Transition helpers public extension ByTypeStorage.HistoryElement { struct TransitionOutcome { public let timestamp: Date public let key: SomeStateful.Type public let oldValue: SomeStateBase public let newValue: SomeStateBase } var asTransition: TransitionOutcome? { switch self.outcome { case let .transition(key, oldValue, newValue): return .init( timestamp: self.timestamp, key: key, oldValue: oldValue, newValue: newValue ) default: return nil } } var isTransition: Bool { asTransition != nil } } // MARK: - Deinitialization helpers public extension ByTypeStorage.HistoryElement { struct DeinitializationOutcome { public let timestamp: Date public let key: SomeStateful.Type public let oldValue: SomeStateBase } var asDeinitialization: DeinitializationOutcome? { switch self.outcome { case let .deinitialization(key, oldValue): return .init( timestamp: self.timestamp, key: key, oldValue: oldValue ) default: return nil } } var isDeinitialization: Bool { asDeinitialization != nil } } // MARK: - BlankRemoval helpers public extension ByTypeStorage.HistoryElement { struct BlankRemovalOutcome { public let timestamp: Date public let key: SomeStateful.Type } var asBlankRemovalOutcome: BlankRemovalOutcome? { switch self.outcome { case let .nothingToRemove(key): return .init( timestamp: self.timestamp, key: key ) default: return nil } } var isBlankRemoval: Bool { asBlankRemovalOutcome != nil } }
2414a19b1da07e288f9c5ef014910be8
21.369668
103
0.513771
false
false
false
false
tomw/SwiftySunrise
refs/heads/master
SwiftySunrise/SwiftySunrise.swift
mit
1
// // SwiftySunrise.swift // // Copyright (c) 2016 Tom Weightman // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation //MARK:- Main class final public class SwiftySunrise { //MARK: Types public enum SunPhase { case sunrise case sunset } public enum TwilightType: Int { case official = 90 case civil = 96 case nautical = 102 case astronomical = 108 } //MARK: Public functions public static func sunPhaseTime(forPhase phase: SunPhase, withTwilightType twilightType: TwilightType = .official, onDay date: Date, atLatitude latitude: Double, andLongitude longitude: Double) -> Date? { var calendar = Calendar(identifier: .gregorian) calendar.timeZone = TimeZone(identifier: "Etc/UTC")! //pretty sure UTC wont disappear! let dateComponents = calendar.dateComponents([ .timeZone, .day, .month, .year ], from: date) let day = dateComponents.day! let month = dateComponents.month! let year = dateComponents.year! //Calculate day of the year let n1 = floor(275 * Double(month) / 9) let n2 = floor(Double(month + 9) / 12) let n3 = 1 + floor((Double(year) - 4 * floor(Double(year) / 4) + 2) / 3) let dayOfYear = n1 - (n2 * n3) + Double(day) - 30 //Convert longitude to hour value let lngHour = longitude / 15 let t: Double switch phase { case .sunrise: t = dayOfYear + ((6 - lngHour) / 24) case .sunset: t = dayOfYear + ((18 - lngHour) / 24) } //Sun's mean anomaly let meanAnomaly = (0.9856 * t) - 3.289 //Sun's true longitude let trueLongitude = fixRange(meanAnomaly + (1.916 * sin(degrees: meanAnomaly)) + (0.020 * sin(degrees: 2 * meanAnomaly)) + 282.634, max: 360) //Sun's right ascension var rightAscension = fixRange(atan(degrees: 0.91764 * tan(degrees: trueLongitude)), max: 360) let lQuadrant = (floor(trueLongitude / 90)) * 90 let raQquadrant = (floor(rightAscension / 90)) * 90 rightAscension += (lQuadrant - raQquadrant) //needs to be in same quandrant as l rightAscension /= 15 //convert to hours //Sun's declination let sinDec = 0.39782 * sin(degrees: trueLongitude) let cosDec = cos(degrees: asin(degrees: sinDec)) //Sun's local hour angle let cosH = (cos(degrees: Double(twilightType.rawValue)) - (sinDec * sin(degrees: latitude))) / (cosDec * cos(degrees: latitude)) if (cosH > 1) { //Sun never rises at this location/day return nil } else if (cosH < -1) { //Sun never sets at this location/day return nil } //Calculate hour let hour: Double switch phase { case .sunrise: hour = (360 - acos(degrees: cosH)) / 15 case .sunset: hour = acos(degrees: cosH) / 15 } //Local time of rising/setting let localTime = hour + rightAscension - (0.06571 * t) - 6.622 let localTimeHourUTC = fixRange(localTime - lngHour, max: 24) var resultDateComponentsUTC = DateComponents() resultDateComponentsUTC.timeZone = calendar.timeZone resultDateComponentsUTC.calendar = calendar resultDateComponentsUTC.day = dateComponents.day resultDateComponentsUTC.month = dateComponents.month resultDateComponentsUTC.year = dateComponents.year resultDateComponentsUTC.hour = Int(localTimeHourUTC) resultDateComponentsUTC.minute = Int((localTimeHourUTC - floor(localTimeHourUTC)) * 60) let resultDate = calendar.date(from: resultDateComponentsUTC) return resultDate } } //MARK:- Date extension public extension Date { public func toSunPhase(forPhase phase: SwiftySunrise.SunPhase, withTwilightType twilightType: SwiftySunrise.TwilightType = .official, atLatitude latitude: Double, andLongitude longitude: Double) -> Date? { return SwiftySunrise.sunPhaseTime(forPhase: phase, withTwilightType: twilightType, onDay: self, atLatitude: latitude, andLongitude: longitude) } public init?(sunPhaseToday sunPhase: SwiftySunrise.SunPhase, withTwilightType twilightType: SwiftySunrise.TwilightType = .official, latitude: Double, longitude: Double) { if let sunPhaseDate = Date().toSunPhase(forPhase: sunPhase, withTwilightType: twilightType, atLatitude: latitude, andLongitude: longitude) { self = sunPhaseDate } else { return nil } } } //MARK:- Convenience functions fileprivate extension SwiftySunrise { // e.g. angle is within 0...360 degrees fileprivate static func fixRange(_ x: Double, max: Double) -> Double { return x - max * floor(x * (1 / max)) } }
fe2220fdc43501efe31f4b2fe7de192d
37.037037
209
0.630477
false
false
false
false
Ashok28/Kingfisher
refs/heads/master
Sources/General/KF.swift
mit
1
// // KF.swift // Kingfisher // // Created by onevcat on 2020/09/21. // // Copyright (c) 2020 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 canImport(UIKit) import UIKit #endif #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit #endif #if canImport(WatchKit) import WatchKit #endif #if canImport(TVUIKit) import TVUIKit #endif /// A helper type to create image setting tasks in a builder pattern. /// Use methods in this type to create a `KF.Builder` instance and configure image tasks there. public enum KF { /// Creates a builder for a given `Source`. /// - Parameter source: The `Source` object defines data information from network or a data provider. /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` /// to start the image loading. public static func source(_ source: Source?) -> KF.Builder { Builder(source: source) } /// Creates a builder for a given `Resource`. /// - Parameter resource: The `Resource` object defines data information like key or URL. /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` /// to start the image loading. public static func resource(_ resource: Resource?) -> KF.Builder { source(resource?.convertToSource()) } /// Creates a builder for a given `URL` and an optional cache key. /// - Parameters: /// - url: The URL where the image should be downloaded. /// - cacheKey: The key used to store the downloaded image in cache. /// If `nil`, the `absoluteString` of `url` is used as the cache key. /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` /// to start the image loading. public static func url(_ url: URL?, cacheKey: String? = nil) -> KF.Builder { source(url?.convertToSource(overrideCacheKey: cacheKey)) } /// Creates a builder for a given `ImageDataProvider`. /// - Parameter provider: The `ImageDataProvider` object contains information about the data. /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` /// to start the image loading. public static func dataProvider(_ provider: ImageDataProvider?) -> KF.Builder { source(provider?.convertToSource()) } /// Creates a builder for some given raw data and a cache key. /// - Parameters: /// - data: The data object from which the image should be created. /// - cacheKey: The key used to store the downloaded image in cache. /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` /// to start the image loading. public static func data(_ data: Data?, cacheKey: String) -> KF.Builder { if let data = data { return dataProvider(RawImageDataProvider(data: data, cacheKey: cacheKey)) } else { return dataProvider(nil) } } } extension KF { /// A builder class to configure an image retrieving task and set it to a holder view or component. public class Builder { private let source: Source? #if os(watchOS) private var placeholder: KFCrossPlatformImage? #else private var placeholder: Placeholder? #endif public var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions) public let onFailureDelegate = Delegate<KingfisherError, Void>() public let onSuccessDelegate = Delegate<RetrieveImageResult, Void>() public let onProgressDelegate = Delegate<(Int64, Int64), Void>() init(source: Source?) { self.source = source } private var resultHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? { { switch $0 { case .success(let result): self.onSuccessDelegate(result) case .failure(let error): self.onFailureDelegate(error) } } } private var progressBlock: DownloadProgressBlock { { self.onProgressDelegate(($0, $1)) } } } } extension KF.Builder { #if !os(watchOS) /// Builds the image task request and sets it to an image view. /// - Parameter imageView: The image view which loads the task and should be set with the image. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @discardableResult public func set(to imageView: KFCrossPlatformImageView) -> DownloadTask? { imageView.kf.setImage( with: source, placeholder: placeholder, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } /// Builds the image task request and sets it to an `NSTextAttachment` object. /// - Parameters: /// - attachment: The text attachment object which loads the task and should be set with the image. /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @discardableResult public func set(to attachment: NSTextAttachment, attributedView: @autoclosure @escaping () -> KFCrossPlatformView) -> DownloadTask? { let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil return attachment.kf.setImage( with: source, attributedView: attributedView, placeholder: placeholderImage, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } #if canImport(UIKit) /// Builds the image task request and sets it to a button. /// - Parameters: /// - button: The button which loads the task and should be set with the image. /// - state: The button state to which the image should be set. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @discardableResult public func set(to button: UIButton, for state: UIControl.State) -> DownloadTask? { let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil return button.kf.setImage( with: source, for: state, placeholder: placeholderImage, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } /// Builds the image task request and sets it to the background image for a button. /// - Parameters: /// - button: The button which loads the task and should be set with the image. /// - state: The button state to which the image should be set. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @discardableResult public func setBackground(to button: UIButton, for state: UIControl.State) -> DownloadTask? { let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil return button.kf.setBackgroundImage( with: source, for: state, placeholder: placeholderImage, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } #endif // end of canImport(UIKit) #if canImport(AppKit) && !targetEnvironment(macCatalyst) /// Builds the image task request and sets it to a button. /// - Parameter button: The button which loads the task and should be set with the image. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @discardableResult public func set(to button: NSButton) -> DownloadTask? { let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil return button.kf.setImage( with: source, placeholder: placeholderImage, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } /// Builds the image task request and sets it to the alternative image for a button. /// - Parameter button: The button which loads the task and should be set with the image. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @discardableResult public func setAlternative(to button: NSButton) -> DownloadTask? { let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil return button.kf.setAlternateImage( with: source, placeholder: placeholderImage, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } #endif // end of canImport(AppKit) #endif // end of !os(watchOS) #if canImport(WatchKit) /// Builds the image task request and sets it to a `WKInterfaceImage` object. /// - Parameter interfaceImage: The watch interface image which loads the task and should be set with the image. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @discardableResult public func set(to interfaceImage: WKInterfaceImage) -> DownloadTask? { return interfaceImage.kf.setImage( with: source, placeholder: placeholder, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } #endif // end of canImport(WatchKit) #if canImport(TVUIKit) /// Builds the image task request and sets it to a TV monogram view. /// - Parameter monogramView: The monogram view which loads the task and should be set with the image. /// - Returns: A task represents the image downloading, if initialized. /// This value is `nil` if the image is being loaded from cache. @available(tvOS 12.0, *) @discardableResult public func set(to monogramView: TVMonogramView) -> DownloadTask? { let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil return monogramView.kf.setImage( with: source, placeholder: placeholderImage, parsedOptions: options, progressBlock: progressBlock, completionHandler: resultHandler ) } #endif // end of canImport(TVUIKit) } #if !os(watchOS) extension KF.Builder { #if os(iOS) || os(tvOS) /// Sets a placeholder which is used while retrieving the image. /// - Parameter placeholder: A placeholder to show while retrieving the image from its source. /// - Returns: A `KF.Builder` with changes applied. public func placeholder(_ placeholder: Placeholder?) -> Self { self.placeholder = placeholder return self } #endif /// Sets a placeholder image which is used while retrieving the image. /// - Parameter placeholder: An image to show while retrieving the image from its source. /// - Returns: A `KF.Builder` with changes applied. public func placeholder(_ image: KFCrossPlatformImage?) -> Self { self.placeholder = image return self } } #endif extension KF.Builder { #if os(iOS) || os(tvOS) /// Sets the transition for the image task. /// - Parameter transition: The desired transition effect when setting the image to image view. /// - Returns: A `KF.Builder` with changes applied. /// /// Kingfisher will use the `transition` to animate the image in if it is downloaded from web. /// The transition will not happen when the /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when /// the image being retrieved from cache, also call `forceRefresh()` on the returned `KF.Builder`. public func transition(_ transition: ImageTransition) -> Self { options.transition = transition return self } /// Sets a fade transition for the image task. /// - Parameter duration: The duration of the fade transition. /// - Returns: A `KF.Builder` with changes applied. /// /// Kingfisher will use the fade transition to animate the image in if it is downloaded from web. /// The transition will not happen when the /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when /// the image being retrieved from cache, also call `forceRefresh()` on the returned `KF.Builder`. public func fade(duration: TimeInterval) -> Self { options.transition = .fade(duration) return self } #endif /// Sets whether keeping the existing image of image view while setting another image to it. /// - Parameter enabled: Whether the existing image should be kept. /// - Returns: A `KF.Builder` with changes applied. /// /// By setting this option, the placeholder image parameter of image view extension method /// will be ignored and the current image will be kept while loading or downloading the new image. /// public func keepCurrentImageWhileLoading(_ enabled: Bool = true) -> Self { options.keepCurrentImageWhileLoading = enabled return self } /// Sets whether only the first frame from an animated image file should be loaded as a single image. /// - Parameter enabled: Whether the only the first frame should be loaded. /// - Returns: A `KF.Builder` with changes applied. /// /// Loading an animated images may take too much memory. It will be useful when you want to display a /// static preview of the first frame from an animated image. /// /// This option will be ignored if the target image is not animated image data. /// public func onlyLoadFirstFrame(_ enabled: Bool = true) -> Self { options.onlyLoadFirstFrame = enabled return self } /// Sets the image that will be used if an image retrieving task fails. /// - Parameter image: The image that will be used when something goes wrong. /// - Returns: A `KF.Builder` with changes applied. /// /// If set and an image retrieving error occurred Kingfisher will set provided image (or empty) /// in place of requested one. It's useful when you don't want to show placeholder /// during loading time but wants to use some default image when requests will be failed. /// public func onFailureImage(_ image: KFCrossPlatformImage?) -> Self { options.onFailureImage = .some(image) return self } /// Enables progressive image loading with a specified `ImageProgressive` setting to process the /// progressive JPEG data and display it in a progressive way. /// - Parameter progressive: The progressive settings which is used while loading. /// - Returns: A `KF.Builder` with changes applied. public func progressiveJPEG(_ progressive: ImageProgressive? = .default) -> Self { options.progressiveJPEG = progressive return self } } // MARK: - Deprecated extension KF.Builder { /// Starts the loading process of `self` immediately. /// /// By default, a `KFImage` will not load its source until the `onAppear` is called. This is a lazily loading /// behavior and provides better performance. However, when you refresh the view, the lazy loading also causes a /// flickering since the loading does not happen immediately. Call this method if you want to start the load at once /// could help avoiding the flickering, with some performance trade-off. /// /// - Deprecated: This is not necessary anymore since `@StateObject` is used for holding the image data. /// It does nothing now and please just remove it. /// /// - Returns: The `Self` value with changes applied. @available(*, deprecated, message: "This is not necessary anymore since `@StateObject` is used. It does nothing now and please just remove it.") public func loadImmediately(_ start: Bool = true) -> Self { return self } } // MARK: - Redirect Handler extension KF { /// Represents the detail information when a task redirect happens. It is wrapping necessary information for a /// `ImageDownloadRedirectHandler`. See that protocol for more information. public struct RedirectPayload { /// The related session data task when the redirect happens. It is /// the current `SessionDataTask` which triggers this redirect. public let task: SessionDataTask /// The response received during redirection. public let response: HTTPURLResponse /// The request for redirection which can be modified. public let newRequest: URLRequest /// A closure for being called with modified request. public let completionHandler: (URLRequest?) -> Void } }
7c1ced982b2e2562ffb0a66d5e692c41
42.523364
148
0.664269
false
false
false
false
P0ed/Fx
refs/heads/master
Sources/Fx/Extensions/Timer.swift
mit
1
#if canImport(UIKit) import UIKit #elseif canImport(AppKit) import AppKit #endif public extension Timer { static func once(_ interval: TimeInterval, _ function: @escaping () -> Void) -> ActionDisposable { makeTimer(offset: interval, repeats: nil, function: function) } static func `repeat`(_ interval: TimeInterval, _ function: @escaping () -> Void) -> ActionDisposable { makeTimer(offset: interval, repeats: interval, function: function) } static func makeTimer(offset: TimeInterval, repeats: TimeInterval?, function: @escaping () -> Void) -> ActionDisposable { var timer = nil as Timer? let makeTimer = { [date = Date().addingTimeInterval(offset), function] in timer = Timer( fire: date, interval: repeats ?? 0, repeats: repeats != nil, block: { _ in function() } ) RunLoop.current.add(timer!, forMode: .default) } makeTimer() let observer = observeDidBecomeActiveNotificationSignal { _ in guard timer?.isValid == false else { return } makeTimer() } return observer • ActionDisposable { timer?.invalidate() } } private static func observeDidBecomeActiveNotificationSignal(handler: @escaping (Notification) -> Void) -> ActionDisposable { #if os(iOS) || os(tvOS) return NotificationCenter.default.addObserver(name: UIApplication.didBecomeActiveNotification, handler: handler) #elseif os(macOS) return NotificationCenter.default.addObserver(name: NSApplication.didBecomeActiveNotification, handler: handler) #else return ActionDisposable {} #endif } }
7068e0d1a4ecac82c451cd900234df90
29.176471
126
0.717999
false
false
false
false
yasuo-/smartNews-clone
refs/heads/master
Pods/WBSegmentControl/Framework/WBSegmentControl/WBSegmentControl.swift
mit
1
// // CustomSegmentControl2.swift // TrafficSecretary // // Created by 王继荣 on 4/9/16. // Copyright © 2016 wonderbear. All rights reserved. // import UIKit public protocol WBSegmentControlDelegate { func segmentControl(_ segmentControl: WBSegmentControl, selectIndex newIndex: Int, oldIndex: Int) } public protocol WBSegmentContentProtocol { var type: WBSegmentType { get } } public protocol WBTouchViewDelegate { func didTouch(_ location: CGPoint) } public class WBSegmentControl: UIControl { // MARK: Configuration - Content public var segments: [WBSegmentContentProtocol] = [] { didSet { innerSegments = segments.map({ (content) -> WBInnerSegment in return WBInnerSegment(content: content) }) self.setNeedsLayout() if segments.count == 0 { selectedIndex = -1 } } } var innerSegments: [WBInnerSegment] = [] // MARK: Configuration - Interaction public var delegate: WBSegmentControlDelegate? public var selectedIndex: Int = -1 { didSet { if selectedIndex != oldValue && validIndex(selectedIndex) { selectedIndexChanged(selectedIndex, oldIndex: oldValue) delegate?.segmentControl(self, selectIndex: selectedIndex, oldIndex: oldValue) } } } public var selectedSegment: WBSegmentContentProtocol? { return validIndex(selectedIndex) ? segments[selectedIndex] : nil } // MARK: Configuration - Appearance public var style: WBSegmentIndicatorStyle = .rainbow public var nonScrollDistributionStyle: WBSegmentNonScrollDistributionStyle = .average public var enableSeparator: Bool = false public var separatorColor: UIColor = UIColor.black public var separatorWidth: CGFloat = 9 public var separatorEdgeInsets: UIEdgeInsets = UIEdgeInsets(top: 8, left: 4, bottom: 8, right: 4) public var enableSlideway: Bool = false public var slidewayHeight: CGFloat = 1 public var slidewayColor: UIColor = UIColor.lightGray public var enableAnimation: Bool = true public var animationDuration: TimeInterval = 0.15 public var segmentMinWidth: CGFloat = 50 public var segmentEdgeInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) public var segmentTextBold: Bool = true public var segmentTextFontSize: CGFloat = 12 public var segmentForegroundColor: UIColor = UIColor.gray public var segmentForegroundColorSelected: UIColor = UIColor.black // Settings - Cover public typealias CoverRange = WBSegmentIndicatorRange public var cover_range: CoverRange = .segment public var cover_opacity: Float = 0.2 public var cover_color: UIColor = UIColor.black // Settings - Strip public typealias StripRange = WBSegmentIndicatorRange public typealias StripLocation = WBSegmentIndicatorLocation public var strip_range: StripRange = .content public var strip_location: StripLocation = .down public var strip_color: UIColor = UIColor.orange public var strip_height: CGFloat = 3 // Settings - Rainbow public typealias RainbowLocation = WBSegmentIndicatorLocation public var rainbow_colors: [UIColor] = [] public var rainbow_height: CGFloat = 3 public var rainbow_roundCornerRadius: CGFloat = 4 public var rainbow_location: RainbowLocation = .down public var rainbow_outsideColor: UIColor = UIColor.gray // Settings - Arrow public typealias ArrowLocation = WBSegmentIndicatorLocation public var arrow_size: CGSize = CGSize(width: 6, height: 6) public var arrow_location: ArrowLocation = .down public var arrow_color: UIColor = UIColor.orange // Settings - ArrowStrip public typealias ArrowStripLocation = WBSegmentIndicatorLocation public typealias ArrowStripRange = WBSegmentIndicatorRange public var arrowStrip_location: ArrowStripLocation = .up public var arrowStrip_color: UIColor = UIColor.orange public var arrowStrip_arrowSize: CGSize = CGSize(width: 6, height: 6) public var arrowStrip_stripHeight: CGFloat = 2 public var arrowStrip_stripRange: ArrowStripRange = .content // MARK: Inner properties fileprivate var scrollView: UIScrollView! fileprivate var touchView: WBTouchView = WBTouchView() fileprivate var layerContainer: CALayer = CALayer() fileprivate var layerCover: CALayer = CALayer() fileprivate var layerStrip: CALayer = CALayer() fileprivate var layerArrow: CALayer = CALayer() fileprivate var segmentControlContentWidth: CGFloat { let sum = self.innerSegments.reduce(0, { (max_x, segment) -> CGFloat in return max(max_x, segment.segmentFrame.maxX) }) return sum + ((self.enableSeparator && self.style != .rainbow) ? self.separatorWidth / 2 : 0) } // MARK: Initialization override init(frame: CGRect) { super.init(frame: frame) scrollView = UIScrollView() self.addSubview(scrollView) scrollView.translatesAutoresizingMaskIntoConstraints = false self.addConstraint(NSLayoutConstraint(item: scrollView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: scrollView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: scrollView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: scrollView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0)) scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.layer.addSublayer(layerContainer) scrollView.addSubview(touchView) touchView.delegate = self } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Override methods override public func layoutSubviews() { super.layoutSubviews() layerContainer.sublayers?.removeAll() // Compute Segment Size for (index, segment) in self.innerSegments.enumerated() { segment.contentSize = self.segmentContentSize(segment) segment.segmentWidth = max(segment.contentSize.width + self.segmentEdgeInsets.left + self.segmentEdgeInsets.right, self.segmentMinWidth) segment.segmentFrame = self.segmentFrame(index) } // Adjust Control Content Size & Segment Size self.scrollView.contentSize = CGSize(width: self.segmentControlContentWidth, height: self.scrollView.frame.height) if self.scrollView.contentSize.width < self.scrollView.frame.width { switch self.nonScrollDistributionStyle { case .center: self.scrollView.contentInset = UIEdgeInsets(top: 0, left: (self.scrollView.frame.width - self.scrollView.contentSize.width) / 2, bottom: 0, right: 0) case .left: self.scrollView.contentInset = UIEdgeInsets.zero case .right: self.scrollView.contentInset = UIEdgeInsets(top: 0, left: self.scrollView.frame.width - self.scrollView.contentSize.width, bottom: 0, right: 0) case .average: self.scrollView.contentInset = UIEdgeInsets.zero self.scrollView.contentSize = self.scrollView.frame.size var averageWidth: CGFloat = (self.scrollView.frame.width - (self.enableSeparator && self.style != .rainbow ? CGFloat(self.innerSegments.count) * self.separatorWidth : 0)) / CGFloat(self.innerSegments.count) let largeSegments = self.innerSegments.filter({ (segment) -> Bool in return segment.segmentWidth >= averageWidth }) let smallSegments = self.innerSegments.filter({ (segment) -> Bool in return segment.segmentWidth < averageWidth }) let sumLarge = largeSegments.reduce(0, { (total, segment) -> CGFloat in return total + segment.segmentWidth }) averageWidth = (self.scrollView.frame.width - (self.enableSeparator && self.style != .rainbow ? CGFloat(self.innerSegments.count) * self.separatorWidth : 0) - sumLarge) / CGFloat(smallSegments.count) for segment in smallSegments { segment.segmentWidth = averageWidth } for (index, segment) in self.innerSegments.enumerated() { segment.segmentFrame = self.segmentFrame(index) segment.segmentFrame.origin.x += self.separatorWidth / 2 } } } else { self.scrollView.contentInset = UIEdgeInsets.zero } // Add Touch View touchView.frame = CGRect(origin: CGPoint.zero, size: self.scrollView.contentSize) // Add Segment SubLayers for (index, segment) in self.innerSegments.enumerated() { let content_x = segment.segmentFrame.origin.x + (segment.segmentFrame.width - segment.contentSize.width) / 2 let content_y = (self.scrollView.frame.height - segment.contentSize.height) / 2 let content_frame = CGRect(x: content_x, y: content_y, width: segment.contentSize.width, height: segment.contentSize.height) // Add Decoration Layer switch self.style { case .rainbow: let layerStrip = CALayer() layerStrip.frame = CGRect(x: segment.segmentFrame.origin.x, y: index == self.selectedIndex ? 0 : segment.segmentFrame.height - self.rainbow_height, width: segment.segmentFrame.width, height: index == self.selectedIndex ? self.scrollView.frame.height : self.rainbow_height) if self.rainbow_colors.isEmpty == false { layerStrip.backgroundColor = self.rainbow_colors[index % self.rainbow_colors.count].cgColor } layerContainer.addSublayer(layerStrip) self.switchRoundCornerForLayer(layerStrip, isRoundCorner: index == self.selectedIndex) segment.layerStrip = layerStrip default: break } // Add Content Layer switch segment.content.type { case let .text(text): let layerText = CATextLayer() layerText.string = text let font = segmentTextBold ? UIFont.boldSystemFont(ofSize: self.segmentTextFontSize) : UIFont.systemFont(ofSize: self.segmentTextFontSize) layerText.font = CGFont(NSString(string:font.fontName)) layerText.fontSize = font.pointSize layerText.frame = content_frame layerText.alignmentMode = kCAAlignmentCenter layerText.truncationMode = kCATruncationEnd layerText.contentsScale = UIScreen.main.scale layerText.foregroundColor = index == self.selectedIndex ? self.segmentForegroundColorSelected.cgColor : self.segmentForegroundColor.cgColor layerContainer.addSublayer(layerText) segment.layerText = layerText case let .icon(icon): let layerIcon = CALayer() let image = icon layerIcon.frame = content_frame layerIcon.contents = image.cgImage layerContainer.addSublayer(layerIcon) segment.layerIcon = layerIcon } } // Add Indicator Layer let initLayerSeparator = { [unowned self] in let layerSeparator = CALayer() layerSeparator.frame = CGRect(x: 0, y: 0, width: self.scrollView.contentSize.width, height: self.scrollView.contentSize.height) layerSeparator.backgroundColor = self.separatorColor.cgColor let layerMask = CAShapeLayer() layerMask.fillColor = UIColor.white.cgColor let maskPath = UIBezierPath() for (index, segment) in self.innerSegments.enumerated() { index < self.innerSegments.count - 1 ? maskPath.append(UIBezierPath(rect: CGRect(x: segment.segmentFrame.maxX + self.separatorEdgeInsets.left, y: self.separatorEdgeInsets.top, width: self.separatorWidth - self.separatorEdgeInsets.left - self.separatorEdgeInsets.right, height: self.scrollView.frame.height - self.separatorEdgeInsets.top - self.separatorEdgeInsets.bottom))) : () } layerMask.path = maskPath.cgPath layerSeparator.mask = layerMask self.layerContainer.addSublayer(layerSeparator) } let initLayerCover = { [unowned self] in self.layerCover.frame = self.indicatorCoverFrame(self.selectedIndex) self.layerCover.backgroundColor = self.cover_color.cgColor self.layerCover.opacity = self.cover_opacity self.layerContainer.addSublayer(self.layerCover) } let addLayerOutside = { [unowned self] in let outsideLayerLeft = CALayer() outsideLayerLeft.frame = CGRect(x: -1 * self.scrollView.frame.width, y: self.scrollView.frame.height - self.rainbow_height, width: self.scrollView.frame.width, height: self.rainbow_height) outsideLayerLeft.backgroundColor = self.rainbow_outsideColor.cgColor self.layerContainer.addSublayer(outsideLayerLeft) let outsideLayerRight = CALayer() outsideLayerRight.frame = CGRect(x: self.scrollView.contentSize.width, y: self.scrollView.frame.height - self.rainbow_height, width: self.scrollView.frame.width, height: self.rainbow_height) outsideLayerRight.backgroundColor = self.rainbow_outsideColor.cgColor self.layerContainer.addSublayer(outsideLayerRight) } let addLayerSlideway = { [unowned self] (slidewayPosition: CGFloat, slidewayHeight: CGFloat, slidewayColor: UIColor) in let layerSlideway = CALayer() layerSlideway.frame = CGRect(x: -1 * self.scrollView.frame.width, y: slidewayPosition - slidewayHeight / 2, width: self.scrollView.contentSize.width + self.scrollView.frame.width * 2, height: slidewayHeight) layerSlideway.backgroundColor = slidewayColor.cgColor self.layerContainer.addSublayer(layerSlideway) } let initLayerStrip = { [unowned self] (stripFrame: CGRect, stripColor: UIColor) in self.layerStrip.frame = stripFrame self.layerStrip.backgroundColor = stripColor.cgColor self.layerContainer.addSublayer(self.layerStrip) } let initLayerArrow = { [unowned self] (arrowFrame: CGRect, arrowLocation: WBSegmentIndicatorLocation, arrowColor: UIColor) in self.layerArrow.frame = arrowFrame self.layerArrow.backgroundColor = arrowColor.cgColor let layerMask = CAShapeLayer() layerMask.fillColor = UIColor.white.cgColor let maskPath = UIBezierPath() var pointA = CGPoint.zero var pointB = CGPoint.zero var pointC = CGPoint.zero switch arrowLocation { case .up: pointA = CGPoint(x: 0, y: 0) pointB = CGPoint(x: self.layerArrow.bounds.width, y: 0) pointC = CGPoint(x: self.layerArrow.bounds.width / 2, y: self.layerArrow.bounds.height) case .down: pointA = CGPoint(x: 0, y: self.layerArrow.bounds.height) pointB = CGPoint(x: self.layerArrow.bounds.width, y: self.layerArrow.bounds.height) pointC = CGPoint(x: self.layerArrow.bounds.width / 2, y: 0) } maskPath.move(to: pointA) maskPath.addLine(to: pointB) maskPath.addLine(to: pointC) maskPath.close() layerMask.path = maskPath.cgPath self.layerArrow.mask = layerMask self.layerContainer.addSublayer(self.layerArrow) } switch self.style { case .cover: initLayerCover() self.enableSeparator ? initLayerSeparator() : () case .strip: let strip_frame = self.indicatorStripFrame(self.selectedIndex, stripHeight: self.strip_height, stripLocation: self.strip_location, stripRange: self.strip_range) self.enableSlideway ? addLayerSlideway(strip_frame.midY, self.slidewayHeight, self.slidewayColor) : () initLayerStrip(strip_frame, self.strip_color) self.enableSeparator ? initLayerSeparator() : () case .rainbow: addLayerOutside() case .arrow: let arrow_frame = self.indicatorArrowFrame(self.selectedIndex, arrowLocation: self.arrow_location, arrowSize: self.arrow_size) var slideway_y: CGFloat = 0 switch self.arrow_location { case .up: slideway_y = arrow_frame.origin.y + self.slidewayHeight / 2 case .down: slideway_y = arrow_frame.maxY - self.slidewayHeight / 2 } self.enableSlideway ? addLayerSlideway(slideway_y, self.slidewayHeight, self.slidewayColor) : () initLayerArrow(arrow_frame, self.arrow_location, self.arrow_color) self.enableSeparator ? initLayerSeparator() : () case .arrowStrip: let strip_frame = self.indicatorStripFrame(self.selectedIndex, stripHeight: self.arrowStrip_stripHeight, stripLocation: self.arrowStrip_location, stripRange: self.arrowStrip_stripRange) self.enableSlideway ? addLayerSlideway(strip_frame.midY, self.slidewayHeight, self.slidewayColor) : () initLayerStrip(strip_frame, self.arrowStrip_color) let arrow_frame = self.indicatorArrowFrame(self.selectedIndex, arrowLocation: self.arrowStrip_location, arrowSize: self.arrowStrip_arrowSize) initLayerArrow(arrow_frame, self.arrowStrip_location, self.arrowStrip_color) self.enableSeparator ? initLayerSeparator() : () } } // MARK: Custom methods func selectedIndexChanged(_ newIndex: Int, oldIndex: Int) { if self.enableAnimation && validIndex(oldIndex) { CATransaction.begin() CATransaction.setAnimationDuration(self.animationDuration) CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)) CATransaction.setCompletionBlock({ [unowned self] in switch self.style { case .rainbow: if self.validIndex(oldIndex) { self.switchRoundCornerForLayer(self.innerSegments[oldIndex].layerStrip!, isRoundCorner: false) } default: break } }) self.scrollView.contentSize.width > self.scrollView.frame.width ? self.scrollToSegment(newIndex) : () self.didSelectedIndexChanged(newIndex, oldIndex: oldIndex) CATransaction.commit() } else { self.didSelectedIndexChanged(newIndex, oldIndex: oldIndex) } self.sendActions(for: .valueChanged) } func didSelectedIndexChanged(_ newIndex: Int, oldIndex: Int) { switch style { case .cover: self.layerCover.actions = nil self.layerCover.frame = self.indicatorCoverFrame(newIndex) case .strip: self.layerStrip.actions = nil self.layerStrip.frame = self.indicatorStripFrame(newIndex, stripHeight: self.strip_height, stripLocation: self.strip_location, stripRange: self.strip_range) case .rainbow: if validIndex(oldIndex), let old_StripLayer = self.innerSegments[oldIndex].layerStrip { let old_StripFrame = old_StripLayer.frame old_StripLayer.frame = CGRect(x: old_StripFrame.origin.x, y: self.scrollView.frame.height - self.strip_height, width: old_StripFrame.width, height: self.strip_height) } if let new_StripLayer = self.innerSegments[newIndex].layerStrip { let new_StripFrame = new_StripLayer.frame new_StripLayer.frame = CGRect(x: new_StripFrame.origin.x, y: 0, width: new_StripFrame.width, height: self.scrollView.frame.height) self.switchRoundCornerForLayer(new_StripLayer, isRoundCorner: true) } case .arrow: self.layerArrow.actions = nil self.layerArrow.frame = self.indicatorArrowFrame(newIndex, arrowLocation: self.arrow_location, arrowSize: self.arrow_size) case .arrowStrip: self.layerStrip.actions = nil self.layerStrip.frame = self.indicatorStripFrame(newIndex, stripHeight: self.arrowStrip_stripHeight, stripLocation: self.arrowStrip_location, stripRange: self.arrowStrip_stripRange) self.layerArrow.actions = nil self.layerArrow.frame = self.indicatorArrowFrame(newIndex, arrowLocation: self.arrowStrip_location, arrowSize: self.arrowStrip_arrowSize) } if validIndex(oldIndex) { switch self.innerSegments[oldIndex].content.type { case .text: if let old_contentLayer = self.innerSegments[oldIndex].layerText as? CATextLayer { old_contentLayer.foregroundColor = self.segmentForegroundColor.cgColor } default: break } } switch self.innerSegments[newIndex].content.type { case .text: if let new_contentLayer = self.innerSegments[newIndex].layerText as? CATextLayer { new_contentLayer.foregroundColor = self.segmentForegroundColorSelected.cgColor } default: break } } func switchRoundCornerForLayer(_ layer: CALayer, isRoundCorner: Bool) { if isRoundCorner { let layerMask = CAShapeLayer() layerMask.fillColor = UIColor.white.cgColor layerMask.path = UIBezierPath(roundedRect: CGRect(origin: CGPoint.zero, size: layer.frame.size), byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: self.rainbow_roundCornerRadius, height: self.rainbow_roundCornerRadius)).cgPath layer.mask = layerMask } else { layer.mask = nil } } func scrollToSegment(_ index: Int) { let segmentFrame = self.innerSegments[index].segmentFrame let targetRect = CGRect(x: segmentFrame.origin.x - (self.scrollView.frame.width - segmentFrame.width) / 2, y: 0, width: self.scrollView.frame.width, height: self.scrollView.frame.height) self.scrollView.scrollRectToVisible(targetRect, animated: true) } func segmentContentSize(_ segment: WBInnerSegment) -> CGSize { var size = CGSize.zero switch segment.content.type { case let .text(text): size = (text as NSString).size(attributes: [ NSFontAttributeName: segmentTextBold ? UIFont.boldSystemFont(ofSize: self.segmentTextFontSize) : UIFont.systemFont(ofSize: self.segmentTextFontSize) ]) case let .icon(icon): size = icon.size } return CGSize(width: ceil(size.width), height: ceil(size.height)) } func segmentFrame(_ index: Int) -> CGRect { var segmentOffset: CGFloat = (self.enableSeparator && self.style != .rainbow ? self.separatorWidth / 2 : 0) for (idx, segment) in self.innerSegments.enumerated() { if idx == index { break } else { segmentOffset += segment.segmentWidth + (self.enableSeparator && self.style != .rainbow ? self.separatorWidth : 0) } } return CGRect(x: segmentOffset , y: 0, width: self.innerSegments[index].segmentWidth, height: self.scrollView.frame.height) } func indicatorCoverFrame(_ index: Int) -> CGRect { if validIndex(index) { var box_x: CGFloat = self.innerSegments[index].segmentFrame.origin.x var box_width: CGFloat = 0 switch self.cover_range { case .content: box_x += (self.innerSegments[index].segmentWidth - self.innerSegments[index].contentSize.width) / 2 box_width = self.innerSegments[index].contentSize.width case .segment: box_width = self.innerSegments[index].segmentWidth } return CGRect(x: box_x, y: 0, width: box_width, height: self.scrollView.frame.height) } else { return CGRect.zero } } func indicatorStripFrame(_ index: Int, stripHeight: CGFloat, stripLocation: WBSegmentIndicatorLocation, stripRange: WBSegmentIndicatorRange) -> CGRect { if validIndex(index) { var strip_x: CGFloat = self.innerSegments[index].segmentFrame.origin.x var strip_y: CGFloat = 0 var strip_width: CGFloat = 0 switch stripLocation { case .down: strip_y = self.innerSegments[index].segmentFrame.height - stripHeight case .up: strip_y = 0 } switch stripRange { case .content: strip_width = self.innerSegments[index].contentSize.width strip_x += (self.innerSegments[index].segmentWidth - strip_width) / 2 case .segment: strip_width = self.innerSegments[index].segmentWidth } return CGRect(x: strip_x, y: strip_y, width: strip_width, height: stripHeight) } else { return CGRect.zero } } func indicatorArrowFrame(_ index: Int, arrowLocation: WBSegmentIndicatorLocation, arrowSize: CGSize) -> CGRect { if validIndex(index) { let arrow_x: CGFloat = self.innerSegments[index].segmentFrame.origin.x + (self.innerSegments[index].segmentFrame.width - arrowSize.width) / 2 var arrow_y: CGFloat = 0 switch arrowLocation { case .up: arrow_y = 0 case .down: arrow_y = self.innerSegments[index].segmentFrame.height - self.arrow_size.height } return CGRect(x: arrow_x, y: arrow_y, width: arrowSize.width, height: arrowSize.height) } else { return CGRect.zero } } func indexForTouch(_ location: CGPoint) -> Int { var touch_offset_x = location.x var touch_index = 0 for (index, segment) in self.innerSegments.enumerated() { touch_offset_x -= segment.segmentWidth + (self.enableSeparator && self.style != .rainbow ? self.separatorWidth : 0) if touch_offset_x < 0 { touch_index = index break } } return touch_index } func validIndex(_ index: Int) -> Bool { return index >= 0 && index < segments.count } } extension WBSegmentControl: WBTouchViewDelegate { public func didTouch(_ location: CGPoint) { selectedIndex = indexForTouch(location) } } class WBInnerSegment { let content: WBSegmentContentProtocol var segmentFrame: CGRect = CGRect.zero var segmentWidth: CGFloat = 0 var contentSize: CGSize = CGSize.zero var layerText: CALayer! var layerIcon: CALayer! var layerStrip: CALayer! init(content: WBSegmentContentProtocol) { self.content = content } } public enum WBSegmentType { case text(String) case icon(UIImage) } public enum WBSegmentIndicatorStyle { case cover, strip, rainbow, arrow, arrowStrip } public enum WBSegmentIndicatorLocation { case up, down } public enum WBSegmentIndicatorRange { case content, segment } public enum WBSegmentNonScrollDistributionStyle { case center, left, right, average } class WBTouchView: UIView { var delegate: WBTouchViewDelegate? override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { delegate?.didTouch(touch.location(in: self)) } } }
850f2b85b7d8bd19319f568c762d2764
46.409699
394
0.648407
false
false
false
false
hilen/TSWeChat
refs/heads/master
Pods/TimedSilver/Sources/UIKit/UIControl+TSSound.swift
mit
2
// // UIControl+TSSound.swift // TimedSilver // Source: https://github.com/hilen/TimedSilver // // Created by Hilen on 8/10/16. // Copyright © 2016 Hilen. All rights reserved. // import Foundation import UIKit import AVFoundation extension UIControl { fileprivate struct AssociatedKeys { static var ts_soundKey = "ts_soundKey" } /** Add sound to UIControl - parameter name: music name - parameter controlEvent: controlEvent */ public func ts_addSoundName(_ name: String, forControlEvent controlEvent: UIControl.Event) { let oldSoundKey: String = "\(controlEvent)" let oldSound: AVAudioPlayer = self.ts_sounds[oldSoundKey]! let selector = NSSelectorFromString("play") self.removeTarget(oldSound, action: selector, for: controlEvent) do { try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: "AVAudioSessionCategoryAmbient")) // Find the sound file. guard let soundFileURL = Bundle.main.url(forResource: name, withExtension: "") else { assert(false, "File not exist") return } let tapSound: AVAudioPlayer = try! AVAudioPlayer(contentsOf: soundFileURL) let controlEventKey: String = "\(controlEvent)" var sounds: [AnyHashable: Any] = self.ts_sounds sounds[controlEventKey] = tapSound tapSound.prepareToPlay() self.addTarget(tapSound, action: selector, for: controlEvent) } catch _ {} } /// AssociatedObject for UIControl var ts_sounds: Dictionary<String, AVAudioPlayer> { get { if let sounds = objc_getAssociatedObject(self, &AssociatedKeys.ts_soundKey) { return sounds as! Dictionary<String, AVAudioPlayer> } var sounds = Dictionary() as Dictionary<String, AVAudioPlayer> sounds = self.ts_sounds return sounds } set { objc_setAssociatedObject(self, &AssociatedKeys.ts_soundKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)} } }
baf05240ece6e66e03878eadddd8d8b7
34.015873
142
0.626927
false
false
false
false
naru-jpn/Monaka
refs/heads/master
Sources/CustomPackable.swift
mit
1
// // CustomPackable.swift // Monaka // // Created by naru on 2016/08/18. // Copyright © 2016年 naru. All rights reserved. // import Foundation /// Protocol for custom packable struct public protocol CustomPackable: Packable { /// Closure to restore struct from unpackable dictionary. static var restoreProcedure: ([String: Packable] -> Packable?) { get } } public extension CustomPackable { func packable() -> [String: Packable] { var children: [String: Packable] = [:] Mirror(reflecting: self).children.forEach { label, value in if let label = label, value = value as? Packable { children[label] = value } } return children } public final var packedIdentifier: String { return "\(Mirror(reflecting: self).subjectType)" } public static var packedIdentifier: String { return "\(self)" } public var packedDataLength: Int { let packable: [String: Packable] = self.packable() let elementsLength: Int = packable.keys.reduce(0) { (length, key) in length + key.packedDataLength } + packable.values.reduce(0) { (length, value) in length + value.packedDataLength } return self.packedIDLength + Int.PackedDataLength*(1+packable.keys.count*2) + elementsLength } public var packedHeaderData: [NSData] { let packable: [String: Packable] = self.packable() return packable.packedHeaderData } public var packedBodyData: [NSData] { let packable: [String: Packable] = self.packable() return packable.packedBodyData } public static var unpackProcedure: ((data: NSData) -> Packable?) { return [String: Packable].unpackProcedure } /// Store procedure to unpack and restore data on memory. public static func activatePack() { Monaka.registerUnpackProcedure(identifier: self.packedIdentifier, procedure: self.unpackProcedure) Monaka.registerRestoreProcedure(identifier: self.packedIdentifier, procedure: self.restoreProcedure) } }
e63bdbf4da53077d101bc9db1b2b57ae
29.704225
108
0.631193
false
false
false
false
ricardopereira/PremierKit
refs/heads/main
Source/Premier+UIScrollView.swift
mit
1
// // Premier+UIScrollView.swift // PremierKit // // Created by Ricardo Pereira on 20/09/2018. // Copyright © 2018 Ricardo Pereira. All rights reserved. // import UIKit extension UIScrollView { public func scrollToBottom(_ animated: Bool = false) { let offsetY = self.contentSize.height - self.frame.size.height self.setContentOffset(CGPoint(x: 0, y: max(0, offsetY)), animated: animated) } // MARK: - Keyboard fileprivate func adjustInsetForKeyboardShow(_ show: Bool, notification: Notification) { guard let value = notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue else { return } let keyboardFrame = value.cgRectValue let adjustmentHeight = (keyboardFrame.height + 20) * (show ? 1 : -1) if contentInset.bottom == 0 && adjustmentHeight < 0 { return } contentInset.bottom += adjustmentHeight scrollIndicatorInsets.bottom += adjustmentHeight } @objc internal func keyboardWillShow(_ sender: Notification) { adjustInsetForKeyboardShow(true, notification: sender) } @objc internal func keyboardWillHide(_ sender: Notification) { adjustInsetForKeyboardShow(false, notification: sender) } @objc internal func keyboardWillChangeFrame(_ sender: Notification) { contentInset.bottom = 0 scrollIndicatorInsets.bottom = 0 } func setupKeyboardNotifications() { NotificationCenter.default.addObserver( self, selector: #selector(self.keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(self.keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(self.keyboardWillChangeFrame(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil ) } }
fbbc5e48dcdb720d3d45eb3a67417296
31.892308
119
0.652947
false
false
false
false
timelessg/TLStoryCamera
refs/heads/master
TLStoryCameraFramework/TLStoryCameraFramework/Class/Views/TLStoryOverlayControlView.swift
mit
1
// // TLStoryOverlayControlView.swift // TLStoryCamera // // Created by GarryGuo on 2017/5/31. // Copyright © 2017年 GarryGuo. All rights reserved. // import UIKit protocol TLStoryOverlayControlDelegate: NSObjectProtocol { func storyOverlayCameraRecordingStart() func storyOverlayCameraRecordingFinish(type:TLStoryType) func storyOverlayCameraZoom(distance:CGFloat) func storyOverlayCameraFlashChange() -> AVCaptureDevice.TorchMode func storyOverlayCameraSwitch() func storyOverlayCameraFocused(point:CGPoint) func storyOverlayCameraClose() } class TLStoryOverlayControlView: UIView { public weak var delegate:TLStoryOverlayControlDelegate? fileprivate lazy var cameraBtn = TLStoryCameraButton.init(frame: CGRect.init(x: 0, y: 0, width: 80, height: 80)) fileprivate lazy var flashBtn:TLButton = { let btn = TLButton.init(type: UIButtonType.custom) btn.showsTouchWhenHighlighted = true btn.setImage(UIImage.tl_imageWithNamed(named: "story_publish_icon_flashlight_auto"), for: .normal) btn.addTarget(self, action: #selector(flashAction), for: .touchUpInside) return btn }() fileprivate lazy var switchBtn:TLButton = { let btn = TLButton.init(type: UIButtonType.custom) btn.showsTouchWhenHighlighted = true btn.setImage(UIImage.tl_imageWithNamed(named: "story_publish_icon_cam_turn"), for: .normal) btn.addTarget(self, action: #selector(switchAction), for: .touchUpInside) return btn }() fileprivate lazy var closeBtn:TLButton = { let btn = TLButton.init(type: UIButtonType.custom) btn.showsTouchWhenHighlighted = true btn.setImage(UIImage.tl_imageWithNamed(named: "story_icon_close"), for: .normal) btn.addTarget(self, action: #selector(closeAction), for: .touchUpInside) return btn }() fileprivate var photoLibraryHintView:TLPhotoLibraryHintView? fileprivate var tapGesture:UITapGestureRecognizer? fileprivate var doubleTapGesture:UITapGestureRecognizer? override init(frame: CGRect) { super.init(frame: frame) closeBtn.sizeToFit() closeBtn.center = CGPoint.init(x: self.width - closeBtn.width / 2 - 15, y: closeBtn.height / 2 + 15) addSubview(closeBtn) cameraBtn.center = CGPoint.init(x: self.center.x, y: self.bounds.height - 52 - 40) cameraBtn.delegete = self addSubview(cameraBtn) flashBtn.sizeToFit() flashBtn.center = CGPoint.init(x: cameraBtn.centerX - 100, y: cameraBtn.centerY) addSubview(flashBtn) switchBtn.sizeToFit() switchBtn.center = CGPoint.init(x: cameraBtn.centerX + 100, y: cameraBtn.centerY) addSubview(switchBtn) photoLibraryHintView = TLPhotoLibraryHintView.init(frame: CGRect.init(x: 0, y: 0, width: 200, height: 50)) photoLibraryHintView?.center = CGPoint.init(x: self.self.width / 2, y: self.height - 25) addSubview(photoLibraryHintView!) tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(tapAction)) tapGesture?.delegate = self tapGesture!.numberOfTapsRequired = 1 self.addGestureRecognizer(tapGesture!) doubleTapGesture = UITapGestureRecognizer.init(target: self, action: #selector(doubleTapAction)) doubleTapGesture?.delegate = self doubleTapGesture!.numberOfTapsRequired = 2 self.addGestureRecognizer(doubleTapGesture!) tapGesture!.require(toFail: doubleTapGesture!) } public func dismiss() { self.isHidden = true self.cameraBtn.reset() self.photoLibraryHintView?.isHidden = false } public func display() { self.isHidden = false self.cameraBtn.show() } public func beginHintAnim () { photoLibraryHintView?.startAnim() } @objc fileprivate func tapAction(sender:UITapGestureRecognizer) { let point = sender.location(in: self) self.delegate?.storyOverlayCameraFocused(point: point) } @objc fileprivate func doubleTapAction(sender:UITapGestureRecognizer) { self.delegate?.storyOverlayCameraSwitch() } @objc fileprivate func closeAction() { self.delegate?.storyOverlayCameraClose() } @objc fileprivate func flashAction(sender: UIButton) { let mode = self.delegate?.storyOverlayCameraFlashChange() let imgs = [AVCaptureDevice.TorchMode.on:UIImage.tl_imageWithNamed(named: "story_publish_icon_flashlight_on"), AVCaptureDevice.TorchMode.off:UIImage.tl_imageWithNamed(named: "story_publish_icon_flashlight_off"), AVCaptureDevice.TorchMode.auto:UIImage.tl_imageWithNamed(named: "story_publish_icon_flashlight_auto")] sender.setImage(imgs[mode!]!, for: .normal) } @objc fileprivate func switchAction(sender: UIButton) { UIView.animate(withDuration: 0.3, animations: { sender.transform = sender.transform.rotated(by: CGFloat(Double.pi)) }) { (x) in self.delegate?.storyOverlayCameraSwitch() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension TLStoryOverlayControlView: UIGestureRecognizerDelegate { override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { let point = gestureRecognizer.location(in: self) if self.cameraBtn.frame.contains(point) { return false } return true } } extension TLStoryOverlayControlView: TLStoryCameraButtonDelegate { internal func cameraStart(hoopButton: TLStoryCameraButton) { self.delegate?.storyOverlayCameraRecordingStart() photoLibraryHintView?.isHidden = true } internal func cameraDrag(hoopButton: TLStoryCameraButton, offsetY: CGFloat) { self.delegate?.storyOverlayCameraZoom(distance: offsetY) } internal func cameraComplete(hoopButton: TLStoryCameraButton, type: TLStoryType) { self.delegate?.storyOverlayCameraRecordingFinish(type: type) self.isHidden = true } } class TLPhotoLibraryHintView: UIView { fileprivate lazy var hintLabel:UILabel = { let label = UILabel.init() label.textColor = UIColor.init(colorHex: 0xffffff, alpha: 0.8) label.font = UIFont.systemFont(ofSize: 12) label.text = "向上滑动打开相册" label.layer.shadowColor = UIColor.black.cgColor label.layer.shadowOffset = CGSize.init(width: 1, height: 1) label.layer.shadowRadius = 2 label.layer.shadowOpacity = 0.7 return label }() fileprivate lazy var arrowIco = UIImageView.init(image: UIImage.tl_imageWithNamed(named: "story_icon_up")) override init(frame: CGRect) { super.init(frame: frame) self.addSubview(hintLabel) hintLabel.sizeToFit() hintLabel.center = CGPoint.init(x: self.width / 2, y: self.height - 10 - hintLabel.height / 2) self.addSubview(arrowIco) arrowIco.sizeToFit() arrowIco.center = CGPoint.init(x: self.width / 2, y: 10 + arrowIco.height / 2) } public func startAnim() { UIView.animate(withDuration: 0.8, delay: 0, options: [.repeat,.autoreverse], animations: { self.arrowIco.centerY = 5 + self.arrowIco.height / 2 }, completion: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
446a4b21500e83d662ca43522f4d8395
36.730392
122
0.670521
false
false
false
false
SteveBarnegren/SwiftChess
refs/heads/master
Example/SwiftChess/PromotionSelectionViewController.swift
mit
1
// // PromotionSelectionViewController.swift // Example // // Created by Steve Barnegren on 29/12/2016. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import SwiftChess class PromotionSelectionViewController: UIViewController { // MARK: - Properties (Passed In) var pawnLocation: BoardLocation! var possibleTypes: [Piece.PieceType]! var callback: ((Piece.PieceType) -> Void)! // MARK: - Properties var buttons = [UIButton]() // MARK: - Creation public static func promotionSelectionViewController(pawnLocation: BoardLocation, possibleTypes: [Piece.PieceType], callback: @escaping (Piece.PieceType) -> Void) -> PromotionSelectionViewController { let viewController = PromotionSelectionViewController() viewController.pawnLocation = pawnLocation viewController.possibleTypes = possibleTypes viewController.callback = callback return viewController } // MARK: - LifeCycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.orange view.layer.cornerRadius = 7 // Add buttons for types for type in possibleTypes { let typeString = stringFromPieceType(pieceType: type) let button = UIButton(type: .system) button.setTitle(typeString, for: .normal) button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) view.addSubview(button) buttons.append(button) } } // MARK: - Layout override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let buttonHeight = view.bounds.size.height / CGFloat(buttons.count) for (index, button) in buttons.enumerated() { button.frame = CGRect(x: 0, y: CGFloat(index) * buttonHeight, width: view.bounds.size.width, height: buttonHeight) } } // MARK: - Actions @objc func buttonPressed(sender: UIButton) { let index = buttons.firstIndex(of: sender)! let chosenType = possibleTypes![index] callback(chosenType) } // MARK: - Helpers func stringFromPieceType(pieceType: Piece.PieceType) -> String { switch pieceType { case .pawn: return "Pawn" case .rook: return "Rook" case .knight: return "Knight" case .bishop: return "Bishop" case .queen: return "Queen" case .king: return "King" } } }
bcadcf3f47b1d444e894b64ab9c8f6e1
29.397849
102
0.569508
false
false
false
false
soloy/BriefCase
refs/heads/master
Example/Tests/Tests.swift
mit
1
// https://github.com/Quick/Quick import Quick import Nimble import BriefCase class TableOfContentsSpec: QuickSpec { override func spec() { let b = BriefCase() describe("Convert from camelCase") { let s = "briefCase" it("to PascalCase") { let answer = b.convert(from: .CamelCase, to: .PascalCase, source: s) expect(answer) == "BriefCase" } it("to cobol-case") { let answer = b.convert(from: .CamelCase, to: .CobolCase, source: s) expect(answer) == "brief-case" } it("to Upper-Cobol-Case") { let answer = b.convert(from: .CamelCase, to: .UpperCobolCase, source: s) expect(answer) == "Brief-Case" } it("to snake_case") { let answer = b.convert(from: .CamelCase, to: .SnakeCase, source: s) expect(answer) == "brief_case" } it("to MACRO_CASE") { let answer = b.convert(from: .CamelCase, to: .MacroCase, source: s) expect(answer) == "BRIEF_CASE" } } } }
5287071ec75430fe4e1ba8a6e5122b0f
28.97619
88
0.466243
false
false
false
false
ello/ello-ios
refs/heads/master
Specs/Utilities/SafariActivitySpec.swift
mit
1
//// /// SafariActivitySpec.swift // @testable import Ello import Quick import Nimble class SafariActivitySpec: QuickSpec { override func spec() { describe("SafariActivity") { var subject: SafariActivity! beforeEach { subject = SafariActivity() } it("activityType()") { expect(subject.activityType.rawValue) == "SafariActivity" } it("activityTitle()") { expect(subject.activityTitle) == "Open in Safari" } it("activityImage()") { expect(subject.activityImage).toNot(beNil()) } context("canPerformWithActivityItems(items: [Any]) -> Bool") { let url = URL(string: "https://ello.co")! let url2 = URL(string: "https://google.com")! let string = "ignore" let image = UIImage.imageWithColor(.blue)! let expectations: [(String, [Any], Bool)] = [ ("a url", [url], true), ("a url and a string", [url, string], true), ("two urls", [string, url, string, url2], true), ("a string", [string], false), ("a string and an image", [image, string], false), ] for (description, items, expected) in expectations { it("should return \(expected) for \(description)") { expect(subject.canPerform(withActivityItems: items)) == expected } } } context("prepareWithActivityItems(items: [Any])") { let url = URL(string: "https://ello.co")! let url2 = URL(string: "https://google.com")! let string = "ignore" let image = UIImage.imageWithColor(.blue)! let expectations: [(String, [Any], URL?)] = [ ("a url", [url], url), ("a url and a string", [url, string], url), ("two urls", [string, url, string, url2], url), ("a string", [string], nil), ("a string and an image", [image, string], nil), ] for (description, items, expected) in expectations { it("should assign \(String(describing: expected)) for \(description)") { subject.prepare(withActivityItems: items) if expected == nil { expect(subject.url).to(beNil()) } else { expect(subject.url) == expected } } } } } } }
c80c82f8b2269c4872922a87c239fcd6
34.860759
92
0.443346
false
false
false
false
kildevaeld/DataBinding
refs/heads/master
Pod/Classes/UIButtonHandler.swift
mit
1
// // UIButtonHandler.swift // Pods // // Created by Rasmus Kildevæld on 21/06/15. // // import Foundation import UIKit class UIButtonHandler : NSObject, HandlerProtocol { var type: AnyObject.Type? = nil func setValue(value: AnyObject?, onView: UIView) { let buttonView = onView as! UIButton; if let str = value as? String { buttonView.setTitle(str, forState:.Normal) } else if let bool = value as? Bool { buttonView.selected = bool } } }
ed20e4b1a9c0395f8e935af0fd939139
17.032258
54
0.569892
false
false
false
false
netcosports/Gnomon
refs/heads/master
Specs/DecodableSpec.swift
mit
1
// // DecodableSpec.swift // Gnomon // // Created by Vladimir Burdukov on 26/9/17. // import XCTest import Nimble @testable import Gnomon struct PlayerModel: DecodableModel, Equatable { let firstName: String let lastName: String enum CodingKeys: String, CodingKey { case firstName = "first_name" case lastName = "last_name" } static func ==(lhs: PlayerModel, rhs: PlayerModel) -> Bool { return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName } } struct TeamModel: DecodableModel { let name: String let players: [PlayerModel] } struct MatchModel: DecodableModel { static let decoder: JSONDecoder = { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .secondsSince1970 return decoder }() let homeTeam: TeamModel let awayTeam: TeamModel let date: Date } class DecodableSpec: XCTestCase { func testTeam() { do { let request = try Request<TeamModel>(URLString: "https://example.com/") request.httpSessionDelegate = try TestSessionDelegate.jsonResponse(result: [ "name": "France", "players": [ [ "first_name": "Vasya", "last_name": "Pupkin" ], [ "first_name": "Petya", "last_name": "Ronaldo" ] ] ], cached: false) let result = Gnomon.models(for: request).toBlocking(timeout: BlockingTimeout).materialize() switch result { case let .completed(responses): expect(responses).to(haveCount(1)) let team = responses[0].result expect(team.name) == "France" expect(team.players[0].firstName) == "Vasya" expect(team.players[0].lastName) == "Pupkin" expect(team.players[1].firstName) == "Petya" expect(team.players[1].lastName) == "Ronaldo" case let .failed(_, error): fail("\(error)") } } catch { fail("\(error)") return } } func testPlayers() { do { let request = try Request<[PlayerModel]>(URLString: "https://example.com") request.httpSessionDelegate = try TestSessionDelegate.jsonResponse(result: [ [ "first_name": "Vasya", "last_name": "Pupkin" ], [ "first_name": "Petya", "last_name": "Ronaldo" ] ], cached: false) let result = Gnomon.models(for: request).toBlocking(timeout: BlockingTimeout).materialize() switch result { case let .completed(responses): expect(responses).to(haveCount(1)) let players = responses[0].result expect(players).to(haveCount(2)) expect(players[0]) == PlayerModel(firstName: "Vasya", lastName: "Pupkin") expect(players[1]) == PlayerModel(firstName: "Petya", lastName: "Ronaldo") case let .failed(_, error): fail("\(error)") } } catch { fail("\(error)") return } } func testOptionalPlayers() { do { let request = try Request<[PlayerModel?]>(URLString: "https://example.com") request.httpSessionDelegate = try TestSessionDelegate.jsonResponse(result: [ [ "first_name": "Vasya", "last_name": "Pupkin" ], [ "first_name": "", "lastname": "" ] ], cached: false) let result = Gnomon.models(for: request).toBlocking(timeout: BlockingTimeout).materialize() switch result { case let .completed(responses): expect(responses).to(haveCount(1)) let players = responses[0].result expect(players).to(haveCount(2)) expect(players[0]) == PlayerModel(firstName: "Vasya", lastName: "Pupkin") expect(players[1]).to(beNil()) case let .failed(_, error): fail("\(error)") } } catch { fail("\(error)") return } } func testMatchWithCustomizedDecoder() { do { let request = try Request<MatchModel>(URLString: "https://example.com") request.httpSessionDelegate = try TestSessionDelegate.jsonResponse(result: [ "homeTeam": [ "name": "France", "players": [] ], "awayTeam": [ "name": "Belarus", "players": [] ], "date": 1507654800 ], cached: false) let result = Gnomon.models(for: request).toBlocking(timeout: BlockingTimeout).materialize() switch result { case let .completed(responses): expect(responses).to(haveCount(1)) let match = responses[0].result expect(match.homeTeam.name) == "France" expect(match.awayTeam.name) == "Belarus" var components = DateComponents() components.year = 2017 components.month = 10 components.day = 10 components.hour = 19 components.minute = 0 components.timeZone = TimeZone(identifier: "Europe/Paris") expect(match.date) == Calendar.current.date(from: components) case let .failed(_, error): fail("\(error)") } } catch { fail("\(error)") return } } func testMatchesWithCustomizedDecoder() { do { let request = try Request<[MatchModel]>(URLString: "https://example.com") request.httpSessionDelegate = try TestSessionDelegate.jsonResponse(result: [ [ "homeTeam": [ "name": "France", "players": [] ], "awayTeam": [ "name": "Belarus", "players": [] ], "date": 1507654800 ] ], cached: false) let result = Gnomon.models(for: request).toBlocking(timeout: BlockingTimeout).materialize() switch result { case let .completed(responses): expect(responses).to(haveCount(1)) expect(responses[0].result).to(haveCount(1)) let match = responses[0].result[0] expect(match.homeTeam.name) == "France" expect(match.awayTeam.name) == "Belarus" var components = DateComponents() components.year = 2017 components.month = 10 components.day = 10 components.hour = 19 components.minute = 0 components.timeZone = TimeZone(identifier: "Europe/Paris") expect(match.date) == Calendar.current.date(from: components) case let .failed(_, error): fail("\(error)") } } catch { fail("\(error)") return } } func testXPath() { do { let request = try Request<PlayerModel>(URLString: "https://example.com/").setXPath("json/data") request.httpSessionDelegate = try TestSessionDelegate.jsonResponse(result: [ "json": ["data": ["first_name": "Vasya", "last_name": "Pupkin"]] ], cached: false) let result = Gnomon.models(for: request).toBlocking(timeout: BlockingTimeout).materialize() switch result { case let .completed(responses): expect(responses).to(haveCount(1)) let player = responses[0].result expect(player.firstName) == "Vasya" expect(player.lastName) == "Pupkin" case let .failed(_, error): fail("\(error)") } } catch { fail("\(error)") return } } func testXPathWithArrayIndex() { let data = [ "teams": [ [ "name": "France", "players": [ ["first_name": "Vasya", "last_name": "Pupkin"], ["first_name": "Petya", "last_name": "Ronaldo"] ] ] ] ] do { let request = try Request<PlayerModel>(URLString: "https://example.com/") .setXPath("teams[0]/players[0]") request.httpSessionDelegate = try TestSessionDelegate.jsonResponse(result: data, cached: false) let result = Gnomon.models(for: request).toBlocking(timeout: BlockingTimeout).materialize() switch result { case let .completed(responses): expect(responses).to(haveCount(1)) let player = responses[0].result expect(player.firstName) == "Vasya" expect(player.lastName) == "Pupkin" case let .failed(_, error): fail("\(error)") } } catch { fail("\(error)") return } do { let request = try Request<PlayerModel>(URLString: "https://example.com/") .setXPath("teams[0]/players[1]") request.httpSessionDelegate = try TestSessionDelegate.jsonResponse(result: data, cached: false) let result = Gnomon.models(for: request).toBlocking(timeout: BlockingTimeout).materialize() switch result { case let .completed(responses): expect(responses).to(haveCount(1)) let player = responses[0].result expect(player.firstName) == "Petya" expect(player.lastName) == "Ronaldo" case let .failed(_, error): fail("\(error)") } } catch { fail("\(error)") return } } func testXPathWithMultipleArrayIndices() { let data = [ "matches": [ [ "id": 1, "lineups": [ [ ["first_name": "Vasya", "last_name": "Pupkin"] ], [ ["first_name": "Vanya", "last_name": "Messi"], ["first_name": "Artem", "last_name": "Dzyuba"], ] ] ] ] ] do { let request = try Request<PlayerModel>(URLString: "https://example.com/") .setXPath("matches[0]/lineups[0][0]") request.httpSessionDelegate = try TestSessionDelegate.jsonResponse(result: data, cached: false) let result = Gnomon.models(for: request).toBlocking(timeout: BlockingTimeout).materialize() switch result { case let .completed(responses): expect(responses).to(haveCount(1)) expect(responses[0].result) == PlayerModel(firstName: "Vasya", lastName: "Pupkin") case let .failed(_, error): fail("\(error)") } } catch { fail("\(error)") return } do { let request = try Request<PlayerModel>(URLString: "https://example.com/") .setXPath("matches[0]/lineups[1][1]") request.httpSessionDelegate = try TestSessionDelegate.jsonResponse(result: data, cached: false) let result = Gnomon.models(for: request).toBlocking(timeout: BlockingTimeout).materialize() switch result { case let .completed(responses): expect(responses).to(haveCount(1)) expect(responses[0].result) == PlayerModel(firstName: "Artem", lastName: "Dzyuba") case let .failed(_, error): fail("\(error)") } } catch { fail("\(error)") return } } }
424cd340f045945ec60ae6b174c7caea
26.666667
108
0.581373
false
true
false
false
RainbowMango/UISwitchDemo
refs/heads/master
UISwitchDemo/UISwitchDemo/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // UISwitchDemo // // Created by ruby on 14-12-25. // Copyright (c) 2014年 ruby. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. 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 throttle down OpenGL ES frame rates. 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 inactive 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 applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.ruby.UISwitchDemo" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("UISwitchDemo", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added 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. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("UISwitchDemo.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() 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. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() 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. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
53a19844452947543bce25e9d4f1cb0f
54.153153
290
0.716433
false
false
false
false
shajrawi/swift
refs/heads/master
validation-test/Evolution/test_struct_resilient_add_conformance.swift
apache-2.0
1
// RUN: %target-resilience-test // REQUIRES: executable_test // Use swift-version 4. // UNSUPPORTED: swift_test_mode_optimize_none_with_implicit_dynamic import StdlibUnittest import struct_resilient_add_conformance var StructResilientAddConformanceTest = TestSuite("StructResilientAddConformance") StructResilientAddConformanceTest.test("AddConformance") { var t = AddConformance() do { t.x = 10 t.y = 20 expectEqual(t.x, 10) expectEqual(t.y, 20) } if (getVersion() == 0) { expectEqual(workWithPointLike(t), 0) } else { expectEqual(workWithPointLike(t), 200) } } #if AFTER protocol MyPointLike { var x: Int { get set } var y: Int { get set } } protocol MyPoint3DLike { var z: Int { get set } } extension AddConformance : MyPointLike {} extension AddConformance : MyPoint3DLike {} @inline(never) func workWithMyPointLike<T>(_ t: T) { var p = t as! MyPointLike p.x = 50 p.y = 60 expectEqual(p.x, 50) expectEqual(p.y, 60) } StructResilientAddConformanceTest.test("MyPointLike") { var p: MyPointLike = AddConformance() do { p.x = 50 p.y = 60 expectEqual(p.x, 50) expectEqual(p.y, 60) } workWithMyPointLike(p) } #endif runAllTests()
d06ecd45a46c4f5b0ba6f9c7a356a967
17.484848
82
0.684426
false
true
false
false
RobberPhex/thrift
refs/heads/master
lib/swift/Sources/TClient.swift
apache-2.0
7
/* * 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. */ open class TClient { public let inProtocol: TProtocol public let outProtocol: TProtocol required public init(inoutProtocol: TProtocol) { self.inProtocol = inoutProtocol self.outProtocol = inoutProtocol } required public init(inProtocol: TProtocol, outProtocol: TProtocol) { self.inProtocol = inProtocol self.outProtocol = outProtocol } } open class TAsyncClient<Protocol: TProtocol, Factory: TAsyncTransportFactory> { public var factory: Factory public init(with protocol: Protocol.Type, factory: Factory) { self.factory = factory } } public enum TAsyncResult<T> { case success(T) case error(Swift.Error) public func value() throws -> T { switch self { case .success(let t): return t case .error(let e): throw e } } }
ab2b7a5a3ec94b1d575918c133c62d6a
28
79
0.730408
false
false
false
false
hooman/swift
refs/heads/main
test/AutoDiff/validation-test/forward_mode_array.swift
apache-2.0
1
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-forward-mode-differentiation -Xfrontend -requirement-machine=off) // REQUIRES: executable_test import StdlibUnittest import DifferentiationUnittest var ForwardModeTests = TestSuite("ForwardModeDifferentiation") //===----------------------------------------------------------------------===// // Array methods from ArrayDifferentiation.swift //===----------------------------------------------------------------------===// typealias FloatArrayTan = Array<Float>.TangentVector ForwardModeTests.test("Array.+") { func sumFirstThreeConcatenating(_ a: [Float], _ b: [Float]) -> Float { let c = a + b return c[0] + c[1] + c[2] } expectEqual(3, differential(at: [0, 0], [0, 0], of: sumFirstThreeConcatenating)(.init([1, 1]), .init([1, 1]))) expectEqual(0, differential(at: [0, 0], [0, 0], of: sumFirstThreeConcatenating)(.init([0, 0]), .init([0, 1]))) expectEqual(1, differential(at: [0, 0], [0, 0], of: sumFirstThreeConcatenating)(.init([0, 1]), .init([0, 1]))) expectEqual(1, differential(at: [0, 0], [0, 0], of: sumFirstThreeConcatenating)(.init([1, 0]), .init([0, 1]))) expectEqual(1, differential(at: [0, 0], [0, 0], of: sumFirstThreeConcatenating)(.init([0, 0]), .init([1, 1]))) expectEqual(2, differential(at: [0, 0], [0, 0], of: sumFirstThreeConcatenating)(.init([1, 1]), .init([0, 1]))) expectEqual( 3, differential(at: [0, 0, 0, 0], [0, 0], of: sumFirstThreeConcatenating)(.init([1, 1, 1, 1]), .init([1, 1]))) expectEqual( 3, differential(at: [0, 0, 0, 0], [0, 0], of: sumFirstThreeConcatenating)(.init([1, 1, 1, 0]), .init([0, 0]))) expectEqual( 3, differential(at: [], [0, 0, 0, 0], of: sumFirstThreeConcatenating)(.init([]), .init([1, 1, 1, 1]))) expectEqual( 0, differential(at: [], [0, 0, 0, 0], of: sumFirstThreeConcatenating)(.init([]), .init([0, 0, 0, 1]))) } ForwardModeTests.test("Array.init(repeating:count:)") { @differentiable(reverse) func repeating(_ x: Float) -> [Float] { Array(repeating: x, count: 10) } expectEqual(Float(10), derivative(at: .zero) { x in repeating(x).differentiableReduce(0, {$0 + $1}) }) expectEqual(Float(20), differential(at: .zero, of: { x in repeating(x).differentiableReduce(0, {$0 + $1}) })(2)) } ForwardModeTests.test("Array.DifferentiableView.init") { @differentiable(reverse) func constructView(_ x: [Float]) -> Array<Float>.DifferentiableView { return Array<Float>.DifferentiableView(x) } let forward = differential(at: [5, 6, 7, 8], of: constructView) expectEqual( FloatArrayTan([1, 2, 3, 4]), forward(FloatArrayTan([1, 2, 3, 4]))) } ForwardModeTests.test("Array.DifferentiableView.base") { @differentiable(reverse) func accessBase(_ x: Array<Float>.DifferentiableView) -> [Float] { return x.base } let forward = differential( at: Array<Float>.DifferentiableView([5, 6, 7, 8]), of: accessBase) expectEqual( FloatArrayTan([1, 2, 3, 4]), forward(FloatArrayTan([1, 2, 3, 4]))) } ForwardModeTests.test("Array.differentiableMap") { let x: [Float] = [1, 2, 3] let tan = Array<Float>.TangentVector([1, 1, 1]) func multiplyMap(_ a: [Float]) -> [Float] { return a.differentiableMap({ x in 3 * x }) } expectEqual([3, 3, 3], differential(at: x, of: multiplyMap)(tan)) func squareMap(_ a: [Float]) -> [Float] { return a.differentiableMap({ x in x * x }) } expectEqual([2, 4, 6], differential(at: x, of: squareMap)(tan)) } ForwardModeTests.test("Array.differentiableReduce") { let x: [Float] = [1, 2, 3] let tan = Array<Float>.TangentVector([1, 1, 1]) func sumReduce(_ a: [Float]) -> Float { return a.differentiableReduce(0, { $0 + $1 }) } expectEqual(1 + 1 + 1, differential(at: x, of: sumReduce)(tan)) func productReduce(_ a: [Float]) -> Float { return a.differentiableReduce(1, { $0 * $1 }) } expectEqual(x[1] * x[2] + x[0] * x[2] + x[0] * x[1], differential(at: x, of: productReduce)(tan)) func sumOfSquaresReduce(_ a: [Float]) -> Float { return a.differentiableReduce(0, { $0 + $1 * $1 }) } expectEqual(2 * x[0] + 2 * x[1] + 2 * x[2], differential(at: x, of: sumOfSquaresReduce)(tan)) } runAllTests()
6ee365b376202f07e27e64f6fe6d3126
35.153846
130
0.610165
false
true
false
false
CanBeMyQueen/DouYuZB
refs/heads/master
DouYu/DouYu/Classes/Home/View/AmuseMenuCollectionViewCell.swift
mit
1
// // AmuseMenuCollectionViewCell.swift // DouYu // // Created by 张萌 on 2018/1/23. // Copyright © 2018年 JiaYin. All rights reserved. // import UIKit private let kMenuCellID = "kMenuCellID" class AmuseMenuCollectionViewCell: UICollectionViewCell { @IBOutlet weak var collectionView: UICollectionView! var groups : [AnchorGroupModel]? { didSet { collectionView.reloadData() } } override func awakeFromNib() { super.awakeFromNib() collectionView.register(UINib(nibName: "CollectionViewGameCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout let itemW = collectionView.bounds.size.width / 4 let itemH = collectionView.bounds.size.height / 2 layout.itemSize = CGSize(width: itemW, height: itemH) } } extension AmuseMenuCollectionViewCell : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups!.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! CollectionViewGameCell cell.clipsToBounds = true cell.group = groups?[indexPath.row] return cell } }
6e6895c1371c85f2f2615ccbb2ef1964
33.088889
130
0.711213
false
false
false
false
KrishMunot/swift
refs/heads/master
test/DebugInfo/linetable-cleanups.swift
apache-2.0
6
// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s func markUsed<T>(_ t: T) {} class Person { var name = "No Name" var age = 0 } func main() { var person = Person() var b = [0,1,13] for element in b { markUsed("element = \(element)") } markUsed("Done with the for loop") // CHECK: call void @_TF4main8markUsedurFxT_ // CHECK: br label // CHECK: <label>: // CHECK: , !dbg ![[LOOPHEADER_LOC:.*]] // CHECK: call void {{.*}}elease({{.*}}) {{#[0-9]+}}, !dbg ![[LOOPHEADER_LOC]] // CHECK: call void @_TF4main8markUsedurFxT_ // The cleanups should share the line number with the ret stmt. // CHECK: call void {{.*}}elease({{.*}}) {{#[0-9]+}}, !dbg ![[CLEANUPS:.*]] // CHECK-NEXT: !dbg ![[CLEANUPS]] // CHECK-NEXT: bitcast // CHECK-NEXT: llvm.lifetime.end // CHECK-NEXT: bitcast // CHECK-NEXT: llvm.lifetime.end // CHECK-NEXT: bitcast // CHECK-NEXT: llvm.lifetime.end // CHECK-NEXT: ret void, !dbg ![[CLEANUPS]] // CHECK: ![[CLEANUPS]] = !DILocation(line: [[@LINE+1]], column: 1, } main()
78c4a53b71b8d0039fcde301406e02c9
28.828571
78
0.591954
false
false
false
false
phausler/Auspicion
refs/heads/master
Auspicion/CompileCommands.swift
mit
1
// // CompileCommands.swift // Auspicion // // Created by Philippe Hausler on 10/6/14. // Copyright (c) 2014 Philippe Hausler. All rights reserved. // import clang public final class CompileCommand { init(_ context: CXCompileCommand) { self.context = context } private var _directory: String? = nil var directory: String { get { if _directory == nil { let dir = clang_CompileCommand_getDirectory(self.context) _directory = String.fromCXString(dir) clang_disposeString(dir) } return _directory! } } private var _arguments: Array<String>? = nil var arguments: Array<String> { get { if _arguments == nil { _arguments = Array<String>() for var i: UInt32 = 0; i < clang_CompileCommand_getNumArgs(self.context); i++ { let val = clang_CompileCommand_getArg(self.context, i) let argument: String = String.fromCXString(val) clang_disposeString(val) _arguments!.append(argument) } } return _arguments! } } private var _mappedSources: Array<String>? = nil var mappedSources: Array<String> { get { if _mappedSources == nil { _mappedSources = Array<String>() for var i: UInt32 = 0; i < clang_CompileCommand_getNumMappedSources(self.context); i++ { let val = clang_CompileCommand_getMappedSourcePath(self.context, i) let path: String = String.fromCXString(val) clang_disposeString(val) _mappedSources!.append(path) } } return _mappedSources! } } internal let context: CXCompileCommand; } public final class CompileCommands { init(_ context: CXCompileCommands) { self.context = context } deinit { clang_CompileCommands_dispose(self.context) } private var _commands: Array<CompileCommand>? = nil var commands: Array<CompileCommand> { get { if _commands == nil { _commands = Array<CompileCommand>() for var i: UInt32 = 0; i < clang_CompileCommands_getSize(self.context); i++ { _commands?.append(CompileCommand(clang_CompileCommands_getCommand(self.context, i))) } } return _commands! } } internal let context: CXCompileCommands; }
d710bc8f612f11167ea18c06d7d4aa6c
29.494253
104
0.537505
false
false
false
false
JGiola/swift
refs/heads/main
test/Generics/unify_protocol_composition.swift
apache-2.0
6
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s class C<T> {} protocol P0 {} protocol P1 { associatedtype T where T == C<U> & P0 associatedtype U } protocol P2 { associatedtype T where T == C<Int> & P0 } // CHECK-LABEL: .P3@ // CHECK-NEXT: Requirement signature: <Self where Self.[P3]T : P1, Self.[P3]T : P2> protocol P3 { associatedtype T : P1 & P2 where T.U == Int }
f2dd4ae0519d45fd07091cb263170ac0
20.3
91
0.651765
false
false
false
false
iOSWizards/AwesomeMedia
refs/heads/master
Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/Happenings.swift
mit
1
// // Happenings.swift // AwesomeCore // // Created by Leonardo Vinicius Kaminski Ferreira on 25/10/17. // import Foundation public struct Happenings: Codable { public let happenings: [Happening] } public struct Happening: Codable { public let type: String public let title: String public let subtitle: String public let description: String public var startDate: String public let endDate: String public let buttonURL: String public let imageURL: String } // MARK: - Coding keys extension Happening { private enum CodingKeys: String, CodingKey { case type case title case subtitle = "sub_title" case description case startDate = "start_date" case endDate = "end_date" case buttonURL = "button_url" case imageURL = "image_url" } } // MARK: - Equatable extension Happenings { public static func ==(lhs: Happenings, rhs: Happenings) -> Bool { if lhs.happenings.first?.title != rhs.happenings.first?.title { return false } return true } }
cec8b8199ce823bd46476a1c437d72a4
20.075472
71
0.63205
false
false
false
false
optimizely/swift-sdk
refs/heads/master
Tests/OptimizelyTests-DataModel/AudienceTests_Evaluate.swift
apache-2.0
1
// // Copyright 2019, 2021, Optimizely, Inc. and contributors // // 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 XCTest // REF: // https://docs.google.com/document/d/158_83difXVXF0nb91rxzrfHZwnhsybH21ImRA_si7sg/edit#heading=h.4pg6cutdopxx // https://github.com/optimizely/objective-c-sdk/blob/master/OptimizelySDKCore/OptimizelySDKCoreTests/OPTLYTypedAudienceTest.m class AudienceTests_Evaluate: XCTestCase { // MARK: - Constants let kAudienceId = "6366023138" let kAudienceName = "Android users" let kAudienceConditions = "[\"and\", [\"or\", [\"or\", {\"name\": \"device_type\", \"type\": \"custom_attribute\", \"value\": \"iPhone\"}]], [\"or\", [\"or\", {\"name\": \"location\", \"type\": \"custom_attribute\", \"value\": \"San Francisco\"}]], [\"or\", [\"not\", [\"or\", {\"name\": \"browser\", \"type\": \"custom_attribute\", \"value\": \"Firefox\"}]]]]" let kAudienceConditionsWithAnd: [Any] = ["and", ["or", ["or", ["name": "device_type", "type": "custom_attribute", "value": "iPhone", "match": "substring"]]], ["or", ["or", ["name": "num_users", "type": "custom_attribute", "value": 15, "match": "exact"]]], ["or", ["or", ["name": "decimal_value", "type": "custom_attribute", "value": 3.14, "match": "gt"]]]] let kAudienceConditionsWithExactMatchStringType: [Any] = ["and", ["or", ["or", ["name": "attr_value", "type": "custom_attribute", "value": "firefox", "match": "exact"]]]] let kAudienceConditionsWithExactMatchBoolType: [Any] = ["and", ["or", ["or", ["name": "attr_value", "type": "custom_attribute", "value": false, "match": "exact"]]]] let kAudienceConditionsWithExactMatchDecimalType: [Any] = ["and", ["or", ["or", ["name": "attr_value", "type": "custom_attribute", "value": 1.5, "match": "exact"]]]] let kAudienceConditionsWithExactMatchIntType: [Any] = ["and", ["or", ["or", ["name": "attr_value", "type": "custom_attribute", "value": 10, "match": "exact"]]]] let kAudienceConditionsWithExistsMatchType: [Any] = ["and", ["or", ["or", ["name": "attr_value", "type": "custom_attribute", "match": "exists"]]]] let kAudienceConditionsWithSubstringMatchType: [Any] = ["and", ["or", ["or", ["name": "attr_value", "type": "custom_attribute", "value": "firefox", "match": "substring"]]]] let kAudienceConditionsWithGreaterThanMatchType: [Any] = ["and", ["or", ["or", ["name": "attr_value", "type": "custom_attribute", "value": 10, "match": "gt"]]]] let kAudienceConditionsWithLessThanMatchType: [Any] = ["and", ["or", ["or", ["name": "attr_value", "type": "custom_attribute", "value": 10, "match": "lt"]]]] let kInfinityIntConditionStr: [Any] = ["and", ["or", ["or", ["name": "attr_value", "type": "custom_attribute", "value": Double.infinity, "match": "exact"]]]] // MARK: - Properties var typedAudienceDatafile: Data! var optimizely: OptimizelyClient! // MARK: - SetUp override func setUp() { super.setUp() self.typedAudienceDatafile = OTUtils.loadJSONDatafile("typed_audience_datafile") self.optimizely = OptimizelyClient(sdkKey: "12345") try! self.optimizely.start(datafile: typedAudienceDatafile) } // MARK: - Utils func makeAudience(conditions: [Any]) -> Audience { let fullAudienceData: [String: Any] = ["id": kAudienceId, "name": kAudienceName, "conditions": conditions] return try! OTUtils.model(from: fullAudienceData) } func makeAudienceLegacy(conditions: String) -> Audience { let fullAudienceData: [String: Any] = ["id": kAudienceId, "name": kAudienceName, "conditions": conditions] return try! OTUtils.model(from: fullAudienceData) } // MARK: - Tests func testEvaluateConditionsMatch() { let audience = makeAudienceLegacy(conditions: kAudienceConditions) let attributes = ["device_type": "iPhone", "location": "San Francisco", "browser": "Chrome"] XCTAssertTrue(try! audience.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) } func testEvaluateConditionsDoNotMatch() { let audience = makeAudienceLegacy(conditions: kAudienceConditions) let attributes = ["device_type": "iPhone", "location": "San Francisco", "browser": "Firefox"] XCTAssertFalse(try! audience.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) } func testEvaluateSingleLeaf() { let config = self.optimizely.config let holder = ConditionHolder.array([ConditionHolder.leaf(ConditionLeaf.audienceId("3468206642"))]) let attributes = ["house": "Gryffindor"] let bool = try? holder.evaluate(project: config?.project, user: OTUtils.user(attributes: attributes)) XCTAssertTrue(bool!) } func testEvaluateEmptyUserAttributes() { let audience = makeAudienceLegacy(conditions: kAudienceConditions) let attributes = [String: String]() XCTAssertNil(try? audience.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) } func testEvaluateNullUserAttributes() { let audience = makeAudienceLegacy(conditions: kAudienceConditions) XCTAssertNil(try? audience.evaluate(project: nil, user: OTUtils.user(attributes: nil))) } func testTypedUserAttributesEvaluateTrue() { let audience = makeAudience(conditions: kAudienceConditionsWithAnd) let attributes: [String: Any] = ["device_type": "iPhone", "is_firefox": false, "num_users": 15, "pi_value": 3.14, "decimal_value": 3.15678] XCTAssertTrue(try! audience.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) } func testEvaluateTrueWhenNoUserAttributesAndConditionEvaluatesTrue() { //should return true if no attributes are passed and the audience conditions evaluate to true in the absence of attributes let conditions: [Any] = ["not", ["or", ["or", ["name": "input_value", "type": "custom_attribute", "match": "exists"]]]] let audience = makeAudience(conditions: conditions) XCTAssertTrue(try! audience.evaluate(project: nil, user: OTUtils.user(attributes: nil))) } // MARK: - Invalid Base Condition Tests func testEvaluateReturnsNullWithInvalidBaseCondition() { let attributes = ["device_type": "iPhone"] var condition = ["name": "device_type"] var userAttribute: UserAttribute = try! OTUtils.model(from: condition) XCTAssertNil(try? userAttribute.evaluate(user: OTUtils.user(attributes: attributes))) condition = ["name": "device_type", "value": "iPhone"] userAttribute = try! OTUtils.model(from: condition) XCTAssertNil(try? userAttribute.evaluate(user: OTUtils.user(attributes: attributes))) condition = ["name": "device_type", "match": "exact"] userAttribute = try! OTUtils.model(from: condition) XCTAssertNil(try? userAttribute.evaluate(user: OTUtils.user(attributes: attributes))) condition = ["name": "device_type", "type": "invalid"] userAttribute = try! OTUtils.model(from: condition) XCTAssertNil(try? userAttribute.evaluate(user: OTUtils.user(attributes: attributes))) condition = ["name": "device_type", "type": "custom_attribute"] userAttribute = try! OTUtils.model(from: condition) XCTAssertNil(try? userAttribute.evaluate(user: OTUtils.user(attributes: attributes))) } // MARK: - Invalid input Tests func testEvaluateReturnsNullWithInvalidConditionType() { let condition = ["name": "device_type", "value": "iPhone", "type": "invalid", "match": "exact"] let attributes = ["device_type": "iPhone"] let userAttribute: UserAttribute = try! OTUtils.model(from: condition) XCTAssertNil(try? userAttribute.evaluate(user: OTUtils.user(attributes: attributes))) } func testEvaluateReturnsNullWithNullValueTypeAndNonExistMatchType() { let condition1 = ["name": "device_type", "value": nil, "type": "custom_attribute", "match": "exact"] let condition2 = ["name": "device_type", "value": nil, "type": "custom_attribute", "match": "exists"] let condition3 = ["name": "device_type", "value": nil, "type": "custom_attribute", "match": "substring"] let condition4 = ["name": "device_type", "value": nil, "type": "custom_attribute", "match": "gt"] let condition5 = ["name": "device_type", "value": nil, "type": "custom_attribute", "match": "lt"] let attributes = ["device_type": "iPhone"] var userAttribute: UserAttribute = try! OTUtils.model(from: condition1) XCTAssertNil(try? userAttribute.evaluate(user: OTUtils.user(attributes: attributes))) userAttribute = try! OTUtils.model(from: condition2) XCTAssertTrue(try! userAttribute.evaluate(user: OTUtils.user(attributes: attributes))) userAttribute = try! OTUtils.model(from: condition3) XCTAssertNil(try? userAttribute.evaluate(user: OTUtils.user(attributes: attributes))) userAttribute = try! OTUtils.model(from: condition4) XCTAssertNil(try? userAttribute.evaluate(user: OTUtils.user(attributes: attributes))) userAttribute = try! OTUtils.model(from: condition5) XCTAssertNil(try? userAttribute.evaluate(user: OTUtils.user(attributes: attributes))) } func testEvaluateReturnsNullWithInvalidMatchType() { let condition = ["name": "device_type", "value": "iPhone", "type": "custom_attribute", "match": "invalid"] let attributes = ["device_type": "iPhone"] let userAttribute: UserAttribute = try! OTUtils.model(from: condition) XCTAssertNil(try? userAttribute.evaluate(user: OTUtils.user(attributes: attributes))) } func testEvaluateReturnsNullWithInvalidValueForMatchType() { let condition: [String: Any] = ["name": "is_firefox", "value": false, "type": "custom_attribute", "match": "substring"] let attributes = ["is_firefox": false] let userAttribute: UserAttribute = try! OTUtils.model(from: condition) XCTAssertNil(try? userAttribute.evaluate(user: OTUtils.user(attributes: attributes))) } // MARK: - ExactMatcher Tests func testExactMatcherReturnsNullWhenUnsupportedConditionValue() { let condition: [String: Any] = ["name": "device_type", "value": [], "type": "custom_attribute", "match": "exact"] let attributes = ["device_type": "iPhone"] let userAttribute: UserAttribute = try! OTUtils.model(from: condition) XCTAssertNil(try? userAttribute.evaluate(user: OTUtils.user(attributes: attributes))) } func testExactMatcherReturnsNullWhenNoUserProvidedValue() { let attributes: [String: Any] = [:] var conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchStringType) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) conditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchBoolType) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) conditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchDecimalType) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) conditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchIntType) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) } func testExactMatcherReturnsFalseWhenAttributeValueDoesNotMatch() { let attributes1 = ["attr_value": "chrome"] let attributes2 = ["attr_value": true] let attributes3 = ["attr_value": 2.5] let attributes4 = ["attr_value": 55] var conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchStringType) XCTAssertFalse(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes1))) conditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchBoolType) XCTAssertFalse(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes2))) conditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchDecimalType) XCTAssertFalse(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes3))) conditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchIntType) XCTAssertFalse(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes4))) } func testExactMatcherReturnsNullWhenTypeMismatch() { let attributes1 = ["attr_value": true] let attributes2 = ["attr_value": "abcd"] let attributes3 = ["attr_value": false] let attributes4 = ["attr_value": "apple"] let attributes5 = [String: String]() //let attributes6 = ["attr_value" : nil] var conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchStringType) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes1))) conditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchBoolType) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes2))) conditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchDecimalType) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes3))) conditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchIntType) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes4))) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes5))) } func testExactMatcherReturnsNullWithNumericInfinity() { // TODO: [Jae] confirm: do we need this inifinite case for Swift? Not parsed OK (invalid) let attributes = ["attr_value": Double.infinity] let andCondition1: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchIntType) XCTAssertNil(try? andCondition1.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) } func testExactMatcherReturnsTrueWhenAttributeValueMatches() { let attributes1 = ["attr_value": "firefox"] let attributes2 = ["attr_value": false] let attributes3 = ["attr_value": 1.5] let attributes4 = ["attr_value": 10] let attributes5 = ["attr_value": 10.0] var conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchStringType) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes1))) conditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchBoolType) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes2))) conditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchDecimalType) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes3))) conditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchIntType) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes4))) conditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExactMatchIntType) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes5))) } // MARK: - ExistsMatcher Tests func testExistsMatcherReturnsFalseWhenAttributeIsNotProvided() { let attributes = [String: String]() let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExistsMatchType) XCTAssertFalse(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) } func testExistsMatcherReturnsFalseWhenAttributeIsNull() { let attributes: [String: Any?] = ["attr_value": nil] let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExistsMatchType) XCTAssertFalse(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) } func testExistsMatcherReturnsFalseWhenAttributeIsNSNull() { let attributes: [String: Any?] = ["attr_value": NSNull()] let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExistsMatchType) XCTAssertFalse(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) } func testExistsMatcherReturnsTrueWhenAttributeValueIsProvided() { let attributes1 = ["attr_value": ""] let attributes2 = ["attr_value": "iPhone"] let attributes3 = ["attr_value": 10] let attributes4 = ["attr_value": 10.5] let attributes5 = ["attr_value": false] let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithExistsMatchType) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes1))) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes2))) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes3))) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes4))) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes5))) } // MARK: - SubstringMatcher Tests func testSubstringMatcherReturnsNullWhenUnsupportedConditionValue() { let condition: [String: Any] = ["name": "device_type", "value": [], "type": "custom_attribute", "match": "substring"] let attributes = ["device_type": "iPhone"] let userAttribute: ConditionHolder = try! OTUtils.model(from: condition) XCTAssertNil(try? userAttribute.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) } func testSubstringMatcherReturnsFalseWhenConditionValueIsNotSubstringOfUserValue() { let attributes = ["attr_value": "Breaking news!"] let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithSubstringMatchType) XCTAssertFalse(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) } func testSubstringMatcherReturnsTrueWhenConditionValueIsSubstringOfUserValue() { let attributes1 = ["attr_value": "firefox"] let attributes2 = ["attr_value": "chrome vs firefox"] let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithSubstringMatchType) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes1))) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes2))) } func testSubstringMatcherReturnsNullWhenAttributeValueIsNotAString() { let attributes1 = ["attr_value": 10.5] let attributes2: [String: Any?] = ["attr_value": nil] let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithSubstringMatchType) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes1))) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes2))) } func testSubstringMatcherReturnsNullWhenAttributeIsNotProvided() { let attributes1: [String: Any] = [:] let attributes2: [String: Any]? = nil let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithSubstringMatchType) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes1))) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes2))) } // MARK: - GTMatcher Tests func testGTMatcherReturnsFalseWhenAttributeValueIsLessThanOrEqualToConditionValue() { let attributes1 = ["attr_value": 5] let attributes2 = ["attr_value": 10] let attributes3 = ["attr_value": 10.0] let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithGreaterThanMatchType) XCTAssertFalse(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes1))) XCTAssertFalse(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes2))) XCTAssertFalse(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes3))) } func testGTMatcherReturnsNullWhenAttributeValueIsNotANumericValue() { let attributes1 = ["attr_value": "invalid"] let attributes2 = [String: String]() let attributes3 = ["attr_value": true] let attributes4 = ["attr_value": false] let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithGreaterThanMatchType) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes1))) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes2))) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes3))) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes4))) } func testGTMatcherReturnsNullWhenAttributeValueIsInfinity() { let attributes = ["attr_value": Double.infinity] let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithGreaterThanMatchType) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) } func testGTMatcherReturnsTrueWhenAttributeValueIsGreaterThanConditionValue() { let attributes1 = ["attr_value": 15] let attributes2 = ["attr_value": 10.1] let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithGreaterThanMatchType) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes1))) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes2))) } // MARK: - LTMatcher Tests func testLTMatcherReturnsFalseWhenAttributeValueIsGreaterThanOrEqualToConditionValue() { let attributes1 = ["attr_value": 15] let attributes2 = ["attr_value": 10] let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithLessThanMatchType) XCTAssertFalse(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes1))) XCTAssertFalse(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes2))) } func testLTMatcherReturnsNullWhenAttributeValueIsNotANumericValue() { let attributes1 = ["attr_value": "invalid"] let attributes2 = [String: String]() let attributes3 = ["attr_value": true] let attributes4 = ["attr_value": false] let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithLessThanMatchType) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes1))) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes2))) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes3))) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes4))) } func testLTMatcherReturnsNullWhenAttributeValueIsInfinity() { let attributes = ["attr_value": Double.infinity] let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithLessThanMatchType) XCTAssertNil(try? conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes))) } func testLTMatcherReturnsTrueWhenAttributeValueIsLessThanConditionValue() { let attributes1 = ["attr_value": 5] let attributes2 = ["attr_value": 9.9] let conditionHolder: ConditionHolder = try! OTUtils.model(from: kAudienceConditionsWithLessThanMatchType) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes1))) XCTAssertTrue(try! conditionHolder.evaluate(project: nil, user: OTUtils.user(attributes: attributes2))) } }
a8292ec127db9ff742251520d50bde19
51.386233
365
0.656508
false
true
false
false
lopsae/sudden
refs/heads/master
Example/Sudden/AppDelegate.swift
mit
1
// // Copyright © 2016 LopSae. // import UIKit import Sudden @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var viewController: UIViewController! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]? ) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds); window!.tintColor = UIColor.redColor() window!.backgroundColor = UIColor.darkGrayColor() let rightBarButton = UIBarButtonItem( title: "demo", style: .Plain ) { [unowned self] in self.viewController.view.backgroundColor = UIColor.greenColor() } viewController = UIViewController() viewController.navigationItem.title = "sudden" viewController.view.backgroundColor = UIColor.grayColor() viewController.navigationItem.rightBarButtonItem = rightBarButton let navController = UINavigationController() navController.viewControllers = [viewController] window!.rootViewController = navController; window!.makeKeyAndVisible() return true } }
bc1f04470c6012221d2e21a1569a383e
22.521739
69
0.756932
false
false
false
false
hikki912/BeautyStory
refs/heads/master
BeautyStory/BeautyStory/Classes/PhotoBrowser/Model/PhotoBrowserLayout.swift
mit
1
// // PhotoBrowserLayout.swift // BeautyStory // // Created by hikki on 2017/3/3. // Copyright © 2017年 hikki. All rights reserved. // import UIKit class PhotoBrowserLayout: UICollectionViewFlowLayout { override func prepare() { super.prepare() // 1.设置itemSize itemSize = UIScreen.main.bounds.size // 2.设置collectionView水平滚动方向 scrollDirection = .horizontal // 3.设置分页效果 collectionView?.isPagingEnabled = true // 4.设置最小行间距 minimumLineSpacing = 15 // 5.CollectionView的宽度加大 collectionView?.frame.size.width = UIScreen.main.bounds.width + minimumLineSpacing // 6.右边增加15的额外滚动区域(设置scrollView的内边距: 增加额外的滚动区域,能够在UIScrollView的四周增加额外的滚动区域) collectionView?.contentInset.right += minimumLineSpacing } }
8a1c772d63b40f8e30b0e50183e131fb
24.818182
90
0.638498
false
false
false
false
prebid/prebid-mobile-ios
refs/heads/master
InternalTestApp/PrebidMobileDemoRendering/ViewControllers/Adapters/Prebid/MAX/PrebidMAXRewardedController.swift
apache-2.0
1
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import UIKit import AppLovinSDK import PrebidMobile import PrebidMobileMAXAdapters class PrebidMAXRewardedController: NSObject, AdaptedController, PrebidConfigurableController { var prebidConfigId: String = "" var storedAuctionResponse = "" var maxAdUnitId = "" private var adUnit: MediationRewardedAdUnit? private var mediationDelegate: MAXMediationRewardedUtils? private var rewarded: MARewardedAd? private weak var adapterViewController: AdapterViewController? private let fetchDemandFailedButton = EventReportContainer() private let didLoadAdButton = EventReportContainer() private let didFailToLoadAdForAdUnitIdentifierButton = EventReportContainer() private let didFailToDisplayButton = EventReportContainer() private let didDisplayAdButton = EventReportContainer() private let didHideAdButton = EventReportContainer() private let didClickAdButton = EventReportContainer() private let didRewardUserButton = EventReportContainer() private let configIdLabel = UILabel() // MARK: - AdaptedController required init(rootController: AdapterViewController) { self.adapterViewController = rootController super.init() setupAdapterController() } deinit { Prebid.shared.storedAuctionResponse = nil } func configurationController() -> BaseConfigurationController? { return BaseConfigurationController(controller: self) } func loadAd() { Prebid.shared.storedAuctionResponse = storedAuctionResponse configIdLabel.isHidden = false configIdLabel.text = "Config ID: \(prebidConfigId)" rewarded = MARewardedAd.shared(withAdUnitIdentifier: maxAdUnitId) rewarded?.delegate = self mediationDelegate = MAXMediationRewardedUtils(rewardedAd: rewarded!) adUnit = MediationRewardedAdUnit(configId: prebidConfigId, mediationDelegate: mediationDelegate!) if let adUnitContext = AppConfiguration.shared.adUnitContext { for dataPair in adUnitContext { adUnit?.addContextData(dataPair.value, forKey: dataPair.key) } } if let userData = AppConfiguration.shared.userData { for dataPair in userData { let appData = PBMORTBContentData() appData.ext = [dataPair.key: dataPair.value] adUnit?.addUserData([appData]) } } if let appData = AppConfiguration.shared.appContentData { for dataPair in appData { let appData = PBMORTBContentData() appData.ext = [dataPair.key: dataPair.value] adUnit?.addAppContentData([appData]) } } adUnit?.fetchDemand { [weak self] result in guard let self = self else { return } if result != .prebidDemandFetchSuccess { self.fetchDemandFailedButton.isEnabled = true } self.rewarded?.load() } } // MARK: - Private Methods private func setupAdapterController() { adapterViewController?.bannerView.isHidden = true setupShowButton() setupActions() configIdLabel.isHidden = true adapterViewController?.actionsView.addArrangedSubview(configIdLabel) } private func setupShowButton() { adapterViewController?.showButton.isEnabled = false adapterViewController?.showButton.addTarget(self, action:#selector(self.showButtonClicked), for: .touchUpInside) } private func setupActions() { adapterViewController?.setupAction(fetchDemandFailedButton, "fetchDemandFailed called") adapterViewController?.setupAction(didLoadAdButton, "didLoadAd called") adapterViewController?.setupAction(didFailToLoadAdForAdUnitIdentifierButton, "didFailToLoadAdForAdUnitIdentifier called") adapterViewController?.setupAction(didFailToDisplayButton, "didFailToDisplay called") adapterViewController?.setupAction(didDisplayAdButton, "didDisplayAd called") adapterViewController?.setupAction(didHideAdButton, "didHideAd called") adapterViewController?.setupAction(didClickAdButton, "didClickAd called") adapterViewController?.setupAction(didRewardUserButton, "didRewardUser called") } private func resetEvents() { fetchDemandFailedButton.isEnabled = false didLoadAdButton.isEnabled = false didFailToLoadAdForAdUnitIdentifierButton.isEnabled = false didFailToDisplayButton.isEnabled = false didDisplayAdButton.isEnabled = false didHideAdButton.isEnabled = false didClickAdButton.isEnabled = false didRewardUserButton.isEnabled = false } @IBAction func showButtonClicked() { if let rewarded = rewarded, rewarded.isReady { adapterViewController?.showButton.isEnabled = false rewarded.show() } } } extension PrebidMAXRewardedController: MARewardedAdDelegate { func didLoad(_ ad: MAAd) { resetEvents() didLoadAdButton.isEnabled = true adapterViewController?.showButton.isEnabled = true } func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) { Log.error(error.message) resetEvents() didFailToLoadAdForAdUnitIdentifierButton.isEnabled = true } func didFail(toDisplay ad: MAAd, withError error: MAError) { Log.error(error.message) resetEvents() didFailToDisplayButton.isEnabled = true } func didDisplay(_ ad: MAAd) { didDisplayAdButton.isEnabled = true } func didHide(_ ad: MAAd) { didHideAdButton.isEnabled = true } func didClick(_ ad: MAAd) { didClickAdButton.isEnabled = true } func didStartRewardedVideo(for ad: MAAd) { } func didCompleteRewardedVideo(for ad: MAAd) { } func didRewardUser(for ad: MAAd, with reward: MAReward) { didRewardUserButton.isEnabled = true } }
e088164fdbc207ae36b3f668a5d87c6d
33.737374
129
0.674179
false
true
false
false
Skogetroll/JSONSerializer
refs/heads/master
Carthage/Checkouts/Argo/Argo/Operators/Decode.swift
mit
7
/** Attempt to decode a value at the specified key into the requested type. This operator is used to decode a mandatory value from the `JSON`. If the decoding fails for any reason, this will result in a `.Failure` being returned. - parameter json: The `JSON` object containing the key - parameter key: The key for the object to decode - returns: A `Decoded` value representing the success or failure of the decode operation */ public func <| <A where A: Decodable, A == A.DecodedType>(json: JSON, key: String) -> Decoded<A> { return json <| [key] } /** Attempt to decode an optional value at the specified key into the requested type. This operator is used to decode an optional value from the `JSON`. If the key isn't present in the `JSON`, this will still return `.Success`. However, if the key exists but the object assigned to that key is unable to be decoded into the requested type, this will return `.Failure`. - parameter json: The `JSON` object containing the key - parameter key: The key for the object to decode - returns: A `Decoded` optional value representing the success or failure of the decode operation */ public func <|? <A where A: Decodable, A == A.DecodedType>(json: JSON, key: String) -> Decoded<A?> { return .optional(json <| [key]) } /** Attempt to decode a value at the specified key path into the requested type. This operator is used to decode a mandatory value from the `JSON`. If the decoding fails for any reason, this will result in a `.Failure` being returned. - parameter json: The `JSON` object containing the key - parameter keys: The key path for the object to decode, represented by an array of strings - returns: A `Decoded` value representing the success or failure of the decode operation */ public func <| <A where A: Decodable, A == A.DecodedType>(json: JSON, keys: [String]) -> Decoded<A> { return flatReduce(keys, initial: json, combine: decodedJSON) >>- A.decode } /** Attempt to decode an optional value at the specified key path into the requested type. This operator is used to decode an optional value from the `JSON`. If any of the keys in the key path aren't present in the `JSON`, this will still return `.Success`. However, if the key path exists but the object assigned to the final key is unable to be decoded into the requested type, this will return `.Failure`. - parameter json: The `JSON` object containing the key - parameter keys: The key path for the object to decode, represented by an array of strings - returns: A `Decoded` optional value representing the success or failure of the decode operation */ public func <|? <A where A: Decodable, A == A.DecodedType>(json: JSON, keys: [String]) -> Decoded<A?> { return .optional(json <| keys) } /** Attempt to decode an array of values at the specified key into the requested type. This operator is used to decode a mandatory array of values from the `JSON`. If the decoding of any of the objects fail for any reason, this will result in a `.Failure` being returned. - parameter json: The `JSON` object containing the key - parameter key: The key for the array of objects to decode - returns: A `Decoded` array of values representing the success or failure of the decode operation */ public func <|| <A where A: Decodable, A == A.DecodedType>(json: JSON, key: String) -> Decoded<[A]> { return json <|| [key] } /** Attempt to decode an optional array of values at the specified key into the requested type. This operator is used to decode an optional array of values from the `JSON`. If the key isn't present in the `JSON`, this will still return `.Success`. However, if the key exists but the objects assigned to that key are unable to be decoded into the requested type, this will return `.Failure`. - parameter json: The `JSON` object containing the key - parameter key: The key for the object to decode - returns: A `Decoded` optional array of values representing the success or failure of the decode operation */ public func <||? <A where A: Decodable, A == A.DecodedType>(json: JSON, key: String) -> Decoded<[A]?> { return .optional(json <|| [key]) } /** Attempt to decode an array of values at the specified key path into the requested type. This operator is used to decode a mandatory array of values from the `JSON`. If the decoding fails for any reason, this will result in a `.Failure` being returned. - parameter json: The `JSON` object containing the key - parameter keys: The key path for the object to decode, represented by an array of strings - returns: A `Decoded` array of values representing the success or failure of the decode operation */ public func <|| <A where A: Decodable, A == A.DecodedType>(json: JSON, keys: [String]) -> Decoded<[A]> { return flatReduce(keys, initial: json, combine: decodedJSON) >>- Array<A>.decode } /** Attempt to decode an optional array of values at the specified key path into the requested type. This operator is used to decode an optional array of values from the `JSON`. If any of the keys in the key path aren't present in the `JSON`, this will still return `.Success`. However, if the key path exists but the objects assigned to the final key are unable to be decoded into the requested type, this will return `.Failure`. - parameter json: The `JSON` object containing the key - parameter keys: The key path for the object to decode, represented by an array of strings - returns: A `Decoded` optional array of values representing the success or failure of the decode operation */ public func <||? <A where A: Decodable, A == A.DecodedType>(json: JSON, keys: [String]) -> Decoded<[A]?> { return .optional(json <|| keys) }
67b1a7bce3769dd6d1a099df1c2d2e32
38.7
106
0.698069
false
false
false
false
quran/quran-ios
refs/heads/main
Sources/TranslationService/TranslationsRepository.swift
apache-2.0
1
// // TranslationsRepository.swift // Quran // // Created by Mohamed Afifi on 2/26/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import BatchDownloader import Foundation import PromiseKit public struct TranslationsRepository { let networkManager: TranslationNetworkManager let persistence: ActiveTranslationsPersistence public init(databasesPath: String, baseURL: URL) { let urlSession = BatchDownloader.NetworkManager(session: .shared, baseURL: baseURL) networkManager = DefaultTranslationNetworkManager(networkManager: urlSession, parser: JSONTranslationsParser()) persistence = SQLiteActiveTranslationsPersistence(directory: databasesPath) } public func downloadAndSyncTranslations() -> Promise<Void> { let local = DispatchQueue.global().async(.promise, execute: persistence.retrieveAll) let remote = networkManager.getTranslations() return when(fulfilled: local, remote) // get local and remote .map(combine) // combine local and remote .map(saveCombined) // save combined list } private func combine(local: [Translation], remote: [Translation]) -> ([Translation], [String: Translation]) { let localMapConstant = local.flatGroup { $0.fileName } var localMap = localMapConstant var combinedList: [Translation] = [] remote.forEach { remote in var combined = remote if let local = localMap[remote.fileName] { combined.installedVersion = local.installedVersion localMap[remote.fileName] = nil } combinedList.append(combined) } combinedList.append(contentsOf: localMap.map { $1 }) return (combinedList, localMapConstant) } private func saveCombined(translations: [Translation], localMap: [String: Translation]) throws { try translations.forEach { translation in if localMap[translation.fileName] != nil { try self.persistence.update(translation) } else { try self.persistence.insert(translation) } } } }
1afb813fb28c733828d06fbad1f8c83f
37.771429
119
0.681282
false
false
false
false
huangxinping/XPKit-swift
refs/heads/master
Source/XPKit/XPDataStructures.swift
mit
1
// // XPDataStructures.swift // XPKit // // The MIT License (MIT) // // Copyright (c) 2015 - 2016 Fabrizio Brancati. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation // MARK: - Stack class - /// Primitive Stack implementation public class Stack: CustomStringConvertible { /// Describe the Stack public var description: String { return "\(stack)" } /// Private, the array behind Stack private var stack: Array<AnyObject> = Array<AnyObject>() /** Returns if the Stack is empty or not - returns: Returns true if the Stack is empty, otherwise false */ public func empty() -> Bool { return stack.isEmpty } /** Adds an element on top of the Stack - parameter object: The element to add */ public func push(object: AnyObject) { stack.append(object) } /** Removes an element on top of the Stack - returns: Returns the removed element */ public func pop() -> AnyObject? { var popped: AnyObject? = nil if !self.empty() { popped = stack[stack.count - 1] stack.removeAtIndex(stack.count - 1) } return popped } } // MARK: - List class - /// Primitive List implementation. In order to work, the List must contain only objects that is subclass of NSObject public class List: CustomStringConvertible { /// Describe the List public var description: String { return "\(list)" } /// Private, the array behind the List private var list: Array<AnyObject> = Array<AnyObject>() /** Search an element and returns the index - parameter object: The element to search - returns: Returns the index of the searched element */ public func search(object: AnyObject) -> Int? { for i in 0 ..< list.count { if object is NSObject { if list[i] as! NSObject == object as! NSObject { return i } } else { return nil } } return nil } /** Search for an index and returns the element - parameter index: The index - returns: Returns the element of the searched index */ public func search(index: Int) -> AnyObject? { return list.safeObjectAtIndex(index) } /** Insert an element in the List - parameter object: The element to insert in the List */ public func insert(object: AnyObject) { list.append(object) } /** Delete an element in the List - parameter object: The object to be deleted - returns: Retruns true if removed, otherwise false */ public func delete(object: AnyObject) -> Bool { let search = self.search(object) if search != nil { list.removeAtIndex(search!) return true } else { return false } } /** Delete an element at the given index - parameter index: The index to delete */ public func delete(index: Int) { list.removeAtIndex(index) } } // MARK: - Queue class - /// Primitive Queue implementation public class Queue: CustomStringConvertible { /// Describe the Queue public var description: String { return "\(queue)" } /// Private, the array behind the Queue private var queue: Array<AnyObject> = Array<AnyObject>() /** Adds an element to the Queue - parameter object: The element to add */ public func enqueue(object: AnyObject) { queue.append(object) } /** Dequeue the first element - returns: Retruns true if removed, otherwise false */ public func dequeue() -> Bool { if queue.count > 0 { queue.removeAtIndex(0) return true } else { return false } } /** Returns the element on the top of the Queue - returns: Returns the element on the top of the Queue */ public func top() -> AnyObject? { return queue.first } /** Remove all the elements in the Queue */ public func emptyQueue() { queue.removeAll(keepCapacity: false) } }
609c479ccf6eecb1586600b189b35f4b
22.067961
116
0.691709
false
false
false
false
Aahung/two-half-password
refs/heads/master
two-half-password/Controllers/VaultItemDetailSubViewControllers/webforms_WebFormViewController.swift
mit
1
// // webforms_WebFormViewController.swift // two-half-password // // Created by Xinhong LIU on 17/6/15. // Copyright © 2015 ParseCool. All rights reserved. // import Cocoa import SwiftyTimer class webforms_WebFormViewController: VaultItemDetailSubViewController { @IBOutlet weak var usernameField: NSTextField! @IBOutlet weak var passwordField: NSSecureTextField! @IBOutlet weak var passwordRevealButton: NSButton! @IBOutlet weak var websiteField: NSTextField! var hud: MBProgressHUD? func showCopiedHUD() { if hud == nil { hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true) hud?.mode = MBProgressHUDModeText hud?.labelText = "Copied to clipboard" } else { hud?.show(true) } NSTimer.after(1.second) { NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in hud?.hide(true) }) } } @IBAction func usernameCopyAction(sender: AnyObject) { NSPasteboard.generalPasteboard().clearContents() NSPasteboard.generalPasteboard().writeObjects([usernameField.stringValue]) showCopiedHUD() } @IBAction func passwordCopyAction(sender: AnyObject) { NSPasteboard.generalPasteboard().clearContents() NSPasteboard.generalPasteboard().writeObjects([passwordField.stringValue]) showCopiedHUD() } @IBAction func passwordRevealAction(sender: AnyObject) { } override func displayInfo(dictionary: NSDictionary) { // fields let fields = dictionary.valueForKey("fields") as! NSArray for field in fields { let name = (field as! NSDictionary).valueForKey("name") as! String let value = (field as! NSDictionary).valueForKey("value") as! String if name == "password" { passwordField.stringValue = value } else if name == "username" { usernameField.stringValue = value } } // url, only showing one if (dictionary.valueForKey("URLs") != nil) { let urls = dictionary.valueForKey("URLs") as! NSArray if urls.count > 0 { let firstURL = urls[0] as! NSDictionary let urlString = firstURL.valueForKey("url") as! String let link = NSMutableAttributedString(string: urlString) link.addAttribute(NSLinkAttributeName, value: urlString, range: NSMakeRange(0, link.length)) websiteField.attributedStringValue = link } } else { websiteField.stringValue = "no specified" } } override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) { if segue.identifier == "popover" { let popoverViewController = segue.destinationController as! PopoverLabelViewController popoverViewController.stringValue = passwordField.stringValue } } }
8e07f9ea276d227c3e9ac9bbeb58e406
33.52809
108
0.615685
false
false
false
false
andrebocchini/SwiftChattyOSX
refs/heads/master
Pods/SwiftChatty/SwiftChatty/Responses/Notifications/GetUserSetupResponse.swift
mit
1
// // GetUserSetupResponse.swift // SwiftChatty // // Created by Andre Bocchini on 1/28/16. // Copyright © 2016 Andre Bocchini. All rights reserved. // import Genome /// - SeeAlso: http://winchatty.com/v2/readme#_Toc421451710 public struct GetUserSetupResponse { public var userSetup: UserSetup = UserSetup() public init() {} } extension GetUserSetupResponse: MappableResponse { public mutating func sequence(map: Map) throws { var triggerOnReply: Bool = false var triggerOnMention: Bool = false var triggerKeywords: [String] = [] try triggerOnReply <~ map ["triggerOnReply"] try triggerOnMention <~ map ["triggerOnMention"] try triggerKeywords <~ map ["triggerKeywords"] userSetup.triggerOnReply = triggerOnReply userSetup.triggerOnMention = triggerOnMention userSetup.triggerKeywords = triggerKeywords } }
e19992bd8a1089623b7c1820a5ce07f9
24.277778
59
0.689011
false
false
false
false
damoyan/BYRClient
refs/heads/master
FromScratch/Constants.swift
mit
1
// // Constants.swift // FromScratch // // Created by Yu Pengyang on 10/27/15. // Copyright (c) 2015 Yu Pengyang. All rights reserved. // import Foundation let appKey = "7f7bcb6eb5c510ce85bdca2473de844b" let appSecret = "44c3edb39e6c18af91296ae617e97846" let bundleID = NSBundle.mainBundle().bundleIdentifier ?? "com.caishuo.FromScratch" let state = "\(Int64(NSDate.timeIntervalSinceReferenceDate()))" let baseURLString = "http://bbs.byr.cn/open" let baseURL = NSURL(string: baseURLString)! let oauth2URLString = "http://bbs.byr.cn/oauth2/authorize" let oauthResponseType = "token" let oauthRedirectUri = "http://bbs.byr.cn/oauth2/callback" struct Notifications { static let InvalidToken = "cn.ypy.notifications.InvalidToken" }
59ed69cc24840d4bba3261c078070bb5
28.64
82
0.756757
false
false
false
false
baiyidjp/SwiftWB
refs/heads/master
SwiftWeibo/SwiftWeibo/Classes/View(视图和控制器)/Main/Compose/View/JPComposeTextView.swift
mit
1
// // JPComposeTextView.swift // SwiftWeibo // // Created by Keep丶Dream on 16/12/12. // Copyright © 2016年 dongjiangpeng. All rights reserved. // import UIKit class JPComposeTextView: UITextView { /// 占位符 fileprivate lazy var placeholderLabel = UILabel() override func awakeFromNib() { //注册通知 NotificationCenter.default.addObserver(self, selector: #selector(textViewTextDidChange), name: NSNotification.Name.UITextViewTextDidChange, object: self) setupUI() } /// 占位符的显示与消失 @objc fileprivate func textViewTextDidChange() { placeholderLabel.isHidden = self.hasText } deinit { //移除通知 NotificationCenter.default.removeObserver(self) } } // MARK: - 设置UI fileprivate extension JPComposeTextView { func setupUI() { placeholderLabel.text = "分享新鲜事..." placeholderLabel.font = self.font placeholderLabel.textColor = UIColor.lightGray placeholderLabel.frame.origin = CGPoint(x: 5, y: 8) placeholderLabel.sizeToFit() addSubview(placeholderLabel) } } //MARK: - 表情键盘与textView结合方法 extension JPComposeTextView { /// 插入表情(图文混排) /// /// - Parameter emoticonModel: nil为删除键 func insertEmoticon(emoticonModel:JPEmoticonModel?) { //若为nil 删除 guard let emoticonModel = emoticonModel else { deleteBackward() return } //是否是emoji 字符串 if let emoji = emoticonModel.emoji, let textRange = selectedTextRange { //插入emoji字符串 replace(textRange, withText: emoji) return } //走到此处 都是图片表情 //1-拿到图片表情对应的属性文本 let imageText = emoticonModel.imageText(font: font!) //2-使用当前textview的文本内容创建一个新的属性文本 用来接收图片的属性文本 let attributeText = NSMutableAttributedString(attributedString: attributedText) //3-更新属性文本 //记录当前鼠标的位置 let range = selectedRange //插入表情文本 attributeText.replaceCharacters(in: range, with: imageText) //4-恢复文本 光标位置 attributedText = attributeText //range的length是选中的文本的长度 重新设置时应该为0 selectedRange = NSRange(location: range.location+1, length: 0) //5-让代理执行(解决占位符不消失) delegate?.textViewDidChange?(self) textViewTextDidChange() } /// 将textview的属性文本 转换成 纯 文字的文本 /// /// - Returns: 纯文字的文本 func emoticonStringText() -> String { //用来接收转换的文本 var resultText = String() //获取textview的属性文本 guard let attritubeText = attributedText else { return resultText } //遍历属性文本 attritubeText.enumerateAttributes(in: NSRange(location: 0, length: (attritubeText.length)), options: [], using: { (dict, range, _) in //表情字符的 dict 中 存在 NSAttachment 便是表情字符 if let textAttachment = dict["NSAttachment"] { resultText += (textAttachment as! JPTextAttachment).chs ?? "" }else { let subStr = (attritubeText.string as NSString).substring(with: range) resultText += subStr } }) print(resultText) return resultText } }
8cda45518c79ab8a7a557a68bba1a753
25.984
161
0.584643
false
false
false
false
FlexMonkey/Blurable
refs/heads/master
FMBlurable/compnents/SliderWidget.swift
gpl-3.0
1
// // SliderWidget.swift // SceneKitExperiment // // Created by Simon Gladman on 04/11/2014. // Copyright (c) 2014 Simon Gladman. All rights reserved. // import UIKit class SliderWidget: UIControl { let slider = UISlider(frame: CGRectZero) let label = UILabel(frame: CGRectZero) required init(title: String) { super.init(frame: CGRectZero) self.title = title updateLabel() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var title: String = "" { didSet { updateLabel() } } var value: Float = 0 { didSet { slider.value = value updateLabel() } } override func didMoveToSuperview() { slider.addTarget(self, action: #selector(SliderWidget.sliderChangeHandler), forControlEvents: .ValueChanged) layer.cornerRadius = 5 layer.borderColor = UIColor.whiteColor().CGColor layer.borderWidth = 2 layer.backgroundColor = UIColor.darkGrayColor().colorWithAlphaComponent(0.25).CGColor addSubview(slider) addSubview(label) } func sliderChangeHandler() { value = slider.value sendActionsForControlEvents(.ValueChanged) } func updateLabel() { label.text = title + ": " + (NSString(format: "%.3f", Float(value)) as String) } override func layoutSubviews() { label.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height / 2).insetBy(dx: 5, dy: 5) slider.frame = CGRect(x: 0, y: frame.height / 2, width: frame.width, height: frame.height / 2).insetBy(dx: 5, dy: 5) } override func intrinsicContentSize() -> CGSize { return CGSize(width: 640, height: 75) } }
1b0371f319278d975994529db21e57a8
22.560976
124
0.573499
false
false
false
false
Crowdmix/Buildasaur
refs/heads/master
BuildaKit/Logging.swift
mit
4
// // Logging.swift // Buildasaur // // Created by Honza Dvorsky on 18/07/2015. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Foundation import BuildaUtils public class Logging { public class func setup(alsoIntoFile alsoIntoFile: Bool) { let path = Persistence.buildaApplicationSupportFolderURL().URLByAppendingPathComponent("Builda.log", isDirectory: false) var loggers = [Logger]() let consoleLogger = ConsoleLogger() loggers.append(consoleLogger) if alsoIntoFile { let fileLogger = FileLogger(filePath: path) loggers.append(fileLogger) } Log.addLoggers(loggers) let version = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String let ascii = " ____ _ _ _\n" + "| _ \\ (_) | | |\n" + "| |_) |_ _ _| | __| | __ _ ___ __ _ _ _ _ __\n" + "| _ <| | | | | |/ _` |/ _` / __|/ _` | | | | '__|\n" + "| |_) | |_| | | | (_| | (_| \\__ \\ (_| | |_| | |\n" + "|____/ \\__,_|_|_|\\__,_|\\__,_|___/\\__,_|\\__,_|_|\n" Log.untouched("*\n*\n*\n\(ascii)\nBuildasaur \(version) launched at \(NSDate()).\n*\n*\n*\n") } }
50faf2c2b18a9c941eb794bd23c3437e
31.875
128
0.462709
false
false
false
false
ThilinaHewagama/Pancha
refs/heads/master
Pancha/Source Files/Extensions/Date+Extension.swift
mit
1
// // Date+Extension.swift // Pancha // // Created by Thilina Chamin Hewagama on 3/28/17. // Copyright © 2017 Pancha iOS. All rights reserved. // import Foundation public extension Date{ //subscripts subscript(format:String)->String{ get{ return self.stringWithFormat(format: format) } } static func monthName(monthIndex:Int)->String{ let dateFormatter = DateFormatter() return dateFormatter.monthSymbols[monthIndex] } static func dayName(dayIndex:Int)->String{ let dateFormatter = DateFormatter() return dateFormatter.weekdaySymbols[dayIndex] } static func dateFromIso8681Timestamp(dateString:String)->Date{ return Date.dateFromString(dateString: dateString, withFormat: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'")! } init(fromIso8681Timestamp: String) { self.init() } static func dateFromString(dateString:String,withFormat format:String)->Date?{ let dateFormatter:DateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.date(from: dateString) as Date? } static func dateFromString(dateString:String,withFormat format:String, timeZone:TimeZone)->Date?{ let dateFormatter:DateFormatter = DateFormatter() dateFormatter.timeZone = timeZone dateFormatter.dateFormat = format return dateFormatter.date(from: dateString) } static func dateWithYear(year:Int, month:Int, day:Int, hour:Int, minute:Int, second:Int)->Date{ var dateComponents = DateComponents() dateComponents.year = year dateComponents.month = month dateComponents.day = day dateComponents.hour = hour dateComponents.minute = minute dateComponents.second = second let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! let date:Date = calendar.date(from: dateComponents)! return date } public var iso8681Timestamp:String{ get{ return self.stringWithFormat(format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'") } } public var year:Int { get{ let units:Set<Calendar.Component> = [.year] return Calendar.current.dateComponents(units, from: self).year! } } public var month:Int { get{ let units:Set<Calendar.Component> = [.month] return Calendar.current.dateComponents(units, from: self).month! } } public var monthName:String{ get{ return Date.monthName(monthIndex: self.month) } } public var weekOfYear:Int{ get{ let units:Set<Calendar.Component> = [.weekOfYear] return Calendar.current.dateComponents(units, from: self).weekOfYear! } } public var weekOfMonth:Int{ get{ let units:Set<Calendar.Component> = [.weekOfMonth] return Calendar.current.dateComponents(units, from: self).weekOfMonth! } } public var dayInWeek:Int{ get{ let units:Set<Calendar.Component> = [.weekday] return Calendar.current.dateComponents(units, from: self).weekday! } } public var weekDayOrdinal:Int{//1-7->1, 8-14->2..etc get{ let units:Set<Calendar.Component> = [.weekdayOrdinal] return Calendar.current.dateComponents(units, from: self).weekdayOrdinal! } } public var day:Int { get{ let units:Set<Calendar.Component> = [.day] return Calendar.current.dateComponents(units, from: self).day! } } public var dayName:String{ get{ return Date.dayName(dayIndex: self.day) } } public var hour:Int { get{ let units:Set<Calendar.Component> = [.hour] return Calendar.current.dateComponents(units, from: self).hour! } } public var minute:Int { get{ let units:Set<Calendar.Component> = [.minute] return Calendar.current.dateComponents(units, from: self).minute! } } public var second:Int { get{ let units:Set<Calendar.Component> = [.second] return Calendar.current.dateComponents(units, from: self).second! } } public var nextDay:Date{ get{ return self.date(byAddingYears: 0, months: 0, days: 1) as Date } } public var nextWorkingDay:Date{ get{ var nextDay = self.nextDay if nextDay.isWeekEnd { let datesToAdd = nextDay.isSaturday ? 2 : 1 nextDay = nextDay.date(byAddingYears: 0, months: 0, days: datesToAdd) } return nextDay } } public var previousDay:Date{ get{ return self.date(byAddingYears: 0, months: 0, days: -1) } } public var nextWeek:Date{ get{ return self.date(byAddingWeeks: 1) } } public var previousWeek:Date{ get{ return self.date(byAddingWeeks: -1) } } public var nextMonth:Date{ get{ return self.date(byAddingYears: 0, months: 1, days: 0) } } public var previousMonth:Date{ get{ return self.date(byAddingYears: 0, months: -1, days: 0) } } public func stringWithFormat(format:String)->String{ let dateFormatter:DateFormatter = DateFormatter() dateFormatter.dateFormat = format let dateString = dateFormatter.string(from: self) return dateString } public func printDateInCurrentLocale(){ print(self.description(with: Locale.current)) } public func date(byAddingYears years:Int, months:Int, days:Int)->Date{ var dateComponents = DateComponents() dateComponents.year = years dateComponents.month = months dateComponents.day = days let calendar = Calendar(identifier: .gregorian) return calendar.date(byAdding: dateComponents, to: self)! } public func date(byAddingHours hours:Int, minutes:Int, seconds:Int)->Date{ var dateComponents = DateComponents() dateComponents.hour = hours dateComponents.minute = minutes dateComponents.second = seconds let calendar = Calendar(identifier: .gregorian) return calendar.date(byAdding: dateComponents, to: self)! } public func date(byAddingWeeks weeks:Int)->Date{ var dateComponents = DateComponents() dateComponents.weekdayOrdinal = weeks let calendar = Calendar(identifier: .gregorian) return calendar.date(byAdding: dateComponents, to: self)! } //only date public var onlyDate:Date{ get{ let calendar = Calendar.current let units:Set<Calendar.Component> = [.hour, .minute, .second] var components = calendar.dateComponents(units, from: self) components.hour = 0 components.minute = 0 components.second = 0 return calendar.date(from: components)! } } //only time public var onlyTime:Date{ get{ let calendar = Calendar.current let units:Set<Calendar.Component> = [.year, .month, .day] var components = calendar.dateComponents(units, from: self) components.hour = 0 components.minute = 0 components.second = 0 return calendar.date(from: components)! } } /* NSCalendar *calendar = [NSCalendar currentCalendar]; NSCalendarUnit calendarUnits = NSCalendarUnitTimeZone | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond; DateComponents *components = [calendar components:calendarUnits fromDate:[Date date]]; components.hour += 3; Date *threeHoursFromNow = [calendar dateFromComponents:components]; */ /* Things to remember - MatchStrictly - MatchNextTime - MatchNextTimePreservingSmallerUnits - MatchPreviousTimePreservingSmallerUnits */ public var isYesterday:Bool{ get{ let date:Date = Date().date(byAddingYears: 0, months: 0, days: -1) return self.isSameDate(date: date) } } public var isToday:Bool{ get{ return self.isSameDate(date: Date()) } } public var isTomorrow:Bool{ get{ let date:Date = Date().date(byAddingYears: 0, months: 0, days: 1) return self.isSameDate(date: date) } } public var isLastMonth:Bool{ get{ let date:Date = Date().date(byAddingYears: 0, months: -1, days: 0) return self.isSameMonth(date: date) } } public var isThisMonth:Bool{ get{ return self.isSameMonth(date: Date()) } } public var isNextMonth:Bool{ get{ let date:Date = Date().date(byAddingYears: 0, months: 1, days: 0) return self.isSameMonth(date: date) } } public var isThisYear:Bool{ get{ return self.isSameYear(date: Date()) } } public func isSameDate(date:Date)->Bool{ let equalDays:Bool = (self.day == date.day) return (equalDays && self.isSameMonth(date: date)) } public func isSameWeek(date:Date)->Bool{ let equalWeeks:Bool = (self.weekOfMonth == date.weekOfMonth) return (equalWeeks && self.isSameMonth(date: date)) } public func isSameMonth(date:Date)->Bool{ let equalMonths:Bool = (self.month == date.month) return (self.isSameYear(date: date) && equalMonths) } public func isSameYear(date:Date)->Bool{ return (self.year == date.year) } public var isSunday:Bool{ get{ return (self.dayInWeek == 1) } } public var isMonday:Bool{ get{ return (self.dayInWeek == 2) } } public var isTuesday:Bool{ get{ return (self.dayInWeek == 3) } } public var isWednesday:Bool{ get{ return (self.dayInWeek == 4) } } public var isThursday:Bool{ get{ return (self.dayInWeek == 5) } } public var isFriday:Bool{ get{ return (self.dayInWeek == 6) } } public var isSaturday:Bool{ get{ return (self.dayInWeek == 7) } } public var isWeekEnd:Bool{ get{ return (self.isSunday || self.isSaturday) } } public var isWeekDay:Bool{ get{ return (self.isWeekEnd == false) } } }
c9c553de7245a61ebd2d1a66babeec27
22.616279
107
0.527901
false
false
false
false
bmichotte/HSTracker
refs/heads/master
HSTracker/HSReplay/HSReplayPreferences.swift
mit
1
// // HSReplayPreferences.swift // HSTracker // // Created by Benjamin Michotte on 13/08/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import MASPreferences import CleanroomLogger class HSReplayPreferences: NSViewController { @IBOutlet weak var synchronizeMatches: NSButton! @IBOutlet weak var gameTypeSelector: NSView! @IBOutlet weak var uploadRankedGames: NSButton! @IBOutlet weak var uploadCasualGames: NSButton! @IBOutlet weak var uploadArenaGames: NSButton! @IBOutlet weak var uploadBrawlGames: NSButton! @IBOutlet weak var uploadFriendlyGames: NSButton! @IBOutlet weak var uploadAdventureGames: NSButton! @IBOutlet weak var uploadSpectatorGames: NSButton! @IBOutlet weak var hsReplayAccountStatus: NSTextField! @IBOutlet weak var claimAccountButton: NSButtonCell! @IBOutlet weak var claimAccountInfo: NSTextField! @IBOutlet weak var disconnectButton: NSButton! @IBOutlet weak var showPushNotification: NSButton! private var getAccountTimer: Timer? private var requests = 0 private let maxRequests = 10 override func viewDidLoad() { super.viewDidLoad() showPushNotification.state = Settings.showHSReplayPushNotification ? NSOnState : NSOffState synchronizeMatches.state = Settings.hsReplaySynchronizeMatches ? NSOnState : NSOffState // swiftlint:disable line_length uploadRankedGames.state = Settings.hsReplayUploadRankedMatches ? NSOnState : NSOffState uploadCasualGames.state = Settings.hsReplayUploadCasualMatches ? NSOnState : NSOffState uploadArenaGames.state = Settings.hsReplayUploadArenaMatches ? NSOnState : NSOffState uploadBrawlGames.state = Settings.hsReplayUploadBrawlMatches ? NSOnState : NSOffState uploadFriendlyGames.state = Settings.hsReplayUploadFriendlyMatches ? NSOnState : NSOffState uploadAdventureGames.state = Settings.hsReplayUploadAdventureMatches ? NSOnState : NSOffState uploadSpectatorGames.state = Settings.hsReplayUploadSpectatorMatches ? NSOnState : NSOffState // swiftlint:enable line_length updateUploadGameTypeView() updateStatus() } override func viewDidDisappear() { getAccountTimer?.invalidate() } @IBAction func checkboxClicked(_ sender: NSButton) { if sender == synchronizeMatches { Settings.hsReplaySynchronizeMatches = synchronizeMatches.state == NSOnState } else if sender == showPushNotification { Settings.showHSReplayPushNotification = showPushNotification.state == NSOnState } else if sender == uploadRankedGames { Settings.hsReplayUploadRankedMatches = uploadRankedGames.state == NSOnState } else if sender == uploadCasualGames { Settings.hsReplayUploadCasualMatches = uploadCasualGames.state == NSOnState } else if sender == uploadArenaGames { Settings.hsReplayUploadArenaMatches = uploadArenaGames.state == NSOnState } else if sender == uploadBrawlGames { Settings.hsReplayUploadBrawlMatches = uploadBrawlGames.state == NSOnState } else if sender == uploadFriendlyGames { Settings.hsReplayUploadFriendlyMatches = uploadFriendlyGames.state == NSOnState } else if sender == uploadAdventureGames { Settings.hsReplayUploadAdventureMatches = uploadAdventureGames.state == NSOnState } else if sender == uploadSpectatorGames { Settings.hsReplayUploadSpectatorMatches = uploadSpectatorGames.state == NSOnState } updateUploadGameTypeView() } fileprivate func updateUploadGameTypeView() { if synchronizeMatches.state == NSOffState { uploadRankedGames.isEnabled = false uploadCasualGames.isEnabled = false uploadArenaGames.isEnabled = false uploadBrawlGames.isEnabled = false uploadFriendlyGames.isEnabled = false uploadAdventureGames.isEnabled = false uploadSpectatorGames.isEnabled = false } else { uploadRankedGames.isEnabled = true uploadCasualGames.isEnabled = true uploadArenaGames.isEnabled = true uploadBrawlGames.isEnabled = true uploadFriendlyGames.isEnabled = true uploadAdventureGames.isEnabled = true uploadSpectatorGames.isEnabled = true } } @IBAction func disconnectAccount(_ sender: AnyObject) { Settings.hsReplayUsername = nil Settings.hsReplayId = nil updateStatus() } @IBAction func resetAccount(_ sender: Any) { Settings.hsReplayUsername = nil Settings.hsReplayId = nil Settings.hsReplayUploadToken = nil updateStatus() } @IBAction func claimAccount(_ sender: AnyObject) { claimAccountButton.isEnabled = false requests = 0 HSReplayAPI.getUploadToken { _ in HSReplayAPI.claimAccount() self.getAccountTimer?.invalidate() self.getAccountTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.checkAccountInfo), userInfo: nil, repeats: true) } } @objc private func checkAccountInfo() { guard requests < maxRequests else { Log.warning?.message("max request for checking account info") return } HSReplayAPI.updateAccountStatus { (status) in self.requests += 1 if status { self.getAccountTimer?.invalidate() } self.updateStatus() } } private func updateStatus() { if Settings.hsReplayId != nil { var information = NSLocalizedString("Connected", comment: "") if let username = Settings.hsReplayUsername { information = String(format: NSLocalizedString("Connected as %@", comment: ""), username) } hsReplayAccountStatus.stringValue = information claimAccountInfo.isEnabled = false claimAccountButton.isEnabled = false disconnectButton.isEnabled = true } else { claimAccountInfo.isEnabled = true claimAccountButton.isEnabled = true disconnectButton.isEnabled = false hsReplayAccountStatus.stringValue = NSLocalizedString("Account status : Anonymous", comment: "") } } } // MARK: - MASPreferencesViewController extension HSReplayPreferences: MASPreferencesViewController { override var identifier: String? { get { return "hsreplay" } set { super.identifier = newValue } } var toolbarItemImage: NSImage? { return NSImage(named: "hsreplay_icon") } var toolbarItemLabel: String? { return "HSReplay" } }
4377ab677f476da588fee1c77f4625d9
38.285714
101
0.654126
false
false
false
false
Chaosspeeder/YourGoals
refs/heads/master
YourGoalsKit/CoreDataManager.swift
lgpl-3.0
1
// // CoreDataManager.swift // YourFitnessPlan // // Created by André Claaßen on 21.05.16. // Copyright © 2016 André Claaßen. All rights reserved. // // Important: Shared File between iOS App and WatchKit Extension import Foundation import CoreData /// a manager class for a core data database public class CoreDataManager { /// the url of the model let modelURL:URL /// name of the database let databaseName:String /// fetch the database from the group container, if this name is set let groupName:String? // true, if write ahead logging (WAL-Mode) on sqllite is enabled (default) let journalingEnabled: Bool /// create a new sqlite database with the given name for a bundle /// /// - Parameters: /// - databaseName: name of the database file /// - modelName: name of the data model /// - bundle: the bundle for storing /// - groupName: optional name of the application group /// - journalingEnabled: true, if write ahead mode is enabled public init(databaseName:String, modelName:String, bundle:Bundle, groupName:String?, journalingEnabled: Bool) { self.databaseName = databaseName self.journalingEnabled = journalingEnabled self.modelURL = bundle.url(forResource: modelName, withExtension: "momd")! self.groupName = groupName } lazy var documentDirectory: URL = { if let groupName = self.groupName { guard let groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: groupName) else { fatalError("couldn't locate the URL for the application group: \(groupName)") } return groupURL } // The directory the application uses to store the Core Data store file. This code uses a directory named "com.andre.claassen.TestMasterDetail" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { let model = self.modelURL // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. return NSManagedObjectModel(contentsOf: model)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added 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. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.documentDirectory.appendingPathComponent(self.databaseName) var failureReason = "There was an error creating or loading the application's saved data." do { var options:[String : Any] = [ NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true ] // disable write ahead mode for sqlite, if journaling is not enabled if !self.journalingEnabled { options[NSSQLitePragmasOption] = ["journal_mode" : "DELETE"] } try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options) } catch { // Report any error we got. var dict = [String : Any]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() 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. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() public lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() internal func saveContext() throws { try self.managedObjectContext.save() } }
91e5b4983cb2bebf524333420b1f516c
45.403509
291
0.677316
false
false
false
false
ninjaprawn/Crunch
refs/heads/master
Crunch/SOLabel.swift
apache-2.0
1
// // SOLabel.swift // Crunch // // Created by George Dan on 17/04/2015. // Copyright (c) 2015 Ninjaprawn. All rights reserved. // import UIKit enum VerticalAlignment { case Top // default case Middle case Bottom } class SOLabel: UILabel { var verticalAlignment: VerticalAlignment override init(frame: CGRect) { verticalAlignment = VerticalAlignment.Top super.init(frame: frame) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setVerticalAlignment(alignment: VerticalAlignment) { self.verticalAlignment = alignment self.setNeedsDisplay() } override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect { var rect = super.textRectForBounds(bounds, limitedToNumberOfLines: numberOfLines) var result: CGRect switch self.verticalAlignment { case VerticalAlignment.Top: result = CGRectMake(bounds.origin.x, bounds.origin.y, rect.size.width, rect.size.height); break case VerticalAlignment.Middle: result = CGRectMake(bounds.origin.x, bounds.origin.y + (bounds.size.height - rect.size.height) / 2, rect.size.width, rect.size.height); break case VerticalAlignment.Bottom: result = CGRectMake(bounds.origin.x, bounds.origin.y + (bounds.size.height - rect.size.height), rect.size.width, rect.size.height); break default: result = bounds break } return result } override func drawTextInRect(rect: CGRect) { var r = self.textRectForBounds(rect, limitedToNumberOfLines: self.numberOfLines) super.drawTextInRect(r) } }
c398a52fe17cb57f09e8507fcc79a91d
28.703125
151
0.619148
false
false
false
false
darkbrow/iina
refs/heads/develop
iina/KeyCodeHelper.swift
gpl-3.0
2
// // KeyCodeHelper.swift // iina // // Created by lhc on 12/12/2016. // Copyright © 2016 lhc. All rights reserved. // import Foundation import Carbon fileprivate let modifierSymbols: [(NSEvent.ModifierFlags, String)] = [(.control, "⌃"), (.option, "⌥"), (.shift, "⇧"), (.command, "⌘")] class KeyCodeHelper { static let keyMap: [UInt16 : (String, String?)] = [ 0x00: ("a", "A"), 0x01: ("s", "S"), 0x02: ("d", "D"), 0x03: ("f", "F"), 0x04: ("h", "H"), 0x05: ("g", "G"), 0x06: ("z", "Z"), 0x07: ("x", "X"), 0x08: ("c", "C"), 0x09: ("v", "V"), 0x0B: ("b", "B"), 0x0C: ("q", "Q"), 0x0D: ("w", "W"), 0x0E: ("e", "E"), 0x0F: ("r", "R"), 0x10: ("y", "Y"), 0x11: ("t", "T"), 0x12: ("1", "!"), 0x13: ("2", "@"), 0x14: ("3", "SHARP"), 0x15: ("4", "$"), 0x16: ("6", "^"), 0x17: ("5", "%"), 0x18: ("=", "+"), 0x19: ("9", "("), 0x1A: ("7", "&"), 0x1B: ("-", "_"), 0x1C: ("8", "*"), 0x1D: ("0", ")"), 0x1E: ("]", "}"), 0x1F: ("o", "O"), 0x20: ("u", "U"), 0x21: ("[", "{"), 0x22: ("i", "I"), 0x23: ("p", "P"), 0x25: ("l", "L"), 0x26: ("j", "J"), 0x27: ("'", "\"\"\""), 0x28: ("k", "K"), 0x29: (";", ":"), 0x2A: ("\"\\\"", "|"), 0x2B: (",", "<"), 0x2C: ("/", "?"), 0x2D: ("n", "N"), 0x2E: ("m", "M"), 0x2F: (".", ">"), 0x32: ("`", "~"), 0x41: ("KP_DEC", nil), 0x43: ("*", nil), 0x45: ("+", nil), // 0x47: ("KeypadClear", nil), 0x4B: ("/", nil), 0x4C: ("KP_ENTER", nil), 0x4E: ("-", nil), 0x51: ("=", nil), 0x52: ("KP0", nil), 0x53: ("KP1", nil), 0x54: ("KP2", nil), 0x55: ("KP3", nil), 0x56: ("KP4", nil), 0x57: ("KP5", nil), 0x58: ("KP6", nil), 0x59: ("KP7", nil), 0x5B: ("KP8", nil), 0x5C: ("KP9", nil), 0x24: ("ENTER", nil), 0x30: ("TAB", nil), 0x31: ("SPACE", nil), 0x33: ("BS", nil), 0x35: ("ESC", nil), // 0x37: ("Command", nil), // 0x38: ("Shift", nil), // 0x39: ("CapsLock", nil), // 0x3A: ("Option", nil), // 0x3B: ("Control", nil), // 0x3C: ("RightShift", nil), // 0x3D: ("RightOption", nil), // 0x3E: ("RightControl", nil), // 0x3F: ("Function", nil), 0x40: ("F17", nil), // 0x48: ("VolumeUp", nil), // 0x49: ("VolumeDown", nil), // 0x4A: ("Mute", nil), 0x4F: ("F18", nil), 0x50: ("F19", nil), 0x5A: ("F20", nil), 0x60: ("F5", nil), 0x61: ("F6", nil), 0x62: ("F7", nil), 0x63: ("F3", nil), 0x64: ("F8", nil), 0x65: ("F9", nil), 0x67: ("F11", nil), 0x69: ("F13", nil), 0x6A: ("F16", nil), 0x6B: ("F14", nil), 0x6D: ("F10", nil), 0x6F: ("F12", nil), 0x71: ("F15", nil), 0x72: ("INS", nil), 0x73: ("HOME", nil), 0x74: ("PGUP", nil), 0x75: ("DEL", nil), 0x76: ("F4", nil), 0x77: ("END", nil), 0x78: ("F2", nil), 0x79: ("PGDWN", nil), 0x7A: ("F1", nil), 0x7B: ("LEFT", nil), 0x7C: ("RIGHT", nil), 0x7D: ("DOWN", nil), 0x7E: ("UP", nil), 0x7F: ("POWER", nil) // This should be KeyCode::PC_POWER. ] static let mpvSymbolToKeyChar: [String: String] = { return [ "LEFT": NSLeftArrowFunctionKey, "RIGHT": NSRightArrowFunctionKey, "UP": NSUpArrowFunctionKey, "DOWN": NSDownArrowFunctionKey, "BS": NSBackspaceCharacter, "KP_DEL": NSDeleteCharacter, "DEL": NSDeleteCharacter, "KP_INS": NSInsertFunctionKey, "INS": NSInsertFunctionKey, "HOME": NSHomeFunctionKey, "END": NSEndFunctionKey, "PGUP": NSPageUpFunctionKey, "PGDWN": NSPageDownFunctionKey, "PRINT": NSPrintFunctionKey, "F1": NSF1FunctionKey, "F2": NSF2FunctionKey, "F3": NSF3FunctionKey, "F4": NSF4FunctionKey, "F5": NSF5FunctionKey, "F6": NSF6FunctionKey, "F7": NSF7FunctionKey, "F8": NSF8FunctionKey, "F9": NSF9FunctionKey, "F10": NSF10FunctionKey, "F11": NSF11FunctionKey, "F12": NSF12FunctionKey ] .mapValues { String(Character(UnicodeScalar($0)!)) } .merging([ "SPACE": " ", "IDEOGRAPHIC_SPACE": "\u{3000}", "SHARP": "#", "ENTER": "\r", "ESC": "\u{1b}", "KP_DEC": ".", "KP_ENTER": "\r", "KP0": "0", "KP1": "1", "KP2": "2", "KP3": "3", "KP4": "4", "KP5": "5", "KP6": "6", "KP7": "7", "KP8": "8", "KP9": "9", "PLUS": "+" ]) { (v0, v1) in return v1 } }() static let mpvSymbolToKeyName: [String: String] = [ "META": "⌘", "SHIFT": "⇧", "ALT": "⌥", "CTRL":"⌃", "SHARP": "#", "ENTER": "↩︎", "KP_ENTER": "↩︎", "SPACE": "␣", "IDEOGRAPHIC_SPACE": "␣", "BS": "⌫", "DEL": "⌦", "KP_DEL": "⌦", "INS": "Ins", "KP_INS": "Ins", "TAB": "⇥", "ESC": "⎋", "UP": "↑", "DOWN": "↓", "LEFT": "←", "RIGHT" : "→", "PGUP": "⇞", "PGDWN": "⇟", "HOME": "↖︎", "END": "↘︎", "PLAY": "▶︎\u{2006}❙\u{200A}❙", "PREV": "◀︎◀︎", "NEXT": "▶︎▶︎", "PLUS": "+", "KP0": "0", "KP1": "1", "KP2": "2", "KP3": "3", "KP4": "4", "KP5": "5", "KP6": "6", "KP7": "7", "KP8": "8", "KP9": "9", ] static var reversedKeyMapForShift: [String: String] = keyMap.reduce([:]) { partial, keyMap in var partial = partial if let value = keyMap.value.1 { partial[value] = keyMap.value.0 } return partial } static func canBeModifiedByShift(_ key: UInt16) -> Bool { return key != 0x24 && (key <= 0x2F || key == 0x32) } static func isPrintable(_ char: String) -> Bool { let utf8View = char.utf8 return utf8View.count == 1 && utf8View.first! > 32 && utf8View.first! < 127 } static func mpvKeyCode(from event: NSEvent) -> String { var keyString = "" let keyChar: String let keyCode = event.keyCode var modifiers = event.modifierFlags if let char = event.charactersIgnoringModifiers, isPrintable(char) { keyChar = char let (_, rawKeyChar) = event.readableKeyDescription if rawKeyChar != char { modifiers.remove(.shift) } } else { // find the key from key code guard let keyName = KeyCodeHelper.keyMap[keyCode] else { Logger.log("Undefined key code?", level: .warning) return "" } keyChar = keyName.0 } // modifiers // the same order as `KeyMapping.modifierOrder` if modifiers.contains(.control) { keyString += "Ctrl+" } if modifiers.contains(.option) { keyString += "Alt+" } if modifiers.contains(.shift) { keyString += "Shift+" } if modifiers.contains(.command) { keyString += "Meta+" } // char keyString += keyChar return keyString } static func macOSKeyEquivalent(from mpvKeyCode: String, usePrintableKeyName: Bool = false) -> (key: String, modifiers: NSEvent.ModifierFlags)? { if mpvKeyCode == "+" { return ("+", []) } let splitted = mpvKeyCode.replacingOccurrences(of: "++", with: "+PLUS").components(separatedBy: "+") var key: String var modifiers: NSEvent.ModifierFlags = [] guard !splitted.isEmpty else { return nil } key = splitted.last! splitted.dropLast().forEach { k in switch k { case "Meta": modifiers.insert(.command) case "Ctrl": modifiers.insert(.control) case "Alt": modifiers.insert(.option) case "Shift": modifiers.insert(.shift) default: break } } if let realKey = (usePrintableKeyName ? mpvSymbolToKeyName : mpvSymbolToKeyChar)[key] { key = realKey } guard key.count == 1 else { return nil } return (key, modifiers) } static func readableString(fromKey key: String, modifiers: NSEvent.ModifierFlags) -> String { var key = key var modifiers = modifiers if let uScalar = key.first?.unicodeScalars.first, NSCharacterSet.uppercaseLetters.contains(uScalar) { modifiers.insert(.shift) } key = key.uppercased() return modifierSymbols.map { modifiers.contains($0.0) ? $0.1 : "" } .joined() .appending(key) } } fileprivate let NSEventKeyCodeMapping: [Int: String] = [ kVK_F1: "F1", kVK_F2: "F2", kVK_F3: "F3", kVK_F4: "F4", kVK_F5: "F5", kVK_F6: "F6", kVK_F7: "F7", kVK_F8: "F8", kVK_F9: "F9", kVK_F10: "F10", kVK_F11: "F11", kVK_F12: "F12", kVK_F13: "F13", kVK_F14: "F14", kVK_F15: "F15", kVK_F16: "F16", kVK_F17: "F17", kVK_F18: "F18", kVK_F19: "F19", kVK_Space: "␣", kVK_Escape: "⎋", kVK_Delete: "⌦", kVK_ForwardDelete: "⌫", kVK_LeftArrow: "←", kVK_RightArrow: "→", kVK_UpArrow: "↑", kVK_DownArrow: "↓", kVK_Help: "", kVK_PageUp: "⇞", kVK_PageDown: "⇟", kVK_Tab: "⇥", kVK_Return: "⏎", kVK_ANSI_Keypad0: "0", kVK_ANSI_Keypad1: "1", kVK_ANSI_Keypad2: "2", kVK_ANSI_Keypad3: "3", kVK_ANSI_Keypad4: "4", kVK_ANSI_Keypad5: "5", kVK_ANSI_Keypad6: "6", kVK_ANSI_Keypad7: "7", kVK_ANSI_Keypad8: "8", kVK_ANSI_Keypad9: "9", kVK_ANSI_KeypadDecimal: ".", kVK_ANSI_KeypadMultiply: "*", kVK_ANSI_KeypadPlus: "+", kVK_ANSI_KeypadClear: "Clear", kVK_ANSI_KeypadDivide: "/", kVK_ANSI_KeypadEnter: "↩︎", kVK_ANSI_KeypadMinus: "-", kVK_ANSI_KeypadEquals: "=" ] extension NSEvent { var readableKeyDescription: (String, String) { get { let rawKeyCharacter: String if let char = NSEventKeyCodeMapping[Int(self.keyCode)] { rawKeyCharacter = char } else { let inputSource = TISCopyCurrentASCIICapableKeyboardLayoutInputSource().takeUnretainedValue() if let layoutData = TISGetInputSourceProperty(inputSource, kTISPropertyUnicodeKeyLayoutData) { let dataRef = unsafeBitCast(layoutData, to: CFData.self) let keyLayout = unsafeBitCast(CFDataGetBytePtr(dataRef), to: UnsafePointer<UCKeyboardLayout>.self) var deadKeyState = UInt32(0) let maxLength = 4 var actualLength = 0 var actualString = [UniChar](repeating: 0, count: maxLength) let error = UCKeyTranslate(keyLayout, UInt16(self.keyCode), UInt16(kUCKeyActionDisplay), UInt32((0 >> 8) & 0xFF), UInt32(LMGetKbdType()), OptionBits(kUCKeyTranslateNoDeadKeysBit), &deadKeyState, maxLength, &actualLength, &actualString) if error == 0 { rawKeyCharacter = String(utf16CodeUnits: &actualString, count: maxLength).uppercased() } else { rawKeyCharacter = KeyCodeHelper.keyMap[self.keyCode]?.0 ?? "" } } else { rawKeyCharacter = KeyCodeHelper.keyMap[self.keyCode]?.0 ?? "" } } return (([(.control, "⌃"), (.option, "⌥"), (.shift, "⇧"), (.command, "⌘")] as [(NSEvent.ModifierFlags, String)]) .map { self.modifierFlags.contains($0.0) ? $0.1 : "" } .joined() .appending(rawKeyCharacter), rawKeyCharacter) } } }
2d3ea0bb173578d4a84757505e8c944c
25.947494
146
0.503853
false
false
false
false
yoonhg84/ModalPresenter
refs/heads/master
RxModalityStack/Transition/ModalityTransition.swift
mit
1
// // Created by Chope on 2018. 3. 15.. // Copyright (c) 2018 Chope Industry. All rights reserved. // import UIKit public enum ModalityTransition: Equatable { case ignore case system case slide(Direction) case nothing case delegate(UIViewControllerTransitioningDelegate?) public static func ==(lhs: ModalityTransition, rhs: ModalityTransition) -> Bool { switch (lhs, rhs) { case (.ignore, .ignore), (.system, .system), (.nothing, .nothing): return true case (.slide(let lhsValue), .slide(let rhsValue)): return lhsValue == rhsValue case (.delegate(let lhsValue), .delegate(let rhsValue)): guard let lhsValue = lhsValue else { return rhsValue == nil } guard let rhsValue = rhsValue else { return false } return lhsValue.isEqual(rhsValue) default: return false } } } extension ModalityTransition { func toDelegate() -> UIViewControllerTransitioningDelegate? { switch self { case .ignore: return nil case .system: return nil case .slide(let direction): return BaseViewControllerTransition(transitionAnimatable: SlideTransition(direction: direction)) case .nothing: return BaseViewControllerTransition(transitionAnimatable: NothingTransition()) case .delegate(let delegate): return delegate } } }
42bdbe900405360ddc5e5d0fc7f39c4b
28.826923
108
0.5951
false
false
false
false
JGiola/swift
refs/heads/main
test/SILOptimizer/inline_self.swift
apache-2.0
5
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -O -emit-sil -primary-file %s | %FileCheck %s // // This is a .swift test because the SIL parser does not support Self. // Do not inline C.factory into main. Doing so would lose the ability // to materialize local Self metadata. class C { required init() {} } class SubC : C {} var g: AnyObject = SubC() @inline(never) func gen<R>() -> R { return g as! R } extension C { @inline(__always) class func factory(_ z: Int) -> Self { return gen() } } // Call the function so it can be inlined. var x = C() var x2 = C.factory(1) @inline(never) func callIt(fn: () -> ()) { fn() } protocol Use { func use<T>(_ t: T) } var user: Use? = nil class BaseZ { final func baseCapturesSelf() -> Self { let fn = { [weak self] in _ = self } callIt(fn: fn) return self } } // Do not inline C.capturesSelf() into main either. Doing so would lose the ability // to materialize local Self metadata. class Z : BaseZ { @inline(__always) final func capturesSelf() -> Self { let fn = { [weak self] in _ = self } callIt(fn: fn) user?.use(self) return self } // Inline captureSelf into callCaptureSelf, // because their respective Self types refer to the same type. final func callCapturesSelf() -> Self { return capturesSelf() } final func callBaseCapturesSelf() -> Self { return baseCapturesSelf() } } _ = Z().capturesSelf() // CHECK-LABEL: sil {{.*}}@main : $@convention(c) // CHECK: function_ref static inline_self.C.factory(Swift.Int) -> Self // CHECK: [[F:%[0-9]+]] = function_ref @$s11inline_self1CC7factory{{[_0-9a-zA-Z]*}}FZ : $@convention(method) (Int, @thick C.Type) -> @owned C // CHECK: apply [[F]](%{{.+}}, %{{.+}}) : $@convention(method) (Int, @thick C.Type) -> @owned C // CHECK: [[Z:%.*]] = alloc_ref $Z // CHECK: function_ref inline_self.Z.capturesSelf() -> Self // CHECK: [[F:%[0-9]+]] = function_ref @$s11inline_self1ZC12capturesSelfACXDyF : $@convention(method) (@guaranteed Z) -> @owned Z // CHECK: apply [[F]]([[Z]]) : $@convention(method) (@guaranteed Z) -> @owned // CHECK: return // CHECK-LABEL: sil hidden @$s11inline_self1ZC16callCapturesSelfACXDyF : $@convention(method) // CHECK-NOT: function_ref @$s11inline_self1ZC12capturesSelfACXDyF : // CHECK: } // CHECK-LABEL: sil hidden {{.*}}@$s11inline_self1ZC20callBaseCapturesSelfACXDyF // CHECK-NOT: function_ref @$s11inline_self5BaseZC16baseCapturesSelfACXDyF : // CHECK: }
9c56b6cf1c7d0907a5320ce9accf595a
26.175824
141
0.64537
false
false
false
false
Visual-Engineering/HiringApp
refs/heads/master
HiringApp/HiringAppCore/RealmModels/TechnologyRealm.swift
apache-2.0
1
// // TechnologyRealm.swift // Pods // // Created by Alba Luján on 26/6/17. // // import Foundation import RealmSwift public class TechnologyRealm: Object { dynamic var id = 0 dynamic var title = "" dynamic var imageURL = "" dynamic var testAvailable = false dynamic var submittedTest: Test? } public class Test: Object { dynamic var status = "" } extension TechnologyRealm { var toModel: TechnologyModel { var submittedTest: [String: String]? = [String: String]() if let status = self.submittedTest?.status { submittedTest!["status"] = status } else { submittedTest = nil } return TechnologyModel(id: self.id, title: self.title, imageURL: self.imageURL, testAvailable: self.testAvailable, submittedTest: submittedTest) } } extension TechnologyModel { var toRealmModel: TechnologyRealm { let techRealm = TechnologyRealm() techRealm.id = self.id techRealm.title = self.title techRealm.imageURL = self.imageURL techRealm.testAvailable = self.testAvailable if let status = self.submittedTest?["status"] { let test = Test() test.status = status techRealm.submittedTest = test } techRealm.submittedTest = nil return techRealm } }
2ff956c32d2e1b69490d0523ec6e26dc
25.52
152
0.644042
false
true
false
false
mpiannucci/HackWinds-iOS
refs/heads/master
HackWindsOSXToday/TodayViewController.swift
mit
1
// // TodayViewController.swift // HackWindsOSXToday // // Created by Matthew Iannucci on 10/23/16. // Copyright © 2016 Rhodysurf Development. All rights reserved. // import Cocoa import NotificationCenter class TodayViewController: NSViewController, NCWidgetProviding { @IBOutlet weak var latestBuoyLabel: NSTextField! @IBOutlet weak var buoyLocationLabel: NSTextField! @IBOutlet weak var upcomingTideLabel: NSTextField! let updateManager: WidgetUpdateManager = WidgetUpdateManager() override var nibName: String? { return "TodayViewController" } override func viewDidLoad() { updateBuoyUI() updateTideUI() updateManager.fetchBuoyUpdate { (Void) -> Void in DispatchQueue.main.async(execute: { self.updateBuoyUI() }) } updateManager.fetchTideUpdate { (Void) -> Void in DispatchQueue.main.async(execute: { self.updateTideUI() }) } } private func widgetPerformUpdate(completionHandler: ((NCUpdateResult) -> Void)) { // Update your data and prepare for a snapshot. Call completion handler when you are done // with NoData if nothing has changed or NewData if there is new data since the last // time we called you updateManager.fetchBuoyUpdate { (Void) -> Void in DispatchQueue.main.async(execute: { self.updateBuoyUI() }) } updateManager.fetchTideUpdate { (Void) -> Void in DispatchQueue.main.async(execute: { self.updateTideUI() }) } completionHandler(.noData) } func updateBuoyUI() { if let buoy = self.updateManager.latestBuoy { self.latestBuoyLabel.stringValue = buoy.waveSummary?.getSwellSummmary() ?? "" } if let location = self.updateManager.buoyLocation { self.buoyLocationLabel.stringValue = location as String } } func updateTideUI () { if let tide = self.updateManager.nextTide { self.upcomingTideLabel.stringValue = tide.getEventSummary() } } }
abcdbcb3bf4ab6392d7b6454ef93723c
28.441558
97
0.603441
false
false
false
false
wangweicheng7/ClouldFisher
refs/heads/master
Carthage/Checkouts/pull-to-refresh/Sources/ESPullToRefresh.swift
mit
2
// // ESPullToRefresh.swift // // Created by egg swift on 16/4/7. // Copyright (c) 2013-2016 ESPullToRefresh (https://github.com/eggswift/pull-to-refresh) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import UIKit private var kESRefreshHeaderKey: Void? private var kESRefreshFooterKey: Void? public extension UIScrollView { /// Pull-to-refresh associated property public var header: ESRefreshHeaderView? { get { return (objc_getAssociatedObject(self, &kESRefreshHeaderKey) as? ESRefreshHeaderView) } set(newValue) { objc_setAssociatedObject(self, &kESRefreshHeaderKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } /// Infinitiy scroll associated property public var footer: ESRefreshFooterView? { get { return (objc_getAssociatedObject(self, &kESRefreshFooterKey) as? ESRefreshFooterView) } set(newValue) { objc_setAssociatedObject(self, &kESRefreshFooterKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } } public extension ES where Base: UIScrollView { /// Add pull-to-refresh @discardableResult public func addPullToRefresh(handler: @escaping ESRefreshHandler) -> ESRefreshHeaderView { removeRefreshHeader() let header = ESRefreshHeaderView(frame: CGRect.zero, handler: handler) let headerH = header.animator.executeIncremental header.frame = CGRect.init(x: 0.0, y: -headerH /* - contentInset.top */, width: self.base.bounds.size.width, height: headerH) self.base.addSubview(header) self.base.header = header return header } @discardableResult public func addPullToRefresh(animator: ESRefreshProtocol & ESRefreshAnimatorProtocol, handler: @escaping ESRefreshHandler) -> ESRefreshHeaderView { removeRefreshHeader() let header = ESRefreshHeaderView(frame: CGRect.zero, handler: handler, animator: animator) let headerH = animator.executeIncremental header.frame = CGRect.init(x: 0.0, y: -headerH /* - contentInset.top */, width: self.base.bounds.size.width, height: headerH) self.base.addSubview(header) self.base.header = header return header } /// Add infinite-scrolling @discardableResult public func addInfiniteScrolling(handler: @escaping ESRefreshHandler) -> ESRefreshFooterView { removeRefreshFooter() let footer = ESRefreshFooterView(frame: CGRect.zero, handler: handler) let footerH = footer.animator.executeIncremental footer.frame = CGRect.init(x: 0.0, y: self.base.contentSize.height + self.base.contentInset.bottom, width: self.base.bounds.size.width, height: footerH) self.base.addSubview(footer) self.base.footer = footer return footer } @discardableResult public func addInfiniteScrolling(animator: ESRefreshProtocol & ESRefreshAnimatorProtocol, handler: @escaping ESRefreshHandler) -> ESRefreshFooterView { removeRefreshFooter() let footer = ESRefreshFooterView(frame: CGRect.zero, handler: handler, animator: animator) let footerH = footer.animator.executeIncremental footer.frame = CGRect.init(x: 0.0, y: self.base.contentSize.height + self.base.contentInset.bottom, width: self.base.bounds.size.width, height: footerH) self.base.footer = footer self.base.addSubview(footer) return footer } /// Remove public func removeRefreshHeader() { self.base.header?.stopRefreshing() self.base.header?.removeFromSuperview() self.base.header = nil } public func removeRefreshFooter() { self.base.footer?.stopRefreshing() self.base.footer?.removeFromSuperview() self.base.footer = nil } /// Manual refresh public func startPullToRefresh() { DispatchQueue.main.async { [weak base] in base?.header?.startRefreshing(isAuto: false) } } /// Auto refresh if expired. public func autoPullToRefresh() { if self.base.expired == true { DispatchQueue.main.async { [weak base] in base?.header?.startRefreshing(isAuto: true) } } } /// Stop pull to refresh public func stopPullToRefresh(ignoreDate: Bool = false, ignoreFooter: Bool = false) { self.base.header?.stopRefreshing() if ignoreDate == false { if let key = self.base.header?.refreshIdentifier { ESRefreshDataManager.sharedManager.setDate(Date(), forKey: key) } self.base.footer?.resetNoMoreData() } self.base.footer?.isHidden = ignoreFooter } /// Footer notice method public func noticeNoMoreData() { self.base.footer?.stopRefreshing() self.base.footer?.noMoreData = true } public func resetNoMoreData() { self.base.footer?.noMoreData = false } public func stopLoadingMore() { self.base.footer?.stopRefreshing() } } public extension UIScrollView /* Date Manager */ { /// Identifier for cache expired timeinterval and last refresh date. public var refreshIdentifier: String? { get { return self.header?.refreshIdentifier } set { self.header?.refreshIdentifier = newValue } } /// If you setted refreshIdentifier and expiredTimeInterval, return nearest refresh expired or not. Default is false. public var expired: Bool { get { if let key = self.header?.refreshIdentifier { return ESRefreshDataManager.sharedManager.isExpired(forKey: key) } return false } } public var expiredTimeInterval: TimeInterval? { get { if let key = self.header?.refreshIdentifier { let interval = ESRefreshDataManager.sharedManager.expiredTimeInterval(forKey: key) return interval } return nil } set { if let key = self.header?.refreshIdentifier { ESRefreshDataManager.sharedManager.setExpiredTimeInterval(newValue, forKey: key) } } } /// Auto cached last refresh date when you setted refreshIdentifier. public var lastRefreshDate: Date? { get { if let key = self.header?.refreshIdentifier { return ESRefreshDataManager.sharedManager.date(forKey: key) } return nil } } } open class ESRefreshHeaderView: ESRefreshComponent { fileprivate var previousOffset: CGFloat = 0.0 fileprivate var scrollViewInsets: UIEdgeInsets = UIEdgeInsets.zero fileprivate var scrollViewBounces: Bool = true open var lastRefreshTimestamp: TimeInterval? open var refreshIdentifier: String? public convenience init(frame: CGRect, handler: @escaping ESRefreshHandler) { self.init(frame: frame) self.handler = handler self.animator = ESRefreshHeaderAnimator.init() } open override func didMoveToSuperview() { super.didMoveToSuperview() DispatchQueue.main.async { [weak self] in self?.scrollViewBounces = self?.scrollView?.bounces ?? true self?.scrollViewInsets = self?.scrollView?.contentInset ?? UIEdgeInsets.zero } } open override func offsetChangeAction(object: AnyObject?, change: [NSKeyValueChangeKey : Any]?) { guard let scrollView = scrollView else { return } super.offsetChangeAction(object: object, change: change) guard self.isRefreshing == false && self.isAutoRefreshing == false else { let top = scrollViewInsets.top let offsetY = scrollView.contentOffset.y let height = self.frame.size.height var scrollingTop = (-offsetY > top) ? -offsetY : top scrollingTop = (scrollingTop > height + top) ? (height + top) : scrollingTop scrollView.contentInset.top = scrollingTop return } // Check needs re-set animator's progress or not. var isRecordingProgress = false defer { if isRecordingProgress == true { let percent = -(previousOffset + scrollViewInsets.top) / self.animator.trigger self.animator.refresh(view: self, progressDidChange: percent) } } let offsets = previousOffset + scrollViewInsets.top if offsets < -self.animator.trigger { // Reached critical if isRefreshing == false && isAutoRefreshing == false { if scrollView.isDragging == false { // Start to refresh... self.startRefreshing(isAuto: false) self.animator.refresh(view: self, stateDidChange: .refreshing) } else { // Release to refresh! Please drop down hard... self.animator.refresh(view: self, stateDidChange: .releaseToRefresh) isRecordingProgress = true } } } else if offsets < 0 { // Pull to refresh! if isRefreshing == false && isAutoRefreshing == false { self.animator.refresh(view: self, stateDidChange: .pullToRefresh) isRecordingProgress = true } } else { // Normal state } previousOffset = scrollView.contentOffset.y } open override func start() { guard let scrollView = scrollView else { return } // ignore observer self.ignoreObserver(true) // stop scroll view bounces for animation scrollView.bounces = false // call super start super.start() self.animator.refreshAnimationBegin(view: self) // 缓存scrollview当前的contentInset, 并根据animator的executeIncremental属性计算刷新时所需要的contentInset,它将在接下来的动画中应用。 // Tips: 这里将self.scrollViewInsets.top更新,也可以将scrollViewInsets整个更新,因为left、right、bottom属性都没有用到,如果接下来的迭代需要使用这三个属性的话,这里可能需要额外的处理。 var insets = scrollView.contentInset self.scrollViewInsets.top = insets.top insets.top += animator.executeIncremental // We need to restore previous offset because we will animate scroll view insets and regular scroll view animating is not applied then. scrollView.contentInset = insets scrollView.contentOffset.y = previousOffset previousOffset -= animator.executeIncremental UIView.animate(withDuration: 0.2, delay: 0.0, options: .curveLinear, animations: { scrollView.contentOffset.y = -insets.top }, completion: { (finished) in self.handler?() // un-ignore observer self.ignoreObserver(false) scrollView.bounces = self.scrollViewBounces }) } open override func stop() { guard let scrollView = scrollView else { return } // ignore observer self.ignoreObserver(true) self.animator.refreshAnimationEnd(view: self) // Back state scrollView.contentInset.top = self.scrollViewInsets.top scrollView.contentOffset.y = self.scrollViewInsets.top + self.previousOffset UIView.animate(withDuration: 0.2, delay: 0, options: .curveLinear, animations: { scrollView.contentOffset.y = -self.scrollViewInsets.top }, completion: { (finished) in self.animator.refresh(view: self, stateDidChange: .pullToRefresh) super.stop() scrollView.contentInset.top = self.scrollViewInsets.top self.previousOffset = scrollView.contentOffset.y // un-ignore observer self.ignoreObserver(false) }) } } open class ESRefreshFooterView: ESRefreshComponent { fileprivate var scrollViewInsets: UIEdgeInsets = UIEdgeInsets.zero open var noMoreData = false { didSet { if noMoreData != oldValue { self.animator.refresh(view: self, stateDidChange: noMoreData ? .noMoreData : .pullToRefresh) } } } open override var isHidden: Bool { didSet { if isHidden == true { scrollView?.contentInset.bottom = scrollViewInsets.bottom var rect = self.frame rect.origin.y = scrollView?.contentSize.height ?? 0.0 self.frame = rect } else { scrollView?.contentInset.bottom = scrollViewInsets.bottom + animator.executeIncremental var rect = self.frame rect.origin.y = scrollView?.contentSize.height ?? 0.0 self.frame = rect } } } public convenience init(frame: CGRect, handler: @escaping ESRefreshHandler) { self.init(frame: frame) self.handler = handler self.animator = ESRefreshFooterAnimator.init() } /** In didMoveToSuperview, it will cache superview(UIScrollView)'s contentInset and update self's frame. It called ESRefreshComponent's didMoveToSuperview. */ open override func didMoveToSuperview() { super.didMoveToSuperview() DispatchQueue.main.async { [weak self] in self?.scrollViewInsets = self?.scrollView?.contentInset ?? UIEdgeInsets.zero self?.scrollView?.contentInset.bottom = (self?.scrollViewInsets.bottom ?? 0) + (self?.bounds.size.height ?? 0) var rect = self?.frame ?? CGRect.zero rect.origin.y = self?.scrollView?.contentSize.height ?? 0.0 self?.frame = rect } } open override func sizeChangeAction(object: AnyObject?, change: [NSKeyValueChangeKey : Any]?) { guard let scrollView = scrollView else { return } super.sizeChangeAction(object: object, change: change) let targetY = scrollView.contentSize.height + scrollViewInsets.bottom if self.frame.origin.y != targetY { var rect = self.frame rect.origin.y = targetY self.frame = rect } } open override func offsetChangeAction(object: AnyObject?, change: [NSKeyValueChangeKey : Any]?) { guard let scrollView = scrollView else { return } super.offsetChangeAction(object: object, change: change) guard isRefreshing == false && isAutoRefreshing == false && noMoreData == false && isHidden == false else { // 正在loading more或者内容为空时不相应变化 return } if scrollView.contentSize.height <= 0.0 || scrollView.contentOffset.y + scrollView.contentInset.top <= 0.0 { self.alpha = 0.0 return } else { self.alpha = 1.0 } if scrollView.contentSize.height + scrollView.contentInset.top > scrollView.bounds.size.height { // 内容超过一个屏幕 计算公式,判断是不是在拖在到了底部 if scrollView.contentSize.height - scrollView.contentOffset.y + scrollView.contentInset.bottom <= scrollView.bounds.size.height { self.animator.refresh(view: self, stateDidChange: .refreshing) self.startRefreshing() } } else { //内容没有超过一个屏幕,这时拖拽高度大于1/2footer的高度就表示请求上拉 if scrollView.contentOffset.y + scrollView.contentInset.top >= animator.trigger / 2.0 { self.animator.refresh(view: self, stateDidChange: .refreshing) self.startRefreshing() } } } open override func start() { guard let scrollView = scrollView else { return } super.start() self.animator.refreshAnimationBegin(view: self) let x = scrollView.contentOffset.x let y = max(0.0, scrollView.contentSize.height - scrollView.bounds.size.height + scrollView.contentInset.bottom) // Call handler UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveLinear, animations: { scrollView.contentOffset = CGPoint.init(x: x, y: y) }, completion: { (animated) in self.handler?() }) } open override func stop() { guard let scrollView = scrollView else { return } self.animator.refreshAnimationEnd(view: self) // Back state UIView.animate(withDuration: 0.3, delay: 0, options: .curveLinear, animations: { }, completion: { (finished) in if self.noMoreData == false { self.animator.refresh(view: self, stateDidChange: .pullToRefresh) } super.stop() }) // Stop deceleration of UIScrollView. When the button tap event is caught, you read what the [scrollView contentOffset].x is, and set the offset to this value with animation OFF. // http://stackoverflow.com/questions/2037892/stop-deceleration-of-uiscrollview if scrollView.isDecelerating { var contentOffset = scrollView.contentOffset contentOffset.y = min(contentOffset.y, scrollView.contentSize.height - scrollView.frame.size.height) if contentOffset.y < 0.0 { contentOffset.y = 0.0 UIView.animate(withDuration: 0.1, animations: { scrollView.setContentOffset(contentOffset, animated: false) }) } else { scrollView.setContentOffset(contentOffset, animated: false) } } } /// Change to no-more-data status. open func noticeNoMoreData() { self.noMoreData = true } /// Reset no-more-data status. open func resetNoMoreData() { self.noMoreData = false } }
a7a2508e00dc6f0b36a03e9147e23cab
37.631048
186
0.622984
false
false
false
false
pekoto/fightydot
refs/heads/master
FightyDot/FightyDot/Mill.swift
mit
1
// // Mill.swift // FightyDot // // Created by Graham McRobbie on 12/12/2016. // Copyright © 2016 Graham McRobbie. All rights reserved. // // A mill is made of an array of three nodes. // It also stores the piece counts in another array (_pieceCounts) // This keeps things fast and makes the mill easy to update. // import Foundation import UIKit class Mill { private var _id: Int private var _pieceCounts = Array(repeating: 0, count: 3) private var _nodes: [Unowned<Node>] = [] private var _colour: PieceColour = PieceColour.none { didSet { if(_colour == .none) { _view?.reset(mill: self) } else { _view?.animate(mill: self, to: _colour) } } } weak private var _view: EngineDelegate? var id: Int { get { return _id } } var nodes: [Unowned<Node>] { get { return _nodes } set { _nodes = newValue } } var colour: PieceColour { get { return _colour } } init(id: Int, view: EngineDelegate?) { _id = id _pieceCounts[PieceColour.none.rawValue] = Constants.GameplayNumbers.piecesInMill _view = view } func reset() { _colour = PieceColour.none _pieceCounts[PieceColour.none.rawValue] = Constants.GameplayNumbers.piecesInMill _pieceCounts[PieceColour.green.rawValue] = 0 _pieceCounts[PieceColour.red.rawValue] = 0 } // Returns true if a mill is formed func updatePieceCounts(oldColour: PieceColour, newColour: PieceColour) -> Bool { _pieceCounts[oldColour.rawValue] -= 1 _pieceCounts[newColour.rawValue] += 1 let newColour = getColourFromPieceCounts() if(_colour != newColour) { // If the updated colour is .none > the mill was broken, else it was formed let millFormed = newColour != PieceColour.none for node in nodes { if(millFormed) { node.value.incrementActiveMillCount() } else { node.value.decrementActiveMillCount() } } _colour = newColour return millFormed } return false } func copyValues(from otherMill: Mill) { _pieceCounts = otherMill._pieceCounts _colour = otherMill._colour } // MARK: - Heuristic evaluation functions // A mill with 2 pieces of the same colour, and an empty piece next // to an active mill, allowing the player to move a node between mills. func isInDoubleMillConfiguration(for colour: PieceColour) -> Bool { if(!isInTwoPieceConfiguration(for: colour)) { return false } let emptyNode = _nodes.filter{ node in node.value.colour == .none}.first for neighbour in (emptyNode?.value.neighbours)! { if(neighbour.value.inActiveMill && neighbour.value.colour == colour) { return true } } return false } // A mill that has one empty node func isInTwoPieceConfiguration(for colour: PieceColour) -> Bool { return (_pieceCounts[PieceColour.none.rawValue] == 1) && (_pieceCounts[colour.rawValue] == 2) } // A mill that has one empty node, and one of its neighbours if of the same colour, // so the player can close the mill next turn func isOpen(for colour: PieceColour) -> Bool { if(!isInTwoPieceConfiguration(for: colour)) { return false } let emptyNode = _nodes.filter{ node in node.value.colour == .none}.first for neighbour in (emptyNode?.value.neighbours)! { // Check neighbour is not in the mill we're checking if _nodes.contains(where: {node in node.value.id == neighbour.value.id}) { continue } if(neighbour.value.colour == colour) { return true } } return false } func intersects(with otherMill: Mill) -> Bool { for node in _nodes { for otherNode in otherMill.nodes { if(node.value.id == otherNode.value.id) { return true } } } return false } // MARK: - Private functions // Once a mill has 3 pieces of a certain colour, the colour of the mill changes private func getColourFromPieceCounts() -> PieceColour{ if (_pieceCounts[PieceColour.green.rawValue] == Constants.GameplayNumbers.piecesInMill) { return PieceColour.green } else if (_pieceCounts[PieceColour.red.rawValue] == Constants.GameplayNumbers.piecesInMill){ return PieceColour.red } else { return PieceColour.none } } }
969c26b9e87b44b80f02e5764fc747df
28.946746
101
0.556017
false
false
false
false
younata/X
refs/heads/master
X/EdgeInsets.swift
mit
1
// // EdgeInsets.swift // X // // Created by Sam Soffes on 5/8/15. // Copyright (c) 2015 Sam Soffes. All rights reserved. // #if os(iOS) import UIKit public typealias EdgeInsets = UIEdgeInsets #else import AppKit public typealias EdgeInsets = NSEdgeInsets #endif public let EdgeInsetsZero = EdgeInsets(top: 0, left: 0, bottom: 0, right: 0) extension EdgeInsets { public static var zeroInsets: EdgeInsets { return EdgeInsetsZero } public var flipped: EdgeInsets { var insets = self insets.top = bottom insets.bottom = top return insets } public func insetRect(rect: CGRect) -> CGRect { #if os(iOS) return UIEdgeInsetsInsetRect(rect, self) #else if (top + bottom > rect.size.height) || (left + right > rect.size.width) { return CGRectNull } var insetRect = rect insetRect.origin.x += left insetRect.origin.y += top; insetRect.size.height -= top + bottom insetRect.size.width -= left + right return insetRect #endif } }
d86bb6cfda1af30959a36d0ca5d9daf1
19.122449
77
0.686613
false
false
false
false
borglab/SwiftFusion
refs/heads/main
Sources/SwiftFusion/Inference/FlattenedScalars.swift
apache-2.0
1
// TODO: Move all these to Penguin. import _Differentiation import PenguinStructures public struct FlattenedScalars<Base: MutableCollection> where Base.Element: Vector { var base: Base init(_ base: Base) { self.base = base } } extension FlattenedScalars: Sequence { public typealias Element = Base.Element.Scalars.Element public struct Iterator: IteratorProtocol { var outer: Base.Iterator var inner: Base.Element.Scalars.Iterator? init(outer: Base.Iterator, inner: Base.Element.Scalars.Iterator? = nil) { self.outer = outer self.inner = inner } public mutating func next() -> Element? { while true { if let r = inner?.next() { return r } guard let o = outer.next() else { return nil } inner = o.scalars.makeIterator() } } } public func makeIterator() -> Iterator { Iterator(outer: base.makeIterator()) } // https://bugs.swift.org/browse/SR-13486 points out that the withContiguousStorageIfAvailable // method is dangerously underspecified, so we don't implement it here. public func _customContainsEquatableElement(_ e: Element) -> Bool? { let m = base.lazy.map({ $0.scalars._customContainsEquatableElement(e) }) if let x = m.first(where: { $0 != false }) { return x } return false } public __consuming func _copyContents( initializing t: UnsafeMutableBufferPointer<Element> ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) { var r = 0 var outer = base.makeIterator() while r < t.count, let e = outer.next() { var (inner, r1) = e.scalars._copyContents( initializing: .init(start: t.baseAddress.map { $0 + r }, count: t.count - r)) r += r1 // See if we ran out of target space before reaching the end of the inner collection. I think // this will be rare, so instead of using an O(N) `e.count` and comparing with `r1` in all // passes of the outer loop, spend `inner` seeing if we reached the end and reconstitute it in // O(N) if not. if inner.next() != nil { @inline(never) func earlyExit() -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) { var i = e.scalars.makeIterator() for _ in 0..<r1 { _ = i.next() } return (.init(outer: outer, inner: i), r) } return earlyExit() } } return (.init(outer: outer, inner: nil), r) } } extension FlattenedScalars: MutableCollection { public typealias Index = FlattenedIndex<Base.Index, Base.Element.Scalars.Index> public var startIndex: Index { .init(firstValidIn: base, innerCollection: \.scalars) } public var endIndex: Index { .init(endIn: base) } public func index(after x: Index) -> Index { .init(nextAfter: x, in: base, innerCollection: \.scalars) } public func formIndex(after x: inout Index) { x.formNextValid(in: base, innerCollection: \.scalars) } public subscript(i: Index) -> Element { get { base[i.outer].scalars[i.inner!] } set { base[i.outer].scalars[i.inner!] = newValue } _modify { yield &base[i.outer].scalars[i.inner!] } } public var isEmpty: Bool { base.allSatisfy { $0.scalars.isEmpty } } public var count: Int { base.lazy.map(\.scalars.count).reduce(0, +) } /* TODO: implement or discard func _customIndexOfEquatableElement(_ element: Element) -> Index?? { } func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? { } /// Returns an index that is the specified distance from the given index. func index(_ i: Index, offsetBy distance: Int) -> Index { } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { vtable[0].indexOffsetByLimitedBy(self, i, distance, limit) } /// Returns the distance between two indices. func distance(from start: Index, to end: Index) -> Int { vtable[0].distance(self, start, end) } // https://bugs.swift.org/browse/SR-13486 points out that these two // methods are dangerously underspecified, so we don't implement them here. public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { } public mutating func withContiguousMutableStorageIfAvailable<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { } /// Reorders the elements of the collection such that all the elements /// that match the given predicate are after all the elements that don't /// match. /// /// - Complexity: O(*n*), where *n* is the length of the collection. public mutating func partition( by belongsInSecondPartition: (Element) throws -> Bool ) rethrows -> Index { } /// Exchanges the values at the specified indices of the collection. public mutating func swapAt(_ i: Index, _ j: Index) { } */ }
eac5b0638ca8a1d9076e3fcf5bbf1835
31.619355
100
0.660601
false
false
false
false
Rag0n/QuNotes
refs/heads/master
Carthage/Checkouts/WSTagsField/Source/WSTag.swift
gpl-3.0
1
// // WSTag.swift // Whitesmith // // Created by Ricardo Pereira on 12/05/16. // Copyright © 2016 Whitesmith. All rights reserved. // import Foundation public struct WSTag: Hashable { public let text: String public init(_ text: String) { self.text = text } public var hashValue: Int { return self.text.hashValue } public func equals(_ other: WSTag) -> Bool { return self.text == other.text } } public func ==(lhs: WSTag, rhs: WSTag) -> Bool { return lhs.equals(rhs) }
5dc5280bbb0c7ba5ccc2d477d4db4244
16.290323
53
0.61194
false
false
false
false
exchangegroup/MprHttp
refs/heads/master
MprHttp/TegHttpRequestIdentity.swift
mit
2
// // Describes an HTTP request: url, HTTP method, body data etc. // import Foundation public struct TegHttpRequestIdentity { public let url: String public let method: TegHttpMethod public let requestBody: NSData? public let contentType: TegHttpContentType public let httpHeaders: [TegHttpHeader] public let mockedResponse: String? /// An optional logger function that will be called during request and response public var logger: TegHttpLoggerCallback? public init(url: String, method: TegHttpMethod, requestBody: NSData?, contentType: TegHttpContentType, httpHeaders: [TegHttpHeader], mockedResponse: String?) { self.url = url self.method = method self.requestBody = requestBody self.contentType = contentType self.httpHeaders = httpHeaders self.mockedResponse = mockedResponse } public init(url: String) { self.url = url method = TegHttpMethod.Get requestBody = nil contentType = TegHttpContentType.Unspecified httpHeaders = [] self.mockedResponse = nil } public init(identityToCopy: TegHttpRequestIdentity, httpHeaders: [TegHttpHeader]) { url = identityToCopy.url method = identityToCopy.method requestBody = identityToCopy.requestBody contentType = identityToCopy.contentType mockedResponse = identityToCopy.mockedResponse logger = identityToCopy.logger self.httpHeaders = httpHeaders } public var nsUrl: NSURL? { return NSURL(string: url) } public var urlRequest: NSURLRequest { let request = NSMutableURLRequest() request.URL = nsUrl request.HTTPMethod = method.rawValue request.HTTPBody = requestBody if contentType != TegHttpContentType.Unspecified { request.addValue(contentType.rawValue, forHTTPHeaderField: "Content-Type") } for httpHeader in httpHeaders { request.addValue(httpHeader.value, forHTTPHeaderField: httpHeader.field) } return request } }
c5615172c837ac50434ea2805995306e
26.068493
85
0.723178
false
false
false
false
attackFromCat/LivingTVDemo
refs/heads/master
LivingTVDemo/LivingTVDemo/Classes/Home/Controller/AmuseViewController.swift
mit
1
// // AmuseViewController.swift // LivingTVDemo // // Created by 李翔 on 2017/1/9. // Copyright © 2017年 Lee Xiang. All rights reserved. // import UIKit fileprivate let kMenuViewH : CGFloat = 200 class AmuseViewController: BaseAnchorViewController { // MARK: 懒加载属性 fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel() fileprivate lazy var menuView : AmuseMenuView = { let menuView = AmuseMenuView.amuseMenuView() menuView.frame = CGRect(x: 0, y: -kMenuViewH, width: kScreenW, height: kMenuViewH) return menuView }() } // MARK:- 设置UI界面 extension AmuseViewController { override func setupUI() { super.setupUI() // 将菜单的View添加到collectionView中 collectionView.addSubview(menuView) collectionView.contentInset = UIEdgeInsets(top: kMenuViewH, left: 0, bottom: 0, right: 0) } } // MARK:- 请求数据 extension AmuseViewController { override func loadData() { // 1.给父类中ViewModel进行赋值 baseVM = amuseVM // 2.请求数据 amuseVM.loadAmuseData { // 2.1.刷新表格 self.collectionView.reloadData() // 2.2.调整数据 var tempGroups = self.amuseVM.anchorGroups tempGroups.removeFirst() self.menuView.groups = tempGroups // 3.数据请求完成 self.loadDataFinished() } } }
ce97f0819fc71f0c0dd9a2d76d239d48
24.321429
97
0.606488
false
false
false
false
laerador/barista
refs/heads/master
Barista/UI Classes/TimeIntervalSlider.swift
bsd-2-clause
1
// // TimeIntervalSlider.swift // Barista // // Created by Franz Greiling on 26.10.17. // Copyright © 2018 Franz Greiling. All rights reserved. // import Cocoa class TimeIntervalSlider: NSSlider { // MARK: - Initializers required init?(coder: NSCoder) { super.init(coder: coder) } // MARK: Setup override func awakeFromNib() { self.updateLabels() } // MARK: - Accessing the Time Interval Value var timeIntervals: [TimeInterval] = [0.0] { didSet { self.resetValueLimits() self.updateLabels() } } var timeValue: TimeInterval { set(value) { switch value { case 0 where showInfinity: self.doubleValue = self.closestTickMarkValue(toValue: self.maxValue) case let x where x < timeIntervals[0]: self.doubleValue = 0 case let x where x > timeIntervals[timeIntervals.count - 1]: self.doubleValue = Double(timeIntervals.count - 1) default: for i in 0 ..< (timeIntervals.count - 1) { if (value >= timeIntervals[i] && value <= timeIntervals[i+1]) { self.doubleValue = TimeIntervalSlider.mapValue( value, from: (timeIntervals[i], timeIntervals[i + 1]), to: (Double(i), Double(i + 1)) )! } } } } get { let value = self.doubleValue for i in 0 ..< (timeIntervals.count - 1) { if (value >= Double(i) && value <= Double(i+1)) { return TimeIntervalSlider.mapValue( value, from: (Double(i), Double(i + 1)), to: (timeIntervals[i], timeIntervals[i + 1]) )! } } return 0 } } // MARK: - "Never" Interval // TODO: Make Snapping happen @objc var showInfinity: Bool = false { didSet { (self.cell as! TimeIntervalSliderCell).snapToLast = showInfinity self.resetValueLimits() self.updateLabels() } } @objc var infinityLabel: String = "Never" // MARK: - Labels private var labels: [NSTextField] = [] @objc var showLabels: Bool = false { didSet { self.updateLabels() } } var labelForTickMarks: [Int] = [] { didSet { self.updateLabels() } } fileprivate func updateLabels() { while labels.count > 0 { let l = labels.popLast()! l.removeFromSuperview() } if showLabels { for m in self.labelForTickMarks { let text = self.timeIntervals[m].simpleFormat(style: .short)! let label = self.createLabelForTickMark(m, withString: text)! labels.append(label) self.superview?.addSubview(label) } if showInfinity { let label = self.createLabelForTickMark(self.numberOfTickMarks - 1, withString: self.infinityLabel, alignment: NSTextAlignment.left)! labels.append(label) self.superview?.addSubview(label) } } } // MARK: - Helper /// Maps a value from one Interval onto another fileprivate static func mapValue(_ value: Double, from: (Double, Double), to: (Double, Double)) -> Double? { guard value >= from.0 && value <= from.1 else { return nil } let fromRange = from.1 - from.0 let toRange = to.1 - to.0 return (value - from.0) * toRange / fromRange + to.0 } fileprivate func resetValueLimits() { if showInfinity { self.maxValue = Double(self.timeIntervals.count) self.numberOfTickMarks = self.timeIntervals.count + 1 } else { self.maxValue = Double(self.timeIntervals.count) - 1.0 self.numberOfTickMarks = self.timeIntervals.count } } }
7968fa73204e2eab57ecd9944b0c082b
29.869565
149
0.507042
false
false
false
false
JohnPJenkins/swift-t
refs/heads/master
stc/tests/321-arrays-computed-ix-2.swift
apache-2.0
4
// dummy function (int r) array_lookup(int A[], int i) { r = A[i]; } (int A[]) constructArray() { A[0] = 9; A[1] = 8; A[2] = 7; A[3] = 6; A[4] = 5; } (int res[]) replicate(int x) { res[0] = x; res[1] = x; res[2] = x; res[3] = x; res[4] = x; res[5] = x; res[6] = x; res[7] = x; res[8] = x; res[9] = x; } main { int A[]; int B[]; B = constructArray(); trace(A[0]); trace(A[1]); trace(A[2*3-2]); trace(A[B[2]]); trace(array_lookup(A, B[2])); trace(999, A[B[0]]); trace(array_lookup(B, A[B[0]])); A[0] = 2; A[1] = 123; A[1+2] = B[0]; // A[3] = 9 A[2] = 321; A[4] = 321; A[5] = 321; A[6] = 321; A[7] = 321; A[9] = 2; A[A[1]] = 3; // A[123] = 3 A[(2*3+243)*300000] = 100; int i; i = (2*3+243)*300000; trace(A[i]); }
73da3c9fbabe9f68347b0df8353dac9a
14.473684
38
0.385488
false
false
true
false
amezcua/actor-platform
refs/heads/master
actor-apps/app-ios/ActorApp/Controllers/Main/MainTabViewController.swift
mit
7
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation import UIKit import MessageUI class MainTabViewController : UITabBarController { // MARK: - // MARK: Private vars private var appEmptyContainer = UIView() private var appIsSyncingPlaceholder = BigPlaceholderView(topOffset: 44 + 20) private var appIsEmptyPlaceholder = BigPlaceholderView(topOffset: 44 + 20) // MARK: - // MARK: Public vars var centerButton:UIButton? = nil var isInited = false var isAfterLogin = false // MARK: - // MARK: Constructors init(isAfterLogin: Bool) { super.init(nibName: nil, bundle: nil); self.isAfterLogin = isAfterLogin self.preferredContentSize = CGSize(width: 320.0, height: 600.0) self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } required init(coder aDecoder: NSCoder) { fatalError("Not implemented") } // MARK: - override func viewDidLoad() { super.viewDidLoad() appEmptyContainer.hidden = true appIsEmptyPlaceholder.hidden = true appIsEmptyPlaceholder.setImage( UIImage(named: "contacts_list_placeholder"), title: NSLocalizedString("Placeholder_Empty_Title", comment: "Placeholder Title"), subtitle: NSLocalizedString("Placeholder_Empty_Message", comment: "Placeholder Message"), actionTitle: NSLocalizedString("Placeholder_Empty_Action", comment: "Placeholder Action"), subtitle2: NSLocalizedString("Placeholder_Empty_Message2", comment: "Placeholder Message2"), actionTarget: self, actionSelector: Selector("showSmsInvitation"), action2title: NSLocalizedString("Placeholder_Empty_Action2", comment: "Placeholder Action2"), action2Selector: Selector("doAddContact")) appEmptyContainer.addSubview(appIsEmptyPlaceholder) appIsSyncingPlaceholder.hidden = true appIsSyncingPlaceholder.setImage( UIImage(named: "chat_list_placeholder"), title: NSLocalizedString("Placeholder_Loading_Title", comment: "Placeholder Title"), subtitle: NSLocalizedString("Placeholder_Loading_Message", comment: "Placeholder Message")) appEmptyContainer.addSubview(appIsSyncingPlaceholder) view.addSubview(appEmptyContainer) view.backgroundColor = UIColor.whiteColor() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if (!isInited) { if (Actor.isLoggedIn()) { isInited = true let contactsNavigation = AANavigationController(rootViewController: ContactsViewController()) let dialogsNavigation = AANavigationController(rootViewController: DialogsViewController()) let settingsNavigation = AANavigationController(rootViewController: SettingsViewController()) viewControllers = [contactsNavigation, dialogsNavigation, settingsNavigation] selectedIndex = 0; selectedIndex = 1; } } } // MARK: - // MARK: Methods func centerButtonTap() { // var actionShit = ABActionShit() // actionShit.buttonTitles = ["Add Contact", "Create group", "Write to..."]; // actionShit.delegate = self // actionShit.showWithCompletion(nil) } // MARK: - // MARK: ABActionShit Delegate // func actionShit(actionShit: ABActionShit!, clickedButtonAtIndex buttonIndex: Int) { // if (buttonIndex == 1) { // navigationController?.pushViewController(GroupMembersController(), animated: true) // } // } // MARK: - // MARK: Placeholder func showAppIsSyncingPlaceholder() { appIsEmptyPlaceholder.hidden = true appIsSyncingPlaceholder.hidden = false appEmptyContainer.hidden = false } func showAppIsEmptyPlaceholder() { appIsEmptyPlaceholder.hidden = false appIsSyncingPlaceholder.hidden = true appEmptyContainer.hidden = false } func hidePlaceholders() { appEmptyContainer.hidden = true } func showSmsInvitation(phone: String?) { if MFMessageComposeViewController.canSendText() { // Silently ignore if not configured if AppConfig.appInviteUrl == nil { return } let messageComposeController = MFMessageComposeViewController() messageComposeController.messageComposeDelegate = self if (phone != nil) { messageComposeController.recipients = [phone!] } messageComposeController.body = localized("InviteText") .replace("{link}", dest: AppConfig.appInviteUrl!) messageComposeController.navigationBar.tintColor = MainAppTheme.navigation.titleColor presentViewController(messageComposeController, animated: true, completion: { () -> Void in MainAppTheme.navigation.applyStatusBarFast() }) } else { UIAlertView(title: "Error", message: "Cannot send SMS", delegate: nil, cancelButtonTitle: "OK").show() } } func showSmsInvitation() { showSmsInvitation(nil) } func doAddContact() { let alertView = UIAlertView( title: NSLocalizedString("ContactsAddHeader", comment: "Alert Title"), message: NSLocalizedString("ContactsAddHint", comment: "Alert Hint"), delegate: self, cancelButtonTitle: NSLocalizedString("AlertCancel", comment: "Alert Cancel"), otherButtonTitles: NSLocalizedString("AlertNext", comment: "Alert Next")) alertView.alertViewStyle = UIAlertViewStyle.PlainTextInput alertView.show() } // MARK: - // MARK: Layout override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() appEmptyContainer.frame = view.bounds appIsSyncingPlaceholder.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height) appIsEmptyPlaceholder.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height) } override func shouldAutorotate() -> Bool { return false } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } } extension MainTabViewController: MFMessageComposeViewControllerDelegate { func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) { controller.dismissViewControllerAnimated(true, completion: nil) } } extension MainTabViewController: UIAlertViewDelegate { func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { // TODO: Localize if buttonIndex == 1 { let textField = alertView.textFieldAtIndex(0)! if textField.text?.length > 0 { self.execute(Actor.findUsersCommandWithQuery(textField.text), successBlock: { (val) -> Void in var user: ACUserVM? user = val as? ACUserVM if user == nil { if let users = val as? IOSObjectArray { if Int(users.length()) > 0 { if let tempUser = users.objectAtIndex(0) as? ACUserVM { user = tempUser } } } } if user != nil { self.execute(Actor.addContactCommandWithUid(user!.getId()), successBlock: { (val) -> () in // DO Nothing }, failureBlock: { (val) -> () in self.showSmsInvitation(textField.text) }) } else { self.showSmsInvitation(textField.text) } }, failureBlock: { (val) -> Void in self.showSmsInvitation(textField.text) }) } } } }
e0307949b7032f64ae13d3ab9da08dca
36.090517
133
0.602627
false
false
false
false
wangjianquan/wjq-weibo
refs/heads/master
weibo_wjq/Tool/Emotion/UITextView - Extension.swift
apache-2.0
1
// // UITextView - Extension.swift // EmotionDemo // // Created by landixing on 2017/6/9. // Copyright © 2017年 WJQ. All rights reserved. // import UIKit extension UITextView { /// 获取textView属性字符串,对应的表情字符串 func getEmoticonString() -> String { // 1.获取属性字符串 let attrMStr = NSMutableAttributedString(attributedString: attributedText) // 2.遍历属性字符串 let range = NSRange(location: 0, length: attrMStr.length) attrMStr.enumerateAttributes(in: range, options: []) { (dict, range, _) -> Void in if let attachment = dict["NSAttachment"] as? EmoticonAttachment { attrMStr.replaceCharacters(in: range, with: attachment.chs!) } } // 3.获取字符串 return attrMStr.string } /// 给textView插入表情 func insertEmoticon(_ emoticon : EmotionModel) { // 1.空白表情 if emoticon.isEmpty { return } // 2.删除按钮 if emoticon.isRemove { deleteBackward() return } // 3.emoji表情 if emoticon.emojiCode != nil { // 3.1.获取光标所在的位置:UITextRange let textRange = selectedTextRange! // 3.2.替换emoji表情 replace(textRange, withText: emoticon.emojiCode!) return } // 4.普通表情:图文混排 // 4.1.根据图片路径创建属性字符串 let attachment = EmoticonAttachment() attachment.chs = emoticon.chs attachment.image = UIImage(contentsOfFile: emoticon.pngPath!) let font = self.font! attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight) let attrImageStr = NSAttributedString(attachment: attachment) // 4.2.创建可变的属性字符串 let attrMStr = NSMutableAttributedString(attributedString: attributedText) // 4.3.将图片属性字符串,替换到可变属性字符串的某一个位置 // 4.3.1.获取光标所在的位置 let range = selectedRange // 4.3.2.替换属性字符串 attrMStr.replaceCharacters(in: range, with: attrImageStr) // 显示属性字符串 attributedText = attrMStr // 将文字的大小重置 self.font = font // 将光标设置回原来位置 + 1 selectedRange = NSRange(location: range.location + 1, length: 0) } }
22ba0556fe6215d9a4155a38776a9ba3
25.761364
96
0.556688
false
false
false
false
JeremyJacquemont/SchoolProjects
refs/heads/master
IUT/iOS-Projects/Cocktails/Cocktails/MasterViewController.swift
apache-2.0
1
// // ViewController.swift // Cocktails // // Created by iem on 12/02/2015. // Copyright (c) 2015 JeremyJacquemont. All rights reserved. // import UIKit class MasterViewController: UITableViewController, UISearchBarDelegate, UISearchDisplayDelegate { // MARK: - Variables var cocktails: [Cocktail]! var filterCocktails = [Cocktail]() @IBOutlet weak var searchBarMaster: UISearchBar! var searchText = "" var scopeChoice = "" var isSearch = false // MARK: - UITableViewController Override override func viewDidLoad() { super.viewDidLoad() setupButtons() setupList() setupTable() } override func viewDidAppear(animated: Bool) { self.refresh(NSNull()) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Functions func setupButtons(){ let addButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addAction") let searchButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: "searchAction") self.navigationItem.setRightBarButtonItems([addButton, searchButton], animated: true) } func addAction(){ let storyboard = UIStoryboard(name: "Main", bundle: nil) var editView: EditViewController = storyboard.instantiateViewControllerWithIdentifier("EditViewController") as EditViewController editView.type = EditViewControllerType.Add editView.lastViewController = self let navigation = UINavigationController(rootViewController: editView) self.presentViewController(navigation, animated: true, completion: nil) } func searchAction() { searchBarMaster.becomeFirstResponder() } func setupList(){ var manager = DBManager.sharedInstance self.cocktails = manager.getAllCocktails() } func setupTable(){ var newBounds = self.tableView.bounds; newBounds.origin.y = newBounds.origin.y + searchBarMaster.bounds.size.height; self.tableView.bounds = newBounds; self.tableView.allowsMultipleSelectionDuringEditing = false self.refreshControl?.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) } func refresh(sender:AnyObject) { setupList() self.tableView.reloadData() if isSearch { filterContentForSearchText(searchText, scope: scopeChoice) self.searchDisplayController?.searchResultsTableView.reloadData() } self.refreshControl?.endRefreshing() } // MARK: - Table view override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == self.searchDisplayController!.searchResultsTableView { return self.filterCocktails.count } else { return self.cocktails.count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier("CocktailCell") as UITableViewCell var cocktail : Cocktail if tableView == self.searchDisplayController!.searchResultsTableView { cocktail = filterCocktails[indexPath.row] } else { cocktail = cocktails[indexPath.row] } cell.textLabel!.text = cocktail.name cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { let manager = DBManager.sharedInstance if isSearch { var indexOpt = findIndexWithFilter(indexPath.row) if let index = indexOpt { manager.deleteCocktail(index) self.cocktails.removeAtIndex(index) self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: indexPath.section)], withRowAnimation: UITableViewRowAnimation.Fade) self.filterCocktails.removeAtIndex(indexPath.row) self.searchDisplayController?.searchResultsTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) } } else { manager.deleteCocktail(indexPath.row) self.cocktails.removeAtIndex(indexPath.row) self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) } } } func findIndexWithFilter(index: Int) -> Int?{ let cocktailInFilter = self.filterCocktails[index] for (index, element) in enumerate(cocktails) { if let index = find(cocktails, cocktailInFilter) { return index } } return nil } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "DetailSegue"{ var index : Int! var cocktail: Cocktail! if isSearch { index = self.searchDisplayController?.searchResultsTableView.indexPathForSelectedRow()?.item cocktail = self.filterCocktails[index] } else { index = tableView.indexPathForSelectedRow()?.item cocktail = self.cocktails[index] } var controller : DetailViewController = segue.destinationViewController as DetailViewController controller.setCocktail(cocktail) } } // MARK: - UISearchBarDelegate - UISearchDisplayDelegate func searchDisplayController(controller: UISearchDisplayController, didShowSearchResultsTableView tableView: UITableView) { isSearch = true } func searchDisplayController(controller: UISearchDisplayController, didHideSearchResultsTableView tableView: UITableView) { isSearch = false } func filterContentForSearchText(searchText: String, scope: String) { self.searchText = (searchText as NSString).lowercaseString self.scopeChoice = (scope as NSString).lowercaseString self.filterCocktails = self.cocktails.filter({( cocktail: Cocktail) -> Bool in let nameLowercase = (cocktail.name as NSString).lowercaseString var stringMatch : Range<String.Index>! switch (self.scopeChoice) { case "name": stringMatch = (cocktail.name as NSString).lowercaseString.rangeOfString(self.searchText) break; case "ingredients": stringMatch = (cocktail.ingredients as NSString).lowercaseString.rangeOfString(self.searchText) break; case "directives": stringMatch = (cocktail.directions as NSString).lowercaseString.rangeOfString(self.searchText) break; case "all": stringMatch = (cocktail.name as NSString).lowercaseString.rangeOfString(self.searchText) != nil ? (cocktail.name as NSString).lowercaseString.rangeOfString(self.searchText) : (cocktail.ingredients as NSString).lowercaseString.rangeOfString(self.searchText) != nil ? (cocktail.ingredients as NSString).lowercaseString.rangeOfString(self.searchText) : (cocktail.directions as NSString).lowercaseString.rangeOfString(self.searchText) != nil ? (cocktail.directions as NSString).lowercaseString.rangeOfString(self.searchText) : nil break; default: break; } return stringMatch != nil }) } func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool { let scopes = self.searchDisplayController?.searchBar.scopeButtonTitles as [String] let selectIndex = self.searchDisplayController?.searchBar.selectedScopeButtonIndex let selectedScope = scopes[selectIndex!] as String self.filterContentForSearchText(searchString, scope: selectedScope) return true } func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchScope searchOption: Int) -> Bool { let scope = self.searchDisplayController?.searchBar.scopeButtonTitles as [String] let selectedScope = scope[searchOption] self.filterContentForSearchText(self.searchDisplayController!.searchBar.text, scope: selectedScope) return true } }
44fb3884ca2c2f784dd88bda357a53e4
42.504673
200
0.656032
false
false
false
false
darina/omim
refs/heads/master
iphone/Maps/UI/Welcome/WelcomePageController.swift
apache-2.0
4
@objc(MWMWelcomePageControllerProtocol) protocol WelcomePageControllerProtocol { var view: UIView! { get set } func addChildViewController(_ childController: UIViewController) func closePageController(_ pageController: WelcomePageController) } @objc(MWMWelcomePageController) final class WelcomePageController: UIPageViewController { fileprivate var controllers: [UIViewController] = [] private var parentController: WelcomePageControllerProtocol! private var iPadBackgroundView: SolidTouchView? private var isAnimatingTransition = true fileprivate var currentController: UIViewController! { get { return viewControllers?.first } set { guard let controller = newValue, let parentView = parentController.view else { return } let animated = !isAnimatingTransition parentView.isUserInteractionEnabled = isAnimatingTransition setViewControllers([controller], direction: .forward, animated: animated) { [weak self] _ in guard let s = self else { return } s.isAnimatingTransition = false parentView.isUserInteractionEnabled = true } isAnimatingTransition = animated } } static func shouldShowWelcome() -> Bool { return WelcomeStorage.shouldShowTerms || Alohalytics.isFirstSession() || (WelcomeStorage.shouldShowWhatsNew && !DeepLinkHandler.shared.isLaunchedByDeeplink) } @objc static func controller(parent: WelcomePageControllerProtocol) -> WelcomePageController? { guard WelcomePageController.shouldShowWelcome() else { return nil } let vc = WelcomePageController(transitionStyle: .scroll , navigationOrientation: .horizontal, options: convertToOptionalUIPageViewControllerOptionsKeyDictionary([:])) vc.parentController = parent var controllersToShow: [UIViewController] = [] if WelcomeStorage.shouldShowTerms { controllersToShow.append(TermsOfUseBuilder.build(delegate: vc)) controllersToShow.append(contentsOf: FirstLaunchBuilder.build(delegate: vc)) } else { if Alohalytics.isFirstSession() { WelcomeStorage.shouldShowTerms = true controllersToShow.append(TermsOfUseBuilder.build(delegate: vc)) controllersToShow.append(contentsOf: FirstLaunchBuilder.build(delegate: vc)) } else { NSLog("deeplinking: whats new check") if (WelcomeStorage.shouldShowWhatsNew && !DeepLinkHandler.shared.isLaunchedByDeeplink) { controllersToShow.append(contentsOf: WhatsNewBuilder.build(delegate: vc)) } } } WelcomeStorage.shouldShowWhatsNew = false vc.controllers = controllersToShow return vc } override func viewDidLoad() { super.viewDidLoad() view.styleName = "Background" iPadSpecific { let parentView = parentController.view! iPadBackgroundView = SolidTouchView(frame: parentView.bounds) iPadBackgroundView!.styleName = "FadeBackground" iPadBackgroundView!.autoresizingMask = [.flexibleWidth, .flexibleHeight] parentView.addSubview(iPadBackgroundView!) view.layer.cornerRadius = 5 view.clipsToBounds = true } currentController = controllers.first } func nextPage() { currentController = pageViewController(self, viewControllerAfter: currentController) } func close() { iPadBackgroundView?.removeFromSuperview() view.removeFromSuperview() removeFromParent() parentController.closePageController(self) FrameworkHelper.processFirstLaunch(LocationManager.lastLocation() != nil) } @objc func show() { parentController.addChildViewController(self) parentController.view.addSubview(view) updateFrame() } private func updateFrame() { let parentView = parentController.view! let size = WelcomeViewController.presentationSize view.frame = alternative(iPhone: CGRect(origin: CGPoint(), size: parentView.size), iPad: CGRect(x: parentView.center.x - size.width/2, y: parentView.center.y - size.height/2, width: size.width, height: size.height)) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { [weak self] _ in self?.updateFrame() }, completion: nil) } } extension WelcomePageController: UIPageViewControllerDataSource { func pageViewController(_: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard viewController != controllers.first else { return nil } let index = controllers.index(before: controllers.firstIndex(of: viewController)!) return controllers[index] } func pageViewController(_: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard viewController != controllers.last else { return nil } let index = controllers.index(after: controllers.firstIndex(of: viewController)!) return controllers[index] } func presentationCount(for _: UIPageViewController) -> Int { return controllers.count } func presentationIndex(for _: UIPageViewController) -> Int { guard let vc = currentController else { return 0 } return controllers.firstIndex(of: vc)! } } extension WelcomePageController: WelcomeViewDelegate { func welcomeDidPressNext(_ viewContoller: UIViewController) { guard let index = controllers.firstIndex(of: viewContoller) else { close() return } if index + 1 < controllers.count { nextPage() } else { if DeepLinkHandler.shared.needExtraWelcomeScreen { let vc = DeepLinkInfoBuilder.build(delegate: self) controllers.append(vc) nextPage() } else { close() DeepLinkHandler.shared.handleDeeplink() } } } func welcomeDidPressClose(_ viewContoller: UIViewController) { close() } } extension WelcomePageController: DeeplinkInfoViewControllerDelegate { func deeplinkInfoViewControllerDidFinish(_ viewController: UIViewController, deeplink: URL?) { close() guard let dl = deeplink else { return } DeepLinkHandler.shared.handleDeeplink(dl) } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalUIPageViewControllerOptionsKeyDictionary(_ input: [String: Any]?) -> [UIPageViewController.OptionsKey: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIPageViewController.OptionsKey(rawValue: key), value)}) }
37bc028d2582cd9d2476a461f83e2b84
36.274725
144
0.713149
false
false
false
false
tjarratt/Xcode-Better-Refactor-Tools
refs/heads/master
Fake4SwiftKit/Use Cases/Implement Equatable/XMASImplementEquatableUseCase.swift
mit
3
import Foundation import Fake4SwiftKit @objc open class XMASImplementEquatableUseCase : NSObject { fileprivate(set) open var logger: XMASLogger fileprivate(set) open var alerter: XMASAlerter fileprivate(set) open var equatableWriter: XMASEquatableWriter fileprivate(set) open var selectedFileOracle: XMASSelectedSourceFileOracle dynamic fileprivate(set) open var parseStructWorkflow: XMASParseSelectedStructWorkflow @objc public init( logger: XMASLogger, alerter: XMASAlerter, equatableWriter: XMASEquatableWriter, selectedFileOracle: XMASSelectedSourceFileOracle, parseStructWorkflow: XMASParseSelectedStructWorkflow) { self.logger = logger self.alerter = alerter self.equatableWriter = equatableWriter self.selectedFileOracle = selectedFileOracle self.parseStructWorkflow = parseStructWorkflow } @objc open func safelyAddEquatableToSelectedStruct() { let filePath = self.selectedFileOracle.selectedFilePath() as NSString if filePath.pathExtension.lowercased() != "swift" { self.alerter.flashMessage( "Select a Swift struct", with: .noSwiftFileSelected, shouldLogMessage: false ) } do { let maybeStruct : StructDeclaration? = try self.parseStructWorkflow.selectedStructInFile(filePath as String) if let selectedStruct = maybeStruct { addEquatableImplPossiblyThrowingError(selectedStruct) } else { self.alerter.flashMessage( "Select a swift struct", with: .noSwiftFileSelected, shouldLogMessage: false ) } } catch let error as NSError { self.alerter.flashComfortingMessage(forError: error) } catch { self.alerter.flashMessage( "Something unexpected happened", with: .abjectFailure, shouldLogMessage: true ) } } fileprivate func addEquatableImplPossiblyThrowingError(_ selectedStruct : StructDeclaration) { do { try self.equatableWriter.addEquatableImplForStruct(selectedStruct) self.alerter.flashMessage( "Success!", with: .implementEquatable, shouldLogMessage: false ) } catch let error as NSError { self.alerter.flashComfortingMessage(forError: error) } catch { self.alerter.flashMessage( "Something unexpected happened", with: .abjectFailure, shouldLogMessage: true ) } } }
a89e3cae4134743a3b01bbbe28e7e290
35.519481
98
0.61202
false
false
false
false
conectas/bleComMitSync
refs/heads/master
bleComMitSync/BleScanTVC.swift
gpl-3.0
1
// // BleScanTVC.swift // bleComMitSync // // Created by Stefan Glaser on 26.03.16. // Copyright © 2016 conectas. All rights reserved. // import UIKit class BleScanTVC: UITableViewController, BTDiscoveryDelegate { // ------------------------------------------------------ let laderBTD = BTDiscovery() // ------------------------------------------------------ var bleDevicesDatenAR = [BleDevices]() var bleConnectDatenAR = [BleDevices]() var identifier = "detailVcSegue" var senderCell : UITableViewCell? // ---------------------------------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() let refreshControl = UIRefreshControl() // refreshControl.addTarget(self, action: Selector("update"), forControlEvents: UIControlEvents.ValueChanged) refreshControl.addTarget(self, action: #selector(BleScanTVC.update), forControlEvents: UIControlEvents.ValueChanged) self.refreshControl = refreshControl } // ---------------------------------------------------------------------------------------------------- override func viewDidAppear(animated: Bool) { // Initialize central manager on load laderBTD.delegateBTDiscovery = self laderBTD.startBteScan(bleConnectDatenAR) } // ---------------------------------------------------------------------------------------------------- // MARK: - ANFANG: BTDiscoveryDelegate // ---------------------------------------------------------------------------------------------------- func bteErgScanFertig(lader: BTDiscovery, bleDevicesDaten: [BleDevices]) { print("BleScanTVC: tableView.reloadData") bleDevicesDatenAR = bleDevicesDaten let navTitleTxt = "Scan Daten" if let _ = navigationController { self.navigationItem.title = navTitleTxt print("BleScanTVC: devNamenCount: \(bleDevicesDatenAR.count)") print("BleScanTVC: devicesNamen: \(bleDevicesDatenAR[0])") self.tableView.reloadData() } } // ---------------------------------------------------------------------------------------------------- func bteErgConnectSET(lader: BTDiscovery) { performSegueWithIdentifier(identifier, sender: senderCell) } // ---------------------------------------------------------------------------------------------------- // MARK: - ENDE: BTDiscoveryDelegate // ---------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------- func update() { self.navigationItem.title = "Update" print("BleScanTVC: update") bleDevicesDatenAR.removeAll(keepCapacity: false) // self.tableView.reloadData() // Initialize central manager on load laderBTD.delegateBTDiscovery = self laderBTD.startBteScan(bleConnectDatenAR) self.refreshControl?.endRefreshing() bleConnectDatenAR.removeAll(keepCapacity: false) } // ---------------------------------------------------------------------------------------------------- // MARK: - Table view data source // ---------------------------------------------------------------------------------------------------- // // ---------------------------------------------------------------------------------------------------- override func numberOfSectionsInTableView(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 bleDevicesDatenAR.count ?? 0 } // // ---------------------------------------------------------------------------------------------------- override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! BleScanTVCell print("BleScanTVC: cellForRowAtIndexPath") let aktuelleDevicesDaten = self.bleDevicesDatenAR[indexPath.row] if aktuelleDevicesDaten.devicesNamen != "nil" { print("BleScanTVC: devicesNamen: \(bleDevicesDatenAR.count) | \(indexPath.row)") cell.nameOutlet.text = ("\(aktuelleDevicesDaten.devicesNamen)") cell.uuidOutlet.text = aktuelleDevicesDaten.deviceUUID cell.rssiOutlet.text = aktuelleDevicesDaten.devicesRSSI.stringValue } return cell } // // ---------------------------------------------------------------------------------------------------- override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { identifier = "detailVcSegue" senderCell = tableView.cellForRowAtIndexPath(indexPath) bleConnectDatenAR.removeAll() let aktuelleConnectDaten = self.bleDevicesDatenAR[indexPath.row] let connectDevice = BleDevices( activeCentralManager : aktuelleConnectDaten.activeCentralManager, peripheral : aktuelleConnectDaten.peripheral, devicesNamen : aktuelleConnectDaten.devicesNamen, deviceUUID : aktuelleConnectDaten.deviceUUID, devicesRSSI : aktuelleConnectDaten.devicesRSSI ) self.bleConnectDatenAR.append(connectDevice) laderBTD.delegateBTDiscovery = self laderBTD.startBteConnect(bleConnectDatenAR) // if let _ = navigationController { // navigationItem.title = "Connecting \(aktuelleConnectDaten.devicesNamen)" // } } // // ---------------------------------------------------------------------------------------------------- override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // print("BleScanTVC: prepareForSegue") if segue.identifier == "detailVcSegue" { guard let zielViewController = segue.destinationViewController as? ViewController else { return } zielViewController.bleConnectDatenAR = bleConnectDatenAR } } }
12d52d926acfbbaa52660e33f623853f
38.348571
124
0.477491
false
false
false
false
gali8/G8SliderStep
refs/heads/master
G8SliderStep/G8SliderStepViewController.swift
mit
1
// // G8SliderStepViewController.swift // G8SliderStep // // Created by Daniele on 25/08/16. // Copyright © 2016 g8production. All rights reserved. // import UIKit class G8SliderStepViewController: UIViewController { @IBOutlet weak var sliderStep: G8SliderStep! override func viewDidLoad() { super.viewDidLoad() ///G8SliderStep configuration sliderStep.stepImages = [UIImage(named:"star")!, UIImage(named:"heart")!, UIImage(named:"house")!] sliderStep.tickTitles = ["STAR", "HEART", "HOUSE"] let shape = UIImage(named:"shape")! sliderStep.tickImages = [shape, shape, shape] sliderStep.minimumValue = 2 sliderStep.maximumValue = Float(sliderStep.stepImages!.count) + sliderStep.minimumValue - 1.0 sliderStep.trackColor = UIColor.darkGray sliderStep.stepTickColor = UIColor.orange sliderStep.stepTickWidth = 30 sliderStep.stepTickHeight = 30 sliderStep.trackHeight = 10 sliderStep.value = 3 } 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. } */ }
6891bc36494b5a7ccfe3d36ada531d9d
31.541667
106
0.676056
false
false
false
false
carlo-/ipolito
refs/heads/master
iPoliTO2/CRTimePicker.swift
gpl-3.0
1
// // CRTimePicker.swift // // Created by Carlo Rapisarda on 07/08/2016. // Copyright © 2016 crapisarda. All rights reserved. // import UIKit protocol CRTimePickerDelegate { func timePickerDidPickDate(picker: CRTimePicker, date: Date) func timePickerDidScroll(picker: CRTimePicker, onDate date: Date) } extension CRTimePickerDelegate { func timePickerDidPickDate(picker: CRTimePicker, date: Date) {} func timePickerDidScroll(picker: CRTimePicker, onDate date: Date) {} } class CRTimePicker: UIView, UIScrollViewDelegate { private var subtitleLabel: UILabel? private var scrollView: CRTimePickerScrollView? private var initialDate: Date? var delegate: CRTimePickerDelegate? override var tintColor: UIColor! { didSet { scrollView?.tintColor = tintColor subtitleLabel?.textColor = tintColor // draw(frame) } } convenience init(frame: CGRect, date: Date? = nil) { self.init(frame: frame) self.initialDate = date } class AccessoryView: UIToolbar { init(frame: CGRect, tintColor: UIColor) { super.init(frame: frame) backgroundColor = UIColor.clear isUserInteractionEnabled = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { // Arrow pointing down let polygonWidth: CGFloat = 14 let polygonHeight: CGFloat = 7 let polygonFrame = CGRect(x: (rect.width - polygonWidth) / 2.0, y: 0, width: polygonWidth, height: polygonHeight) let polygonPath = UIBezierPath() polygonPath.move(to: CGPoint(x: polygonFrame.origin.x, y: polygonFrame.origin.y)) // Left corner polygonPath.addLine(to: CGPoint(x: polygonFrame.origin.x + polygonFrame.width, y: polygonFrame.origin.y)) // Right corner polygonPath.addLine(to: CGPoint(x: polygonFrame.origin.x + polygonFrame.width/2.0, y: polygonFrame.origin.y+polygonFrame.height)) // Tip polygonPath.close() tintColor.setFill() polygonPath.fill() /* // Separator let linePath = UIBezierPath() linePath.move(to: CGPoint.zero) linePath.addLine(to: CGPoint(x: rect.width, y: 0)) linePath.lineWidth = 1 /*UIColor.black()*/ tintColor.setStroke() linePath.stroke() */ } } override func draw(_ rect: CGRect) { subviews.forEach { $0.removeFromSuperview() } // Background let background = UIToolbar(frame: rect) addSubview(background) // Scroll View let scrollViewFrame = CGRect(x: 0, y: 11, width: rect.width, height: 50) scrollView = CRTimePickerScrollView(frame: scrollViewFrame, date: initialDate) scrollView?.delegate = self scrollView?.tintColor = tintColor addSubview(scrollView!) // Subtitle subtitleLabel = UILabel(frame: CGRect(x: 0, y: scrollViewFrame.origin.y+scrollViewFrame.height, width: rect.width, height: 20)) guard let subtitleLabel = subtitleLabel else { return } subtitleLabel.textColor = tintColor // UIColor.white() subtitleLabel.text = ~"ls.timePicker.subtitle"+" XXXXX" subtitleLabel.adjustsFontSizeToFitWidth = true subtitleLabel.sizeToFit() subtitleLabel.center = CGPoint(x: rect.width/2, y: subtitleLabel.center.y) addSubview(subtitleLabel) // Accessory View addSubview(AccessoryView(frame: rect, tintColor: tintColor)) updateSubtitleLabel() } override func layoutSubviews() { super.layoutSubviews() draw(bounds) } func stopScrollView() { guard let scrollView = scrollView else { return } scrollView.setContentOffset(scrollView.contentOffset, animated: false) } func currentSelection() -> Date { guard let scrollView = scrollView else { return Date() } let portionWidth = scrollView.contentSize.width/3 let intervalWidth = portionWidth/48 let relativePosX = Int(scrollView.contentOffset.x + scrollView.frame.width/2) % Int(portionWidth) var decimal = Float(relativePosX - Int(intervalWidth)/2) / Float(intervalWidth*2) if decimal < 0 { decimal += 24 } let hour = Int(decimal) let minute = Int((decimal - Float(hour)) * 60.0) var cal = Calendar(identifier: Calendar.Identifier.gregorian) cal.timeZone = TimeZone.Turin return cal.date(bySettingHour: hour, minute: minute, second: 0, of: Date())! } private func updateSubtitleLabel() { let formatter = DateFormatter() formatter.dateStyle = .none formatter.timeStyle = .short formatter.timeZone = TimeZone.Turin formatter.locale = Locale(identifier: "it-IT") let selection = currentSelection() subtitleLabel?.text = ~"ls.timePicker.subtitle"+" "+formatter.string(from: selection) } func scrollViewDidScroll(_ scrollView: UIScrollView) { // Patch (since scrollViewDidEndScrollingAnimation is not called as it should) // See: http://stackoverflow.com/questions/993280/how-to-detect-when-a-uiscrollview-has-finished-scrolling NSObject.cancelPreviousPerformRequests(withTarget: self) perform(#selector(scrollViewDidEndScrollingAnimation), with: scrollView, afterDelay: 0.1) updateSubtitleLabel() delegate?.timePickerDidScroll(picker: self, onDate: currentSelection()) } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { // Patch (see scrollViewDidScroll) NSObject.cancelPreviousPerformRequests(withTarget: self) delegate?.timePickerDidPickDate(picker: self, date: currentSelection()) } } private class CRTimePickerScrollView: UIScrollView { private let pickerContentL: CRTimePickerContentView private let pickerContentC: CRTimePickerContentView private let pickerContentR: CRTimePickerContentView override var tintColor: UIColor! { didSet { pickerContentL.tintColor = tintColor pickerContentC.tintColor = tintColor pickerContentR.tintColor = tintColor } } init(frame: CGRect, date: Date? = nil) { let labels = CRTimePickerContentView.precomputeLabels() pickerContentL = CRTimePickerContentView(withPrecomputedLabels: labels) pickerContentC = CRTimePickerContentView(withPrecomputedLabels: labels) pickerContentR = CRTimePickerContentView(withPrecomputedLabels: labels) super.init(frame: frame) let portionWidth: CGFloat = 3000 contentSize = CGSize(width: portionWidth*3, height: frame.height) backgroundColor = UIColor.clear showsVerticalScrollIndicator = false showsHorizontalScrollIndicator = false pickerContentL.frame = CGRect(x: 0, y: 0, width: portionWidth, height: frame.height) pickerContentC.frame = CGRect(x: portionWidth, y: 0, width: portionWidth, height: frame.height) pickerContentR.frame = CGRect(x: portionWidth*2, y: 0, width: portionWidth, height: frame.height) pickerContentL.backgroundColor = UIColor.clear pickerContentC.backgroundColor = UIColor.clear pickerContentR.backgroundColor = UIColor.clear addSubview(pickerContentL) addSubview(pickerContentC) addSubview(pickerContentR) contentOffset = CGPoint(x: horizontalOffset(forDate: date ?? Date()), y: contentOffset.y) } private func horizontalOffset(forDate date: Date) -> CGFloat { var cal = Calendar(identifier: Calendar.Identifier.gregorian) cal.timeZone = TimeZone.Turin let hour = cal.component(.hour, from: date) let minute = cal.component(.minute, from: date) let decimal = Float(hour)+Float(minute)/60.0 let portionWidth = contentSize.width/3 let intervalWidth = portionWidth/48 var partialRes = intervalWidth * 2 * CGFloat(decimal) partialRes += portionWidth partialRes += intervalWidth/2 partialRes -= frame.width/2 return partialRes } private func recenterIfNecessary() { let portionWidth = contentSize.width/3 if contentOffset.x < portionWidth { // We are in the left portion contentOffset = CGPoint(x: contentOffset.x + portionWidth, y: contentOffset.y) } else if contentOffset.x > portionWidth*2 { // We are in the right portion contentOffset = CGPoint(x: contentOffset.x - portionWidth, y: contentOffset.y) } // Else we are in the central portion } fileprivate override func layoutSubviews() { super.layoutSubviews() recenterIfNecessary() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } private class CRTimePickerContentView: UIView { static let intervals: Int = 48 private var precomputedLabels: [String] = [] convenience init(withPrecomputedLabels precomputedLabels: [String]) { self.init() self.precomputedLabels = precomputedLabels } class func precomputeLabels() -> [String] { var cal = Calendar(identifier: .gregorian) cal.timeZone = TimeZone.Turin let today = Date() let formatter = DateFormatter() formatter.timeZone = TimeZone.Turin formatter.dateStyle = .none formatter.timeStyle = .short formatter.locale = Locale(identifier: "it-IT") var labels: [String] = [] for i in 0..<intervals { let hour = i/2 let minute = i%2 == 0 ? 0 : 30 let date = cal.date(bySettingHour: hour, minute: minute, second: 0, of: today)! let timeStr = formatter.string(from: date) labels.append(timeStr) } return labels } fileprivate override func draw(_ rect: CGRect) { let intervals = CRTimePickerContentView.intervals let intervalWidth = rect.width/CGFloat(intervals) if precomputedLabels.count != intervals { precomputedLabels = CRTimePickerContentView.precomputeLabels() } for i in 0..<intervals { let xpos = intervalWidth * (0.5 + CGFloat(i)) let timeLabelWidth = intervalWidth-16 let timeStr = precomputedLabels[i] let timeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: timeLabelWidth, height: 20)) timeLabel.text = timeStr timeLabel.textColor = tintColor timeLabel.adjustsFontSizeToFitWidth = true timeLabel.center = CGPoint(x: xpos, y: rect.height/2) addSubview(timeLabel) let separator = UIBezierPath() separator.move(to: CGPoint(x: xpos, y: 0)) separator.addLine(to: CGPoint(x: xpos, y: (rect.height-timeLabel.frame.height)/2 - 5)) separator.lineWidth = 1 tintColor.setStroke() separator.stroke() } } }
5c427c492850be15bb79c7794412ef6c
31.382199
148
0.590946
false
false
false
false
ltcarbonell/deckstravaganza
refs/heads/master
Deckstravaganza/DetailViewController.swift
mit
1
// // DetailViewController.swift // Deckstravaganza // // Created by Stephen on 9/28/15. // Copyright © 2015 University of Florida. All rights reserved. // import UIKit import SpriteKit import GameKit enum GameState : Int { case kGameStateWaitingForMatch = 0 case kGameStateWaitingForStart case kGameStateActive case kGameStateDone case kGameStateWaitingForRandomNumber } enum MessageType : Int { case kMessageTypeGameBegin case kMessageTypeAction case kMessageTypeGameOver case kMessageTypeRandomNumber } struct Message{ var messageType: MessageType } struct MessageRandomNumber{ var message: Message var randomNumber: Int } struct MessageGameBegin{ var message: Message } struct MessageGameAction{ var message: Message } struct MessageGameOver{ var message: Message var player1Won: Bool } let FIELD_START_FROM_TOP: CGFloat = 50; let FIELD_TOP_MARGIN: CGFloat = 10; let FIELD_HEIGHT: CGFloat = 40; let TITLE_SIZE: CGFloat = 25; class DetailViewController: UIViewController, GCHelperDelegate { let titleMargin: CGFloat = 50; let buttonFrame = CGRect(x: 0, y: 0, width: 100, height: 50); var selectedMenuOption: Menu!; var gameOptions: [AdjustableSetting]? = nil; var newGame: Bool = true; var menuDescription = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 30)) var formFields: [GameFormElement] = []; var buttonOption = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 20)); override func viewDidLoad() { super.viewDidLoad() // Setup the menu tearDownMenuUI(); setupMenuUI(); } override func viewDidAppear(_ animated: Bool) { self.view.setNeedsDisplay(); self.view.setNeedsLayout(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tearDownMenuUI() { for element in formFields { element.removeFromSuperview(); } menuDescription.removeFromSuperview(); buttonOption.removeFromSuperview(); } /////////////////////////////////////// BEGIN MULTIPLAYER /////////////////////////////////////////////////////// var _gameState: GameState = .kGameStateWaitingForMatch var _ourRandomNumber: Int = Int(arc4random()) var _isPlayer1: Bool = false var _receivedAllRandomNumbers: Bool = false var orderOfPlayers: NSMutableArray = [] var playerIdKey = "PlayerId" var randomNumberKey = "randomNumber" /// Method called when a match has been initiated. func matchStarted(){ orderOfPlayers.add([playerIdKey: GKLocalPlayer.localPlayer().playerID!, randomNumberKey: _ourRandomNumber]) // performSegueWithIdentifier("menuToGameSegue", sender: nil); print("Match has started successfully") if _receivedAllRandomNumbers { _gameState = .kGameStateWaitingForStart } else { _gameState = .kGameStateWaitingForRandomNumber } self.sendRandomNumber() print("sent random number", _ourRandomNumber) self.tryStartGame() } /// Method called when the device received data about the match from another device in the match. func match(_ match: GKMatch, didReceiveData data: Data, fromPlayer playerID: String){ let message = (data as NSData).bytes.bindMemory(to: Message.self, capacity: data.count).pointee if message.messageType == MessageType.kMessageTypeRandomNumber { let messageRandomNumber = (data as NSData).bytes.bindMemory(to: MessageRandomNumber.self, capacity: data.count).pointee print("recieved random number ", messageRandomNumber.randomNumber) var tie: Bool = false if (messageRandomNumber.randomNumber == _ourRandomNumber) { print("tie") tie = true self._ourRandomNumber = Int(arc4random()) self.sendRandomNumber() } else { let dictionary: [AnyHashable: Any] = [playerIdKey : playerID, randomNumberKey: messageRandomNumber.randomNumber] // dictionary[playerID] = messageRandomNumber.randomNumber self.processReceivedRandomNumber(dictionary) } if _receivedAllRandomNumbers { // self._isPlayer1 = self.isLocalPlayerPlayer1() } if !tie && _receivedAllRandomNumbers { //5 if _gameState == .kGameStateWaitingForRandomNumber { self._gameState = .kGameStateWaitingForStart } self.tryStartGame() } } } /// Method called when the match has ended. func matchEnded(){ } func sendRandomNumber(){ _ = MessageRandomNumber(message: Message(messageType: .kMessageTypeRandomNumber), randomNumber: _ourRandomNumber) // let data = Data(bytes: UnsafePointer<UInt8>(&message1), count: sizeof(MessageRandomNumber)) // let data = str.dataUsingEncoding(NSUTF8StringEncoding) // self.sendData(data) } func sendGameBegin() { _ = MessageGameBegin(message: Message(messageType: .kMessageTypeGameBegin)) // let data = Data(bytes: UnsafePointer<UInt8>(&message2), count: sizeof(MessageGameBegin)) // self.sendData(data) } func tryStartGame(){ if _isPlayer1 && _gameState == .kGameStateWaitingForStart { self._gameState = .kGameStateActive self.sendGameBegin() } } func processReceivedRandomNumber(_ randomNumberDetails: [AnyHashable: Any]) { //1 if orderOfPlayers.contains(randomNumberDetails) { orderOfPlayers.removeObject(at: orderOfPlayers.index(of: randomNumberDetails)) } //2 orderOfPlayers.add(randomNumberDetails) //3 let sortByRandomNumber: NSSortDescriptor = NSSortDescriptor(key: randomNumberKey, ascending: false) let sortDescriptors: [NSSortDescriptor] = [sortByRandomNumber] orderOfPlayers.sort(using: sortDescriptors) //4 // if self.allRandomNumbersAreReceived() { self._receivedAllRandomNumbers = true // } } // func allRandomNumbersAreReceived() -> Bool{ // var receivedRandomNumbers: [AnyObject] = NSMutableArray() as [AnyObject] // for dict: [NSObject: AnyObject] in orderOfPlayers { // receivedRandomNumbers.addObject(dict[randomNumberKey]) // } // var arrayOfUniqueRandomNumbers: [AnyObject] = NSSet.setWithArray(receivedRandomNumbers).allObjects() // if arrayOfUniqueRandomNumbers.count == GCHelper.sharedInstance.match.playerIDs.count + 1 { // return true // } // return false // } // func isLocalPlayerPlayer1() -> Bool { // let dictionary: [NSObject : String] = orderOfPlayers[0] // if (dictionary[playerIdKey] == GKLocalPlayer.localPlayer().playerID) { // print("I'm player 1") // return true // } // return false // } func sendData(_ data: Data){ do{ try GCHelper.sharedInstance.match.sendData(toAllPlayers: data, with: .reliable) } catch{ print("An unknown error has occured") } } ///////////////////////////////////////// END MULTIPLAYER ///////////////////////////////////////////////////////////////////////////////////// func setupMenuUI() { gameOptions = nil; menuDescription.text = selectedMenuOption.description; menuDescription.font = UIFont.systemFont(ofSize: 25, weight: UIFontWeightBold); menuDescription.textAlignment = .center; if(splitViewController != nil) { menuDescription.center = CGPoint(x: (UIScreen.main.bounds.width - splitViewController!.primaryColumnWidth) / 2, y: titleMargin); } else { menuDescription.center = CGPoint(x: UIScreen.main.bounds.midX, y: titleMargin); } self.view.addSubview(menuDescription); if(selectedMenuOption.viewGameOptions && selectedMenuOption.gameType != nil) { switch(selectedMenuOption.gameType!) { case .solitaire: gameOptions = Solitaire(selectedOptions: nil).getGameOptions(); case .rummy: gameOptions = Rummy(selectedOptions: nil).getGameOptions(); } } let elementFrame : CGRect; if(splitViewController != nil) { elementFrame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - splitViewController!.primaryColumnWidth, height: FIELD_HEIGHT); } else { elementFrame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: FIELD_HEIGHT); } var numberFields = 0; if(gameOptions != nil) { for gameOption in gameOptions! { let element: GameFormElement; let elementLabel = UILabel(); elementLabel.text = gameOption.settingName; switch(gameOption.formType) { case .cards: element = GameFormElement(frame: CGRect(), settingName: "", formLabel: nil, formField: UIView()); break; case .dropDown: let elementField = GenericPickerView(data: gameOption.options); elementField.dataSource = elementField; elementField.delegate = elementField; element = GameFormElement(frame: elementFrame, settingName: gameOption.settingName, formLabel: elementLabel, formField: elementField); case .slider: let elementField = GenericSliderView(data: gameOption.options); element = GameFormElement(frame: elementFrame, settingName: gameOption.settingName, formLabel: elementLabel, formField: elementField); case .switch: let elementField = GenericSwitchView(); /* All switches are assumed to be for multiplayer settings. */ elementField.addTarget(self, action: #selector(DetailViewController.updateMultiplayer(_:)), for: UIControlEvents.allTouchEvents); element = GameFormElement(frame: elementFrame, settingName: gameOption.settingName, formLabel: elementLabel, formField: elementField); } element.center = CGPoint(x: elementFrame.midX, y: FIELD_START_FROM_TOP + FIELD_TOP_MARGIN + (CGFloat(numberFields) * FIELD_HEIGHT) + TITLE_SIZE); formFields.append(element); self.view.addSubview(formFields.last!); numberFields += 1; } } buttonOption.frame = buttonFrame; buttonOption.center = CGPoint(x: elementFrame.midX, y: FIELD_START_FROM_TOP + FIELD_TOP_MARGIN + (CGFloat(numberFields) * FIELD_HEIGHT) + TITLE_SIZE); buttonOption.alpha = 0.8; buttonOption.backgroundColor = UIColor.clear; buttonOption.setTitleColor(UIColor(red: 0, green: 122.0/255.0, blue: 1.0, alpha: 1.0), for: UIControlState()); buttonOption.setTitleColor(UIColor(red: 0, green: 122.0/255.0, blue: 1.0, alpha: 0.5), for: .highlighted); buttonOption.isUserInteractionEnabled = true; if(selectedMenuOption.name == "Continue") { buttonOption.setTitle("Continue", for: UIControlState()); newGame = false; if(gameScene == nil) { // Continue should be disabled. buttonOption.isUserInteractionEnabled = false; buttonOption.setTitleColor(UIColor.lightGray, for: UIControlState()); } } else { buttonOption.setTitle("Play", for: UIControlState()); newGame = true; } self.view.addSubview(buttonOption); buttonOption.isHidden = false; buttonOption.setNeedsDisplay(); buttonOption.setNeedsLayout(); buttonOption.addTarget(self, action: #selector(DetailViewController.buttonPressed(_:)), for: .touchUpInside); } func buttonPressed(_ sender: UIButton?) { if(sender != nil) { if(sender!.titleLabel?.text == "Continue") { if(gameScene == nil) { return; } } } performSegue(withIdentifier: "menuToGameSegue", sender: sender); } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let gameViewController = (segue.destination as? GameSceneViewController) { gameViewController.gameType = selectedMenuOption.gameType; gameViewController.newGame = self.newGame; gameViewController.selectedMenuOption = self.selectedMenuOption; var selectedOptions = gameOptions; if(sender != nil && selectedOptions != nil) { if((sender! as! UIButton).titleLabel?.text != "Continue") { for index in (0 ..< selectedOptions!.count).reversed() { switch(selectedOptions![index].formType) { case .cards: break; case .dropDown: selectedOptions![index].options = [(formFields[index].formField as! GenericPickerView).getResults()]; case .slider: selectedOptions![index].options = [(formFields[index].formField as! GenericSliderView).getResults()]; case .switch: selectedOptions![index].options = [(formFields[index].formField as! GenericSwitchView).getResults()]; } } } } gameViewController.selectedOptions = selectedOptions; if let menuSplitViewController = self.splitViewController as? MenuSplitViewController { menuSplitViewController.toggleMasterView(); } } } func updateMultiplayer(_ sender: UISwitch?) { if(sender != nil) { if(sender!.isOn) { // Start multiplayer. GCHelper.sharedInstance.findMatchWithMinPlayers(2, maxPlayers: 4, viewController: self, delegate: self) } else { // Check if multiplayer is on and turn off if necessary. } } } } /* // 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. } */ extension DetailViewController: MenuSelectionDelegate { func menuSelected(_ newMenu: Menu) { selectedMenuOption = newMenu; } }
651f384a4e90a64aaf588aa47c89323a
36.606715
161
0.58768
false
false
false
false
BanyaKrylov/Learn-Swift
refs/heads/master
Skill/Weather/Weather/AlamofirePers.swift
apache-2.0
1
// // AlamofirePers.swift // Weather // // Created by Ivan Krylov on 02.03.2020. // Copyright © 2020 Ivan Krylov. All rights reserved. // import Foundation import CoreData import UIKit var cities = [NSManagedObject]() let appDelegate = UIApplication.shared.delegate as! AppDelegate let managedContext = appDelegate.persistentContainer.viewContext let entity = NSEntityDescription.entity(forEntityName: "City", in: managedContext) func addStartCity() { if userDefaults.bool(forKey: "firstRun") { let startCities = ["Rostov", "Sochi", "Tomsk", "Omsk"] for item in startCities { print(item) let city = NSManagedObject(entity: entity!, insertInto:managedContext) city.setValue(item, forKey: "name") cities.append(city) do { try managedContext.save() userDefaults.set(false, forKey: "firstRun") } catch { print(error) } } } } func addNewCity(nameTask: String) { let city = NSManagedObject(entity: entity!, insertInto:managedContext) city.setValue(nameTask, forKey: "name") cities.append(city) do { try managedContext.save() } catch { print(error) } } func removeCity(at index: Int) { let objectToDelete = cities[index] cities.remove(at: index) managedContext.delete(objectToDelete) do { try managedContext.save() } catch { let saveError = error as NSError print(saveError) } }
3d34d8718ff1750f581689b6a4129f46
24.145161
83
0.618345
false
false
false
false
waltflanagan/AdventOfCode
refs/heads/master
2015/AOC5.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit let input = ["sszojmmrrkwuftyv", "isaljhemltsdzlum", "fujcyucsrxgatisb", "qiqqlmcgnhzparyg", "oijbmduquhfactbc", "jqzuvtggpdqcekgk", "zwqadogmpjmmxijf", "uilzxjythsqhwndh", "gtssqejjknzkkpvw", "wrggegukhhatygfi", "vhtcgqzerxonhsye", "tedlwzdjfppbmtdx", "iuvrelxiapllaxbg", "feybgiimfthtplui", "qxmmcnirvkzfrjwd", "vfarmltinsriqxpu", "oanqfyqirkraesfq", "xilodxfuxphuiiii", "yukhnchvjkfwcbiq", "bdaibcbzeuxqplop", "ivegnnpbiyxqsion", "ybahkbzpditgwdgt", "dmebdomwabxgtctu", "ibtvimgfaeonknoh", "jsqraroxudetmfyw", "dqdbcwtpintfcvuz", "tiyphjunlxddenpj", "fgqwjgntxagidhah", "nwenhxmakxqkeehg", "zdoheaxqpcnlhnen", "tfetfqojqcdzlpbm", "qpnxkuldeiituggg", "xwttlbdwxohahwar", "hjkwzadmtrkegzye", "koksqrqcfwcaxeof", "wulwmrptktliyxeq", "gyufbedqhhyqgqzj", "txpunzodohikzlmj", "jloqfuejfkemcrvu", "amnflshcheuddqtc", "pdvcsduggcogbiia", "yrioavgfmeafjpcz", "uyhbtmbutozzqfvq", "mwhgfwsgyuwcdzik", "auqylgxhmullxpaa", "lgelzivplaeoivzh", "uyvcepielfcmswoa", "qhirixgwkkccuzlp", "zoonniyosmkeejfg", "iayfetpixkedyana", "ictqeyzyqswdskiy", "ejsgqteafvmorwxe", "lhaiqrlqqwfbrqdx", "ydjyboqwhfpqfydc", "dwhttezyanrnbybv", "edgzkqeqkyojowvr", "rmjfdwsqamjqehdq", "ozminkgnkwqctrxz", "bztjhxpjthchhfcd", "vrtioawyxkivrpiq", "dpbcsznkpkaaclyy", "vpoypksymdwttpvz", "hhdlruwclartkyap", "bqkrcbrksbzcggbo", "jerbbbnxlwfvlaiw", "dwkasufidwjrjfbf", "kkfxtjhbnmqbmfwf", "vmnfziwqxmioukmj", "rqxvcultipkecdtu", "fhmfdibhtjzkiqsd", "hdpjbuzzbyafqrpd", "emszboysjuvwwvts", "msyigmwcuybfiooq", "druyksfnbluvnwoh", "fvgstvynnfbvxhsx", "bmzalvducnqtuune", "lzwkzfzttsvpllei", "olmplpvjamynfyfd", "padcwfkhystsvyfb", "wjhbvxkwtbfqdilb", "hruaqjwphonnterf", "bufjobjtvxtzjpmj", "oiedrjvmlbtwyyuy", "sgiemafwfztwsyju", "nsoqqfudrtwszyqf", "vonbxquiiwxnazyl", "yvnmjxtptujwqudn", "rrnybqhvrcgwvrkq", "taktoxzgotzxntfu", "quffzywzpxyaepxa", "rfvjebfiddcfgmwv", "iaeozntougqwnzoh", "scdqyrhoqmljhoil", "bfmqticltmfhxwld", "brbuktbyqlyfpsdl", "oidnyhjkeqenjlhd", "kujsaiqojopvrygg", "vebzobmdbzvjnjtk", "uunoygzqjopwgmbg", "piljqxgicjzgifso", "ikgptwcjzywswqnw", "pujqsixoisvhdvwi", "trtuxbgigogfsbbk", "mplstsqclhhdyaqk", "gzcwflvmstogdpvo", "tfjywbkmimyyqcjd", "gijutvhruqcsiznq", "ibxkhjvzzxgavkha", "btnxeqvznkxjsgmq", "tjgofgauxaelmjoq", "sokshvyhlkxerjrv", "ltogbivktqmtezta", "uduwytzvqvfluyuf", "msuckpthtgzhdxan", "fqmcglidvhvpirzr", "gwztkqpcwnutvfga", "bsjfgsrntdhlpqbx", "xloczbqybxmiopwt", "orvevzyjliomkkgu", "mzjbhmfjjvaziget", "tlsdxuhwdmghdyjb", "atoecyjhwmznaewi", "pyxpyvvipbqibiox", "ajbfmpqqobfsmesj", "siknbzefjblnohgd", "eqfhgewbblwdfkmc", "opylbscrotckkrbk", "lbwxbofgjkzdxkle", "ceixfjstaptdomvm", "hnkrqxifjmmjktie", "aqykzeuzvvetoygd", "fouahjimfcisxima", "prkzhutbqsyrhjzx", "qqwliakathnsbzne", "sayhgqtlcqqidqhj", "ygduolbysehdudra", "zricvxhdzznuxuce", "ucvzakslykpgsixd", "udirhgcttmyspgsb", "yuwzppjzfsjhhdzi", "gtqergjiuwookwre", "xvxexbjyjkxovvwf", "mlpaqhnnkqxrmwmm", "ezuqbrjozwuqafhb", "mcarusdthcbsonoq", "weeguqeheeiigrue", "pngtfugozxofaqxv", "copphvbjcmfspenv", "jiyahihykjjkdaya", "gdqnmesvptuyrfwp", "vbdscfywqmfxbohh", "crtrfuxyjypzubrg", "seihvevtxywxhflp", "fvvpmgttnapklwou", "qmqaqsajmqwhetpk", "zetxvrgjmblxvakr", "kpvwblrizaabmnhz", "mwpvvzaaicntrkcp", "clqyjiegtdsswqfm", "ymrcnqgcpldgfwtm", "nzyqpdenetncgnwq", "cmkzevgacnmdkqro", "kzfdsnamjqbeirhi", "kpxrvgvvxapqlued", "rzskbnfobevzrtqu", "vjoahbfwtydugzap", "ykbbldkoijlvicbl", "mfdmroiztsgjlasb", "quoigfyxwtwprmdr", "ekxjqafwudgwfqjm", "obtvyjkiycxfcdpb", "lhoihfnbuqelthof", "eydwzitgxryktddt", "rxsihfybacnpoyny", "bsncccxlplqgygtw", "rvmlaudsifnzhcqh", "huxwsyjyebckcsnn", "gtuqzyihwhqvjtes", "zreeyomtngvztveq", "nwddzjingsarhkxb", "nuqxqtctpoldrlsh", "wkvnrwqgjooovhpf", "kwgueyiyffudtbyg", "tpkzapnjxefqnmew", "ludwccvkihagvxal", "lfdtzhfadvabghna", "njqmlsnrkcfhtvbb", "cajzbqleghhnlgap", "vmitdcozzvqvzatp", "eelzefwqwjiywbcz", "uyztcuptfqvymjpi", "aorhnrpkjqqtgnfo", "lfrxfdrduoeqmwwp", "vszpjvbctblplinh", "zexhadgpqfifcqrz", "ueirfnshekpemqua", "qfremlntihbwabtb", "nwznunammfexltjc", "zkyieokaaogjehwt", "vlrxgkpclzeslqkq", "xrqrwfsuacywczhs", "olghlnfjdiwgdbqc", "difnlxnedpqcsrdf", "dgpuhiisybjpidsj", "vlwmwrikmitmoxbt", "sazpcmcnviynoktm", "pratafauetiknhln", "ilgteekhzwlsfwcn", "ywvwhrwhkaubvkbl", "qlaxivzwxyhvrxcf", "hbtlwjdriizqvjfb", "nrmsononytuwslsa", "mpxqgdthpoipyhjc", "mcdiwmiqeidwcglk", "vfbaeavmjjemfrmo", "qzcbzmisnynzibrc", "shzmpgxhehhcejhb", "wirtjadsqzydtyxd", "qjlrnjfokkqvnpue", "dxawdvjntlbxtuqc", "wttfmnrievfestog", "eamjfvsjhvzzaobg", "pbvfcwzjgxahlrag", "omvmjkqqnobvnzkn", "lcwmeibxhhlxnkzv", "uiaeroqfbvlazegs", "twniyldyuonfyzqw", "wgjkmsbwgfotdabi", "hnomamxoxvrzvtew", "ycrcfavikkrxxfgw", "isieyodknagzhaxy", "mgzdqwikzullzyco", "mumezgtxjrrejtrs", "nwmwjcgrqiwgfqel", "wjgxmebfmyjnxyyp", "durpspyljdykvzxf", "zuslbrpooyetgafh", "kuzrhcjwbdouhyme", "wyxuvbciodscbvfm", "kbnpvuqwmxwfqtqe", "zddzercqogdpxmft", "sigrdchxtgavzzjh", "lznjolnorbuddgcs", "ycnqabxlcajagwbt", "bnaudeaexahdgxsj", "rlnykxvoctfwanms", "jngyetkoplrstfzt", "tdpxknwacksotdub", "yutqgssfoptvizgr", "lzmqnxeqjfnsxmsa", "iqpgfsfmukovsdgu", "qywreehbidowtjyz", "iozamtgusdctvnkw", "ielmujhtmynlwcfd", "hzxnhtbnmmejlkyf", "ftbslbzmiqkzebtd", "bcwdqgiiizmohack", "dqhfkzeddjzbdlxu", "mxopokqffisxosci", "vciatxhtuechbylk", "khtkhcvelidjdena", "blatarwzfqcapkdt", "elamngegnczctcck", "xeicefdbwrxhuxuf", "sawvdhjoeahlgcdr", "kmdcimzsfkdfpnir", "axjayzqlosrduajb", "mfhzreuzzumvoggr", "iqlbkbhrkptquldb", "xcvztvlshiefuhgb", "pkvwyqmyoazocrio", "ajsxkdnerbmhyxaj", "tudibgsbnpnizvsi", "cxuiydkgdccrqvkh", "cyztpjesdzmbcpot", "nnazphxpanegwitx", "uphymczbmjalmsct", "yyxiwnlrogyzwqmg", "gmqwnahjvvdyhnfa", "utolskxpuoheugyl", "mseszdhyzoyavepd", "ycqknvbuvcjfgmlc", "sknrxhxbfpvpeorn", "zqxqjetooqcodwml", "sesylkpvbndrdhsy", "fryuxvjnsvnjrxlw", "mfxusewqurscujnu", "mbitdjjtgzchvkfv", "ozwlyxtaalxofovd", "wdqcduaykxbunpie", "rlnhykxiraileysk", "wgoqfrygttlamobg", "kflxzgxvcblkpsbz", "tmkisflhativzhde", "owsdrfgkaamogjzd", "gaupjkvkzavhfnes", "wknkurddcknbdleg", "lltviwincmbtduap", "qwzvspgbcksyzzmb", "ydzzkumecryfjgnk", "jzvmwgjutxoysaam", "icrwpyhxllbardkr", "jdopyntshmvltrve", "afgkigxcuvmdbqou", "mfzzudntmvuyhjzt", "duxhgtwafcgrpihc", "tsnhrkvponudumeb", "sqtvnbeiigdzbjgv", "eczmkqwvnsrracuo", "mhehsgqwiczaiaxv", "kaudmfvifovrimpd", "lupikgivechdbwfr", "mwaaysrndiutuiqx", "aacuiiwgaannunmm", "tjqjbftaqitukwzp", "lrcqyskykbjpaekn", "lirrvofbcqpjzxmr", "jurorvzpplyelfml", "qonbllojmloykjqe", "sllkzqujfnbauuqp", "auexjwsvphvikali", "usuelbssqmbrkxyc", "wyuokkfjexikptvv", "wmfedauwjgbrgytl", "sfwvtlzzebxzmuvw", "rdhqxuechjsjcvaf", "kpavhqkukugocsxu", "ovnjtumxowbxduts", "zgerpjufauptxgat", "pevvnzjfwhjxdoxq", "pmmfwxajgfziszcs", "difmeqvaghuitjhs", "icpwjbzcmlcterwm", "ngqpvhajttxuegyh", "mosjlqswdngwqsmi", "frlvgpxrjolgodlu", "eazwgrpcxjgoszeg", "bbtsthgkjrpkiiyk", "tjonoglufuvsvabe", "xhkbcrofytmbzrtk", "kqftfzdmpbxjynps", "kmeqpocbnikdtfyv", "qjjymgqxhnjwxxhp", "dmgicrhgbngdtmjt", "zdxrhdhbdutlawnc", "afvoekuhdboxghvx", "hiipezngkqcnihty", "bbmqgheidenweeov", "suprgwxgxwfsgjnx", "adeagikyamgqphrj", "zzifqinoeqaorjxg", "adhgppljizpaxzld", "lvxyieypvvuqjiyc", "nljoakatwwwoovzn", "fcrkfxclcacshhmx", "ownnxqtdhqbgthch", "lmfylrcdmdkgpwnj", "hlwjfbvlswbzpbjr", "mkofhdtljdetcyvp", "synyxhifbetzarpo", "agnggugngadrcxoc", "uhttadmdmhidpyjw", "ohfwjfhunalbubpr", "pzkkkkwrlvxiuysn", "kmidbxmyzkjrwjhu", "egtitdydwjxmajnw", "civoeoiuwtwgbqqs", "dfptsguzfinqoslk", "tdfvkreormspprer", "zvnvbrmthatzztwi", "ffkyddccrrfikjde", "hrrmraevdnztiwff", "qaeygykcpbtjwjbr", "purwhitkmrtybslh", "qzziznlswjaussel", "dfcxkvdpqccdqqxj", "tuotforulrrytgyn", "gmtgfofgucjywkev", "wkyoxudvdkbgpwhd", "qbvktvfvipftztnn", "otckgmojziezmojb", "inxhvzbtgkjxflay", "qvxapbiatuudseno", "krpvqosbesnjntut", "oqeukkgjsfuqkjbb", "prcjnyymnqwqksiz", "vuortvjxgckresko", "orqlyobvkuwgathr", "qnpyxlnazyfuijox", "zwlblfkoklqmqzkw", "hmwurwtpwnrcsanl", "jzvxohuakopuzgpf", "sfcpnxrviphhvxmx", "qtwdeadudtqhbely", "dbmkmloasqphnlgj", "olylnjtkxgrubmtk", "nxsdbqjuvwrrdbpq", "wbabpirnpcsmpipw", "hjnkyiuxpqrlvims", "enzpntcjnxdpuqch", "vvvqhlstzcizyimn", "triozhqndbttglhv", "fukvgteitwaagpzx", "uhcvukfbmrvskpen", "tizcyupztftzxdmt", "vtkpnbpdzsaluczz", "wodfoyhoekidxttm", "otqocljrmwfqbxzu", "linfbsnfvixlwykn", "vxsluutrwskslnye", "zbshygtwugixjvsi", "zdcqwxvwytmzhvoo", "wrseozkkcyctrmei", "fblgtvogvkpqzxiy", "opueqnuyngegbtnf", "qxbovietpacqqxok", "zacrdrrkohfygddn", "gbnnvjqmkdupwzpq", "qgrgmsxeotozvcak", "hnppukzvzfmlokid", "dzbheurndscrrtcl", "wbgdkadtszebbrcw", "fdmzppzphhpzyuiz", "bukomunhrjrypohj", "ohodhelegxootqbj", "rsplgzarlrknqjyh", "punjjwpsxnhpzgvu", "djdfahypfjvpvibm", "mlgrqsmhaozatsvy", "xwktrgyuhqiquxgn", "wvfaoolwtkbrisvf", "plttjdmguxjwmeqr", "zlvvbwvlhauyjykw", "cigwkbyjhmepikej", "masmylenrusgtyxs", "hviqzufwyetyznze", "nzqfuhrooswxxhus", "pdbdetaqcrqzzwxf", "oehmvziiqwkzhzib", "icgpyrukiokmytoy", "ooixfvwtiafnwkce", "rvnmgqggpjopkihs", "wywualssrmaqigqk", "pdbvflnwfswsrirl", "jeaezptokkccpbuj", "mbdwjntysntsaaby", "ldlgcawkzcwuxzpz", "lwktbgrzswbsweht", "ecspepmzarzmgpjm", "qmfyvulkmkxjncai", "izftypvwngiukrns", "zgmnyjfeqffbooww", "nyrkhggnprhedows", "yykzzrjmlevgffah", "mavaemfxhlfejfki", "cmegmfjbkvpncqwf", "zxidlodrezztcrij", "fseasudpgvgnysjv", "fupcimjupywzpqzp", "iqhgokavirrcvyys", "wjmkcareucnmfhui", "nftflsqnkgjaexhq", "mgklahzlcbapntgw", "kfbmeavfxtppnrxn", "nuhyvhknlufdynvn", "nviogjxbluwrcoec", "tyozixxxaqiuvoys", "kgwlvmvgtsvxojpr", "moeektyhyonfdhrb", "kahvevmmfsmiiqex", "xcywnqzcdqtvhiwd", "fnievhiyltbvtvem", "jlmndqufirwgtdxd", "muypbfttoeelsnbs", "rypxzbnujitfwkou", "ubmmjbznskildeoj", "ofnmizdeicrmkjxp", "rekvectjbmdnfcib", "yohrojuvdexbctdh", "gwfnfdeibynzjmhz", "jfznhfcqdwlpjull", "scrinzycfhwkmmso", "mskutzossrwoqqsi", "rygoebkzgyzushhr", "jpjqiycflqkexemx", "arbufysjqmgaapnl", "dbjerflevtgweeoj", "snybnnjlmwjvhois", "fszuzplntraprmbj", "mkvaatolvuggikvg", "zpuzuqygoxesnuyc", "wnpxvmxvllxalulm", "eivuuafkvudeouwy", "rvzckdyixetfuehr", "qgmnicdoqhveahyx", "miawwngyymshjmpj", "pvckyoncpqeqkbmx", "llninfenrfjqxurv", "kzbjnlgsqjfuzqtp", "rveqcmxomvpjcwte", "bzotkawzbopkosnx", "ktqvpiribpypaymu", "wvlzkivbukhnvram", "uohntlcoguvjqqdo", "ajlsiksjrcnzepkt", "xsqatbldqcykwusd", "ihbivgzrwpmowkop", "vfayesfojmibkjpb", "uaqbnijtrhvqxjtb", "hhovshsfmvkvymba", "jerwmyxrfeyvxcgg", "hncafjwrlvdcupma", "qyvigggxfylbbrzt", "hiiixcyohmvnkpgk", "mmitpwopgxuftdfu", "iaxderqpceboixoa", "zodfmjhuzhnsqfcb", "sthtcbadrclrazsi", "bkkkkcwegvypbrio", "wmpcofuvzemunlhj", "gqwebiifvqoeynro", "juupusqdsvxcpsgv", "rbhdfhthxelolyse", "kjimpwnjfrqlqhhz", "rcuigrjzarzpjgfq", "htxcejfyzhydinks", "sxucpdxhvqjxxjwf", "omsznfcimbcwaxal", "gufmtdlhgrsvcosb", "bssshaqujtmluerz", "uukotwjkstgwijtr", "kbqkneobbrdogrxk", "ljqopjcjmelgrakz", "rwtfnvnzryujwkfb", "dedjjbrndqnilbeh", "nzinsxnpptzagwlb", "lwqanydfirhnhkxy", "hrjuzfumbvfccxno", "okismsadkbseumnp", "sfkmiaiwlktxqvwa", "hauwpjjwowbunbjj", "nowkofejwvutcnui", "bqzzppwoslaeixro", "urpfgufwbtzenkpj", "xgeszvuqwxeykhef", "yxoldvkyuikwqyeq", "onbbhxrnmohzskgg", "qcikuxakrqeugpoa", "lnudcqbtyzhlpers", "nxduvwfrgzaailgl", "xniuwvxufzxjjrwz", "ljwithcqmgvntjdj", "awkftfagrfzywkhs", "uedtpzxyubeveuek", "bhcqdwidbjkqqhzl", "iyneqjdmlhowwzxx", "kvshzltcrrururty", "zgfpiwajegwezupo", "tkrvyanujjwmyyri", "ercsefuihcmoaiep", "ienjrxpmetinvbos", "jnwfutjbgenlipzq", "bgohjmrptfuamzbz", "rtsyamajrhxbcncw", "tfjdssnmztvbnscs", "bgaychdlmchngqlp", "kfjljiobynhwfkjo", "owtdxzcpqleftbvn", "ltjtimxwstvzwzjj", "wbrvjjjajuombokf", "zblpbpuaqbkvsxye", "gwgdtbpnlhyqspdi", "abipqjihjqfofmkx", "nlqymnuvjpvvgova", "avngotmhodpoufzn", "qmdyivtzitnrjuae", "xfwjmqtqdljuerxi", "csuellnlcyqaaamq", "slqyrcurcyuoxquo", "dcjmxyzbzpohzprl", "uqfnmjwniyqgsowb", "rbmxpqoblyxdocqc", "ebjclrdbqjhladem", "ainnfhxnsgwqnmyo", "eyytjjwhvodtzquf", "iabjgmbbhilrcyyp", "pqfnehkivuelyccc", "xgjbyhfgmtseiimt", "jwxyqhdbjiqqqeyy", "gxsbrncqkmvaryln", "vhjisxjkinaejytk", "seexagcdmaedpcvh", "lvudfgrcpjxzdpvd", "fxtegyrqjzhmqean", "dnoiseraqcoossmc", "nwrhmwwbykvwmgep", "udmzskejvizmtlce", "hbzvqhvudfdlegaa", "cghmlfqejbxewskv", "bntcmjqfwomtbwsb", "qezhowyopjdyhzng", "todzsocdkgfxanbz", "zgjkssrjlwxuhwbk", "eibzljqsieriyrzr", "wamxvzqyycrxotjp", "epzvfkispwqynadu", "dwlpfhtrafrxlyie", "qhgzujhgdruowoug", "girstvkahaemmxvh", "baitcrqmxhazyhbl", "xyanqcchbhkajdmc", "gfvjmmcgfhvgnfdq", "tdfdbslwncbnkzyz", "jojuselkpmnnbcbb", "hatdslkgxtqpmavj", "dvelfeddvgjcyxkj", "gnsofhkfepgwltse", "mdngnobasfpewlno", "qssnbcyjgmkyuoga", "glvcmmjytmprqwvn", "gwrixumjbcdffsdl", "lozravlzvfqtsuiq", "sicaflbqdxbmdlch", "inwfjkyyqbwpmqlq", "cuvszfotxywuzhzi", "igfxyoaacoarlvay", "ucjfhgdmnjvgvuni", "rvvkzjsytqgiposh", "jduinhjjntrmqroz", "yparkxbgsfnueyll", "lyeqqeisxzfsqzuj", "woncskbibjnumydm", "lltucklragtjmxtl", "ubiyvmyhlesfxotj", "uecjseeicldqrqww", "xxlxkbcthufnjbnm", "lhqijovvhlffpxga", "fzdgqpzijitlogjz", "efzzjqvwphomxdpd", "jvgzvuyzobeazssc", "hejfycgxywfjgbfw", "yhjjmvkqfbnbliks", "sffvfyywtlntsdsz", "dwmxqudvxqdenrur", "asnukgppdemxrzaz", "nwqfnumblwvdpphx", "kqsmkkspqvxzuket", "cpnraovljzqiquaz", "qrzgrdlyyzbyykhg", "opoahcbiydyhsmqe", "hjknnfdauidjeydr", "hczdjjlygoezadow", "rtflowzqycimllfv", "sfsrgrerzlnychhq", "bpahuvlblcolpjmj", "albgnjkgmcrlaicl", "pijyqdhfxpaxzdex", "eeymiddvcwkpbpux", "rqwkqoabywgggnln", "vckbollyhgbgmgwh", "ylzlgvnuvpynybkm", "hpmbxtpfosbsjixt", "ocebeihnhvkhjfqz", "tvctyxoujdgwayze", "efvhwxtuhapqxjen", "rusksgefyidldmpo", "nkmtjvddfmhirmzz", "whvtsuadwofzmvrt", "iiwjqvsdxudhdzzk", "gucirgxaxgcassyo", "rmhfasfzexeykwmr", "hynlxcvsbgosjbis", "huregszrcaocueen", "pifezpoolrnbdqtv", "unatnixzvdbqeyox", "xtawlpduxgacchfe", "bdvdbflqfphndduf", "xtdsnjnmzccfptyt", "nkhsdkhqtzqbphhg", "aqcubmfkczlaxiyb", "moziflxpsfubucmv", "srdgnnjtfehiimqx", "pwfalehdfyykrohf", "sysxssmvewyfjrve", "brsemdzosgqvvlxe", "bimbjoshuvflkiat", "hkgjasmljkpkwwku", "sbnmwjvodygobpqc", "bbbqycejueruihhd", "corawswvlvneipyc", "gcyhknmwsczcxedh", "kppakbffdhntmcqp", "ynulzwkfaemkcefp", "pyroowjekeurlbii", "iwksighrswdcnmxf", "glokrdmugreygnsg", "xkmvvumnfzckryop", "aesviofpufygschi", "csloawlirnegsssq", "fkqdqqmlzuxbkzbc", "uzlhzcfenxdfjdzp", "poaaidrktteusvyf", "zrlyfzmjzfvivcfr", "qwjulskbniitgqtx", "gjeszjksbfsuejki", "vczdejdbfixbduaq", "knjdrjthitjxluth", "jweydeginrnicirl", "bottrfgccqhyycsl", "eiquffofoadmbuhk", "lbqfutmzoksscswf", "xfmdvnvfcnzjprba", "uvugkjbkhlaoxmyx", "wadlgtpczgvcaqqv", "inzrszbtossflsxk", "dbzbtashaartczrj", "qbjiqpccefcfkvod", "hluujmokjywotvzy", "thwlliksfztcmwzh", "arahybspdaqdexrq", "nuojrmsgyipdvwyx", "hnajdwjwmzattvst", "sulcgaxezkprjbgu", "rjowuugwdpkjtypw", "oeugzwuhnrgiaqga", "wvxnyymwftfoswij", "pqxklzkjpcqscvde", "tuymjzknntekglqj", "odteewktugcwlhln", "exsptotlfecmgehc", "eeswfcijtvzgrqel", "vjhrkiwmunuiwqau", "zhlixepkeijoemne", "pavfsmwesuvebzdd", "jzovbklnngfdmyws", "nbajyohtzfeoiixz", "ciozmhrsjzrwxvhz", "gwucrxieqbaqfjuv", "uayrxrltnohexawc", "flmrbhwsfbcquffm", "gjyabmngkitawlxc", "rwwtggvaygfbovhg", "xquiegaisynictjq", "oudzwuhexrwwdbyy", "lengxmguyrwhrebb", "uklxpglldbgqsjls", "dbmvlfeyguydfsxq", "zspdwdqcrmtmdtsc", "mqfnzwbfqlauvrgc", "amcrkzptgacywvhv", "ndxmskrwrqysrndf", "mwjyhsufeqhwisju", "srlrukoaenyevykt", "tnpjtpwawrxbikct", "geczalxmgxejulcv", "tvkcbqdhmuwcxqci", "tiovluvwezwwgaox", "zrjhtbgajkjqzmfo", "vcrywduwsklepirs", "lofequdigsszuioy", "wxsdzomkjqymlzat", "iabaczqtrfbmypuy", "ibdlmudbajikcncr", "rqcvkzsbwmavdwnv", "ypxoyjelhllhbeog", "fdnszbkezyjbttbg", "uxnhrldastpdjkdz", "xfrjbehtxnlyzcka", "omjyfhbibqwgcpbv", "eguucnoxaoprszmp", "xfpypldgcmcllyzz", "aypnmgqjxjqceelv", "mgzharymejlafvgf", "tzowgwsubbaigdok", "ilsehjqpcjwmylxc", "pfmouwntfhfnmrwk", "csgokybgdqwnduwp", "eaxwvxvvwbrovypz", "nmluqvobbbmdiwwb", "lnkminvfjjzqbmio", "mjiiqzycqdhfietz", "towlrzriicyraevq", "obiloewdvbrsfwjo", "lmeooaajlthsfltw", "ichygipzpykkesrw", "gfysloxmqdsfskvt", "saqzntehjldvwtsx", "pqddoemaufpfcaew", "mjrxvbvwcreaybwe", "ngfbrwfqnxqosoai", "nesyewxreiqvhald", "kqhqdlquywotcyfy", "liliptyoqujensfi", "nsahsaxvaepzneqq", "zaickulfjajhctye", "gxjzahtgbgbabtht", "koxbuopaqhlsyhrp", "jhzejdjidqqtjnwe", "dekrkdvprfqpcqki", "linwlombdqtdeyop", "dvckqqbnigdcmwmx", "yaxygbjpzkvnnebv", "rlzkdkgaagmcpxah", "cfzuyxivtknirqvt", "obivkajhsjnrxxhn", "lmjhayymgpseuynn", "bbjyewkwadaipyju", "lmzyhwomfypoftuu", "gtzhqlgltvatxack", "jfflcfaqqkrrltgq", "txoummmnzfrlrmcg", "ohemsbfuqqpucups", "imsfvowcbieotlok", "tcnsnccdszxfcyde", "qkcdtkwuaquajazz", "arcfnhmdjezdbqku", "srnocgyqrlcvlhkb", "mppbzvfmcdirbyfw", "xiuarktilpldwgwd", "ypufwmhrvzqmexpc", "itpdnsfkwgrdujmj", "cmpxnodtsswkyxkr", "wayyxtjklfrmvbfp", "mfaxphcnjczhbbwy", "sjxhgwdnqcofbdra", "pnxmujuylqccjvjm", "ivamtjbvairwjqwl", "deijtmzgpfxrclss", "bzkqcaqagsynlaer", "tycefobvxcvwaulz", "ctbhnywezxkdsswf", "urrxxebxrthtjvib", "fpfelcigwqwdjucv", "ngfcyyqpqulwcphb", "rltkzsiipkpzlgpw", "qfdsymzwhqqdkykc", "balrhhxipoqzmihj", "rnwalxgigswxomga", "ghqnxeogckshphgr", "lyyaentdizaumnla", "exriodwfzosbeoib", "speswfggibijfejk", "yxmxgfhvmshqszrq", "hcqhngvahzgawjga", "qmhlsrfpesmeksur", "eviafjejygakodla", "kvcfeiqhynqadbzv", "fusvyhowslfzqttg", "girqmvwmcvntrwau", "yuavizroykfkdekz", "jmcwohvmzvowrhxf", "kzimlcpavapynfue", "wjudcdtrewfabppq", "yqpteuxqgbmqfgxh", "xdgiszbuhdognniu", "jsguxfwhpftlcjoh", "whakkvspssgjzxre", "ggvnvjurlyhhijgm", "krvbhjybnpemeptr", "pqedgfojyjybfbzr", "jzhcrsgmnkwwtpdo", "yyscxoxwofslncmp", "gzjhnxytmyntzths", "iteigbnqbtpvqumi", "zjevfzusnjukqpfw", "xippcyhkfuounxqk", "mcnhrcfonfdgpkyh", "pinkcyuhjkexbmzj", "lotxrswlxbxlxufs", "fmqajrtoabpckbnu", "wfkwsgmcffdgaqxg", "qfrsiwnohoyfbidr", "czfqbsbmiuyusaqs", "ieknnjeecucghpoo", "cevdgqnugupvmsge", "gjkajcyjnxdrtuvr", "udzhrargnujxiclq", "zqqrhhmjwermjssg", "ggdivtmgoqajydzz", "wnpfsgtxowkjiivl", "afbhqawjbotxnqpd", "xjpkifkhfjeqifdn", "oyfggzsstfhvticp", "kercaetahymeawxy", "khphblhcgmbupmzt", "iggoqtqpvaebtiol", "ofknifysuasshoya", "qxuewroccsbogrbv", "apsbnbkiopopytgu", "zyahfroovfjlythh", "bxhjwfgeuxlviydq", "uvbhdtvaypasaswa", "qamcjzrmesqgqdiz", "hjnjyzrxntiycyel", "wkcrwqwniczwdxgq", "hibxlvkqakusswkx", "mzjyuenepwdgrkty", "tvywsoqslfsulses", "jqwcwuuisrclircv", "xanwaoebfrzhurct", "ykriratovsvxxasf", "qyebvtqqxbjuuwuo", "telrvlwvriylnder", "acksrrptgnhkeiaa", "yemwfjhiqlzsvdxf", "banrornfkcymmkcc", "ytbhxvaeiigjpcgm", "crepyazgxquposkn", "xlqwdrytzwnxzwzv", "xtrbfbwopxscftps", "kwbytzukgseeyjla", "qtfdvavvjogybxjg", "ytbmvmrcxwfkgvzw", "nbscbdskdeocnfzr", "sqquwjbdxsxhcseg", "ewqxhigqcgszfsuw", "cvkyfcyfmubzwsee", "dcoawetekigxgygd", "ohgqnqhfimyuqhvi", "otisopzzpvnhctte", "bauieohjejamzien", "ewnnopzkujbvhwce", "aeyqlskpaehagdiv", "pncudvivwnnqspxy", "ytugesilgveokxcg", "zoidxeelqdjesxpr", "ducjccsuaygfchzj", "smhgllqqqcjfubfc", "nlbyyywergronmir", "prdawpbjhrzsbsvj", "nmgzhnjhlpcplmui", "eflaogtjghdjmxxz", "qolvpngucbkprrdc", "ixywxcienveltgho", "mwnpqtocagenkxut", "iskrfbwxonkguywx", "ouhtbvcaczqzmpua", "srewprgddfgmdbao", "dyufrltacelchlvu", "czmzcbrkecixuwzz", "dtbeojcztzauofuk", "prrgoehpqhngfgmw", "baolzvfrrevxsyke", "zqadgxshwiarkzwh", "vsackherluvurqqj", "surbpxdulvcvgjbd", "wqxytarcxzgxhvtx", "vbcubqvejcfsgrac", "zqnjfeapshjowzja", "hekvbhtainkvbynx", "knnugxoktxpvoxnh", "knoaalcefpgtvlwm", "qoakaunowmsuvkus", "ypkvlzcduzlezqcb", "ujhcagawtyepyogh", "wsilcrxncnffaxjf", "gbbycjuscquaycrk", "aduojapeaqwivnly", "ceafyxrakviagcjy", "nntajnghicgnrlst", "vdodpeherjmmvbje", "wyyhrnegblwvdobn", "xlfurpghkpbzhhif", "xyppnjiljvirmqjo", "kglzqahipnddanpi", "omjateouxikwxowr", "ocifnoopfglmndcx", "emudcukfbadyijev", "ooktviixetfddfmh", "wtvrhloyjewdeycg", "cgjncqykgutfjhvb", "nkwvpswppeffmwad", "hqbcmfhzkxmnrivg", "mdskbvzguxvieilr", "anjcvqpavhdloaqh", "erksespdevjylenq", "fadxwbmisazyegup", "iyuiffjmcaahowhj", "ygkdezmynmltodbv", "fytneukxqkjattvh", "woerxfadbfrvdcnz", "iwsljvkyfastccoa", "movylhjranlorofe", "drdmicdaiwukemep", "knfgtsmuhfcvvshg", "ibstpbevqmdlhajn", "tstwsswswrxlzrqs", "estyydmzothggudf", "jezogwvymvikszwa", "izmqcwdyggibliet", "nzpxbegurwnwrnca", "kzkojelnvkwfublh", "xqcssgozuxfqtiwi", "tcdoigumjrgvczfv", "ikcjyubjmylkwlwq", "kqfivwystpqzvhan", "bzukgvyoqewniivj", "iduapzclhhyfladn", "fbpyzxdfmkrtfaeg", "yzsmlbnftftgwadz"] let badStrings = ["ab","cd","pq","xy"] extension String { func isNiceV1() -> Bool { for badString in badStrings { if self.containsString(badString) { return false } } var vowelCount = 0 let vowels = "aeiou" var hasDouble = false var hasVowels = false for (index,letter) in characters.enumerate() { if index+1 < characters.count && letter == characters[characters.startIndex.advancedBy(index+1)] { hasDouble = true } if vowels.containsString("\(letter)") { vowelCount += 1 if vowelCount >= 3 { hasVowels = true } } } return hasDouble && hasVowels } func isNiceV2() -> Bool { var hasDoubles = false var hasPattern = false for (index,letter) in characters.enumerate() { guard index+1 < characters.count else { break } let nextCharacter = characters[characters.startIndex.advancedBy(index+1)] let testString = "\(letter)\(nextCharacter)" for subIndex in (index+2)..<characters.count { guard subIndex+1 < characters.count else { break } let nextNext = characters[characters.startIndex.advancedBy(subIndex)] let nextNextNext = characters[characters.startIndex.advancedBy(subIndex+1)] let testString2 = "\(nextNext)\(nextNextNext)" if testString == testString2 { hasDoubles = true } } guard index+2 < characters.count else { break } if letter == characters[characters.startIndex.advancedBy(index+2)] { hasPattern = true } } return hasDoubles && hasPattern } } var count = 0 let input2 = ["aataa"] let nicewords = input.filter { $0.isNiceV2() } nicewords.count
9b9cce364c813ebea837dd465a697429
19.522099
110
0.768475
false
false
false
false
benlangmuir/swift
refs/heads/master
SwiftCompilerSources/Sources/Optimizer/DataStructures/BasicBlockRange.swift
apache-2.0
2
//===--- BasicBlockRange.swift - a range of basic blocks ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SIL /// A range of basic blocks. /// /// The `BasicBlockRange` defines a range from a dominating "begin" block to one or more "end" blocks. /// The range is "exclusive", which means that the "end" blocks are not part of the range. /// /// The `BasicBlockRange` is in the same spirit as a linear range, but as the control flow is a graph /// and not a linear list, there can be "exit" blocks from within the range. /// /// One or more "potential" end blocks can be inserted. /// Though, not all inserted blocks end up as "end" blocks. /// /// There are several kind of blocks: /// * begin: it is a single block which dominates all blocks of the range /// * range: all blocks from which there is a path from the begin block to any of the end blocks /// * ends: all inserted blocks which are at the end of the range /// * exits: all successor blocks of range blocks which are not in the range themselves /// * interiors: all inserted blocks which are not end blocks. /// /// In the following example, let's assume `B` is the begin block and `I1`, `I2` and `I3` /// were inserted as potential end blocks: /// /// B /// / \ /// I1 I2 /// / \ /// I3 X /// /// Then `I1` and `I3` are "end" blocks. `I2` is an interior block and `X` is an exit block. /// The range consists of `B` and `I2`. Note that the range does not include `I1` and `I3` /// because it's an _exclusive_ range. /// /// This type should be a move-only type, but unfortunately we don't have move-only /// types yet. Therefore it's needed to call `deinitialize()` explicitly to /// destruct this data structure, e.g. in a `defer {}` block. struct BasicBlockRange : CustomStringConvertible, CustomReflectable { /// The dominating begin block. let begin: BasicBlock /// The inclusive range, i.e. the exclusive range plus the end blocks. private(set) var inclusiveRange: Stack<BasicBlock> /// The exclusive range, i.e. not containing the end blocks. var range: LazyFilterSequence<Stack<BasicBlock>> { inclusiveRange.lazy.filter { contains($0) } } /// All inserted blocks. private(set) var inserted: Stack<BasicBlock> private var wasInserted: BasicBlockSet private var inExclusiveRange: BasicBlockSet private var worklist: BasicBlockWorklist init(begin: BasicBlock, _ context: PassContext) { self.begin = begin self.inclusiveRange = Stack(context) self.inserted = Stack(context) self.wasInserted = BasicBlockSet(context) self.inExclusiveRange = BasicBlockSet(context) self.worklist = BasicBlockWorklist(context) worklist.pushIfNotVisited(begin) } /// Insert a potential end block. mutating func insert(_ block: BasicBlock) { if wasInserted.insert(block) { inserted.append(block) } worklist.pushIfNotVisited(block) while let b = worklist.pop() { inclusiveRange.append(b) if b != begin { for pred in b.predecessors { worklist.pushIfNotVisited(pred) inExclusiveRange.insert(pred) } } } } /// Insert a sequence of potential end blocks. mutating func insert<S: Sequence>(contentsOf other: S) where S.Element == BasicBlock { for block in other { insert(block) } } /// Returns true if the exclusive range contains `block`. func contains(_ block: BasicBlock) -> Bool { inExclusiveRange.contains(block) } /// Returns true if the inclusive range contains `block`. func inclusiveRangeContains (_ block: BasicBlock) -> Bool { worklist.hasBeenPushed(block) } /// Returns true if the range is valid and that's iff the begin block dominates all blocks of the range. var isValid: Bool { let entry = begin.function.entryBlock return begin == entry || // If any block in the range is not dominated by `begin`, the range propagates back to the entry block. !inclusiveRangeContains(entry) } /// Returns the end blocks. var ends: LazyFilterSequence<Stack<BasicBlock>> { inserted.lazy.filter { !contains($0) } } /// Returns the exit blocks. var exits: LazySequence<FlattenSequence< LazyMapSequence<LazyFilterSequence<Stack<BasicBlock>>, LazyFilterSequence<SuccessorArray>>>> { range.flatMap { $0.successors.lazy.filter { !inclusiveRangeContains($0) || $0 == begin } } } /// Returns the interior blocks. var interiors: LazyFilterSequence<Stack<BasicBlock>> { inserted.lazy.filter { contains($0) && $0 != begin } } var description: String { return (isValid ? "" : "<invalid>\n") + """ begin: \(begin.name) range: \(range) inclrange: \(inclusiveRange) ends: \(ends) exits: \(exits) interiors: \(interiors) """ } var customMirror: Mirror { Mirror(self, children: []) } /// TODO: once we have move-only types, make this a real deinit. mutating func deinitialize() { worklist.deinitialize() inExclusiveRange.deinitialize() wasInserted.deinitialize() inserted.deinitialize() inclusiveRange.deinitialize() } }
ae9e5740323e05d129327aa7742e909a
33.722222
109
0.658489
false
false
false
false
bykoianko/omim
refs/heads/master
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/UGC/UGCYourReviewCell.swift
apache-2.0
6
@objc(MWMUGCYourReviewCell) final class UGCYourReviewCell: MWMTableViewCell { private enum Config { static let defaultReviewBottomOffset: CGFloat = 16 } @IBOutlet private weak var titleLabel: UILabel! { didSet { titleLabel.font = UIFont.bold14() titleLabel.textColor = UIColor.blackPrimaryText() titleLabel.text = L("placepage_reviews_your_comment") } } @IBOutlet private weak var dateLabel: UILabel! { didSet { dateLabel.font = UIFont.regular12() dateLabel.textColor = UIColor.blackSecondaryText() } } @IBOutlet private weak var reviewLabel: ExpandableTextView! { didSet { reviewLabel.textFont = UIFont.regular14() reviewLabel.textColor = UIColor.blackPrimaryText() reviewLabel.expandText = L("placepage_more_button") reviewLabel.expandTextColor = UIColor.linkBlue() } } @IBOutlet private weak var reviewBottomOffset: NSLayoutConstraint! @IBOutlet private weak var ratingCollectionView: UICollectionView! { didSet { ratingCollectionView.register(cellClass: UGCSummaryRatingStarsCell.self) } } private var yourReview: UGCYourReview! override var frame: CGRect { didSet { if frame.size != oldValue.size { updateCollectionView() } } } @objc func config(yourReview: UGCYourReview, onUpdate: @escaping () -> Void) { dateLabel.text = yourReview.date self.yourReview = yourReview reviewLabel.text = yourReview.text reviewBottomOffset.constant = yourReview.text.isEmpty ? 0 : Config.defaultReviewBottomOffset reviewLabel.onUpdate = onUpdate updateCollectionView() isSeparatorHidden = true } override func didMoveToSuperview() { super.didMoveToSuperview() updateCollectionView() } private func updateCollectionView() { DispatchQueue.main.async { self.ratingCollectionView.reloadData() } } } extension UGCYourReviewCell: UICollectionViewDataSource { func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int { return yourReview?.ratings.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withCellClass: UGCSummaryRatingStarsCell.self, indexPath: indexPath) as! UGCSummaryRatingStarsCell cell.config(rating: yourReview!.ratings[indexPath.item]) return cell } }
748f7504fcf58d347e20d302c8b4bfb2
29.5875
148
0.724969
false
false
false
false
RushingTwist/SwiftExamples
refs/heads/master
Swifttttt/Swifttttt/SplitViewController/ListViewController.swift
apache-2.0
1
// // ListViewController.swift // Swifttttt // // Created by 王福林 on 2018/9/27. // Copyright © 2018年 lynn. All rights reserved. // import UIKit class ListViewController: UITableViewController { let links = ["https://www.baidu.com", "https://www.github.com"] override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .red title = "Master" navigationItem.leftBarButtonItem = UIBarButtonItem(title: "❎", style: .plain, target: self, action: #selector(back)) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellId") } @objc func back() { dismiss(animated: true, completion: nil) } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return links.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) cell.textLabel?.text = links[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selLink = links[indexPath.row] let detailVC = DetailViewController(urlStr: selLink) showDetailViewController(detailVC, sender: nil) } }
055f08ead21008406afe163cd97bbdaa
28
124
0.654483
false
false
false
false
narner/AudioKit
refs/heads/master
AudioKit/Common/Internals/Audio File/AKAudioFile+Processing.swift
mit
1
// // AKAudioFile+Processing.swift // AudioKit // // Created by Laurent Veliscek, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // // // IMPORTANT: Any AKAudioFile process will output a .caf AKAudioFile // set with a PCM Linear Encoding (no compression) // But it can be applied to any readable file (.wav, .m4a, .mp3...) // extension AKAudioFile { /// Normalize an AKAudioFile to have a peak of newMaxLevel dB. /// /// - Parameters: /// - baseDir: where the file will be located, can be set to .resources, .documents or .temp /// - name: the name of the file without its extension (String). If none is given, a unique random name is used. /// - newMaxLevel: max level targeted as a Float value (default if 0 dB) /// /// - returns: An AKAudioFile, or nil if init failed. /// public func normalized(baseDir: BaseDirectory = .temp, name: String = UUID().uuidString, newMaxLevel: Float = 0.0 ) throws -> AKAudioFile { let level = self.maxLevel var outputFile = try AKAudioFile (writeIn: baseDir, name: name) if self.samplesCount == 0 { AKLog("WARNING AKAudioFile: cannot normalize an empty file") return try AKAudioFile(forReading: outputFile.url) } if level == Float.leastNormalMagnitude { AKLog("WARNING AKAudioFile: cannot normalize a silent file") return try AKAudioFile(forReading: outputFile.url) } let gainFactor = Float( pow(10.0, newMaxLevel / 20.0) / pow(10.0, level / 20.0)) let arrays = self.floatChannelData ?? [[]] var newArrays: [[Float]] = [] for array in arrays { let newArray = array.map { $0 * gainFactor } newArrays.append(newArray) } outputFile = try AKAudioFile(createFileFromFloats: newArrays, baseDir: baseDir, name: name) return try AKAudioFile(forReading: outputFile.url) } /// Returns an AKAudioFile with audio reversed (will playback in reverse from end to beginning). /// /// - Parameters: /// - baseDir: where the file will be located, can be set to .resources, .documents or .temp /// - name: the name of the file without its extension (String). If none is given, a unique random name is used. /// /// - Returns: An AKAudioFile, or nil if init failed. /// public func reversed(baseDir: BaseDirectory = .temp, name: String = UUID().uuidString ) throws -> AKAudioFile { var outputFile = try AKAudioFile (writeIn: baseDir, name: name) if self.samplesCount == 0 { return try AKAudioFile(forReading: outputFile.url) } let arrays = self.floatChannelData ?? [[]] var newArrays: [[Float]] = [] for array in arrays { newArrays.append(Array(array.reversed())) } outputFile = try AKAudioFile(createFileFromFloats: newArrays, baseDir: baseDir, name: name) return try AKAudioFile(forReading: outputFile.url) } /// Returns an AKAudioFile with appended audio data from another AKAudioFile. /// /// Notice that Source file and appended file formats must match. /// /// - Parameters: /// - file: an AKAudioFile that will be used to append audio from. /// - baseDir: where the file will be located, can be set to .Resources, .Documents or .Temp /// - name: the name of the file without its extension (String). If none is given, a unique random name is used. /// /// - Returns: An AKAudioFile, or nil if init failed. /// public func appendedBy(file: AKAudioFile, baseDir: BaseDirectory = .temp, name: String = UUID().uuidString) throws -> AKAudioFile { var sourceBuffer = self.pcmBuffer var appendedBuffer = file.pcmBuffer if self.fileFormat != file.fileFormat { AKLog("WARNING AKAudioFile.append: appended file should be of same format as source file") AKLog("WARNING AKAudioFile.append: trying to fix by converting files...") // We use extract method to get a .CAF file with the right format for appending // So sourceFile and appended File formats should match do { // First, we convert the source file to .CAF using extract() let convertedFile = try self.extracted() sourceBuffer = convertedFile.pcmBuffer AKLog("AKAudioFile.append: source file has been successfully converted") if convertedFile.fileFormat != file.fileFormat { do { // If still don't match we convert the appended file to .CAF using extract() let convertedAppendFile = try file.extracted() appendedBuffer = convertedAppendFile.pcmBuffer AKLog("AKAudioFile.append: appended file has been successfully converted") } catch let error as NSError { AKLog("ERROR AKAudioFile.append: cannot set append file format match source file format") throw error } } } catch let error as NSError { AKLog("ERROR AKAudioFile: Cannot convert sourceFile to .CAF") throw error } } // We check that both pcm buffers share the same format if appendedBuffer.format != sourceBuffer.format { AKLog("ERROR AKAudioFile.append: Couldn't match source file format with appended file format") let userInfo: [AnyHashable: Any] = [ NSLocalizedDescriptionKey: NSLocalizedString( "AKAudioFile append process Error", value: "Couldn't match source file format with appended file format", comment: ""), NSLocalizedFailureReasonErrorKey: NSLocalizedString( "AKAudioFile append process Error", value: "Couldn't match source file format with appended file format", comment: "") ] throw NSError(domain: "AKAudioFile ASync Process Unknown Error", code: 0, userInfo: userInfo as? [String : Any]) } let outputFile = try AKAudioFile (writeIn: baseDir, name: name) // Write the buffer in file do { try outputFile.write(from: sourceBuffer) } catch let error as NSError { AKLog("ERROR AKAudioFile: cannot writeFromBuffer Error: \(error)") throw error } do { try outputFile.write(from: appendedBuffer) } catch let error as NSError { AKLog("ERROR AKAudioFile: cannot writeFromBuffer Error: \(error)") throw error } return try AKAudioFile(forReading: outputFile.url) } /// Returns an AKAudioFile that will contain a range of samples from the current AKAudioFile /// /// - Parameters: /// - fromSample: the starting sampleFrame for extraction. /// - toSample: the ending sampleFrame for extraction /// - baseDir: where the file will be located, can be set to .Resources, .Documents or .Temp /// - name: the name of the file without its extension (String). If none is given, a unique random name is used. /// /// - Returns: An AKAudioFile, or nil if init failed. /// public func extracted(fromSample: Int64 = 0, toSample: Int64 = 0, baseDir: BaseDirectory = .temp, name: String = UUID().uuidString) throws -> AKAudioFile { let fixedFrom = abs(fromSample) let fixedTo: Int64 = toSample == 0 ? Int64(self.samplesCount) : min(toSample, Int64(self.samplesCount)) if fixedTo <= fixedFrom { AKLog("ERROR AKAudioFile: cannot extract, from must be less than to") throw NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotCreateFile, userInfo: nil) } let arrays = self.floatChannelData ?? [[]] var newArrays: [[Float]] = [] for array in arrays { let extract = Array(array[Int(fixedFrom)..<Int(fixedTo)]) newArrays.append(extract) } let newFile = try AKAudioFile(createFileFromFloats: newArrays, baseDir: baseDir, name: name) return try AKAudioFile(forReading: newFile.url) } }
d78d4d5664cc8cfb3de9101fdf10263f
42.167488
124
0.591236
false
false
false
false
SwiftStudies/OysterKit
refs/heads/master
Sources/OysterKit/Parser/Grammar.swift
bsd-2-clause
1
// Copyright (c) 2016, RED When Excited // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation /// Depricated, use `Grammar` @available(*,deprecated,message: "Parser has been depricated the rules used at initialization can be directly used as a Grammar. e.g. let parser = Parser(grammar:rules) becomes let parser = rules") public typealias Parser = Grammar /// Depricated, use `Grammar` @available(*,deprecated,message: "Replace with Grammar and use the rules property of Grammar instead of a grammar property of Language") public typealias Language = Grammar /** A language stores a set of grammar rules that can be used to parse `String`s. Extensions provide additional methods (such as parsing) that operate on these rules. */ public protocol Grammar{ /// The rules in the `Language`'s grammar var rules : [Rule] {get} } /// Extensions to an array where the elements are `Rule`s extension Array : Grammar where Element == Rule { public var rules: [Rule] { return self } } public extension Grammar { /** Creates an iterable stream of tokens using the supplied source and this `Grammar` It is very easy to create and iterate through a stream, for example: let source = "12+3+10" for token in try calculationGrammar.stream(source){ // Do something cool... } Streams are the easiest way to use a `Grammar`, and consume less memory and are in general faster (they certainly will never be slower). However you cannot easily navigate and reason about the stream, and only top level rules and tokens will be created. - Parameter source: The source to parse - Returns: An iterable stream of tokens **/ public func tokenize(_ source:String)->TokenStream{ return TokenStream(source, using: self) } /** Creates a `HomogenousTree` using the supplied grammar. A `HomogenousTree` captures the result of parsing hierarchically making it easy to manipulate the resultant data-structure. It is also possible to get more information about any parsing errors. For example: let source = "12+3+10" do { // Build the HomogenousTree let ast = try calculationGrammar.parse(source) // Prints the parsing tree print(ast) } catch let error as ProcessingError { print(error.debugDescription) } - Parameter source: The source to parse with the `Grammar` - Returns: A `HomogenousTree` **/ public func parse(_ source:String) throws ->HomogenousTree{ return try AbstractSyntaxTreeConstructor(with: source).build(using: self) } /** Builds the supplied source into a Heterogeneous representation (any Swift `Decodable` type). This is the most powerful application of a `Grammar` and leverages Swift's `Decoable` protocol. It is strongly recommended that you [read a little about that first](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types). Essentially each token in the grammar will be mapped to a `CodingKey`. You should first parse into a `HomogenousTree` to make sure your types and the hierarchy generated from your grammar align. If you want to automatically generate the `Decodable` types you can do this using [STLR](https://github.com/SwiftStudies/OysterKit/blob/master/Documentation/STLR.md) and [`stlrc`](https://github.com/SwiftStudies/OysterKit/blob/master/Documentation/stlr-toolc.md) which will automatically synthesize your grammar and data-structures in Swift. - Parameter source: The source to compile - Parameter type: The `Decodable` type that should be created - Returns: The populated type **/ public func build<T : Decodable>(_ source:String,as type: T.Type) throws -> T{ return try ParsingDecoder().decode(T.self, using: parse(source)) } }
a6979a5230c29fd8d186102396666f65
44.327731
197
0.702633
false
false
false
false
mansoor92/MaksabComponents
refs/heads/master
MaksabComponents/Classes/Settings/cells/TextFieldTableViewCell.swift
mit
1
// // TextFieldTableViewCell.swift // Pods // // Created by Incubasys on 20/09/2017. // // import UIKit import StylingBoilerPlate public protocol TextFieldTableViewCellDelegate{ func textFieldExit(indexPath: IndexPath, text: String) } public class TextFieldTableViewCell: UITableViewCell, NibLoadableView, UITextFieldDelegate { @IBOutlet weak public var field: UITextField! @IBOutlet weak var label: TextLabel! var delegate: TextFieldTableViewCellDelegate? var indexPath: IndexPath? override public func awakeFromNib() { super.awakeFromNib() // Initialization code configView() hideDefaultSeparator() } func configView() { self.backgroundColor = UIColor.appColor(color: .Light) field.textColor = UIColor.appColor(color: .DarkText) field.tintColor = UIColor.appColor(color: .Dark) field.font = UIFont.appFont(font: .RubikMedium, pontSize: 17) field.delegate = self } override public func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } public func config(label: String, placeholder: String,delegate: TextFieldTableViewCellDelegate, indexPath: IndexPath) { self.delegate = delegate self.label.text = label field.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: UIColor.appColor(color: .LightText).withAlphaComponent(0.6) , NSFontAttributeName: UIFont.appFont(font: .RubikMedium, pontSize: 17)]) self.indexPath = indexPath } //MARK:- UITextFieldDelegate public func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard let index = indexPath else { return true } delegate?.textFieldExit(indexPath: index, text: textField.text ?? "") textField.resignFirstResponder() return true } }
34d862d3c5109459f1e370af34067f48
31.774194
182
0.684055
false
true
false
false
oskarpearson/rileylink_ios
refs/heads/master
NightscoutUploadKit/NightscoutEntry.swift
mit
1
// // NightscoutEntry.swift // RileyLink // // Created by Timothy Mecklem on 11/5/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation import MinimedKit public class NightscoutEntry: DictionaryRepresentable { public enum GlucoseType: String { case Meter case Sensor } public let timestamp: Date let glucose: Int let previousSGV: Int? let previousSGVNotActive: Bool? let direction: String? let device: String let glucoseType: GlucoseType init(glucose: Int, timestamp: Date, device: String, glucoseType: GlucoseType, previousSGV: Int? = nil, previousSGVNotActive: Bool? = nil, direction: String? = nil) { self.glucose = glucose self.timestamp = timestamp self.device = device self.previousSGV = previousSGV self.previousSGVNotActive = previousSGVNotActive self.direction = direction self.glucoseType = glucoseType } convenience init?(event: TimestampedGlucoseEvent, device: String) { if let glucoseSensorData = event.glucoseEvent as? GlucoseSensorDataGlucoseEvent { self.init(glucose: glucoseSensorData.sgv, timestamp: event.date, device: device, glucoseType: .Sensor) } else { return nil } } public var dictionaryRepresentation: [String: Any] { var representation: [String: Any] = [ "device": device, "date": timestamp.timeIntervalSince1970 * 1000, "dateString": TimeFormat.timestampStrFromDate(timestamp) ] switch glucoseType { case .Meter: representation["type"] = "mbg" representation["mbg"] = glucose case .Sensor: representation["type"] = "sgv" representation["sgv"] = glucose } if let direction = direction { representation["direction"] = direction } if let previousSGV = previousSGV { representation["previousSGV"] = previousSGV } if let previousSGVNotActive = previousSGVNotActive { representation["previousSGVNotActive"] = previousSGVNotActive } return representation } }
c8ec71e3cb6db38864a70d1bb8391263
28.935065
114
0.612148
false
false
false
false
matrix-org/matrix-ios-sdk
refs/heads/develop
MatrixSDK/Contrib/Swift/MXSession.swift
apache-2.0
1
// // MXSession.swift // MatrixSDK // // Created by Avery Pierce on 2/11/17. // Copyright © 2017 matrix.org. All rights reserved. // Copyright 2019 The Matrix.org Foundation C.I.C // import Foundation public extension MXSession { enum Error: Swift.Error { case missingRoom } /// Module that manages threads var threadingService: MXThreadingService { return __threadingService } /** Start fetching events from the home server. If the attached MXStore does not cache data permanently, the function will begin by making an initialSync request to the home server to get information about the rooms the user has interactions with. Then, it will start the events streaming, a long polling connection to the home server to listen to new coming events. If the attached MXStore caches data permanently, the function will do an initialSync only at the first launch. Then, for next app launches, the SDK will load events from the MXStore and will resume the events streaming from where it had been stopped the time before. - parameters: - filterId: the id of the filter to use. - completion: A block object called when the operation completes. In case of failure during the initial sync, the session state is `MXSessionStateInitialSyncFailed`. - response: Indicates whether the operation was successful. */ @nonobjc func start(withSyncFilterId filterId: String? = nil, completion: @escaping (_ response: MXResponse<Void>) -> Void) { __start(withSyncFilterId:filterId, onServerSyncDone: currySuccess(completion), failure: curryFailure(completion)) } /** Start fetching events from the home server with a filter object. - parameters: - filter: The filter to use. - completion: A block object called when the operation completes. In case of failure during the initial sync, the session state is `MXSessionStateInitialSyncFailed`. - response: Indicates whether the operation was successful. */ @nonobjc func start(withSyncFilter filter: MXFilterJSONModel, completion: @escaping (_ response: MXResponse<Void>) -> Void) { __start(withSyncFilter:filter, onServerSyncDone: currySuccess(completion), failure: curryFailure(completion)) } /** Perform an events stream catchup in background (by keeping user offline). - parameters: - clientTimeout: the max time to perform the catchup for the client side (in seconds) - ignoreSessionState: set true to force the sync, otherwise considers session state equality to paused. Defaults to false. - completion: A block called when the SDK has completed a catchup, or times out. - response: Indicates whether the sync was successful. */ @nonobjc func backgroundSync(withTimeout clientTimeout: TimeInterval = 0, ignoreSessionState: Bool = false, completion: @escaping (_ response: MXResponse<Void>) -> Void) { let clientTimeoutMilliseconds = UInt32(clientTimeout * 1000) __backgroundSync(clientTimeoutMilliseconds, ignoreSessionState: ignoreSessionState, success: currySuccess(completion), failure: curryFailure(completion)) } /** Invalidate the access token, so that it can no longer be used for authorization. - parameters: - completion: A block called when the SDK has completed a catchup, or times out. - response: Indicates whether the sync was successful. - returns: an `MXHTTPOperation` instance. */ @nonobjc @discardableResult func logout(completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __logout(currySuccess(completion), failure: curryFailure(completion)) } /** Deactivate the user's account, removing all ability for the user to login again. This API endpoint uses the User-Interactive Authentication API. An access token should be submitted to this endpoint if the client has an active session. The homeserver may change the flows available depending on whether a valid access token is provided. - parameters: - authParameters The additional authentication information for the user-interactive authentication API. - eraseAccount Indicating whether the account should be erased. - completion: A block object called when the operation completes. - response: indicates whether the request succeeded or not. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func deactivateAccount(withAuthParameters authParameters: [String: Any], eraseAccount: Bool, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __deactivateAccount(withAuthParameters: authParameters, eraseAccount: eraseAccount, success: currySuccess(completion), failure: curryFailure(completion)) } /** Define the Matrix storage component to use. It must be set before calling [MXSession start]. Else, by default, the MXSession instance will use MXNoStore as storage. - parameters: - store: the store to use for the session. - completion: A block object called when the operation completes. If the operation was successful, the SDK is then able to serve this data to its client. Note the data may not be up-to-date. You need to call [MXSession start] to ensure the sync with the home server. - response: indicates whether the operation was successful. */ @nonobjc func setStore(_ store: MXStore, completion: @escaping (_ response: MXResponse<Void>) -> Void) { __setStore(store, success: currySuccess(completion), failure: curryFailure(completion)) } /** Enable End-to-End encryption. In case of enabling, the operation will complete when the session will be ready to make encrytion with other users devices - parameters: - isEnabled: `false` stops crypto and erases crypto data. - completion: A block called when the SDK has completed a catchup, or times out. - response: Indicates whether the sync was successful. */ @nonobjc func enableCrypto(_ isEnabled: Bool, completion: @escaping (_ response: MXResponse<Void>) -> Void) { __enableCrypto(isEnabled, success: currySuccess(completion), failure: curryFailure(completion)) } /// Create a new room with the given parameters. /// - Parameters: /// - name: Name of the room /// - joinRule: join rule of the room: can be `public`, `restricted`, or `private` /// - topic: topic of the room /// - parentRoomId: Optional parent room ID. Required for `restricted` join rule /// - aliasLocalPart: local part of the alias (required for `public` room) /// (e.g. for the alias "#my_alias:example.org", the local part is "my_alias") /// - isEncrypted: `true` if you want to enable encryption for this room. `false` otherwise. /// - completion: A closure called when the operation completes. Provides the instance of created room in case of success. /// - Returns: a `MXHTTPOperation` instance. @nonobjc @discardableResult func createRoom(withName name: String, joinRule: MXRoomJoinRule, topic: String? = nil, parentRoomId: String? = nil, aliasLocalPart: String? = nil, isEncrypted: Bool = true, completion: @escaping (_ response: MXResponse<MXRoom>) -> Void) -> MXHTTPOperation? { let parameters = MXRoomCreationParameters() parameters.name = name parameters.topic = topic parameters.roomAlias = aliasLocalPart let stateEventBuilder = MXRoomInitialStateEventBuilder() switch joinRule { case .public: if aliasLocalPart == nil { MXLog.warning("[MXSession] createRoom: creating public room \"\(name)\" without alias") } parameters.preset = kMXRoomPresetPublicChat parameters.visibility = kMXRoomDirectoryVisibilityPublic let guestAccessStateEvent = stateEventBuilder.buildGuestAccessEvent(withAccess: .canJoin) parameters.addOrUpdateInitialStateEvent(guestAccessStateEvent) let historyVisibilityStateEvent = stateEventBuilder.buildHistoryVisibilityEvent(withVisibility: .worldReadable) parameters.addOrUpdateInitialStateEvent(historyVisibilityStateEvent) case .restricted: let guestAccessStateEvent = stateEventBuilder.buildGuestAccessEvent(withAccess: .forbidden) parameters.addOrUpdateInitialStateEvent(guestAccessStateEvent) let historyVisibilityStateEvent = stateEventBuilder.buildHistoryVisibilityEvent(withVisibility: .shared) parameters.addOrUpdateInitialStateEvent(historyVisibilityStateEvent) let joinRuleSupportType = homeserverCapabilitiesService.isFeatureSupported(.restricted) if joinRuleSupportType == .supported || joinRuleSupportType == .supportedUnstable { guard let parentRoomId = parentRoomId else { fatalError("[MXSession] createRoom: parentRoomId is required for restricted room") } parameters.roomVersion = homeserverCapabilitiesService.versionOverrideForFeature(.restricted) let joinRuleStateEvent = stateEventBuilder.buildJoinRuleEvent(withJoinRule: .restricted, allowedParentsList: [parentRoomId]) parameters.addOrUpdateInitialStateEvent(joinRuleStateEvent) } else { let joinRuleStateEvent = stateEventBuilder.buildJoinRuleEvent(withJoinRule: .invite) parameters.addOrUpdateInitialStateEvent(joinRuleStateEvent) } default: parameters.preset = kMXRoomPresetPrivateChat let guestAccessStateEvent = stateEventBuilder.buildGuestAccessEvent(withAccess: .forbidden) parameters.addOrUpdateInitialStateEvent(guestAccessStateEvent) let historyVisibilityStateEvent = stateEventBuilder.buildHistoryVisibilityEvent(withVisibility: .shared) parameters.addOrUpdateInitialStateEvent(historyVisibilityStateEvent) let joinRuleStateEvent = stateEventBuilder.buildJoinRuleEvent(withJoinRule: .invite) parameters.addOrUpdateInitialStateEvent(joinRuleStateEvent) } if isEncrypted { let encryptionStateEvent = stateEventBuilder.buildAlgorithmEvent(withAlgorithm: kMXCryptoMegolmAlgorithm) parameters.addOrUpdateInitialStateEvent(encryptionStateEvent) } return createRoom(parameters: parameters) { response in completion(response) } } /** Create a room. - parameters: - parameters: The parameters for room creation. - completion: A block object called when the operation completes. - response: Provides a MXRoom object on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func createRoom(parameters: MXRoomCreationParameters, completion: @escaping (_ response: MXResponse<MXRoom>) -> Void) -> MXHTTPOperation { return __createRoom(with: parameters, success: currySuccess(completion), failure: curryFailure(completion)) } /** Create a room. - parameters: - parameters: The parameters. Refer to the matrix specification for details. - completion: A block object called when the operation completes. - response: Provides a MXCreateRoomResponse object on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func createRoom(parameters: [String: Any], completion: @escaping (_ response: MXResponse<MXRoom>) -> Void) -> MXHTTPOperation { return __createRoom(parameters, success: currySuccess(completion), failure: curryFailure(completion)) } /** Return the first joined direct chat listed in account data for this user, or it will create one if no room exists yet. */ func getOrCreateDirectJoinedRoom(with userId: String) async throws -> MXRoom { try await withCheckedThrowingContinuation { continuation in _ = getOrCreateDirectJoinedRoom(withUserId: userId) { room in if let room = room { continuation.resume(returning: room) } else { continuation.resume(throwing: Error.missingRoom) } } failure: { error in continuation.resume(throwing: error ?? Error.missingRoom) } } } /** Join a room, optionally where the user has been invited by a 3PID invitation. - parameters: - roomIdOrAlias: The id or an alias of the room to join. - viaServers The server names to try and join through in addition to those that are automatically chosen. - signUrl: the url provided in an invitation. - completion: A block object called when the operation completes. - response: Provides the room on success. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func joinRoom(_ roomIdOrAlias: String, viaServers: [String]? = nil, withSignUrl signUrl: URL? = nil, completion: @escaping (_ response: MXResponse<MXRoom>) -> Void) -> MXHTTPOperation { if let signUrl = signUrl { return __joinRoom(roomIdOrAlias, viaServers: viaServers, withSignUrl: signUrl.absoluteString, success: currySuccess(completion), failure: curryFailure(completion)) } else { return __joinRoom(roomIdOrAlias, viaServers: viaServers, success: currySuccess(completion), failure: curryFailure(completion)) } } /** Leave a room. - parameters: - roomId: the id of the room to leave. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func leaveRoom(_ roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __leaveRoom(roomId, success: currySuccess(completion), failure: curryFailure(completion)) } /// list of all rooms. @nonobjc var rooms: [MXRoom] { return __rooms() } /** Start peeking a room. The operation succeeds only if the history visibility for the room is world_readable. - parameters: - roomId: The room id to the room. - completion: A block object called when the operation completes. - response: Provides the `MXPeekingRoom` to get the room data on success. */ @nonobjc func peek(inRoom roomId: String, completion: @escaping (_ response: MXResponse<MXPeekingRoom>) -> Void) { return __peekInRoom(withRoomId: roomId, success: currySuccess(completion), failure: curryFailure(completion)) } /** Ignore a list of users. - parameters: - userIds: a list of users ids - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func ignore(users userIds: [String], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __ignoreUsers(userIds, success: currySuccess(completion), failure: curryFailure(completion)) } /** Unignore a list of users. - parameters: - userIds: a list of users ids - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful - returns: a `MXHTTPOperation` instance. */ @nonobjc @discardableResult func unIgnore(users userIds: [String], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation { return __unIgnoreUsers(userIds, success: currySuccess(completion), failure: curryFailure(completion)) } /** Register a global listener to events related to the current session. The listener will receive all events including all events of all rooms. - parameters: - types: an array of event types to listen to - block: the block that will be called once a new event has been handled. - returns: a reference to use to unregister the listener */ @nonobjc func listenToEvents(_ types: [MXEventType]? = nil, _ block: @escaping MXOnSessionEvent) -> Any { let legacyBlock: __MXOnSessionEvent = { (event, direction, customObject) in guard let event = event else { return } block(event, direction, customObject) } if let types = types { let typeStrings = types.map({ return $0.identifier }) return __listen(toEventsOfTypes: typeStrings, onEvent: legacyBlock) as Any } else { return __listen(toEvents: legacyBlock) as Any } } /// Fetch an event from the session store, or from the homeserver if required. /// - Parameters: /// - eventId: Event identifier to be fetched. /// - roomId: Room identifier for the event. /// - completion: Completion block to be called at the end of the process. /// - Returns: a `MXHTTPOperation` instance. @nonobjc @discardableResult func event(withEventId eventId: String, inRoom roomId: String?, _ completion: @escaping (_ response: MXResponse<MXEvent>) -> Void) -> MXHTTPOperation { return __event(withEventId: eventId, inRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion)) } // MARK: - Homeserver Information /// The homeserver capabilities var homeserverCapabilities: MXCapabilities? { return __homeserverCapabilities } /// Matrix versions supported by the homeserver. /// /// - Parameter completion: A block object called when the operation completes. /// - Returns: a `MXHTTPOperation` instance. @nonobjc @discardableResult func supportedMatrixVersions(_ completion: @escaping (_ response: MXResponse<MXMatrixVersions>) -> Void) -> MXHTTPOperation { return __supportedMatrixVersions(currySuccess(completion), failure: curryFailure(completion)) } }
af3a0f4a1bdefd2cbbd5f3e7309df7e5
44.58134
217
0.666719
false
false
false
false
JeffESchmitz/RideNiceRide
refs/heads/master
RideNiceRide/Extensions/UIApplication.swift
mit
1
// // UIApplication.swift // SlideMenuControllerSwift // // Created by Yuji Hato on 11/11/15. // Copyright © 2015 Yuji Hato. All rights reserved. // import UIKit import SlideMenuControllerSwift extension UIApplication { class func topViewController(_ viewController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { if let nav = viewController as? UINavigationController { return topViewController(nav.visibleViewController) } if let tab = viewController as? UITabBarController { if let selected = tab.selectedViewController { return topViewController(selected) } } if let presented = viewController?.presentedViewController { return topViewController(presented) } if let slide = viewController as? SlideMenuController { return topViewController(slide.mainViewController) } return viewController } }
ea05139a0a624f8a6a03393d85187190
31.548387
145
0.677899
false
false
false
false
zneak/swift-chess
refs/heads/master
chess/Board.swift
gpl-3.0
1
// // Board.swift // chess // // Created by Félix on 16-02-12. // Copyright © 2016 Félix Cloutier. All rights reserved. // import Foundation enum Tile { case Empty case Occupied(Player, Piece) } private func backRow(color: Player) -> [Tile] { return [ .Occupied(color, .Rook), .Occupied(color, .Knight), .Occupied(color, .Bishop), .Occupied(color, .Queen), .Occupied(color, .King), .Occupied(color, .Bishop), .Occupied(color, .Knight), .Occupied(color, .Rook), ] } private func pawnRow(color: Player) -> [Tile] { return (0..<8).map { _ in .Occupied(color, .Pawn) } } private func emptyRows() -> [Tile] { return (0..<32).map { _ in .Empty } } struct Board { private var tiles = [Tile]() init() { tiles += backRow(.White) tiles += pawnRow(.White) tiles += emptyRows() tiles += pawnRow(.Black) tiles += backRow(.Black) } subscript(locator: Locator) -> Tile { get { return tiles[locator.index] } set(value) { tiles[locator.index] = value } } subscript(locator: Locator?) -> Tile? { get { return locator.map { self[$0] } } } func move(from: Locator, to: Locator) -> Board { var copy = self copy[to] = copy[from] copy[from] = .Empty return copy } private func kingLocator(player: Player) -> Locator { for loc in Locator.all { if case .Occupied(player, .King) = self[loc] { return loc } } fatalError("missing king?") } func isCheck(player: Player) -> Bool { let kingLoc = kingLocator(player) let moves = Moves.calculate(self, player: player.opponent) return moves.goingTo(kingLoc).count != 0 } func isCheckmate(player: Player) -> Bool { for move in Moves.calculate(self, player: player).all { let copy = self.move(move.0, to: move.1) if !copy.isCheck(player) { return false } } return true } }
ad67d642b7696eb1710c0593e4d8a245
19.602273
60
0.633205
false
false
false
false
fitpay/fitpay-ios-sdk
refs/heads/develop
FitpaySDK/PaymentDevice/EventListeners/FitpayEventDispatcher.swift
mit
1
import Foundation open class FitpayEventDispatcher { private var bindingsDictionary: [Int: [FitpayEventBinding]] = [:] public init() { } open func addListenerToEvent(_ listener: FitpayEventListener, eventId: FitpayEventTypeProtocol) -> FitpayEventBinding? { var bindingsArray = bindingsDictionary[eventId.eventId()] ?? [] let binding = FitpayEventBinding(eventId: eventId, listener: listener) bindingsArray.append(binding) bindingsDictionary[eventId.eventId()] = bindingsArray return binding } open func removeBinding(_ binding: FitpayEventBinding) { guard var bindingsArray = bindingsDictionary[binding.eventId.eventId()] else { return } if bindingsArray.contains(binding) { binding.invalidate() bindingsArray.removeObject(binding) bindingsDictionary[binding.eventId.eventId()] = bindingsArray } } open func removeAllBindings() { for (_, bindingsArray) in bindingsDictionary { for binding in bindingsArray { binding.invalidate() } } bindingsDictionary.removeAll() } open func dispatchEvent(_ event: FitpayEvent) { guard let bindingsArray = bindingsDictionary[event.eventId.eventId()] else { return } for binding in bindingsArray { binding.dispatchEvent(event) } } }
7bb5056ad0a6ffe565329ccacfda75ca
30.723404
124
0.622401
false
false
false
false
bugsnag/bugsnag-cocoa
refs/heads/master
features/fixtures/shared/scenarios/ModifyBreadcrumbInNotifyScenario.swift
mit
1
import Foundation class ModifyBreadcrumbInNotifyScenario: Scenario { override func startBugsnag() { self.config.autoTrackSessions = false; super.startBugsnag() } override func run() { Bugsnag.leaveBreadcrumb(withMessage: "Cache cleared") let error = NSError(domain: "HandledErrorScenario", code: 100, userInfo: nil) Bugsnag.notifyError(error) { event in event.breadcrumbs.forEach({ crumb in if crumb.message == "Cache cleared" { crumb.message = "Cache locked" } }) return true } } }
fd67a4724f1c04e76d930633b4869aea
26.782609
85
0.58216
false
false
false
false
ryanglobus/Augustus
refs/heads/master
Augustus/Augustus/AppDelegate.swift
gpl-2.0
1
// // AppDelegate.swift // Augustus // // Created by Ryan Globus on 6/22/15. // Copyright (c) 2015 Ryan Globus. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { let log = AULog.instance func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application // TODO make below queue proper UI queue/execute in UI queue // TODO test below // TODO is below even needed? self.alertIfEventStorePermissionDenied() NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: AUModel.notificationName), object: nil, queue: nil, using: { (notification: Notification) -> Void in DispatchQueue.main.async { self.alertIfEventStorePermissionDenied() } }) log.info("did finish launching") } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application log.info("will terminate") } func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return true } fileprivate func alertIfEventStorePermissionDenied() { if AUModel.eventStore.permission == .denied { let alert = NSAlert() alert.addButton(withTitle: "Go to System Preferences...") alert.addButton(withTitle: "Quit") alert.messageText = "Please grant Augustus access to your calendars." alert.informativeText = "You must grant Augustus access to your calendars in order to see or create events. To do so, go to System Preferences. Select Calendars in the left pane. Then, in the center pane, click the checkbox next to Augustus. Then restart Augustus." alert.alertStyle = NSAlertStyle.warning let response = alert.runModal() if response == NSAlertFirstButtonReturn { let scriptSource = "tell application \"System Preferences\"\n" + "set securityPane to pane id \"com.apple.preference.security\"\n" + "tell securityPane to reveal anchor \"Privacy\"\n" + "set the current pane to securityPane\n" + "activate\n" + "end tell" let script = NSAppleScript(source: scriptSource) let error: AutoreleasingUnsafeMutablePointer<NSDictionary?>? = nil self.log.info("About to go to System Preferences") if script?.executeAndReturnError(error) == nil { self.log.error(error.debugDescription) } // TODO now what? } else { NSApplication.shared().terminate(self) } } } }
e8285ed351c56f98476e8975613bc27f
39.041667
277
0.61984
false
false
false
false
igroomgrim/swift101
refs/heads/master
swift101/Day97_custom_extension.swift
mit
1
// // Day97_custom_extension.swift // swift101 // // Created by Anak Mirasing on 10/3/2558 BE. // Copyright © 2558 iGROOMGRiM. All rights reserved. // import Foundation extension Double { var roundUpTwofractionDigits:Double { let formatter = NSNumberFormatter() formatter.numberStyle = NSNumberFormatterStyle.NoStyle formatter.maximumFractionDigits = 2 formatter.roundingMode = .RoundUp if let stringFromDouble = formatter.stringFromNumber(self) { if let doubleFromString = formatter.numberFromString( stringFromDouble ) as? Double { return doubleFromString } } return 0 } } extension String { var day: String { get { return self.substringWithRange(Range(start: self.startIndex.advancedBy(8), end: self.endIndex.advancedBy(-9))) } set { let normalDate = getDateNow() self.day = normalDate } } } func getDateNow()->String { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy/MM/dd HH:mm:ss" formatter.timeZone = NSTimeZone.localTimeZone() let date = NSDate() let nowDate = formatter.stringFromDate(date) return nowDate }
f4db0a8078213b842fae101f2d211cf3
24.078431
122
0.625978
false
false
false
false
dmitryrybakov/hubchatsample
refs/heads/master
hubchatTestapp/ViewControllers/PostsTableViewCell.swift
mit
1
// // PostsTableViewCell.swift // hubchatTestapp // // Created by Dmitry on 05.02.17. // Copyright © 2017 hubchat. All rights reserved. // import Foundation import UIKit import SnapKit class PostsTableViewCell: UITableViewCell { let avatarImageView = UIImageView() let userNameLabel = UILabel() let upVotesLabel = UILabel() let postTextLabel = UILabel() var viewModel: PostsViewModelling? { didSet { self.postTextLabel.text = viewModel?.postText self.userNameLabel.text = viewModel?.userName self.upVotesLabel.text = String(describing: viewModel?.upvotes) self.avatarImageView.image = UIImage(named: "placeholder-image") if let viewModel = viewModel { viewModel.getAvatarImage(size: self.avatarImageView.bounds.size) .take(until: self.reactive.prepareForReuse) .on(value: { self.avatarImageView.image = ($0 ?? UIImage(named: "placeholder-image")) }) .start() } } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.contentView.addSubview(avatarImageView) self.contentView.addSubview(userNameLabel) self.contentView.addSubview(upVotesLabel) self.contentView.addSubview(postTextLabel) self.postTextLabel.numberOfLines = 0 self.postTextLabel.lineBreakMode = .byWordWrapping avatarImageView.snp.makeConstraints { (make) in make.top.equalTo(self.contentView).inset(15) make.leading.equalTo(self.contentView).inset(15) make.size.equalTo(CGSize(width: 100, height: 100)) } userNameLabel.snp.makeConstraints { (make) in make.top.equalTo(self.avatarImageView.snp.top) make.left.equalTo(self.avatarImageView.snp.right).inset(-15) make.bottom.equalTo(self.avatarImageView.snp.centerY) make.trailing.equalTo(self.contentView).inset(15) } upVotesLabel.snp.makeConstraints { (make) in make.left.equalTo(self.userNameLabel.snp.left) make.right.equalTo(self.userNameLabel.snp.right) make.top.equalTo(self.avatarImageView.snp.centerY) make.bottom.equalTo(self.avatarImageView.snp.bottom) make.trailing.equalTo(self.contentView).inset(15) } postTextLabel.snp.makeConstraints { (make) in make.top.equalTo(self.avatarImageView.snp.bottom).inset(-15) make.trailing.equalTo(self.contentView).inset(15) make.leading.equalTo(self.contentView).inset(15) make.bottom.equalTo(self.contentView).inset(0) } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
b684ae4f98fe08e638856407e9183689
36.0625
108
0.631366
false
false
false
false
marinehero/DominantColor
refs/heads/master
DominantColor/Shared/ColorDifference.swift
mit
2
// // ColorDifference.swift // DominantColor // // Created by Indragie on 12/22/14. // Copyright (c) 2014 Indragie Karunaratne. All rights reserved. // import GLKit.GLKMath // These functions return the squared color difference because for distance // calculations it doesn't matter and saves an unnecessary computation. // From http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE76.html func CIE76SquaredColorDifference(lab1: INVector3, lab2: INVector3) -> Float { let (L1, a1, b1) = lab1.unpack() let (L2, a2, b2) = lab2.unpack() return pow(L2 - L1, 2) + pow(a2 - a1, 2) + pow(b2 - b1, 2) } private func C(a: Float, b: Float) -> Float { return sqrt(pow(a, 2) + pow(b, 2)) } // From http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE94.html func CIE94SquaredColorDifference( kL: Float = 1, kC: Float = 1, kH: Float = 1, K1: Float = 0.045, K2: Float = 0.015 )(lab1:INVector3, lab2:INVector3) -> Float { let (L1, a1, b1) = lab1.unpack() let (L2, a2, b2) = lab2.unpack() let ΔL = L1 - L2 let (C1, C2) = (C(a1, b1), C(a2, b2)) let ΔC = C1 - C2 let ΔH = sqrt(pow(a1 - a2, 2) + pow(b1 - b2, 2) - pow(ΔC, 2)) let Sl: Float = 1 let Sc = 1 + K1 * C1 let Sh = 1 + K2 * C1 return pow(ΔL / (kL * Sl), 2) + pow(ΔC / (kC * Sc), 2) + pow(ΔH / (kH * Sh), 2) } // From http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE2000.html func CIE2000SquaredColorDifference( kL: Float = 1, kC: Float = 1, kH: Float = 1 )(lab1:INVector3, lab2:INVector3) -> Float { let (L1, a1, b1) = lab1.unpack() let (L2, a2, b2) = lab2.unpack() let ΔLp = L2 - L1 let Lbp = (L1 + L2) / 2 let (C1, C2) = (C(a1, b1), C(a2, b2)) let Cb = (C1 + C2) / 2 let G = (1 - sqrt(pow(Cb, 7) / (pow(Cb, 7) + pow(25, 7)))) / 2 let ap: Float -> Float = { a in return a * (1 + G) } let (a1p, a2p) = (ap(a1), ap(a2)) let (C1p, C2p) = (C(a1p, b1), C(a2p, b2)) let ΔCp = C2p - C1p let Cbp = (C1p + C2p) / 2 let hp: (Float, Float) -> Float = { ap, b in if ap == 0 && b == 0 { return 0 } let θ = GLKMathRadiansToDegrees(atan2(b, ap)) return fmod(θ < 0 ? (θ + 360) : θ, 360) } let (h1p, h2p) = (hp(a1p, b1), hp(a2p, b2)) let Δhabs = abs(h1p - h2p) let Δhp: Float = { if (C1p == 0 || C2p == 0) { return 0 } else if Δhabs <= 180 { return h2p - h1p } else if h2p <= h1p { return h2p - h1p + 360 } else { return h2p - h1p - 360 } }() let ΔHp = 2 * sqrt(C1p * C2p) * sin(GLKMathDegreesToRadians(Δhp / 2)) let Hbp: Float = { if (C1p == 0 || C2p == 0) { return h1p + h2p } else if Δhabs > 180 { return (h1p + h2p + 360) / 2 } else { return (h1p + h2p) / 2 } }() let T = 1 - 0.17 * cos(GLKMathDegreesToRadians(Hbp - 30)) + 0.24 * cos(GLKMathDegreesToRadians(2 * Hbp)) + 0.32 * cos(GLKMathDegreesToRadians(3 * Hbp + 6)) - 0.20 * cos(GLKMathDegreesToRadians(4 * Hbp - 63)) let Sl = 1 + (0.015 * pow(Lbp - 50, 2)) / sqrt(20 + pow(Lbp - 50, 2)) let Sc = 1 + 0.045 * Cbp let Sh = 1 + 0.015 * Cbp * T let Δθ = 30 * exp(-pow((Hbp - 275) / 25, 2)) let Rc = 2 * sqrt(pow(Cbp, 7) / (pow(Cbp, 7) + pow(25, 7))) let Rt = -Rc * sin(GLKMathDegreesToRadians(2 * Δθ)) let Lterm = ΔLp / (kL * Sl) let Cterm = ΔCp / (kC * Sc) let Hterm = ΔHp / (kH * Sh) return pow(Lterm, 2) + pow(Cterm, 2) + pow(Hterm, 2) + Rt * Cterm * Hterm }
56c8b0929e6a46eb81d1ec082d4d8366
28.864
83
0.510313
false
false
false
false