repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/Cells/ReviewHighlights/HotelDetailsQuotesContainerView.swift
1
2103
import UIKit class HotelDetailsQuotesContainerView: HLAutolayoutView { private var quotesViews = [HotelDetailsReviewHighlightQuoteView]() private struct Consts { static let quotesVerticalSpacing: CGFloat = 10 } func configureForQuotes(_ quotes: [String], width: CGFloat) { quotesViews = createQuoteViews(quotes, width: width) setupConstraintsForQuotesViews() } private func createQuoteViews(_ quotes: [String], width: CGFloat) -> [HotelDetailsReviewHighlightQuoteView] { guard quotes.count > 0 else { return [] } var quoteViews: [HotelDetailsReviewHighlightQuoteView] = [] for quote in quotes { createQuoteView(quote, quoteViews: &quoteViews) } return quoteViews } private func setupConstraintsForQuotesViews() { guard quotesViews.count > 0 else { return } (quotesViews as NSArray).autoDistributeViews(along: .vertical, alignedTo: .leading, withFixedSpacing: Consts.quotesVerticalSpacing, insetSpacing: false, matchedSizes: false) for quoteView in quotesViews { quoteView.autoPinEdge(toSuperviewEdge: .leading) quoteView.autoPinEdge(toSuperviewEdge: .trailing) } } private func createQuoteView(_ quote: String, quoteViews: inout [HotelDetailsReviewHighlightQuoteView]) { let view = HotelDetailsReviewHighlightQuoteView() view.configureForQuote(quote) addSubview(view) quoteViews.append(view) } func prepareForReuse() { for view in quotesViews { view.removeFromSuperview() } quotesViews = [] } class func preferredHeight(_ quotes: [String], width: CGFloat) -> CGFloat { guard quotes.count > 0 else { return 0 } var result: CGFloat = 0 for quote in quotes { result += HotelDetailsReviewHighlightQuoteView.preferredHeight(quote, width: width) } let innerSpacing = Consts.quotesVerticalSpacing * CGFloat(quotes.count - 1) result += innerSpacing return result } }
mit
83b2846defec77e9296161a3ebf9d519
31.353846
181
0.667142
4.823394
false
false
false
false
dleonard00/firebase-user-signup
Pods/Material/Sources/NavigationBarView.swift
1
4347
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * 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. * * * Neither the name of Material nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * 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 UIKit public class NavigationBarView : StatusBarView { /// Title label. public var titleLabel: UILabel? { didSet { if let v: UILabel = titleLabel { contentView.addSubview(v) } layoutSubviews() } } /// Detail label. public var detailLabel: UILabel? { didSet { if let v: UILabel = detailLabel { contentView.addSubview(v) } layoutSubviews() } } /// A convenience initializer. public convenience init() { self.init(frame: CGRectZero) } /** A convenience initializer with parameter settings. - Parameter titleLabel: UILabel for the title. - Parameter detailLabel: UILabel for the details. - Parameter leftControls: An Array of UIControls that go on the left side. - Parameter rightControls: An Array of UIControls that go on the right side. */ public convenience init?(titleLabel: UILabel? = nil, detailLabel: UILabel? = nil, leftControls: Array<UIControl>? = nil, rightControls: Array<UIControl>? = nil) { self.init(frame: CGRectZero) prepareProperties(titleLabel, detailLabel: detailLabel, leftControls: leftControls, rightControls: rightControls) } public override func layoutSubviews() { super.layoutSubviews() if willRenderView { // TitleView alignment. if let v: UILabel = titleLabel { if let d: UILabel = detailLabel { v.grid.rows = 2 v.font = v.font.fontWithSize(17) d.grid.rows = 2 d.font = d.font.fontWithSize(12) contentView.grid.axis.rows = 3 contentView.grid.spacing = -8 contentView.grid.contentInset.top = -8 } else { v.grid.rows = 1 v.font = v.font?.fontWithSize(20) contentView.grid.axis.rows = 1 contentView.grid.spacing = 0 contentView.grid.contentInset.top = 0 } } contentView.grid.views = [] if let v: UILabel = titleLabel { contentView.grid.views?.append(v) } if let v: UILabel = detailLabel { contentView.grid.views?.append(v) } grid.reloadLayout() contentView.grid.reloadLayout() } } /// Prepares the contentView. public override func prepareContentView() { super.prepareContentView() contentView.grid.axis.direction = .Vertical } /** Used to trigger property changes that initializers avoid. - Parameter titleLabel: UILabel for the title. - Parameter detailLabel: UILabel for the details. - Parameter leftControls: An Array of UIControls that go on the left side. - Parameter rightControls: An Array of UIControls that go on the right side. */ internal func prepareProperties(titleLabel: UILabel?, detailLabel: UILabel?, leftControls: Array<UIControl>?, rightControls: Array<UIControl>?) { prepareProperties(leftControls, rightControls: rightControls) self.titleLabel = titleLabel self.detailLabel = detailLabel } }
mit
b3b57e0200cc19190756d79f4a97735c
33.784
163
0.732919
3.980769
false
false
false
false
zwaldowski/ParksAndRecreation
Latest/Deriving Scroll Views.playground/Sources/DerivingContentSizeTableView.swift
1
2963
// // DerivingContentSizeTableView.swift // Deriving // // Created by Zachary Waldowski on 10/26/16. // Copyright © 2016 Big Nerd Ranch. All rights reserved. // import UIKit public final class DerivingContentSizeTableView: UITableView, ScrollViewBoundsDeriving { private let helper = ScrollViewDerivedBoundsHelper() private func commonInit() { helper.isEnabled = !isScrollEnabled helper.owner = self } public override init(frame: CGRect, style: UITableView.Style) { super.init(frame: frame, style: style) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } deinit { helper.reset() } // MARK: - UIScrollView public override var contentSize: CGSize { didSet { if helper.isEnabled { invalidateIntrinsicContentSize() } } } public override var isScrollEnabled: Bool { didSet { helper.isEnabled = !isScrollEnabled invalidateIntrinsicContentSize() } } // MARK: - UIView public override var frame: CGRect { get { return super.frame } set { helper.whileClippingBounds { super.frame = newValue } } } public override var bounds: CGRect { get { return helper.shouldClipBounds ? helper.visibleBounds(forOriginalBounds: super.bounds) : super.bounds } set { helper.whileClippingBounds { super.bounds = newValue } } } public override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) helper.reset() } public override func didMoveToWindow() { super.didMoveToWindow() helper.validate() if helper.isEnabled { invalidateIntrinsicContentSize() } } public override func layoutSubviews() { helper.validate() helper.whileClippingBounds { super.layoutSubviews() } if helper.shouldSizeToFit && bounds.size != contentSize { invalidateIntrinsicContentSize() } } public override var intrinsicContentSize: CGSize { guard helper.shouldSizeToFit else { return super.intrinsicContentSize } layoutIfNeeded() return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height) } // MARK: - ScrollViewBoundsDeriving func invalidateLayoutForVisibleBoundsChange() { // assigning bounds to get: // - collection view layout invalidation // - set the "scheduledUpdateVisibleCells" flag let oldBounds = super.bounds super.bounds = helper.visibleBounds(forOriginalBounds: oldBounds) super.bounds = oldBounds } }
mit
286329756657b93e7f68e44dfe6a9c10
23.081301
113
0.602633
5.34657
false
false
false
false
Dan2552/Placemat
Placemat/Classes/String.swift
1
4616
import UIKit private let acronyms = [ "URL", "HTTP", "SSL", "HTML", "API" ] public enum FirstCharacterCase { case lower case upper } public extension String { static func nameFor(object: Any?) -> String { if let object = object { // return "\(object)" //.components(separatedBy: " ").first!.components(separatedBy: ".").last! return (object is Any.Type) ? "\(object)" : "\(type(of: object))" } else { return "nil" } } func changingCaseOf(firstCharacter: FirstCharacterCase) -> String { guard self.characters.count > 0 else { return self } let rest = characters.index(after: startIndex)..<endIndex if firstCharacter == .lower { return self[startIndex...startIndex].lowercased() + self[rest] } else { return self[startIndex...startIndex].uppercased() + self[rest] } } func camelCased(firstCharacterCase: FirstCharacterCase = .upper) -> String { let range = rangeOfCharacter(from: NSCharacterSet.uppercaseLetters) let hasNoCapitals = range?.isEmpty var result: String = self if hasNoCapitals == true || hasNoCapitals == nil { result = self.capitalized } return result.changingCaseOf(firstCharacter: firstCharacterCase).replacingOccurrences(of: "_", with: "") } func pluralize() -> String { if hasSuffix("s") { if !hasSuffix("ss") { return self } } var plural = "\(self)s" if plural.hasSuffix("eys") { // "moneys" -> "monies" let range = plural.index(endIndex, offsetBy: -2)..<plural.endIndex plural = plural.replacingCharacters(in: range, with: "ies") } else if plural.hasSuffix("ys") { // "categorys" -> "categories" let range = plural.index(endIndex, offsetBy: -1)..<plural.endIndex plural = plural.replacingCharacters(in: range, with: "ies") } else if plural.hasSuffix("sss") { // "address" -> "addresses" let range = plural.index(endIndex, offsetBy: -2)..<plural.endIndex plural = plural.replacingCharacters(in: range, with: "sses") } return plural } func underscoreCased() -> String { let output = NSMutableString() let uppercase = NSCharacterSet.uppercaseLetters as NSCharacterSet var previousCharacterWasUppercase = false var currentCharacterIsUppercase = false for (index, character) in self.characters.enumerated() { let units = [unichar](String(character).utf16) previousCharacterWasUppercase = currentCharacterIsUppercase currentCharacterIsUppercase = uppercase.characterIsMember(units[0]) if !previousCharacterWasUppercase && currentCharacterIsUppercase && index > 0 { output.append("_") } else if previousCharacterWasUppercase && !currentCharacterIsUppercase { if output.length > 1 { let charTwoBack = output.character(at: output.length - 2) if !NSCharacterSet(charactersIn: "_").characterIsMember(charTwoBack) { output.insert("_", at: output.length - 1) } } } output.append(String(character).lowercased()) } return String(output) } public func humanize(firstCharacterCase: FirstCharacterCase = .upper) -> String { var human = self.underscoreCased() human = human.replacingOccurrences(of: "_", with: " ") human = human.lowercased() let words = human.components(separatedBy: " ") for (index, var word) in words.enumerated() { let upper = word.uppercased() if acronyms.contains(upper) { word = upper } if index == 0 { human = word } else { human += " \(word)" } } return human.changingCaseOf(firstCharacter: firstCharacterCase) } public func titleize() -> String { var string = underscoreCased().humanize().capitalized let words = string.components(separatedBy: " ") for (index, var word) in words.enumerated() { let upper = word.uppercased() if acronyms.contains(upper) { word = upper } if index == 0 { string = word } else { string += " \(word)" } } return string } }
mit
3f17e8d8da050b846d3604d69b88a9b9
32.693431
112
0.567158
4.798337
false
false
false
false
dongdongSwift/guoke
gouke/果壳/launchViewController.swift
1
2163
// // launchViewController.swift // 果壳 // // Created by qianfeng on 2016/11/8. // Copyright © 2016年 张冬. All rights reserved. // import UIKit class launchViewController: UIViewController,NavigationProtocol { @IBAction func btnClick(btn: UIButton) { if btn.tag==300{ print("微信登录") }else if btn.tag==301{ print("微博登录") }else if btn.tag==302{ print("QQ登录") }else if btn.tag==303{ print("豆瓣登录") }else if btn.tag==304{ print("登录") }else if btn.tag==305{ print("查看用户协议") }else if btn.tag==306{ print("刷新验证码") }else if btn.tag==307{ navigationController?.pushViewController(forgetController(), animated: true) } } @IBAction func back(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } @IBOutlet weak var accountTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var verificationCodeTextField: UITextField! @IBOutlet weak var verificationImage: UIImageView! override func viewDidLoad() { super.viewDidLoad() addTitle("登录") } func keyBoardDidReturn(){ } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { accountTextField.resignFirstResponder() passwordTextField.resignFirstResponder() verificationCodeTextField.resignFirstResponder() } 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. } */ }
mit
2aa75bfa4880a7dfb4a08d08a9233d3b
26.552632
106
0.622254
4.869767
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/unique-binary-search-trees.swift
2
908
/** * https://leetcode.com/problems/unique-binary-search-trees/ * * */ // Date: Wed Jun 24 09:24:48 PDT 2020 class Solution { func numTrees(_ n: Int) -> Int { var map: [Int : Int] = [:] map[0] = 1 map[1] = 1 map[2] = 2 /// In this function, we are trying to choose the position of the root from number 1 ... key. /// We let the left + 1 as the root, then, there will be left number elements in left tree. /// key - left - 1 on the right subtree. /// We also use memorization tech to store all the calculated answers. func cal(_ key : Int) -> Int { if let val = map[key] { return val } var count = 0 for left in 0 ..< key { count += cal(left) * cal(key - left - 1) } map[key] = count return count } return cal(n) } }
mit
fd7b0dab3c7d0e36cf2e4e8dfaccd660
30.310345
101
0.505507
3.783333
false
false
false
false
firebase/firebase-ios-sdk
FirebaseRemoteConfigSwift/Tests/FakeUtils/URLSessionPartialMock.swift
1
2210
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation #if SWIFT_PACKAGE import RemoteConfigFakeConsoleObjC #endif // Create a partial mock by subclassing the URLSessionDataTask. class URLSessionDataTaskMock: URLSessionDataTask { private let closure: () -> Void init(closure: @escaping () -> Void) { self.closure = closure } override func resume() { closure() } } class URLSessionMock: URLSession { typealias CompletionHandler = (Data?, URLResponse?, Error?) -> Void private let fakeConsole: FakeConsole init(with fakeConsole: FakeConsole) { self.fakeConsole = fakeConsole } // Properties to control what gets returned to the URLSession callback. // error could also be added here. var data: Data? var response: URLResponse? var etag = "" override func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask { let consoleValues = fakeConsole.get() if etag == "" || consoleValues["state"] as! String == RCNFetchResponseKeyStateUpdate { // Time string in microseconds to insure a different string from previous change. etag = String(NSDate().timeIntervalSince1970) } let jsonData = try! JSONSerialization.data(withJSONObject: consoleValues) let response = HTTPURLResponse(url: URL(fileURLWithPath: "fakeURL"), statusCode: 200, httpVersion: nil, headerFields: ["etag": etag]) return URLSessionDataTaskMock { completionHandler(jsonData, response, nil) } } }
apache-2.0
83f2456ab30d3e3dd27e0fc036180af2
33
92
0.683258
4.773218
false
false
false
false
czerenkow/LublinWeather
App/Settings Info/InfoBuilder.swift
1
747
// // InfoBuilder.swift // LublinWeather // // Created by Damian Rzeszot on 24/04/2018. // Copyright © 2018 Damian Rzeszot. All rights reserved. // import UIKit protocol InfoDependency: Dependency { var localizer: Localizer { get } func tracker() -> Tracker<InfoEvent> } class InfoBuilder: Builder<InfoDependency> { func build() -> InfoRouter { let vc = InfoViewController() let router = InfoRouter() let interactor = InfoInteractor() router.controller = vc router.interactor = interactor vc.output = interactor vc.localizer = dependency.localizer interactor.router = router interactor.tracker = dependency.tracker() return router } }
mit
6e83875cecb7758ef32988cab0b0820d
19.162162
57
0.647453
4.493976
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Home/Wallpapers/Legacy/Utilities/LegacyWallpaperNetworkUtility.swift
2
3224
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import Foundation import Shared protocol LegacyWallpaperDownloadProtocol { func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask } extension URLSession: LegacyWallpaperDownloadProtocol {} class LegacyWallpaperNetworkUtility: LegacyWallpaperFilePathProtocol, Loggable { // MARK: - Variables private static let wallpaperURLScheme = "MozWallpaperURLScheme" lazy var downloadProtocol: LegacyWallpaperDownloadProtocol = { return URLSession.shared }() // MARK: - Public interfaces public func downloadTaskFor(id: LegacyWallpaperImageResourceName) { // Prioritize downloading the image matching the current orientation if UIDevice.current.orientation.isLandscape { downloadResourceFrom(urlPath: id.landscapePath, andLocalPath: id.landscape) downloadResourceFrom(urlPath: id.portraitPath, andLocalPath: id.portrait) } else { downloadResourceFrom(urlPath: id.portraitPath, andLocalPath: id.portrait) downloadResourceFrom(urlPath: id.landscapePath, andLocalPath: id.landscape) } } // MARK: - Private methods private func downloadResourceFrom(urlPath: String, andLocalPath localPath: String) { guard let url = buildURLWith(path: urlPath) else { return } downloadProtocol.dataTask(with: url) { data, response, error in if let error = error { self.browserLog.debug("Error fetching wallpaper: \(error.localizedDescription)") return } guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { self.browserLog.debug("Wallpaper download - bad networking response: \(response.debugDescription)") return } guard let data = data, let image = UIImage(data: data) else { self.browserLog.error("") return } let storageUtility = LegacyWallpaperStorageUtility() do { try storageUtility.store(image: image, forKey: localPath) } catch let error { self.browserLog.error("Error saving downloaded image - \(error.localizedDescription)") } }.resume() } private func buildURLWith(path: String) -> URL? { guard let scheme = urlScheme() else { return nil } let urlString = scheme + "\(path).png" return URL(string: urlString) } private func urlScheme() -> String? { let bundle = AppInfo.applicationBundle guard let appToken = bundle.object(forInfoDictionaryKey: LegacyWallpaperNetworkUtility.wallpaperURLScheme) as? String, !appToken.isEmpty else { browserLog.debug("Error fetching wallpapers: asset scheme not configured in Info.plist") return nil } return appToken } }
mpl-2.0
b0113c7207ef49282dc1e4bb3879854c
36.057471
126
0.650124
5.11746
false
false
false
false
codwam/NPB
Demos/NPBDemo/NPB/UINavigationController+NPB.swift
1
13205
// // UINavigationController+NPB.swift // NPBDemo // // Created by 李辉 on 2017/4/8. // Copyright © 2017年 codwam. All rights reserved. // import UIKit /// Expand two different navigation bar transition style, setting this property for the global navigation transition. It is worth noting that custom navigation transitions or disable navigation bar translucent will crossfade the navigation bar forcibly. /// If you have some ViewController which doesn't wants a navigation bar, you can set the "jz_wantsNavigationBarVisible" property to NO. /// You can also adjust your navigationBar or toolbar's background alpha. /// /// - none: 没有效果,直接显示的 /// - system: 系统过渡效果 /// - doppelganger: 二重身,就是看起来两个导航栏的效果 @objc enum NPBTransitionStyle: Int { case none case system case doppelganger } var Associated_npb_transitionStyle_Handle: UInt8 = 0 extension UINavigationController { fileprivate struct AssociatedKeys { // static var npb_transitionStyle: NPBTransitionStyle? static var npb_fullScreenInteractivePopGestureEnabled: Bool? static var npb_fullScreenInteractivePopGestureRecognizer: UIPanGestureRecognizer? static var npb_operation: UINavigationControllerOperation? static var npb_previousVisibleViewController: UIViewController? static var npb_interactivePopGestureRecognizerCompletion: UInt8 = 0 } /// Expand two different navigation bar transition style, setting this property for the global navigation transition. It is worth noting that custom navigation transitions or disable navigation bar translucent will crossfade the navigation bar forcibly. var npb_transitionStyle: NPBTransitionStyle { get { return objc_getAssociatedObject(self, &Associated_npb_transitionStyle_Handle) as? NPBTransitionStyle ?? .system } set { objc_setAssociatedObject(self, &Associated_npb_transitionStyle_Handle, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) npb_inject() } } /// If YES, then you can have a fullscreen gesture recognizer responsible for popping the top view controller off the navigation stack, and the property is still "interactivePopGestureRecognizer", see more for "UINavigationController.h", Default is NO. var npb_fullScreenInteractivePopGestureEnabled: Bool { get { guard let npb_fullScreenInteractivePopGestureRecognizer = self.npb_fullScreenInteractivePopGestureRecognizer else { return false } return npb_fullScreenInteractivePopGestureRecognizer.isEnabled } set { objc_setAssociatedObject(self, &AssociatedKeys.npb_fullScreenInteractivePopGestureEnabled, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) if self.npb_fullScreenInteractivePopGestureRecognizer == nil { guard let interactivePopGestureRecognizer = self.interactivePopGestureRecognizer else { print("interactivePopGestureRecognizer == nil") return } let _interactiveTargets = interactivePopGestureRecognizer.value(forKey: _InteractivePopGestureRecognizer_Targets) as? [AnyObject] let _interactiveFirsTarget = _interactiveTargets?.first?.value(forKey: _InteractivePopGestureRecognizer_Targets) let panGestureRecognizer = UIPanGestureRecognizer(target: _interactiveFirsTarget, action: NSSelectorFromString(_InteractivePopGestureRecognizer_HandleNavigationTransition)) panGestureRecognizer.setValue(false, forKey: _InteractivePopGestureRecognizer_CanPanVertically) self.npb_interactiveTransition = NPBNavigationInteractiveTransition() panGestureRecognizer.delegate = self.npb_interactiveTransition interactivePopGestureRecognizer.view?.addGestureRecognizer(panGestureRecognizer) self.npb_fullScreenInteractivePopGestureRecognizer = panGestureRecognizer } self.npb_fullScreenInteractivePopGestureEnabled = newValue } } /// navigationBar's background alpha, when 0 your navigationBar will be invisable, default is 1. Animatable override var npb_navigationBarBackgroundAlpha: CGFloat { get { guard let npb_backgroundView = self.navigationBar.npb_backgroundView else { return 1 } return npb_backgroundView.alpha } set { self.navigationBar.npb_backgroundView?.alpha = newValue } } /// Current navigationController's toolbar background alpha, make sure the toolbarHidden property is NO, default is 1. Animatable var npb_toolbarBackgroundAlpha: CGFloat { get { guard let npb_backgroundView = self.toolbar.npb_backgroundView else { return 1 } return npb_backgroundView.alpha } set { self.toolbar.npb_shadowView?.alpha = newValue self.toolbar.npb_backgroundView?.alpha = newValue } } /// Could use this propery to adjust navigation controller's operation, then do some logic. internal(set) var npb_operation: UINavigationControllerOperation { get { guard let npb_operation = objc_getAssociatedObject(self, &AssociatedKeys.npb_operation) as? UINavigationControllerOperation else { return .none } return npb_operation } set { objc_setAssociatedObject(self, &AssociatedKeys.npb_operation, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Return the previous visible view controller in navigation controller. Could use this to do any logic during navigation transition in any method you want, like "viewWillAppear:". This can is a replacement of property "interactivePopedViewController". internal(set) var npb_previousVisibleViewController: UIViewController? { // TODO: weakObjectValue get { guard let npb_previousVisibleViewController = objc_getAssociatedObject(self, &AssociatedKeys.npb_previousVisibleViewController) as? UIViewController else { return nil } return npb_previousVisibleViewController } set { objc_setAssociatedObject(self, &AssociatedKeys.npb_previousVisibleViewController, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Change navigationBar to any size, if you want default value, then set to 0.f. var npb_navigationBarSize: CGSize { get { return self.navigationBar.npb_size } set { self.navigationBar.npb_size = newValue } } /// Change toolBar to any size, if you want default value, then set to 0.f. var npb_toolbarSize: CGSize { get { return self.toolbar.npb_size } set { self.toolbar.npb_size = newValue } } // MARK: Private override var npb_navigationBarTintColor: UIColor? { get { return self.navigationBar.barTintColor } set { self.navigationBar.barTintColor = newValue } } // TODO: _JZValue weak??? fileprivate var npb_fullScreenInteractivePopGestureRecognizer: UIPanGestureRecognizer? { get { guard let _fullScreenInteractivePopGestureRecognizer = objc_getAssociatedObject(self, &AssociatedKeys.npb_fullScreenInteractivePopGestureRecognizer) as? UIPanGestureRecognizer else { // self.npb_fullScreenInteractivePopGestureRecognizer = nil return nil } return _fullScreenInteractivePopGestureRecognizer } set { objc_setAssociatedObject(self, &AssociatedKeys.npb_fullScreenInteractivePopGestureRecognizer, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - methods /// Return the gives view controller's previous view controller in the navigation stack. func npb_previousViewController(for viewController: UIViewController) -> UIViewController? { guard let index = self.viewControllers.index(of: viewController) else { return nil } return self.viewControllers[index - 1] } /// Called at end of animation of push/pop or immediately if not animated. The completion block will be set to nil while transition finish. func npb_pushViewController(_ viewController: UIViewController, animated: Bool, completion: npb_navigation_block_t?) { self.npb_operation = .push self.npb_navigationTransitionFinished = completion npb_handleNavigationTransitionAnimated(animated: animated, fromViewController: self.visibleViewController, toViewController: viewController) { (_) in npb_pushViewController(viewController, animated: animated) } } /// Called at end of animation of push/pop or immediately if not animated. The completion block will be set to nil while transition finish. func npb_popViewController(animated: Bool, completion: npb_navigation_block_t?) -> UIViewController? { self.npb_operation = .pop self.npb_navigationTransitionFinished = completion let fromViewController = self.visibleViewController npb_handleNavigationTransitionAnimated(animated: animated, fromViewController: fromViewController, toViewController: fromViewController?.npb_previousViewController) { (_) in npb_popViewController(animated: animated) } return fromViewController } /// Called at end of animation of push/pop or immediately if not animated. The completion block will be set to nil while transition finish. func npb_popToRootViewController(animated: Bool, completion: npb_navigation_block_t?) -> [UIViewController]? { self.npb_operation = .pop self.npb_navigationTransitionFinished = completion var popedViewControllers: [UIViewController]? npb_handleNavigationTransitionAnimated(animated: animated, fromViewController: self.visibleViewController, toViewController: self.viewControllers.first) { (_) in popedViewControllers = npb_popToRootViewController(animated: true) } return popedViewControllers } /// Called at end of animation of push/pop or immediately if not animated. The completion block will be set to nil while transition finish. func npb_popToViewController(_ viewController: UIViewController, animated: Bool, completion: npb_navigation_block_t?) -> [UIViewController]? { self.npb_operation = .pop self.npb_navigationTransitionFinished = completion var popedViewControllers: [UIViewController]? npb_handleNavigationTransitionAnimated(animated: animated, fromViewController: self.visibleViewController, toViewController: viewController) { (_) in popedViewControllers = npb_popToViewController(viewController, animated: true) } return popedViewControllers } /// Called at end of animation of push/pop or immediately if not animated. The completion block will be set to nil while transition finish. func npb_setViewControllers(_ viewControllers: [UIViewController], animated: Bool, completion: npb_navigation_block_t?) { let oldViewControllers = self.viewControllers var operation = UINavigationControllerOperation.none if viewControllers.count > oldViewControllers.count { operation = .push } else if viewControllers.count < oldViewControllers.count { operation = .pop } self.npb_operation = operation self.npb_navigationTransitionFinished = completion npb_handleNavigationTransitionAnimated(animated: animated, fromViewController: oldViewControllers.last, toViewController: viewControllers.last) { (_) in npb_setViewControllers(viewControllers, animated: animated) } } /// Called at end of interactive pop gesture immediately. You could use poppedViewController/visibleViewController/npb_previousVisibleViewController properties to decide what to do. var npb_interactivePopGestureRecognizerCompletion: npb_navigation_block_t? { get { guard let npb_interactivePopGestureRecognizerCompletion = objc_getAssociatedObject(self, &AssociatedKeys.npb_interactivePopGestureRecognizerCompletion) as? ClosureWrapper<npb_navigation_block_t> else { return nil } return npb_interactivePopGestureRecognizerCompletion.closure } set { let closureWrapper = newValue != nil ? ClosureWrapper(closure: newValue) : nil objc_setAssociatedObject(self, &AssociatedKeys.npb_interactivePopGestureRecognizerCompletion, closureWrapper, .OBJC_ASSOCIATION_COPY_NONATOMIC) } } }
mit
f3adaaecafc27c2d25ba07aea0da3db1
46.57971
257
0.69106
5.473947
false
false
false
false
mobgeek/swift
Swift em 4 Semanas/Playgrounds/Semana 1/4-Operadores Basicos.playground/Contents.swift
2
1017
// Playground - noun: a place where people can play import UIKit // Operadores básicos :-] let taxaMinima = 150 var taxaServico = 5 1 + 1 7 - 6 5 * 7 15.0 / 7.5 7 % 3 -7 % 3 5 % 1.5 var cal = 130 cal = cal + 1 ++cal cal = cal - 1 --cal var pontosTotal = 300 let pontosLevel1 = ++pontosTotal let pontosBonus = pontosTotal++ let quatro = 4 let menosQuatro = -quatro let menosSete = -7 let tambemMenosSete = +menosSete var valorPositivo: Int = +1000 var valorNegativo: Int = -1000 var passos = 1500 passos += 350 passos -= 350 // passos = passos - 350 passos *= 3 // passos = passos * 3 passos /= 3 1 == 1 2 != 1 2 > 1 1 < 2 1 >= 1 2 <= 1 var mesadaFixa = 100 var seComportou = false var mesadaTotal = mesadaFixa + (seComportou ? 20 : 5) // Concatenar: var filmeSessaoDaTarde = "As Aventuras de" filmeSessaoDaTarde += " João e seu cachorrinho Fluffy" let programaEleitoral = "Horário Eleitoral" // Não rola! -> programaEleitoral += "e outros"
mit
2ae58a09b325052d63bf5d150e128834
7.65812
54
0.631787
2.440964
false
false
false
false
JoseLuis1987/GestorWS
WS-Connector/Classes/Extensions.swift
1
27104
// // Extensions.swift // WS-Connector // // Created by QACG MAC2 on 8/23/17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import CoreGraphics import UIKit typealias JSONObject = [String : AnyObject] typealias JSONDictionary = [String: Any] typealias JsonArray = Array<[String: Any]> extension Int { var array: [Int] { return description.characters.map{Int(String($0)) ?? 0} } //Para SLCAlertView func toUIColor() -> UIColor { return UIColor( red: CGFloat((self & 0xFF0000) >> 16) / 255.0, green: CGFloat((self & 0x00FF00) >> 8) / 255.0, blue: CGFloat(self & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } func toCGColor() -> CGColor { return self.toUIColor().cgColor } } extension Double { /// Rounds the double to decimal places value func roundTo(places:Int) -> Double { let divisor = pow(10.0, Double(places)) return (self * divisor).rounded() / divisor } var asLocaleCurrency: String { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = Locale.current return formatter.string(from: self as NSNumber)! } /// Rounds the double to decimal places value func redondearDecimales(places:Int) -> Double { let divisor = pow(10.0, Double(places)) return (self * divisor).rounded() / divisor } func format(f: String) -> String { return String(format: "%\(f)f", self) } } extension Float { var asLocaleCurrency:String { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = Locale.current return formatter.string(from: self as NSNumber)! } } extension Dictionary{ func getJsonAsset(name: String) -> JSONObject { let file = Bundle.main.path(forResource: name, ofType: "json") let url = URL(fileURLWithPath: file!) let data = try! Data(contentsOf: url) let json = try! JSONSerialization.jsonObject(with: data) // print(json) return json as! JSONObject } } extension NSDictionary { func loadJson(forFilename fileName: String) -> NSDictionary? { if let url = Bundle.main.url(forResource: fileName, withExtension: "json") { if let data = NSData(contentsOf: url) { do { let dictionary = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) as? NSDictionary return dictionary } catch { // print("Error!! Unable to parse \(fileName).json") } } // print("Error!! Unable to load \(fileName).json") } return nil } } extension String { var localized: String { return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "") } func localizedWithComment(comment:String) -> String { return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: comment) } var length: Int { return characters.count } // Swift 3.0 var isEmail: Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,20}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: self) } var numbers: String { return components(separatedBy: Numbers.characterSet.inverted).joined() } var integer: Int { return Int(numbers) ?? 0 } //separa las palabras func words(with charset: CharacterSet = .alphanumerics) -> [String] { return self.unicodeScalars.split { !charset.contains($0) }.map(String.init) } /// Encode a String to Base64 func toBase64() -> String { return Data(self.utf8).base64EncodedString() } /// Decode a String from Base64. Returns nil if unsuccessful. func fromBase64() -> String? { guard let data = Data(base64Encoded: self) else { return nil } return String(data: data, encoding: .utf8) } func hexadecimal() -> Data? { var data = Data(capacity: characters.count / 2) let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive) regex.enumerateMatches(in: self, options: [], range: NSMakeRange(0, characters.count)) { match, flags, stop in let byteString = (self as NSString).substring(with: match!.range) var num = UInt8(byteString, radix: 16)! data.append(&num, count: 1) } guard data.count > 0 else { return nil } return data } func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return boundingBox.height } // formatting text for currency textField func currencyInputFormatting() -> String { var number: NSNumber! let formatter = NumberFormatter() if #available(iOS 9.0, *) { formatter.numberStyle = .currencyAccounting } else { // Fallback on earlier versions } formatter.currencySymbol = "$" formatter.maximumFractionDigits = 2 formatter.minimumFractionDigits = 2 var amountWithPrefix = self // remove from String: "$", ".", "," let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive) amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "") let double = (amountWithPrefix as NSString).doubleValue number = NSNumber(value: (double / 100)) // if first number is 0 or all numbers were deleted guard number != 0 as NSNumber else { return "" } return formatter.string(from: number)! } func contains(find: String) -> Bool { return self.range(of: find) != nil } } extension UInt { func toUIColor() -> UIColor { return UIColor( red: CGFloat((self & 0xFF0000) >> 16) / 255.0, green: CGFloat((self & 0x00FF00) >> 8) / 255.0, blue: CGFloat(self & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } func toCGColor() -> CGColor { return self.toUIColor().cgColor } } extension NSString { class func convertFormatOfDate(date: String, originalFormat: String, destinationFormat: String) -> String! { // Orginal format : let dateOriginalFormat = DateFormatter() dateOriginalFormat.dateFormat = originalFormat // in the example it'll take "yy MM dd" (from our call) // Destination format : let dateDestinationFormat = DateFormatter() dateDestinationFormat.dateFormat = destinationFormat // in the example it'll take "EEEE dd MMMM yyyy" (from our call) // Convert current String Date to NSDate let dateFromString = dateOriginalFormat.date(from: date) // Convert new NSDate created above to String with the good format let dateFormated = dateDestinationFormat.string(from: dateFromString!) return dateFormated } } extension CGRect { var centerCuadro: CGRect { let side = min(width, height) return CGRect( x: midX - side / 2.0, y: midY - side / 2.0, width: side, height: side) } } extension Bundle { var releaseVersionNumber: String? { return infoDictionary?["CFBundleShortVersionString"] as? String } var buildVersionNumber: String? { return infoDictionary?["CFBundleVersion"] as? String } } @discardableResult func printMessage(message: String) -> String { let outputMessage = "Output : \(message)" print(outputMessage) return outputMessage } extension UINavigationController { public func presentTransparentNavigationBar() { navigationBar.setBackgroundImage(UIImage(), for:UIBarMetrics.default) navigationBar.isTranslucent = true navigationBar.shadowImage = UIImage() setNavigationBarHidden(false, animated:true) } public func hideTransparentNavigationBar() { setNavigationBarHidden(true, animated:false) navigationBar.setBackgroundImage(UINavigationBar.appearance().backgroundImage(for: UIBarMetrics.default), for:UIBarMetrics.default) navigationBar.isTranslucent = UINavigationBar.appearance().isTranslucent navigationBar.shadowImage = UINavigationBar.appearance().shadowImage } } extension UIImage { class func imageWithColor(color: UIColor, size: CGSize) -> UIImage { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setFill() UIRectFill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } static func imageWithCollor(tintColor: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0) tintColor.setFill() UIRectFill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } class func image(name: String, withColor color: UIColor) -> UIImage? { if var image = UIImage(named: name) { // begin a new image context, to draw our colored image onto. Passing in zero for scale tells the system to take from the current device's screen scale. // UIGraphicsBeginImageContext(image.size, false, 0) UIGraphicsBeginImageContext(image.size) // get a reference to that context we created let context = UIGraphicsGetCurrentContext() // set the context's fill color color.setFill() // translate/flip the graphics context (for transforming from CoreGraphics coordinates to default UI coordinates. The Y axis is flipped on regular coordinate systems) context!.translateBy(x: 0.0, y: image.size.height) context!.scaleBy(x: 1.0, y: -1.0) // set the blend mode to color burn so we can overlay our color to our image. context!.setBlendMode(.multiply) let rect = CGRect(origin: .zero, size: image.size) context?.draw(image.cgImage!, in: rect) // set a mask that matches the rect of the image, then draw the color burned context path. context!.clip(to: rect, mask: image.cgImage!) context!.addRect(rect) context!.drawPath(using: .fillStroke) // generate a new UIImage from the graphics context we've been drawing onto image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } return nil } } extension UIScrollView { func scrollToTop() { let desiredOffset = CGPoint(x: 0, y: -contentInset.top) setContentOffset(desiredOffset, animated: true) } } struct Formatter { static let decimal = NumberFormatter(numberStyle: .decimal) } extension UITextField { var string: String { return text ?? "" } } struct Numbers { static let characterSet = CharacterSet(charactersIn: "0123456789") } extension NumberFormatter { convenience init(numberStyle: NumberFormatter.Style) { self.init() self.numberStyle = numberStyle } } extension UIImageView { public func imageFromUrl(urlString: String) { if let url = NSURL(string: urlString) { let request = NSMutableURLRequest(url: url as URL) // request.setValue("<YOUR_HEADER_VALUE>", forHTTPHeaderField: "<YOUR_HEADER_KEY>") URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in guard let data = data, error == nil else{ NSLog("Image download error: \(String(describing: error))") return } if let httpResponse = response as? HTTPURLResponse{ if httpResponse.statusCode > 400 { let errorMsg = NSString(data: data, encoding: String.Encoding.utf8.rawValue) NSLog("Image download error, statusCode: \(httpResponse.statusCode), error: \(errorMsg!)") return } } DispatchQueue.main.async { self.image = UIImage(data: data) } }.resume() } } } extension UIColor { convenience init(hex:Int, alpha:CGFloat = 1.0) { self.init( red: CGFloat((hex & 0xFF0000) >> 16) / 255.0, green: CGFloat((hex & 0x00FF00) >> 8) / 255.0, blue: CGFloat((hex & 0x0000FF) >> 0) / 255.0, alpha: alpha ) } } extension UIView { func rotate(toValue: CGFloat, duration: CFTimeInterval = 0.2) { let animation = CABasicAnimation(keyPath: "transform.rotation") animation.toValue = toValue animation.duration = duration animation.isRemovedOnCompletion = false animation.fillMode = kCAFillModeForwards self.layer.add(animation, forKey: nil) } } extension Data { // GET JSONFILE static func getJsonFile(fileName: String) -> Any? { if let url = Bundle.main.url(forResource: fileName, withExtension: "json") { if let data = NSData(contentsOf: url) { do { return try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) /* if let dictionary = object as? Any? { return dictionary }*/ } catch { // print("Error!! Unable to parse \(fileName).json") } } // print("Error!! Unable to load \(fileName).json") } return nil } // GET JSONFILE func loadJson(filename fileName: String) -> [[String: AnyObject]]? { if let url = Bundle.main.url(forResource: fileName, withExtension: "json") { if let data = NSData(contentsOf: url) { do { let object = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) if let dictionary = object as? [[String: AnyObject]] { return dictionary } } catch { // print("Error!! Unable to parse \(fileName).json") } } //print("Error!! Unable to load \(fileName).json") } return nil } } extension NSData { // Convert from NSData to json object func nsdataToJSON(data: NSData) -> Any? { do { return try JSONSerialization.jsonObject(with: data as Data, options: .mutableContainers) } catch let myJSONError { print(myJSONError) } return nil } // Convert from JSON to nsdata func jsonToNSData(json: AnyObject) -> NSData?{ do { return try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) as NSData? } catch let myJSONError { print(myJSONError) } return nil; } } extension NSDate { /* convenience init(dateString:String, format:String="yyyy-MM-dd") { let formatter = DateFormatter() formatter.timeZone = NSTimeZone.default formatter.dateFormat = format let d = formatter.date(from: dateString) self(timeInterval: 0, since: d!) } */ //compare fecha menor a fecha mayor static public func <(a: NSDate, b: NSDate) -> Bool { return a.compare(b as Date) == ComparisonResult.orderedAscending } //compare fecha mayor a fecha menor static public func >(a: NSDate, b: NSDate) -> Bool { return a.compare(b as Date) == ComparisonResult.orderedDescending } //compare si es igual static public func ==(a: NSDate, b: NSDate) -> Bool { return a.compare(b as Date) == ComparisonResult.orderedSame } } extension UITextField{ @IBInspectable var placeHolderColor: UIColor? { get { return self.placeHolderColor } set { self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!]) } } } extension UILabel{ var defaultFont: UIFont? { get { return self.font } set { self.font = newValue } } } extension UINavigationItem { //Make the title 2 lines with a title and a subtitle func addTitleAndSubtitleToNavigationBar( title:String, subtitle:String) -> UIView { let titleLabel = UILabel(frame: CGRect(x: 0, y: -2, width: 0, height: 0)) titleLabel.backgroundColor = UIColor.clear titleLabel.textColor = UIColor.gray titleLabel.font = UIFont.boldSystemFont(ofSize: 17) titleLabel.text = title titleLabel.sizeToFit() let subtitleLabel = UILabel(frame: CGRect(x: 0, y: 18, width: 0, height: 0)) subtitleLabel.backgroundColor = UIColor.clear subtitleLabel.textColor = UIColor.black subtitleLabel.font = UIFont.systemFont(ofSize: 12) subtitleLabel.text = subtitle subtitleLabel.sizeToFit() let titleView = UIView(frame: CGRect(x: 0, y: 0, width: max(titleLabel.frame.size.width, subtitleLabel.frame.size.width), height: 30)) titleView.addSubview(titleLabel) titleView.addSubview(subtitleLabel) let widthDiff = subtitleLabel.frame.size.width - titleLabel.frame.size.width if widthDiff < 0 { let newX = widthDiff / 2 subtitleLabel.frame.origin.x = abs(newX) } else { let newX = widthDiff / 2 titleLabel.frame.origin.x = newX } return titleView } } extension UIViewController { private var availableWidthForTitle: CGFloat { get { var total = UIScreen.main.bounds.width if let navigationBar = navigationController?.navigationBar { var maxYLeft: CGFloat = 0 var minYRight: CGFloat = 0 for subview in navigationBar.subviews.dropFirst() where !subview.isHidden { if subview.frame.origin.x < total / 2 { let rightEdge = subview.frame.origin.x + subview.frame.size.width if rightEdge < total / 2 { maxYLeft = max(maxYLeft, rightEdge) } } else { let leftEdge = subview.frame.origin.x if leftEdge > total / 2 { minYRight = min(minYRight, total - leftEdge) } } } total = total - maxYLeft - minYRight } return total } } func setTitle(title:String, subtitle:String?) { if (subtitle == nil) { self.title = title.uppercased() } else { let titleLabel = UILabel(frame: CGRect(x:0 , y: -2, width: 0, height: 0)) titleLabel.backgroundColor = UIColor.clear titleLabel.textColor = UIColor.white // titleLabel.font = Font titleLabel.textAlignment = .center let availableWidth = availableWidthForTitle let titleUppercase = NSString(string: title.uppercased()) if titleUppercase.boundingRect( // if title needs to be truncated with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName : titleLabel.font], context: nil).width > availableWidth { let truncTitle: NSMutableString = "" for nextChar in title.uppercased().characters { if truncTitle.boundingRect( with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName : titleLabel.font], context: nil).width > availableWidth - 16 { // for ellipsis + some margin truncTitle.append("...") break } else { truncTitle.append(String(nextChar)) } } titleLabel.text = truncTitle as String } else { // use title as-is titleLabel.text = titleUppercase as String } titleLabel.sizeToFit() let subtitleLabel = UILabel(frame: CGRect(x: 0, y: 18, width: 0, height: 0)) subtitleLabel.backgroundColor = UIColor.clear subtitleLabel.textColor = UIColor.white // subtitleLabel.font = MaterialFont.italicSystemFontWithSize(10) subtitleLabel.text = subtitle subtitleLabel.sizeToFit() let titleView = UIView(frame: CGRect(x: 0, y: 0, width: max(titleLabel.frame.size.width, subtitleLabel.frame.size.width), height: 30)) // Center title or subtitle on screen (depending on which is larger) if titleLabel.frame.width >= subtitleLabel.frame.width { var adjustment = subtitleLabel.frame adjustment.origin.x = titleView.frame.origin.x + (titleView.frame.width/2) - (subtitleLabel.frame.width/2) subtitleLabel.frame = adjustment } else { var adjustment = titleLabel.frame adjustment.origin.x = titleView.frame.origin.x + (titleView.frame.width/2) - (titleLabel.frame.width/2) titleLabel.frame = adjustment } titleView.addSubview(titleLabel) titleView.addSubview(subtitleLabel) self.navigationItem.titleView = titleView } } } public extension UIDevice { var modelName: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8 , value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,7", "iPad6,8": return "iPad Pro" case "AppleTV5,3": return "Apple TV" case "i386", "x86_64": return "Simulator" default: return identifier } } } extension UIWindow { func visibleViewController() -> UIViewController? { if let rootViewController: UIViewController = self.rootViewController { return UIWindow.getVisibleViewControllerFrom(vc: rootViewController) } return nil } class func getVisibleViewControllerFrom(vc:UIViewController) -> UIViewController { if vc.isKind(of: UINavigationController.self) { let navigationController = vc as! UINavigationController return UIWindow.getVisibleViewControllerFrom( vc: navigationController.visibleViewController!) } else if vc.isKind(of: UITabBarController.self) { let tabBarController = vc as! UITabBarController return UIWindow.getVisibleViewControllerFrom(vc: tabBarController.selectedViewController!) } else { if let presentedViewController = vc.presentedViewController { return UIWindow.getVisibleViewControllerFrom(vc: presentedViewController.presentedViewController!) } else { return vc; } } } }
mit
b34b37722c19b88c8dfb6fcc06d73f89
33.926546
202
0.574955
4.917982
false
false
false
false
onmyway133/Github.swift
Sources/Classes/Client/Error.swift
1
6942
// // Client+Error.swift // GithubSwift // // Created by Khoa Pham on 27/03/16. // Copyright © 2016 Fantageek. All rights reserved. // import Foundation import Sugar public enum ErrorCode: Int { case NotFound = 404 case AuthenticationFailed = 666 case ServiceRequestFailed = 667 case ConnectionFailed = 668 case JSONParsingFailed = 669 case BadRequest = 670 case TwoFactorAuthenticationOneTimePasswordRequired = 671 case UnsupportedServer = 672 case OpeningBrowserFailed = 673 case RequestForbidden = 674 case TokenAuthenticationUnsupported = 675 case UnsupportedServerScheme = 676 case SecureConnectionFailed = 677 } public enum ErrorKey: String { case RequestURLKey case HTTPStatusCodeKey case OneTimePasswordMediumKey case OAuthScopesStringKey case RequestStateRedirectedKey case DescriptionKey case MessagesKey } public struct Error { public static func authenticationRequiredError() -> NSError { let userInfo = [ NSLocalizedDescriptionKey: "Sign In Required".localized, NSLocalizedFailureReasonErrorKey: "You must sign in to access user information.".localized ] return NSError(domain: Constant.errorDomain, code: ErrorCode.AuthenticationFailed.rawValue, userInfo: userInfo) } public static func tokenUnsupportedError() -> NSError { let userInfo = [ NSLocalizedDescriptionKey: "Password Required".localized, NSLocalizedFailureReasonErrorKey: "You must sign in with a password. Token authentication is not supported.".localized ] return NSError(domain: Constant.errorDomain, code:ErrorCode.TokenAuthenticationUnsupported.rawValue, userInfo: userInfo) } public static func unsupportedVersionError() -> NSError { let userInfo = [ NSLocalizedDescriptionKey: "Unsupported Server".localized, NSLocalizedFailureReasonErrorKey: "The request failed because the server is out of date.".localized ] return NSError(domain: Constant.errorDomain, code: ErrorCode.UnsupportedServer.rawValue, userInfo: userInfo) } public static func userRequiredError() -> NSError { let userInfo = [ NSLocalizedDescriptionKey: "Username Required".localized, NSLocalizedFailureReasonErrorKey: "No username was provided for getting user information.".localized ] return NSError(domain: Constant.errorDomain, code: ErrorCode.AuthenticationFailed.rawValue, userInfo: userInfo) } public static func openingBrowserError(url: NSURL) -> NSError { let userInfo = [ NSLocalizedDescriptionKey: "Could not open web browser".localized, NSLocalizedRecoverySuggestionErrorKey: "Please make sure you have a default web browser set.".localized, NSURLErrorKey: url ] return NSError(domain: Constant.errorDomain, code: ErrorCode.OpeningBrowserFailed.rawValue, userInfo: userInfo) } internal static func transform(error: NSError, response: NSHTTPURLResponse?) -> NSError { guard let response = response else { return error } let httpCode = response.statusCode var errorCode = ErrorCode.ConnectionFailed.rawValue var userInfo: JSONDictionary = [:] userInfo.update(evalutedUserInfo(error, response: response)) switch httpCode { case 401: let errorTemplate = Error.authenticationRequiredError() errorCode = errorTemplate.code if let info = errorTemplate.userInfo as? JSONDictionary { userInfo.update(info) } if let oneTimePassword = response.allHeaderFields[Constant.oneTimePasswordHeaderField] as? String, medium = oneTimePasswordMedium(oneTimePassword) { errorCode = ErrorCode.TwoFactorAuthenticationOneTimePasswordRequired.rawValue userInfo[ErrorKey.OneTimePasswordMediumKey.rawValue] = medium.rawValue } case 400: errorCode = ErrorCode.BadRequest.rawValue case 403: errorCode = ErrorCode.RequestForbidden.rawValue case 404: errorCode = ErrorCode.NotFound.rawValue case 422: errorCode = ErrorCode.ServiceRequestFailed.rawValue default: if error.domain == NSURLErrorDomain { switch error.code { case NSURLErrorSecureConnectionFailed, NSURLErrorServerCertificateHasBadDate, NSURLErrorServerCertificateHasUnknownRoot, NSURLErrorServerCertificateUntrusted, NSURLErrorServerCertificateNotYetValid, NSURLErrorClientCertificateRejected, NSURLErrorClientCertificateRequired: errorCode = ErrorCode.SecureConnectionFailed.rawValue default: break } } } // if (operation.userInfo[OCTClientErrorRequestStateRedirected] != nil) { // errorCode = OCTClientErrorUnsupportedServerScheme; // } userInfo[ErrorKey.HTTPStatusCodeKey.rawValue] = httpCode // if (operation.request.URL != nil) userInfo[OCTClientErrorRequestURLKey] = operation.request.URL; // if (operation.error != nil) userInfo[NSUnderlyingErrorKey] = operation.error; if let scopes = response.allHeaderFields[Constant.oAuthScopesHeaderField] as? String { userInfo[ErrorKey.OAuthScopesStringKey.rawValue] = scopes } return NSError(domain: Constant.errorDomain, code: errorCode, userInfo: userInfo) } private static func evalutedUserInfo(error: NSError, response: NSHTTPURLResponse) -> JSONDictionary { // TODO return [:] } private static func evaluatedErrorMessage(dict: JSONDictionary) -> String { let resource = dict["resource"] as? String ?? "" if let message = dict["message"] as? String { return "• \(resource) \(message).".localized } else { let field = dict["field"] as? String ?? "" let codeType = dict["code"] as? String ?? "" func format(message: String) -> String { return String(format: message, resource, field) } var codeString = format("%@ %@ is missing") switch codeType { case "missing": codeString = format("%@ %@ does not exist".localized) case "missing_field": codeString = format("%@ %@ is missing".localized) case "invalid": codeString = format("%@ %@ is invalid".localized) case "already_exists": codeString = format("%@ %@ already exists".localized) default: break } return "• \(codeString)." } } private static func oneTimePasswordMedium(header: String) -> OneTimePasswordMedium? { let segments = header.componentsSeparatedByString(";").map { return $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } guard segments.count == 2, let status = segments.first, medium = segments.last where status.lowercaseString == "required" else { return nil } return OneTimePasswordMedium(rawValue: medium) } }
mit
97246fe407b5ec2325e3ee5432e484d0
33.512438
124
0.700159
5.247352
false
false
false
false
vlfm/VFTableViewAdapter
src/ViewController/TableViewController.swift
1
1763
import UIKit open class TableViewController: UITableViewController { private var isWillAppearFirstTime = true public let tableViewAdapter = TableViewAdapter() override open func viewDidLoad() { super.viewDidLoad() tableViewAdapter.target = self tableView.dataSource = tableViewAdapter tableView.delegate = tableViewAdapter tableView.estimatedRowHeight = 100 registerTableViewComponents() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if isWillAppearFirstTime { createTable() isWillAppearFirstTime = false } } open func registerTableViewComponents() { tableView.register(UITableViewCell.self, forCellReuseIdentifier: TableRow.ReuseIdentifier.reuseIdentifier(forCellType: UITableViewCell.self)) } public final func createTable() { guard isViewLoaded else { return } tableViewAdapter.createTable {table in self.createTable(table: table) self.didCreateTable(table: table) } tableView.reloadData() } public final func updateTable() { guard isViewLoaded else { return } tableViewAdapter.updateTable {table in self.updateTable(table: table) self.didUpdateTable(table: table) } tableView.reloadData() } open func createTable(table: Table) { } open func updateTable(table: Table) { } open func didCreateTable(table: Table) { } open func didUpdateTable(table: Table) { } }
apache-2.0
59c89051cee3526634daed2ff1b16d45
24.185714
149
0.601248
5.857143
false
false
false
false
khizkhiz/swift
test/Prototypes/FloatingPoint.swift
2
48116
// RUN: rm -rf %t && mkdir -p %t // RUN: %S/../../utils/line-directive %s -- %target-build-swift -parse-stdlib %s -o %t/a.out // RUN: %S/../../utils/line-directive %s -- %target-run %t/a.out // REQUIRES: executable_test import Swift // TODO: These should probably subsumed into UnsignedInteger or // another integer protocol. Dave has already done some work here. public protocol FloatingPointRepresentation : UnsignedInteger { var leadingZeros: UInt { get } func <<(left: Self, right: Self) -> Self func >>(left: Self, right: Self) -> Self init(_ value: UInt) } extension UInt64 : FloatingPointRepresentation { public var leadingZeros: UInt { return UInt(_countLeadingZeros(Int64(bitPattern: self))) } } extension UInt32 : FloatingPointRepresentation { public var leadingZeros: UInt { return UInt64(self).leadingZeros - 32 } } // Ewwww? <rdar://problem/20060017> #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) import Glibc #endif public protocol FloatingPoint : Comparable, SignedNumber, IntegerLiteralConvertible, FloatLiteralConvertible { /// An unsigned integer type large enough to hold the significand field. associatedtype SignificandBits: FloatingPointRepresentation /// Positive infinity. /// /// Compares greater than all finite numbers. static var infinity: Self { get } /// Quiet NaN. /// /// Compares not equal to every value, including itself. Most operations /// with a `NaN` operand will produce a `NaN` result. static var NaN: Self { get } /// NaN with specified `payload`. /// /// Compares not equal to every value, including itself. Most operations /// with a `NaN` operand will produce a `NaN` result. static func NaN(payload bits: SignificandBits, signaling: Bool) -> Self /// The greatest finite value. /// /// Compares greater than or equal to all finite numbers, but less than /// infinity. static var greatestFiniteMagnitude: Self { get } // Note -- rationale for "ulp" instead of "epsilon": // We do not use that name because it is ambiguous at best and misleading // at worst: // // - Historically several definitions of "machine epsilon" have commonly // been used, which differ by up to a factor of two or so. By contrast // "ulp" is a term with a specific unambiguous definition. // // - Some languages have used "epsilon" to refer to wildly different values, // such as `leastMagnitude`. // // - Inexperienced users often believe that "epsilon" should be used as a // tolerance for floating-point comparisons, because of the name. It is // nearly always the wrong value to use for this purpose. /// The unit in the last place of 1.0. /// /// This is the weight of the least significant bit of the significand of 1.0, /// or the positive difference between 1.0 and the next greater representable /// number. /// /// This value (or a similar value) is often called "epsilon", "machine /// epsilon", or "macheps" in other languages. static var ulp: Self { get } /// The least positive normal value. /// /// Compares less than or equal to all positive normal numbers. There may /// be smaller positive numbers, but they are "subnormal", meaning that /// they are represented with less precision than normal numbers. static var leastNormalMagnitude: Self { get } /// The least positive value. /// /// Compares less than or equal to all positive numbers, but greater than /// zero. If the target supports subnormal values, this is smaller than /// `leastNormalMagnitude`; otherwise (as on armv7), they are equal. static var leastMagnitude: Self { get } /// The `signbit`. True for negative numbers, false for positive. /// /// This is simply the high-order bit in the encoding of `self`, regardless /// of the encoded value. This *is not* the same thing as `self < 0`. /// In particular: /// /// - If `x` is `-0.0`, then `x.signbit` is `true`, but `x < 0` is `false`. /// - If `x` is `NaN`, then `x.signbit` could be either `true` or `false`, /// (the signbit of `NaN` is unspecified) but `x < 0` is `false`. /// /// Implements the IEEE-754 `isSignMinus` operation. var signbit: Bool { get } /// The mathematical `exponent`. /// /// If `x` is a normal floating-point number, then `exponent` is simply the /// raw encoded exponent interpreted as a signed integer with the exponent /// bias removed. /// /// For subnormal numbers, `exponent` is computed as though the exponent /// range of `Self` were unbounded. In particular, `x.exponent` will /// be smaller than the minimum normal exponent that can be encoded. /// /// Other edge cases: /// /// - If `x` is zero, then `x.exponent` is `Int.min`. /// - If `x` is +/-infinity or NaN, then `x.exponent` is `Int.max` /// /// Implements the IEEE-754 `logB` operation. var exponent: Int { get } /// The mathematical `significand` (sometimes erroneously called the "mantissa"). /// /// `significand` is computed as though the exponent range of `Self` were /// unbounded; if `x` is a finite non-zero number, then `x.significand` is /// in the range `[1,2)`. /// /// For other values of `x`, `x.significand` is defined as follows: /// /// - If `x` is zero, then `x.significand` is 0.0. /// - If `x` is infinity, then `x.significand` is 1.0. /// - If `x` is NaN, then `x.significand` is NaN. /// /// For all floating-point `x`, if we define y by: /// /// let y = Self(signbit: x.signbit, exponent: x.exponent, /// significand: x.significand) /// /// then `y` is equivalent to `x`, meaning that `y` is `x` canonicalized. /// For types that do not have non-canonical encodings, this implies that /// `y` has the same encoding as `x`. Note that this is a stronger /// statement than `x == y`, as it implies that both the sign of zero and /// the payload of NaN are preserved. var significand: Self { get } /// Combines a signbit, exponent, and significand to produce a floating-point /// datum. /// /// In common usage, `significand` will generally be a number in the range /// `[1,2)`, but this is not required; the initializer supports any valid /// floating-point datum. The result is: /// /// `(-1)^signbit * significand * 2^exponent` /// /// (where ^ denotes the mathematical operation of exponentiation) computed /// as if by a single correctly-rounded floating-point operation. If this /// value is outside the representable range of the type, overflow or /// underflow will occur, and zero, a subnormal value, or infinity will be /// returned, as with any basic operation. Other edge cases: /// /// - If `significand` is zero or infinite, the result is zero or infinite, /// regardless of the value of `exponent`. /// - If `significand` is NaN, the result is NaN. /// /// Note that for any floating-point datum `x` the result of /// /// `Self(signbit: x.signbit, /// exponent: x.exponent, /// significand: x.significand)` /// /// is "the same" as `x` (if `x` is NaN, then this result is also `NaN`, but /// it might be a different NaN). /// /// Because of these properties, this initializer also implements the /// IEEE-754 `scaleB` operation. init(signbit: Bool, exponent: Int, significand: Self) /// The unit in the last place of `self`. /// /// This is the value of the least significant bit in the significand of /// `self`. For most numbers `x`, this is the difference between `x` and /// the next greater (in magnitude) representable number. There are some /// edge cases to be aware of: /// /// - `greatestFiniteMagnitude.ulp` is a finite number, even though /// the next greater representable value is `infinity`. /// - `x.ulp` is `NaN` if `x` is not a finite number. /// - If `x` is very small in magnitude, then `x.ulp` may be a subnormal /// number. On targets that do not support subnormals, `x.ulp` may be /// flushed to zero. var ulp: Self { get } // TODO: IEEE-754 requires the following operations for every FP type. // They need bindings (names) for Swift. Some of them map to existing // C library functions, so the default choice would be to use the C // names, but we should consider if other names would be more appropriate // for Swift. // // For now I have simply used the IEEE-754 names to track them. // // The C bindings for these operations are: // roundToIntegralTiesToEven roundeven (n1778) // roundToIntegralTiesAway round (c99) // roundToIntegralTowardZero trunc (c99) // roundToIntegralTowardPositive ceil (c90) // roundToIntegralTowardNegative floor (c90) // // Also TBD: should these only be available as free functions? /// Rounds `self` to nearest integral value, with halfway cases rounded /// to the even integer. func roundToIntegralTiesToEven() -> Self /// Rounds `self` to the nearest integral value, with halfway cases rounded /// away from zero. func roundToIntegralTiesToAway() -> Self /// Rounds `self` to an integral value towards zero. func roundToIntegralTowardZero() -> Self /// Rounds `self` to an integral value toward positive infinity. func roundToIntegralTowardPositive() -> Self /// Rounds `self` to an integral value toward negative infinity. func roundToIntegralTowardNegative() -> Self // TODO: roundToIntegralExact requires a notion of flags and of // rounding modes, which require language design. // TODO: should nextUp and nextDown be computed properties or funcs? // For me, these sit right on the edge in terms of what makes sense. /// The least `Self` that compares greater than `self`. /// /// - If `x` is `-infinity`, then `x.nextUp` is `-greatestMagnitude`. /// - If `x` is `-leastMagnitude`, then `x.nextUp` is `-0.0`. /// - If `x` is zero, then `x.nextUp` is `leastMagnitude`. /// - If `x` is `greatestMagnitude`, then `x.nextUp` is `infinity`. /// - If `x` is `infinity` or `NaN`, then `x.nextUp` is `x`. var nextUp: Self { get } /// The greatest `Self` that compares less than `self`. /// /// `x.nextDown` is equivalent to `-(-x).nextUp` var nextDown: Self { get } // TODO: IEEE-754 defines the following semantics for remainder(x, y). // // This operation differs from what is currently provided by the % // operator, which implements fmod, not remainder. The difference is // that fmod is the remainder of truncating division (the sign matches // that of x and the magnitude is in [0, y)), whereas remainder is what // results from round-to-nearest division (it lies in [y/2, y/2]). // // I would prefer that % implement the remainder operation, but this is // a fairly significant change to the language that needs discussion. // Both operations should be probably be available, anyway. /// Remainder of `x` divided by `y`. /// /// `remainder(x,y)` is defined for finite `x` and `y` by the mathematical /// relation `r = x - yn`, where `n` is the integer nearest to the exact /// number (*not* the floating-point value) `x/y`. If `x/y` is exactly /// halfway between two integers, `n` is even. `remainder` is always /// exact, and therefore is not affected by the rounding mode. /// /// If `remainder(x,y)` is zero, it has the same sign as `x`. If `y` is /// infinite, then `remainder(x,y)` is `x`. static func remainder(x: Self, _ y: Self) -> Self // TODO: The IEEE-754 "minNumber" and "maxNumber" operations should // probably be provided by the min and max generic free functions, but // there is some question of how best to do that. As an initial // binding, they are provided as static functions. // // We will end up naming the static functions something else // (if we keep them at all) to avoid confusion with Int.min, etc. /// The minimum of `x` and `y`. /// /// Returns `x` if `x < y`, `y` if `y < x`, and whichever of `x` or `y` /// is a number if the other is NaN. The result is NaN only if both /// arguments are NaN. static func min(x: Self, _ y: Self) -> Self /// The maximum of `x` and `y`. /// /// Returns `x` if `x > y`, `y` if `y > x`, and whichever of `x` or `y` /// is a number if the other is NaN. The result is NaN only if both /// arguments are NaN. static func max(x: Self, _ y: Self) -> Self // Note: IEEE-754 calls these "minNumMag" and "maxNumMag". C (n1778) // uses "fminmag" and "fmaxmag". Neither of these strike me as very // good names. I prefer minMagnitude and maxMagnitude, which are // clear without being too wordy. /// Whichever of `x` or `y` has lesser magnitude. /// /// Returns `x` if `|x| < |y|`, `y` if `|y| < |x|`, and whichever of /// `x` or `y` is a number if the other is NaN. The result is NaN /// only if both arguments are NaN. static func minMagnitude(left: Self, _ right: Self) -> Self /// Whichever of `x` or `y` has greater magnitude. /// /// Returns `x` if `|x| > |y|`, `y` if `|y| > |x|`, and whichever of /// `x` or `y` is a number if the other is NaN. The result is NaN /// only if both arguments are NaN. static func maxMagnitude(left: Self, _ right: Self) -> Self func +(x: Self, y: Self) -> Self func -(x: Self, y: Self) -> Self func *(x: Self, y: Self) -> Self func /(x: Self, y: Self) -> Self // Implementation details of formatOf operations. static func _addStickyRounding(x: Self, _ y: Self) -> Self static func _mulStickyRounding(x: Self, _ y: Self) -> Self static func _divStickyRounding(x: Self, _ y: Self) -> Self static func _sqrtStickyRounding(x: Self) -> Self static func _mulAddStickyRounding(x: Self, _ y: Self, _ z: Self) -> Self // TODO: do we actually want to provide remainder as an operator? It's // definitely not obvious to me that we should, but we have until now. // See further discussion with func remainder(x,y) above. func %(x: Self, y: Self) -> Self // Conversions from all integer types. init(_ value: Int8) init(_ value: Int16) init(_ value: Int32) init(_ value: Int64) init(_ value: Int) init(_ value: UInt8) init(_ value: UInt16) init(_ value: UInt32) init(_ value: UInt64) init(_ value: UInt) init(_ value: SignificandBits) // Conversions from all floating-point types. init(_ value: Float) init(_ value: Double) #if arch(i386) || arch(x86_64) init(_ value: Float80) #endif // TODO: where do conversions to/from string live? IEEE-754 requires // conversions to/from decimal character and hexadecimal character // sequences. /// Implements the IEEE-754 copy operation. prefix func +(value: Self) -> Self // IEEE-754 negate operation is prefix `-`, provided by SignedNumber. // TODO: ensure that the optimizer is able to produce a simple xor for -. // IEEE-754 abs operation is the free function abs( ), provided by // SignedNumber. TODO: ensure that the optimizer is able to produce // a simple and or bic for abs( ). // TODO: should this be the free function copysign(x, y) instead, a la C? /// Returns datum with magnitude of `self` and sign of `from`. /// /// Implements the IEEE-754 copysign operation. func copysign(from: Self) -> Self // TODO: "signaling/quiet" comparison predicates if/when we have a model for // floating-point flags and exceptions in Swift. /// The floating point "class" of this datum. /// /// Implements the IEEE-754 `class` operation. var floatingPointClass: FloatingPointClassification { get } /// True if and only if `self` is zero. var isZero: Bool { get } /// True if and only if `self` is subnormal. /// /// A subnormal number does not use the full precision available to normal /// numbers of the same format. Zero is not a subnormal number. var isSubnormal: Bool { get } /// True if and only if `self` is normal. /// /// A normal number uses the full precision available in the format. Zero /// is not a normal number. var isNormal: Bool { get } /// True if and only if `self` is finite. /// /// If `x.isFinite` is `true`, then one of `x.isZero`, `x.isSubnormal`, or /// `x.isNormal` is also `true`, and `x.isInfinite` and `x.isNaN` are /// `false`. var isFinite: Bool { get } /// True if and only if `self` is infinite. /// /// Note that `isFinite` and `isInfinite` do not form a dichotomy, because /// they are not total. If `x` is `NaN`, then both properties are `false`. var isInfinite: Bool { get } /// True if and only if `self` is NaN ("not a number"). var isNaN: Bool { get } /// True if and only if `self` is a signaling NaN. var isSignaling: Bool { get } /// True if and only if `self` is canonical. /// /// Every floating-point datum of type Float or Double is canonical, but /// non-canonical values of type Float80 exist. These are known as /// "pseudo-denormal", "unnormal", "pseudo-infinity", and "pseudo-nan". /// (https://en.wikipedia.org/wiki/Extended_precision#x86_Extended_Precision_Format) var isCanonical: Bool { get } /// A total order relation on all values of type Self (including NaN). func totalOrder(other: Self) -> Bool /// A total order relation that compares magnitudes. func totalOrderMagnitude(other: Self) -> Bool // Note: this operation is *not* required by IEEE-754, but it is an oft- // requested feature. TBD: should +0 and -0 be equivalent? Substitution // property of equality says no. // // More adventurous (probably crazy) thought: we *could* make this (or // something like it) the default behavior of the == operator, and make // IEEE-754 equality be the function. IEEE-754 merely dictates that // certain operations be available, not what their bindings in a // language actually are. Their are two problems with this: // // - it violates the hell out of the principle of least surprise, // given that programmers have been conditioned by years of using // other languages. // // - it would introduce a gratuitous minor inefficiency to most // code on the hardware we have today, where IEEE-754 equality is // generally a single test, and "equivalent" is not. // // Still, I want to at least make note of the possibility. /// An equivalence relation on all values of type Self (including NaN). /// /// Unlike `==`, this relation is a formal equivalence relation. In /// particular, it is reflexive. All NaNs compare equal to each other /// under this relation. func equivalent(other: Self) -> Bool } // Features of FloatingPoint that can be implemented without any // dependence on the internals of the type. extension FloatingPoint { public static var NaN: Self { return NaN(payload: 0, signaling: false) } public static var ulp: Self { return Self(1).ulp } public func roundToIntegralTiesToEven() -> Self { fatalError("TODO once roundeven functions are provided in math.h") } public static func minMagnitude(left: Self, _ right: Self) -> Self { fatalError("TODO once fminmag functions are available in libm") } public static func maxMagnitude(left: Self, _ right: Self) -> Self { fatalError("TODO once fmaxmag functions are available in libm") } public static func _addStickyRounding(x: Self, _ y: Self) -> Self { fatalError("TODO: Unimplemented") } public static func _mulStickyRounding(x: Self, _ y: Self) -> Self { fatalError("TODO: Unimplemented") } public static func _divStickyRounding(x: Self, _ y: Self) -> Self { fatalError("TODO: Unimplemented") } public static func _sqrtStickyRounding(x: Self) -> Self { fatalError("TODO: Unimplemented") } public static func _mulAddStickyRounding(x: Self, _ y: Self, _ z: Self) -> Self { fatalError("TODO: Unimplemented") } public var floatingPointClass: FloatingPointClassification { if isSignaling { return .signalingNaN } if isNaN { return .quietNaN } if isInfinite { return signbit ? .negativeInfinity : .positiveInfinity } if isNormal { return signbit ? .negativeNormal : .positiveNormal } if isSubnormal { return signbit ? .negativeSubnormal : .positiveSubnormal } return signbit ? .negativeZero : .positiveZero } public func totalOrderMagnitude(other: Self) -> Bool { return abs(self).totalOrder(abs(other)) } public func equivalent(other: Self) -> Bool { if self.isNaN && other.isNaN { return true } if self.isZero && other.isZero { return self.signbit == other.signbit } return self == other } } public protocol BinaryFloatingPoint: FloatingPoint { /// Values that parameterize the type: static var _exponentBitCount: UInt { get } static var _fractionalBitCount: UInt { get } /// The raw encoding of the exponent field of the floating-point datum. var exponentBitPattern: UInt { get } /// The raw encoding of the significand field of the floating-point datum. var significandBitPattern: SignificandBits { get } /// The least-magnitude member of the binade of `self`. /// /// If `x` is `+/-significand * 2^exponent`, then `x.binade` is /// `+/- 2^exponent`; i.e. the floating point number with the same sign /// and exponent, but a significand of 1.0. var binade: Self { get } /// Combines a signbit, exponent and significand bit patterns to produce a /// floating-point datum. No error-checking is performed by this function; /// the bit patterns are simply concatenated to produce the floating-point /// encoding of the result. init(signbit: Bool, exponentBitPattern: UInt, significandBitPattern: SignificandBits) init<T: BinaryFloatingPoint>(_ other: T) // TODO: IEEE-754 requires that the six basic operations (add, subtract, // multiply, divide, square root, and FMA) be provided from all source // formats to all destination formats, with a single rounding. In order // to satisfy this requirement (which I believe we should), we'll need // something like the following. // // fusedMultiplyAdd needs naming attention for Swift. The C name // fma(x,y,z) might be too terse for the Swift standard library, but // fusedMultiplyAdd is awfully verbose. mulAdd(x, y, z), perhaps? // Or we could go full Obj-C style and do mul(_:, _:, add:), I suppose. // // While `sqrt` and `fma` have traditionally been part of the // math library in C-derived languages, they rightfully belong as part // of the base FloatingPoint protocol in Swift, because they are // IEEE-754 required operations, like + or *. /// The sum of `x` and `y`, correctly rounded to `Self`. static func add<X: BinaryFloatingPoint, Y: BinaryFloatingPoint>(x: X, _ y: Y) -> Self /// The difference of `x` and `y`, correctly rounded to `Self`. static func sub<X: BinaryFloatingPoint, Y: BinaryFloatingPoint>(x: X, _ y: Y) -> Self /// The product of `x` and `y`, correctly rounded to `Self`. static func mul<X: BinaryFloatingPoint, Y: BinaryFloatingPoint>(x: X, _ y: Y) -> Self /// The quotient of `x` and `y`, correctly rounded to `Self`. static func div<X: BinaryFloatingPoint, Y: BinaryFloatingPoint>(x: X, _ y: Y) -> Self /// The square root of `x`, correctly rounded to `Self`. static func sqrt<X: BinaryFloatingPoint>(x: X) -> Self /// (x*y) + z correctly rounded to `Self`. static func mulAdd<X: BinaryFloatingPoint, Y: BinaryFloatingPoint, Z: BinaryFloatingPoint>(x: X, _ y: Y, _ z: Z) -> Self } extension BinaryFloatingPoint { static var _exponentBias: UInt { return Self._infinityExponent >> 1 } static var _infinityExponent: UInt { return 1 << _exponentBitCount - 1 } static var _integralBitMask: SignificandBits { return 1 << SignificandBits(UIntMax(_fractionalBitCount)) } static var _fractionalBitMask: SignificandBits { return _integralBitMask - 1 } static var _quietBitMask: SignificandBits { return _integralBitMask >> 1 } static var _payloadBitMask: SignificandBits { return _quietBitMask - 1 } public static var infinity: Self { return Self(signbit: false, exponentBitPattern:_infinityExponent, significandBitPattern: 0) } public static func NaN(payload bits: SignificandBits, signaling: Bool) -> Self { var significand = bits & _payloadBitMask if signaling { // Ensure at least one bit is set in payload, otherwise we will get // an infinity instead of NaN. if significand == 0 { significand = _quietBitMask >> 1 } } else { significand = significand | _quietBitMask } return Self(signbit: false, exponentBitPattern: _infinityExponent, significandBitPattern: significand) } public static var greatestFiniteMagnitude: Self { return Self(signbit: false, exponentBitPattern: _infinityExponent - 1, significandBitPattern: _fractionalBitMask) } public static var leastNormalMagnitude: Self { return Self(signbit: false, exponentBitPattern: 1, significandBitPattern: 0) } public static var leastMagnitude: Self { #if arch(arm) return .leastNormalMagnitude #else return Self(signbit: false, exponentBitPattern: 0, significandBitPattern: 1) #endif } public var exponent: Int { if !isFinite { return .max } let provisional = Int(exponentBitPattern) - Int(Self._exponentBias) if isNormal { return provisional } if isZero { return .min } let shift = significandBitPattern.leadingZeros - Self._fractionalBitMask.leadingZeros return provisional - Int(shift) } public var significand: Self { if isNaN { return self } if isNormal { return Self(Self._integralBitMask | significandBitPattern) * Self.ulp } if isZero { return 0 } let shift = 1 + significandBitPattern.leadingZeros - Self._fractionalBitMask.leadingZeros return Self(significandBitPattern << SignificandBits(shift)) * Self.ulp } public init(signbit: Bool, exponent: Int, significand: Self) { var result = significand if signbit { result = -result } if significand.isFinite && !significand.isZero { var clamped = exponent if clamped < Self.leastNormalMagnitude.exponent { clamped = max(clamped, 3*Self.leastNormalMagnitude.exponent) while clamped < Self.leastNormalMagnitude.exponent { result = result * Self.leastNormalMagnitude clamped += Self.leastNormalMagnitude.exponent } } else if clamped > Self.greatestFiniteMagnitude.exponent { clamped = min(clamped, 3*Self.greatestFiniteMagnitude.exponent) while clamped > Self.greatestFiniteMagnitude.exponent { result = result * Self.greatestFiniteMagnitude.binade clamped -= Self.greatestFiniteMagnitude.exponent } } let scale = Self(signbit: false, exponentBitPattern: UInt(Int(Self._exponentBias) + clamped), significandBitPattern: Self._integralBitMask) result = result * scale } self = result } public var ulp: Self { if !isFinite { return .NaN } if exponentBitPattern > Self._fractionalBitCount { // ulp is normal, so we directly manifest its exponent and use a // significand of 1. let ulpExponent = exponentBitPattern - Self._fractionalBitCount return Self(signbit: false, exponentBitPattern: ulpExponent, significandBitPattern: 0) } if exponentBitPattern >= 1 { // self is normal, but ulp is subnormal; we need to compute a shift // to apply to the significand. let ulpShift = SignificandBits(exponentBitPattern - 1) return Self(signbit: false, exponentBitPattern: 0, significandBitPattern: 1 << ulpShift) } return Self(signbit:false, exponentBitPattern:0, significandBitPattern:1) } public var nextUp: Self { if isNaN { return self } if signbit { if significandBitPattern == 0 { if exponentBitPattern == 0 { return Self.leastMagnitude } return Self(signbit: true, exponentBitPattern: exponentBitPattern - 1, significandBitPattern: Self._fractionalBitMask) } return Self(signbit: true, exponentBitPattern: exponentBitPattern, significandBitPattern: significandBitPattern - 1) } if isInfinite { return self } if significandBitPattern == Self._fractionalBitMask { return Self(signbit: false, exponentBitPattern: exponentBitPattern + 1, significandBitPattern: 0) } return Self(signbit: false, exponentBitPattern: exponentBitPattern, significandBitPattern: significandBitPattern + 1) } public var nextDown: Self { return -(-self).nextUp } public var binade: Self { if !isFinite { return .NaN } if isNormal { return Self(signbit: false, exponentBitPattern: exponentBitPattern, significandBitPattern: Self._integralBitMask) } if isZero { return 0 } let shift = significandBitPattern.leadingZeros - Self._integralBitMask.leadingZeros let significand = Self._integralBitMask >> SignificandBits(shift) return Self(signbit: false, exponentBitPattern: 0, significandBitPattern: significand) } public static func add<X: BinaryFloatingPoint, Y: BinaryFloatingPoint>(x: X, _ y: Y) -> Self { if X._fractionalBitCount < Y._fractionalBitCount { return add(y, x) } if X._fractionalBitCount <= Self._fractionalBitCount { return Self(x) + Self(y) } return Self(X._addStickyRounding(x, X(y))) } public static func sub<X: BinaryFloatingPoint, Y: BinaryFloatingPoint>(x: X, _ y: Y) -> Self { return Self.add(x, -y) } public static func mul<X: BinaryFloatingPoint, Y: BinaryFloatingPoint>(x: X, _ y: Y) -> Self { if X._fractionalBitCount < Y._fractionalBitCount { return mul(y, x) } if X._fractionalBitCount <= Self._fractionalBitCount { return Self(x) * Self(y) } return Self(X._mulStickyRounding(x, X(y))) } public static func div<X: BinaryFloatingPoint, Y: BinaryFloatingPoint>(x: X, _ y: Y) -> Self { if X._fractionalBitCount <= Self._fractionalBitCount && Y._fractionalBitCount <= Self._fractionalBitCount { return Self(x) / Self(y) } if X._fractionalBitCount < Y._fractionalBitCount { return Self(Y._divStickyRounding(Y(x), y)) } return Self(X._divStickyRounding(x, X(y))) } public static func sqrt<X: BinaryFloatingPoint>(x: X) -> Self { if X._fractionalBitCount <= Self._fractionalBitCount { return sqrt(Self(x)) } return Self(X._sqrtStickyRounding(x)) } public static func mulAdd<X: BinaryFloatingPoint, Y: BinaryFloatingPoint, Z: BinaryFloatingPoint>(x: X, _ y: Y, _ z: Z) -> Self { if X._fractionalBitCount < Y._fractionalBitCount { return mulAdd(y, x, z) } if X._fractionalBitCount <= Self._fractionalBitCount && Z._fractionalBitCount <= Self._fractionalBitCount { return mulAdd(Self(x), Self(y), Self(z)) } if X._fractionalBitCount < Z._fractionalBitCount { return Self(Z._mulAddStickyRounding(Z(x), Z(y), z)) } return Self(X._mulAddStickyRounding(x, X(y), X(z))) } public var absoluteValue: Self { return Self(signbit: false, exponentBitPattern: exponentBitPattern, significandBitPattern: significandBitPattern) } public func copysign(from: Self) -> Self { return Self(signbit: from.signbit, exponentBitPattern: exponentBitPattern, significandBitPattern: significandBitPattern) } public var isZero: Bool { return exponentBitPattern == 0 && significandBitPattern == 0 } public var isSubnormal: Bool { return exponentBitPattern == 0 && significandBitPattern != 0 } public var isNormal: Bool { return exponentBitPattern > 0 && isFinite } public var isFinite: Bool { return exponentBitPattern < Self._infinityExponent } public var isInfinite: Bool { return exponentBitPattern == Self._infinityExponent && significandBitPattern == Self._integralBitMask } public var isNaN: Bool { return exponentBitPattern == Self._infinityExponent && !isInfinite } public var isSignaling: Bool { return isNaN && (significandBitPattern & Self._quietBitMask == 0) } public var isCanonical: Bool { return true } public func totalOrder(other: Self) -> Bool { // Every negative-signed value (even NaN) is less than every positive- // signed value, so if the signs do not match, we simply return the // signbit of self. if signbit != other.signbit { return signbit } // Signbits match; look at exponents. if exponentBitPattern > other.exponentBitPattern { return signbit } if exponentBitPattern < other.exponentBitPattern { return !signbit } // Signs and exponents match, look at significands. if significandBitPattern > other.significandBitPattern { return signbit } if significandBitPattern < other.significandBitPattern { return !signbit } return true } } public protocol FloatingPointInterchange: FloatingPoint { /// An unsigned integer type used to represent floating-point encodings. associatedtype BitPattern: FloatingPointRepresentation /// Interpret `encoding` as a little-endian encoding of `Self`. init(littleEndian encoding: BitPattern) /// Interpret `encoding` as a big-endian encoding of `Self`. init(bigEndian encoding: BitPattern) /// Get the little-endian encoding of `self` as an integer. var littleEndian: BitPattern { get } /// Get the big-endian encoding of `self` as an integer. var bigEndian: BitPattern { get } } extension FloatingPointInterchange { public init(littleEndian encoding: BitPattern) { #if arch(i386) || arch(x86_64) || arch(arm) || arch(arm64) || arch(powerpc64le) self = unsafeBitCast(encoding, to: Self.self) #else _UnsupportedArchitectureError() #endif } public init(bigEndian encoding: BitPattern) { fatalError("TODO: with low-level generic integer type support for bswap.") } public var littleEndian: BitPattern { #if arch(i386) || arch(x86_64) || arch(arm) || arch(arm64) || arch(powerpc64le) return unsafeBitCast(self, to: BitPattern.self) #else _UnsupportedArchitectureError() #endif } public var bigEndian: BitPattern { fatalError("TODO: with low-level generic integer type support for bswap.") } } extension Float : BinaryFloatingPoint, FloatingPointInterchange { var _representation: UInt32 { return unsafeBitCast(self, to: UInt32.self) } public typealias SignificandBits = UInt32 public typealias BitPattern = UInt32 public static var _fractionalBitCount: UInt { return 23 } public static var _exponentBitCount: UInt { return 8 } public var signbit: Bool { return _representation >> 31 == 1 } public var exponentBitPattern: UInt { return UInt(_representation >> 23) & 0xff } public var significandBitPattern: SignificandBits { return _representation & Float._fractionalBitMask } public init(signbit: Bool, exponentBitPattern: UInt, significandBitPattern: SignificandBits) { let sign = SignificandBits(signbit ? 1 : 0) << 31 let exponent = SignificandBits(exponentBitPattern) << 23 let _representation = sign | exponent | significandBitPattern self = unsafeBitCast(_representation, to: Float.self) } public init<T: BinaryFloatingPoint>(_ other: T) { // rdar://16980851 #if does not work with 'switch' #if arch(i386) || arch(x86_64) switch other { case let f as Float: self = f case let d as Double: self = Float(d) case let ld as Float80: self = Float(ld) default: fatalError() } #else switch other { case let f as Float: self = f case let d as Double: self = Float(d) default: fatalError() } #endif } public func roundToIntegralTiesToAway() -> Float { return roundf(self) } public func roundToIntegralTowardZero() -> Float { return truncf(self) } public func roundToIntegralTowardPositive() -> Float { return ceilf(self) } public func roundToIntegralTowardNegative() -> Float { return floorf(self) } public static func remainder(left: Float, _ right: Float) -> Float { return remainderf(left, right) } public static func min(left: Float, _ right: Float) -> Float { return fminf(left, right) } public static func max(left: Float, _ right: Float) -> Float { return fmaxf(left, right) } public static func sqrt(x: Float) -> Float { return sqrtf(x) } } extension Double : BinaryFloatingPoint { var _representation: UInt64 { return unsafeBitCast(self, to: UInt64.self) } public typealias SignificandBits = UInt64 public static var _fractionalBitCount: UInt { return 52 } public static var _exponentBitCount: UInt { return 11 } public var signbit: Bool { return _representation >> 63 == 1 } public var exponentBitPattern: UInt { return UInt(_representation >> 52) & 0x7ff } public var significandBitPattern: SignificandBits { return _representation & Double._fractionalBitMask } public init(signbit: Bool, exponentBitPattern: UInt, significandBitPattern: SignificandBits) { let sign = SignificandBits(signbit ? 1 : 0) << 63 let exponent = SignificandBits(exponentBitPattern) << 52 let _representation = sign | exponent | significandBitPattern self = unsafeBitCast(_representation, to: Double.self) } public init<T: BinaryFloatingPoint>(_ other: T) { // rdar://16980851 #if does not work with 'switch' cases #if arch(i386) || arch(x86_64) switch other { case let f as Float: self = Double(f) case let d as Double: self = d case let ld as Float80: self = Double(ld) default: fatalError() } #else switch other { case let f as Float: self = Double(f) case let d as Double: self = d default: fatalError() } #endif } public func roundToIntegralTiesToAway() -> Double { return round(self) } public func roundToIntegralTowardZero() -> Double { return trunc(self) } public func roundToIntegralTowardPositive() -> Double { return ceil(self) } public func roundToIntegralTowardNegative() -> Double { return floor(self) } public static func remainder(left: Double, _ right: Double) -> Double { return remainder(left, right) } public static func min(left: Double, _ right: Double) -> Double { return fmin(left, right) } public static func max(left: Double, _ right: Double) -> Double { return fmax(left, right) } } #if arch(i386) || arch(x86_64) extension Float80 : BinaryFloatingPoint { // Internal implementation details struct _Float80Representation { var explicitSignificand: UInt64 var signAndExponent: UInt16 var _padding: (UInt16, UInt16, UInt16) = (0, 0, 0) var signbit: Bool { return signAndExponent >> 15 == 1 } var exponentBitPattern: UInt { return UInt(signAndExponent) & 0x7fff } init(explicitSignificand: UInt64, signAndExponent: UInt16) { self.explicitSignificand = explicitSignificand self.signAndExponent = signAndExponent } } var _representation: _Float80Representation { return unsafeBitCast(self, to: _Float80Representation.self) } // Public requirements public typealias SignificandBits = UInt64 public static var _fractionalBitCount: UInt { return 63 } public static var _exponentBitCount: UInt { return 15 } public var signbit: Bool { return _representation.signbit } public var exponentBitPattern: UInt { if _representation.exponentBitPattern == 0 { if _representation.explicitSignificand >= Float80._integralBitMask { // Pseudo-denormals have an exponent of 0 but the leading bit of the // significand field is set. These are non-canonical encodings of the // same significand with an exponent of 1. return 1 } // Exponent is zero, leading bit of significand is clear, so this is // just a canonical zero or subnormal number. return 0 } if _representation.explicitSignificand < Float80._integralBitMask { // If the exponent is not-zero and the leading bit of the significand // is clear, then we have an invalid operand (unnormal, pseudo-inf, or // pseudo-nan). All of these are treated as NaN by the hardware, so // we pretend that the exponent is that of a NaN. return Float80._infinityExponent } return _representation.exponentBitPattern } public var significandBitPattern: UInt64 { if _representation.exponentBitPattern > 0 && _representation.explicitSignificand < Float80._integralBitMask { // If the exponent is non-zero and the leading bit of the significand // is clear, then we have an invalid operand (unnormal, pseudo-inf, or // pseudo-nan). All of these are treated as NaN by the hardware, so // we make sure that bit of the significand field is set. return _representation.explicitSignificand | Float80._quietBitMask } // Otherwise we always get the "right" significand by simply clearing the // integral bit. return _representation.explicitSignificand & Float80._fractionalBitMask } public init(signbit: Bool, exponentBitPattern: UInt, significandBitPattern: UInt64) { let sign = UInt16(signbit ? 0x8000 : 0) let exponent = UInt16(exponentBitPattern) var significand = significandBitPattern if exponent != 0 { significand |= Float80._integralBitMask } let representation = _Float80Representation(explicitSignificand: significand, signAndExponent: sign|exponent) self = unsafeBitCast(representation, to: Float80.self) } public init<T: BinaryFloatingPoint>(_ other: T) { switch other { case let f as Float: self = Float80(f) case let d as Double: self = Float80(d) case let ld as Float80: self = ld default: fatalError() } } public func roundToIntegralTiesToAway() -> Float80 { fatalError("TODO: nead roundl( )") } public func roundToIntegralTowardZero() -> Float80 { fatalError("TODO: nead truncl( )") } public func roundToIntegralTowardPositive() -> Float80 { fatalError("TODO: nead ceill( )") } public func roundToIntegralTowardNegative() -> Float80 { fatalError("TODO: nead floorl( )") } public static func remainder(left: Float80, _ right: Float80) -> Float80 { fatalError("TODO: nead remainderl( )") } public static func min(left: Float80, _ right: Float80) -> Float80 { fatalError("TODO: nead fminl( )") } public static func max(left: Float80, _ right: Float80) -> Float80 { fatalError("TODO: nead fmaxl( )") } public var isCanonical: Bool { if exponentBitPattern == 0 { return _representation.explicitSignificand < Float80._integralBitMask } return _representation.explicitSignificand >= Float80._integralBitMask } } #endif // Unchanged from existing FloatingPoint protocol support. /// The set of IEEE-754 floating-point "classes". Every floating-point datum /// belongs to exactly one of these classes. public enum FloatingPointClassification { case signalingNaN case quietNaN case negativeInfinity case negativeNormal case negativeSubnormal case negativeZero case positiveZero case positiveSubnormal case positiveNormal case positiveInfinity } extension FloatingPointClassification : Equatable {} public func ==(lhs: FloatingPointClassification, rhs: FloatingPointClassification) -> Bool { switch (lhs, rhs) { case (.signalingNaN, .signalingNaN), (.quietNaN, .quietNaN), (.negativeInfinity, .negativeInfinity), (.negativeNormal, .negativeNormal), (.negativeSubnormal, .negativeSubnormal), (.negativeZero, .negativeZero), (.positiveZero, .positiveZero), (.positiveSubnormal, .positiveSubnormal), (.positiveNormal, .positiveNormal), (.positiveInfinity, .positiveInfinity): return true default: return false } } //===--- tests ------------------------------------------------------------===// import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate #if _runtime(_ObjC) import ObjectiveC #endif var tests = TestSuite("Floating Point") tests.test("Parts") { expectEqual(Int.max, (-Float.infinity).exponent) expectEqual(127, (-Float.greatestFiniteMagnitude).exponent) expectEqual(1, Float(-2).exponent) expectEqual(0, Float(-1).exponent) expectEqual(-1, Float(-0.5).exponent) expectEqual(-23, (-Float.ulp).exponent) expectEqual(-125, (-2*Float.leastNormalMagnitude).exponent) expectEqual(-126, Float.leastNormalMagnitude.exponent) #if !arch(arm) expectEqual(-127, (-0.5*Float.leastNormalMagnitude).exponent) expectEqual(-149, (-Float.leastMagnitude).exponent) #endif expectEqual(Int.min, Float(-0).exponent) expectEqual(Int.min, Float(0).exponent) #if !arch(arm) expectEqual(-149, Float.leastMagnitude.exponent) expectEqual(-127, (Float.leastNormalMagnitude/2).exponent) #endif expectEqual(-126, Float.leastNormalMagnitude.exponent) expectEqual(-125, (2*Float.leastNormalMagnitude).exponent) expectEqual(-23, Float.ulp.exponent) expectEqual(-1, Float(0.5).exponent) expectEqual(0, Float(1).exponent) expectEqual(1, Float(2).exponent) expectEqual(127, Float.greatestFiniteMagnitude.exponent) expectEqual(Int.max, Float.infinity.exponent) expectEqual(Int.max, Float.NaN.exponent) expectEqual(Int.max, (-Double.infinity).exponent) expectEqual(1023, (-Double.greatestFiniteMagnitude).exponent) expectEqual(1, Double(-2).exponent) expectEqual(0, Double(-1).exponent) expectEqual(-1, Double(-0.5).exponent) expectEqual(-52, (-Double.ulp).exponent) expectEqual(-1021, (-2*Double.leastNormalMagnitude).exponent) expectEqual(-1022, Double.leastNormalMagnitude.exponent) #if !arch(arm) expectEqual(-1023, (-0.5*Double.leastNormalMagnitude).exponent) expectEqual(-1074, (-Double.leastMagnitude).exponent) #endif expectEqual(Int.min, Double(-0).exponent) expectEqual(Int.min, Double(0).exponent) #if !arch(arm) expectEqual(-1074, Double.leastMagnitude.exponent) expectEqual(-1023, (Double.leastNormalMagnitude/2).exponent) #endif expectEqual(-1022, Double.leastNormalMagnitude.exponent) expectEqual(-1021, (2*Double.leastNormalMagnitude).exponent) expectEqual(-52, Double.ulp.exponent) expectEqual(-1, Double(0.5).exponent) expectEqual(0, Double(1).exponent) expectEqual(1, Double(2).exponent) expectEqual(1023, Double.greatestFiniteMagnitude.exponent) expectEqual(Int.max, Double.infinity.exponent) expectEqual(Int.max, Double.NaN.exponent) #if arch(i386) || arch(x86_64) expectEqual(Int.max, (-Float80.infinity).exponent) expectEqual(16383, (-Float80.greatestFiniteMagnitude).exponent) expectEqual(1, Float80(-2).exponent) expectEqual(0, Float80(-1).exponent) expectEqual(-1, Float80(-0.5).exponent) expectEqual(-63, (-Float80.ulp).exponent) expectEqual(-16381, (-2*Float80.leastNormalMagnitude).exponent) expectEqual(-16382, Float80.leastNormalMagnitude.exponent) expectEqual(-16383, (-0.5*Float80.leastNormalMagnitude).exponent) expectEqual(-16445, (-Float80.leastMagnitude).exponent) expectEqual(Int.min, Float80(-0).exponent) expectEqual(Int.min, Float80(0).exponent) expectEqual(-16445, Float80.leastMagnitude.exponent) expectEqual(-16383, (Float80.leastNormalMagnitude/2).exponent) expectEqual(-16382, Float80.leastNormalMagnitude.exponent) expectEqual(-16381, (2*Float80.leastNormalMagnitude).exponent) expectEqual(-63, Float80.ulp.exponent) expectEqual(-1, Float80(0.5).exponent) expectEqual(0, Float80(1).exponent) expectEqual(1, Float80(2).exponent) expectEqual(16383, Float80.greatestFiniteMagnitude.exponent) expectEqual(Int.max, Float80.infinity.exponent) expectEqual(Int.max, Float80.NaN.exponent) #endif } runAllTests()
apache-2.0
1ddaf387cc5aaf2f5c15e1c186ff9e84
38.601646
131
0.685427
4.067974
false
false
false
false
slavapestov/swift
test/IRGen/generic_tuples.swift
1
7774
// RUN: %target-swift-frontend -emit-ir -primary-file %s | FileCheck %s // Make sure that optimization passes don't choke on storage types for generic tuples // RUN: %target-swift-frontend -emit-ir -O %s // REQUIRES: CPU=x86_64 // CHECK: [[TYPE:%swift.type]] = type { // CHECK: [[OPAQUE:%swift.opaque]] = type opaque // CHECK: [[TUPLE_TYPE:%swift.tuple_type]] = type { [[TYPE]], i64, i8*, [0 x %swift.tuple_element_type] } // CHECK: %swift.tuple_element_type = type { [[TYPE]]*, i64 } func dup<T>(x: T) -> (T, T) { var x = x; return (x,x) } // CHECK: define hidden void @_TF14generic_tuples3dup{{.*}}(<{}>* noalias nocapture sret // CHECK: entry: // Allocate a local variable for 'x'. // CHECK-NEXT: [[XBUF:%.*]] = alloca [[BUFFER:.*]], align 8 // CHECK-NEXT: [[XBUFLIFE:%.*]] = bitcast {{.*}} [[XBUF]] // CHECK-NEXT: call void @llvm.lifetime.start({{.*}} [[XBUFLIFE]]) // CHECK-NEXT: [[T0:%.*]] = bitcast [[TYPE]]* %T to i8*** // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], i64 -1 // CHECK-NEXT: [[T_VALUE:%.*]] = load i8**, i8*** [[T1]], align 8 // CHECK-NEXT: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE]] // CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]], align 8 // CHECK-NEXT: [[INITIALIZE_BUFFER_FN:%.*]] = bitcast i8* [[T1]] to [[OPAQUE]]* ([[BUFFER]]*, [[OPAQUE]]*, [[TYPE]]*)* // CHECK-NEXT: [[X:%.*]] = call [[OPAQUE]]* [[INITIALIZE_BUFFER_FN]]([[BUFFER]]* [[XBUF]], [[OPAQUE]]* {{.*}}, [[TYPE]]* %T) // Get value witnesses for T. // Project to first element of tuple. // CHECK: [[FST:%.*]] = bitcast <{}>* [[RET:%.*]] to [[OPAQUE]]* // Get the tuple metadata. // FIXME: maybe this should get passed in? // CHECK-NEXT: [[TT_PAIR:%.*]] = call [[TYPE]]* @swift_getTupleTypeMetadata2([[TYPE]]* %T, [[TYPE]]* %T, i8* null, i8** null) // Pull out the offset of the second element and GEP to that. // CHECK-NEXT: [[T0:%.*]] = bitcast [[TYPE]]* [[TT_PAIR]] to [[TUPLE_TYPE]]* // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds [[TUPLE_TYPE]], [[TUPLE_TYPE]]* [[T0]], i64 0, i32 3, i64 1, i32 1 // CHECK-NEXT: [[T2:%.*]] = load i64, i64* [[T1]], align 8 // CHECK-NEXT: [[T3:%.*]] = bitcast <{}>* [[RET]] to i8* // CHECK-NEXT: [[T4:%.*]] = getelementptr inbounds i8, i8* [[T3]], i64 [[T2]] // CHECK-NEXT: [[SND:%.*]] = bitcast i8* [[T4]] to [[OPAQUE]]* // Copy 'x' into the first element. // CHECK-NEXT: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE]], i32 6 // CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]], align 8 // CHECK-NEXT: [[COPY_FN:%.*]] = bitcast i8* [[T1]] to [[OPAQUE]]* ([[OPAQUE]]*, [[OPAQUE]]*, [[TYPE]]*)* // CHECK-NEXT: call [[OPAQUE]]* [[COPY_FN]]([[OPAQUE]]* [[FST]], [[OPAQUE]]* [[X]], [[TYPE]]* %T) // Copy 'x' into the second element. // CHECK-NEXT: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T_VALUE]], i32 9 // CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]], align 8 // CHECK-NEXT: [[TAKE_FN:%.*]] = bitcast i8* [[T1]] to [[OPAQUE]]* ([[OPAQUE]]*, [[OPAQUE]]*, [[TYPE]]*)* // CHECK-NEXT: call [[OPAQUE]]* [[TAKE_FN]]([[OPAQUE]]* [[SND]], [[OPAQUE]]* [[X]], [[TYPE]]* %T) struct S {} func callDup(let s: S) { _ = dup(s) } // CHECK-LABEL: define hidden void @_TF14generic_tuples7callDupFVS_1ST_() // CHECK-NEXT: entry: // CHECK-NEXT: call void @_TF14generic_tuples3dupurFxTxx_({{.*}} undef, {{.*}} undef, %swift.type* {{.*}} @_TMfV14generic_tuples1S, {{.*}}) // CHECK-NEXT: ret void class C {} func dupC<T : C>(let x: T) -> (T, T) { return (x, x) } // CHECK-LABEL: define hidden { %C14generic_tuples1C*, %C14generic_tuples1C* } @_TF14generic_tuples4dupCuRxCS_1CrFxTxx_(%C14generic_tuples1C*, %swift.type* %T) // CHECK-NEXT: entry: // CHECK: [[REF:%.*]] = bitcast %C14generic_tuples1C* %0 to %swift.refcounted* // CHECK-NEXT: call void @swift_retain(%swift.refcounted* [[REF]]) // CHECK-NEXT: [[TUP1:%.*]] = insertvalue { %C14generic_tuples1C*, %C14generic_tuples1C* } undef, %C14generic_tuples1C* %0, 0 // CHECK-NEXT: [[TUP2:%.*]] = insertvalue { %C14generic_tuples1C*, %C14generic_tuples1C* } [[TUP1:%.*]], %C14generic_tuples1C* %0, 1 // CHECK-NEXT: ret { %C14generic_tuples1C*, %C14generic_tuples1C* } [[TUP2]] func callDupC(let c: C) { _ = dupC(c) } // CHECK-LABEL: define hidden void @_TF14generic_tuples8callDupCFCS_1CT_(%C14generic_tuples1C*) // CHECK-NEXT: entry: // CHECK-NEXT: [[REF:%.*]] = bitcast %C14generic_tuples1C* %0 to %swift.refcounted* // CHECK-NEXT: call void @swift_retain(%swift.refcounted* [[REF]]) // CHECK-NEXT: [[METATYPE:%.*]] = call %swift.type* @_TMaC14generic_tuples1C() // CHECK-NEXT: [[TUPLE:%.*]] = call { %C14generic_tuples1C*, %C14generic_tuples1C* } @_TF14generic_tuples4dupCuRxCS_1CrFxTxx_(%C14generic_tuples1C* %0, %swift.type* [[METATYPE]]) // CHECK-NEXT: [[LEFT:%.*]] = extractvalue { %C14generic_tuples1C*, %C14generic_tuples1C* } [[TUPLE]], 0 // CHECK-NEXT: [[RIGHT:%.*]] = extractvalue { %C14generic_tuples1C*, %C14generic_tuples1C* } [[TUPLE]], 1 // CHECK-NEXT: call void bitcast (void (%swift.refcounted*)* @swift_release to void (%C14generic_tuples1C*)*)(%C14generic_tuples1C* [[RIGHT]]) // CHECK-NEXT: call void bitcast (void (%swift.refcounted*)* @swift_release to void (%C14generic_tuples1C*)*)(%C14generic_tuples1C* [[LEFT]]) // CHECK-NEXT: call void bitcast (void (%swift.refcounted*)* @swift_release to void (%C14generic_tuples1C*)*)(%C14generic_tuples1C* %0) // CHECK-NEXT: ret void // CHECK: define hidden void @_TF14generic_tuples4lump{{.*}}(<{ %Si }>* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.type* %T) func lump<T>(x: T) -> (Int, T, T) { return (0,x,x) } // CHECK: define hidden void @_TF14generic_tuples5lump2{{.*}}(<{ %Si, %Si }>* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.type* %T) func lump2<T>(x: T) -> (Int, Int, T) { return (0,0,x) } // CHECK: define hidden void @_TF14generic_tuples5lump3{{.*}}(<{}>* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.type* %T) func lump3<T>(x: T) -> (T, T, T) { return (x,x,x) } // CHECK: define hidden void @_TF14generic_tuples5lump4{{.*}}(<{}>* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.type* %T) func lump4<T>(x: T) -> (T, Int, T) { return (x,0,x) } // CHECK: define hidden i64 @_TF14generic_tuples6unlump{{.*}}(i64, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) func unlump<T>(x: (Int, T, T)) -> Int { return x.0 } // CHECK: define hidden void @_TF14generic_tuples7unlump{{.*}}(%swift.opaque* noalias nocapture sret, i64, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T) func unlump1<T>(x: (Int, T, T)) -> T { return x.1 } // CHECK: define hidden void @_TF14generic_tuples7unlump2{{.*}}(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i64, %swift.opaque* noalias nocapture, %swift.type* %T) func unlump2<T>(x: (T, Int, T)) -> T { return x.0 } // CHECK: define hidden i64 @_TF14generic_tuples7unlump3{{.*}}(%swift.opaque* noalias nocapture, i64, %swift.opaque* noalias nocapture, %swift.type* %T) func unlump3<T>(x: (T, Int, T)) -> Int { return x.1 } // CHECK: tuple_existentials func tuple_existentials() { // Empty tuple: var a : Any = () // CHECK: store %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* @_TMT_, i32 0, i32 1), // 2 element tuple var t2 = (1,2.0) a = t2 // CHECK: call %swift.type* @swift_getTupleTypeMetadata2({{.*}}@_TMSi{{.*}},{{.*}}@_TMSd{{.*}}, i8* null, i8** null) // 3 element tuple var t3 = ((),(),()) a = t3 // CHECK: call %swift.type* @swift_getTupleTypeMetadata3({{.*}}@_TMT_{{.*}},{{.*}}@_TMT_{{.*}},{{.*}}@_TMT_{{.*}}, i8* null, i8** null) // 4 element tuple var t4 = (1,2,3,4) a = t4 // CHECK: call %swift.type* @swift_getTupleTypeMetadata(i64 4, {{.*}}, i8* null, i8** null) }
apache-2.0
ae680940b97afc4f1abf337c6de6112e
60.698413
192
0.611011
2.964912
false
false
false
false
insidegui/WWDC
Packages/ConfCore/ConfCore/SessionAsset.swift
1
5353
// // SessionAsset.swift // WWDC // // Created by Guilherme Rambo on 06/02/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa import RealmSwift public enum SessionAssetType: String { case none case hdVideo = "WWDCSessionAssetTypeHDVideo" case sdVideo = "WWDCSessionAssetTypeSDVideo" case image = "WWDCSessionAssetTypeShelfImage" case slides = "WWDCSessionAssetTypeSlidesPDF" case streamingVideo = "WWDCSessionAssetTypeStreamingVideo" case liveStreamVideo = "WWDCSessionAssetTypeLiveStreamVideo" case webpage = "WWDCSessionAssetTypeWebpageURL" } /// Session assets are resources associated with sessions, like videos, PDFs and useful links public class SessionAsset: Object, Decodable { /// The type of asset: /// /// - WWDCSessionAssetTypeHDVideo /// - WWDCSessionAssetTypeSDVideo /// - WWDCSessionAssetTypeShelfImage /// - WWDCSessionAssetTypeSlidesPDF /// - WWDCSessionAssetTypeStreamingVideo /// - WWDCSessionAssetTypeWebpageURL @objc internal dynamic var rawAssetType = "" { didSet { identifier = generateIdentifier() } } @objc public dynamic var identifier = "" public var assetType: SessionAssetType { get { return SessionAssetType(rawValue: rawAssetType) ?? .none } set { rawAssetType = newValue.rawValue } } /// The year of the session this asset belongs to @objc public dynamic var year = 0 { didSet { identifier = generateIdentifier() } } /// The id of the session this asset belongs to @objc public dynamic var sessionId = "" { didSet { identifier = generateIdentifier() } } /// URL for this asset @objc public dynamic var remoteURL = "" /// Relative local URL to save the asset to when downloading @objc public dynamic var relativeLocalURL = "" @objc public dynamic var actualEndDate: Date? /// The session this asset belongs to public let session = LinkingObjects(fromType: Session.self, property: "assets") public override class func primaryKey() -> String? { return "identifier" } func merge(with other: SessionAsset, in realm: Realm) { assert(other.remoteURL == remoteURL, "Can't merge two objects with different identifiers!") year = other.year sessionId = other.sessionId relativeLocalURL = other.relativeLocalURL } public func generateIdentifier() -> String { return String(year) + "@" + sessionId + "~" + rawAssetType.replacingOccurrences(of: "WWDCSessionAssetType", with: "") } public convenience required init(from decoder: Decoder) throws { let context = DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "SessionAsset decoding is not currently supported") throw DecodingError.dataCorrupted(context) } } struct LiveAssetWrapper: Decodable { let liveSession: SessionAsset private enum CodingKeys: String, CodingKey { case sessionId, tvosUrl, iosUrl, actualEndDate } public init(from decoder: Decoder) throws { guard let sessionId = decoder.codingPath.last?.stringValue else { let context = DecodingError.Context( codingPath: decoder.codingPath, debugDescription: "Session id is not the last coding path", underlyingError: nil) throw DecodingError.dataCorrupted(context) } let container = try decoder.container(keyedBy: CodingKeys.self) guard let remoteURL = try container.decodeIfPresent(String.self, forKey: .tvosUrl) ?? container.decodeIfPresent(String.self, forKey: .iosUrl) else { let context = DecodingError.Context( codingPath: decoder.codingPath, debugDescription: "no url for the live asset", underlyingError: nil) throw DecodingError.dataCorrupted(context) } let asset = SessionAsset() // Live assets are always for the current year asset.year = Calendar.current.component(.year, from: Date()) // There are two assumptions being made here // 1 - Live assets are always for the current year // 2 - Live assets are always for "WWDC" events // FIXME: done in a rush to fix live streaming in 2018 asset.sessionId = "wwdc\(asset.year)-"+sessionId asset.rawAssetType = SessionAssetType.liveStreamVideo.rawValue asset.remoteURL = remoteURL // Not using decodeIfPresent because date can actually be an empty string :/ asset.actualEndDate = try? container.decode(Date.self, forKey: .actualEndDate) self.liveSession = asset } } struct LiveVideosWrapper: Decodable { let liveAssets: [SessionAsset] // MARK: - Decodable private enum CodingKeys: String, CodingKey { case liveSessions = "live_sessions" } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let assets = try container.decode([String: LiveAssetWrapper].self, forKey: .liveSessions) self.liveAssets = assets.values.map { $0.liveSession } } }
bsd-2-clause
e2969740ce9eb6736cde4abe24664c53
32.45
156
0.659193
4.937269
false
false
false
false
qmathe/Starfish
Flux/Wave.swift
1
1603
/** Copyright (C) 2017 Quentin Mathe Author: Quentin Mathe <[email protected]> Date: June 2017 License: MIT */ import Foundation open class Wave<T>: Flux<Flux<T>> { private var subscribedFluxes = [Flux<T>]() // MARK: - Combining Fluxes open func merge() -> Flux<T> { let stream = Flux<T>() _ = subscribe() { event in switch event { case .value(let value): self.subscribe(to: value, redirectingEventsTo: stream) case .error(let error): stream.append(Flux<T>.Event.error(error)) case .completed: stream.append(Flux<T>.Event.completed) } } return stream } open func switchLatest() -> Flux<T> { let stream = Flux<T>() _ = subscribe() { event in switch event { case .value(let value): self.unsubscribeFromAll() self.subscribe(to: value, redirectingEventsTo: stream) case .error(let error): stream.append(Flux<T>.Event.error(error)) case .completed: stream.append(Flux<T>.Event.completed) } } return stream } // MARK: - Redirecting Fluxes private func unsubscribeFromAll() { subscribedFluxes.forEach { $0.unsubscribe(self) } subscribedFluxes.removeAll() } private func subscribe(to inputFlux: Flux<T>, redirectingEventsTo outputFlux: Flux<T>) { subscribedFluxes += [inputFlux] _ = inputFlux.subscribe(self) { event in outputFlux.append(event) } } }
mit
c064aafa16f46c95897fb758a2c55eb0
24.444444
89
0.570805
3.853365
false
false
false
false
artemkrachulov/AKImageCropperView
AKImageCropperViewExample/CropperViewController.swift
1
7622
// // CropperViewController.swift // // Created by Artem Krachulov. // Copyright (c) 2016 Artem Krachulov. All rights reserved. // Website: http://www.artemkrachulov.com/ // import UIKit import AKImageCropperView final class CropperViewController: UIViewController { // MARK: - Properties var image: UIImage! // MARK: - Connections: // MARK: -- Outlets private var cropView: AKImageCropperView { return cropViewProgrammatically ?? cropViewStoryboard } @IBOutlet weak var cropViewStoryboard: AKImageCropperView! private var cropViewProgrammatically: AKImageCropperView! @IBOutlet weak var overlayActionView: UIView! @IBOutlet weak var navigationView: UIView! // MARK: -- Actions @IBAction func backAction(_ sender: AnyObject) { guard !cropView.isEdited else { let alertController = UIAlertController(title: "Warning!", message: "All changes will be lost.", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.cancel, handler: { _ in _ = self.navigationController?.popViewController(animated: true) })) alertController.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.default, handler: nil)) present(alertController, animated: true, completion: nil) return } _ = navigationController?.popViewController(animated: true) } @IBAction func cropRandomAction(_ sender: AnyObject) { // cropView.setCropRectAnin(CGRect(x: 50, y: 200, width: 100, height: 100)) /* let randomWidth = max(UInt32(cropView.configuration.cropRect.minimumSize.width), arc4random_uniform(UInt32(cropView.scrollView.frame.size.width))) let randomHeight = max(UInt32(cropView.configuration.cropRect.minimumSize.height), arc4random_uniform(UInt32(cropView.scrollView.frame.size.height))) let offsetX = CGFloat(arc4random_uniform(UInt32(cropView.scrollView.frame.size.width) - randomWidth)) let offsetY = CGFloat(arc4random_uniform(UInt32(cropView.scrollView.frame.size.height) - randomHeight)) cropView.cropRect(CGRectMake(offsetX, offsetY, CGFloat(randomWidth), CGFloat(randomHeight)))*/ } @IBAction func randomImageAction(_ sender: AnyObject) { let images = Constants.images.flatMap { $0 } cropView.image = UIImage(named: images[Int(arc4random_uniform(UInt32(images.count)))]) angle = 0.0 } @IBAction func cropImageAction(_ sender: AnyObject) { guard let image = cropView.croppedImage else { return } let imageViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ImageViewController") as! ImageViewController imageViewController.image = image navigationController?.pushViewController(imageViewController, animated: true) } @IBAction func showHideOverlayAction(_ sender: AnyObject) { if cropView.isoverlayViewActive { cropView.hideOverlayView(animationDuration: 0.3) UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: { self.overlayActionView.alpha = 0 }, completion: nil) } else { cropView.showOverlayView(animationDuration: 0.3) UIView.animate(withDuration: 0.3, delay: 0.3, options: UIViewAnimationOptions.curveLinear, animations: { self.overlayActionView.alpha = 1 }, completion: nil) } } var angle: Double = 0.0 @IBAction func rotateAction(_ sender: AnyObject) { angle += M_PI_2 cropView.rotate(angle, withDuration: 0.3, completion: { _ in if self.angle == 2 * M_PI { self.angle = 0.0 } }) } @IBAction func resetAction(_ sender: AnyObject) { cropView.reset(animationDuration: 0.3) angle = 0.0 } // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() navigationController?.isNavigationBarHidden = true // Programmatically initialization /* cropViewProgrammatically = AKImageCropperView() */ // iPhone 4.7" /* cropViewProgrammatically = AKImageCropperView(frame: CGRect(x: 0, y: 20.0, width: 375.0, height: 607.0)) view.addSubview(cropViewProgrammatically) */ // with constraints /* cropViewProgrammatically = AKImageCropperView() cropViewProgrammatically.translatesAutoresizingMaskIntoConstraints = false view.addSubview(cropViewProgrammatically) if #available(iOS 9.0, *) { cropViewProgrammatically.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true cropViewProgrammatically.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true topLayoutGuide.bottomAnchor.constraint(equalTo: cropViewProgrammatically.topAnchor).isActive = true cropViewProgrammatically.bottomAnchor.constraint(equalTo: navigationView.topAnchor).isActive = true } else { for attribute: NSLayoutAttribute in [.top, .left, .bottom, .right] { var toItem: Any? var toAttribute: NSLayoutAttribute! if attribute == .top { toItem = topLayoutGuide toAttribute = .bottom } else if attribute == .bottom { toItem = navigationView toAttribute = .top } else { toItem = view toAttribute = attribute } view.addConstraint( NSLayoutConstraint( item: cropViewProgrammatically, attribute: attribute, relatedBy: NSLayoutRelation.equal, toItem: toItem, attribute: toAttribute, multiplier: 1.0, constant: 0)) } } */ // Inset for overlay action view /* cropView.overlayView?.configuraiton.cropRectInsets.bottom = 50 */ // Custom overlay view configuration /* var customConfiguraiton = AKImageCropperCropViewConfiguration() customConfiguraiton.cropRectInsets.bottom = 50 cropView.overlayView = CustomImageCropperOverlayView(configuraiton: customConfiguraiton) */ cropView.delegate = self cropView.image = image } } // MARK: - AKImageCropperViewDelegate extension CropperViewController: AKImageCropperViewDelegate { func imageCropperViewDidChangeCropRect(view: AKImageCropperView, cropRect rect: CGRect) { // print("New crop rectangle: \(rect)") } }
mit
f2d78006013bc3f7489a17a5ee4156c5
32.875556
163
0.582655
5.616802
false
false
false
false
aerogear/aerogear-ios-oauth2
AeroGearOAuth2Tests/OpenIDConnectFacebookOAuth2ModuleTest.swift
1
4585
/* * JBoss, Home of Professional Open Source. * Copyright Red Hat, Inc., and individual 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 UIKit import XCTest import AeroGearOAuth2 import AeroGearHttp import OHHTTPStubs class OpenIDConnectFacebookOAuth2ModuleTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() OHHTTPStubs.removeAllStubs() } class MyFacebookMockOAuth2ModuleSuccess: FacebookOAuth2Module { override func requestAccess(completionHandler: @escaping (AnyObject?, NSError?) -> Void) { let accessToken: AnyObject? = NSString(string:"TOKEN") completionHandler(accessToken, nil) } } class MyFacebookMockOAuth2ModuleFailure: FacebookOAuth2Module { override func requestAccess(completionHandler: @escaping (AnyObject?, NSError?) -> Void) { completionHandler(nil, NSError(domain: "", code: 0, userInfo: nil)) } } func testFacebookOpenIDSuccess() { let loginExpectation = expectation(description: "Login") let facebookConfig = FacebookConfig( clientId: "YYY", clientSecret: "XXX", scopes:["publish_actions"], isOpenIDConnect: true) // set up http stub setupStubWithNSURLSessionDefaultConfiguration() let oauth2Module = AccountManager.addAccountWith(config: facebookConfig, moduleClass: MyFacebookMockOAuth2ModuleSuccess.self) oauth2Module.login {(accessToken: AnyObject?, claims: OpenIdClaim?, error: NSError?) in XCTAssertTrue("Corinne Krych" == claims?.name, "name should be filled") XCTAssertTrue("Corinne" == claims?.givenName, "first name should be filled") XCTAssertTrue("Krych" == claims?.familyName, "family name should be filled") XCTAssertTrue("female" == claims?.gender, "gender should be filled") loginExpectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testFacebookOpenIDFailureNoUserInfoEndPoint() { let loginExpectation = expectation(description: "Login") let fbConfig = Config(base: "https://fb", authzEndpoint: "o/oauth2/auth", redirectURL: "google:/oauth2Callback", accessTokenEndpoint: "o/oauth2/token", clientId: "302356789040-eums187utfllgetv6kmbems0pm3mfhgl.apps.googleusercontent.com", refreshTokenEndpoint: "o/oauth2/token", revokeTokenEndpoint: "rest/revoke", isOpenIDConnect: true, userInfoEndpoint: nil, scopes: ["openid", "email", "profile"], accountId: "acc") // set up http stub setupStubWithNSURLSessionDefaultConfiguration() let oauth2Module = AccountManager.addAccountWith(config: fbConfig, moduleClass: MyFacebookMockOAuth2ModuleSuccess.self) oauth2Module.login {(accessToken: AnyObject?, claims: OpenIdClaim?, error: NSError?) in let erroDict = (error?.userInfo)! let value = erroDict["OpenID Connect"] as! String XCTAssertTrue( value == "No UserInfo endpoint available in config", "claim should be as mocked") loginExpectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testFacebookOpenIDFailure() { let loginExpectation = expectation(description: "Login") let facebookConfig = FacebookConfig( clientId: "YYY", clientSecret: "XXX", scopes:["photo_upload, publish_actions"], isOpenIDConnect: true) let oauth2Module = AccountManager.addAccountWith(config: facebookConfig, moduleClass: MyFacebookMockOAuth2ModuleFailure.self) oauth2Module.login {(accessToken: AnyObject?, claims: OpenIdClaim?, error: NSError?) in XCTAssertTrue(error != nil, "Error") loginExpectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) } }
apache-2.0
e4a8f7a33d12b198f35b3f3474f5e338
36.276423
133
0.669138
4.692938
false
true
false
false
AdaptiveMe/adaptive-arp-api-lib-darwin
Pod/Classes/Sources.Api/SocketBridge.swift
1
3463
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:[email protected]> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:[email protected]> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation /** Interface for Managing the Socket operations Auto-generated implementation of ISocket specification. */ public class SocketBridge : BaseCommunicationBridge, ISocket, APIBridge { /** API Delegate. */ private var delegate : ISocket? = nil /** Constructor with delegate. @param delegate The delegate implementing platform specific functions. */ public init(delegate : ISocket?) { self.delegate = delegate } /** Get the delegate implementation. @return ISocket delegate that manages platform specific functions.. */ public final func getDelegate() -> ISocket? { return self.delegate } /** Set the delegate implementation. @param delegate The delegate implementing platform specific functions. */ public final func setDelegate(delegate : ISocket) { self.delegate = delegate; } /** Invokes the given method specified in the API request object. @param request APIRequest object containing method name and parameters. @return APIResponse with status code, message and JSON response or a JSON null string for void functions. Status code 200 is OK, all others are HTTP standard error conditions. */ public override func invoke(request : APIRequest) -> APIResponse? { let response : APIResponse = APIResponse() var responseCode : Int32 = 200 var responseMessage : String = "OK" let responseJSON : String? = "null" switch request.getMethodName()! { default: // 404 - response null. responseCode = 404 responseMessage = "SocketBridge does not provide the function '\(request.getMethodName()!)' Please check your client-side API version; should be API version >= v2.2.15." } response.setResponse(responseJSON!) response.setStatusCode(responseCode) response.setStatusMessage(responseMessage) return response } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
a37047836d73da6ed1a07e6e116f9041
34.680412
185
0.622652
5.135015
false
false
false
false
seongkyu-sim/BaseVCKit
BaseVCKit/Classes/extensions/UIViewExtensions.swift
1
822
// // UIViewExtensions.swift // BaseVCKit // // Created by frank on 2015. 11. 10.. // Copyright © 2016년 colavo. All rights reserved. // import UIKit public extension UIView { var parentViewController: UIViewController? { var parentResponder: UIResponder? = self while parentResponder != nil { parentResponder = parentResponder!.next if let viewController = parentResponder as? UIViewController { return viewController } } return nil } func setRoundCorner(radius: CGFloat) { self.layer.masksToBounds = true self.layer.cornerRadius = radius } func setBorder(color: UIColor, width: CGFloat = 0.5) { self.layer.borderWidth = width self.layer.borderColor = color.cgColor } }
mit
195e901b0e0bdfb8d7f71c2e5c3bceb6
23.818182
74
0.626374
4.706897
false
false
false
false
MartinLasek/vaporberlinBE
Sources/App/Backend/Topic/Dispatcher/TopicDispatcher.swift
1
1151
class TopicDispatcher { let topicRepository: TopicRepository init() { self.topicRepository = TopicRepository() } func getList(req: TopicListRequest) throws -> TopicListResponse? { guard let list = try topicRepository.findAll() else { return nil } return TopicListResponse(list: list) } func create(req: CreateTopicRequest) throws -> CreateTopicResponse? { let userId = req.user.id!.int! guard let topic = try topicRepository.save(Topic(description: req.description, userId: userId)) else { return nil } try topic.votes.add(req.user) return CreateTopicResponse.fromEntity(topic: topic) } func vote(req: VoteTopicRequest) throws -> VoteTopicResponse? { let topicList = try req.user.votes.filter("id", req.topicId).all() if (topicList.count > 0) { return nil } guard let topic = try getById(topicId: req.topicId) else { return nil } try topic.votes.add(req.user) return VoteTopicResponse(topic: topic) } private func getById(topicId: Int) throws -> Topic? { return try topicRepository.findBy(topicId) } }
mit
b03c9f6c38764ecfd3d28b8de4042389
25.767442
106
0.668115
3.982699
false
false
false
false
proxyco/RxBluetoothKit
Source/RxCharacteristicType.swift
1
2734
// The MIT License (MIT) // // Copyright (c) 2016 Polidea // // 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 CoreBluetooth /** Protocol which wraps characteristic for bluetooth devices. */ protocol RxCharacteristicType { /// Characteristic UUID var uuid: CBUUID { get } /// Current characteristic value var value: NSData? { get } /// True if characteristic value changes are notified var isNotifying: Bool { get } /// Characteristic properties var properties: CBCharacteristicProperties { get } /// Characteristic descriptors var descriptors: [RxDescriptorType]? { get } /// Characteristic service var service: RxServiceType { get } } /** Characteristics are equal if their UUIDs are equal - parameter lhs: First characteristic to compare - parameter rhs: Second characteristic to compare - returns: True if characteristics are the same */ func == (lhs: RxCharacteristicType, rhs: RxCharacteristicType) -> Bool { return lhs.uuid == rhs.uuid } /** Function compares if two characteristic arrays are the same, which is true if both of them in sequence are equal and their size is the same. - parameter lhs: First array of characteristics to compare - parameter rhs: Second array of characteristics to compare - returns: True if both arrays contain same characteristics */ func == (lhs: [RxCharacteristicType], rhs: [RxCharacteristicType]) -> Bool { guard lhs.count == rhs.count else { return false } var i1 = lhs.generate() var i2 = rhs.generate() var isEqual = true while let e1 = i1.next(), e2 = i2.next() where isEqual { isEqual = e1 == e2 } return isEqual }
mit
8c5228c438c782c827d7391480b87410
33.175
81
0.724214
4.657581
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/SubredditThemeEditViewController.swift
1
8833
// // SubredditThemeEditViewController.swift // Slide for Reddit // // Created by Carlos Crane on 9/17/20. // Copyright © 2020 Haptic Apps. All rights reserved. // import Anchorage import UIKit protocol SubredditThemeEditViewControllerDelegate { func didChangeColors(_ isAccent: Bool, color: UIColor) func didClear() -> Bool } //VC for presenting theme pickers for a specific subreddit @available(iOS 14.0, *) class SubredditThemeEditViewController: UIViewController, UIColorPickerViewControllerDelegate { static var changed = false var subreddit: String var primary = UILabel() var accent = UILabel() var primaryWell: UIColorWell? var accentWell: UIColorWell? var primaryCard = UIView() var accentCard = UIView() var resetCard = UIView() //Delegate will handle instant color changes var delegate: SubredditThemeEditViewControllerDelegate init(subreddit: String, delegate: SubredditThemeEditViewControllerDelegate) { self.subreddit = subreddit self.delegate = delegate super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupBaseBarColors() navigationController?.setToolbarHidden(true, animated: false) setupTitleView(subreddit) } //Configure wells and set constraints func configureLayout() { primary = UILabel().then { $0.textColor = ColorUtil.theme.fontColor $0.text = "Primary color" $0.font = UIFont.boldSystemFont(ofSize: 16) $0.textAlignment = .left } accent = UILabel().then { $0.textColor = ColorUtil.theme.fontColor $0.text = "Accent color" $0.font = UIFont.boldSystemFont(ofSize: 16) $0.textAlignment = .left } primaryWell = UIColorWell().then { $0.selectedColor = ColorUtil.getColorForSub(sub: subreddit) $0.supportsAlpha = false $0.title = "Primary color" $0.addTarget(self, action: #selector(colorWellChangedPrimary(_:)), for: .valueChanged) } accentWell = UIColorWell().then { $0.selectedColor = ColorUtil.accentColorForSub(sub: subreddit) $0.supportsAlpha = false $0.title = "Accent color" $0.addTarget(self, action: #selector(colorWellChangedAccent(_:)), for: .valueChanged) } primaryCard.backgroundColor = ColorUtil.theme.backgroundColor primaryCard.clipsToBounds = true primaryCard.layer.cornerRadius = 10 primaryCard.addSubviews(primary, primaryWell!) accentCard.backgroundColor = ColorUtil.theme.backgroundColor accentCard.clipsToBounds = true accentCard.layer.cornerRadius = 10 accentCard.addSubviews(accent, accentWell!) resetCard.backgroundColor = ColorUtil.theme.backgroundColor resetCard.clipsToBounds = true resetCard.layer.cornerRadius = 10 let resetLabel = UILabel().then { $0.textColor = ColorUtil.theme.fontColor $0.text = "Reset colors" $0.font = UIFont.boldSystemFont(ofSize: 16) $0.textAlignment = .left } let resetIcon = UIImageView().then { $0.image = UIImage(sfString: SFSymbol.clear, overrideString: "close")?.navIcon() $0.contentMode = .center } resetCard.addTapGestureRecognizer { self.setupTitleView(self.subreddit) self.delegate.didChangeColors(false, color: ColorUtil.getColorForSub(sub: self.subreddit)) if !self.delegate.didClear() { UserDefaults.standard.removeObject(forKey: "color+" + self.subreddit) UserDefaults.standard.removeObject(forKey: "accent+" + self.subreddit) UserDefaults.standard.synchronize() } } resetCard.addSubviews(resetLabel, resetIcon) view.addSubviews(primaryCard, accentCard, resetCard) primaryCard.topAnchor == self.view.safeTopAnchor + 16 primaryCard.horizontalAnchors == self.view.horizontalAnchors + 8 primary.rightAnchor == primaryCard.rightAnchor - 8 primary.leftAnchor == primaryWell!.rightAnchor + 8 primary.centerYAnchor == primaryCard.centerYAnchor primaryCard.heightAnchor == 50 primaryWell!.centerYAnchor == primaryCard.centerYAnchor primaryWell!.leftAnchor == primaryCard.leftAnchor + 8 accentCard.topAnchor == self.primaryCard.bottomAnchor + 16 accentCard.horizontalAnchors == self.view.horizontalAnchors + 8 accent.rightAnchor == accentCard.rightAnchor - 8 accent.leftAnchor == accentWell!.rightAnchor + 8 accent.centerYAnchor == accentCard.centerYAnchor accentCard.heightAnchor == 50 accentWell!.centerYAnchor == accentCard.centerYAnchor accentWell!.leftAnchor == accentCard.leftAnchor + 8 resetCard.topAnchor == self.accentCard.bottomAnchor + 24 resetCard.horizontalAnchors == self.view.horizontalAnchors + 8 resetCard.heightAnchor == 50 resetIcon.sizeAnchors == CGSize.square(size: 30) resetIcon.centerYAnchor == resetCard.centerYAnchor resetIcon.leftAnchor == resetCard.leftAnchor + 8 resetLabel.rightAnchor == resetCard.rightAnchor resetLabel.leftAnchor == resetIcon.rightAnchor + 8 resetLabel.centerYAnchor == resetCard.centerYAnchor } //Primary color changed, set color and call delegate @objc func colorWellChangedPrimary(_ sender: Any) { if let selected = primaryWell?.selectedColor { ColorUtil.setColorForSub(sub: subreddit, color: selected) setupTitleView(subreddit) delegate.didChangeColors(false, color: selected) } } //Accent color changed, set color and call delegate @objc func colorWellChangedAccent(_ sender: Any) { if let selected = accentWell?.selectedColor { ColorUtil.setAccentColorForSub(sub: subreddit, color: selected) delegate.didChangeColors(true, color: selected) } } //Create view for header with icon and subreddit name func setupTitleView(_ sub: String) { let label = UILabel() label.text = " \(SettingValues.reduceColor ? " " : "")\(sub)" label.textColor = SettingValues.reduceColor ? ColorUtil.theme.fontColor : .white label.adjustsFontSizeToFitWidth = true label.font = UIFont.boldSystemFont(ofSize: 20) if SettingValues.reduceColor { let sideView = UIImageView(frame: CGRect(x: 5, y: 5, width: 30, height: 30)) let subreddit = sub sideView.backgroundColor = ColorUtil.getColorForSub(sub: subreddit) if let icon = Subscriptions.icon(for: subreddit) { sideView.contentMode = .scaleAspectFill sideView.image = UIImage() sideView.sd_setImage(with: URL(string: icon.unescapeHTML), completed: nil) } else { sideView.contentMode = .center if subreddit.contains("m/") { sideView.image = SubredditCellView.defaultIconMulti } else if subreddit.lowercased() == "all" { sideView.image = SubredditCellView.allIcon } else if subreddit.lowercased() == "frontpage" { sideView.image = SubredditCellView.frontpageIcon } else if subreddit.lowercased() == "popular" { sideView.image = SubredditCellView.popularIcon } else { sideView.image = SubredditCellView.defaultIcon } } label.addSubview(sideView) sideView.sizeAnchors == CGSize.square(size: 30) sideView.centerYAnchor == label.centerYAnchor sideView.leftAnchor == label.leftAnchor sideView.layer.cornerRadius = 15 sideView.clipsToBounds = true } label.sizeToFit() self.navigationItem.titleView = label } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } override func viewDidLoad() { super.viewDidLoad() self.title = subreddit configureLayout() } }
apache-2.0
4b4f9f34b5b643ec03761746b62f0a36
36.905579
102
0.624207
5.134884
false
false
false
false
melling/ios_topics
CoreDataHighScores/CoreDataHighScores/HighScoreTableViewController.swift
1
5977
// // SimpleTableViewController.swift // SimpleTableViewController // // Created by Michael Mellinger on 3/8/16. // import UIKit import CoreData struct GameType { let gameLanguage:Int let numBoardRows:Int let numBoardCols:Int let numberWords:Int let actualNumberWords:Int let isDirectionEastSouth:Bool let isDirectionWestNorth:Bool let isDirectionDiagonal:Bool } class HighScoreTableViewController: UITableViewController { private let CellIdentifier = "Cell" private var highScores: [NSManagedObject] = [] private var gameType:GameType! func config(gameType:GameType) { self.gameType = gameType } override func viewDidLoad() { super.viewDidLoad() tableView.backgroundColor = UIColor(named:"AppleVideosColor") // loadData() let gt = GameType(gameLanguage:1, numBoardRows: 8, numBoardCols: 8, numberWords: 10, actualNumberWords: 10, isDirectionEastSouth: true, isDirectionWestNorth: true, isDirectionDiagonal: true) // let gameLanguage = 1 // let numBoardRows = 8 // let numBoardCols = 8 // let numberWords = 10 // let actualNumberWords = 10 // let isDirectionEastSouth = true // let isDirectionWestNorth = true // let isDirectionDiagonal = true let highScoreDAO = HighScoreDAO() highScores = highScoreDAO.fetchHighScores(gameType: gt) tableView.rowHeight = 55 tableView.tableFooterView = UIView() // Remove "empty" table centers in footer self.tableView.register(HighScoreTableViewCell.self, forCellReuseIdentifier:CellIdentifier) } } // Data source delegate extension HighScoreTableViewController { // We can skip overriding this function and it will default to 1 override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return highScores.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:HighScoreTableViewCell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier, for: indexPath) as! HighScoreTableViewCell cell.backgroundColor = UIColor(red: 90/255.0, green: 120.0/255.0, blue: 250.0/255, alpha: 1.0) // Configure the cell... let s = highScores[indexPath.row] if let numBoardRows = s.value(forKey: "numBoardRows") as! Int? , let numBoardCols = s.value(forKey: "numBoardCols") as! Int?, let numberWords = s.value(forKey: "numberWords") as! Int?, let actualNumberWords = s.value(forKey: "actualNumberWords") as! Int?, let isDirectionEastSouth = s.value(forKey: "isDirectionEastSouth") as! Bool?, let isDirectionWestNorth = s.value(forKey: "isDirectionWestNorth") as! Bool?, let isDirectionDiagonal = s.value(forKey: "isDirectionDiagonal") as! Bool?, let score = s.value(forKey: "score") as! Int?, let gameTime = s.value(forKey: "gameTime") as! Date? { let dateFmt = DateFormatter() dateFmt.timeZone = NSTimeZone.default dateFmt.dateFormat = "yyyy-MM-dd" let dateString = dateFmt.string(from: gameTime) // let text = "\(dateString), \(score)" cell.label1.text = "\(dateString)" cell.label2.text = "\(timeStr(seconds: score))" if gameType == nil { gameType = GameType(gameLanguage: 1, numBoardRows: numBoardRows, numBoardCols: numBoardCols, numberWords: numberWords, actualNumberWords: actualNumberWords, isDirectionEastSouth: isDirectionEastSouth, isDirectionWestNorth: isDirectionWestNorth, isDirectionDiagonal: isDirectionDiagonal) } } return cell } private func timeStr(seconds:Int) -> String { // let hours = seconds / 3600 let minutes = seconds / 60 % 60 let seconds = seconds % 60 // String(format:"%02i:%02i:%02i", hours, minutes, seconds) // let s = String(format:"%02i:%02i", minutes, seconds) return s } } // Header Cell extension HighScoreTableViewController { //: Optional Header title // override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { // let title:String // if gameType != nil { // title = "High Scores:\(gameType.numBoardRows)x\(gameType.numBoardCols), Words:\(gameType.numberWords), (\(gameType.actualNumberWords)), \(highScores.count)" // } else { // title = "none" // } // return title // } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // let header = UIView() let header = HighScoreHeaderCell() // header.frame = CGRect(x: 0, y: 0, width: 120, height: 150) header.backgroundColor = UIColor(named:"AppleVideosColor") let title = "\(gameType.numBoardRows)x\(gameType.numBoardCols)" let title2 = "\(gameType.numberWords) (\(gameType.actualNumberWords))" header.boardSizeLabel.text = title header.numWordsLabel.text = title2 header.languagelLabel.text = "🇬🇧" return header } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { view.tintColor = .orange } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 80.0 } } // MARK: - Core Data extension HighScoreTableViewController { }
cc0-1.0
b6b25089e7cd8e6af62631a330e27580
35.858025
302
0.63239
4.575479
false
false
false
false
timvermeulen/DraughtsCloud
Sources/App/Request+filter.swift
1
5538
import Vapor import Fluent import Draughts extension Request { var bitboardsConstraints: Bitboards.Constraints { return .init( whiteMen: Bitboards.Constraint( matching: optionalQueryParameter("white"), containing: optionalQueryParameter("white-pattern"), matchingSquares: optionalQueryParameter("white-squares"), containingSquares: optionalQueryParameter("white-squares-pattern") ), blackMen: Bitboards.Constraint( matching: optionalQueryParameter("black"), containing: optionalQueryParameter("black-pattern"), matchingSquares: optionalQueryParameter("black-squares"), containingSquares: optionalQueryParameter("black-squares-pattern") ), whiteKings: Bitboards.Constraint( matching: optionalQueryParameter("white-kings"), containing: optionalQueryParameter("white-kings-pattern"), matchingSquares: optionalQueryParameter("white-kings-squares"), containingSquares: optionalQueryParameter("white-kings-squares-pattern") ), blackKings: Bitboards.Constraint( matching: optionalQueryParameter("black-kings"), containing: optionalQueryParameter("black-kings-pattern"), matchingSquares: optionalQueryParameter("black-kings-squares"), containingSquares: optionalQueryParameter("black-kings-squares-pattern") ), empty: Bitboards.Constraint( matching: optionalQueryParameter("empty"), containing: optionalQueryParameter("empty-pattern"), matchingSquares: optionalQueryParameter("empty-squares"), containingSquares: optionalQueryParameter("empty-squares-pattern") ) ) } // TODO: simplify func getCountFilter<T: BitboardsContainer>() -> CompleteFilter<T>? { let whiteMenCount: Int? = optionalQueryParameter("white-count") let blackMenCount: Int? = optionalQueryParameter("black-count") let whiteKingsCount: Int? = optionalQueryParameter("white-kings-count") let blackKingsCount: Int? = optionalQueryParameter("black-kings-count") let emptyCount: Int? = optionalQueryParameter("empty-count") let whiteMenCountMinimum: Int? = optionalQueryParameter("white-count-minimum") let blackMenCountMinimum: Int? = optionalQueryParameter("black-count-minimum") let whiteKingsCountMinimum: Int? = optionalQueryParameter("white-kings-count-minimum") let blackKingsCountMinimum: Int? = optionalQueryParameter("black-kings-count-minimum") let emptyCountMinimum: Int? = optionalQueryParameter("empty-count-minimum") let whiteMenCountMaximum: Int? = optionalQueryParameter("white-count-maximum") let blackMenCountMaximum: Int? = optionalQueryParameter("black-count-maximum") let whiteKingsCountMaximum: Int? = optionalQueryParameter("white-kings-count-maximum") let blackKingsCountMaximum: Int? = optionalQueryParameter("black-kings-count-maximum") let emptyCountMaximum: Int? = optionalQueryParameter("empty-count-maximum") let countFilters: [CompleteFilter<T>?] = [ whiteMenCount.map { count in CompleteFilter { $0.bitboards.white.count == count } }, blackMenCount.map { count in CompleteFilter { $0.bitboards.blackMen.count == count } }, whiteKingsCount.map { count in CompleteFilter { $0.bitboards.whiteKings.count == count } }, blackKingsCount.map { count in CompleteFilter { $0.bitboards.blackKings.count == count } }, emptyCount.map { count in CompleteFilter { $0.bitboards.empty.count == count } }, whiteMenCountMinimum.map { count in CompleteFilter { $0.bitboards.whiteMen.count >= count } }, blackMenCountMinimum.map { count in CompleteFilter { $0.bitboards.blackMen.count >= count } }, whiteKingsCountMinimum.map { count in CompleteFilter { $0.bitboards.whiteKings.count >= count } }, blackKingsCountMinimum.map { count in CompleteFilter { $0.bitboards.blackKings.count >= count } }, emptyCountMinimum.map { count in CompleteFilter { $0.bitboards.empty.count >= count } }, whiteMenCountMaximum.map { count in CompleteFilter { $0.bitboards.whiteMen.count <= count } }, blackMenCountMaximum.map { count in CompleteFilter { $0.bitboards.blackMen.count <= count } }, whiteKingsCountMaximum.map { count in CompleteFilter { $0.bitboards.whiteKings.count <= count } }, blackKingsCountMaximum.map { count in CompleteFilter { $0.bitboards.blackKings.count <= count } }, emptyCountMaximum.map { count in CompleteFilter { $0.bitboards.empty.count <= count } } ] return countFilters.flatMap { $0 }.concatenated() } }
mit
fc9b36fe2ee14f0591536468a372bc39
48.891892
94
0.6013
4.794805
false
false
false
false
otto-schnurr/MetalMatrixMultiply-swift
Source/Model/Matrix.swift
1
1553
// // Matrix.swift // // Created by Otto Schnurr on 12/14/2015. // Copyright © 2015 Otto Schnurr. All rights reserved. // // MIT License // file: ../../LICENSE.txt // http://opensource.org/licenses/MIT // // TODO: Can this somehow be nested as Matrix.Element? typealias MatrixElement = Float32 /// A row-major matrix of 32-bit floating point numbers. protocol Matrix: class { /// The number of rows of data in the matrix. var rowCount: Int { get } /// The number of elements of data in every row of the matrix. var columnCount: Int { get } /// The total number of rows in the matrix including padded rows. /// /// - Invariant: `m.paddedRowCount >= m.rowCount` var paddedRowCount: Int { get } /// A constant stride of elements that separates every element within /// a column of this matrix. /// /// - Note: BLAS refers to this as the *leading dimension* of the matrix. /// /// - Invariant: `m.paddedColumnCount >= m.columnCount` var paddedColumnCount: Int { get } var baseAddress: UnsafeMutablePointer<MatrixElement>? { get } /// - Invariant: `m.byteCount == m.paddedRowCount * m.bytesPerRow` var byteCount: Int { get } } extension Matrix { /// A constant stride of bytes that separates every element within /// a column of this matrix. /// /// - Invariant: `m.bytesPerRow == m.paddedColumnCount * sizeof(MatrixElement)` var bytesPerRow: Int { return paddedColumnCount * MemoryLayout<MatrixElement>.size } }
mit
fe7aae71b1c8e53710f80ee749de1f57
28.846154
88
0.648196
4.205962
false
false
false
false
cubixlabs/GIST-Framework
GISTFramework/Classes/Controls/ValidatedTextField.swift
1
14711
// // ValidatedTextField.swift // GISTFramework // // Created by Shoaib Abdul on 06/09/2016. // Copyright © 2016 Social Cubix. All rights reserved. // import UIKit import PhoneNumberKit /// ValidatedTextField Protocol to receive events. @objc public protocol ValidatedTextFieldDelegate { @objc optional func validatedTextFieldInvalidSignDidTap(_ validatedTextField:ValidatedTextField, sender:UIButton); } //P.E. /// ValidatedTextField is subclass of InputMaskTextField with extra proporties to validate text input. open class ValidatedTextField: InputMaskTextField, ValidatedTextInput { //MARK: - Properties /// Bool flag for validating an empty text. @IBInspectable open var validateEmpty:Bool = false; /// Bool flag for validating a valid email text. @IBInspectable open var validateEmail:Bool = false; /// Bool flag for validating a valid phone number text. @IBInspectable open var validatePhone:Bool = false; /// Bool flag for validating a valid email or phone number text. @IBInspectable open var validateEmailOrPhone:Bool = false; /// Bool flag for validating a valid email, phone or non empty number text. @IBInspectable open var validateEmailPhoneOrUserName:Bool = false; /// Bool flag for validating a valid url text. @IBInspectable open var validateURL:Bool = false; /// Bool flag for validating a valid numaric input. @IBInspectable open var validateNumeric:Bool = false; /// Bool flag for validating a valid alphabetic input. @IBInspectable open var validateAlphabetic:Bool = false; /// Bool flag for validating a valid alphabetic input. @IBInspectable open var validateRegex:String = ""; /// Validats minimum character limit. @IBInspectable open var minChar:Int = 0; /// Validats maximum character limit. @IBInspectable open var maxChar:Int = 0; /// Max Character Count Limit for the text field. @IBInspectable open var maxCharLimit: Int = 50; /// Validats minimum character limit. @IBInspectable open var minValue:Int = -1; /// Validats maximum character limit. @IBInspectable open var maxValue:Int = -1; /// Inspectable property for invalid sign image. @IBInspectable open var invalidSign:UIImage? = nil { didSet { invalidSignBtn.setImage(invalidSign, for: UIControl.State()); } } //P.E. /** Validity msg for invalid input text. - Default text is 'Invalid' The msg can be a key of SyncEngine with a prefix '#' */ @IBInspectable open var validityMsg:String? = nil; @IBInspectable open var validityMsgForEmpty:String? = nil; internal var errorMsg:String { get { if (_isEmpty && self.validityMsgForEmpty != nil) { return self.validityMsgForEmpty!; } else { return validityMsg ?? ""; } } } /// Lazy Button instance for invalid sign. private lazy var invalidSignBtn:CustomUIButton = { let cBtn:CustomUIButton = CustomUIButton(type: UIButton.ButtonType.custom); cBtn.isHidden = true; cBtn.frame = CGRect(x: self.frame.size.width - self.frame.size.height, y: 0, width: self.frame.size.height, height: self.frame.size.height); cBtn.contentMode = UIView.ContentMode.right; cBtn.containtOffSet = GISTUtility.convertPointToRatio(CGPoint(x: 10, y: 0)); cBtn.addTarget(self, action: #selector(invalidSignBtnHandler(_:)), for: UIControl.Event.touchUpInside); self.addSubview(cBtn); return cBtn; } (); private var _isEmpty:Bool = false; private var _isValid:Bool = false; public var phoneNumber:PhoneNumber?; private var _data:Any? /// Holds Data. open var data:Any? { get { return _data; } } //P.E. /// Flag for whether the input is valid or not. open var isValid:Bool { get { if (self.isFirstResponder) { self.validateText(); } let cValid:Bool = (_isValid && (!validateEmpty || !_isEmpty)); self.isInvalidSignHidden = cValid; return cValid; } } //F.E. /// Overridden property to get text changes. open override var text: String? { didSet { if (!self.isFirstResponder) { if maskFormat != nil { self.applyMaskFormat(); } else if maskPhone { self.applyPhoneMaskFormat(); } self.validateText(); } } } //P.E. open var validText: String?; open var isInvalidSignHidden:Bool = true { didSet { self.invalidSignBtn.isHidden = isInvalidSignHidden; } } //P.E. public override var defaultRegion: String { get { return super.defaultRegion; } set { super.defaultRegion = newValue; if (!self.isFirstResponder) { self.validateText(); } } } //MARK: - Overridden Methods /// Overridden methed to update layout. open override func layoutSubviews() { super.layoutSubviews(); self.invalidSignBtn.frame = CGRect(x: self.frame.size.width - self.frame.size.height, y: 0, width: self.frame.size.height, height: self.frame.size.height); } //F.E. /// Overridden property to get text changes. /// /// - Parameter textField: UITextField open override func textFieldDidEndEditing(_ textField: UITextField) { super.textFieldDidEndEditing(textField); //Updating text in the holding dictionary let dicData:NSMutableDictionary? = data as? NSMutableDictionary; dicData?["text"] = textField.text; //Validating the input self.validateText(); } //F.E. /// Protocol method of shouldChangeCharactersIn for limiting the character limit. - Default value is true /// /// - Parameters: /// - textField: Text Field /// - range: Change Characters Range /// - string: Replacement String /// - Returns: Bool flag for should change characters in range open override func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let rtn = super.textField(textField, shouldChangeCharactersIn:range, replacementString:string); //IF CHARACTERS-LIMIT <= ZERO, MEANS NO RESTRICTIONS ARE APPLIED if (self.maxCharLimit <= 0) { return rtn; } guard let text = textField.text else { return true } let newLength = text.utf16.count + string.utf16.count - range.length return (newLength <= self.maxCharLimit) && rtn // Bool } //F.E. //MARK: - Methods open override func updateData(_ data: Any?) { super.updateData(data); _data = data; let dicData:NSMutableDictionary? = data as? NSMutableDictionary; //First set the validations self.validateEmpty = dicData?["validateEmpty"] as? Bool ?? false; self.validateEmail = dicData?["validateEmail"] as? Bool ?? false; self.validatePhone = dicData?["validatePhone"] as? Bool ?? false; self.validateEmailOrPhone = dicData?["validateEmailOrPhone"] as? Bool ?? false; self.validateEmailPhoneOrUserName = dicData?["validateEmailPhoneOrUserName"] as? Bool ?? false; self.validityMsg = dicData?["validityMsg"] as? String; self.validityMsgForEmpty = dicData?["validityMsgForEmpty"] as? String; self.validateURL = dicData?["validateURL"] as? Bool ?? false; self.validateNumeric = dicData?["validateNumeric"] as? Bool ?? false; self.validateAlphabetic = dicData?["validateAlphabetic"] as? Bool ?? false; self.validateRegex = dicData?["validateRegex"] as? String ?? ""; //Set the character Limit self.minChar = dicData?["minChar"] as? Int ?? 0; self.maxChar = dicData?["maxChar"] as? Int ?? 0; //Set the Value Limit self.minValue = dicData?["minValue"] as? Int ?? -1; self.maxValue = dicData?["maxValue"] as? Int ?? -1; self.maxCharLimit = dicData?["maxCharLimit"] as? Int ?? 50; //Set the text and placeholder self.text = dicData?["text"] as? String; self.placeholder = dicData?["placeholder"] as? String; //Set the is password check self.isSecureTextEntry = dicData?["isSecureTextEntry"] as? Bool ?? false; self.isUserInteractionEnabled = dicData?["isUserInteractionEnabled"] as? Bool ?? true; if let autocapitalizationTypeStr:String = dicData?["autocapitalizationType"] as? String { self.autocapitalizationType = UITextAutocapitalizationType.textAutocapitalizationType(for: autocapitalizationTypeStr); } if let autocorrectionTypeStr:String = dicData?["autocorrectionType"] as? String { self.autocorrectionType = UITextAutocorrectionType.textAutocorrectionType(for: autocorrectionTypeStr); } if let keyboardTypeStr:String = dicData?["keyboardType"] as? String { self.keyboardType = UIKeyboardType.keyboardType(for: keyboardTypeStr); } if let returnKeyTypeStr:String = dicData?["returnKeyType"] as? String { self.returnKeyType = UIReturnKeyType.returnKeyType(for: returnKeyTypeStr); } if let validated:Bool = dicData?["validated"] as? Bool, validated == true { self.isInvalidSignHidden = (_isValid && (!validateEmpty || !_isEmpty)); } } //F.E. /// Validating in input and updating the flags of isValid and isEmpty. private func validateText() { _isEmpty = self.isEmpty(); _isValid = ((maskFormat == nil) || self.isValidMask) && (!validateEmail || self.isValidEmail()) && (!validatePhone || self.isValidPhoneNo()) && (!validateEmailOrPhone || (self.isValidEmail() || self.isValidPhoneNo())) && (!validateEmailPhoneOrUserName || (self.isValidEmail() || self.isValidPhoneNo() || !_isEmpty)) && (!validateURL || self.isValidUrl()) && (!validateNumeric || self.isNumeric()) && (!validateAlphabetic || self.isAlphabetic()) && ((minChar == 0) || self.isValidForMinChar(minChar)) && ((maxChar == 0) || self.isValidForMaxChar(maxChar)) && ((minValue == -1) || self.isValidForMinValue(minValue)) && ((maxValue == -1) || self.isValidForMaxValue(maxValue)) && ((validateRegex == "") || self.isValidForRegex(validateRegex)); self.isInvalidSignHidden = (_isValid || _isEmpty); let valid:Bool = (_isValid && (!validateEmpty || !_isEmpty)); if valid { if let pNumber:PhoneNumber = self.phoneNumber { self.validText = "+\(pNumber.countryCode)-\(pNumber.nationalNumber)"; } else { self.validText = (self.sendMaskedText) ? self.text : self.curText; } } else { self.validText = nil; } if let dicData:NSMutableDictionary = self.data as? NSMutableDictionary { dicData["isValid"] = valid; dicData["validText"] = self.validText; } } //F.E. /// Validats for an empty text /// /// - Returns: Bool flag for a valid input. open func isEmpty()->Bool { return GISTUtility.isEmpty(self.curText); } //F.E. /// Validats for a valid email text /// /// - Returns: Bool flag for a valid input. private func isValidEmail()->Bool { return GISTUtility.isValidEmail(self.curText); } //F.E. /// Validats for a valid url text /// /// - Returns: Bool flag for a valid input. private func isValidUrl() -> Bool { return GISTUtility.isValidUrl(self.curText); } //F.E. /// Validats for a valid phone number text /// /// - Returns: Bool flag for a valid input. private func isValidPhoneNo() -> Bool { self.phoneNumber = GISTUtility.validatePhoneNumber(self.curText, withRegion: self.defaultRegion); return self.phoneNumber != nil; } //F.E. /// Validats for a valid numeric text /// /// - Returns: Bool flag for a valid input. private func isNumeric() -> Bool { return GISTUtility.isNumeric(self.curText); } //F.E. /// Validats for a valid alphabetic text /// /// - Returns: Bool flag for a valid input. private func isAlphabetic() -> Bool { return GISTUtility.isAlphabetic(self.curText); } //F.E. /// Validats for minimum chararacter limit /// /// - Parameter noOfChar: No. of characters /// - Returns: Bool flag for a valid input. private func isValidForMinChar(_ noOfChar:Int) -> Bool { return GISTUtility.isValidForMinChar(self.curText, noOfChar: noOfChar); } //F.E. /// Validats for maximum chararacter limit /// /// - Parameter noOfChar: No. of characters /// - Returns: Bool flag for a valid input. private func isValidForMaxChar(_ noOfChar:Int) -> Bool { return GISTUtility.isValidForMaxChar(self.curText, noOfChar: noOfChar); } //F.E. private func isValidForMinValue(_ value:Int) -> Bool { return GISTUtility.isValidForMinValue(self.curText, value: value); } //F.E. private func isValidForMaxValue(_ value:Int) -> Bool { return GISTUtility.isValidForMaxValue(self.curText, value: value); } //F.E. /// Validats for a regex /// /// - Parameter regex: Regex /// - Returns: Bool flag for a valid input. private func isValidForRegex(_ regex:String)->Bool { return GISTUtility.isValidForRegex(self.curText, regex: regex); } //F.E. /// Method to handle tap event for invalid sign button. /// /// - Parameter sender: Invalid Sign Button @objc func invalidSignBtnHandler(_ sender:UIButton) { (self.delegate as? ValidatedTextFieldDelegate)?.validatedTextFieldInvalidSignDidTap?(self, sender: sender) } //F.E. } //CLS END
agpl-3.0
64c88e4992e1832bff0f5641348f20d2
35.683292
163
0.605914
4.719281
false
false
false
false
steryokhin/AsciiArtPlayer
src/AsciiArtPlayer/Pods/R.swift.Library/Library/Core/StringResource.swift
25
1227
// // StringResource.swift // R.swift.Library // // Created by Tom Lokhorst on 2016-04-23. // From: https://github.com/mac-cain13/R.swift.Library // License: MIT License // import Foundation public protocol StringResourceType { /// Key for the string var key: String { get } /// File in containing the string var tableName: String { get } /// Bundle this string is in var bundle: Bundle { get } /// Locales of the a localizable string var locales: [String] { get } /// Comment directly before and/or after the string, if any var comment: String? { get } } public struct StringResource: StringResourceType { /// Key for the string public let key: String /// File in containing the string public let tableName: String /// Bundle this string is in public let bundle: Bundle /// Locales of the a localizable string public let locales: [String] /// Comment directly before and/or after the string, if any public let comment: String? public init(key: String, tableName: String, bundle: Bundle, locales: [String], comment: String?) { self.key = key self.tableName = tableName self.bundle = bundle self.locales = locales self.comment = comment } }
mit
05307d447be8bffc6ddd9fa249f39a6a
21.722222
100
0.681337
3.996743
false
false
false
false
LeeShiYoung/LSYWeibo
LSYWeiBo/LSYPhotoBrowser/LSYTransitionAnimator.swift
1
4288
// // TransitionAnimator.swift // LSYPhotoBrowser // // Created by 李世洋 on 16/7/1. // Copyright © 2016年 李世洋. All rights reserved. // import UIKit protocol LSYTransitionAnimatorDelegate: NSObjectProtocol { func imageViewForPresent(indexPath: NSIndexPath?) -> UIImageView func startAnimationFrame(indexPath: NSIndexPath?) -> CGRect func endAnimationFrame(indexPath: NSIndexPath?) -> CGRect func imageViewForDismiss() -> UIImageView func indexForDisMiss() -> NSIndexPath } class LSYTransitionAnimator: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning { private var indexpath: NSIndexPath? // 设置属性 func setInfo(presentedDelegate: LSYTransitionAnimatorDelegate, indexPath: NSIndexPath?) { self.lsytansitionAnimatorDelegate = presentedDelegate self.indexpath = indexPath } // 动画显示的图片 var imageUrl: NSURL? weak var lsytansitionAnimatorDelegate: LSYTransitionAnimatorDelegate? private var isPresent = true func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = true return self } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = false return self } func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.3 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { isPresent == true ? showAnimation(transitionContext) : disMissAnimation(transitionContext) } // 弹出动画 private func showAnimation(transitionContext: UIViewControllerContextTransitioning) { let toview = transitionContext.viewForKey(UITransitionContextToViewKey) transitionContext.containerView()!.addSubview(toview!) let imageView = lsytansitionAnimatorDelegate!.imageViewForPresent(indexpath) imageView.frame = lsytansitionAnimatorDelegate!.startAnimationFrame(indexpath) transitionContext.containerView()!.backgroundColor = UIColor.blackColor() transitionContext.containerView()!.addSubview(imageView) toview?.alpha = 0 UIView.animateWithDuration(transitionDuration(transitionContext), animations: { imageView.frame = self.lsytansitionAnimatorDelegate!.endAnimationFrame(self.indexpath) }) { (_) in imageView.removeFromSuperview() toview?.alpha = 1 transitionContext.completeTransition(true) } } //消失动画 private func disMissAnimation(transitionContext: UIViewControllerContextTransitioning) { guard let delegate = lsytansitionAnimatorDelegate else { return } let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey) fromView?.alpha = 0 transitionContext.containerView()?.backgroundColor = UIColor.clearColor() let disMissImage = lsytansitionAnimatorDelegate!.imageViewForDismiss() transitionContext.containerView()?.addSubview(disMissImage) UIView.animateWithDuration(transitionDuration(transitionContext), animations: { disMissImage.frame = delegate.startAnimationFrame(delegate.indexForDisMiss()) }) { (_) in disMissImage.removeFromSuperview() transitionContext.completeTransition(true) } } private lazy var animationImage: UIImageView = { let imageView = UIImageView() imageView.backgroundColor = UIColor.redColor() return imageView }() } class LSYPresentationController: UIPresentationController { override init(presentedViewController: UIViewController, presentingViewController: UIViewController) { super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController) } }
artistic-2.0
1d9e8c54164fdf70e32e821a4de86d8c
35.517241
215
0.710272
6.320896
false
false
false
false
MiniKeePass/MiniKeePass
MiniKeePass/Settings View/SettingsViewController.swift
1
15549
/* * Copyright 2016 Jason Rush and John Flanagan. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import UIKit import AudioToolbox import LocalAuthentication class SettingsViewController: UITableViewController, PinViewControllerDelegate { @IBOutlet weak var pinEnabledSwitch: UISwitch! @IBOutlet weak var pinLockTimeoutCell: UITableViewCell! @IBOutlet weak var touchIdEnabledCell: UITableViewCell! @IBOutlet weak var touchIdEnabledSwitch: UISwitch! @IBOutlet weak var deleteAllDataEnabledCell: UITableViewCell! @IBOutlet weak var deleteAllDataEnabledSwitch: UISwitch! @IBOutlet weak var deleteAllDataAttemptsCell: UITableViewCell! @IBOutlet weak var closeDatabaseEnabledSwitch: UISwitch! @IBOutlet weak var closeDatabaseTimeoutCell: UITableViewCell! @IBOutlet weak var rememberDatabasePasswordsEnabledSwitch: UISwitch! @IBOutlet weak var hidePasswordsEnabledSwitch: UISwitch! @IBOutlet weak var sortingEnabledSwitch: UISwitch! @IBOutlet weak var searchTitleOnlySwitch: UISwitch! @IBOutlet weak var passwordEncodingCell: UITableViewCell! @IBOutlet weak var clearClipboardEnabledSwitch: UISwitch! @IBOutlet weak var clearClipboardTimeoutCell: UITableViewCell! @IBOutlet weak var excludeFromBackupsEnabledSwitch: UISwitch! @IBOutlet weak var integratedWebBrowserEnabledSwitch: UISwitch! @IBOutlet weak var versionLabel: UILabel! fileprivate let pinLockTimeouts = [NSLocalizedString("Immediately", comment: ""), NSLocalizedString("30 Seconds", comment: ""), NSLocalizedString("1 Minute", comment: ""), NSLocalizedString("2 Minutes", comment: ""), NSLocalizedString("5 Minutes", comment: "")] fileprivate let deleteAllDataAttempts = ["3", "5", "10", "15"] fileprivate let closeDatabaseTimeouts = [NSLocalizedString("Immediately", comment: ""), NSLocalizedString("30 Seconds", comment: ""), NSLocalizedString("1 Minute", comment: ""), NSLocalizedString("2 Minutes", comment: ""), NSLocalizedString("5 Minutes", comment: "")] fileprivate let passwordEncodings = [NSLocalizedString("UTF-8", comment: ""), NSLocalizedString("UTF-16 Big Endian", comment: ""), NSLocalizedString("UTF-16 Little Endian", comment: ""), NSLocalizedString("Latin 1 (ISO/IEC 8859-1)", comment: ""), NSLocalizedString("Latin 2 (ISO/IEC 8859-2)", comment: ""), NSLocalizedString("7-Bit ASCII", comment: ""), NSLocalizedString("Japanese EUC", comment: ""), NSLocalizedString("ISO-2022-JP", comment: "")] fileprivate let clearClipboardTimeouts = [NSLocalizedString("30 Seconds", comment: ""), NSLocalizedString("1 Minute", comment: ""), NSLocalizedString("2 Minutes", comment: ""), NSLocalizedString("3 Minutes", comment: "")] fileprivate var appSettings = AppSettings.sharedInstance() fileprivate var touchIdSupported = false fileprivate var tempPin: String? = nil override func viewDidLoad() { super.viewDidLoad() // Get the version number versionLabel.text = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String // Check if TouchID is supported let laContext = LAContext() touchIdSupported = laContext.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Delete the temp pin tempPin = nil if let appSettings = appSettings { // Initialize all the controls with their settings pinEnabledSwitch.isOn = appSettings.pinEnabled() pinLockTimeoutCell.detailTextLabel!.text = pinLockTimeouts[appSettings.pinLockTimeoutIndex()] touchIdEnabledSwitch.isOn = touchIdSupported && appSettings.touchIdEnabled() deleteAllDataEnabledSwitch.isOn = appSettings.deleteOnFailureEnabled() deleteAllDataAttemptsCell.detailTextLabel!.text = deleteAllDataAttempts[appSettings.deleteOnFailureAttemptsIndex()] closeDatabaseEnabledSwitch.isOn = appSettings.closeEnabled() closeDatabaseTimeoutCell.detailTextLabel!.text = closeDatabaseTimeouts[appSettings.closeTimeoutIndex()] rememberDatabasePasswordsEnabledSwitch.isOn = appSettings.rememberPasswordsEnabled() hidePasswordsEnabledSwitch.isOn = appSettings.hidePasswords() sortingEnabledSwitch.isOn = appSettings.sortAlphabetically() searchTitleOnlySwitch.isOn = appSettings.searchTitleOnly() passwordEncodingCell.detailTextLabel!.text = passwordEncodings[appSettings.passwordEncodingIndex()] clearClipboardEnabledSwitch.isOn = appSettings.clearClipboardEnabled() clearClipboardTimeoutCell.detailTextLabel!.text = clearClipboardTimeouts[appSettings.clearClipboardTimeoutIndex()] excludeFromBackupsEnabledSwitch.isOn = appSettings.backupDisabled() integratedWebBrowserEnabledSwitch.isOn = appSettings.webBrowserIntegrated() } // Update which controls are enabled updateEnabledControls() } fileprivate func updateEnabledControls() { guard let appSettings = appSettings else { return } let pinEnabled = appSettings.pinEnabled() let deleteOnFailureEnabled = appSettings.deleteOnFailureEnabled() let closeEnabled = appSettings.closeEnabled() let clearClipboardEnabled = appSettings.clearClipboardEnabled() // Enable/disable the components dependant on settings setCellEnabled(pinLockTimeoutCell, enabled: pinEnabled) setCellEnabled(touchIdEnabledCell, enabled: pinEnabled && touchIdSupported) touchIdEnabledSwitch.isEnabled = pinEnabled && touchIdSupported setCellEnabled(deleteAllDataEnabledCell, enabled: pinEnabled) setCellEnabled(deleteAllDataAttemptsCell, enabled: pinEnabled && deleteOnFailureEnabled) setCellEnabled(closeDatabaseTimeoutCell, enabled: closeEnabled) setCellEnabled(clearClipboardTimeoutCell, enabled: clearClipboardEnabled) } fileprivate func setCellEnabled(_ cell: UITableViewCell, enabled: Bool) { cell.selectionStyle = enabled ? UITableViewCellSelectionStyle.blue : UITableViewCellSelectionStyle.none cell.textLabel!.isEnabled = enabled cell.detailTextLabel?.isEnabled = enabled } override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { // Only allow these segues if the setting is enabled if (identifier == "PIN Lock Timeout") { return pinEnabledSwitch.isOn } else if (identifier == "Delete All Data Attempts") { return deleteAllDataEnabledSwitch.isOn } else if (identifier == "Close Database Timeout") { return closeDatabaseEnabledSwitch.isOn } else if (identifier == "Clear Clipboard Timeout") { return clearClipboardEnabledSwitch.isOn } return true } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let selectionViewController = segue.destination as! SelectionViewController if (segue.identifier == "PIN Lock Timeout") { selectionViewController.items = pinLockTimeouts selectionViewController.selectedIndex = (appSettings?.pinLockTimeoutIndex())! selectionViewController.itemSelected = { (selectedIndex) in self.appSettings?.setPinLockTimeoutIndex(selectedIndex) self.navigationController?.popViewController(animated: true) } } else if (segue.identifier == "Delete All Data Attempts") { selectionViewController.items = deleteAllDataAttempts selectionViewController.selectedIndex = (appSettings?.deleteOnFailureAttemptsIndex())! selectionViewController.itemSelected = { (selectedIndex) in self.appSettings?.setDeleteOnFailureAttemptsIndex(selectedIndex) self.navigationController?.popViewController(animated: true) } } else if (segue.identifier == "Close Database Timeout") { selectionViewController.items = closeDatabaseTimeouts selectionViewController.selectedIndex = (appSettings?.closeTimeoutIndex())! selectionViewController.itemSelected = { (selectedIndex) in self.appSettings?.setCloseTimeoutIndex(selectedIndex) self.navigationController?.popViewController(animated: true) } } else if (segue.identifier == "Password Encoding") { selectionViewController.items = passwordEncodings selectionViewController.selectedIndex = (appSettings?.passwordEncodingIndex())! selectionViewController.itemSelected = { (selectedIndex) in self.appSettings?.setPasswordEncoding(selectedIndex) self.navigationController?.popViewController(animated: true) } } else if (segue.identifier == "Clear Clipboard Timeout") { selectionViewController.items = clearClipboardTimeouts selectionViewController.selectedIndex = (appSettings?.clearClipboardTimeoutIndex())! selectionViewController.itemSelected = { (selectedIndex) in self.appSettings?.setClearClipboardTimeoutIndex(selectedIndex) self.navigationController?.popViewController(animated: true) } } else { assertionFailure("Unknown segue") } } // MARK: - Actions @IBAction func donePressedAction(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } @IBAction func pinEnabledChanged(_ sender: UISwitch) { if (pinEnabledSwitch.isOn) { let pinViewController = PinViewController() pinViewController.titleLabel.text = NSLocalizedString("Set PIN", comment: "") pinViewController.delegate = self // Background is clear for lock screen blur, set to white to set the pin. pinViewController.view.backgroundColor = UIColor.white present(pinViewController, animated: true, completion: nil) } else { self.appSettings?.setPinEnabled(false) // Delete the PIN from the keychain KeychainUtils.deleteString(forKey: "PIN", andServiceName: KEYCHAIN_PIN_SERVICE) // Update which controls are enabled updateEnabledControls() } } @IBAction func touchIdEnabledChanged(_ sender: UISwitch) { self.appSettings?.setTouchIdEnabled(touchIdEnabledSwitch.isOn) } @IBAction func deleteAllDataEnabledChanged(_ sender: UISwitch) { self.appSettings?.setDeleteOnFailureEnabled(deleteAllDataEnabledSwitch.isOn) // Update which controls are enabled updateEnabledControls() } @IBAction func closeDatabaseEnabledChanged(_ sender: UISwitch) { self.appSettings?.setCloseEnabled(closeDatabaseEnabledSwitch.isOn) // Update which controls are enabled updateEnabledControls() } @IBAction func rememberDatabasePasswordsEnabledChanged(_ sender: UISwitch) { self.appSettings?.setRememberPasswordsEnabled(rememberDatabasePasswordsEnabledSwitch.isOn) KeychainUtils.deleteAll(forServiceName: KEYCHAIN_PASSWORDS_SERVICE) KeychainUtils.deleteAll(forServiceName: KEYCHAIN_KEYFILES_SERVICE) } @IBAction func hidePasswordsEnabledChanged(_ sender: UISwitch) { self.appSettings?.setHidePasswords(hidePasswordsEnabledSwitch.isOn) } @IBAction func sortingEnabledChanged(_ sender: UISwitch) { self.appSettings?.setSortAlphabetically(sortingEnabledSwitch.isOn) } @IBAction func searchTitleOnlyChanged(_ sender: UISwitch) { self.appSettings?.setSearchTitleOnly(searchTitleOnlySwitch.isOn) } @IBAction func clearClipboardEnabledChanged(_ sender: UISwitch) { self.appSettings?.setClearClipboardEnabled(clearClipboardEnabledSwitch.isOn) // Update which controls are enabled updateEnabledControls() } @IBAction func excludeFromBackupEnabledChanged(_ sender: UISwitch) { self.appSettings?.setBackupDisabled(excludeFromBackupsEnabledSwitch.isOn) } @IBAction func integratedWebBrowserEnabledChanged(_ sender: UISwitch) { self.appSettings?.setWebBrowserIntegrated(integratedWebBrowserEnabledSwitch.isOn) } // MARK: - Pin view delegate func pinViewController(_ pinViewController: PinViewController!, pinEntered: String!) { if (tempPin == nil) { tempPin = pinEntered pinViewController.titleLabel.text = NSLocalizedString("Confirm PIN", comment: "") // Clear the PIN entry for confirmation pinViewController.clearPin() } else if (tempPin == pinEntered) { tempPin = nil // Hash the pin let pinHash = PasswordUtils.hashPassword(pinEntered) // Set the PIN and enable the PIN enabled setting appSettings?.setPin(pinHash) appSettings?.setPinEnabled(true) // Update which controls are enabled updateEnabledControls() // Remove the PIN view dismiss(animated: true, completion: nil) } else { tempPin = nil // Notify the user the PINs they entered did not match pinViewController.titleLabel.text = NSLocalizedString("PINs did not match. Try again", comment: "") // Vibrate the phone AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) // Clear the PIN entry to let them try again pinViewController.clearPin() } } }
gpl-3.0
0644a24e3d4ee0d798ddaae82001c7ca
45.002959
127
0.65181
5.756757
false
false
false
false
seorenn/SRChoco
Source/SRExternalApp.swift
1
1795
// // SRExternalApp.swift // SRChoco // // Created by Seorenn. // Copyright (c) 2014 Seorenn. All rights reserved. // #if os(iOS) // MARK: SRExternalApp for iOS import UIKit public func canLaunchApp(appScheme: String) -> Bool { if let appURL = URL(string: appScheme) { return UIApplication.shared.canOpenURL(appURL) } else { return false } } public func launchApp(appScheme: String) { if let appURL = URL(string: appScheme) { if #available(iOS 10.0, *) { UIApplication.shared.open(appURL, options: [:]) { (succeed) in // TDOO } } else { // Fallback on earlier versions UIApplication.shared.openURL(appURL) } } } #elseif os(OSX) // MARK: SRExternalApp for OSX import Cocoa public func getAppPath(bundleIdentifier: String) -> String? { return NSWorkspace.shared.absolutePathForApplication(withBundleIdentifier: bundleIdentifier) } public func launchApp(appPath: String, arguments: [String]) -> Process! { let task = Process() task.launchPath = appPath task.arguments = arguments task.launch() return task } public func launchApp(appPath: String) { NSWorkspace.shared.launchApplication(appPath) } public func activateApp(pid: pid_t) { if let app = NSRunningApplication(processIdentifier: pid) { activateApp(app: app) } } public func activateApp(bundleIdentifier: String) { let apps = NSRunningApplication.runningApplications(withBundleIdentifier: bundleIdentifier) if let app = apps.first { activateApp(app: app) } } public func activateApp(app: NSRunningApplication) { app.activate(options: NSApplication.ActivationOptions.activateAllWindows) } #endif
mit
44720e61f5d13e51d91acb4105cfc7e5
22.311688
96
0.660167
4.193925
false
false
false
false
hooman/swift
test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_generic-1argument-1st_argument_constant_int.swift
14
10832
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment --check-prefix=CHECK --check-prefix=CHECK-%target-vendor // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main9Ancestor1[[UNIQUE_ID_1:[A-Za-z_0-9]+]]CySiGMf" = // CHECK: @"$s4main5Value[[UNIQUE_ID_1]]CySSGMf" = linkonce_odr hidden // CHECK-apple-SAME: global // CHECK-unknown-SAME: constant // CHECK-SAME: <{ // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* // CHECK-SAME: )*, // CHECK-SAME: i8**, // : [[INT]], // CHECK-SAME: %swift.type*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: [[INT]], // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i16, // CHECK-SAME: i16, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* // CHECK-SAME: )*, // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]], // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* ( // CHECK-SAME: %TSi*, // CHECK-SAME: %swift.type* // CHECK-SAME: )*, // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]], // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* ( // CHECK-SAME: %swift.opaque*, // CHECK-SAME: %swift.type* // CHECK-SAME: )* // CHECK-SAME:}> <{ // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CfD // CHECK-SAME: $sBoWV // CHECK-apple-SAME: $s4main5Value[[UNIQUE_ID_1]]CySSGMM // CHECK-unknown-SAME: [[INT]] 0, // : %swift.type* getelementptr inbounds ( // : %swift.full_heapmetadata, // : %swift.full_heapmetadata* bitcast ( // : <{ // : void ( // : %T4main9Ancestor1[[UNIQUE_ID_1]]C* // : )*, // : i8**, // : [[INT]], // : %objc_class*, // : %swift.type*, // : %swift.opaque*, // : %swift.opaque*, // : [[INT]], // : i32, // : i32, // : i32, // : i16, // : i16, // : i32, // : i32, // : %swift.type_descriptor*, // : i8*, // : %swift.type*, // : [[INT]], // : %T4main9Ancestor1[[UNIQUE_ID_1]]C* ( // : %swift.opaque*, // : %swift.type* // : )* // : }>* @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMf" to %swift.full_heapmetadata* // : ), // : i32 0, // : i32 2 // : ), // CHECK-apple-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-apple-SAME: %swift.opaque* null, // CHECK-apple-SAME: [[INT]] add ( // CHECK-apple-SAME: [[INT]] ptrtoint ( // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // : i32, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // : i8*, // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: [ // CHECK-apple-SAME: 1 x { // CHECK-apple-SAME: [[INT]]*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32 // CHECK-apple-SAME: } // CHECK-apple-SAME: ] // CHECK-apple-SAME: }*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8* // CHECK-apple-SAME: }* @"_DATA_$s4main5Value[[UNIQUE_ID_1]]CySSGMf" to [[INT]] // CHECK-apple-SAME: ), // CHECK-apple-SAME: [[INT]] 2 // CHECK-apple-SAME: ), // CHECK-SAME: i32 26, // CHECK-SAME: i32 0, // CHECK-SAME: i32 {{(40|24)}}, // CHECK-SAME: i16 {{(7|3)}}, // CHECK-SAME: i16 0, // CHECK-apple-SAME: i32 {{(144|84)}}, // CHECK-unknown-SAME: i32 120, // CHECK-SAME: i32 {{(16|8)}}, // : %swift.type_descriptor* bitcast ( // : <{ // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i16, // : i16, // : i16, // : i16, // : i8, // : i8, // : i8, // : i8, // : i32, // : i32, // : %swift.method_descriptor, // : i32, // : %swift.method_override_descriptor // : }>* @"$s4main5Value[[UNIQUE_ID_1]]CMn" to %swift.type_descriptor* // : ), // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CfE // CHECK-SAME: %swift.type* @"$sSSN", // CHECK-SAME: [[INT]] {{(16|8)}}, // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* ( // CHECK-SAME: %TSi*, // CHECK-SAME: %swift.type* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]C5firstADyxGSi_tcfCAA9Ancestor1ACLLCAeHyxGx_tcfCTV // CHECK-SAME: %swift.type* @"$sSSN", // CHECK-SAME: [[INT]] {{(24|12)}}, // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* ( // CHECK-SAME: %swift.opaque*, // CHECK-SAME: %swift.type* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]C5firstADyxGx_tcfC // CHECK-SAME:}>, // CHECK-SAME:align [[ALIGNMENT]] fileprivate class Ancestor1<First> { let first_Ancestor1: First init(first: First) { self.first_Ancestor1 = first } } fileprivate class Value<First> : Ancestor1<Int> { let first_Value: First init(first: First) { self.first_Value = first super.init(first: 13) } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } func doit() { consume( Value(first: "13") ) } doit() // CHECK-LABEL: define hidden swiftcc void @"$s4main4doityyF"() // CHECK: call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CySSGMb" // CHECK: } // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CySSGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} { // CHECK-NEXT: entry: // CHECK: [[SUPER_CLASS_METADATA:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMb"([[INT]] 0) // CHECK-unknown: ret // CHECK-apple: [[THIS_CLASS_METADATA:%[0-9]+]] = call %objc_class* @objc_opt_self( // : %objc_class* bitcast ( // : %swift.type* getelementptr inbounds ( // : %swift.full_heapmetadata, // : %swift.full_heapmetadata* bitcast ( // : <{ // : void ( // : %T4main5Value[[UNIQUE_ID_1]]C* // : )*, // : i8**, // : i64, // : %swift.type*, // : %swift.opaque*, // : %swift.opaque*, // : i64, // : i32, // : i32, // : i32, // : i16, // : i16, // : i32, // : i32, // : %swift.type_descriptor*, // : void ( // : %T4main5Value[[UNIQUE_ID_1]]C* // : )*, // : %swift.type*, // : i64, // : %T4main5Value[[UNIQUE_ID_1]]C* ( // : %TSi*, // : %swift.type* // : )*, // : %swift.type*, // : i64, // : %T4main5Value[[UNIQUE_ID_1]]C* ( // : %swift.opaque*, // : %swift.type* // : )* // : }>* // CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]CySSGMf" // : to %swift.full_heapmetadata* // : ), // : i32 0, // : i32 2 // : ) to %objc_class* // : ) // : ) // CHECK-apple: [[THIS_TYPE_METADATA:%[0-9]+]] = bitcast %objc_class* [[THIS_CLASS_METADATA]] to %swift.type* // CHECK-apple: [[RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[THIS_TYPE_METADATA]], 0 // CHECK-apple: [[COMPLETE_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response %5, [[INT]] 0, 1 // CHECK-apple: ret %swift.metadata_response [[COMPLETE_RESPONSE]] // CHECK: } // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMb"
apache-2.0
a295c23d782e9cda08a92dee72b881f7
39.721805
214
0.388294
3.410579
false
false
false
false
powerytg/Accented
Accented/UI/Search/ViewModels/UserSearchResultViewModel.swift
1
2963
// // UserSearchResultViewModel.swift // Accented // // User search result stream view model // // Created by Tiangong You on 5/22/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit import RMessage class UserSearchResultViewModel : InfiniteLoadingViewModel<UserModel> { private let rendererIdentifier = "renderer" required init(collection : UserSearchResultModel, collectionView : UICollectionView) { super.init(collection: collection, collectionView: collectionView) let rendererNib = UINib(nibName: "UserSearchResultRenderer", bundle: nil) collectionView.register(rendererNib, forCellWithReuseIdentifier: rendererIdentifier) // Events NotificationCenter.default.addObserver(self, selector: #selector(userSearchResultDidUpdate(_:)), name: StorageServiceEvents.userSearchResultDidUpdate, object: nil) // Load first page loadIfNecessary() } deinit { NotificationCenter.default.removeObserver(self) } override func createCollectionViewLayout() { layout = UserSearchResultLayout() } override func loadPageAt(_ page : Int) { APIService.sharedInstance.searchUsers(keyword: collection.modelId!, page: page, success: nil) { [weak self] (errorMessage) in self?.collectionFailedLoading(errorMessage) RMessage.showNotification(withTitle: errorMessage, subtitle: nil, type: .error, customTypeName: nil, callback: nil) } } // Events @objc private func userSearchResultDidUpdate(_ notification : Notification) { let updatedKeyword = notification.userInfo![StorageServiceEvents.keyword] as! String let page = notification.userInfo![StorageServiceEvents.page] as! Int guard updatedKeyword == collection.modelId else { return } // Get a new copy of the search results collection = StorageService.sharedInstance.getUserSearchResult(keyword: collection.modelId!) updateCollectionView(page == 1) streamState.loading = false if page == 1 { streamState.refreshing = false delegate?.viewModelDidRefresh() } } // MARK: - UICollectionViewDelegateFlowLayout override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if !collection.loaded { let loadingCell = collectionView.dequeueReusableCell(withReuseIdentifier: initialLoadingRendererReuseIdentifier, for: indexPath) return loadingCell } else { let user = collection.items[indexPath.item] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: rendererIdentifier, for: indexPath) as! UserSearchResultRenderer cell.user = user cell.setNeedsLayout() return cell } } }
mit
caeba25a566728a929bf73c39b388c9f
37.467532
171
0.683997
5.475046
false
false
false
false
LawrenceHan/iOS-project-playground
Swift_A_Big_Nerd_Ranch_Guide/MonsterTown Initialization/MonsterTown/Town.swift
1
1255
// // Town.swift // MonsterTown // // Created by Hanguang on 3/1/16. // Copyright © 2016 Hanguang. All rights reserved. // import Foundation struct Town { static let region = "South" var population = 5422 { didSet(oldPopulation) { if population < oldPopulation { print("The population has changed to \(population) from \(oldPopulation)") } else { mayor.saySomething() } } } var numberOfStoplights = 4 enum Size { case Small case Medium case Large } var townSize: Size { get { switch self.population { case 0...10000: return Size.Small case 10001...100000: return Size.Medium default: return Size.Large } } } var mayor = Mayor() func printTownDescription() { print("Population: \(myTown.population), number of stoplights: \(myTown.numberOfStoplights)") } mutating func changePopulation(amount: Int) { population += amount if population < 0 { population = 0 } } }
mit
d46de34bcfaf3f0708067a5e019b0b09
21.017544
101
0.5
4.841699
false
false
false
false
See-Ku/SK4Toolkit
SK4Toolkit/extention/SK4NSDictionaryExtension.swift
1
795
// // SK4NSDictionaryExtension.swift // SK4Toolkit // // Created by See.Ku on 2016/04/02. // Copyright (c) 2016 AxeRoad. All rights reserved. // import Foundation extension NSDictionary { /// 型とキーを指定して値を取得 public func sk4Get<T>(key: String, inout value: T) { if let tmp = self[key] { if let tmp = tmp as? T { value = tmp } else { sk4DebugLog("Type mismatch error: \(key)") } } } /// JSON形式のNSDictionaryから文字列を生成 public func sk4DicToJson(options: NSJSONWritingOptions = [.PrettyPrinted]) -> String? { do { let data = try NSJSONSerialization.dataWithJSONObject(self, options: options) return data.sk4ToString() } catch { sk4DebugLog("dataWithJSONObject error: \(error)") return nil } } } // eof
mit
23a8a6e905c57f87757a1d453561ab8a
19.189189
88
0.668005
3.099585
false
false
false
false
BlakeBarrett/wndw
wtrmrkr/TouchableUIImageView.swift
1
3574
// // TouchableUIImageView.swift // wndw // // Created by Blake Barrett on 6/4/16. // Copyright © 2016 Blake Barrett. All rights reserved. // import UIKit class TouchableUIImageView: UIImageView { var touchesEnabled = true override var image: UIImage? { didSet { if let img = self.image { let rect = ImageMaskingUtils.center(img, inFrame: self.frame).rect self.rect = rect self.frame = rect self.bounds = rect self.invalidateIntrinsicContentSize() } } } override func layoutSubviews() { self.mask.frame = self.rect self.temp.frame = self.rect self.masked.frame = self.rect } func setOriginalImage(image: UIImage) { temp.image = UIImage() mask.image = UIImage() masked.image = UIImage() self.image = image self.original = image self.rect = ImageMaskingUtils.center(image, inFrame: self.frame).rect } // MARK: - Line Drawing Code var brush = Brush(red: 1.0 ,green: 1.0, blue: 1.0, width: 50.0, alpha: 1.0) func setBrush(brush: Brush) { self.brush = brush } var swiped = false var lastPoint = CGPointMake(0,0) override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if !touchesEnabled { return } swiped = false if let touch = touches.first { let view = UIView(frame: self.rect) lastPoint = touch.locationInView(view) } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { if !touchesEnabled { return } swiped = true if let touch = touches.first { let view = UIView(frame: self.rect) let currentPoint = touch.locationInView(view) self.temp.image = DrawingUtils.drawLineFrom(lastPoint, toPoint: currentPoint, onImage: self.temp.image!, inFrame: self.rect, withBrush: self.brush) lastPoint = currentPoint } dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { dispatch_async(dispatch_get_main_queue(), { self.mask.image = ImageMaskingUtils.mergeImages(self.mask.image!, second: self.temp.image!) self.applyMask() }) } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if !touchesEnabled { return } if !swiped { self.temp.image = DrawingUtils.drawLineFrom(lastPoint, toPoint: lastPoint, onImage: self.temp.image!, inFrame: self.rect, withBrush: self.brush) } dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { dispatch_async(dispatch_get_main_queue(), { self.mask.image = ImageMaskingUtils.mergeImages(self.mask.image!, second: self.temp.image!) self.temp.image = UIImage() self.applyMask() }) } } var rect: CGRect = CGRectMake(0, 0, 1920, 1080) var temp = UIImageView() var mask = UIImageView() var masked = UIImageView() var original = UIImage() func applyMask() { guard let mask = self.mask.image else { return } self.masked.image = ImageMaskingUtils.maskImage(original, maskImage: mask) self.image = self.masked.image } }
mit
9793c28bdb9732c55fcc7e27704bc849
31.189189
159
0.574307
4.362637
false
false
false
false
cc001/learnSwiftBySmallProjects
15-AnimatedSplash/AnimatedSplash/ViewController.swift
1
2118
// // ViewController.swift // AnimatedSplash // // Created by 陈闯 on 2016/12/21. // Copyright © 2016年 CC. All rights reserved. // import UIKit class ViewController: UIViewController, CAAnimationDelegate { var mask: CALayer? var imageView: UIImageView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationController?.navigationBar.barStyle = UIBarStyle.blackTranslucent let imageView = UIImageView(frame: (self.view.bounds)) imageView.image = UIImage(named: "screen") self.view.addSubview(imageView) mask = CALayer() mask?.contents = UIImage(named: "twitter")?.cgImage mask?.contentsGravity = kCAGravityResizeAspect mask?.bounds = CGRect(x: 0, y: 0, width: 100, height: 81) mask?.anchorPoint = CGPoint(x: 0.5, y: 0.5) mask?.position = CGPoint(x: imageView.frame.size.width/2, y: imageView.frame.size.height/2) imageView.layer.mask = mask self.imageView = imageView animateMask() } func animateMask() { let keyFrameAnimation = CAKeyframeAnimation(keyPath: "bounds") keyFrameAnimation.delegate = self keyFrameAnimation.duration = 0.6 keyFrameAnimation.beginTime = CACurrentMediaTime() + 0.5 keyFrameAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)] let initalBounds = NSValue(cgRect: (mask?.bounds)!) let secondBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 90, height: 73)) let finalBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 1600, height: 1300)) keyFrameAnimation.values = [initalBounds, secondBounds, finalBounds] keyFrameAnimation.keyTimes = [0, 0.3, 1] self.mask?.add(keyFrameAnimation, forKey: "bounds") } func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { self.imageView!.layer.mask = nil } }
mit
329909ac71e987bb0263fda73651c7ec
36.035088
170
0.663193
4.481953
false
false
false
false
DashiDashCam/iOS-App
Dashi/Pods/PromiseKit/Sources/when.swift
1
8597
import Foundation import Dispatch private func _when<T>(_ promises: [Promise<T>]) -> Promise<Void> { let root = Promise<Void>.pending() var countdown = promises.count guard countdown > 0 else { #if swift(>=4.0) root.fulfill(()) #else root.fulfill() #endif return root.promise } #if PMKDisableProgress || os(Linux) var progress: (completedUnitCount: Int, totalUnitCount: Int) = (0, 0) #else let progress = Progress(totalUnitCount: Int64(promises.count)) progress.isCancellable = false progress.isPausable = false #endif let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: .concurrent) for promise in promises { promise.state.pipe { resolution in barrier.sync(flags: .barrier) { switch resolution { case let .rejected(error, token): token.consumed = true if root.promise.isPending { progress.completedUnitCount = progress.totalUnitCount root.reject(error) } case .fulfilled: guard root.promise.isPending else { return } progress.completedUnitCount += 1 countdown -= 1 if countdown == 0 { #if swift(>=4.0) root.fulfill(()) #else root.fulfill() #endif } } } } } return root.promise } /** Wait for all promises in a set to fulfill. For example: when(fulfilled: promise1, promise2).then { results in //… }.catch { error in switch error { case URLError.notConnectedToInternet: //… case CLError.denied: //… } } - Note: If *any* of the provided promises reject, the returned promise is immediately rejected with that error. - Warning: In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed, in such situations use `when(resolved:)`. - Parameter promises: The promises upon which to wait before the returned promise resolves. - Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. - Note: `when` provides `NSProgress`. - SeeAlso: `when(resolved:)` */ public func when<T>(fulfilled promises: [Promise<T>]) -> Promise<[T]> { return _when(promises).then(on: zalgo) { promises.map { $0.value! } } } /// Wait for all promises in a set to fulfill. public func when(fulfilled promises: Promise<Void>...) -> Promise<Void> { return _when(promises) } /// Wait for all promises in a set to fulfill. public func when(fulfilled promises: [Promise<Void>]) -> Promise<Void> { return _when(promises) } /// Wait for all promises in a set to fulfill. public func when<U, V>(fulfilled pu: Promise<U>, _ pv: Promise<V>) -> Promise<(U, V)> { return _when([pu.asVoid(), pv.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!) } } /// Wait for all promises in a set to fulfill. public func when<U, V, W>(fulfilled pu: Promise<U>, _ pv: Promise<V>, _ pw: Promise<W>) -> Promise<(U, V, W)> { return _when([pu.asVoid(), pv.asVoid(), pw.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, pw.value!) } } /// Wait for all promises in a set to fulfill. public func when<U, V, W, X>(fulfilled pu: Promise<U>, _ pv: Promise<V>, _ pw: Promise<W>, _ px: Promise<X>) -> Promise<(U, V, W, X)> { return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, pw.value!, px.value!) } } /// Wait for all promises in a set to fulfill. public func when<U, V, W, X, Y>(fulfilled pu: Promise<U>, _ pv: Promise<V>, _ pw: Promise<W>, _ px: Promise<X>, _ py: Promise<Y>) -> Promise<(U, V, W, X, Y)> { return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid(), py.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, pw.value!, px.value!, py.value!) } } /** Generate promises at a limited rate and wait for all to fulfill. For example: func downloadFile(url: URL) -> Promise<Data> { // ... } let urls: [URL] = /* … */ let urlGenerator = urls.makeIterator() let generator = AnyIterator<Promise<Data>> { guard url = urlGenerator.next() else { return nil } return downloadFile(url) } when(generator, concurrently: 3).then { datum: [Data] -> Void in // ... } - Warning: Refer to the warnings on `when(fulfilled:)` - Parameter promiseGenerator: Generator of promises. - Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. - SeeAlso: `when(resolved:)` */ public func when<T, PromiseIterator: IteratorProtocol>(fulfilled promiseIterator: PromiseIterator, concurrently: Int) -> Promise<[T]> where PromiseIterator.Element == Promise<T> { guard concurrently > 0 else { return Promise(error: PMKError.whenConcurrentlyZero) } var generator = promiseIterator var root = Promise<[T]>.pending() var pendingPromises = 0 var promises: [Promise<T>] = [] let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: [.concurrent]) func dequeue() { guard root.promise.isPending else { return } // don’t continue dequeueing if root has been rejected var shouldDequeue = false barrier.sync { shouldDequeue = pendingPromises < concurrently } guard shouldDequeue else { return } var index: Int! var promise: Promise<T>! barrier.sync(flags: .barrier) { guard let next = generator.next() else { return } promise = next index = promises.count pendingPromises += 1 promises.append(next) } func testDone() { barrier.sync { if pendingPromises == 0 { root.fulfill(promises.flatMap { $0.value }) } } } guard promise != nil else { return testDone() } promise.state.pipe { resolution in barrier.sync(flags: .barrier) { pendingPromises -= 1 } switch resolution { case .fulfilled: dequeue() testDone() case let .rejected(error, token): token.consumed = true root.reject(error) } } dequeue() } dequeue() return root.promise } /** Waits on all provided promises. `when(fulfilled:)` rejects as soon as one of the provided promises rejects. `when(resolved:)` waits on all provided promises and **never** rejects. when(resolved: promise1, promise2, promise3).then { results in for result in results where case .fulfilled(let value) { //… } }.catch { error in // invalid! Never rejects } - Returns: A new promise that resolves once all the provided promises resolve. - Warning: The returned promise can *not* be rejected. - Note: Any promises that error are implicitly consumed, your UnhandledErrorHandler will not be called. */ public func when<T>(resolved promises: Promise<T>...) -> Promise<[Result<T>]> { return when(resolved: promises) } /// Waits on all provided promises. public func when<T>(resolved promises: [Promise<T>]) -> Promise<[Result<T>]> { guard !promises.isEmpty else { return Promise(value: []) } var countdown = promises.count let barrier = DispatchQueue(label: "org.promisekit.barrier.join", attributes: .concurrent) return Promise { fulfill, _ in for promise in promises { promise.state.pipe { resolution in if case let .rejected(_, token) = resolution { token.consumed = true // all errors are implicitly consumed } var done = false barrier.sync(flags: .barrier) { countdown -= 1 done = countdown == 0 } if done { fulfill(promises.map { Result($0.state.get()!) }) } } } } }
mit
a18aeb24c6a7a5e17bdb7c77925b65bf
32.404669
424
0.595923
4.235323
false
false
false
false
atomkirk/TouchForms
TouchForms/Source/PickerFormElement.swift
1
3886
// // TextFieldFormElement.swift // TouchForms // // Created by Adam Kirk on 7/25/15. // Copyright (c) 2015 Adam Kirk. All rights reserved. // import UIKit class PickerFormElementDelegate: NSObject, UIPickerViewDataSource, UIPickerViewDelegate { let element: PickerFormElement init(element: PickerFormElement) { self.element = element } // MARK: - Picker View Data Source func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return element.values.count } // MARK: - Picker View Delegate func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { var value = element.values[row] if let valueTransformer = element.valueTransformer, let transformedValue = valueTransformer.transformedValue(value) as? String { value = transformedValue } return value } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let value = element.values[row] element.delegate?.formElement(element, valueDidChange: value) if element.closesOnSelect { element.closePicker() } } } public class PickerFormElement: FormElement { /** The label that appears as the title of what the user is picking. On the left of the element is the title and on the right is the current value they've chosen. */ public var label: String /** Closes the picker as soon as the value changes. `YES` by default. */ public var closesOnSelect = true /** `true` if the picker has currently been toggled visible in the form. */ public var visible = false /** The possible values to choose from. */ public var values: [String] { didSet { pickerView.reloadAllComponents() } } var pickerElementDelegate: PickerFormElementDelegate? let pickerView: UIPickerView public init(label: String, values: [String]) { self.label = label self.values = values self.pickerView = UIPickerView() super.init() self.pickerElementDelegate = PickerFormElementDelegate(element: self) self.pickerView.dataSource = self.pickerElementDelegate self.pickerView.delegate = self.pickerElementDelegate self.pickerView.backgroundColor = UIColor.whiteColor() } /** Open the actual picker below this element. */ public func openPicker() { delegate?.formElement(self, didRequestPresentationOfChildView: pickerView) } /** If the picker is open, close it. */ public func closePicker() { delegate?.formElement(self, didRequestDismissalOfChildView: pickerView) } // MARK: - FormElement public override func populateCell() { if let cell = cell as? PickerFormCell { cell.formLabel?.text = label cell.formButton?.enabled = enabled } super.populateCell() } public override func isEditable() -> Bool { return true } // MARK: - Cell Delegate public override func formCell(cell: FormCell, userDidPerformInteraction interaction: FormCellUserInteraction, view: UIView) { if let value = currentModelValue() as? String, let index = values.indexOf(value) { pickerView.selectRow(index, inComponent: 0, animated: true) } if !visible { visible = true delegate?.formElement(self, didRequestPresentationOfChildView: pickerView) } else { visible = false delegate?.formElement(self, didRequestDismissalOfChildView: pickerView) } } }
mit
9c1d9c4f8f0315941342faf05a1907fe
27.364964
129
0.64771
4.937738
false
false
false
false
LimonTop/StoreKit
StoreKit/CoreDataModel.swift
1
6206
// // Created by Jesse Squires // http://www.jessesquires.com // // // Documentation // http://www.jessesquires.com/JSQCoreDataKit // // // GitHub // https://github.com/jessesquires/JSQCoreDataKit // // // License // Copyright (c) 2015 Jesse Squires // Released under an MIT license: http://opensource.org/licenses/MIT // import Foundation import CoreData /// :nodoc: public func ==(lhs: StoreType, rhs: StoreType) -> Bool { switch (lhs, rhs) { case let (.SQLite(left), .SQLite(right)) where left == right: return true case let (.Binary(left), .Binary(right)) where left == right: return true case (.InMemory, .InMemory): return true default: return false } } /// Describes a Core Data persistent store type. public enum StoreType: CustomStringConvertible, Equatable { /// The SQLite database store type. The associated file URL specifies the directory for the store. case SQLite (NSURL) /// The binary store type. The associated file URL specifies the directory for the store. case Binary (NSURL) /// The in-memory store type. case InMemory /** - returns: The file URL specifying the directory in which the store is located. - Note: If the store is in-memory, then this value will be `nil`. */ public func storeDirectory() -> NSURL? { switch self { case let .SQLite(url): return url case let .Binary(url): return url case .InMemory: return nil } } /// :nodoc: public var description: String { get { switch self { case .SQLite: return NSSQLiteStoreType case .Binary: return NSBinaryStoreType case .InMemory: return NSInMemoryStoreType } } } } /** An instance of `CoreDataModel` represents a Core Data model. It provides the model and store URLs as well as methods for interacting with the store. */ public struct CoreDataModel: CustomStringConvertible { // MARK: Properties /// The name of the Core Data model resource. public let name: String /// The bundle in which the model is located. public let bundle: NSBundle /// The type of the Core Data persistent store for the model. public let storeType: StoreType /** The file URL specifying the full path to the store. - Note: If the store is in-memory, then this value will be `nil`. */ public var storeURL: NSURL? { get { return storeType.storeDirectory()?.URLByAppendingPathComponent(databaseFileName) } } /// The file URL specifying the model file in the bundle specified by `bundle`. public var modelURL: NSURL { get { guard let url = bundle.URLForResource(name, withExtension: "momd") else { fatalError("*** Error loading model URL for model named \(name) in bundle: \(bundle)") } return url } } /// The database file name for the store. public var databaseFileName: String { get { switch storeType { case .SQLite: return name + ".sqlite" default: return name } } } /// The managed object model for the model specified by `name`. public var managedObjectModel: NSManagedObjectModel { get { guard let model = NSManagedObjectModel(contentsOfURL: modelURL) else { fatalError("*** Error loading managed object model at url: \(modelURL)") } return model } } /** Queries the meta data for the persistent store specified by the receiver and returns whether or not a migration is needed. - returns: `true` if the store requires a migration, `false` otherwise. */ public var needsMigration: Bool { get { guard let storeURL = storeURL else { return false } do { let sourceMetaData = try NSPersistentStoreCoordinator.metadataForPersistentStoreOfType( storeType.description, URL: storeURL, options: nil) return !managedObjectModel.isConfiguration(nil, compatibleWithStoreMetadata: sourceMetaData) } catch { debugPrint("*** Error checking persistent store coordinator meta data: \(error)") return false } } } // MARK: Initialization /** Constructs a new `CoreDataModel` instance with the specified name and bundle. - parameter name: The name of the Core Data model. - parameter bundle: The bundle in which the model is located. The default is the main bundle. - parameter storeType: The store type for the Core Data model. The default is `.SQLite`, with the user's documents directory. - returns: A new `CoreDataModel` instance. */ public init(name: String, bundle: NSBundle = .mainBundle(), storeType: StoreType = .SQLite(DocumentsDirectoryURL())) { self.name = name self.bundle = bundle self.storeType = storeType } // MARK: Methods /** Removes the existing model store specfied by the receiver. - throws: If removing the store fails or errors, then this function throws an `NSError`. */ public func removeExistingModelStore() throws { let fileManager = NSFileManager.defaultManager() if let storePath = storeURL?.path where fileManager.fileExistsAtPath(storePath) { try fileManager.removeItemAtPath(storePath) } } // MARK: CustomStringConvertible /// :nodoc: public var description: String { get { return "<\(CoreDataModel.self): name=\(name), storeType=\(storeType) needsMigration=\(needsMigration), modelURL=\(modelURL), storeURL=\(storeURL)>" } } } // MARK: Private private func DocumentsDirectoryURL() -> NSURL { do { return try NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) } catch { fatalError("*** Error finding documents directory: \(error)") } }
mit
14d030763e7e8c7c0bfb3f57e60e6c36
29.571429
159
0.627941
4.952913
false
false
false
false
hxx0215/VPNOn
VPNOn/LTVPNDownloader.swift
1
1228
// // LTVPNDownloader.swift // VPNOn // // Created by Lex Tang on 1/27/15. // Copyright (c) 2015 LexTang.com. All rights reserved. // import UIKit class LTVPNDownloader: NSObject { var queue: NSOperationQueue? func download(URL: NSURL, callback: (NSURLResponse!, NSData!, NSError!) -> Void) { let request = NSMutableURLRequest(URL: URL) var agent = "VPN On" if let version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String? { agent = "\(agent) \(version)" } request.HTTPShouldHandleCookies = false request.HTTPShouldUsePipelining = true request.cachePolicy = NSURLRequestCachePolicy.ReloadRevalidatingCacheData request.addValue(agent, forHTTPHeaderField: "User-Agent") request.timeoutInterval = 20 if let q = queue { q.suspended = true queue = nil } queue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler: callback) } func cancel() { if let q = queue { q.suspended = true queue = nil } } }
mit
a1ad0020470da5a72964ba84169de4d7
27.55814
117
0.610749
4.89243
false
false
false
false
jegumhon/URWeatherView
URWeatherView/SpriteAssets/URSnowGroundEmitterNode.swift
1
1836
// // URSnowGroundEmitterNode.swift // URWeatherView // // Created by DongSoo Lee on 2017. 6. 14.. // Copyright © 2017년 zigbang. All rights reserved. // import SpriteKit open class URSnowGroundEmitterNode: SKEmitterNode { public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init() { super.init() let bundle = Bundle(for: URSnowGroundEmitterNode.self) let particleImage = UIImage(named: "snow_typeB", in: bundle, compatibleWith: nil)! self.particleTexture = SKTexture(image: particleImage) self.particleBirthRate = 100.0 // self.particleBirthRateMax? self.particleLifetime = 2.0 self.particleLifetimeRange = 5.0 self.particlePositionRange = CGVector(dx: 100.0, dy: 7.5) self.zPosition = 0.0 self.emissionAngle = CGFloat(-90.0 * .pi / 180.0) self.emissionAngleRange = 0.0 self.particleSpeed = 0.1 self.particleSpeedRange = 0.1 self.xAcceleration = 0.0 self.yAcceleration = 0.0 self.particleAlpha = 0.1 self.particleAlphaRange = 0.3 self.particleAlphaSpeed = 0.3 self.particleScale = 0.06 self.particleScaleRange = 0.1 self.particleScaleSpeed = 0.0 self.particleRotation = 0.0 self.particleRotationRange = 0.0 self.particleRotationSpeed = 0.0 self.particleColorBlendFactor = 1.0 self.particleColorBlendFactorRange = 0.0 self.particleColorBlendFactorSpeed = 0.0 self.particleColorSequence = SKKeyframeSequence(keyframeValues: [UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 1.0, alpha: 1.0), UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 1.0, alpha: 1.0)], times: [0.0, 1.0]) self.particleBlendMode = .alpha } }
mit
50f66bc25a1996b1301ab6fb18b42125
36.408163
232
0.6503
3.651394
false
false
false
false
PrimarySA/Hackaton2015
stocker/BachiTrading/Inspectables.swift
1
2715
// // Inspectables.swift // BachiTrading // // Created by Emiliano Bivachi on 14/11/15. // Copyright (c) 2015 Emiliano Bivachi. All rights reserved. // import Foundation extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable var borderColor: UIColor { get { return UIColor(CGColor: layer.borderColor!)! } set { layer.borderColor = newValue.CGColor } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var shadowColor: UIColor { get { return UIColor(CGColor: layer.shadowColor!)! } set { layer.shadowColor = newValue.CGColor } } @IBInspectable var shadowOpacity: Float { get { return layer.shadowOpacity } set { layer.shadowOpacity = newValue } } @IBInspectable var shadowRadius: CGFloat { get { return layer.shadowRadius } set { layer.shadowRadius = newValue } } @IBInspectable var shadowWidthOffset: CGFloat { get { return layer.shadowOffset.width } set { layer.shadowOffset.width = newValue } } @IBInspectable var shadowHeightOffset: CGFloat { get { return layer.shadowOffset.height } set { layer.shadowOffset.height = newValue } } } extension UILabel { @IBInspectable var localizedText: String? { set { if newValue != nil && newValue != "" { text = NSLocalizedString(newValue!, comment: "") } } get { return text } } } extension UIButton { @IBInspectable var localizedTitle: String? { set { if newValue != nil && newValue != "" { setTitle(NSLocalizedString(newValue!, comment: ""), forState: .Normal) } } get { return titleForState(.Normal) } } } extension UITextField { @IBInspectable var localizedTitle: String? { set { if newValue != nil && newValue != "" { placeholder = NSLocalizedString(newValue!, comment: "") } } get { return placeholder } } }
gpl-3.0
0a5a0b80fbfc23894dd40069471fd0dd
20.895161
86
0.504604
5.261628
false
false
false
false
WSDOT/wsdot-ios-app
wsdot/TimeUtils.swift
2
8829
// // TimeUtils.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import Foundation import SwiftyJSON class TimeUtils { enum TimeUtilsError: Error { case invalidTimeString } static var currentTime: Int64{ get { return Int64(floor(Date().timeIntervalSince1970 * 1000)) } } // formats a /Date(1468516282113-0700)/ date into NSDate static func parseJSONDateToNSDate(_ date: String) -> Date { if (date.count < 16) { return Date(timeIntervalSince1970: 0) } let parseDateString = date[date.index(date.startIndex, offsetBy: 6)..<date.index(date.startIndex, offsetBy: 16)] if let date = Double(parseDateString) { return Date(timeIntervalSince1970: date) } else { return Date(timeIntervalSince1970: 0) } } // formates a /Date(1468516282113-0700)/ date into a Int64 static func parseJSONDate(_ date: String) -> Int64{ let parseDateString = date[date.index(date.startIndex, offsetBy: 6)..<date.index(date.startIndex, offsetBy: 16)] if let date = Int64(parseDateString) { return date } else { return 0 } } static func getTimeOfDay(_ date: Date) -> String{ //Get Short Time String let formatter = DateFormatter() formatter.timeStyle = .short formatter.timeZone = TimeZone(abbreviation: "PDT") let timeString = formatter.string(from: date) //Return Short Time String return timeString } // Returns an array of the days of the week starting with the current day static func nextSevenDaysStrings(_ date: Date) -> [String]{ let weekdays = DateFormatter().weekdaySymbols let dayOfWeekInt = getDayOfWeek(date) return Array(weekdays![dayOfWeekInt-1..<weekdays!.count]) + weekdays![0..<dayOfWeekInt] } fileprivate static func getDayOfWeek(_ date: Date)->Int { let myCalendar = Calendar(identifier: Calendar.Identifier.gregorian) let myComponents = (myCalendar as NSCalendar).components(.weekday, from: date) let weekDay = myComponents.weekday return weekDay! } // Returns an array of dates n days out from givin day, including the given date static func nextNDayDates(n: Int, _ date: Date) -> [Date]{ let array = [Int](0...(n-1)) let dates: [Date] = array.enumerated().map { (index, element) in return date.addingTimeInterval(TimeInterval(86400 * element)) } return dates } static func getDayOfWeekString(_ date: Date) -> String { let weekdays = DateFormatter().weekdaySymbols return weekdays![getDayOfWeek(date)-1] } // Returns an NSDate object form a date string with the given format "yyyy-MM-dd hh:mm a" static func formatTimeStamp(_ timestamp: String, dateFormat:String = "yyyy-MM-dd hh:mm a") throws -> Date{ let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.timeZone = TimeZone(abbreviation: "PST") dateFormatter.dateFormat = dateFormat guard let time = dateFormatter.date(from: timestamp) else { throw TimeUtilsError.invalidTimeString } return time } static func getDateFromJSONArray(_ time: [JSON]) -> Date{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-M-d H:mm" dateFormatter.timeZone = TimeZone(abbreviation: "PDT") let year = time[0].stringValue let month = time[1].stringValue let day = time[2].stringValue let hour = time[3].stringValue let min = time[4].stringValue let dateString = year + "-" + month + "-" + day + " " + hour + ":" + min if let date = dateFormatter.date(from: dateString){ return date } else { return Date.init(timeIntervalSince1970: 0) } } // Converts blogger pub date format into an NSDate object (ex. 2016-08-26T09:24:00.000-07:00) static func postPubDateToNSDate(_ time: String, formatStr: String, isUTC: Bool) -> Date{ let dateFormatter = DateFormatter() if (isUTC){ dateFormatter.timeZone = TimeZone(abbreviation: "UTC") } dateFormatter.dateFormat = formatStr return dateFormatter.date(from: time)! } // returns a date string with the format MMMM DD, YYYY H:mm a static func formatTime(_ date: Date, format: String) -> String { let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(abbreviation: "PDT") dateFormatter.dateFormat = format return dateFormatter.string(from: date) } // Calculates the number of mins mentions in a string. Assumes string format XX HR XX MIN, XX MIN, XX HR static func getMinsFromString(_ string: String) -> Double { let stringArr = string.split{$0 == " "}.map(String.init) var index = 0 var mins = 0.0 for string in stringArr { if (string.rangeOfCharacter(from: CharacterSet.decimalDigits, options: NSString.CompareOptions(), range: nil) != nil) { if Double(string) != nil { if stringArr[index + 1] == "HR" { mins += Double(string)! * 60 } else { mins += Double(string)! } } } index += 1 } return mins } // Returns a string timestamp since a given time in miliseconds. // Source: https://gist.github.com/chashmeetsingh/736b4898d0988888a2e6695455cb8edc static func timeAgoSinceDate(date:Date, numericDates:Bool) -> String { let calendar = NSCalendar.current let unitFlags: Set<Calendar.Component> = [.minute, .hour, .day, .weekOfYear, .month, .year, .second] let now = NSDate() let earliest = now.earlierDate(date as Date) let latest = (earliest == now as Date) ? date : now as Date let components = calendar.dateComponents(unitFlags, from: earliest as Date, to: latest as Date) if (components.year! >= 2) { return "\(components.year!) years ago" } else if (components.year! >= 1){ if (numericDates){ return "1 year ago" } else { return "Last year" } } else if (components.month! >= 2) { return "\(components.month!) months ago" } else if (components.month! >= 1){ if (numericDates){ return "1 month ago" } else { return "Last month" } } else if (components.weekOfYear! >= 2) { return "\(components.weekOfYear!) weeks ago" } else if (components.weekOfYear! >= 1){ if (numericDates){ return "1 week ago" } else { return "Last week" } } else if (components.day! >= 2) { return "\(components.day!) days ago" } else if (components.day! >= 1){ if (numericDates){ return "1 day ago" } else { return "Yesterday" } } else if (components.hour! >= 2) { return "\(components.hour!) hours ago" } else if (components.hour! >= 1){ if (numericDates){ return "1 hour ago" } else { return "An hour ago" } } else if (components.minute! >= 2) { return "\(components.minute!) minutes ago" } else if (components.minute! >= 1){ if (numericDates){ return "1 minute ago" } else { return "A minute ago" } } else if (components.second! >= 3) { return "\(components.second!) seconds ago" } else { return "Just now" } } }
gpl-3.0
d6e354c52e921ab455ba233a5098a2e6
36.411017
131
0.582852
4.527692
false
false
false
false
WangCrystal/actor-platform
actor-apps/app-ios/ActorApp/View/Cells/CommonCell.swift
4
4532
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import UIKit enum CommonCellStyle { case Normal case DestructiveCentered case Destructive case Switch case Blue case Green case Navigation case Hint } class CommonCell: UATableViewCell { // MARK: - // MARK: Private vars private var switcher: UISwitch? // MARK: - // MARK: Public vars var style: CommonCellStyle = .Normal { didSet { updateCellStyle() } } var switchBlock: ((Bool) -> ())? // MARK: - // MARK: Constructors override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) textLabel!.font = UIFont.systemFontOfSize(17.0) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - // MARK: Methods private func updateCellStyle() { switch (style) { case .Normal: textLabel!.textColor = MainAppTheme.list.textColor textLabel!.textAlignment = NSTextAlignment.Left switcher?.hidden = true accessoryType = UITableViewCellAccessoryType.None break case .Hint: textLabel!.textColor = MainAppTheme.list.hintColor textLabel!.textAlignment = NSTextAlignment.Left switcher?.hidden = true accessoryType = UITableViewCellAccessoryType.None break case .DestructiveCentered: textLabel!.textColor = UIColor.redColor() textLabel!.textAlignment = NSTextAlignment.Center switcher?.hidden = true accessoryType = UITableViewCellAccessoryType.None break case .Destructive: textLabel!.textColor = UIColor.redColor() textLabel!.textAlignment = NSTextAlignment.Left switcher?.hidden = true accessoryType = UITableViewCellAccessoryType.None break case .Switch: textLabel!.textColor = MainAppTheme.list.textColor setupSwitchIfNeeded() switcher?.hidden = false accessoryType = UITableViewCellAccessoryType.None break case .Blue: // TODO: Maybe rename? // textLabel!.textColor = UIColor.RGB(0x007ee5) textLabel!.textColor = MainAppTheme.list.actionColor textLabel!.textAlignment = NSTextAlignment.Left switcher?.hidden = true accessoryType = UITableViewCellAccessoryType.None break case .Green: textLabel!.textColor = UIColor(red: 76/255.0, green: 216/255.0, blue: 100/255.0, alpha: 1.0) // TODO: Change color textLabel!.textAlignment = NSTextAlignment.Left switcher?.hidden = true accessoryType = UITableViewCellAccessoryType.None break case .Navigation: textLabel!.textColor = MainAppTheme.list.textColor textLabel!.textAlignment = NSTextAlignment.Left switcher?.hidden = true accessoryType = UITableViewCellAccessoryType.DisclosureIndicator } } private func setupSwitchIfNeeded() { if switcher == nil { switcher = UISwitch() switcher!.addTarget(self, action: Selector("switcherSwitched"), forControlEvents: UIControlEvents.ValueChanged) contentView.addSubview(switcher!) } } func switcherSwitched() { if switchBlock != nil { switchBlock!(switcher!.on) } } // MARK: - // MARK: Setters func setContent(content: String) { textLabel!.text = content } func setSwitcherOn(on: Bool) { setSwitcherOn(on, animated: false) } func setSwitcherOn(on: Bool, animated: Bool) { switcher?.setOn(on, animated: animated) } func setSwitcherEnabled(enabled: Bool) { switcher?.enabled = enabled } // MARK: - // MARK: Layout override func layoutSubviews() { super.layoutSubviews() if switcher != nil { let switcherSize = switcher!.bounds.size switcher!.frame = CGRect(x: contentView.bounds.width - switcherSize.width - 15, y: (contentView.bounds.height - switcherSize.height) / 2, width: switcherSize.width, height: switcherSize.height) } } }
mit
71db050245c9562e1df13cb332f05053
29.621622
205
0.599294
5.395238
false
false
false
false
achimk/Cars
CarsApp/CarsApp/Presenters/Error/RetryErrorPresenter.swift
1
2385
// // RetryErrorPresenter.swift // CarsApp // // Created by Joachim Kret on 30/07/2017. // Copyright © 2017 Joachim Kret. All rights reserved. // import Foundation import UIKit struct RetryErrorPresenterSpecs { let cancelTitle: String let retryTitle: String let onDissmissCallback: ((Void) -> Void)? } final class RetryErrorPresenter: ErrorPresenterType, ErrorPresenterFactoryType { weak var sourceViewController: UIViewController? var currentAlert: UIAlertController? let parser: ErrorMessageParserType let specs: RetryErrorPresenterSpecs var next: ErrorHandlingChainable? static func create(using contextController: UIViewController?) -> ErrorPresenterType { let specs = RetryErrorPresenterSpecs( cancelTitle: NSLocalizedString("Cancel", comment: "Cancel button"), retryTitle: NSLocalizedString("Retry", comment: "Retry button"), onDissmissCallback: nil ) let presenter = RetryErrorPresenter(parser: ErrorMessageParser(), specs: specs) presenter.sourceViewController = contextController return presenter } init(parser: ErrorMessageParserType, specs: RetryErrorPresenterSpecs) { self.parser = parser self.specs = specs } func present(with error: Error) { let alert = UIAlertController( title: NSLocalizedString("Error", comment: "Error title"), message: parser.parse(error), preferredStyle: UIAlertControllerStyle.alert ) let retry = UIAlertAction( title: specs.retryTitle, style: UIAlertActionStyle.default, handler: { [weak self] action in self?.dismiss() let _ = self?.can(handle: error) }) let cancel = UIAlertAction( title: specs.cancelTitle, style: UIAlertActionStyle.destructive, handler: { [weak self] _ in self?.dismiss() }) alert.addAction(retry) alert.addAction(cancel) currentAlert = alert sourceViewController?.present(alert, animated: true, completion: nil) } func dismiss() { currentAlert?.dismiss(animated: true, completion: { [weak self] in self?.specs.onDissmissCallback?() self?.currentAlert = nil }) } }
mit
6dd2429daef3ab1523c3cc94d6f1e495
28.8
90
0.638003
5.029536
false
false
false
false
natecook1000/swift
test/DebugInfo/transparent.swift
3
752
// RUN: %target-swift-frontend %s -O -I %t -emit-ir -g -o - | %FileCheck %s func use<T>(_ t: T) {} @inline(never) public func noinline(_ x: Int64) -> Int64 { return x } @_transparent public func transparent(_ y: Int64) -> Int64 { var local = y return noinline(local) } let z = transparent(0) use(z) // Check that a transparent function has no debug information. // CHECK: define {{.*}}$S11transparentAA // CHECK-SAME: !dbg ![[SP:[0-9]+]] // CHECK-NEXT: entry: // CHECK-NEXT: !dbg ![[ZERO:[0-9]+]] // CHECK-NEXT: !dbg ![[ZERO]] // CHECK-NEXT: } // CHECK: ![[SP]] = {{.*}}name: "transparent" // CHECK-SAME: file: ![[FILE:[0-9]+]] // CHECK-NOT: line: // CHECK: ![[FILE]] = {{.*}}"<compiler-generated>" // CHECK: ![[ZERO]] = !DILocation(line: 0,
apache-2.0
532854fc791c32ba813d2f807fb2fcaf
24.931034
75
0.591755
2.892308
false
false
false
false
natecook1000/swift
test/Frontend/OptimizationOptions-with-stdlib-checks.swift
2
6389
// RUN: %target-swift-frontend -module-name OptimizationOptions -Onone -emit-sil -primary-file %s -o - | %FileCheck %s --check-prefix=DEBUG // RUN: %target-swift-frontend -module-name OptimizationOptions -O -emit-sil -primary-file %s -o - | %FileCheck %s --check-prefix=RELEASE // RUN: %target-swift-frontend -module-name OptimizationOptions -Ounchecked -emit-sil -primary-file %s -o - | %FileCheck %s --check-prefix=UNCHECKED // RUN: %target-swift-frontend -module-name OptimizationOptions -Oplayground -emit-sil -primary-file %s -o - | %FileCheck %s --check-prefix=PLAYGROUND // REQUIRES: optimized_stdlib // REQUIRES: swift_stdlib_asserts func test_assert(x: Int, y: Int) -> Int { assert(x >= y , "x smaller than y") return x + y } func test_fatal(x: Int, y: Int) -> Int { if x > y { return x + y } preconditionFailure("Human nature ...") } func testprecondition_check(x: Int, y: Int) -> Int { precondition(x > y, "Test precondition check") return x + y } func test_partial_safety_check(x: Int, y: Int) -> Int { assert(x > y, "Test partial safety check") return x + y } // In debug mode keep user asserts and runtime checks. // DEBUG-LABEL: sil hidden @$S19OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // DEBUG-DAG: string_literal utf8 "x smaller than y" // DEBUG-DAG: string_literal utf8 "Assertion failed" // DEBUG-DAG: cond_fail // DEBUG: return // In playground mode keep user asserts and runtime checks. // PLAYGROUND-LABEL: sil hidden @$S19OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // PLAYGROUND-DAG: "Assertion failed" // PLAYGROUND-DAG: "x smaller than y" // PLAYGROUND-DAG: cond_fail // PLAYGROUND: return // In release mode remove user asserts and keep runtime checks. // RELEASE-LABEL: sil hidden @$S19OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // RELEASE-NOT: "x smaller than y" // RELEASE-NOT: "Assertion failed" // RELEASE: cond_fail // RELEASE: return // In fast mode remove user asserts and runtime checks. // FAST-LABEL: sil hidden @$S19OptimizationOptions11test_assert1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // FAST-NOT: "x smaller than y" // FAST-NOT: "Assertion failed" // FAST-NOT: cond_fail // In debug mode keep verbose fatal errors. // DEBUG-LABEL: sil hidden @$S19OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // DEBUG-DAG: "Human nature ..." // DEBUG-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC:.*assertionFailure.*]] : $@convention(thin) // DEBUG: apply %[[FATAL_ERROR]]{{.*}} // DEBUG: unreachable // In playground mode keep verbose fatal errors. // PLAYGROUND-LABEL: sil hidden @$S19OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // PLAYGROUND-DAG: "Human nature ..." // PLAYGROUND-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC:.*assertionFailure.*]] : $@convention(thin) // PLAYGROUND: apply %[[FATAL_ERROR]]{{.*}} // PLAYGROUND: unreachable // In release mode keep succinct fatal errors (trap). // RELEASE-LABEL: sil hidden @$S19OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // RELEASE-NOT: "Human nature ..." // RELEASE-NOT: "Fatal error" // RELEASE: cond_fail // RELEASE: return // In fast mode remove fatal errors. // FAST-LABEL: sil hidden @$S19OptimizationOptions10test_fatal1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // FAST-NOT: "Human nature ..." // FAST-NOT: "Fatal error" // FAST-NOT: int_trap // Precondition safety checks. // In debug mode keep verbose library precondition checks. // DEBUG-LABEL: sil hidden @$S19OptimizationOptions22testprecondition_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // DEBUG-DAG: "Precondition failed" // DEBUG-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]] // DEBUG: apply %[[FATAL_ERROR]]{{.*}} // DEBUG: unreachable // DEBUG: return // In playground mode keep verbose library precondition checks. // PLAYGROUND-LABEL: sil hidden @$S19OptimizationOptions22testprecondition_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // PLAYGROUND-DAG: "Precondition failed" // PLAYGROUND-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]] // PLAYGROUND: apply %[[FATAL_ERROR]]{{.*}} // PLAYGROUND: unreachable // PLAYGROUND: return // In release mode keep succinct library precondition checks (trap). // RELEASE-LABEL: sil hidden @$S19OptimizationOptions22testprecondition_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // RELEASE-NOT: "Fatal error" // RELEASE: %[[V2:.+]] = builtin "xor_Int1"(%{{.+}}, %{{.+}}) // RELEASE: cond_fail %[[V2]] // RELEASE: return // In unchecked mode remove library precondition checks. // UNCHECKED-LABEL: sil hidden @$S19OptimizationOptions22testprecondition_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // UNCHECKED-NOT: "Fatal error" // UNCHECKED-NOT: builtin "int_trap" // UNCHECKED-NOT: unreachable // UNCHECKED: return // Partial safety checks. // In debug mode keep verbose partial safety checks. // DEBUG-LABEL: sil hidden @$S19OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // DEBUG-DAG: "Assertion failed" // DEBUG-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]] // DEBUG: apply %[[FATAL_ERROR]]{{.*}} // DEBUG: unreachable // In playground mode keep verbose partial safety checks. // PLAYGROUND-LABEL: sil hidden @$S19OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // PLAYGROUND-DAG: "Assertion failed" // PLAYGROUND-DAG: %[[FATAL_ERROR:.+]] = function_ref @[[FATAL_ERROR_FUNC]] // PLAYGROUND: apply %[[FATAL_ERROR]]{{.*}} // PLAYGROUND: unreachable // In release mode remove partial safety checks. // RELEASE-LABEL: sil hidden @$S19OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // RELEASE-NOT: "Fatal error" // RELEASE-NOT: builtin "int_trap" // RELEASE-NOT: unreachable // RELEASE: return // In fast mode remove partial safety checks. // FAST-LABEL: sil hidden @$S19OptimizationOptions25test_partial_safety_check1x1yS2i_SitF : $@convention(thin) (Int, Int) -> Int { // FAST-NOT: "Fatal error" // FAST-NOT: builtin "int_trap" // FAST-NOT: unreachable // FAST: return
apache-2.0
01399cc66bfc30f4e75e3ffa0715a411
42.760274
150
0.702301
3.332812
false
true
false
false
wpuricz/vapor-database-sample
Sources/App/Controllers/ApplicationController.swift
1
2171
import Vapor import HTTP extension Vapor.KeyAccessible where Key == HeaderKey, Value == String { var contentType: String? { get { return self["Content-Type"] } set { self["Content-Type"] = newValue } } var authorization: String? { get { return self["Authorization"] } set { self["Authorization"] = newValue } } } public enum ContentType: String { case html = "text/html" case json = "application/json" } open class ApplicationController { private var resourcefulName: String { let className = String(describing: type(of: self)) return className.replacingOccurrences(of: "Controller", with: "").lowercased() } public func respond(to request: Request, with response: [ContentType : ResponseRepresentable]) -> ResponseRepresentable { let contentTypeValue = request.headers.contentType ?? ContentType.html.rawValue let contentType = ContentType(rawValue: contentTypeValue) ?? ContentType.html return response[contentType] ?? Response(status: .notFound) } public func render(_ path: String, _ context: NodeRepresentable? = nil) throws -> View { return try drop.view.make("\(resourcefulName)/\(path)", context ?? Node.null) } public func render(_ path: String, _ context: [String : NodeRepresentable]?) throws -> View { return try render(path, context?.makeNode()) } } extension Resource { public convenience init( index: Multiple? = nil, show: Item? = nil, create: Multiple? = nil, replace: Item? = nil, update: Item? = nil, destroy: Item? = nil, clear: Multiple? = nil, aboutItem: Item? = nil, aboutMultiple: Multiple? = nil) { self.init( index: index, store: create, show: show, replace: replace, modify: update, destroy: destroy, clear: clear, aboutItem: aboutItem, aboutMultiple: aboutMultiple ) } }
mit
40750eb9a8df547a5b3d7037779c0c84
27.194805
125
0.576693
4.688985
false
false
false
false
fespinoza/linked-ideas-osx
LinkedIdeasTests/TestProtocolConformance.swift
1
2765
// // File.swift // LinkedIdeas // // Created by Felipe Espinoza Castillo on 27/09/2016. // Copyright © 2016 Felipe Espinoza Dev. All rights reserved. // import Foundation @testable import LinkedIdeas @testable import LinkedIdeas_Shared class TestLinkedIdeasDocument: LinkedIdeasDocument { var concepts = [Concept]() var links = [Link]() var observer: DocumentObserver? func save(concept: Concept) { concepts.append(concept) } func remove(concept: Concept) {} func save(link: Link) {} func remove(link: Link) {} func move(concept: Concept, toPoint: CGPoint) {} } protocol MockMethodCalls: class { var methodCalls: [String: Int] { get set } } extension MockMethodCalls { func registerCall(methodName: String) { if let currentCallsNumber = methodCalls[methodName] { methodCalls[methodName] = currentCallsNumber + 1 } else { methodCalls[methodName] = 1 } } } class StateManagerTestDelegate: MockMethodCalls { var methodCalls = [String: Int]() } extension StateManagerTestDelegate: StateManagerDelegate { func transitionedToResizingConcept(fromState: CanvasState) { registerCall(methodName: #function) } func transitionSuccesfull() {} func transitionedToNewConcept(fromState: CanvasState) { registerCall(methodName: #function) } func transitionedToCanvasWaiting(fromState: CanvasState) { registerCall(methodName: #function) } func transitionedToCanvasWaitingSavingConcept(fromState: CanvasState, point: CGPoint, text: NSAttributedString) { registerCall(methodName: #function) } func transitionedToSelectedElement(fromState: CanvasState) { registerCall(methodName: #function) } func transitionedToSelectedElementSavingChanges(fromState: CanvasState) { registerCall(methodName: #function) } func transitionedToEditingElement(fromState: CanvasState) { registerCall(methodName: #function) } func transitionedToMultipleSelectedElements(fromState: CanvasState) { registerCall(methodName: #function) } func transitionedToCanvasWaitingDeletingElements(fromState: CanvasState) { registerCall(methodName: #function) } } struct TestElement: Element { var stringValue: String { return attributedStringValue.string } var identifier: String var area: CGRect var isSelected: Bool = false var isEditable: Bool = false var centerPoint: CGPoint { return area.center } var attributedStringValue: NSAttributedString var debugDescription: String { return "[Concept][\(identifier)]" } static let sample = TestElement( identifier: "element #1", area: CGRect(x: 30, y: 40, width: 100, height: 50), isSelected: false, isEditable: false, attributedStringValue: NSAttributedString(string: "") ) }
mit
ed330e5552fd853a2935cafeb23da86f
25.075472
115
0.737699
4.219847
false
true
false
false
SvenTiigi/PerfectAPIClient
Tests/PerfectAPIClientTests/GithubAPI/Models/Repository.swift
1
1054
// // Repository.swift // PerfectAPIClientTests // // Created by Sven Tiigi on 12.12.17. // import ObjectMapper struct Repository { /// The name var name: String? /// The full name var fullName: String? } // MARK: Mappable extension Repository: Mappable { /// ObjectMapper initializer init?(map: Map) { } /// Mapping mutating func mapping(map: Map) { self.name <- map["name"] self.fullName <- map["full_name"] } } // MARK: Equatable extension Repository: Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. /// Equatable public static func == (lhs: Repository, rhs: Repository) -> Bool { return lhs.name == rhs.name && lhs.fullName == rhs.fullName } }
mit
831043451936e47b385ff86a07122ce5
20.08
74
0.570209
3.932836
false
false
false
false
mownier/photostream
Photostream/UI/Shared/PostListCollectionCell/PostListCollectionCellItem.swift
1
3272
// // PostListCollectionCellItem.swift // Photostream // // Created by Mounir Ybanez on 08/12/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // import Kingfisher protocol PostListCollectionCellItem { var message: String { get } var displayName: String { get } var avatarUrl: String { get } var photoUrl: String { get } var photoSize: CGSize { get } var timeAgo: String { get } var isLiked: Bool { get } var likesText: String { get } var commentsText: String { get } } protocol PostListCollectionCellConfig { var dynamicHeight: CGFloat { get } func configure(with item: PostListCollectionCellItem?, isPrototype: Bool) func set(message: String, displayName: String) func set(photo url: String) func set(liked: Bool) } extension PostListCollectionCell: PostListCollectionCellConfig { var dynamicHeight: CGFloat { var height = timeLabel.frame.origin.y height += timeLabel.frame.size.height height += (spacing * 2) return height } func configure(with item: PostListCollectionCellItem?, isPrototype: Bool = false) { guard let item = item else { return } if !isPrototype { set(photo: item.photoUrl) } set(message: item.message, displayName: item.displayName) set(liked: item.isLiked) timeLabel.text = item.timeAgo.uppercased() likeCountLabel.text = item.likesText commentCountLabel.text = item.commentsText photoImageView.frame.size = item.photoSize setNeedsLayout() layoutIfNeeded() } func set(message: String, displayName: String) { guard !message.isEmpty else { messageLabel.attributedText = NSAttributedString(string: "") return } let font = messageLabel.font! let semiBold = UIFont.systemFont(ofSize: font.pointSize, weight: UIFont.Weight.semibold) let regular = UIFont.systemFont(ofSize: font.pointSize) let name = NSAttributedString(string: displayName, attributes: [NSAttributedStringKey.font: semiBold]) let message = NSAttributedString(string: message, attributes: [NSAttributedStringKey.font: regular]) let text = NSMutableAttributedString() text.append(name) text.append(NSAttributedString(string: " ")) text.append(message) messageLabel.attributedText = text } func set(photo url: String) { guard let downloadUrl = URL(string: url) else { return } let resource = ImageResource(downloadURL: downloadUrl) photoImageView.backgroundColor = UIColor.lightGray photoImageView.kf.setImage( with: resource, placeholder: nil, options: nil, progressBlock: nil) { [weak self] (_, _, _, _) in self?.photoImageView.backgroundColor = UIColor.white } } func set(liked: Bool) { if liked { heartButton.setImage(UIImage(named: "heart_pink"), for: .normal) } else { heartButton.setImage(UIImage(named: "heart"), for: .normal) } } }
mit
132f416b502ec61e2dd98112147971ea
30.152381
110
0.620605
4.824484
false
false
false
false
NikitaAsabin/pdpDecember
DayPhoto/APIManager.swift
1
4105
// // APIManager.swift // DayPhoto // // Created by Kruperfone on 16.02.15. // Copyright (c) 2015 Flatstack. All rights reserved. // import Foundation class APIManager: NSObject { class var sharedInstance: APIManager { struct Static { static var instance: APIManager? static var token: dispatch_once_t = 0 } dispatch_once(&Static.token) { Static.instance = APIManager() } return Static.instance! } class var hostURL: NSURL { let URL_HOST = NSBundle.mainBundle().infoDictionary!["URL_HOST"] as! String return NSURL(string: URL_HOST)! } class var currentAPIVersion: UInt { return 1 } class var baseURL: NSURL { let version = "v\(self.currentAPIVersion)" let hostURLString = "\(APIManager.hostURL.absoluteString)/\(version)" return NSURL(string: hostURLString)! } private lazy var manager:AFHTTPRequestOperationManager = { let manager = AFHTTPRequestOperationManager(baseURL: APIManager.baseURL) manager.requestSerializer = AFJSONRequestSerializer(writingOptions: NSJSONWritingOptions.PrettyPrinted) manager.responseSerializer = AFJSONResponseSerializer(readingOptions: NSJSONReadingOptions.AllowFragments) manager.responseSerializer.acceptableContentTypes = NSSet(objects: "text/plain", "text/html", "application/json") as Set<NSObject> #if DEBUG manager.securityPolicy.allowInvalidCertificates = true #endif return manager }() } //MARK: - Basic methods extension APIManager { func failureErrorRecognizer (operation: AFHTTPRequestOperation?, error: NSError) -> NSError { guard let lOperation = operation else { return APIManagerError.connectionMissing.generateError() } guard !lOperation.cancelled else { return APIManagerError.cancelled.generateError() } return error } //MARK: - Basic Methods func GET (endpoint:String, params:Dictionary<String, AnyObject>?, success:((operation: AFHTTPRequestOperation, responseObject: AnyObject?) -> Void)?, failure:((operation: AFHTTPRequestOperation?, error: NSError) -> Void)?) -> AFHTTPRequestOperation? { let operation = manager.GET(endpoint, parameters: params, success: { (operation:AFHTTPRequestOperation!, responseObject:AnyObject!) -> Void in success?(operation: operation, responseObject: responseObject) }) { (operation: AFHTTPRequestOperation?, error: NSError) -> Void in var resultError = self.failureErrorRecognizer(operation, error: error) defer { failure?(operation: operation, error: resultError) } } return operation } func POST (endpoint:String, params:Dictionary<String, AnyObject>?, success:((operation: AFHTTPRequestOperation, responseObject: AnyObject?) -> Void)?, failure:((operation: AFHTTPRequestOperation?, error: NSError) -> Void)?) -> AFHTTPRequestOperation? { let operation = manager.POST(endpoint, parameters: params, success: { (operation:AFHTTPRequestOperation!, responseObject:AnyObject!) -> Void in success?(operation: operation, responseObject: responseObject) }) { (operation: AFHTTPRequestOperation?, error: NSError) -> Void in var resultError = self.failureErrorRecognizer(operation, error: error) defer { failure?(operation: operation, error: resultError) } } return operation } }
mit
1c3e81bc3d86c5f8ca20b0b77dd1207d
33.495798
155
0.584409
5.914986
false
false
false
false
joshua-d-miller/macOSLAPS
macOSLAPS/Password Tools/ValidatePassword.swift
1
1656
/// /// ValidatePassword.swift /// macOSLAPS /// /// Created by Joshua D. Miller on 3/17/22. /// /// Rreference: https://stackoverflow.com/questions/39284607/how-to-implement-a-regex-for-password-validation-in-swift /// Last Updated March 18, 2022 import Foundation func ValidatePassword (generated_password: String) -> Bool { // Build the Regex to be used var lowercase_regex = "" var uppercase_regex = "" var number_regex = "" var symbol_regex = "" if Constants.passwordrequirements["Lowercase"] as! Int != 0 { lowercase_regex = "(?=" + String.init(repeating: ".*[a-z]", count: Constants.passwordrequirements["Lowercase"] as! Int) + ")" } if Constants.passwordrequirements["Uppercase"] as! Int != 0 { uppercase_regex = "(?=" + String.init(repeating: ".*[A-Z]", count: Constants.passwordrequirements["Uppercase"] as! Int) + ")" } if Constants.passwordrequirements["Number"] as! Int != 0 { number_regex = "(?=" + String.init(repeating: ".*[0-9]", count: Constants.passwordrequirements["Number"] as! Int) + ")" } if Constants.passwordrequirements["Symbol"] as! Int != 0 { symbol_regex = "(?=" + String.init(repeating: "[.*! \"#$%&'()*+,-./:;<=>?@\\[\\\\\\]^_`{|}~]", count: Constants.passwordrequirements["Symbol"] as! Int) + ")" } var full_regex = "^" + lowercase_regex + uppercase_regex + number_regex + symbol_regex + ".{\(Constants.password_length)}$" if full_regex.count < 8 { full_regex = ".*" } let password_check = NSPredicate(format: "SELF MATCHES %@", full_regex) return password_check.evaluate(with: generated_password) }
mit
f6ee3fff9a79d480db0d2cf380d59927
43.756757
165
0.622585
3.721348
false
false
false
false
64characters/Telephone
UseCases/CallHistoryRecordAddUseCase.swift
1
1579
// // CallHistoryRecordAddUseCase.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone 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. // // Telephone 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. // public final class CallHistoryRecordAddUseCase { private let history: CallHistory private let record: CallHistoryRecord private let domain: String public init(history: CallHistory, record: CallHistoryRecord, domain: String) { self.history = history self.record = record self.domain = domain } } extension CallHistoryRecordAddUseCase: UseCase { public func execute() { history.add(recordByRemovingHostIfNeeded(from: record)) } private func recordByRemovingHostIfNeeded(from record: CallHistoryRecord) -> CallHistoryRecord { if shouldRemoveHost(from: record) { return record.removingHost() } else { return record } } private func shouldRemoveHost(from record: CallHistoryRecord) -> Bool { return record.uri.host == domain || record.uri.user.isTelephoneNumber && record.uri.user.count > 4 } }
gpl-3.0
8c909ded53dccb77817130dd01720c24
32.553191
106
0.704502
4.584302
false
false
false
false
perlguy99/GAS3_XLActionControllerAdditions
Example/Pods/XLActionController/Source/Action.swift
1
1910
// Action.swift // XLActionController ( https://github.com/xmartlabs/XLActionController ) // // Copyright (c) 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. import Foundation import UIKit public enum ActionStyle { case Default case Cancel case Destructive } public struct Action<T> { public var enabled: Bool public var executeImmediatelyOnTouch = false public private(set) var data: T? public private(set) var style = ActionStyle.Default public private(set) var handler: (Action<T> -> Void)? public init(_ data: T?, style: ActionStyle, executeImmediatelyOnTouch: Bool = false, handler: (Action<T> -> Void)?) { enabled = true self.executeImmediatelyOnTouch = executeImmediatelyOnTouch self.data = data self.style = style self.handler = handler } }
mit
d90ae12e992e08bf0464cf6968021366
35.730769
121
0.728796
4.483568
false
false
false
false
puffinsupply/TransitioningKit
Example/Example/FirstViewController.swift
1
1279
import UIKit import TransitioningKit class FirstViewController: UIViewController { // MARK: Public override func viewDidLoad() { super.viewDidLoad() let pushAnimator = FirstViewToSecondViewPushAnimator() let interactionControllerDelegate = FirstViewInteractionControllerDelegate() let interactionController = PSPanGestureInteractionController(viewController: self, delegate: interactionControllerDelegate) navigationControllerDelegate = PSNavigationControllerDelegate( pushAnimator: pushAnimator, interactionController: interactionController ) navigationController?.delegate = navigationControllerDelegate } @IBAction func buttonWasPressed(button: UIButton) { UIView.animateWithDuration(0.1, animations: { button.transform = CGAffineTransformMakeTranslation(-32, 0) }) UIView.animateWithDuration(0.4, delay: 0.1, usingSpringWithDamping: 0.4, initialSpringVelocity: 0, options: .CurveEaseOut, animations: { button.transform = CGAffineTransformIdentity }, completion: nil ) } // MARK: Private private var navigationControllerDelegate: PSNavigationControllerDelegate? }
mit
bac116a7fb55918cc6eeb6fdd43076a8
29.452381
136
0.705238
5.976636
false
false
false
false
rozd/ToDoLite-iOS-Swift
ToDoLite/AppDelegate.swift
1
14050
// // AppDelegate.swift // TodoLightSwift // // Created by Max Rozdobudko on 9/17/16. // Copyright © 2016 Max Rozdobudko. All rights reserved. // import UIKit import FBSDKCoreKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, LoginViewControllerDelegate { //------------------------------------------------------------------ // // MARK: - Class constants // //------------------------------------------------------------------ // static let kSyncGatewayUrl = "http://us-east.testfest.couchbasemobile.com:4984/todolite" static let kSyncGatewayUrl = "http://localhost:4984/todolite-swift" static let kSyncGatewayWebSocketSupport = true static let kGuestDBName = "guest" static let kStorageType = kCBLSQLiteStorage static let kEncryptionEnabled = false static let kEncryptionKey = "seekrit" static let kLoggingEnabled = true //------------------------------------------------------------------ // // MARK: - Properties // //------------------------------------------------------------------ var window: UIWindow? var currentUserId:String? { set { UserDefaults.standard.set(newValue, forKey: "user_id") } get { return UserDefaults.standard.object(forKey: "user_id") as? String } } var database:CBLDatabase? { willSet { self.willChangeValue(forKey: "database") } didSet { self.didChangeValue(forKey: "database") } } var loginViewController:LoginViewController! // Replication var push:CBLReplication? var pull:CBLReplication? var lastSyncError:NSError? //------------------------------------------------------------------ // // MARK: - Methods // //------------------------------------------------------------------ //------------------------------------ // MARK: UIApplicationDelegate //------------------------------------ func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions); self.loginViewController = self.window?.rootViewController as! LoginViewController self.loginViewController.delegate = self self.enableLogging() return true } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { let handled = FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation) return handled; } //--------------------------------- // MARK: Logging //--------------------------------- func enableLogging() { if AppDelegate.kLoggingEnabled { CBLManager.enableLogging("Database") CBLManager.enableLogging("View") CBLManager.enableLogging("ViewVerbose") CBLManager.enableLogging("Query") CBLManager.enableLogging("Sync") CBLManager.enableLogging("SyncVerbose") CBLManager.enableLogging("ChnageTracker") } } //--------------------------------- // MARK: Database //--------------------------------- func databaseForName(name:String) -> CBLDatabase? { let dbName = "db\(name.md5().lowercased())" let option = CBLDatabaseOptions() option.create = true option.storageType = AppDelegate.kStorageType option.encryptionKey = AppDelegate.kEncryptionEnabled ? AppDelegate.kEncryptionKey : nil do { let database = try CBLManager.sharedInstance().openDatabaseNamed(dbName, with: option) return database; } catch let error { print("Cannot create database with an error : \(error.localizedDescription)") } return nil } func databaseForUser(user:String?) -> CBLDatabase? { return user != nil ? databaseForName(name: user!) : nil; } func databaseForGuest() -> CBLDatabase? { return databaseForName(name: AppDelegate.kGuestDBName) } func migrateGuestDatabaseToUser(profile:Profile) { if let guestDB = self.databaseForGuest() { if guestDB.lastSequenceNumber > 0 { var rows:CBLQueryEnumerator! do { rows = try guestDB.createAllDocumentsQuery().run() } catch { return } if let userDB = profile.database { for case let row as CBLQueryRow in rows { if let doc = row.document { let newDoc = userDB.document(withID: doc.documentID) if let userProperties = doc.userProperties { do { try newDoc?.putProperties(userProperties) } catch let error { print("Error when saving a new document during migrating guest data : \(error.localizedDescription)") continue } } if let attachments = doc.currentRevision?.attachments { if attachments.count > 0 { let newRev = newDoc?.currentRevision?.createRevision() for att in attachments { newRev?.setAttachmentNamed(att.name, withContentType: att.contentType, content: att.content) } do { try newRev?.save() } catch let error { print("Error when saving an attachment during migrating guest data : \(error.localizedDescription)") } } } } do { try List.updateAllListsInDatabase(db: profile.database!, withOwner: profile) } catch { print("Error when transfering the ownership of the list documents : \(error.localizedDescription)"); } do { try guestDB.delete() } catch { print("Error when deleting the guest database during migrating guest data : \(error.localizedDescription)") } } } } } } //--------------------------------- // MARK: Replication //--------------------------------- func startReplicationWithAuthenticator(authenticator:CBLAuthenticatorProtocol) { if (pull == nil && push == nil) { if let syncURL = NSURL(string: AppDelegate.kSyncGatewayUrl) as? URL { pull = database!.createPullReplication(syncURL) pull!.continuous = true; if !AppDelegate.kSyncGatewayWebSocketSupport { pull?.customProperties = ["websocket" : false] } push = database!.createPushReplication(syncURL) push!.continuous = true; NotificationCenter.default .addObserver(self, selector: #selector(AppDelegate.replicationProgress), name: Notification.Name.cblReplicationChange, object: pull!) NotificationCenter.default .addObserver(self, selector: #selector(AppDelegate.replicationProgress), name: Notification.Name.cblReplicationChange, object: push!) } } push?.authenticator = authenticator; pull?.authenticator = authenticator; if (pull?.running)! { pull?.stop() } pull?.start() if (push?.running)! { push?.stop() } push?.start() } func stopReplication() { pull?.stop() do { try pull?.clearAuthenticationStores() } catch let error { print(error); } NotificationCenter.default.removeObserver(self, name: NSNotification.Name.cblReplicationChange, object: pull) pull = nil push?.stop(); do { try push?.clearAuthenticationStores() } catch let error { print(error); } NotificationCenter.default.removeObserver(self, name: NSNotification.Name.cblReplicationChange, object: push) push = nil; } func replicationProgress(notification:NSNotification) { print("pull status: \(pull!.status.rawValue)") print("push status: \(push!.status.rawValue)") if (pull?.status == CBLReplicationStatus.active || push?.status == CBLReplicationStatus.active) { UIApplication.shared.isNetworkActivityIndicatorVisible = true } else { UIApplication.shared.isNetworkActivityIndicatorVisible = false } if let syncError = pull?.lastError as? NSError ?? push?.lastError as? NSError { if syncError != lastSyncError { lastSyncError = syncError if syncError.code == 404 { showMessage(message: "Authentication failed", withTitle: "Sync Error") logout() } else { showMessage(message: syncError.localizedDescription, withTitle: "Sync Error") } } } } //------------------------------------ // MARK: Login/Logout //------------------------------------ func logout() { loginViewController.logoutFacebook() } // MARK: LoginViewControllerDelegate func didLoginAsGuest() { self.database = databaseForGuest() self.currentUserId = nil } func didLoginWithFacebookUser(userId:String, name:String?, token:String) { self.currentUserId = userId if let database = databaseForUser(user: userId) { self.database = database var profile = Profile.profileInDatabase(db: database, forExistinUserId: userId) if profile == nil { if name != nil { profile = Profile.profieInDatabase(db: database, forNewUserId: userId, name!) guard profile != nil else { print("Cannot create a new user profile") return } do { try profile!.save() migrateGuestDatabaseToUser(profile: profile!) } catch { print("Cannot create a new user profile with error : \(error.localizedDescription)") } } else { print("Cannot create a new user profile as there is no name information.") } } if profile != nil { startReplicationWithAuthenticator(authenticator: CBLAuthenticator.facebookAuthenticator(withToken: token)) } else { showMessage(message: "Cannot create a new user profile", withTitle: "Error") } } } func didLogout() { currentUserId = nil stopReplication() database = nil loginViewController.dismiss(animated: true, completion: nil) } // MARK: Alerts func showMessage(message:String, withTitle title:String) { let controller = UIAlertController(title: title, message: message, preferredStyle: .alert) controller.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.window?.rootViewController?.present(controller, animated: true, completion: nil) } }
mit
55eb2cd319e9badc38f80bf2b4037a8b
31.296552
161
0.450779
6.403373
false
false
false
false
Intercambio/CloudService
CloudService/CloudServiceTests/ResourceAPIResponseTests.swift
1
1651
// // ResourceAPIResponseTests.swift // CloudServiceTests // // Created by Tobias Kraentzer on 06.02.17. // Copyright © 2017 Tobias Kräntzer. All rights reserved. // import XCTest import PureXML @testable import CloudService class ResourceAPIResponseTests: XCTestCase { func testParseResponse() { guard let document = PXDocument(named: "propfind.xml", in: Bundle(for: ResourceAPIResponseTests.self)), let baseURL = URL(string: "https://example.com/") else { XCTFail(); return } let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US") formatter.timeZone = TimeZone(identifier: "GMT") formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z" do { let response = try ResourceAPIResponse(document: document, baseURL: baseURL) XCTAssertEqual(response.resources.count, 6) XCTAssertTrue(response.resources[0].isCollection) let resource = response.resources[1] XCTAssertEqual(resource.url.absoluteString, "https://example.com/webdav/Noten/%20St.%20James%20Infirmary.pdf") XCTAssertEqual(resource.etag, "daf566feead4f993a07c2acf71dae583") XCTAssertFalse(resource.isCollection) XCTAssertEqual(resource.contentLength, 38059) XCTAssertEqual(resource.contentType, "application/pdf") XCTAssertEqual(resource.modified, formatter.date(from: "Fri, 17 Jul 2015 15:18:09 GMT")) } catch { XCTFail("\(error)") } } }
gpl-3.0
0620247fe9af380ef47d6cc094f73ce8
34.085106
122
0.624015
4.593315
false
true
false
false
sanghapark/Vigorous
Example/VigorousExample/CornerRadiusChangeable.swift
1
959
// // CornerRadiusChangeable.swift // FeedableTest // // Created by ParkSangHa on 2017. 3. 20.. // Copyright © 2017년 sanghapark1021. All rights reserved. // import Foundation import UIKit import Vigorous protocol CornerRadiusChangeable { } extension CornerRadiusChangeable where Self: UIView { func cornerRadius(value: CGFloat) -> Animatable { return Animatable { animation, completion in animation { CATransaction.begin() let animation = CABasicAnimation(keyPath:"cornerRadius") animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.fromValue = self.layer.cornerRadius animation.toValue = value animation.duration = 2 CATransaction.setCompletionBlock { completion(true) } self.layer.add(animation, forKey: "cornerRadius") self.layer.cornerRadius = value CATransaction.commit() } } } }
mit
cb7bb0cffb654a2237ec4cc638e9bb6b
27.117647
92
0.691423
4.80402
false
false
false
false
codefellows/sea-c40-iOS
Sample Code/SwiftClassRoster/SwiftClassRoster/ViewController.swift
1
4066
// // ViewController.swift // SwiftClassRoster // // Created by Bradley Johnson on 6/3/15. // Copyright (c) 2015 BPJ. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var people = [Person]() var myInfo = [String : Person]() override func viewDidLoad() { super.viewDidLoad() if let peopleFromArchive = self.loadFromArchive() { self.people = peopleFromArchive } else { self.loadPeopleFromPlist() self.saveToArchive() } self.tableView.dataSource = self } private func loadPeopleFromPlist() { if let peoplePath = NSBundle.mainBundle().pathForResource("People", ofType: "plist"), peopleObjects = NSArray(contentsOfFile: peoplePath) as? [[String : String]] { for object in peopleObjects { if let firstName = object["FirstName"], lastName = object["LastName"] { let person = Person(first: firstName, last: lastName) self.people.append(person) } } } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.saveToArchive() self.tableView.reloadData() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.people.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! PersonCell cell.backgroundColor = UIColor.whiteColor() cell.personImageView.layer.cornerRadius = 15 cell.personImageView.layer.masksToBounds = true; cell.personImageView.layer.borderWidth = 10 cell.personImageView.layer.borderColor = UIColor.redColor().CGColor let personToDisplay = self.people[indexPath.row] //with optional binding if let image = personToDisplay.image { cell.personImageView.image = image } cell.firstNameLabel.text = personToDisplay.firstName cell.lastNameLabel.text = personToDisplay.lastName let userDefaults = NSUserDefaults.standardUserDefaults() if let lastSelectedName = userDefaults.objectForKey("LastSelected") as? String where lastSelectedName == personToDisplay.firstName { cell.backgroundColor = UIColor.lightGrayColor() } return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowDetailViewController" { if let detailViewController = segue.destinationViewController as? DetailViewController { let myIndexPath = self.tableView.indexPathForSelectedRow() if let indexPath = self.tableView.indexPathForSelectedRow() { let selectedRow = indexPath.row let selectedPerson = self.people[selectedRow] println(selectedPerson.firstName) detailViewController.selectedPerson = selectedPerson let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setObject(selectedPerson.firstName, forKey: "LastSelected") userDefaults.synchronize() // detailViewController.setupTextFields() } } } } func saveToArchive() { if let archivePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as? String { println(archivePath) NSKeyedArchiver.archiveRootObject(self.people, toFile: archivePath + "/archive") } } func loadFromArchive() -> [Person]? { if let archivePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as? String { if let peopleFromArchive = NSKeyedUnarchiver.unarchiveObjectWithFile(archivePath + "/archive") as? [Person] { return peopleFromArchive } } return nil } }
mit
c813c58fed65ac8709180d1dea68ac93
29.571429
164
0.69454
5.273671
false
false
false
false
dangquochoi2007/cleancodeswift
CleanStore/CleanStore/App/Common/SJSegmentedScrollView/Classes/SJSegmentedViewController.swift
1
16127
// // SJSegmentedViewController.swift // Pods // // Created by Subins Jose on 20/06/16. // Copyright © 2016 Subins Jose. 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 UIKit @objc public protocol SJSegmentedViewControllerDelegate { @objc optional func didSelectSegmentAtIndex(_ index:Int) /** Method to identify the current controller and segment of contentview - parameter controller: Current controller - parameter segment: selected segment - parameter index: index of selected segment. */ @objc optional func didMoveToPage(_ controller: UIViewController, segment: SJSegmentTab?, index: Int) } /** * Public protocol of SJSegmentedViewController for content changes and makes the scroll effect. */ @objc public protocol SJSegmentedViewControllerViewSource { /** By default, SJSegmentedScrollView will observe the default view of viewcontroller for content changes and makes the scroll effect. If you want to change the default view, implement SJSegmentedViewControllerViewSource and pass your custom view. - returns: observe view */ @objc optional func viewForSegmentControllerToObserveContentOffsetChange() -> UIView } /** * Public class for customizing and setting our segmented scroll view */ @objc open class SJSegmentedViewController: UIViewController { /** * The headerview height for 'Header'. * * By default the height will be 0.0 * * segmentedViewController.headerViewHeight = 200.0 */ open var headerViewHeight: CGFloat = 0.0 { didSet { segmentedScrollView.headerViewHeight = headerViewHeight } } /** * Set height for segment view. * * By default the height is 40.0 * * segmentedViewController.segmentViewHeight = 60.0 */ open var segmentViewHeight: CGFloat = 40.0 { didSet { segmentedScrollView.segmentViewHeight = segmentViewHeight } } /** * Set headerview offset height. * * By default the height is 0.0 * * segmentedViewController. headerViewOffsetHeight = 10.0 */ open var headerViewOffsetHeight: CGFloat = 0.0 { didSet { segmentedScrollView.headerViewOffsetHeight = headerViewOffsetHeight } } /** * Set color for selected segment. * * By default the color is light gray. * * segmentedViewController.selectedSegmentViewColor = UIColor.redColor() */ open var selectedSegmentViewColor = UIColor.lightGray { didSet { segmentedScrollView.selectedSegmentViewColor = selectedSegmentViewColor } } /** * Set height for selected segment view. * * By default the height is 5.0 * * segmentedViewController.selectedSegmentViewHeight = 5.0 */ open var selectedSegmentViewHeight: CGFloat = 5.0 { didSet { segmentedScrollView.selectedSegmentViewHeight = selectedSegmentViewHeight } } /** * Set color for segment title. * * By default the color is black. * * segmentedViewController.segmentTitleColor = UIColor.redColor() */ open var segmentTitleColor = UIColor.black { didSet { segmentedScrollView.segmentTitleColor = segmentTitleColor } } /** * Set color for segment background. * * By default the color is white. * * segmentedViewController.segmentBackgroundColor = UIColor.whiteColor() */ open var segmentBackgroundColor = UIColor.white { didSet { segmentedScrollView.segmentBackgroundColor = segmentBackgroundColor } } /** * Set shadow for segment. * * By default the color is light gray. * * segmentedViewController.segmentShadow = SJShadow.light() */ open var segmentShadow = SJShadow() { didSet { segmentedScrollView.segmentShadow = segmentShadow } } /** * Set font for segment title. * * segmentedViewController.segmentTitleFont = UIFont.systemFontOfSize(14.0) */ open var segmentTitleFont = UIFont.systemFont(ofSize: 14.0) { didSet { segmentedScrollView.segmentTitleFont = segmentTitleFont } } /** * Set bounce for segment. * * By default it is set to false. * * segmentedViewController.segmentBounces = true */ open var segmentBounces = false { didSet { segmentedScrollView.segmentBounces = segmentBounces } } /** * Set ViewController for header view. */ open var headerViewController: UIViewController? { didSet { setDefaultValuesToSegmentedScrollView() } } /** * Array of ViewControllers for segments. */ open var segmentControllers = [UIViewController]() { didSet { setDefaultValuesToSegmentedScrollView() } } /** * Array of segments. For single view controller segments will be empty. */ open var segments: [SJSegmentTab] { get { if let segmentView = segmentedScrollView.segmentView { return segmentView.segments } return [SJSegmentTab]() } } /** * Set color of SegmentedScrollView. * * By default it is set to white. * * segmentedScrollView.backgroundColor = UIColor.white */ open var segmentedScrollViewColor = UIColor.white { didSet { segmentedScrollView.backgroundColor = segmentedScrollViewColor } } /** * Set vertical scroll indicator. * * By default true. * * segmentedScrollView.showsVerticalScrollIndicator = false */ open var showsVerticalScrollIndicator = true { didSet { segmentedScrollView.sjShowsVerticalScrollIndicator = showsVerticalScrollIndicator } } /** * Set horizontal scroll indicator. * * By default true. * * segmentedScrollView.showsHorizontalScrollIndicator = false */ open var showsHorizontalScrollIndicator = true { didSet { segmentedScrollView.sjShowsHorizontalScrollIndicator = showsHorizontalScrollIndicator } } open weak var delegate:SJSegmentedViewControllerDelegate? var viewObservers = [UIView]() var segmentedScrollView = SJSegmentedScrollView(frame: CGRect.zero) var segmentScrollViewTopConstraint: NSLayoutConstraint? /** Custom initializer for SJSegmentedViewController. - parameter headerViewController: A UIViewController - parameter segmentControllers: Array of UIViewControllers for segments. */ convenience public init(headerViewController: UIViewController?, segmentControllers: [UIViewController]) { self.init(nibName: nil, bundle: nil) self.headerViewController = headerViewController self.segmentControllers = segmentControllers setDefaultValuesToSegmentedScrollView() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { for view in viewObservers { view.removeObserver(self, forKeyPath: "contentOffset", context: nil) } } override open func loadView() { super.loadView() addSegmentedScrollView() } override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white automaticallyAdjustsScrollViewInsets = false loadControllers() } /** * Update view as per the current layout */ override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let topSpacing = SJUtil.getTopSpacing(self) segmentedScrollView.topSpacing = topSpacing segmentedScrollView.bottomSpacing = SJUtil.getBottomSpacing(self) segmentScrollViewTopConstraint?.constant = topSpacing segmentedScrollView.updateSubviewsFrame(view.bounds) } /** * To select segment programmatically * - parameter index Int Segment index * - parameter animated Bool Move with an animation or not. */ open func setSelectedSegmentAt(_ index: Int, animated: Bool) { if index >= 0 && index < segmentControllers.count { segmentedScrollView.segmentView?.didSelectSegmentAtIndex!(segments[index], index, animated) NotificationCenter.default.post(name: Notification.Name(rawValue: "DidChangeSegmentIndex"), object: index) } } /** * Set the default values for the segmented scroll view. */ func setDefaultValuesToSegmentedScrollView() { segmentedScrollView.selectedSegmentViewColor = selectedSegmentViewColor segmentedScrollView.selectedSegmentViewHeight = selectedSegmentViewHeight segmentedScrollView.segmentTitleColor = segmentTitleColor segmentedScrollView.segmentBackgroundColor = segmentBackgroundColor segmentedScrollView.segmentShadow = segmentShadow segmentedScrollView.segmentTitleFont = segmentTitleFont segmentedScrollView.segmentBounces = segmentBounces segmentedScrollView.headerViewHeight = headerViewHeight segmentedScrollView.headerViewOffsetHeight = headerViewOffsetHeight segmentedScrollView.segmentViewHeight = segmentViewHeight segmentedScrollView.backgroundColor = segmentedScrollViewColor } /** * Private method for adding the segmented scroll view. */ func addSegmentedScrollView() { let topSpacing = SJUtil.getTopSpacing(self) segmentedScrollView.topSpacing = topSpacing let bottomSpacing = SJUtil.getBottomSpacing(self) segmentedScrollView.bottomSpacing = bottomSpacing view.addSubview(segmentedScrollView) let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[scrollView]-0-|", options: [], metrics: nil, views: ["scrollView": segmentedScrollView]) view.addConstraints(horizontalConstraints) let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[scrollView]-bp-|", options: [], metrics: ["tp": topSpacing, "bp": bottomSpacing], views: ["scrollView": segmentedScrollView]) view.addConstraints(verticalConstraints) segmentScrollViewTopConstraint = NSLayoutConstraint(item: segmentedScrollView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: topSpacing) view.addConstraint(segmentScrollViewTopConstraint!) segmentedScrollView.setContentView() // selected segment at index segmentedScrollView.didSelectSegmentAtIndex = {(segment, index, animated) in let selectedController = self.segmentControllers[index] self.delegate?.didMoveToPage?(selectedController, segment: segment!, index: index) } } /** Method for adding the HeaderViewController into the container - parameter headerViewController: Header ViewController. */ func addHeaderViewController(_ headerViewController: UIViewController) { addChildViewController(headerViewController) segmentedScrollView.addHeaderView(headerViewController.view) headerViewController.didMove(toParentViewController: self) } /** Method for adding the array of content ViewControllers into the container - parameter contentControllers: array of ViewControllers */ func addContentControllers(_ contentControllers: [UIViewController]) { viewObservers.removeAll() segmentedScrollView.addSegmentView(contentControllers, frame: view.bounds) var index = 0 for controller in contentControllers { addChildViewController(controller) segmentedScrollView.addContentView(controller.view, frame: view.bounds) controller.didMove(toParentViewController: self) let delegate = controller as? SJSegmentedViewControllerViewSource var observeView = controller.view if let collectionController = controller as? UICollectionViewController { observeView = collectionController.collectionView } if let view = delegate?.viewForSegmentControllerToObserveContentOffsetChange?() { observeView = view } viewObservers.append(observeView!) segmentedScrollView.addObserverFor(observeView!) index += 1 } segmentedScrollView.segmentView?.contentView = segmentedScrollView.contentView } /** * Method for loading content ViewControllers and header ViewController */ func loadControllers() { if headerViewController == nil { headerViewController = UIViewController() headerViewHeight = 0.0 } addHeaderViewController(headerViewController!) addContentControllers(segmentControllers) //Delegate call for setting the first view of segments. var segment: SJSegmentTab? if segments.count > 0 { segment = segments[0] } delegate?.didMoveToPage?(segmentControllers[0], segment: segment, index: 0) } }
mit
7efa5cc96208df666246cb7a16015f63
33.165254
126
0.613481
5.759286
false
false
false
false
VBVMI/VerseByVerse-iOS
VBVMI-tvOS/StudyViewController.swift
1
13624
// // StudyViewController.swift // VBVMI // // Created by Thomas Carey on 26/11/16. // Copyright © 2016 Tom Carey. All rights reserved. // import UIKit import CoreData import AlamofireImage import AVFoundation import AVKit import MediaPlayer enum LessonSection : Int { case completed = 0 case incomplete = 1 } class StudyViewController: UIViewController { fileprivate let lessonCellReuseIdentifier = "LessonCell" fileprivate let lessonDescriptionCellReuseIdentifier = "LessonDescriptionCell" fileprivate let filterHeaderReuseIdentifier = "FilterHeader" @IBOutlet weak var descriptionTextView: UITextView! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var imageView: UIImageView! private var focusGuide: UIFocusGuide! var audioPlayer: AVPlayer? fileprivate var fetchedResultsController: NSFetchedResultsController<Lesson>! var study: Study! { didSet { self.navigationItem.title = study.title if let identifier = study?.identifier { APIDataManager.lessons(identifier) } reloadImageView() } } func reloadImageView() { if let thumbnailSource = study.thumbnailSource, let imageView = imageView { if let url = URL(string: thumbnailSource) { let width = 460 let imageFilter = ScaledToSizeWithRoundedCornersFilter(size: CGSize(width: width, height: width), radius: 10, divideRadiusByImageScale: false) imageView.af_setImage(withURL: url, placeholderImage: nil, filter: imageFilter, imageTransition: UIImageView.ImageTransition.crossDissolve(0.3), runImageTransitionIfCached: false, completion: nil) // cell.coverImageView.af_setImage(withURL: url) } } } let sections: [LessonSection] = [.incomplete, .completed] fileprivate func configureFetchController() { let fetchRequest = NSFetchRequest<Lesson>(entityName: Lesson.entityName()) let context = ContextCoordinator.sharedInstance.managedObjectContext! fetchRequest.entity = Lesson.entity(managedObjectContext: context) let sectionSort = NSSortDescriptor(key: LessonAttributes.completed.rawValue, ascending: true, selector: #selector(NSNumber.compare(_:))) let indexSort = NSSortDescriptor(key: LessonAttributes.lessonIndex.rawValue, ascending: true, selector: #selector(NSNumber.compare(_:))) fetchRequest.sortDescriptors = [sectionSort, indexSort] fetchRequest.predicate = NSPredicate(format: "%K == %@", LessonAttributes.studyIdentifier.rawValue, study.identifier) fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: "completed", cacheName: nil) fetchedResultsController.delegate = self try! fetchedResultsController.performFetch() } override func viewDidLoad() { super.viewDidLoad() configureFetchController() collectionView.contentInset = UIEdgeInsets(top: 0, left: 60, bottom: 60, right: 30) reloadImageView() // Do any additional setup after loading the view. descriptionTextView.text = study.descriptionText descriptionTextView.textContainerInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) descriptionTextView.layer.cornerRadius = 10 descriptionTextView.isSelectable = true; descriptionTextView.isUserInteractionEnabled = true; descriptionTextView.panGestureRecognizer.allowedTouchTypes = [NSNumber(value: UITouchType.indirect.rawValue)]; focusGuide = UIFocusGuide() view.addLayoutGuide(focusGuide) focusGuide.rightAnchor.constraint(equalTo: imageView.leftAnchor).isActive = true focusGuide.topAnchor.constraint(equalTo: imageView.topAnchor).isActive = true focusGuide.bottomAnchor.constraint(equalTo: imageView.bottomAnchor).isActive = true focusGuide.widthAnchor.constraint(equalToConstant: 1).isActive = true focusGuide.preferredFocusEnvironments = [descriptionTextView] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } fileprivate func makeMetadataItem(_ identifier: String, value: Any) -> AVMetadataItem { let item = AVMutableMetadataItem() item.identifier = AVMetadataIdentifier(rawValue: identifier) item.value = value as? NSCopying & NSObjectProtocol item.extendedLanguageTag = "und" return item.copy() as! AVMetadataItem } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) UIApplication.shared.isIdleTimerDisabled = false } override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) { super.didUpdateFocus(in: context, with: coordinator) guard let nextFocusedView = context.nextFocusedView else { return } switch nextFocusedView { case descriptionTextView: coordinator.addCoordinatedAnimations({ self.descriptionTextView.backgroundColor = self.traitCollection.userInterfaceStyle == .light ? StyleKit.darkGrey.withAlphaComponent(0.1) : StyleKit.white.withAlphaComponent(0.1) }, completion: nil) default: coordinator.addCoordinatedAnimations({ self.descriptionTextView.backgroundColor = .clear }, completion: nil) } } } extension StudyViewController : UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let lesson = fetchedResultsController.object(at: indexPath) if let urlString = lesson.videoSourceURL, urlString.contains("vimeo.com"), let url = URL(string: urlString) { let player = AVPlayer(url: url) let controller = AVPlayerViewController() controller.delegate = self controller.player = player let titleItem = makeMetadataItem(AVMetadataIdentifier.commonIdentifierTitle.rawValue, value: lesson.title) var items = [titleItem] if let text = lesson.descriptionText { items.append(makeMetadataItem(AVMetadataIdentifier.commonIdentifierDescription.rawValue, value: text)) } if let image = imageView.image { items.append(makeMetadataItem(AVMetadataIdentifier.commonIdentifierArtwork.rawValue, value: image)) } player.currentItem?.externalMetadata = items UIApplication.shared.isIdleTimerDisabled = true present(controller, animated: true, completion: { player.play() }) } else if let urlString = ResourceManager.LessonType.audio.urlString(lesson) { if let url = URL(string: urlString) { let audioPlayer = AVPlayer(url: url) self.audioPlayer = audioPlayer let controller = AVPlayerViewController() controller.delegate = self controller.player = audioPlayer let titleItem = makeMetadataItem(AVMetadataIdentifier.commonIdentifierTitle.rawValue, value: lesson.title) var items = [titleItem] if let text = lesson.descriptionText { items.append(makeMetadataItem(AVMetadataIdentifier.commonIdentifierDescription.rawValue, value: text)) } if let image = imageView.image { items.append(makeMetadataItem(AVMetadataIdentifier.commonIdentifierArtwork.rawValue, value: image)) } audioPlayer.currentItem?.externalMetadata = items let contentView = UIImageView() contentView.image = imageView.image contentView.contentMode = .scaleAspectFill let _ = controller.view controller.contentOverlayView?.addSubview(contentView) let contentImageView = UIImageView() contentImageView.image = imageView.image contentView.addSubview(contentImageView) contentView.alpha = 0 let background = UIVisualEffectView(effect: UIBlurEffect(style: .extraDark)) contentView.addSubview(background) background.snp.makeConstraints({ (make) in make.edges.equalTo(contentView) }) background.contentView.addSubview(contentImageView) contentImageView.snp.makeConstraints({ (make) in make.centerX.equalTo(background) make.top.equalTo(240) make.width.height.equalTo(440) }) contentView.snp.makeConstraints({ (make) in make.edges.equalTo(0) }) let label = UILabel() label.font = UIFont.preferredFont(forTextStyle: .title3) label.text = lesson.title background.contentView.addSubview(label) label.textAlignment = .center label.snp.makeConstraints({ (make) in make.top.equalTo(contentImageView.snp.bottom).offset(40) make.centerX.equalTo(contentImageView) make.width.lessThanOrEqualTo(900) }) label.numberOfLines = 0 label.textColor = .white let descriptionLabel = UILabel() descriptionLabel.font = UIFont.preferredFont(forTextStyle: .body) descriptionLabel.text = lesson.descriptionText background.contentView.addSubview(descriptionLabel) descriptionLabel.textAlignment = .center descriptionLabel.snp.makeConstraints({ (make) in make.top.equalTo(label.snp.bottom).offset(20) make.centerX.equalTo(contentImageView) make.width.lessThanOrEqualTo(900) }) descriptionLabel.numberOfLines = 0 descriptionLabel.textColor = .white controller.contentOverlayView?.addSubview(contentView) UIApplication.shared.isIdleTimerDisabled = true present(controller, animated: true, completion: { audioPlayer.play() UIView.animate(withDuration: 0.4, animations: { contentView.alpha = 1 }) }) } } } } extension StudyViewController : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return fetchedResultsController?.sections?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let fetchedSection = fetchedResultsController.sections?[section] else { return 0 } return fetchedSection.numberOfObjects } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let lesson = fetchedResultsController.object(at: indexPath) let cell : LessonCollectionViewCell if let lessonNumber = lesson.lessonNumber, lessonNumber.count > 0 { cell = collectionView.dequeueReusableCell(withReuseIdentifier: lessonCellReuseIdentifier, for: indexPath) as! LessonCollectionViewCell } else { cell = collectionView.dequeueReusableCell(withReuseIdentifier: lessonDescriptionCellReuseIdentifier, for: indexPath) as! LessonCollectionViewCell } cell.numberLabel?.text = lesson.lessonNumber cell.descriptionLabel?.text = lesson.descriptionText return cell } } extension StudyViewController : NSFetchedResultsControllerDelegate { func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { collectionView.reloadData() } func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { } } extension StudyViewController : AVPlayerViewControllerDelegate { func playerViewController(_ playerViewController: AVPlayerViewController, shouldPresent proposal: AVContentProposal) -> Bool { return true } }
mit
1e36695438185ff0687ae101d492423c
41.571875
212
0.637965
6.15868
false
false
false
false
Joachimdj/JobResume
Apps/Forum17/2017/Forum/Views/MapView.swift
1
2595
// // MapView.swift // Forum // // Created by Joachim Dittman on 16/08/2017. // Copyright © 2017 Joachim Dittman. All rights reserved. // import UIKit class MapView: UIViewController { var imageView = UIImageView() var scrollView = UIScrollView() override func viewDidLoad() { super.viewDidLoad() MapController().loadMap { (result) in self.imageView.kf.setImage(with: URL(string:result)!, placeholder: nil, options: nil, progressBlock: { (start, end) in }) { (image, error, CacheType, URL) in // 1 self.imageView = UIImageView(image: image) self.imageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size:(image?.size)!) self.scrollView.addSubview(self.imageView) // 2 self.scrollView.contentSize = (image?.size)! // 4 let scrollViewFrame = self.scrollView.frame let scaleWidth = scrollViewFrame.size.width / self.scrollView.contentSize.width let scaleHeight = scrollViewFrame.size.height / self.scrollView.contentSize.height let minScale = min(scaleWidth, scaleHeight); self.scrollView.minimumZoomScale = minScale; // 5 self.scrollView.maximumZoomScale = 0.5 self.scrollView.zoomScale = minScale; self.scrollView.backgroundColor = .white // 6 self.scrollView.frame = CGRect(x:0,y:20,width:UIScreen.main.bounds.width,height:UIScreen.main.bounds.height - 65) self.centerScrollViewContents() self.view.addSubview(self.scrollView) } } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func centerScrollViewContents() { let boundsSize = scrollView.bounds.size var contentsFrame = imageView.frame if contentsFrame.size.width < boundsSize.width { contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0 } else { contentsFrame.origin.x = 0.0 } if contentsFrame.size.height < boundsSize.height { contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0 } else { contentsFrame.origin.y = 0.0 } imageView.frame = contentsFrame } }
mit
d90287a8b29415aea66759025965b6ac
32.688312
126
0.589823
4.857678
false
false
false
false
yulingtianxia/Spiral
Spiral/MagicRoad.swift
1
1648
// // MagicRoad.swift // Spiral // // Created by 杨萧玉 on 15/10/7. // Copyright © 2015年 杨萧玉. All rights reserved. // import SpriteKit import GameplayKit class MagicRoad: SKNode { init(graph: GKGridGraph<GKGridGraphNode>, position: vector_int2){ let roadWidth: CGFloat = 2 super.init() let left = graph.node(atGridPosition: vector_int2(position.x - 1, position.y)) let right = graph.node(atGridPosition: vector_int2(position.x + 1, position.y)) let up = graph.node(atGridPosition: vector_int2(position.x, position.y + 1)) let down = graph.node(atGridPosition: vector_int2(position.x, position.y - 1)) if left != nil && right != nil && up == nil && down == nil { // 一 if let magic = SKEmitterNode(fileNamed: "magic") { magic.particlePositionRange = CGVector(dx: mazeCellWidth, dy: roadWidth) addChild(magic) } } else if up != nil && down != nil && left == nil && right == nil { // | if let magic = SKEmitterNode(fileNamed: "magic") { magic.particlePositionRange = CGVector(dx: roadWidth, dy: mazeCellWidth) addChild(magic) } } else { //丄丅卜十... if let magic = SKEmitterNode(fileNamed: "magic") { magic.particlePositionRange = CGVector(dx: roadWidth, dy: roadWidth) addChild(magic) } } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
5c13dcd5e53c04599e9a503fb95f0e4d
33.531915
88
0.561306
4.047382
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Services/Models/PXRemedy.swift
1
2733
import Foundation enum CardSize: String, Codable { case mini = "mini" case xSmall = "xsmall" case small = "small" case medium = "medium" case large = "large" } struct PXRemedy: Codable { let cvv: PXInvalidCVV? let highRisk: PXHighRisk? let callForAuth: PXCallForAuth? let suggestedPaymentMethod: PXSuggestedPaymentMethod? let trackingData: [String: String]? let displayInfo: PXRemedyDisplayInfo? } // PXRemedy Helpers extension PXRemedy { init() { self.init(cvv: nil, highRisk: nil, callForAuth: nil, suggestedPaymentMethod: nil, trackingData: nil, displayInfo: nil) } var isEmpty: Bool { return cvv == nil && highRisk == nil && callForAuth == nil && suggestedPaymentMethod == nil } var shouldShowAnimatedButton: Bool { // These remedy types have its own animated button return cvv != nil || suggestedPaymentMethod != nil } var title: String? { // Get title for remedy if let title = suggestedPaymentMethod?.title { return title } else if let title = cvv?.title { return title } else if let title = highRisk?.title { return title } return nil } } struct PXInvalidCVV: Codable { let title: String? let message: String? let fieldSetting: PXFieldSetting? } struct PXHighRisk: Codable { let title: String? let message: String? let deepLink: String? let actionLoud: PXButtonAction? } struct PXCallForAuth: Codable { let title: String? let message: String? } struct PXFieldSetting: Codable { let name: String? let length: Int let title: String? let hintMessage: String? } struct PXButtonAction: Codable { let label: String? } struct PXSuggestedPaymentMethod: Codable { let title: String? let message: String? let actionLoud: PXButtonAction? let bottomMessage: PXRemedyBottomMessage? let alternativePaymentMethod: PXRemedyPaymentMethod? let modal: Modal? } struct PXRemedyPaymentMethod: Codable { let bin: String? let customOptionId: String? let paymentMethodId: String? let paymentTypeId: String? let escStatus: String let issuerName: String? let lastFourDigit: String? let securityCodeLocation: String? let securityCodeLength: Int? let installmentsList: [PXPaymentMethodInstallment]? let installment: PXPaymentMethodInstallment? let cardSize: CardSize? } struct PXPaymentMethodInstallment: Codable { let installments: Int let totalAmount: Double } struct PXRemedyBottomMessage: Codable { let message: String let backgroundColor: String let textColor: String let weight: String }
mit
c7278baff7af7fb34cb032ca0cb90414
23.621622
126
0.677644
4.147193
false
false
false
false
johnno1962c/swift-corelibs-foundation
Tools/plutil/main.swift
10
11806
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if os(OSX) || os(iOS) import Darwin import SwiftFoundation #elseif os(Linux) import Foundation import Glibc #endif func help() -> Int32 { print("plutil: [command_option] [other_options] file...\n" + "The file '-' means stdin\n" + "Command options are (-lint is the default):\n" + " -help show this message and exit\n" + " -lint check the property list files for syntax errors\n" + " -convert fmt rewrite property list files in format\n" + " fmt is one of: xml1 binary1 json\n" + " -p print property list in a human-readable fashion\n" + " (not for machine parsing! this 'format' is not stable)\n" + "There are some additional optional arguments that apply to -convert\n" + " -s be silent on success\n" + " -o path specify alternate file path name for result;\n" + " the -o option is used with -convert, and is only\n" + " useful with one file argument (last file overwrites);\n" + " the path '-' means stdout\n" + " -e extension specify alternate extension for converted files\n" + " -r if writing JSON, output in human-readable form\n" + " -- specifies that all further arguments are file names\n") return EXIT_SUCCESS } enum ExecutionMode { case help case lint case convert case print } enum ConversionFormat { case xml1 case binary1 case json } struct Options { var mode: ExecutionMode = .lint var silent: Bool = false var output: String? var fileExtension: String? var humanReadable: Bool? var conversionFormat: ConversionFormat? var inputs = [String]() } enum OptionParseError : Swift.Error { case unrecognizedArgument(String) case missingArgument(String) case invalidFormat(String) } func parseArguments(_ args: [String]) throws -> Options { var opts = Options() var iterator = args.makeIterator() while let arg = iterator.next() { switch arg { case "--": while let path = iterator.next() { opts.inputs.append(path) } case "-s": opts.silent = true case "-o": if let path = iterator.next() { opts.output = path } else { throw OptionParseError.missingArgument("-o requires a path argument") } case "-convert": opts.mode = .convert if let format = iterator.next() { switch format { case "xml1": opts.conversionFormat = .xml1 case "binary1": opts.conversionFormat = .binary1 case "json": opts.conversionFormat = .json default: throw OptionParseError.invalidFormat(format) } } else { throw OptionParseError.missingArgument("-convert requires a format argument of xml1 binary1 json") } case "-e": if let ext = iterator.next() { opts.fileExtension = ext } else { throw OptionParseError.missingArgument("-e requires an extension argument") } case "-help": opts.mode = .help case "-lint": opts.mode = .lint case "-p": opts.mode = .print default: if arg.hasPrefix("-") && arg.utf8.count > 1 { throw OptionParseError.unrecognizedArgument(arg) } } } return opts } func lint(_ options: Options) -> Int32 { if options.output != nil { print("-o is not used with -lint") let _ = help() return EXIT_FAILURE } if options.fileExtension != nil { print("-e is not used with -lint") let _ = help() return EXIT_FAILURE } if options.inputs.count < 1 { print("No files specified.") let _ = help() return EXIT_FAILURE } let silent = options.silent var doError = false for file in options.inputs { let data : Data? if file == "-" { // stdin data = FileHandle.standardInput.readDataToEndOfFile() } else { data = try? Data(contentsOf: URL(fileURLWithPath: file)) } if let d = data { do { let _ = try PropertyListSerialization.propertyList(from: d, options: [], format: nil) if !silent { print("\(file): OK") } } catch { print("\(file): \(error)") } } else { print("\(file) does not exists or is not readable or is not a regular file") doError = true continue } } if doError { return EXIT_FAILURE } else { return EXIT_SUCCESS } } func convert(_ options: Options) -> Int32 { print("Unimplemented") return EXIT_FAILURE } enum DisplayType { case primary case key case value } extension Dictionary { func display(_ indent: Int = 0, type: DisplayType = .primary) { let indentation = String(repeating: " ", count: indent * 2) switch type { case .primary, .key: print("\(indentation)[\n", terminator: "") case .value: print("[\n", terminator: "") } forEach() { if let key = $0.0 as? String { key.display(indent + 1, type: .key) } else { fatalError("plists should have strings as keys but got a \(type(of: $0.0))") } print(" => ", terminator: "") displayPlist($0.1, indent: indent + 1, type: .value) } print("\(indentation)]\n", terminator: "") } } extension Array { func display(_ indent: Int = 0, type: DisplayType = .primary) { let indentation = String(repeating: " ", count: indent * 2) switch type { case .primary, .key: print("\(indentation)[\n", terminator: "") case .value: print("[\n", terminator: "") } for idx in 0..<count { print("\(indentation) \(idx) => ", terminator: "") displayPlist(self[idx], indent: indent + 1, type: .value) } print("\(indentation)]\n", terminator: "") } } extension String { func display(_ indent: Int = 0, type: DisplayType = .primary) { let indentation = String(repeating: " ", count: indent * 2) switch type { case .primary: print("\(indentation)\"\(self)\"\n", terminator: "") case .key: print("\(indentation)\"\(self)\"", terminator: "") case .value: print("\"\(self)\"\n", terminator: "") } } } extension Bool { func display(_ indent: Int = 0, type: DisplayType = .primary) { let indentation = String(repeating: " ", count: indent * 2) switch type { case .primary: print("\(indentation)\"\(self ? "1" : "0")\"\n", terminator: "") case .key: print("\(indentation)\"\(self ? "1" : "0")\"", terminator: "") case .value: print("\"\(self ? "1" : "0")\"\n", terminator: "") } } } extension NSNumber { func display(_ indent: Int = 0, type: DisplayType = .primary) { let indentation = String(repeating: " ", count: indent * 2) switch type { case .primary: print("\(indentation)\"\(self)\"\n", terminator: "") case .key: print("\(indentation)\"\(self)\"", terminator: "") case .value: print("\"\(self)\"\n", terminator: "") } } } extension NSData { func display(_ indent: Int = 0, type: DisplayType = .primary) { let indentation = String(repeating: " ", count: indent * 2) switch type { case .primary: print("\(indentation)\"\(self)\"\n", terminator: "") case .key: print("\(indentation)\"\(self)\"", terminator: "") case .value: print("\"\(self)\"\n", terminator: "") } } } func displayPlist(_ plist: Any, indent: Int = 0, type: DisplayType = .primary) { switch plist { case let val as [String : Any]: val.display(indent, type: type) case let val as [Any]: val.display(indent, type: type) case let val as String: val.display(indent, type: type) case let val as Bool: val.display(indent, type: type) case let val as NSNumber: val.display(indent, type: type) case let val as NSData: val.display(indent, type: type) default: fatalError("unhandled type \(type(of: plist))") } } func display(_ options: Options) -> Int32 { if options.inputs.count < 1 { print("No files specified.") let _ = help() return EXIT_FAILURE } var doError = false for file in options.inputs { let data : Data? if file == "-" { // stdin data = FileHandle.standardInput.readDataToEndOfFile() } else { data = try? Data(contentsOf: URL(fileURLWithPath: file)) } if let d = data { do { let plist = try PropertyListSerialization.propertyList(from: d, options: [], format: nil) displayPlist(plist) } catch { print("\(file): \(error)") } } else { print("\(file) does not exists or is not readable or is not a regular file") doError = true continue } } if doError { return EXIT_FAILURE } else { return EXIT_SUCCESS } } func main() -> Int32 { var args = ProcessInfo.processInfo.arguments if args.count < 2 { print("No files specified.") return EXIT_FAILURE } // Throw away process path args.removeFirst() do { let opts = try parseArguments(args) switch opts.mode { case .lint: return lint(opts) case .convert: return convert(opts) case .print: return display(opts) case .help: return help() } } catch let err { switch err as! OptionParseError { case .unrecognizedArgument(let arg): print("unrecognized option: \(arg)") let _ = help() case .invalidFormat(let format): print("unrecognized format \(format)\nformat should be one of: xml1 binary1 json") case .missingArgument(let errorStr): print(errorStr) } return EXIT_FAILURE } } exit(main())
apache-2.0
3119830e4b0cda13a211a1b2efea687d
29.664935
118
0.502033
4.599143
false
false
false
false
Ferrari-lee/firefox-ios
ReadingList/ReadingListRecordResponse.swift
57
932
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation class ReadingListRecordResponse: ReadingListResponse { override init?(response: NSHTTPURLResponse, json: AnyObject?) { super.init(response: response, json: json) } var wasSuccessful: Bool { get { return response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 204 // TODO On Android we call super.wasSuccessful() .. is there another value that we consider a success? } } var record: ReadingListServerRecord? { get { if let json: AnyObject = self.json { return ReadingListServerRecord(json: json) } else { return nil } } } }
mpl-2.0
7b9626895dd8422a2370f0bfbd0fb925
32.321429
114
0.61588
4.636816
false
false
false
false
1amageek/StripeAPI
StripeAPI/StripeAPI.swift
1
5049
// // API.swift // StripeAPI // // Created by 1amageek on 2017/10/01. // Copyright © 2017年 Stamp Inc. All rights reserved. // import Foundation import APIKit import Stripe import Result /** Stripe Model Stripe model supports coding possibilities */ public typealias StripeModel = Codable public protocol StripeAPI: Request { associatedtype Parameters = Void } public protocol ListProtocol { static var path: String { get } } extension StripeAPI { public var baseURL: URL { return URL(string: "https://api.stripe.com/v1")! } public var headerFields: [String : String] { return ["authorization": "Bearer \(apiKey)"] } public var apiKey: String { return Configuration.shared.apiKey } var encodedKey: String { let data: Data = self.apiKey.data(using: String.Encoding.utf8)! return data.base64EncodedString() } public var bodyParameters: BodyParameters? { guard let parameters = self.parameters as? [String: Any], !self.method.prefersQueryParameters else { return nil } return FormURLEncodedBodyParameters(formObject: parameters) } public var dataParser: DataParser { return DecodableDataParser() } @discardableResult public func send(_ block: @escaping (Result<Self.Response, SessionTaskError>) -> Void) -> SessionTask? { return Session.send(self, callbackQueue: .main, handler: block) } } // MARK: - public protocol ParametersProtocol { var _parameters: Any? { get set } } public typealias StripeParametersAPI = ParametersProtocol & StripeAPI public extension StripeAPI where Parameters: Encodable, Self: ParametersProtocol { public var parameters: Any? { return _parameters } public var bodyParameters: BodyParameters? { guard let parameters = self.parameters as? Parameters else { return nil } let data: Data = try! JSONEncoder().encode(parameters) let json: [String: Any] = try! JSONSerialization.jsonObject(with: data, options: [.allowFragments]) as! [String : Any] return URLEncodedBodyParameters(formObject: json) } } extension StripeAPI where Response: Decodable { public func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response { guard let data: Data = object as? Data else { throw ResponseError.unexpectedObject(object) } if let string = String(data: data, encoding: .utf8) { print("response: \(string)") } return try JSONDecoder().decode(Response.self, from: data) } } final class DecodableDataParser: DataParser { var contentType: String? { return "application/json" } func parse(data: Data) throws -> Any { return data } } public struct URLEncodedBodyParameters: BodyParameters { /// The form object to be serialized. public let form: [String: Any] /// The string encoding of the serialized form. public let encoding: String.Encoding /// Returns `FormURLEncodedBodyParameters` that is initialized with form object and encoding. public init(formObject: [String: Any], encoding: String.Encoding = .utf8) { self.form = formObject self.encoding = encoding } // MARK: - BodyParameters /// `Content-Type` to send. The value for this property will be set to `Accept` HTTP header field. public var contentType: String { return "application/x-www-form-urlencoded" } /// Builds `RequestBodyEntity.data` that represents `form`. /// - Throws: `URLEncodedSerialization.Error` if `URLEncodedSerialization` fails to serialize form object. public func buildEntity() throws -> RequestBodyEntity { return .data(try _URLEncodedSerialization.data(from: form, encoding: encoding)) } } extension StripeAPI { public func intercept(urlRequest: URLRequest) throws -> URLRequest { var urlRequest = urlRequest urlRequest.timeoutInterval = 10.0 print("requestURL: \(urlRequest)") print("requestHeader: \(urlRequest.allHTTPHeaderFields!)") print("requestBody: \(String(data: urlRequest.httpBody ?? Data(), encoding: .utf8).debugDescription)") return urlRequest } public func intercept(object: Any, urlResponse: HTTPURLResponse) throws -> Any { print("raw response header: \(urlResponse)") print("raw response header: \(urlResponse.allHeaderFields)") print("raw response body: \(object)") if let data: Data = object as? Data { // let json = try! JSONSerialization.data(withJSONObject: data, options: []) // print("raw response body", json) print("raw response body: \(String(data: data ?? Data(), encoding: .utf8).debugDescription)") } switch urlResponse.statusCode { case 200..<300: return object default: throw ResponseError.unacceptableStatusCode(urlResponse.statusCode) } } }
mit
b25953f8c83202b4b9e9351591cbba02
28.857988
126
0.663099
4.637868
false
false
false
false
kerry/KGProgress
Sources/KGProgress/Styles/Style.swift
1
1694
// // DefaultStyle.swift // KGProgress // // Created by kerry // import Foundation import UIKit public struct Style: StyleProperty { // Progress Size public var containerSize: CGSize = CGSize(width: 150, height: 150) public var progressSize: CGFloat = 44 // Gradient Circular public var arcLineWidth: CGFloat = 2.0 public var startArcColor: UIColor = UIColor.white public var endArcColor: UIColor = ColorUtil.toUIColor(r: 239, g: 64, b: 61, a: 1.0) // Base Circular public var baseLineWidth: CGFloat? = 2.0 public var baseArcColor: UIColor? = UIColor.gray // Ratio public var ratioLabelFont: UIFont? = UIFont.systemFont(ofSize: 12.0) public var ratioLabelFontColor: UIColor? = UIColor.black // Message public var hasMessage: Bool = true public var messageLabelFont: UIFont? = UIFont.systemFont(ofSize: 14.0) public var messageLabelFontColor: UIColor? = ColorUtil.toUIColor(r: 128, g: 128, b: 128, a: 1.0) // Background // public var backgroundStyle: BackgroundStyles = .white public var backgroundColor: UIColor? = .white public var backgroundCornerRadius: CGFloat? = 10 public var hasBackgroundShadow: Bool = true public var backgroundShadowOpacity: CGFloat? = 0.2 public var backgroundShadowRadius: CGFloat? = 5 public var backgroundShadowOffset: CGSize? = CGSize(width: 0, height: 0) //Blanket public var hasBlanket: Bool = true public var blanketOpacity: CGFloat? = 0.2 public var blanketColor: UIColor? = .black // Dismiss public var dismissTimeInterval: Double? = nil // 'nil' for default setting. public init() {} }
mit
5e99a64c8f771da1093814a569eddc52
32.215686
100
0.68477
4.162162
false
false
false
false
doubleleft/hook-swift
Hook/Source/Request.swift
1
4108
// // Request.swift // hook // // Created by Endel on 10/01/15. // Copyright (c) 2015 Doubleleft. All rights reserved. // import Alamofire; import Foundation; //import SwiftyJSON; public class Request { var request : Alamofire.Request; public init(url : String, method: Alamofire.Method, headers: [String: String], data : [String: AnyObject]? = nil) { let manager = Alamofire.Manager.sharedInstance manager.session.configuration.HTTPAdditionalHeaders = headers if method == Alamofire.Method.GET { self.request = Alamofire.request(method, url, parameters: data, encoding: Alamofire.ParameterEncoding.Custom({ (URLRequest, parameters) -> (NSURLRequest, NSError?) in if parameters == nil { return (URLRequest.URLRequest, nil) } // func escape(string: String) -> String { let legalURLCharactersToBeEscaped: CFStringRef = ":/?&=;+!@#$()',*" return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) } // var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as NSMutableURLRequest if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false){ URLComponents.percentEncodedQuery = escape(JSON(parameters!).rawString()!) mutableURLRequest.URL = URLComponents.URL } return (mutableURLRequest, nil) })) } else { self.request = Alamofire.request(method, url, parameters: data, encoding: Alamofire.ParameterEncoding.JSON) } } public func execute() -> Self { return self; } public func onSuccess(completionHandler: (JSON) -> Void) -> Self { self.request.responseString { (request, response, str, error) in //print("GOT: \(str)") if response?.statusCode < 400 { if let data = str?.dataUsingEncoding(NSUTF8StringEncoding) { completionHandler(JSON(data: data)); } else { println("Hook.Request: SOMETHING IS WRONG \(str)") } } } return self } public func onError(completionHandler: (JSON) -> Void) -> Self { self.request.responseString { (request, response, str, error) in if error != nil || response?.statusCode >= 400 { println("ERROR ERROR ERROR \(response?.statusCode)") if let data = str?.dataUsingEncoding(NSUTF8StringEncoding) { completionHandler(JSON(data: data)); } else if let e:NSError = error? { completionHandler(JSON([ "code": e.code, "error": e.localizedDescription, ])) } } } return self } // alias to onError public func onFail(completionHandler: (JSON) -> Void) -> Self { return self.onError(completionHandler) } public func onComplete(completionHandler: (JSON) -> Void) -> Self { self.request.responseString { (request, response, str, error) in if error == nil { if let data = str?.dataUsingEncoding(NSUTF8StringEncoding) { completionHandler(JSON(data: data)); } } else if let e:NSError = error? { completionHandler(JSON([ "code": e.code, "error": e.localizedDescription, ])) } else { completionHandler(JSON.nullJSON) } } return self; } public func suspend() { self.request.suspend() } public func resume() { self.request.resume() } public func cancel() { self.request.cancel() } }
mit
a99911147802e39292554a72b44e38e0
34.721739
178
0.549416
5.293814
false
false
false
false
nextcloud/ios
iOSClient/Viewer/NCViewerRichdocument/NCViewerRichdocument.swift
1
15981
// // NCViewerRichdocument.swift // Nextcloud // // Created by Marino Faggiana on 06/09/18. // Copyright © 2018 Marino Faggiana. All rights reserved. // // Author Marino Faggiana <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit import WebKit import NextcloudKit class NCViewerRichdocument: UIViewController, WKNavigationDelegate, WKScriptMessageHandler, NCSelectDelegate { let appDelegate = UIApplication.shared.delegate as! AppDelegate var webView = WKWebView() var bottomConstraint: NSLayoutConstraint? var documentController: UIDocumentInteractionController? var link: String = "" var metadata: tableMetadata = tableMetadata() var imageIcon: UIImage? // MARK: - View Life Cycle required init?(coder: NSCoder) { super.init(coder: coder) } override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "more")!.image(color: .label, size: 25), style: .plain, target: self, action: #selector(self.openMenuMore)) navigationController?.navigationBar.prefersLargeTitles = false navigationItem.title = metadata.fileNameView let config = WKWebViewConfiguration() config.websiteDataStore = WKWebsiteDataStore.nonPersistent() let contentController = config.userContentController contentController.add(self, name: "RichDocumentsMobileInterface") webView = WKWebView(frame: CGRect.zero, configuration: config) webView.navigationDelegate = self view.addSubview(webView) webView.translatesAutoresizingMaskIntoConstraints = false webView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true webView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true webView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true bottomConstraint = webView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0) bottomConstraint?.isActive = true var request = URLRequest(url: URL(string: link)!) request.addValue("true", forHTTPHeaderField: "OCS-APIRequest") let language = NSLocale.preferredLanguages[0] as String request.addValue(language, forHTTPHeaderField: "Accept-Language") webView.customUserAgent = CCUtility.getUserAgent() webView.load(request) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) appDelegate.activeViewController = self NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(viewUnload), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuDetailClose), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(viewUnload), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.grabFocus), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRichdocumentGrabFocus), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if let navigationController = self.navigationController { if !navigationController.viewControllers.contains(self) { let functionJS = "OCA.RichDocuments.documentsMain.onClose()" webView.evaluateJavaScript(functionJS) { _, _ in print("close") } } } NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMenuDetailClose), object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRichdocumentGrabFocus), object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func viewUnload() { navigationController?.popViewController(animated: true) } // MARK: - NotificationCenter @objc func favoriteFile(_ notification: NSNotification) { guard let userInfo = notification.userInfo as NSDictionary?, let ocId = userInfo["ocId"] as? String, ocId == self.metadata.ocId, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return } self.metadata = metadata } @objc func keyboardDidShow(notification: Notification) { guard let info = notification.userInfo else { return } guard let frameInfo = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return } let keyboardFrame = frameInfo.cgRectValue let height = keyboardFrame.size.height bottomConstraint?.constant = -height } @objc func keyboardWillHide(notification: Notification) { bottomConstraint?.constant = 0 } // MARK: - Action @objc func openMenuMore() { if imageIcon == nil { imageIcon = UIImage(named: "file_txt") } NCViewer.shared.toggleMenu(viewController: self, metadata: metadata, webView: true, imageIcon: imageIcon) } // MARK: - public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if message.name == "RichDocumentsMobileInterface" { if message.body as? String == "close" { viewUnload() } if message.body as? String == "insertGraphic" { let storyboard = UIStoryboard(name: "NCSelect", bundle: nil) let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController let viewController = navigationController.topViewController as! NCSelect viewController.delegate = self viewController.typeOfCommandView = .select viewController.enableSelectFile = true viewController.includeImages = true viewController.type = "" self.present(navigationController, animated: true, completion: nil) } if message.body as? String == "share" { NCFunctionCenter.shared.openShare(viewController: self, metadata: metadata, indexPage: .sharing) } if let param = message.body as? [AnyHashable: Any] { if param["MessageName"] as? String == "downloadAs" { if let values = param["Values"] as? [AnyHashable: Any] { guard let type = values["Type"] as? String else { return } guard let urlString = values["URL"] as? String else { return } guard let url = URL(string: urlString) else { return } let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + metadata.fileNameWithoutExt NCActivityIndicator.shared.start(backgroundView: view) NextcloudKit.shared.download(serverUrlFileName: url, fileNameLocalPath: fileNameLocalPath, requestHandler: { _ in }, taskHandler: { _ in }, progressHandler: { _ in }, completionHandler: { account, _, _, _, allHeaderFields, afError, error in NCActivityIndicator.shared.stop() if error == .success && account == self.metadata.account { var item = fileNameLocalPath if let allHeaderFields = allHeaderFields { if let disposition = allHeaderFields["Content-Disposition"] as? String { let components = disposition.components(separatedBy: "filename=") if let filename = components.last?.replacingOccurrences(of: "\"", with: "") { item = CCUtility.getDirectoryUserData() + "/" + filename _ = NCUtilityFileSystem.shared.moveFile(atPath: fileNameLocalPath, toPath: item) } } } if type == "print" { let pic = UIPrintInteractionController.shared let printInfo = UIPrintInfo.printInfo() printInfo.outputType = UIPrintInfo.OutputType.general printInfo.orientation = UIPrintInfo.Orientation.portrait printInfo.jobName = "Document" pic.printInfo = printInfo pic.printingItem = URL(fileURLWithPath: item) pic.present(from: CGRect.zero, in: self.view, animated: true, completionHandler: { _, _, _ in }) } else { self.documentController = UIDocumentInteractionController() self.documentController?.url = URL(fileURLWithPath: item) self.documentController?.presentOptionsMenu(from: CGRect.zero, in: self.view, animated: true) } } else { NCContentPresenter.shared.showError(error: error) } }) } } else if param["MessageName"] as? String == "fileRename" { if let values = param["Values"] as? [AnyHashable: Any] { guard let newName = values["NewName"] as? String else { return } metadata.fileName = newName metadata.fileNameView = newName } } else if param["MessageName"] as? String == "hyperlink" { if let values = param["Values"] as? [AnyHashable: Any] { guard let urlString = values["Url"] as? String else { return } if let url = URL(string: urlString) { UIApplication.shared.open(url) } } } } if message.body as? String == "documentLoaded" { print("documentLoaded") } if message.body as? String == "paste" { // ? } } } // MARK: - @objc func grabFocus() { let functionJS = "OCA.RichDocuments.documentsMain.postGrabFocus()" webView.evaluateJavaScript(functionJS) { _, _ in } } // MARK: - func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) { if serverUrl != nil && metadata != nil { let path = CCUtility.returnFileNamePath(fromFileName: metadata!.fileName, serverUrl: serverUrl!, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: metadata!.account)! NextcloudKit.shared.createAssetRichdocuments(path: path) { account, url, data, error in if error == .success && account == self.appDelegate.account { let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata!.fileNameView)', '\(url!)')" self.webView.evaluateJavaScript(functionJS, completionHandler: { _, _ in }) } else if error != .success { NCContentPresenter.shared.showError(error: error) } else { print("[LOG] It has been changed user during networking process, error.") } } } } func select(_ metadata: tableMetadata!, serverUrl: String!) { let path = CCUtility.returnFileNamePath(fromFileName: metadata!.fileName, serverUrl: serverUrl!, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: metadata!.account)! NextcloudKit.shared.createAssetRichdocuments(path: path) { account, url, data, error in if error == .success && account == self.appDelegate.account { let functionJS = "OCA.RichDocuments.documentsMain.postAsset('\(metadata.fileNameView)', '\(url!)')" self.webView.evaluateJavaScript(functionJS, completionHandler: { _, _ in }) } else if error != .success { NCContentPresenter.shared.showError(error: error) } else { print("[LOG] It has been changed user during networking process, error.") } } } // MARK: - public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { DispatchQueue.global().async { if let serverTrust = challenge.protectionSpace.serverTrust { completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust)) } else { completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil) } } } public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { print("didStartProvisionalNavigation") } public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) { print("didReceiveServerRedirectForProvisionalNavigation") } public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { NCActivityIndicator.shared.stop() } } extension NCViewerRichdocument: UINavigationControllerDelegate { override func didMove(toParent parent: UIViewController?) { super.didMove(toParent: parent) if parent == nil { NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced, userInfo: ["serverUrl": self.metadata.serverUrl]) } } }
gpl-3.0
f9b5de4ca097c907663290650face298
45.453488
200
0.620526
5.56213
false
false
false
false
zhubinchen/MarkLite
MarkLite/Utils/IAPHelper.swift
2
12112
// // IAPHelper.swift // IAPDemo // // Created by Jason Zheng on 8/24/16. // Copyright © 2016 Jason Zheng. All rights reserved. // import StoreKit extension SKProduct { public func localizedPrice() -> String? { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = self.priceLocale return formatter.string(from: self.price) } } public let IAP = IAPHelper.sharedInstance public typealias ProductIdentifier = String public typealias ProductWithExpireDate = [ProductIdentifier: Date] public typealias ProductsRequestHandler = (_ response: SKProductsResponse?, _ error: Error?) -> () public typealias PurchaseHandler = (_ productIdentifier: ProductIdentifier?, _ error: Error?) -> () public typealias RestoreHandler = (_ productIdentifiers: Set<ProductIdentifier>, _ error: Error?) -> () public typealias ValidateHandler = (_ statusCode: Int?, _ products: ProductWithExpireDate?, _ json: [String: Any]?) -> () public class IAPHelper: NSObject { private override init() { super.init() addObserver() } static let sharedInstance = IAPHelper() fileprivate var productsRequest: SKProductsRequest? fileprivate var productsRequestHandler: ProductsRequestHandler? fileprivate var purchaseHandler: PurchaseHandler? fileprivate var restoreHandler: RestoreHandler? private var observerAdded = false public func addObserver() { if !observerAdded { observerAdded = true SKPaymentQueue.default().add(self) } } public func removeObserver() { if observerAdded { observerAdded = false SKPaymentQueue.default().remove(self) } } } // MARK: StoreKit API extension IAPHelper { public func requestProducts(_ productIdentifiers: Set<ProductIdentifier>, handler: @escaping ProductsRequestHandler) { productsRequest?.cancel() productsRequestHandler = handler productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers) productsRequest?.delegate = self productsRequest?.start() } public func purchaseProduct(_ productIdentifier: ProductIdentifier, handler: @escaping PurchaseHandler) { purchaseHandler = handler let payment = SKMutablePayment() payment.productIdentifier = productIdentifier SKPaymentQueue.default().add(payment) } public func restorePurchases(_ handler: @escaping RestoreHandler) { restoreHandler = handler SKPaymentQueue.default().restoreCompletedTransactions() } /* * password: Only used for receipts that contain auto-renewable subscriptions. * It's your app’s shared secret (a hexadecimal string) which was generated on iTunesConnect. */ public func validateReceipt(_ password: String? = nil, handler: @escaping ValidateHandler) { validateReceiptInternal(true, password: password) { (statusCode, products, json) in if let statusCode = statusCode , statusCode == ReceiptStatus.testReceipt.rawValue { self.validateReceiptInternal(false, password: password, handler: { (statusCode, products, json) in handler(statusCode, products, json) }) } else { handler(statusCode, products, json) } } } } // MARK: SKProductsRequestDelegate extension IAPHelper: SKProductsRequestDelegate { public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { productsRequestHandler?(response, nil) clearRequestAndHandler() } public func request(_ request: SKRequest, didFailWithError error: Error) { productsRequestHandler?(nil, error) clearRequestAndHandler() } private func clearRequestAndHandler() { productsRequest = nil productsRequestHandler = nil } } // MARK: SKPaymentTransactionObserver extension IAPHelper: SKPaymentTransactionObserver { public func paymentQueue(_ queue: SKPaymentQueue, shouldAddStorePayment payment: SKPayment, for product: SKProduct) -> Bool { let sb = UIStoryboard(name: "Settings", bundle: Bundle.main) let vc = sb.instantiateVC(PurchaseViewController.self)! vc.productId = product.productIdentifier let nav = NavigationViewController(rootViewController: vc) nav.modalPresentationStyle = .fullScreen UIApplication.shared.keyWindow?.rootViewController?.presentVC(nav) return false } public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions { switch (transaction.transactionState) { case SKPaymentTransactionState.purchased: completePurchaseTransaction(transaction) case SKPaymentTransactionState.restored: finishTransaction(transaction) case SKPaymentTransactionState.failed: failedTransaction(transaction) case SKPaymentTransactionState.purchasing, SKPaymentTransactionState.deferred: break } } } public func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) { completeRestoreTransactions(queue, error: nil) } public func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) { completeRestoreTransactions(queue, error: error) } private func completePurchaseTransaction(_ transaction: SKPaymentTransaction) { purchaseHandler?(transaction.payment.productIdentifier, transaction.error) purchaseHandler = nil finishTransaction(transaction) } private func completeRestoreTransactions(_ queue: SKPaymentQueue, error: Error?) { var productIdentifiers = Set<ProductIdentifier>() for transaction in queue.transactions { if let productIdentifier = transaction.original?.payment.productIdentifier { productIdentifiers.insert(productIdentifier) } finishTransaction(transaction) } restoreHandler?(productIdentifiers, error) restoreHandler = nil } private func failedTransaction(_ transaction: SKPaymentTransaction) { // NOTE: Both purchase and restore may come to this state. So need to deal with both handlers. purchaseHandler?(nil, transaction.error) purchaseHandler = nil restoreHandler?(Set<ProductIdentifier>(), transaction.error) restoreHandler = nil finishTransaction(transaction) } // MARK: Helper private func finishTransaction(_ transaction: SKPaymentTransaction) { switch transaction.transactionState { case SKPaymentTransactionState.purchased, SKPaymentTransactionState.restored, SKPaymentTransactionState.failed: SKPaymentQueue.default().finishTransaction(transaction) default: break } } } // MARK: Validate Receipt extension IAPHelper { fileprivate func validateReceiptInternal(_ isProduction: Bool, password: String?, handler: @escaping ValidateHandler) { let serverURL = isProduction ? "https://buy.itunes.apple.com/verifyReceipt" : "https://sandbox.itunes.apple.com/verifyReceipt" let appStoreReceiptURL = Bundle.main.appStoreReceiptURL guard let receiptData = receiptData(appStoreReceiptURL, password: password), let url = URL(string: serverURL) else { handler(ReceiptStatus.noRecipt.rawValue, nil, nil) return } let request = NSMutableURLRequest(url: url) request.httpMethod = "POST" request.httpBody = receiptData let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in guard let data = data, error == nil else { handler(nil, nil, nil) return } do { let json = try JSONSerialization.jsonObject(with: data, options:[]) as? [String: Any] let statusCode = json?["status"] as? Int let products = self.parseValidateResultJSON(json) handler(statusCode, products, json) } catch { handler(nil, nil, nil) } } task.resume() } internal func parseValidateResultJSON(_ json: [String: Any]?) -> ProductWithExpireDate? { var products = ProductWithExpireDate() var canceledProducts = ProductWithExpireDate() var productDateDict = [String: [ProductDateHelper]]() let dateOf5000 = Date(timeIntervalSince1970: 95617584000) // 5000-01-01 var totalInAppPurchaseList = [[String: Any]]() if let receipt = json?["receipt"] as? [String: Any], let inAppPurchaseList = receipt["in_app"] as? [[String: Any]] { totalInAppPurchaseList += inAppPurchaseList } if let inAppPurchaseList = json?["latest_receipt_info"] as? [[String: Any]] { totalInAppPurchaseList += inAppPurchaseList } for inAppPurchase in totalInAppPurchaseList { if let productID = inAppPurchase["product_id"] as? String, let purchaseDate = parseDate(inAppPurchase["purchase_date_ms"] as? String) { let expiresDate = parseDate(inAppPurchase["expires_date_ms"] as? String) let cancellationDate = parseDate(inAppPurchase["cancellation_date_ms"] as? String) let productDateHelper = ProductDateHelper(purchaseDate: purchaseDate, expiresDate: expiresDate, canceledDate: cancellationDate) if productDateDict[productID] == nil { productDateDict[productID] = [productDateHelper] } else { productDateDict[productID]?.append(productDateHelper) } if let cancellationDate = cancellationDate { if let lastCanceledDate = canceledProducts[productID] { if lastCanceledDate.timeIntervalSince1970 < cancellationDate.timeIntervalSince1970 { canceledProducts[productID] = cancellationDate } } else { canceledProducts[productID] = cancellationDate } } } } for (productID, productDateHelpers) in productDateDict { var date = Date(timeIntervalSince1970: 0) let lastCanceledDate = canceledProducts[productID] for productDateHelper in productDateHelpers { let validDate = productDateHelper.getValidDate(lastCanceledDate: lastCanceledDate, unlimitedDate: dateOf5000) if date.timeIntervalSince1970 < validDate.timeIntervalSince1970 { date = validDate } } products[productID] = date } return products.isEmpty ? nil : products } private func receiptData(_ appStoreReceiptURL: URL?, password: String?) -> Data? { guard let receiptURL = appStoreReceiptURL, let receipt = try? Data(contentsOf: receiptURL) else { return nil } do { let receiptData = receipt.base64EncodedString() var requestContents = ["receipt-data": receiptData] if let password = password { requestContents["password"] = password } let requestData = try JSONSerialization.data(withJSONObject: requestContents, options: []) return requestData } catch let error { print("\(error)") } return nil } private func parseDate(_ str: String?) -> Date? { guard let str = str, let msTimeInterval = TimeInterval(str) else { return nil } return Date(timeIntervalSince1970: msTimeInterval / 1000) } } internal struct ProductDateHelper { var purchaseDate = Date(timeIntervalSince1970: 0) var expiresDate: Date? = nil var canceledDate: Date? = nil func getValidDate(lastCanceledDate: Date?, unlimitedDate: Date) -> Date { if let lastCanceledDate = lastCanceledDate { return (purchaseDate.timeIntervalSince1970 > lastCanceledDate.timeIntervalSince1970) ? (expiresDate ?? unlimitedDate) : lastCanceledDate } if let canceledDate = canceledDate { return canceledDate } else if let expiresDate = expiresDate { return expiresDate } else { return unlimitedDate } } } public enum ReceiptStatus: Int { case noRecipt = -999 case valid = 0 case testReceipt = 21007 }
gpl-3.0
90608d1fcce2231e787323ce2bf50ca6
31.290667
135
0.693451
5.08141
false
false
false
false
Urinx/Vu
唯舞/唯舞/PageViewController.swift
2
3196
// // PageViewController.swift // 唯舞 // // Created by Eular on 15/8/19. // Copyright © 2015年 eular. All rights reserved. // import UIKit import AVFoundation class PageViewController: UIPageViewController, UIPageViewControllerDataSource { var avPlayer: AVAudioPlayer! var pageHeadings = ["", "身在红尘的喧嚣", "回首路过的痕迹", "直到此刻"] var subHeadings = ["", "有时会往记自己属于哪道风景", "一直日光倾城", "不为繁华而动,只为宁静而舞"] var pageImages = ["g0", "g1", "g2", "g3"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. dataSource = self if let startingViewController = self.viewControllerAtIndex(0) { setViewControllers([startingViewController], direction: .Forward, animated: true, completion: nil) } do { avPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Audio Machine - Breath and Life", ofType: "mp3")!)) avPlayer.play() } catch {} } override func viewDidDisappear(animated: Bool) { avPlayer.stop() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { var index = ( viewController as! PageContentViewController ).index index++ return viewControllerAtIndex(index) } func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { var index = ( viewController as! PageContentViewController ).index index-- return viewControllerAtIndex(index) } /* Page Control*/ func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int { return pageHeadings.count } func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int { if let pageView = storyboard?.instantiateViewControllerWithIdentifier("PageContentViewController") as? PageContentViewController { return pageView.index } return 0 } func viewControllerAtIndex(index: Int) -> PageContentViewController? { if index == NSNotFound || index < 0 || index >= self.pageHeadings.count { return nil } // Create a new view controller and pass suitable data. if let pageView = storyboard?.instantiateViewControllerWithIdentifier("PageContentViewController") as? PageContentViewController { pageView.heading = pageHeadings[index] pageView.subHeading = subHeadings[index] pageView.img = pageImages[index] pageView.index = index return pageView } return nil } }
apache-2.0
162d11500799db8224cbdc68f11c05f7
34.102273
169
0.659437
5.372174
false
false
false
false
lieyunye/WeixinWalk
微信运动/微信运动/HRToast+UIView.swift
5
16352
// // HRToast + UIView.swift // ToastDemo // // Created by Rannie on 14/7/6. // Copyright (c) 2014年 Rannie. All rights reserved. // import UIKit /* * Infix overload method */ func /(lhs: CGFloat, rhs: Int) -> CGFloat { return lhs / CGFloat(rhs) } /* * Toast Config */ let HRToastDefaultDuration = 2.0 let HRToastFadeDuration = 0.2 let HRToastHorizontalMargin : CGFloat = 10.0 let HRToastVerticalMargin : CGFloat = 10.0 let HRToastPositionDefault = "bottom" let HRToastPositionTop = "top" let HRToastPositionCenter = "center" // activity let HRToastActivityWidth : CGFloat = 100.0 let HRToastActivityHeight : CGFloat = 100.0 let HRToastActivityPositionDefault = "center" // image size let HRToastImageViewWidth : CGFloat = 80.0 let HRToastImageViewHeight: CGFloat = 80.0 // label setting let HRToastMaxWidth : CGFloat = 0.8; // 80% of parent view width let HRToastMaxHeight : CGFloat = 0.8; let HRToastFontSize : CGFloat = 16.0 let HRToastMaxTitleLines = 0 let HRToastMaxMessageLines = 0 // shadow appearance let HRToastShadowOpacity : CGFloat = 0.8 let HRToastShadowRadius : CGFloat = 6.0 let HRToastShadowOffset : CGSize = CGSizeMake(CGFloat(4.0), CGFloat(4.0)) let HRToastOpacity : CGFloat = 0.8 let HRToastCornerRadius : CGFloat = 10.0 var HRToastActivityView: UnsafePointer<UIView> = nil var HRToastTimer: UnsafePointer<NSTimer> = nil var HRToastView: UnsafePointer<UIView> = nil /* * Custom Config */ let HRToastHidesOnTap = true let HRToastDisplayShadow = true //HRToast (UIView + Toast using Swift) extension UIView { /* * public methods */ func makeToast(message msg: String) { self.makeToast(message: msg, duration: HRToastDefaultDuration, position: HRToastPositionDefault) } func makeToast(message msg: String, duration: Double, position: AnyObject) { let toast = self.viewForMessage(msg, title: nil, image: nil) self.showToast(toast: toast!, duration: duration, position: position) } func makeToast(message msg: String, duration: Double, position: AnyObject, title: String) { let toast = self.viewForMessage(msg, title: title, image: nil) self.showToast(toast: toast!, duration: duration, position: position) } func makeToast(message msg: String, duration: Double, position: AnyObject, image: UIImage) { let toast = self.viewForMessage(msg, title: nil, image: image) self.showToast(toast: toast!, duration: duration, position: position) } func makeToast(message msg: String, duration: Double, position: AnyObject, title: String, image: UIImage) { let toast = self.viewForMessage(msg, title: title, image: image) self.showToast(toast: toast!, duration: duration, position: position) } func showToast(toast: UIView) { self.showToast(toast: toast, duration: HRToastDefaultDuration, position: HRToastPositionDefault) } func showToast(toast toast: UIView, duration: Double, position: AnyObject) { let existToast = objc_getAssociatedObject(self, &HRToastView) as! UIView? if existToast != nil { if let timer: NSTimer = objc_getAssociatedObject(existToast, &HRToastTimer) as? NSTimer { timer.invalidate(); } self.hideToast(toast: existToast!, force: false); } toast.center = self.centerPointForPosition(position, toast: toast) toast.alpha = 0.0 if HRToastHidesOnTap { let tapRecognizer = UITapGestureRecognizer(target: toast, action: Selector("handleToastTapped:")) toast.addGestureRecognizer(tapRecognizer) toast.userInteractionEnabled = true; toast.exclusiveTouch = true; } self.addSubview(toast) objc_setAssociatedObject(self, &HRToastView, toast, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) UIView.animateWithDuration(HRToastFadeDuration, delay: 0.0, options: [.CurveEaseOut , .AllowUserInteraction], animations: { toast.alpha = 1.0 }, completion: { (finished: Bool) in let timer = NSTimer.scheduledTimerWithTimeInterval(duration, target: self, selector: Selector("toastTimerDidFinish:"), userInfo: toast, repeats: false) objc_setAssociatedObject(toast, &HRToastTimer, timer, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }) } func makeToastActivity() { self.makeToastActivity(position: HRToastActivityPositionDefault) } func makeToastActivityWithMessage(message msg: String){ self.makeToastActivity(position: HRToastActivityPositionDefault, message: msg) } func makeToastActivity(position pos: AnyObject, message msg: String = "") { let existingActivityView: UIView? = objc_getAssociatedObject(self, &HRToastActivityView) as? UIView if existingActivityView != nil { return } let activityView = UIView(frame: CGRectMake(0, 0, HRToastActivityWidth, HRToastActivityHeight)) activityView.center = self.centerPointForPosition(pos, toast: activityView) activityView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(HRToastOpacity) activityView.alpha = 0.0 activityView.autoresizingMask = [.FlexibleLeftMargin , .FlexibleTopMargin , .FlexibleRightMargin , .FlexibleBottomMargin] activityView.layer.cornerRadius = HRToastCornerRadius if HRToastDisplayShadow { activityView.layer.shadowColor = UIColor.blackColor().CGColor activityView.layer.shadowOpacity = Float(HRToastShadowOpacity) activityView.layer.shadowRadius = HRToastShadowRadius activityView.layer.shadowOffset = HRToastShadowOffset } let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge) activityIndicatorView.center = CGPointMake(activityView.bounds.size.width / 2, activityView.bounds.size.height / 2) activityView.addSubview(activityIndicatorView) activityIndicatorView.startAnimating() if (!msg.isEmpty){ activityIndicatorView.frame.origin.y -= 10 let activityMessageLabel = UILabel(frame: CGRectMake(activityView.bounds.origin.x, (activityIndicatorView.frame.origin.y + activityIndicatorView.frame.size.height + 10), activityView.bounds.size.width, 20)) activityMessageLabel.textColor = UIColor.whiteColor() activityMessageLabel.font = (msg.characters.count<=10) ? UIFont(name:activityMessageLabel.font.fontName, size: 16) : UIFont(name:activityMessageLabel.font.fontName, size: 13) activityMessageLabel.textAlignment = .Center activityMessageLabel.text = msg activityView.addSubview(activityMessageLabel) } self.addSubview(activityView) // associate activity view with self objc_setAssociatedObject(self, &HRToastActivityView, activityView, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) UIView.animateWithDuration(HRToastFadeDuration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { activityView.alpha = 1.0 }, completion: nil) } func hideToastActivity() { let existingActivityView = objc_getAssociatedObject(self, &HRToastActivityView) as! UIView? if existingActivityView == nil { return } UIView.animateWithDuration(HRToastFadeDuration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { existingActivityView!.alpha = 0.0 }, completion: { (finished: Bool) in existingActivityView!.removeFromSuperview() objc_setAssociatedObject(self, &HRToastActivityView, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }) } /* * private methods (helper) */ func hideToast(toast toast: UIView) { self.hideToast(toast: toast, force: false); } func hideToast(toast toast: UIView, force: Bool) { let completeClosure = { (finish: Bool) -> () in toast.removeFromSuperview() objc_setAssociatedObject(self, &HRToastTimer, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } if force { completeClosure(true) } else { UIView.animateWithDuration(HRToastFadeDuration, delay: 0.0, options: [.CurveEaseIn , .BeginFromCurrentState], animations: { toast.alpha = 0.0 }, completion:completeClosure) } } func toastTimerDidFinish(timer: NSTimer) { self.hideToast(toast: timer.userInfo as! UIView) } func handleToastTapped(recognizer: UITapGestureRecognizer) { let timer = objc_getAssociatedObject(self, &HRToastTimer) as! NSTimer timer.invalidate() self.hideToast(toast: recognizer.view!) } func centerPointForPosition(position: AnyObject, toast: UIView) -> CGPoint { if position is String { let toastSize = toast.bounds.size let viewSize = self.bounds.size if position.lowercaseString == HRToastPositionTop { return CGPointMake(viewSize.width/2, toastSize.height/2 + HRToastVerticalMargin) } else if position.lowercaseString == HRToastPositionDefault { return CGPointMake(viewSize.width/2, viewSize.height - toastSize.height/2 - HRToastVerticalMargin) } else if position.lowercaseString == HRToastPositionCenter { return CGPointMake(viewSize.width/2, viewSize.height/2) } } else if position is NSValue { return position.CGPointValue } print("Warning: Invalid position for toast.") return self.centerPointForPosition(HRToastPositionDefault, toast: toast) } func viewForMessage(msg: String?, title: String?, image: UIImage?) -> UIView? { if msg == nil && title == nil && image == nil { return nil } var msgLabel: UILabel? var titleLabel: UILabel? var imageView: UIImageView? let wrapperView = UIView() wrapperView.autoresizingMask = [.FlexibleLeftMargin ,.FlexibleRightMargin , .FlexibleTopMargin , .FlexibleBottomMargin] wrapperView.layer.cornerRadius = HRToastCornerRadius wrapperView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(HRToastOpacity) if HRToastDisplayShadow { wrapperView.layer.shadowColor = UIColor.blackColor().CGColor wrapperView.layer.shadowOpacity = Float(HRToastShadowOpacity) wrapperView.layer.shadowRadius = HRToastShadowRadius wrapperView.layer.shadowOffset = HRToastShadowOffset } if image != nil { imageView = UIImageView(image: image) imageView!.contentMode = .ScaleAspectFit imageView!.frame = CGRectMake(HRToastHorizontalMargin, HRToastVerticalMargin, CGFloat(HRToastImageViewWidth), CGFloat(HRToastImageViewHeight)) } var imageWidth: CGFloat, imageHeight: CGFloat, imageLeft: CGFloat if imageView != nil { imageWidth = imageView!.bounds.size.width imageHeight = imageView!.bounds.size.height imageLeft = HRToastHorizontalMargin } else { imageWidth = 0.0; imageHeight = 0.0; imageLeft = 0.0 } if title != nil { titleLabel = UILabel() titleLabel!.numberOfLines = HRToastMaxTitleLines titleLabel!.font = UIFont.boldSystemFontOfSize(HRToastFontSize) titleLabel!.textAlignment = .Center titleLabel!.lineBreakMode = .ByWordWrapping titleLabel!.textColor = UIColor.whiteColor() titleLabel!.backgroundColor = UIColor.clearColor() titleLabel!.alpha = 1.0 titleLabel!.text = title // size the title label according to the length of the text let maxSizeTitle = CGSizeMake((self.bounds.size.width * HRToastMaxWidth) - imageWidth, self.bounds.size.height * HRToastMaxHeight); let expectedHeight = title!.stringHeightWithFontSize(HRToastFontSize, width: maxSizeTitle.width) titleLabel!.frame = CGRectMake(0.0, 0.0, maxSizeTitle.width, expectedHeight) } if msg != nil { msgLabel = UILabel(); msgLabel!.numberOfLines = HRToastMaxMessageLines msgLabel!.font = UIFont.systemFontOfSize(HRToastFontSize) msgLabel!.lineBreakMode = .ByWordWrapping msgLabel!.textAlignment = .Center msgLabel!.textColor = UIColor.whiteColor() msgLabel!.backgroundColor = UIColor.clearColor() msgLabel!.alpha = 1.0 msgLabel!.text = msg let maxSizeMessage = CGSizeMake((self.bounds.size.width * HRToastMaxWidth) - imageWidth, self.bounds.size.height * HRToastMaxHeight) let expectedHeight = msg!.stringHeightWithFontSize(HRToastFontSize, width: maxSizeMessage.width) msgLabel!.frame = CGRectMake(0.0, 0.0, maxSizeMessage.width, expectedHeight) } var titleWidth: CGFloat, titleHeight: CGFloat, titleTop: CGFloat, titleLeft: CGFloat if titleLabel != nil { titleWidth = titleLabel!.bounds.size.width titleHeight = titleLabel!.bounds.size.height titleTop = HRToastVerticalMargin titleLeft = imageLeft + imageWidth + HRToastHorizontalMargin } else { titleWidth = 0.0; titleHeight = 0.0; titleTop = 0.0; titleLeft = 0.0 } var msgWidth: CGFloat, msgHeight: CGFloat, msgTop: CGFloat, msgLeft: CGFloat if msgLabel != nil { msgWidth = msgLabel!.bounds.size.width msgHeight = msgLabel!.bounds.size.height msgTop = titleTop + titleHeight + HRToastVerticalMargin msgLeft = imageLeft + imageWidth + HRToastHorizontalMargin } else { msgWidth = 0.0; msgHeight = 0.0; msgTop = 0.0; msgLeft = 0.0 } let largerWidth = max(titleWidth, msgWidth) let largerLeft = max(titleLeft, msgLeft) // set wrapper view's frame let wrapperWidth = max(imageWidth + HRToastHorizontalMargin * 2, largerLeft + largerWidth + HRToastHorizontalMargin) let wrapperHeight = max(msgTop + msgHeight + HRToastVerticalMargin, imageHeight + HRToastVerticalMargin * 2) wrapperView.frame = CGRectMake(0.0, 0.0, wrapperWidth, wrapperHeight) // add subviews if titleLabel != nil { titleLabel!.frame = CGRectMake(titleLeft, titleTop, titleWidth, titleHeight) wrapperView.addSubview(titleLabel!) } if msgLabel != nil { msgLabel!.frame = CGRectMake(msgLeft, msgTop, msgWidth, msgHeight) wrapperView.addSubview(msgLabel!) } if imageView != nil { wrapperView.addSubview(imageView!) } return wrapperView } } extension String { func stringHeightWithFontSize(fontSize: CGFloat,width: CGFloat) -> CGFloat { let font = UIFont.systemFontOfSize(fontSize) let size = CGSizeMake(width, CGFloat.max) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = .ByWordWrapping; let attributes = [NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy()] let text = self as NSString let rect = text.boundingRectWithSize(size, options:.UsesLineFragmentOrigin, attributes: attributes, context:nil) return rect.size.height } }
apache-2.0
6aefb100ebae12e26a499e9dc6fa2857
41.030848
218
0.646606
4.933615
false
false
false
false
tkremenek/swift
test/SILGen/accessors.swift
20
8314
// RUN: %target-swift-emit-silgen -module-name accessors -Xllvm -sil-full-demangle %s | %FileCheck %s // Hold a reference to do to magically become non-POD. class Reference {} // A struct with a non-mutating getter and a mutating setter. struct OrdinarySub { var ptr = Reference() subscript(value: Int) -> Int { get { return value } set {} } } class A { var array = OrdinarySub() } func index0() -> Int { return 0 } func index1() -> Int { return 1 } func someValidPointer<T>() -> UnsafePointer<T> { fatalError() } func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() } // Verify that there is no unnecessary extra copy_value of ref.array. // rdar://19002913 func test0(_ ref: A) { ref.array[index0()] = ref.array[index1()] } // CHECK: sil hidden [ossa] @$s9accessors5test0yyAA1ACF : $@convention(thin) (@guaranteed A) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $A): // CHECK-NEXT: debug_value // Formal evaluation of LHS. // CHECK-NEXT: // function_ref accessors.index0() -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @$s9accessors6index0SiyF // CHECK-NEXT: [[INDEX0:%.*]] = apply [[T0]]() // Formal evaluation of RHS. // CHECK-NEXT: // function_ref accessors.index1() -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @$s9accessors6index1SiyF // CHECK-NEXT: [[INDEX1:%.*]] = apply [[T0]]() // Formal access to RHS. // CHECK-NEXT: [[T0:%.*]] = class_method [[ARG]] : $A, #A.array!getter // CHECK-NEXT: [[OWNED_SELF:%.*]] = apply [[T0]]([[ARG]]) // CHECK-NEXT: [[SELF:%.*]] = begin_borrow [[OWNED_SELF]] // CHECK-NEXT: // function_ref accessors.OrdinarySub.subscript.getter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T1:%.*]] = function_ref @$s9accessors11OrdinarySubVyS2icig // CHECK-NEXT: [[VALUE:%.*]] = apply [[T1]]([[INDEX1]], [[SELF]]) // CHECK-NEXT: end_borrow [[SELF]] // Formal access to LHS. // CHECK-NEXT: [[T0:%.*]] = class_method [[ARG]] : $A, #A.array!modify // CHECK-NEXT: ([[T1:%.*]], [[T2:%.*]]) = begin_apply [[T0]]([[ARG]]) // CHECK-NEXT: // function_ref accessors.OrdinarySub.subscript.setter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[SETTER:%.*]] = function_ref @$s9accessors11OrdinarySubVyS2icis // CHECK-NEXT: apply [[SETTER]]([[VALUE]], [[INDEX0]], [[T1]]) // CHECK-NEXT: end_apply [[T2]] // CHECK-NEXT: destroy_value [[OWNED_SELF]] // CHECK-NEXT: tuple () // CHECK-NEXT: return // A struct with a mutating getter and a mutating setter. struct MutatingSub { var ptr = Reference() subscript(value: Int) -> Int { mutating get { return value } set {} } } class B { var array = MutatingSub() } func test1(_ ref: B) { ref.array[index0()] = ref.array[index1()] } // CHECK-LABEL: sil hidden [ossa] @$s9accessors5test1yyAA1BCF : $@convention(thin) (@guaranteed B) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $B): // CHECK-NEXT: debug_value // Formal evaluation of LHS. // CHECK-NEXT: // function_ref accessors.index0() -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @$s9accessors6index0SiyF // CHECK-NEXT: [[INDEX0:%.*]] = apply [[T0]]() // Formal evaluation of RHS. // CHECK-NEXT: // function_ref accessors.index1() -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @$s9accessors6index1SiyF // CHECK-NEXT: [[INDEX1:%.*]] = apply [[T0]]() // Formal access to RHS. // CHECK-NEXT: [[T0:%.*]] = class_method [[ARG]] : $B, #B.array!modify // CHECK-NEXT: ([[T1:%.*]], [[TOKEN:%.*]]) = begin_apply [[T0]]([[ARG]]) // CHECK-NEXT: // function_ref accessors.MutatingSub.subscript.getter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @$s9accessors11MutatingSubVyS2icig : $@convention(method) (Int, @inout MutatingSub) -> Int // CHECK-NEXT: [[VALUE:%.*]] = apply [[T0]]([[INDEX1]], [[T1]]) // CHECK-NEXT: end_apply [[TOKEN]] // Formal access to LHS. // CHECK-NEXT: [[T0:%.*]] = class_method [[ARG]] : $B, #B.array!modify // CHECK-NEXT: ([[T1:%.*]], [[TOKEN:%.*]]) = begin_apply [[T0]]([[ARG]]) // CHECK-NEXT: // function_ref accessors.MutatingSub.subscript.setter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[SETTER:%.*]] = function_ref @$s9accessors11MutatingSubVyS2icis : $@convention(method) (Int, Int, @inout MutatingSub) -> () // CHECK-NEXT: apply [[SETTER]]([[VALUE]], [[INDEX0]], [[T1]]) // CHECK-NEXT: end_apply [[TOKEN]] // CHECK-NEXT: tuple () // CHECK-NEXT: return struct RecInner { subscript(i: Int) -> Int { get { return i } } } struct RecOuter { var inner : RecInner { unsafeAddress { return someValidPointer() } unsafeMutableAddress { return someValidPointer() } } } func test_rec(_ outer: inout RecOuter) -> Int { return outer.inner[0] } // This uses the immutable addressor. // CHECK: sil hidden [ossa] @$s9accessors8test_recySiAA8RecOuterVzF : $@convention(thin) (@inout RecOuter) -> Int { // CHECK: function_ref @$s9accessors8RecOuterV5innerAA0B5InnerVvlu : $@convention(method) (RecOuter) -> UnsafePointer<RecInner> struct Rec2Inner { subscript(i: Int) -> Int { mutating get { return i } } } struct Rec2Outer { var inner : Rec2Inner { unsafeAddress { return someValidPointer() } unsafeMutableAddress { return someValidPointer() } } } func test_rec2(_ outer: inout Rec2Outer) -> Int { return outer.inner[0] } // This uses the mutable addressor. // CHECK: sil hidden [ossa] @$s9accessors9test_rec2ySiAA9Rec2OuterVzF : $@convention(thin) (@inout Rec2Outer) -> Int { // CHECK: function_ref @$s9accessors9Rec2OuterV5innerAA0B5InnerVvau : $@convention(method) (@inout Rec2Outer) -> UnsafeMutablePointer<Rec2Inner> // SR-12456: Compiler crash on class var override adding observer. class SR12456Base { open class var instance: SR12456Base { get { return SR12456Base() } set {} } } class SR12456Subclass : SR12456Base { override class var instance: SR12456Base { didSet {} } } // Make sure we can handle more complicated overrides. class Parent<V> { class C<T, U> { class var foo: Int { get { 0 } set {} } } class D<T> : C<T, Int> {} class E : D<Double> { // CHECK-LABEL: sil hidden [ossa] @$s9accessors6ParentC1EC3fooSivgZ : $@convention(method) <V> (@thick Parent<V>.E.Type) -> Int // CHECK: [[TY:%.+]] = upcast {{%.+}} : $@thick Parent<V>.E.Type to $@thick Parent<V>.D<Double>.Type // CHECK: [[UPCASTTY:%.+]] = upcast [[TY]] : $@thick Parent<V>.D<Double>.Type to $@thick Parent<V>.C<Double, Int>.Type // CHECK: [[GETTER:%.+]] = function_ref @$s9accessors6ParentC1CC3fooSivgZ : $@convention(method) <τ_0_0><τ_1_0, τ_1_1> (@thick Parent<τ_0_0>.C<τ_1_0, τ_1_1>.Type) -> Int // CHECK: apply [[GETTER]]<V, Double, Int>([[UPCASTTY]]) override class var foo: Int { didSet {} } } } struct Foo { private subscript(privateSubscript x: Void) -> Void { // CHECK-DAG: sil private [ossa] @$s9accessors3FooV16privateSubscriptyyt_tc33_D7F31B09EE737C687DC580B2014D759CLlig : $@convention(method) (Foo) -> () { get {} } private(set) subscript(withPrivateSet x: Void) -> Void { // CHECK-DAG: sil hidden [ossa] @$s9accessors3FooV14withPrivateSetyyt_tcig : $@convention(method) (Foo) -> () { get {} // CHECK-DAG: sil hidden [ossa] @$s9accessors3FooV14withPrivateSetyyt_tcis : $@convention(method) (@inout Foo) -> () { set {} } subscript(withNestedClass x: Void) -> Void { // Check for initializer of NestedClass // CHECK-DAG: sil private [ossa] @$s9accessors3FooV15withNestedClassyyt_tcig0dE0L_CAFycfc : $@convention(method) (@owned NestedClass) -> @owned NestedClass { class NestedClass {} } // CHECK-DAG: sil private [ossa] @$s9accessors3FooV15privateVariable33_D7F31B09EE737C687DC580B2014D759CLLytvg : $@convention(method) (Foo) -> () { private var privateVariable: Void { return } private(set) var variableWithPrivateSet: Void { // CHECK-DAG: sil hidden [ossa] @$s9accessors3FooV22variableWithPrivateSetytvg : $@convention(method) (Foo) -> () { get {} // CHECK-DAG: sil hidden [ossa] @$s9accessors3FooV22variableWithPrivateSetytvs : $@convention(method) (@inout Foo) -> () { set {} } var propertyWithNestedClass: Void { // Check for initializer of NestedClass // CHECK-DAG: sil private [ossa] @$s9accessors3FooV23propertyWithNestedClassytvg0eF0L_CAFycfc : $@convention(method) (@owned NestedClass) -> @owned NestedClass { class NestedClass {} } }
apache-2.0
56ebd11cab553f54b208351fd928a40b
40.128713
173
0.649374
3.255486
false
false
false
false
xmartlabs/XLForm
Examples/Swift/SwiftExample/CustomSelectors/XLFormRowViewController/MapViewController.swift
1
3798
// // MapViewController.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. import UIKit import MapKit class MapAnnotation : NSObject, MKAnnotation { @objc var coordinate : CLLocationCoordinate2D override init() { coordinate = CLLocationCoordinate2D(latitude: -33.0, longitude: -56.0) super.init() } } @objc(MapViewController) class MapViewController : UIViewController, XLFormRowDescriptorViewController, MKMapViewDelegate { var rowDescriptor: XLFormRowDescriptor? lazy var mapView : MKMapView = { [unowned self] in let mapView = MKMapView(frame: self.view.frame) mapView.autoresizingMask = [UIView.AutoresizingMask.flexibleHeight, UIView.AutoresizingMask.flexibleWidth] return mapView }() override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.addSubview(mapView) mapView.delegate = self if let value = rowDescriptor?.value as? CLLocation { mapView.setCenter(value.coordinate, animated: false) title = String(format: "%0.4f, %0.4f", mapView.centerCoordinate.latitude, mapView.centerCoordinate.longitude) let annotation = MapAnnotation() annotation.coordinate = value.coordinate self.mapView.addAnnotation(annotation) } } //MARK - - MKMapViewDelegate func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "annotation") pinAnnotationView.pinTintColor = .red pinAnnotationView.isDraggable = true pinAnnotationView.animatesDrop = true return pinAnnotationView } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationView.DragState, fromOldState oldState: MKAnnotationView.DragState) { if (newState == .ending){ if let rowDescriptor = rowDescriptor, let annotation = view.annotation { rowDescriptor.value = CLLocation(latitude:annotation.coordinate.latitude, longitude:annotation.coordinate.longitude) self.title = String(format: "%0.4f, %0.4f", annotation.coordinate.latitude, annotation.coordinate.longitude) } } } }
mit
f55698f8c5617a4aab311c384804489a
38.5625
178
0.705371
5.003953
false
false
false
false
naokits/my-programming-marathon
iPhoneSensorDemo/Pods/RxCocoa/RxCocoa/iOS/UIImageView+Rx.swift
27
1411
// // UIImageView+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 4/1/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation #if !RX_NO_MODULE import RxSwift #endif import UIKit extension UIImageView { /** Bindable sink for `image` property. */ public var rx_image: AnyObserver<UIImage?> { return self.rx_imageAnimated(nil) } /** Bindable sink for `image` property. - parameter transitionType: Optional transition type while setting the image (kCATransitionFade, kCATransitionMoveIn, ...) */ public func rx_imageAnimated(transitionType: String?) -> AnyObserver<UIImage?> { return UIBindingObserver(UIElement: self) { imageView, image in if let transitionType = transitionType { if image != nil { let transition = CATransition() transition.duration = 0.25 transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transition.type = transitionType imageView.layer.addAnimation(transition, forKey: kCATransition) } } else { imageView.layer.removeAllAnimations() } imageView.image = image }.asObserver() } } #endif
mit
44b5d39193bdaffe84ca0a6c8d9149c9
26.647059
126
0.602128
5.017794
false
false
false
false
yanyuqingshi/ios-charts
Charts/Classes/Renderers/ChartXAxisRendererHorizontalBarChart.swift
1
10539
// // ChartXAxisRendererHorizontalBarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics.CGBase import UIKit.UIFont public class ChartXAxisRendererHorizontalBarChart: ChartXAxisRendererBarChart { public override init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer, chart: chart); } public override func computeAxis(#xValAverageLength: Double, xValues: [String?]) { _xAxis.values = xValues; var longest = _xAxis.getLongestLabel() as NSString; var longestSize = longest.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]); _xAxis.labelWidth = floor(longestSize.width + _xAxis.xOffset * 3.5); _xAxis.labelHeight = longestSize.height; } public override func renderAxisLabels(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled || _chart.data === nil) { return; } var xoffset = _xAxis.xOffset; if (_xAxis.labelPosition == .Top) { drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, align: .Left); } else if (_xAxis.labelPosition == .Bottom) { drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, align: .Right); } else if (_xAxis.labelPosition == .BottomInside) { drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, align: .Left); } else if (_xAxis.labelPosition == .TopInside) { drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, align: .Right); } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.contentLeft, align: .Left); drawLabels(context: context, pos: viewPortHandler.contentRight, align: .Left); } } /// draws the x-labels on the specified y-position internal func drawLabels(#context: CGContext, pos: CGFloat, align: NSTextAlignment) { var labelFont = _xAxis.labelFont; var labelTextColor = _xAxis.labelTextColor; // pre allocate to save performance (dont allocate in loop) var position = CGPoint(x: 0.0, y: 0.0); var bd = _chart.data as! BarChartData; var step = bd.dataSetCount; for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus) { var label = _xAxis.values[i]; if (label == nil) { continue; } position.x = 0.0; position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace + bd.groupSpace / 2.0; // consider groups (center label for each group) if (step > 1) { position.y += (CGFloat(step) - 1.0) / 2.0; } transformer.pointValueToPixel(&position); if (viewPortHandler.isInBoundsY(position.y)) { ChartUtils.drawText(context: context, text: label!, point: CGPoint(x: pos, y: position.y - _xAxis.labelHeight / 2.0), align: align, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]); } } } private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderGridLines(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawGridLinesEnabled || _chart.data === nil) { return; } CGContextSaveGState(context); CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor); CGContextSetLineWidth(context, _xAxis.gridLineWidth); if (_xAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } var position = CGPoint(x: 0.0, y: 0.0); var bd = _chart.data as! BarChartData; // take into consideration that multiple DataSets increase _deltaX var step = bd.dataSetCount; for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus) { position.x = 0.0; position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace - 0.5; transformer.pointValueToPixel(&position); if (viewPortHandler.isInBoundsY(position.y)) { _gridLineSegmentsBuffer[0].x = viewPortHandler.contentLeft; _gridLineSegmentsBuffer[0].y = position.y; _gridLineSegmentsBuffer[1].x = viewPortHandler.contentRight; _gridLineSegmentsBuffer[1].y = position.y; CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2); } } CGContextRestoreGState(context); } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderAxisLine(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawAxisLineEnabled) { return; } CGContextSaveGState(context); CGContextSetStrokeColorWithColor(context, _xAxis.axisLineColor.CGColor); CGContextSetLineWidth(context, _xAxis.axisLineWidth); if (_xAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.axisLineDashPhase, _xAxis.axisLineDashLengths, _xAxis.axisLineDashLengths.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } if (_xAxis.labelPosition == .Top || _xAxis.labelPosition == .TopInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentRight; _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop; _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight; _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom; CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2); } if (_xAxis.labelPosition == .Bottom || _xAxis.labelPosition == .BottomInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft; _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop; _axisLineSegmentsBuffer[1].x = viewPortHandler.contentLeft; _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom; CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2); } CGContextRestoreGState(context); } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderLimitLines(#context: CGContext) { var limitLines = _xAxis.limitLines; if (limitLines.count == 0) { return; } CGContextSaveGState(context); var trans = transformer.valueToPixelMatrix; var position = CGPoint(x: 0.0, y: 0.0); for (var i = 0; i < limitLines.count; i++) { var l = limitLines[i]; position.x = 0.0; position.y = CGFloat(l.limit); position = CGPointApplyAffineTransform(position, trans); _limitLineSegmentsBuffer[0].x = viewPortHandler.contentLeft; _limitLineSegmentsBuffer[0].y = position.y; _limitLineSegmentsBuffer[1].x = viewPortHandler.contentRight; _limitLineSegmentsBuffer[1].y = position.y; CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor); CGContextSetLineWidth(context, l.lineWidth); if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2); var label = l.label; // if drawing the limit-value label is enabled if (count(label) > 0) { var labelLineHeight = l.valueFont.lineHeight; let add = CGFloat(4.0); var xOffset: CGFloat = add; var yOffset: CGFloat = l.lineWidth + labelLineHeight / 2.0; if (l.labelPosition == .Right) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y - yOffset - labelLineHeight), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]); } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y - yOffset - labelLineHeight), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]); } } } CGContextRestoreGState(context); } }
apache-2.0
3bfef5838aa832dc689a8daa11c17632
36.508897
242
0.566562
5.415725
false
false
false
false
jacobwhite/firefox-ios
Client/Frontend/Home/HomePanelViewController.swift
1
15012
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import SnapKit import UIKit import Storage private struct HomePanelViewControllerUX { // Height of the top panel switcher button toolbar. static let ButtonContainerHeight: CGFloat = 40 static let ButtonContainerBorderColor = UIColor.black.withAlphaComponent(0.1) static let BackgroundColorPrivateMode = UIConstants.PrivateModeAssistantToolbarBackgroundColor static let ToolbarButtonDeselectedColorNormalMode = UIColor(white: 0.2, alpha: 0.5) static let ToolbarButtonDeselectedColorPrivateMode = UIColor(white: 0.9, alpha: 1) static let ButtonHighlightLineHeight: CGFloat = 2 static let ButtonSelectionAnimationDuration = 0.2 } protocol HomePanelViewControllerDelegate: class { func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectURL url: URL, visitType: VisitType) func homePanelViewController(_ HomePanelViewController: HomePanelViewController, didSelectPanel panel: Int) func homePanelViewControllerDidRequestToSignIn(_ homePanelViewController: HomePanelViewController) func homePanelViewControllerDidRequestToCreateAccount(_ homePanelViewController: HomePanelViewController) func homePanelViewControllerDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) } protocol HomePanel: class { weak var homePanelDelegate: HomePanelDelegate? { get set } } struct HomePanelUX { static let EmptyTabContentOffset = -180 } protocol HomePanelDelegate: class { func homePanelDidRequestToSignIn(_ homePanel: HomePanel) func homePanelDidRequestToCreateAccount(_ homePanel: HomePanel) func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) func homePanel(_ homePanel: HomePanel, didSelectURL url: URL, visitType: VisitType) func homePanel(_ homePanel: HomePanel, didSelectURLString url: String, visitType: VisitType) } struct HomePanelState { var selectedIndex: Int = 0 } enum HomePanelType: Int { case topSites = 0 case bookmarks = 1 case history = 2 case readingList = 3 var localhostURL: URL { return URL(string: "#panel=\(self.rawValue)", relativeTo: UIConstants.AboutHomePage as URL)! } } class HomePanelViewController: UIViewController, UITextFieldDelegate, HomePanelDelegate { var profile: Profile! var notificationToken: NSObjectProtocol! var panels: [HomePanelDescriptor]! var url: URL? weak var delegate: HomePanelViewControllerDelegate? fileprivate var buttonContainerView = UIStackView() fileprivate var buttonContainerBottomBorderView: UIView! fileprivate var controllerContainerView: UIView! fileprivate var buttons: [UIButton] = [] fileprivate var highlightLine = UIView() //The line underneath a panel button that shows which one is selected fileprivate var buttonTintColor: UIColor? fileprivate var buttonSelectedTintColor: UIColor? var homePanelState: HomePanelState { return HomePanelState(selectedIndex: selectedPanel?.rawValue ?? 0) } override func viewDidLoad() { view.backgroundColor = UIConstants.AppBackgroundColor buttonContainerView.axis = .horizontal buttonContainerView.alignment = .fill buttonContainerView.distribution = .fillEqually buttonContainerView.spacing = 14 buttonContainerView.clipsToBounds = true buttonContainerView.accessibilityNavigationStyle = .combined buttonContainerView.accessibilityLabel = NSLocalizedString("Panel Chooser", comment: "Accessibility label for the Home panel's top toolbar containing list of the home panels (top sites, bookmarsk, history, remote tabs, reading list).") view.addSubview(buttonContainerView) buttonContainerView.addSubview(highlightLine) self.buttonContainerBottomBorderView = UIView() self.view.addSubview(buttonContainerBottomBorderView) buttonContainerBottomBorderView.backgroundColor = HomePanelViewControllerUX.ButtonContainerBorderColor controllerContainerView = UIView() view.addSubview(controllerContainerView) buttonContainerView.snp.makeConstraints { make in make.top.equalTo(self.view) make.leading.trailing.equalTo(self.view).inset(14) make.height.equalTo(HomePanelViewControllerUX.ButtonContainerHeight) } buttonContainerBottomBorderView.snp.makeConstraints { make in make.top.equalTo(self.buttonContainerView.snp.bottom).offset(-1) make.bottom.equalTo(self.buttonContainerView) make.leading.trailing.equalToSuperview() } controllerContainerView.snp.makeConstraints { make in make.top.equalTo(self.buttonContainerView.snp.bottom) make.left.right.bottom.equalTo(self.view) } self.panels = HomePanels().enabledPanels updateButtons() // Gesture recognizer to dismiss the keyboard in the URLBarView when the buttonContainerView is tapped let dismissKeyboardGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) dismissKeyboardGestureRecognizer.cancelsTouchesInView = false buttonContainerView.addGestureRecognizer(dismissKeyboardGestureRecognizer) } @objc func dismissKeyboard(_ gestureRecognizer: UITapGestureRecognizer) { view.window?.rootViewController?.view.endEditing(true) } var selectedPanel: HomePanelType? = nil { didSet { if oldValue == selectedPanel { // Prevent flicker, allocations, and disk access: avoid duplicate view controllers. return } if let index = oldValue?.rawValue { if index < buttons.count { let currentButton = buttons[index] currentButton.isSelected = false currentButton.isUserInteractionEnabled = true } } hideCurrentPanel() if let index = selectedPanel?.rawValue { if index < buttons.count { let newButton = buttons[index] newButton.isSelected = true newButton.isUserInteractionEnabled = false } if index < panels.count { let panel = self.panels[index].makeViewController(profile) let accessibilityLabel = self.panels[index].accessibilityLabel if let panelController = panel as? UINavigationController, let rootPanel = panelController.viewControllers.first { setupHomePanel(rootPanel, accessibilityLabel: accessibilityLabel) self.showPanel(panelController) } else { setupHomePanel(panel, accessibilityLabel: accessibilityLabel) self.showPanel(panel) } } } self.updateButtonTints() } } func setupHomePanel(_ panel: UIViewController, accessibilityLabel: String) { (panel as? HomePanel)?.homePanelDelegate = self panel.view.accessibilityNavigationStyle = .combined panel.view.accessibilityLabel = accessibilityLabel } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } fileprivate func hideCurrentPanel() { if let panel = childViewControllers.first { panel.willMove(toParentViewController: nil) panel.beginAppearanceTransition(false, animated: false) panel.view.removeFromSuperview() panel.endAppearanceTransition() panel.removeFromParentViewController() } } fileprivate func showPanel(_ panel: UIViewController) { addChildViewController(panel) panel.beginAppearanceTransition(true, animated: false) controllerContainerView.addSubview(panel.view) panel.endAppearanceTransition() panel.view.snp.makeConstraints { make in make.top.equalTo(self.buttonContainerView.snp.bottom) make.left.right.bottom.equalTo(self.view) } panel.didMove(toParentViewController: self) } @objc func tappedButton(_ sender: UIButton!) { for (index, button) in buttons.enumerated() where button == sender { selectedPanel = HomePanelType(rawValue: index) delegate?.homePanelViewController(self, didSelectPanel: index) if selectedPanel == .bookmarks { UnifiedTelemetry.recordEvent(category: .action, method: .view, object: .bookmarksPanel, value: .homePanelTabButton) } break } } fileprivate func updateButtons() { for panel in panels { let button = UIButton() button.addTarget(self, action: #selector(tappedButton), for: .touchUpInside) if let image = UIImage.templateImageNamed("panelIcon\(panel.imageName)") { button.setImage(image, for: .normal) } button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 4, right: 0) button.accessibilityLabel = panel.accessibilityLabel button.accessibilityIdentifier = panel.accessibilityIdentifier buttons.append(button) self.buttonContainerView.addArrangedSubview(button) } } func updateButtonTints() { var selectedbutton: UIView? for (index, button) in self.buttons.enumerated() { if index == self.selectedPanel?.rawValue { button.tintColor = self.buttonSelectedTintColor selectedbutton = button } else { button.tintColor = self.buttonTintColor } } guard let button = selectedbutton else { return } // Calling this before makes sure that only the highlightline animates and not the homepanels self.view.setNeedsUpdateConstraints() self.view.layoutIfNeeded() UIView.animate(withDuration: HomePanelViewControllerUX.ButtonSelectionAnimationDuration, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: [], animations: { self.highlightLine.snp.remakeConstraints { make in make.leading.equalTo(button.snp.leading) make.trailing.equalTo(button.snp.trailing) make.bottom.equalToSuperview() make.height.equalTo(HomePanelViewControllerUX.ButtonHighlightLineHeight) } self.view.setNeedsUpdateConstraints() self.view.layoutIfNeeded() }, completion: nil) } func homePanel(_ homePanel: HomePanel, didSelectURLString url: String, visitType: VisitType) { // If we can't get a real URL out of what should be a URL, we let the user's // default search engine give it a shot. // Typically we'll be in this state if the user has tapped a bookmarked search template // (e.g., "http://foo.com/bar/?query=%s"), and this will get them the same behavior as if // they'd copied and pasted into the URL bar. // See BrowserViewController.urlBar:didSubmitText:. guard let url = URIFixup.getURL(url) ?? profile.searchEngines.defaultEngine.searchURLForQuery(url) else { Logger.browserLogger.warning("Invalid URL, and couldn't generate a search URL for it.") return } return self.homePanel(homePanel, didSelectURL: url, visitType: visitType) } func homePanel(_ homePanel: HomePanel, didSelectURL url: URL, visitType: VisitType) { delegate?.homePanelViewController(self, didSelectURL: url, visitType: visitType) dismiss(animated: true, completion: nil) } func homePanelDidRequestToCreateAccount(_ homePanel: HomePanel) { delegate?.homePanelViewControllerDidRequestToCreateAccount(self) } func homePanelDidRequestToSignIn(_ homePanel: HomePanel) { delegate?.homePanelViewControllerDidRequestToSignIn(self) } func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) { delegate?.homePanelViewControllerDidRequestToOpenInNewTab(url, isPrivate: isPrivate) } } // MARK: UIAppearance extension HomePanelViewController: Themeable { func applyTheme(_ theme: Theme) { buttonContainerView.backgroundColor = UIColor.HomePanel.ToolbarBackground.colorFor(theme) view.backgroundColor = UIColor.HomePanel.ToolbarBackground.colorFor(theme) buttonTintColor = UIColor.HomePanel.ToolbarTint.colorFor(theme) buttonSelectedTintColor = UIColor.HomePanel.ToolbarHighlight.colorFor(theme) highlightLine.backgroundColor = UIColor.HomePanel.ToolbarHighlight.colorFor(theme) updateButtonTints() } } protocol HomePanelContextMenu { func getSiteDetails(for indexPath: IndexPath) -> Site? func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? func presentContextMenu(for indexPath: IndexPath) func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) } extension HomePanelContextMenu { func presentContextMenu(for indexPath: IndexPath) { guard let site = getSiteDetails(for: indexPath) else { return } presentContextMenu(for: site, with: indexPath, completionHandler: { return self.contextMenu(for: site, with: indexPath) }) } func contextMenu(for site: Site, with indexPath: IndexPath) -> PhotonActionSheet? { guard let actions = self.getContextMenuActions(for: site, with: indexPath) else { return nil } let contextMenu = PhotonActionSheet(site: site, actions: actions) contextMenu.modalPresentationStyle = .overFullScreen contextMenu.modalTransitionStyle = .crossDissolve return contextMenu } func getDefaultContextMenuActions(for site: Site, homePanelDelegate: HomePanelDelegate?) -> [PhotonActionSheetItem]? { guard let siteURL = URL(string: site.url) else { return nil } let openInNewTabAction = PhotonActionSheetItem(title: Strings.OpenInNewTabContextMenuTitle, iconString: "quick_action_new_tab") { action in homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false) } let openInNewPrivateTabAction = PhotonActionSheetItem(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "quick_action_new_private_tab") { action in homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true) } return [openInNewTabAction, openInNewPrivateTabAction] } }
mpl-2.0
3773ef65055184a1ba0387f17aeb8465
42.766764
243
0.692246
5.74732
false
false
false
false
as767439266/DouYuZG
DouYuZG/DouYuZG/Classes/Home/Controller/HomeViewController.swift
1
3801
// // HomeViewController.swift // DouYuZG // // Created by 蒋学超 on 16/9/22. // Copyright © 2016年 JiangXC. All rights reserved. // import UIKit private let kTitleViewH : CGFloat = 40 class HomeViewController: UIViewController { // MARK : 懒加载 lazy var pageTitleView : PageTitleView = { [weak self] in let titleFrame = CGRect(x: 0, y: kNavgationBarH+kStatusBar, width: kScreenW, height: kTitleViewH) let titles = ["推荐", "游戏", "娱乐", "趣玩"] let pageTitleView = PageTitleView(frame: titleFrame, titles: titles) // pageTitleView.backgroundColor = UIColor.yellow pageTitleView.delegate = self as PageTitleViewDelegate? return pageTitleView }() lazy var pageContentView : PageContentView = {[weak self] in // 1.确定内容的frame let contentH = kScreenH - kStatusBar - kNavgationBarH - kTitleViewH - kTabbarH let contentFrame = CGRect(x: 0, y: kStatusBar + kNavgationBarH + kTitleViewH, width: kScreenW, height: contentH) // 2.确定所有的子控制器 var childVcs = [UIViewController]() let recommendVc = RecommendViewController() childVcs.append(recommendVc) for _ in 0..<3 { let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) childVcs.append(vc) } let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self) contentView.delegate = self as PageContentViewDelegate? return contentView }() override func viewDidLoad() { super.viewDidLoad() //设置UI 界面 setupUI() } } //MARK : 设置UI界面 extension HomeViewController{ func setupUI(){ // 0.不需要调整UIScrollView的内边距 automaticallyAdjustsScrollViewInsets = false //1 添加导航栏 setupNavBar() //2 添加 TitleView view.addSubview(pageTitleView) // 3.添加ContentView view.addSubview(pageContentView) } private func setupNavBar(){ //设置左侧item navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") //设置右侧的item let size = CGSize(width: 40, height: 40) //历史 //类方法 // let historyItem = UIBarButtonItem.createIetm(imageName: "image_my_history", hightImage: "Image_my_history_click", size: size) //构造方法 苹果推荐使用 let historyItem = UIBarButtonItem(imageName: "image_my_history", hightImage: "Image_my_history_click", size: size) //搜索 let searchItem = UIBarButtonItem(imageName: "btn_search", hightImage: "btn_search_clicked", size: size) //二维码 let qrcodeBtnItem = UIBarButtonItem(imageName: "Image_scan", hightImage: "Image_scan_click", size: size) navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeBtnItem] } } //MARK:-遵守PageTitleViewDelegate协议 extension HomeViewController : PageTitleViewDelegate{ func pageTitleView(titleView: PageTitleView, selectedIndex index: Int) { pageContentView.setCurrentIndex(currentIndex: index) } } //MARK:遵守pageContentViewDelegate协议 extension HomeViewController:PageContentViewDelegate{ func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
mit
cef24ca0026afdc000393cf721958090
34.106796
156
0.651549
4.873315
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Domains/Domain registration/RegisterDomainDetails/ViewController/RegisterDomainDetailsViewController.swift
1
14840
import UIKit import WordPressAuthenticator import WordPressEditor class RegisterDomainDetailsViewController: UITableViewController { typealias Localized = RegisterDomainDetails.Localized typealias SectionIndex = RegisterDomainDetailsViewModel.SectionIndex typealias EditableKeyValueRow = RegisterDomainDetailsViewModel.Row.EditableKeyValueRow typealias CheckMarkRow = RegisterDomainDetailsViewModel.Row.CheckMarkRow typealias Context = RegisterDomainDetailsViewModel.ValidationRule.Context typealias CellIndex = RegisterDomainDetailsViewModel.CellIndex enum Constants { static let estimatedRowHeight: CGFloat = 62 static let buttonContainerHeight: CGFloat = 84 } var viewModel: RegisterDomainDetailsViewModel! private var selectedItemIndex: [IndexPath: Int] = [:] private(set) lazy var footerView: RegisterDomainDetailsFooterView = { let buttonView = RegisterDomainDetailsFooterView.loadFromNib() buttonView.translatesAutoresizingMaskIntoConstraints = false buttonView.submitButton.isEnabled = false buttonView.submitButton.addTarget( self, action: #selector(registerDomainButtonTapped(sender:)), for: .touchUpInside ) buttonView.submitButton.setTitle(Localized.buttonTitle, for: .normal) return buttonView }() init() { super.init(style: .grouped) } //Overriding this to be able to implement the empty init() otherwise compile error occurs required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() configureView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // This form is only used to redeem an existing domain credit WPAnalytics.track(.domainsRegistrationFormViewed, properties: WPAnalytics.domainsProperties(usingCredit: true)) } private func configureView() { title = NSLocalizedString("Register domain", comment: "Title for the Register domain screen") configureTableView() WPStyleGuide.configureColors(view: view, tableView: tableView) viewModel.onChange = { [weak self] (change) in self?.handle(change: change) } viewModel.prefill() setupEditingEndingTapGestureRecognizer() } private func configureTableView() { configureTableFooterView() tableView.register( UINib(nibName: RegisterDomainSectionHeaderView.identifier, bundle: nil), forHeaderFooterViewReuseIdentifier: RegisterDomainSectionHeaderView.identifier ) tableView.register( UINib(nibName: EpilogueSectionHeaderFooter.identifier, bundle: nil), forHeaderFooterViewReuseIdentifier: EpilogueSectionHeaderFooter.identifier ) tableView.register( RegisterDomainDetailsErrorSectionFooter.defaultNib, forHeaderFooterViewReuseIdentifier: RegisterDomainDetailsErrorSectionFooter.defaultReuseID ) tableView.register( InlineEditableNameValueCell.defaultNib, forCellReuseIdentifier: InlineEditableNameValueCell.defaultReuseID ) tableView.register( WPTableViewCellDefault.self, forCellReuseIdentifier: WPTableViewCellDefault.defaultReuseID ) tableView.estimatedRowHeight = Constants.estimatedRowHeight tableView.estimatedSectionHeaderHeight = Constants.estimatedRowHeight tableView.sectionHeaderHeight = UITableView.automaticDimension tableView.estimatedSectionFooterHeight = Constants.estimatedRowHeight tableView.sectionFooterHeight = UITableView.automaticDimension tableView.cellLayoutMarginsFollowReadableWidth = false tableView.reloadData() } private func showAlert(title: String? = nil, message: String) { let alertCancel = NSLocalizedString( "OK", comment: "Title of an OK button. Pressing the button acknowledges and dismisses a prompt." ) let alertController = UIAlertController( title: title, message: message, preferredStyle: .alert ) alertController.addCancelActionWithTitle(alertCancel, handler: nil) present(alertController, animated: true, completion: nil) } /// Sets up a gesture recognizer to make tap gesture close the keyboard private func setupEditingEndingTapGestureRecognizer() { let gestureRecognizer = UITapGestureRecognizer() gestureRecognizer.cancelsTouchesInView = false gestureRecognizer.on { [weak self] (gesture) in self?.view.endEditing(true) } view.addGestureRecognizer(gestureRecognizer) } private func handle(change: RegisterDomainDetailsViewModel.Change) { switch change { case let .formValidated(context, isValid): switch context { case .clientSide: footerView.submitButton.isEnabled = isValid default: break } break case .addNewAddressLineEnabled(let indexPath): tableView.insertRows(at: [indexPath], with: .none) case .addNewAddressLineReplaced(let indexPath): tableView.reloadRows(at: [indexPath], with: .none) case .checkMarkRowsUpdated: tableView.reloadData() case .registerSucceeded(let domain): dismiss(animated: true) { [weak self] in self?.viewModel.domainPurchasedCallback(domain) } case .unexpectedError(let message): showAlert(message: message) case .loading(let isLoading): if isLoading { footerView.submitButton.isEnabled = false SVProgressHUD.setDefaultMaskType(.clear) SVProgressHUD.show() } else { footerView.submitButton.isEnabled = true SVProgressHUD.dismiss() } case .prefillSuccess: tableView.reloadData() case .prefillError(let message): showAlert(message: message) case .multipleChoiceRowValueChanged(let indexPath): tableView.reloadRows(at: [indexPath], with: .none) case .remoteValidationFinished: tableView.reloadData() default: break } } } // MARK: - Actions extension RegisterDomainDetailsViewController { @objc private func registerDomainButtonTapped(sender: UIButton) { WPAnalytics.track(.domainsRegistrationFormSubmitted, properties: WPAnalytics.domainsProperties(usingCredit: true)) viewModel.register() } @objc func handleTermsAndConditionsTap(_ sender: UITapGestureRecognizer) { UIApplication.shared.open(URL(string: WPAutomatticTermsOfServiceURL)!, options: [:], completionHandler: nil) } } // MARK: - InlineEditableNameValueCellDelegate extension RegisterDomainDetailsViewController: InlineEditableNameValueCellDelegate { func inlineEditableNameValueCell(_ cell: InlineEditableNameValueCell, valueTextFieldDidChange text: String) { guard let indexPath = tableView.indexPath(for: cell), let sectionType = SectionIndex(rawValue: indexPath.section) else { return } viewModel.updateValue(text, at: indexPath) if sectionType == .address, viewModel.addressSectionIndexHelper.addressField(for: indexPath.row) == .addressLine1, indexPath.row == viewModel.addressSectionIndexHelper.extraAddressLineCount, text.isEmpty == false { viewModel.enableAddAddressRow() } } func inlineEditableNameValueCell(_ cell: InlineEditableNameValueCell, valueTextFieldEditingDidEnd text: String) { inlineEditableNameValueCell(cell, valueTextFieldDidChange: text) } func inlineEditableNameValueCell(_ cell: InlineEditableNameValueCell, valueTextFieldShouldReturn textField: UITextField) -> Bool { guard let indexPath = tableView.indexPath(for: cell) else { return false } let nextSection = indexPath.section + 1 let nextRow = indexPath.row + 1 // If there's an enabled editable row next in this section then select it, otherwise check the next section if tableView.numberOfRows(inSection: indexPath.section) > nextRow, let nextCell = tableView.cellForRow(at: IndexPath(row: nextRow, section: indexPath.section)) as? InlineEditableNameValueCell, nextCell.valueTextField.isEnabled { nextCell.valueTextField.becomeFirstResponder() } else if tableView.numberOfSections > nextSection, let nextCell = tableView.cellForRow(at: IndexPath(row: indexPath.row, section: nextSection)) as? InlineEditableNameValueCell, nextCell.valueTextField.isEnabled { nextCell.valueTextField.becomeFirstResponder() } else { textField.resignFirstResponder() } return true } } // MARK: - UITableViewDelegate extension RegisterDomainDetailsViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let sectionType = SectionIndex(rawValue: indexPath.section) else { return } switch sectionType { case .privacyProtection: viewModel.updateValue(true, at: indexPath) case .contactInformation: guard let field = CellIndex.ContactInformation(rawValue: indexPath.row) else { return } switch field { case .country: if viewModel.countryNames.count > 0 { showItemSelectionPage(onSelectionAt: indexPath, title: Localized.ContactInformation.country, items: viewModel.countryNames) } default: break } case .address: let addressField = viewModel.addressSectionIndexHelper.addressField(for: indexPath.row) switch addressField { case .addNewAddressLine: viewModel.replaceAddNewAddressLine() case .state: if viewModel.stateNames.count > 0 { showItemSelectionPage(onSelectionAt: indexPath, title: Localized.Address.state, items: viewModel.stateNames) } default: break } case .phone: break } } private func showItemSelectionPage(onSelectionAt indexPath: IndexPath, title: String, items: [String]) { var options: [OptionsTableViewOption] = [] for item in items { let attributedItem = NSAttributedString.init( string: item, attributes: [.font: WPStyleGuide.tableviewTextFont(), .foregroundColor: UIColor.text] ) let option = OptionsTableViewOption( image: nil, title: attributedItem, accessibilityLabel: nil) options.append(option) } let viewController = OptionsTableViewController(options: options) viewController.cellBackgroundColor = .listForeground if let selectedIndex = selectedItemIndex[indexPath] { viewController.selectRow(at: selectedIndex) } viewController.title = title viewController.onSelect = { [weak self] (index) in self?.navigationController?.popViewController(animated: true) self?.selectedItemIndex[indexPath] = index if let section = SectionIndex(rawValue: indexPath.section) { switch section { case .address: self?.viewModel.selectState(at: index) case .contactInformation: self?.viewModel.selectCountry(at: index) default: break } } } navigationController?.pushViewController(viewController, animated: true) } } // MARK: - UITableViewDatasource extension RegisterDomainDetailsViewController { override func numberOfSections(in tableView: UITableView) -> Int { return viewModel.sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.sections[section].rows.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let rowType = viewModel.sections[indexPath.section].rows[indexPath.row] switch rowType { case .checkMark(let checkMarkRow): return checkMarkCell(with: checkMarkRow) case .inlineEditable(let editableRow): return editableKeyValueCell(with: editableRow, indexPath: indexPath) case .addAddressLine(let title): return addAdddressLineCell(with: title) } } // MARK: Section Header Footer open override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard let sectionType = SectionIndex(rawValue: section) else { return nil } switch sectionType { case .privacyProtection: return privacyProtectionSectionFooter() default: return errorShowingSectionFooter(section: section) } } open override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let sectionType = SectionIndex(rawValue: section) else { return nil } switch sectionType { case .privacyProtection: return privacyProtectionSectionHeader() case .contactInformation: return contactInformationSectionHeader() default: break } return nil } open override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard let sectionType = SectionIndex(rawValue: section) else { return nil } switch sectionType { case .address: return Localized.Address.headerTitle case .phone: return Localized.PhoneNumber.headerTitle default: break } return nil } }
gpl-2.0
cacca29d68636694d400d1b523397d2a
36.007481
137
0.644003
5.998383
false
false
false
false
chinlam91/edx-app-ios
Source/OEXAnalytics+Swift.swift
4
931
// // OEXAnalytics+Swift.swift // edX // // Created by Akiva Leffert on 9/15/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation extension OEXAnalytics { func trackOutlineModeChanged(mode : CourseOutlineMode) { let event = OEXAnalyticsEvent() event.name = OEXAnalyticsEventOutlineModeChanged event.displayName = "Switch outline mode" event.category = OEXAnalyticsCategoryNavigation let modeValue : String switch mode { case .Full: modeValue = OEXAnalyticsValueNavigationModeFull event.label = "Switch to Full Mode" case .Video: modeValue = OEXAnalyticsValueNavigationModeVideo event.label = "Switch to Video Mode" } let info = [OEXAnalyticsKeyNavigationMode : modeValue] self.trackEvent(event, forComponent: nil, withInfo: info) } }
apache-2.0
20bf51b83605625bcbedd8d5c05c49ed
27.242424
65
0.639098
4.9
false
false
false
false
tonystone/tracelog
Sources/TraceLog/Writers/FileStrategy+Rotate.swift
1
6524
/// /// FileStrategyRotate.swift /// /// Copyright 2019 Tony Stone /// /// 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. /// /// Created by Tony Stone on 2/1/19. /// import CoreFoundation import Foundation @available(iOSApplicationExtension, unavailable) internal class FileStrategyRotate: FileStrategyManager { /// The current url in use or if none open yet, the one that will be used. /// var url: URL { return self.stream.url } /// Initialize the FileStrategy with the directory for files, the template for /// file naming, and the options for rotation. /// /// - Parameters: /// - directory: The directory URL that the strategy will write files to. /// - template: The naming template to use for naming files. /// - options: The rotation options to use for file rotation. /// init(directory: URL, template: String, options: Set<FileWriter.Strategy.RotationOption>) throws { var rotate: (onStartup: Bool, maxSize: UInt64?) = (false, nil) for option in options { switch option { case .startup: rotate.onStartup = true case .maxSize(let maxSize): rotate.maxSize = maxSize } } let fileStreamManager = FileStreamManager(directory: directory, template: template) /// Open the file for writing. self.stream = rotate.onStartup ? try fileStreamManager.openNewFileStream() : try fileStreamManager.openLatestFileStream() self.fileStreamManager = fileStreamManager self.rotate = rotate self.mutex = Mutex(.normal) } /// Required implementation for FileStrategyManager classes. /// func write(_ bytes: [UInt8]) -> Result<Int, FailureReason> { /// Note: Since we could be called on any thread in TraceLog direct mode /// we protect the file with a low-level mutex. /// /// PThreads mutexes were chosen because out of all the methods of synchronization /// available in swift (queue, dispatch semaphores, etc), PThread mutexes are /// the lowest overhead and fastest lock. /// /// We also want to ensure we maintain thread boundaries when in direct mode (avoid /// jumping threads). /// mutex.lock(); defer { mutex.unlock() } /// Does the file need to be rotated? if let maxSize = self.rotate.maxSize, self.stream.position + UInt64(bytes.count) >= maxSize { do { /// Open the new file first so that if we get an error, we can leave the old stream as is let newStream = try fileStreamManager.openNewFileStream() self.stream.close() self.stream = newStream } catch { return .failure(.error(error)) } } return self.stream.write(bytes).mapError({ self.failureReason($0) }) } /// Rotation options. /// private let rotate: (onStartup: Bool, maxSize: UInt64?) /// File configuration for naming file. /// private let fileStreamManager: FileStreamManager /// The outputStream to use for writing. /// private var stream: FileOutputStream /// Low level mutex for locking print since it's not reentrant. /// private let mutex: Mutex } /// Represents log file configuration settings /// internal /* @testable */ struct FileStreamManager: Equatable { internal init(directory: URL, template: String) { self.directory = directory self.nameFormatter = DateFormatter() self.nameFormatter.dateFormat = template let metaDirectory = directory.appendingPathComponent(".tracelog", isDirectory: true) self.metaDirectory = metaDirectory self.metaFile = metaDirectory.appendingPathComponent("filewriter.meta", isDirectory: false) } /// Open the output stream creating the meta file when created /// internal func openNewFileStream() throws -> FileOutputStream { let newURL = self.newFileURL() try writeMetaFile(for: newURL) return try FileOutputStream(url: newURL, options: [.create]) } /// Find the latest log file by creation date that exists. /// /// - Returns: a URL if there is an existing file otherwise, nil. /// internal func openLatestFileStream() throws -> FileOutputStream { let latestURL = latestFileURL() try writeMetaFile(for: latestURL) return try FileOutputStream(url: latestURL, options: [.create]) } /// Create a file URL based on the files configuration. /// internal /* @testable */ func newFileURL() -> URL { return self.directory.appendingPathComponent(self.nameFormatter.string(from: Date())) } /// Find the latest log file by creation date that exists. /// /// - Returns: a URL if there is an existing file otherwise, nil. /// internal /* @testable */ func latestFileURL() -> URL { guard let latestPath = try? String(contentsOf: self.metaFile, encoding: .utf8) else { return self.newFileURL() } return URL(fileURLWithPath: latestPath, isDirectory: false) } /// Writes a meta file out for the url passed. /// private func writeMetaFile(for url: URL) throws { /// Write the file that contains the last path. do { if !FileManager.default.fileExists(atPath: self.metaDirectory.path) { try FileManager.default.createDirectory(at: self.metaDirectory, withIntermediateDirectories: true) } try url.path.write(to: self.metaFile, atomically: false, encoding: .utf8) } catch { throw FileOutputStreamError.unknownError(0, error.localizedDescription) } } private let directory: URL private var metaDirectory: URL private var metaFile: URL private let nameFormatter: DateFormatter }
apache-2.0
4faadcc8434991cd9afb59f9eb8435e9
33.336842
129
0.641478
4.686782
false
true
false
false
amuramoto/realm-objc
Realm/Tests/Swift/SwiftArrayTests.swift
1
13001
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import TestFramework class SwiftArrayTests: RLMTestCase { func testFastEnumeration() { let realm = realmWithTestPath() realm.beginWriteTransaction() let dateMinInput = NSDate() let dateMaxInput = dateMinInput.dateByAddingTimeInterval(1000) AggregateObject.createInRealm(realm, withObject: [10, 1.2 as Float, 0 as Double, true, dateMinInput]) AggregateObject.createInRealm(realm, withObject: [10, 0 as Float, 2.5 as Double, false, dateMaxInput]) AggregateObject.createInRealm(realm, withObject: [10, 1.2 as Float, 0 as Double, true, dateMinInput]) AggregateObject.createInRealm(realm, withObject: [10, 0 as Float, 2.5 as Double, false, dateMaxInput]) AggregateObject.createInRealm(realm, withObject: [10, 1.2 as Float, 0 as Double, true, dateMinInput]) AggregateObject.createInRealm(realm, withObject: [10, 0 as Float, 2.5 as Double, false, dateMaxInput]) AggregateObject.createInRealm(realm, withObject: [10, 1.2 as Float, 0 as Double, true, dateMinInput]) AggregateObject.createInRealm(realm, withObject: [10, 0 as Float, 2.5 as Double, false, dateMaxInput]) AggregateObject.createInRealm(realm, withObject: [10, 1.2 as Float, 0 as Double, true, dateMinInput]) AggregateObject.createInRealm(realm, withObject: [10, 1.2 as Float, 0 as Double, true, dateMinInput]) realm.commitWriteTransaction() let result = AggregateObject.objectsInRealm(realm, withPredicate: NSPredicate(format: "intCol < \(100)")) XCTAssertEqual(result.count, 10, "10 objects added") var totalSum: CInt = 0 // FIXME: Support Sequence-style enumeration for idx in 0..<result.count { if let ao = result[idx] as? AggregateObject { totalSum += ao.intCol } } XCTAssertEqual(totalSum, 100, "total sum should be 100") } func testReadOnly() { let realm = realmWithTestPath() realm.beginWriteTransaction() let obj = StringObject.createInRealm(realm, withObject: ["name"]) realm.commitWriteTransaction() let array = StringObject.allObjectsInRealm(realm) XCTAssertTrue(array.readOnly, "Array returned from query should be readonly") } func testObjectAggregate() { let realm = realmWithTestPath() realm.beginWriteTransaction() let dateMinInput = NSDate() let dateMaxInput = dateMinInput.dateByAddingTimeInterval(1000) AggregateObject.createInRealm(realm, withObject: [0, 1.2 as Float, 0 as Double, true, dateMinInput]) AggregateObject.createInRealm(realm, withObject: [1, 0 as Float, 2.5 as Double, false, dateMaxInput]) AggregateObject.createInRealm(realm, withObject: [0, 1.2 as Float, 0 as Double, true, dateMinInput]) AggregateObject.createInRealm(realm, withObject: [1, 0 as Float, 2.5 as Double, false, dateMaxInput]) AggregateObject.createInRealm(realm, withObject: [0, 1.2 as Float, 0 as Double, true, dateMinInput]) AggregateObject.createInRealm(realm, withObject: [1, 0 as Float, 2.5 as Double, false, dateMaxInput]) AggregateObject.createInRealm(realm, withObject: [0, 1.2 as Float, 0 as Double, true, dateMinInput]) AggregateObject.createInRealm(realm, withObject: [1, 0 as Float, 2.5 as Double, false, dateMaxInput]) AggregateObject.createInRealm(realm, withObject: [0, 1.2 as Float, 0 as Double, true, dateMinInput]) AggregateObject.createInRealm(realm, withObject: [0, 1.2 as Float, 0 as Double, true, dateMinInput]) realm.commitWriteTransaction() let noArray = AggregateObject.objectsInRealm(realm, withPredicate: NSPredicate(format: "boolCol == NO")) let yesArray = AggregateObject.objectsInRealm(realm, withPredicate: NSPredicate(format: "boolCol == YES")) // SUM :::::::::::::::::::::::::::::::::::::::::::::: // Test int sum XCTAssertEqual(noArray.sumOfProperty("intCol").integerValue, 4, "Sum should be 4") XCTAssertEqual(yesArray.sumOfProperty("intCol").integerValue, 0, "Sum should be 0") // Test float sum XCTAssertEqualWithAccuracy(noArray.sumOfProperty("floatCol").floatValue, 0, 0.1, "Sum should be 0.0") XCTAssertEqualWithAccuracy(yesArray.sumOfProperty("floatCol").floatValue, 7.2, 0.1, "Sum should be 7.2") // Test double sum XCTAssertEqualWithAccuracy(noArray.sumOfProperty("doubleCol").doubleValue, 10, 0.1, "Sum should be 10.0") XCTAssertEqualWithAccuracy(yesArray.sumOfProperty("doubleCol").doubleValue, 0, 0.1, "Sum should be 0.0") // Average :::::::::::::::::::::::::::::::::::::::::::::: // Test int average XCTAssertEqualWithAccuracy(noArray.averageOfProperty("intCol").doubleValue, 1, 0.1, "Average should be 1.0") XCTAssertEqualWithAccuracy(yesArray.averageOfProperty("intCol").doubleValue, 0, 0.1, "Average should be 0.0") // Test float average XCTAssertEqualWithAccuracy(noArray.averageOfProperty("floatCol").doubleValue, 0, 0.1, "Average should be 0.0") XCTAssertEqualWithAccuracy(yesArray.averageOfProperty("floatCol").doubleValue, 1.2, 0.1, "Average should be 1.2") // Test double average XCTAssertEqualWithAccuracy(noArray.averageOfProperty("doubleCol").doubleValue, 2.5, 0.1, "Average should be 2.5") XCTAssertEqualWithAccuracy(yesArray.averageOfProperty("doubleCol").doubleValue, 0, 0.1, "Average should be 0.0") // MIN :::::::::::::::::::::::::::::::::::::::::::::: // Test int min var min = noArray.minOfProperty("intCol") as NSNumber XCTAssertEqual(min.intValue, 1, "Minimum should be 1") min = yesArray.minOfProperty("intCol") as NSNumber XCTAssertEqual(min.intValue, 0, "Minimum should be 0") // Test float min min = noArray.minOfProperty("floatCol") as NSNumber XCTAssertEqualWithAccuracy(min.floatValue, 0, 0.1, "Minimum should be 0.0f") min = yesArray.minOfProperty("floatCol") as NSNumber XCTAssertEqualWithAccuracy(min.floatValue, 1.2, 0.1, "Minimum should be 1.2f") // Test double min min = noArray.minOfProperty("doubleCol") as NSNumber XCTAssertEqualWithAccuracy(min.doubleValue, 2.5, 0.1, "Minimum should be 1.5") min = yesArray.minOfProperty("doubleCol") as NSNumber XCTAssertEqualWithAccuracy(min.doubleValue, 0, 0.1, "Minimum should be 0.0") // Test date min var dateMinOutput = noArray.minOfProperty("dateCol") as NSDate XCTAssertEqualWithAccuracy(dateMinOutput.timeIntervalSince1970, dateMaxInput.timeIntervalSince1970, 1, "Minimum should be dateMaxInput") dateMinOutput = yesArray.minOfProperty("dateCol") as NSDate XCTAssertEqualWithAccuracy(dateMinOutput.timeIntervalSince1970, dateMinInput.timeIntervalSince1970, 1, "Minimum should be dateMinInput") // MAX :::::::::::::::::::::::::::::::::::::::::::::: // Test int max var max = noArray.maxOfProperty("intCol") as NSNumber XCTAssertEqual(max.integerValue, 1, "Maximum should be 8") max = yesArray.maxOfProperty("intCol") as NSNumber XCTAssertEqual(max.integerValue, 0, "Maximum should be 10") // Test float max max = noArray.maxOfProperty("floatCol") as NSNumber XCTAssertEqualWithAccuracy(max.floatValue, 0, 0.1, "Maximum should be 0.0f") max = yesArray.maxOfProperty("floatCol") as NSNumber XCTAssertEqualWithAccuracy(max.floatValue, 1.2, 0.1, "Maximum should be 1.2f") // Test double max max = noArray.maxOfProperty("doubleCol") as NSNumber XCTAssertEqualWithAccuracy(max.doubleValue, 2.5, 0.1, "Maximum should be 3.5") max = yesArray.maxOfProperty("doubleCol") as NSNumber XCTAssertEqualWithAccuracy(max.doubleValue, 0, 0.1, "Maximum should be 0.0") // Test date max var dateMaxOutput = noArray.maxOfProperty("dateCol") as NSDate XCTAssertEqualWithAccuracy(dateMaxOutput.timeIntervalSince1970, dateMaxInput.timeIntervalSince1970, 1, "Maximum should be dateMaxInput") dateMaxOutput = yesArray.maxOfProperty("dateCol") as NSDate XCTAssertEqualWithAccuracy(dateMaxOutput.timeIntervalSince1970, dateMinInput.timeIntervalSince1970, 1, "Maximum should be dateMinInput") } func testArrayDescription() { let realm = realmWithTestPath() realm.beginWriteTransaction() for i in 0..<1012 { let person = EmployeeObject() person.name = "Mary" person.age = 24 person.hired = true realm.addObject(person) } realm.commitWriteTransaction() let description = EmployeeObject.allObjectsInRealm(realm).description XCTAssertTrue((description as NSString).rangeOfString("name").location != Foundation.NSNotFound, "property names should be displayed when calling \"description\" on RLMArray") XCTAssertTrue((description as NSString).rangeOfString("Mary").location != Foundation.NSNotFound, "property values should be displayed when calling \"description\" on RLMArray") XCTAssertTrue((description as NSString).rangeOfString("age").location != Foundation.NSNotFound, "property names should be displayed when calling \"description\" on RLMArray") XCTAssertTrue((description as NSString).rangeOfString("24").location != Foundation.NSNotFound, "property values should be displayed when calling \"description\" on RLMArray") XCTAssertTrue((description as NSString).rangeOfString("12 objects skipped").location != Foundation.NSNotFound, "'12 objects skipped' should be displayed when calling \"description\" on RLMArray") } func testDeleteLinksAndObjectsInArray() { let realm = realmWithTestPath() realm.beginWriteTransaction() let po1 = EmployeeObject() po1.age = 40 po1.name = "Joe" po1.hired = true let po2 = EmployeeObject() po2.age = 30 po2.name = "John" po2.hired = false let po3 = EmployeeObject() po3.age = 25 po3.name = "Jill" po3.hired = true realm.addObject(po1) realm.addObject(po2) realm.addObject(po3) let company = CompanyObject() company.employees = EmployeeObject.allObjectsInRealm(realm) realm.addObject(company) realm.commitWriteTransaction() let peopleInCompany = company.employees XCTAssertEqual(peopleInCompany.count, 3, "No links should have been deleted") realm.beginWriteTransaction() peopleInCompany.removeObjectAtIndex(1) // Should delete link to employee realm.commitWriteTransaction() XCTAssertEqual(peopleInCompany.count, 2, "link deleted when accessing via links") var test = peopleInCompany[0] as EmployeeObject XCTAssertEqual(test.age, po1.age, "Should be equal") XCTAssertEqualObjects(test.name, po1.name, "Should be equal") XCTAssertEqual(test.hired, po1.hired, "Should be equal") // XCTAssertEqualObjects(test, po1, "Should be equal") //FIXME, should work. Asana : https://app.asana.com/0/861870036984/13123030433568 test = peopleInCompany[1] as EmployeeObject XCTAssertEqual(test.age, po3.age, "Should be equal") XCTAssertEqualObjects(test.name, po3.name, "Should be equal") XCTAssertEqual(test.hired, po3.hired, "Should be equal") // XCTAssertEqualObjects(test, po3, "Should be equal") //FIXME, should work. Asana : https://app.asana.com/0/861870036984/13123030433568 let allPeople = EmployeeObject.allObjectsInRealm(realm) XCTAssertEqual(allPeople.count, 3, "Only links should have been deleted, not the employees") } }
apache-2.0
51a099578b02b9347ea7ba6fc9acc1d1
50.59127
203
0.654411
4.553765
false
true
false
false
Gaea-iOS/FoundationExtension
FoundationExtension/Classes/Foundation/NetworkStatus.swift
1
2172
//// //// NetworkStatus.swift //// Pods //// //// Created by 王小涛 on 2017/8/17. //// //// // //import CoreTelephony //import ReachabilitySwift // //public class NetworkStatus { // // private let reachability: Reachability? // // public init() { // self.reachability = Reachability() // } // // public init(hostname: String) { // self.reachability = Reachability(hostname: hostname) // } // // // public enum NetworkConnectionType { // case unknow // case wifi // case cellular2G // case cellular3G // case cellular4G // case notReachable // } // // public var currentNetworkStatus: NetworkConnectionType { // // guard let status = reachability?.currentReachabilityStatus else { // return .unknow // } // // switch status { // case .reachableViaWiFi: // return .wifi // case .reachableViaWWAN: // return currentCellularNetworkStatus // case .notReachable: // return .notReachable // } // } // // private var currentCellularNetworkStatus: NetworkConnectionType { // // let networkStatus = CTTelephonyNetworkInfo() // let currentStatus = networkStatus.currentRadioAccessTechnology // // if currentStatus == CTRadioAccessTechnologyGPRS // || currentStatus == CTRadioAccessTechnologyEdge { // return .cellular2G // } // // if currentStatus == CTRadioAccessTechnologyWCDMA // || currentStatus == CTRadioAccessTechnologyHSDPA // || currentStatus == CTRadioAccessTechnologyHSUPA // || currentStatus == CTRadioAccessTechnologyCDMA1x // || currentStatus == CTRadioAccessTechnologyCDMAEVDORev0 // || currentStatus == CTRadioAccessTechnologyCDMAEVDORevA // || currentStatus == CTRadioAccessTechnologyCDMAEVDORevB // || currentStatus == CTRadioAccessTechnologyeHRPD { // return .cellular3G; // } // // if currentStatus == CTRadioAccessTechnologyLTE { // return .cellular4G // } // // return .unknow // } //} //
mit
af8d8f332fe8f0caaade1622bffaa030
26.769231
75
0.596491
4.5125
false
false
false
false
mibaldi/IOS_MIMO_APP
iosAPP/models/Ingredient.swift
1
2022
// // Ingredient.swift // iosAPP // // Created by mikel balduciel diaz on 17/2/16. // Copyright © 2016 mikel balduciel diaz. All rights reserved. // import Foundation enum FrozenTypes: Int64{ case frozen = 1 case noFrozen = 0 } class Ingredient : NSObject { var ingredientId = Int64() var ingredientIdServer = Int64() var name = String () var baseType = String() var category = String() var frozen = FrozenTypes.noFrozen var storageId = Int64() var cartId = Int64() var measure = String() var quantity = Double() static func addIngredientStorage(ingredient: Ingredient) throws -> Void{ ingredient.storageId = 1 try IngredientDataHelper.insert(ingredient) } static func updateIngredientStorage(ingredient: Ingredient) throws -> Void{ ingredient.storageId = 1 try IngredientDataHelper.updateStorage(ingredient) } static func deleteIngredientStorage(ingredient: Ingredient) throws -> Void{ ingredient.storageId = 0 try IngredientDataHelper.updateStorage(ingredient) } static func addIngredientCart(ingredient: Ingredient) throws -> Void{ ingredient.cartId = 1 try IngredientDataHelper.insert(ingredient) } static func updateIngredientCart(ingredient: Ingredient) throws -> Void{ ingredient.cartId = 1 try IngredientDataHelper.updateCart(ingredient) } static func deleteIngredientCart(ingredient: Ingredient) throws -> Void{ ingredient.cartId = 0 try IngredientDataHelper.updateCart(ingredient) } static func stringIngredientsIds(ingredients :[Ingredient]) -> String { var ingredientesString = "0" if ingredients.count != 0{ for ing in ingredients { let io = ing let id = String(io.ingredientIdServer) ingredientesString += id + ","; } } return ingredientesString } }
apache-2.0
2718317e4843131b24827f751eaa4625
28.289855
79
0.643741
4.53139
false
false
false
false
openHPI/xikolo-ios
iOS/Extensions/NSDirectionalEdgeInsets+custom.swift
1
3692
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import UIKit extension NSDirectionalEdgeInsets { static func customInsets(for viewController: UIViewController) -> NSDirectionalEdgeInsets { return self.customInsets(for: viewController.view, traitCollection: viewController.traitCollection, minimumInsets: viewController.systemMinimumLayoutMargins) } static func customInsets( for view: UIView, traitCollection: UITraitCollection, minimumInsets: NSDirectionalEdgeInsets = .zero ) -> NSDirectionalEdgeInsets { var minimumLeadingInset = minimumInsets.leading var minimumTrailingInset = minimumInsets.trailing if traitCollection.horizontalSizeClass == .regular && UIDevice.current.userInterfaceIdiom == .pad { minimumLeadingInset = max(48, minimumLeadingInset) minimumTrailingInset = max(48, minimumTrailingInset) } let minimumInsets = NSDirectionalEdgeInsets(top: 0, leading: minimumLeadingInset, bottom: 0, trailing: minimumTrailingInset) return self.insets(for: view.bounds.size, traitCollection: traitCollection, factor: 0.5, minimumInsets: minimumInsets) } static func readableContentInsets(for viewController: UIViewController) -> NSDirectionalEdgeInsets { return self.readableContentInsets(for: viewController.view, traitCollection: viewController.traitCollection, minimumInsets: viewController.systemMinimumLayoutMargins) } static func readableContentInsets( for view: UIView, traitCollection: UITraitCollection, minimumInsets: NSDirectionalEdgeInsets = .zero ) -> NSDirectionalEdgeInsets { return self.insets(for: view.bounds.size, traitCollection: traitCollection, factor: 1, minimumInsets: minimumInsets) } private static func insets( for size: CGSize, traitCollection: UITraitCollection, factor: CGFloat, minimumInsets: NSDirectionalEdgeInsets = .zero ) -> NSDirectionalEdgeInsets { let readableWidth = self.readableWidth(for: traitCollection) ?? size.width let remainingWidth = size.width - readableWidth let padding = remainingWidth / 2 * factor return NSDirectionalEdgeInsets( top: 0, leading: max(padding, minimumInsets.leading), bottom: 0, trailing: max(padding, minimumInsets.trailing) ) } // swiftlint:disable:next cyclomatic_complexity private static func readableWidth(for traitCollection: UITraitCollection) -> CGFloat? { guard traitCollection.horizontalSizeClass == .regular && UIDevice.current.userInterfaceIdiom == .pad else { return nil } switch traitCollection.preferredContentSizeCategory { case .extraSmall: return 560 case .small: return 600 case .medium: return 632 case .large: return 672 case .extraLarge: return 744 case .extraExtraLarge: return 824 case .extraExtraExtraLarge: return 896 case .accessibilityMedium: return 1088 case .accessibilityLarge: return 1400 case .accessibilityExtraLarge: return 1500 case .accessibilityExtraExtraLarge: return 1600 case .accessibilityExtraExtraExtraLarge: return 1700 default: return nil } } }
gpl-3.0
1ceaeb3ac14437975d695229e9319fb2
35.91
132
0.649147
5.896166
false
false
false
false
alvarozizou/Noticias-Leganes-iOS
NoticiasLeganes/ViewControllers/ViewModelDelegate.swift
1
1891
// // ViewModelDelegate.swift // NoticiasLeganes // // Created by Alvaro Informática on 12/1/18. // Copyright © 2018 Alvaro Blazquez Montero. All rights reserved. // import UIKit import Material struct Process: Equatable { var rawValue: String static let Main = Process(rawValue: "Main") static func == (lhs: Process, rhs: Process) -> Bool { return lhs.rawValue == rhs.rawValue } } enum ProcessViewState { case loading case loaded(Process) case error(Process) } protocol ViewModelDelegate: class { func render(state: ProcessViewState) } class InputDataViewController: UIViewController, TextFieldDelegate, ViewModelDelegate { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } func prepareErrorTextField(placeholder: String, error: String, centerInLayout: UIView?) -> ErrorTextField { let errorTextField = ErrorTextField() errorTextField.delegate = self errorTextField.placeholder = placeholder errorTextField.detail = error errorTextField.isClearIconButtonEnabled = true errorTextField.placeholderActiveColor = UIColor.FlatColor.Blue.Leganes errorTextField.dividerActiveColor = UIColor.FlatColor.Blue.Leganes centerInLayout?.layout(errorTextField).center().left(0).right(0) return errorTextField } func textFieldShouldClear(_ textField: UITextField) -> Bool { (textField as? ErrorTextField)?.isErrorRevealed = false return true } func textField(textField: TextField, didChange text: String?) { (textField as? ErrorTextField)?.isErrorRevealed = false } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func render(state: ProcessViewState) { } }
mit
20426a6e725840e23ad67efd0c64734f
24.186667
111
0.695606
4.607317
false
false
false
false
Urinx/SublimeCode
Sublime/Sublime/Utils/Extension/Date.swift
1
3966
// // Date.swift // Sublime // // Created by Eular on 4/25/16. // Copyright © 2016 Eular. All rights reserved. // import Foundation enum TimeIntervalUnit { case Seconds, Minutes, Hours, Days, Months, Years func dateComponents(interval: Int) -> NSDateComponents { let components = NSDateComponents() switch (self) { case .Seconds: components.second = interval case .Minutes: components.minute = interval case .Hours: components.hour = interval case .Days: components.day = interval case .Months: components.month = interval case .Years: components.year = interval } return components } } struct TimeInterval { var interval: Int var unit: TimeIntervalUnit var ago: NSDate { let calendar = NSCalendar.currentCalendar() let today = NSDate() let components = unit.dateComponents(-self.interval) return calendar.dateByAddingComponents(components, toDate: today, options: .WrapComponents)! } init(interval: Int, unit: TimeIntervalUnit) { self.interval = interval self.unit = unit } } extension Int { var seconds: TimeInterval { return TimeInterval(interval: self, unit: .Seconds) } var minutes: TimeInterval { return TimeInterval(interval: self, unit: .Minutes) } var hours: TimeInterval { return TimeInterval(interval: self, unit: .Hours) } var days: TimeInterval { return TimeInterval(interval: self, unit: .Days) } var months: TimeInterval { return TimeInterval(interval: self, unit: .Months) } var years: TimeInterval { return TimeInterval(interval: self, unit: .Years) } } extension NSDate { class func yesterday() -> NSDate { return NSDate() - 1.days } func toS(format: String) -> String? { let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") formatter.timeZone = NSTimeZone() formatter.dateFormat = format return formatter.stringFromDate(self) } } extension String { func toDate(format: String = "dd/MM/yyyy") -> NSDate? { let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") formatter.timeZone = NSTimeZone() formatter.dateFormat = format return formatter.dateFromString(self) } func toGMTDate(format: String = "dd/MM/yyyy") -> NSDate? { let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) formatter.dateFormat = format return formatter.dateFromString(self) } } func + (left: NSDate, right: TimeInterval) -> NSDate { let calendar = NSCalendar.currentCalendar() let components = right.unit.dateComponents(right.interval) return calendar.dateByAddingComponents(components, toDate: left, options: .WrapComponents)! } func - (left: NSDate, right: TimeInterval) -> NSDate { let calendar = NSCalendar.currentCalendar() let components = right.unit.dateComponents(-right.interval) return calendar.dateByAddingComponents(components, toDate: left, options: .WrapComponents)! } func < (left: NSDate, right: NSDate) -> Bool { let result: NSComparisonResult = left.compare(right) var isEarlier = false if (result == NSComparisonResult.OrderedAscending) { isEarlier = true } return isEarlier } func - (left: NSDate, right: NSDate) -> NSDateComponents { let diffDateComponents = NSCalendar.currentCalendar().components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: right, toDate: left, options: NSCalendarOptions.init(rawValue: 0)) return diffDateComponents }
gpl-3.0
7b7a24e1a6483cec3754b9635e5a3fd6
28.589552
193
0.644136
4.6483
false
false
false
false
liuxuan30/ios-charts
ChartsDemo-iOS/Swift/Demos/CandleStickChartViewController.swift
3
4691
// // CandleStickChartViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // #if canImport(UIKit) import UIKit #endif import Charts class CandleStickChartViewController: DemoBaseViewController { @IBOutlet var chartView: CandleStickChartView! @IBOutlet var sliderX: UISlider! @IBOutlet var sliderY: UISlider! @IBOutlet var sliderTextX: UITextField! @IBOutlet var sliderTextY: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Candle Stick Chart" self.options = [.toggleValues, .toggleIcons, .toggleHighlight, .animateX, .animateY, .animateXY, .saveToGallery, .togglePinchZoom, .toggleAutoScaleMinMax, .toggleShadowColorSameAsCandle, .toggleShowCandleBar, .toggleData] chartView.delegate = self chartView.chartDescription?.enabled = false chartView.dragEnabled = false chartView.setScaleEnabled(true) chartView.maxVisibleCount = 200 chartView.pinchZoomEnabled = true chartView.legend.horizontalAlignment = .right chartView.legend.verticalAlignment = .top chartView.legend.orientation = .vertical chartView.legend.drawInside = false chartView.legend.font = UIFont(name: "HelveticaNeue-Light", size: 10)! chartView.leftAxis.labelFont = UIFont(name: "HelveticaNeue-Light", size: 10)! chartView.leftAxis.spaceTop = 0.3 chartView.leftAxis.spaceBottom = 0.3 chartView.leftAxis.axisMinimum = 0 chartView.rightAxis.enabled = false chartView.xAxis.labelPosition = .bottom chartView.xAxis.labelFont = UIFont(name: "HelveticaNeue-Light", size: 10)! sliderX.value = 10 sliderY.value = 50 slidersValueChanged(nil) } override func updateChartData() { if self.shouldHideData { chartView.data = nil return } self.setDataCount(Int(sliderX.value), range: UInt32(sliderY.value)) } func setDataCount(_ count: Int, range: UInt32) { let yVals1 = (0..<count).map { (i) -> CandleChartDataEntry in let mult = range + 1 let val = Double(arc4random_uniform(40) + mult) let high = Double(arc4random_uniform(9) + 8) let low = Double(arc4random_uniform(9) + 8) let open = Double(arc4random_uniform(6) + 1) let close = Double(arc4random_uniform(6) + 1) let even = i % 2 == 0 return CandleChartDataEntry(x: Double(i), shadowH: val + high, shadowL: val - low, open: even ? val + open : val - open, close: even ? val - close : val + close, icon: UIImage(named: "icon")!) } let set1 = CandleChartDataSet(entries: yVals1, label: "Data Set") set1.axisDependency = .left set1.setColor(UIColor(white: 80/255, alpha: 1)) set1.drawIconsEnabled = false set1.shadowColor = .darkGray set1.shadowWidth = 0.7 set1.decreasingColor = .red set1.decreasingFilled = true set1.increasingColor = UIColor(red: 122/255, green: 242/255, blue: 84/255, alpha: 1) set1.increasingFilled = false set1.neutralColor = .blue let data = CandleChartData(dataSet: set1) chartView.data = data } override func optionTapped(_ option: Option) { switch option { case .toggleShadowColorSameAsCandle: for set in chartView.data!.dataSets as! [CandleChartDataSet] { set.shadowColorSameAsCandle = !set.shadowColorSameAsCandle } chartView.notifyDataSetChanged() case .toggleShowCandleBar: for set in chartView.data!.dataSets as! [CandleChartDataSet] { set.showCandleBar = !set.showCandleBar } chartView.notifyDataSetChanged() default: super.handleOption(option, forChartView: chartView) } } // MARK: - Actions @IBAction func slidersValueChanged(_ sender: Any?) { sliderTextX.text = "\(Int(sliderX.value))" sliderTextY.text = "\(Int(sliderY.value))" self.updateChartData() }}
apache-2.0
23c984dab8ee97a71c2fa2600882579c
34.801527
204
0.584435
4.825103
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/ViewRelated/Aztec/Processors/ShortcodeProcessor.swift
1
3140
import Foundation import Aztec /// Struct to represent a WordPress shortcode /// More details here: https://codex.wordpress.org/Shortcode and here: https://en.support.wordpress.com/shortcodes/ /// public struct Shortcode { public enum TagType { case selfClosing case closed case single } public let tag: String public let attributes: HTMLAttributes public let type: TagType public let content: String? } /// A class that processes a string and replace the designated shortcode for the replacement provided strings /// open class ShortcodeProcessor: RegexProcessor { public typealias ShortcodeReplacer = (Shortcode) -> String let tag: String /// Regular expression to detect attributes /// Capture groups: /// /// 1. An extra `[` to allow for escaping shortcodes with double `[[]]` /// 2. The shortcode name /// 3. The shortcode argument list /// 4. The self closing `/` /// 5. The content of a shortcode when it wraps some content. /// 6. The closing tag. /// 7. An extra `]` to allow for escaping shortcodes with double `[[]]` /// static func makeShortcodeRegex(tag: String) -> NSRegularExpression { let pattern = "\\[(\\[?)(\(tag))(?![\\w-])([^\\]\\/]*(?:\\/(?!\\])[^\\]\\/]*)*?)(?:(\\/)\\]|\\](?:([^\\[]*(?:\\[(?!\\/\\2\\])[^\\[]*)*)(\\[\\/\\2\\]))?)(\\]?)" let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive) return regex } enum CaptureGroups: Int { case all = 0 case extraOpen case name case arguments case selfClosingElement case content case closingTag case extraClose static let allValues = [.all, extraOpen, .name, .arguments, .selfClosingElement, .content, .closingTag, .extraClose] } public init(tag: String, replacer: @escaping ShortcodeReplacer) { self.tag = tag let regex = ShortcodeProcessor.makeShortcodeRegex(tag: tag) let regexReplacer = { (match: NSTextCheckingResult, text: String) -> String? in guard match.numberOfRanges == CaptureGroups.allValues.count else { return nil } var attributes = HTMLAttributes(named: [:], unamed: []) if let attributesText = match.captureGroup(in:CaptureGroups.arguments.rawValue, text: text) { attributes = HTMLAttributesParser.makeAttributes(in: attributesText) } var type: Shortcode.TagType = .single if match.captureGroup(in:CaptureGroups.selfClosingElement.rawValue, text: text) != nil { type = .selfClosing } else if match.captureGroup(in:CaptureGroups.closingTag.rawValue, text: text) != nil { type = .closed } let content: String? = match.captureGroup(in:CaptureGroups.content.rawValue, text: text) let shortcode = Shortcode(tag: tag, attributes: attributes, type: type, content: content) return replacer(shortcode) } super.init(regex: regex, replacer: regexReplacer) } }
gpl-2.0
f80f1305d114643268178971d15aa7b1
36.831325
167
0.614013
4.355062
false
false
false
false
Jus10Lewis/Swift-Matching-Cards-Game
FlagMemoryCards/DeckOfCards.swift
1
1287
// // DeckOfCards.swift // FlagMemoryCards // // Created by Justin Lewis on 7/18/17. // Copyright © 2017 DevTrain. All rights reserved. // import Foundation struct DeckOfCards { // MARK: - Properties var nameList = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa"] let numberOfMatches = 6 var dealtCards : [String] = [] init(){ drawNewCards() } mutating func drawNewCards() { dealtCards.removeAll() nameList.shuffle() for i in 0..<numberOfMatches { dealtCards.append(nameList[i]) dealtCards.append(nameList[i]) } dealtCards.shuffle() } func randomFromZero(to number: Int) -> Int { return Int(arc4random_uniform(UInt32(number))) } func shuffle(_ array: [String]) -> [String] { var newArray = array for index in 0..<array.count { let randomIndex = randomFromZero(to: array.count) let value = newArray[randomIndex] newArray[randomIndex] = newArray[index] newArray[index] = value } return newArray } }
mit
56034a4972ddeaf85968f898cab7fb77
22.814815
188
0.567652
3.920732
false
false
false
false
gitizenme/SwiftKeyboardExtension
SwiftKeyboardExtension/SwiftKeyboardExtension/RootViewController.swift
1
4902
// // RootViewController.swift // SwiftKeyboardExtension // // Created by Joe Chavez on 8/11/15. // Copyright (c) 2015 izen.me, Inc. All rights reserved. // import UIKit class RootViewController: UIViewController, UIPageViewControllerDelegate { var pageViewController: UIPageViewController? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Configure the page view controller and add it as a child view controller. self.pageViewController = UIPageViewController(transitionStyle: .PageCurl, navigationOrientation: .Horizontal, options: nil) self.pageViewController!.delegate = self let startingViewController: DataViewController = self.modelController.viewControllerAtIndex(0, storyboard: self.storyboard!)! let viewControllers = [startingViewController] self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: false, completion: {done in }) self.pageViewController!.dataSource = self.modelController self.addChildViewController(self.pageViewController!) self.view.addSubview(self.pageViewController!.view) // Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages. var pageViewRect = self.view.bounds if UIDevice.currentDevice().userInterfaceIdiom == .Pad { pageViewRect = CGRectInset(pageViewRect, 40.0, 40.0) } self.pageViewController!.view.frame = pageViewRect self.pageViewController!.didMoveToParentViewController(self) // Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily. self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var modelController: ModelController { // Return the model controller object, creating it if necessary. // In more complex implementations, the model controller may be passed to the view controller. if _modelController == nil { _modelController = ModelController() } return _modelController! } var _modelController: ModelController? = nil // MARK: - UIPageViewController delegate methods func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation { if (orientation == .Portrait) || (orientation == .PortraitUpsideDown) || (UIDevice.currentDevice().userInterfaceIdiom == .Phone) { // In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to YES, so set it to NO here. let currentViewController = self.pageViewController!.viewControllers[0] as! UIViewController let viewControllers = [currentViewController] self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in }) self.pageViewController!.doubleSided = false return .Min } // In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers. let currentViewController = self.pageViewController!.viewControllers[0] as! DataViewController var viewControllers: [AnyObject] let indexOfCurrentViewController = self.modelController.indexOfViewController(currentViewController) if (indexOfCurrentViewController == 0) || (indexOfCurrentViewController % 2 == 0) { let nextViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerAfterViewController: currentViewController) viewControllers = [currentViewController, nextViewController!] } else { let previousViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerBeforeViewController: currentViewController) viewControllers = [previousViewController!, currentViewController] } self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in }) return .Mid } }
mit
12f860951282b56683fdad5309bf0645
51.709677
329
0.733782
5.849642
false
false
false
false
andrebocchini/SwiftChatty
SwiftChatty/Requests/Notifications/RegisterNotifierClientRequest.swift
1
608
// // RegisterNotifierClientRequest.swift // SwiftChatty // // Created by Andre Bocchini on 1/28/16. // Copyright © 2016 Andre Bocchini. All rights reserved. import Alamofire /// -SeeAlso: http://winchatty.com/v2/readme#_Toc421451706 public struct RegisterNotifierClientRequest: Request { public let endpoint: ApiEndpoint = .RegisterNotifierClient public let httpMethod: HTTPMethod = .post public var customParameters: [String : Any] = [:] public init(withId id: String, name: String) { self.customParameters["id"] = id self.customParameters["name"] = name } }
mit
1f85393e5106448f6b6e277b536e58e4
27.904762
62
0.701812
4.129252
false
false
false
false
quadro5/swift3_L
Swift_api.playground/Pages/JSON Parser.xcplaygroundpage/Contents.swift
1
1974
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) /// json keys for lines struct LinesKey { static let lines = "lines" static let name = "name" static let hexcolor = "hexcolor" static let letter = "letter" static let desc = "desc" } /// model for Lines struct LineModel { var name: String var hexcolor: String var letter: String var desc: String init?(dict: Dictionary<String, AnyObject>?) { guard let name = dict?[LinesKey.name] as? String, let hexcolor = dict?[LinesKey.hexcolor] as? String, let letter = dict?[LinesKey.letter] as? String, let desc = dict?[LinesKey.desc] as? String else { return nil } self.name = name self.hexcolor = hexcolor self.letter = letter self.desc = desc } } func fetchTestJson(with file: String) -> Array<LineModel>? { // get path guard let path = Bundle.main.path(forResource: file, ofType: "json") else { print("BaseD.C: not such testJson file") return nil } // get data json let jsonData = try! Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped) let json = try! JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves) // parse json guard let lines = json as? Dictionary<String, Any>, let linesData = lines[LinesKey.lines] else { return nil } // to models var models = Array<LineModel>() if let jsonArray = linesData as? Array<Any> { for element in jsonArray { if let modelDict = element as? Dictionary<String, AnyObject>, let model = LineModel(dict: modelDict) { models.append(model) } } } return models } let fileName = "subway-lister" if let res = fetchTestJson(with: fileName) { print(res[0]) }
unlicense
d89a17033e1e7f44ee29591494319753
23.675
92
0.590172
4.061728
false
false
false
false
sunyazhou13/Developing-iOS-9-Apps-with-Swift
6.FaceIt/FaceIt/EmotionsViewController.swift
1
1393
// // EmotionsViewController.swift // FaceIt // // Created by sunyazhou on 16/5/13. // Copyright © 2016年 Baidu, Inc. All rights reserved. // import UIKit class EmotionsViewController: UIViewController { private let emotionalFaces: Dictionary<String, FacialExpression> = [ "angry" : FacialExpression(eyes: .Closed, eyeBrows: .Furrowed, mouth: .Frown), "happy" : FacialExpression(eyes: .Open, eyeBrows: .Normal, mouth: .Smile), "worried" : FacialExpression(eyes: .Open, eyeBrows: .Relaxed, mouth: .Smirk), "mischievious" : FacialExpression(eyes: .Open, eyeBrows: .Furrowed, mouth: .Grin) ] override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var destinationvc = segue.destinationViewController if let navcon = destinationvc as? UINavigationController { destinationvc = navcon.visibleViewController ?? destinationvc } if let facevc = destinationvc as? FaceViewController { if let identifier = segue.identifier { if let expression = emotionalFaces[identifier] { facevc.expression = expression if let sendingButton = sender as? UIButton { facevc.navigationItem.title = sendingButton.currentTitle } } } } } }
mit
010a8fa3cd6ab1aa3b3ad4c6fe312a8a
35.578947
89
0.62446
4.34375
false
false
false
false
thankmelater23/MyFitZ
MyFitZ/DoubleLabelTableViewCell.swift
1
1579
// // DoubleLabelTableViewCell.swift // My_Fitz // // Created by Andre Villanueva on 4/14/15. // Copyright (c) 2015 BangBangStudios. All rights reserved. // import UIKit //MARK: -DoubleLabelTableViewCell Class class DoubleLabelTableViewCell: UITableViewCell { //MARK: -Outlets ///The second label in the cell that holds the name of the info that will be displayed in the second label @IBOutlet var nameLabel: UILabel! ///The second label in the cell that holds information of the first labels name @IBOutlet var infoLabel: UILabel! //MARK: -View Methods override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @objc func borderCustomization(){ // self.layer.cornerRadius = self.frame.size.width / 10 self.contentMode = UIViewContentMode.scaleToFill self.clipsToBounds = true self.layer.borderWidth = 2 self.layer.borderColor = BrownLeatherStitching.cgColor } @objc func customizeView(){ self.backgroundColor = SpecialLeatherTexture self.borderCustomization() } } //MARK: -Initializers extension DoubleLabelTableViewCell{ @objc func configure(name: String, infoString: String){ nameLabel.text = name + ":" infoLabel.text = infoString self.customizeView() } }
mit
aefbc3371f9a44d52c6efe0d6acbc2a7
26.224138
110
0.659278
4.657817
false
false
false
false