| repo_name
				 stringlengths 6 91 | ref
				 stringlengths 12 59 | path
				 stringlengths 7 936 | license
				 stringclasses 15
				values | copies
				 stringlengths 1 3 | content
				 stringlengths 61 714k | hash
				 stringlengths 32 32 | line_mean
				 float64 4.88 60.8 | line_max
				 int64 12 421 | alpha_frac
				 float64 0.1 0.92 | autogenerated
				 bool 1
				class | config_or_test
				 bool 2
				classes | has_no_keywords
				 bool 2
				classes | has_few_assignments
				 bool 1
				class | 
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 
	MKGitHub/UIPheonix | 
	refs/heads/master | 
	Demo/Shared/Models/SimpleButtonModel.swift | 
	apache-2.0 | 
	1 | 
	/**
    UIPheonix
    Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
    https://github.com/MKGitHub/UIPheonix
    http://www.xybernic.com
    Copyright 2016/2017/2018/2019 Mohsan Khan
    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.
*/
final class SimpleButtonModel:UIPBaseCellModel
{
    // MARK: Public Constants
    struct Key
    {
        static let id = "id"
        static let title = "title"
        static let alignment = "alignment"
        static let focus = "focus"
    }
    struct Alignment
    {
        static let left = "left"
        static let center = "center"
        static let right = "right"
    }
    // MARK: Public Members
    public var pId:Int!
    public var pTitle:String!
    #if os(macOS)
        public var pAlignment:String!
    #endif
    #if os(tvOS)
        public var pFocus = false
    #endif
    // MARK:- UIPBaseCellModelProtocol
    required init()
    {
        super.init()
    }
    override func setContents(with dictionary:Dictionary<String, Any>)
    {
        pId = dictionary[Key.id] as? Int
        pTitle = dictionary[Key.title] as? String
        #if os(macOS)
            pAlignment = (dictionary[Key.alignment] as? String) ?? Alignment.center    // fallback to default value
        #endif
        #if os(tvOS)
            pFocus = (dictionary[Key.focus] as? Bool) ?? false    // fallback to default value
        #endif
    }
    // MARK:- Life Cycle
    #if os(iOS)
        init(id:Int, title:String)
        {
            super.init()
            pId = id
            pTitle = title
        }
    #elseif os(tvOS)
        init(id:Int, title:String, focus:Bool)
        {
            super.init()
            pId = id
            pTitle = title
            pFocus = focus
        }
    #elseif os(macOS)
        init(id:Int, title:String, alignment:String)
        {
            super.init()
            pId = id
            pTitle = title
            pAlignment = alignment
        }
    #endif
    // MARK:- UIPBaseCellModel
    override func toDictionary() -> Dictionary<String, Any>
    {
        var dictionary = Dictionary<String, Any>(minimumCapacity:2)
        dictionary[Key.id] = pId
        dictionary[Key.title] = pTitle
        #if os(macOS)
            dictionary[Key.alignment] = pAlignment
        #endif
        #if os(tvOS)
            dictionary[Key.focus] = pFocus
        #endif
        return dictionary
    }
}
 | 
	2dcc4e302e94629771fd8b2e236b4220 | 21.044776 | 115 | 0.581923 | false | false | false | false | 
| 
	WaterReporter/WaterReporter-iOS | 
	refs/heads/master | 
	WaterReporter/WaterReporter/UserProfileTableView.swift | 
	agpl-3.0 | 
	1 | 
	//
//  UserProfileTableView.swift
//  Water-Reporter
//
//  Created by Viable Industries on 8/22/16.
//  Copyright © 2016 Viable Industries, L.L.C. All rights reserved.
//
import Alamofire
import Foundation
import UIKit
class UserProfileTableView: UITableView {
    
    var reports = [AnyObject]()
    var singleReport: Bool = false
    var page: Int = 1
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        if (!singleReport) {
            self.loadSubmissions()
        }
    }
    
    func loadSubmissions() {
        
        print("loadSubmissions")
        
        //
        // Send a request to the defined endpoint with the given parameters
        //
        let parameters = [
            "q": "{\"filters\": [{\"name\":\"owner_id\", \"op\":\"eq\", \"val\":274}], \"order_by\": [{\"field\":\"created\",\"direction\":\"desc\"}]}",
            "page": self.page
        ]
        
        Alamofire.request(.GET, Endpoints.GET_MANY_REPORTS, parameters: parameters as? [String : AnyObject])
            .responseJSON { response in
                
                switch response.result {
                case .Success(let value):
                    self.reports += value["features"] as! [AnyObject]
                    self.reloadData()
                    
                    print(value["features"])
                    self.page += 1
                    
                case .Failure(let error):
                    print(error)
                    break
                }
                
        }
    }
    
}
 | 
	0cfaf347d8173c0a7f6aed2079d77d10 | 25.5 | 152 | 0.485535 | false | false | false | false | 
| 
	AKIRA-MIYAKE/SFOAuth | 
	refs/heads/master | 
	15-MeiTuan/SwiftyJSON-master/Tests/StringTests.swift | 
	apache-2.0 | 
	117 | 
	//  StringTests.swift
//
//  Copyright (c) 2014 Pinglin Tang
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
import XCTest
import SwiftyJSON
class StringTests: XCTestCase {
    func testString() {
        //getter
        var json = JSON("abcdefg hijklmn;opqrst.?+_()")
        XCTAssertEqual(json.string!, "abcdefg hijklmn;opqrst.?+_()")
        XCTAssertEqual(json.stringValue, "abcdefg hijklmn;opqrst.?+_()")
        json.string = "12345?67890.@#"
        XCTAssertEqual(json.string!, "12345?67890.@#")
        XCTAssertEqual(json.stringValue, "12345?67890.@#")
    }
    
    func testURL() {
        let json = JSON("http://github.com")
        XCTAssertEqual(json.URL!, NSURL(string:"http://github.com")!)
    }
    func testURLPercentEscapes() {
        let emDash = "\\u2014"
        let urlString = "http://examble.com/unencoded" + emDash + "string"
        let encodedURLString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
        let json = JSON(urlString)
        XCTAssertEqual(json.URL!, NSURL(string: encodedURLString!)!, "Wrong unpacked ")
    }
}
 | 
	03e87c4f02faf3891c22a9c9058b640c | 41 | 104 | 0.697479 | false | true | false | false | 
| 
	epv44/TwitchAPIWrapper | 
	refs/heads/master | 
	Sources/TwitchAPIWrapper/Network/Authorization/TWAuthWebviewController.swift | 
	mit | 
	1 | 
	//
//  TWAuthWebviewController.swift
//  TwitchAPIWrapper
//
//  Created by Eric Vennaro on 4/25/21.
//
import Foundation
import WebKit
protocol TWAuthWebViewDelegate: AnyObject {
    func completeAuthentication(_ vc: UIViewController, token: String, scopes: [String]) -> Void
}
final class TWAuthWebViewController: UIViewController {
    private let redirectURI: String
    private let authURL: URL
    private let state: String
    private weak var delegate: TWAuthWebViewDelegate?
    
    private var webView: WKWebView = {
        let webView = WKWebView()
        webView.translatesAutoresizingMaskIntoConstraints = false
        return webView
    }()
    
    public init(delegate: TWAuthWebViewDelegate?, redirectURI: String, authURL: URL, state: String) {
        self.delegate = delegate
        self.redirectURI = redirectURI
        self.authURL = authURL
        self.state = state
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        setupChildViews()
        webView.navigationDelegate = self
        webView.load(URLRequest(url: authURL))
    }
    
    private func setupChildViews() {
        view.addSubview(webView)
        
        NSLayoutConstraint.activate([
            webView.leftAnchor.constraint(equalTo: view.leftAnchor),
            webView.rightAnchor.constraint(equalTo: view.rightAnchor),
            webView.topAnchor.constraint(equalTo: view.topAnchor),
            webView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
    }
}
//MARK: - Web Kit Navigation Delegate
extension TWAuthWebViewController: WKNavigationDelegate {
    
    public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        handleRedirect(url: webView.url)
    }
    
    public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        if let response = navigationResponse.response as? HTTPURLResponse, 500 ..< 600 ~= response.statusCode {
            EVLog(text: "Twitch - Status code was \(response.statusCode), but expected 2xx.", line: #line, fileName: #file)
            dismiss(animated: true, completion: nil)
        }
        decisionHandler(.allow)
    }
    
    private func handleRedirect(url: URL?) {
        if isCorrectRedirectURL(webView.url),
           let fragment = getFragments(from: webView.url),
           let token = fragment["access_token"],
           let returnState = fragment["state"],
           let scopesStr = fragment["scope"] {
            if state == returnState {
                delegate?.completeAuthentication(self, token: token, scopes: scopesStr.components(separatedBy: ":"))
            } else {
                EVLog(text: "Invalid state: sent: \(state), returned was: \(returnState)", line: #line, fileName: #file)
            }
            dismiss(animated: true, completion: nil)
        }
    }
    
    private func isCorrectRedirectURL(_ url: URL?) -> Bool {
        guard let urlStr = url?.absoluteString, urlStr.count >= redirectURI.count else {
            return false
        }
        let index = urlStr.index(urlStr.startIndex, offsetBy: redirectURI.count)
        let substring = urlStr.prefix(upTo: index)
        return substring == redirectURI
    }
    
    private func getFragments(from url: URL?) -> [String:String]? {
        guard let urlString = url?.absoluteString,
              let components = URLComponents(string: urlString),
              let fragment = components.fragment else {
            return nil
        }
        return fragment.components(separatedBy: "&").map({
            $0.components(separatedBy: "=")
        }).reduce(into: [String:String]()) { dict, pair in
            if pair.count == 2 {
                dict[pair[0]] = pair[1]
            }
        }
    }
}
 | 
	c6d1a52559bfe50535a80ab85b961d32 | 35.504505 | 170 | 0.634995 | false | false | false | false | 
| 
	flovouin/AsyncDisplayKit | 
	refs/heads/master | 
	examples_extra/ASDKgram-Swift/ASDKgram-Swift/PhotoModel.swift | 
	bsd-3-clause | 
	5 | 
	//
//  PhotoModel.swift
//  ASDKgram-Swift
//
//  Created by Calum Harris on 07/01/2017.
//
//  Copyright (c) 2014-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
//  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
//  FACEBOOK 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
typealias JSONDictionary = [String : Any]
struct PhotoModel {
	
	let url: String
	let photoID: Int
	let dateString: String
	let descriptionText: String
	let likesCount: Int
	let ownerUserName: String
	let ownerPicURL: String
	
	init?(dictionary: JSONDictionary) {
		
		guard let url = dictionary["image_url"] as? String, let date = dictionary["created_at"] as? String, let photoID = dictionary["id"] as? Int, let descriptionText = dictionary["name"] as? String, let likesCount = dictionary["positive_votes_count"] as? Int else { print("error parsing JSON within PhotoModel Init"); return nil }
		
		guard let user = dictionary["user"] as? JSONDictionary, let username = user["username"] as? String, let ownerPicURL = user["userpic_url"] as? String else { print("error parsing JSON within PhotoModel Init"); return nil }
		
		self.url = url
		self.photoID = photoID
		self.descriptionText = descriptionText
		self.likesCount = likesCount
		self.dateString = date
		self.ownerUserName = username
		self.ownerPicURL = ownerPicURL
	}
}
extension PhotoModel {
	
	// MARK: - Attributed Strings
	
	func attrStringForUserName(withSize size: CGFloat) -> NSAttributedString {
		let attr = [
			NSForegroundColorAttributeName : UIColor.darkGray,
			NSFontAttributeName: UIFont.boldSystemFont(ofSize: size)
		]
		return NSAttributedString(string: self.ownerUserName, attributes: attr)
	}
	
	func attrStringForDescription(withSize size: CGFloat) -> NSAttributedString {
		let attr = [
			NSForegroundColorAttributeName : UIColor.darkGray,
			NSFontAttributeName: UIFont.systemFont(ofSize: size)
		]
		return NSAttributedString(string: self.descriptionText, attributes: attr)
	}
	
	func attrStringLikes(withSize size: CGFloat) -> NSAttributedString {
		
		let formatter = NumberFormatter()
		formatter.numberStyle = .decimal
		let formattedLikesNumber: String? = formatter.string(from: NSNumber(value: self.likesCount))
		let likesString: String = "\(formattedLikesNumber!) Likes"
		let textAttr = [NSForegroundColorAttributeName : UIColor.mainBarTintColor(), NSFontAttributeName: UIFont.systemFont(ofSize: size)]
		let likesAttrString = NSAttributedString(string: likesString, attributes: textAttr)
		
		let heartAttr = [NSForegroundColorAttributeName : UIColor.red, NSFontAttributeName: UIFont.systemFont(ofSize: size)]
		let heartAttrString = NSAttributedString(string: "♥︎ ", attributes: heartAttr)
		
		let combine = NSMutableAttributedString()
		combine.append(heartAttrString)
		combine.append(likesAttrString)
		return combine
	}
	
	func attrStringForTimeSinceString(withSize size: CGFloat) -> NSAttributedString {
		
		let attr = [
			NSForegroundColorAttributeName : UIColor.mainBarTintColor(),
			NSFontAttributeName: UIFont.systemFont(ofSize: size)
		]
		
		let date = Date.iso8601Formatter.date(from: self.dateString)!
		return NSAttributedString(string: timeStringSince(fromConverted: date), attributes: attr)
	}
	
	private func timeStringSince(fromConverted date: Date) -> String {
		let diffDates = NSCalendar.current.dateComponents([.day, .hour, .second], from: date, to: Date())
		
		if let week = diffDates.day, week > 7 {
			return "\(week / 7)w"
		} else if let day = diffDates.day, day > 0 {
			return "\(day)d"
		} else if let hour = diffDates.hour, hour > 0 {
			return "\(hour)h"
		} else if let second = diffDates.second, second > 0 {
			return "\(second)s"
		} else if let zero = diffDates.second, zero == 0 {
			return "1s"
		} else {
			return "ERROR"
		}
	}
}
 | 
	3ae5b3b608a6581a4d76d8af099dfa4f | 36.525862 | 326 | 0.737882 | false | false | false | false | 
| 
	FreddyZeng/Charts | 
	refs/heads/master | 
	Source/Charts/Components/AxisBase.swift | 
	apache-2.0 | 
	1 | 
	//
//  AxisBase.swift
//  Charts
//
//  Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
//  A port of MPAndroidChart for iOS
//  Licensed under Apache License 2.0
//
//  https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
/// Base class for all axes
@objc(ChartAxisBase)
open class AxisBase: ComponentBase
{
    public override init()
    {
        super.init()
    }
    
    /// Custom formatter that is used instead of the auto-formatter if set
    private var _axisValueFormatter: IAxisValueFormatter?
    
    @objc open var labelFont = NSUIFont.systemFont(ofSize: 10.0)
    @objc open var labelTextColor = NSUIColor.black
    
    @objc open var axisLineColor = NSUIColor.gray
    @objc open var axisLineWidth = CGFloat(0.5)
    @objc open var axisLineDashPhase = CGFloat(0.0)
    @objc open var axisLineDashLengths: [CGFloat]!
    
    @objc open var gridColor = NSUIColor.gray.withAlphaComponent(0.9)
    @objc open var gridLineWidth = CGFloat(0.5)
    @objc open var gridLineDashPhase = CGFloat(0.0)
    @objc open var gridLineDashLengths: [CGFloat]!
    @objc open var gridLineCap = CGLineCap.butt
    
    @objc open var drawGridLinesEnabled = true
    @objc open var drawAxisLineEnabled = true
    
    /// flag that indicates of the labels of this axis should be drawn or not
    @objc open var drawLabelsEnabled = true
    
    private var _centerAxisLabelsEnabled = false
    /// Centers the axis labels instead of drawing them at their original position.
    /// This is useful especially for grouped BarChart.
    @objc open var centerAxisLabelsEnabled: Bool
    {
        get { return _centerAxisLabelsEnabled && entryCount > 0 }
        set { _centerAxisLabelsEnabled = newValue }
    }
    
    @objc open var isCenterAxisLabelsEnabled: Bool
    {
        get { return centerAxisLabelsEnabled }
    }
    /// array of limitlines that can be set for the axis
    private var _limitLines = [ChartLimitLine]()
    
    /// Are the LimitLines drawn behind the data or in front of the data?
    /// 
    /// **default**: false
    @objc open var drawLimitLinesBehindDataEnabled = false
    /// the flag can be used to turn off the antialias for grid lines
    @objc open var gridAntialiasEnabled = true
    
    /// the actual array of entries
    @objc open var entries = [Double]()
    
    /// axis label entries only used for centered labels
    @objc open var centeredEntries = [Double]()
    
    /// the number of entries the legend contains
    @objc open var entryCount: Int { return entries.count }
    
    /// the number of label entries the axis should have
    ///
    /// **default**: 6
    private var _labelCount = Int(6)
    
    /// the number of decimal digits to use (for the default formatter
    @objc open var decimals: Int = 0
    
    /// When true, axis labels are controlled by the `granularity` property.
    /// When false, axis values could possibly be repeated.
    /// This could happen if two adjacent axis values are rounded to same value.
    /// If using granularity this could be avoided by having fewer axis values visible.
    @objc open var granularityEnabled = false
    
    private var _granularity = Double(1.0)
    
    /// The minimum interval between axis values.
    /// This can be used to avoid label duplicating when zooming in.
    ///
    /// **default**: 1.0
    @objc open var granularity: Double
    {
        get
        {
            return _granularity
        }
        set
        {
            _granularity = newValue
            
            // set this to `true` if it was disabled, as it makes no sense to set this property with granularity disabled
            granularityEnabled = true
        }
    }
    
    /// The minimum interval between axis values.
    @objc open var isGranularityEnabled: Bool
    {
        get
        {
            return granularityEnabled
        }
    }
    
    /// if true, the set number of y-labels will be forced
    @objc open var forceLabelsEnabled = false
    
    @objc open func getLongestLabel() -> String
    {
        var longest = ""
        
        for i in 0 ..< entries.count
        {
            let text = getFormattedLabel(i)
            
            if longest.count < text.count
            {
                longest = text
            }
        }
        
        return longest
    }
    
    /// - returns: The formatted label at the specified index. This will either use the auto-formatter or the custom formatter (if one is set).
    @objc open func getFormattedLabel(_ index: Int) -> String
    {
        if index < 0 || index >= entries.count
        {
            return ""
        }
        
        return valueFormatter?.stringForValue(entries[index], axis: self) ?? ""
    }
    
    /// Sets the formatter to be used for formatting the axis labels.
    /// If no formatter is set, the chart will automatically determine a reasonable formatting (concerning decimals) for all the values that are drawn inside the chart.
    /// Use `nil` to use the formatter calculated by the chart.
    @objc open var valueFormatter: IAxisValueFormatter?
    {
        get
        {
            if _axisValueFormatter == nil ||
                (_axisValueFormatter is DefaultAxisValueFormatter &&
                    (_axisValueFormatter as! DefaultAxisValueFormatter).hasAutoDecimals &&
                    (_axisValueFormatter as! DefaultAxisValueFormatter).decimals != decimals)
            {
                _axisValueFormatter = DefaultAxisValueFormatter(decimals: decimals)
            }
            
            return _axisValueFormatter
        }
        set
        {
            _axisValueFormatter = newValue ?? DefaultAxisValueFormatter(decimals: decimals)
        }
    }
    
    @objc open var isDrawGridLinesEnabled: Bool { return drawGridLinesEnabled }
    
    @objc open var isDrawAxisLineEnabled: Bool { return drawAxisLineEnabled }
    
    @objc open var isDrawLabelsEnabled: Bool { return drawLabelsEnabled }
    
    /// Are the LimitLines drawn behind the data or in front of the data?
    /// 
    /// **default**: false
    @objc open var isDrawLimitLinesBehindDataEnabled: Bool { return drawLimitLinesBehindDataEnabled }
    
    /// Extra spacing for `axisMinimum` to be added to automatically calculated `axisMinimum`
    @objc open var spaceMin: Double = 0.0
    
    /// Extra spacing for `axisMaximum` to be added to automatically calculated `axisMaximum`
    @objc open var spaceMax: Double = 0.0
    
    /// Flag indicating that the axis-min value has been customized
    internal var _customAxisMin: Bool = false
    
    /// Flag indicating that the axis-max value has been customized
    internal var _customAxisMax: Bool = false
    
    /// Do not touch this directly, instead, use axisMinimum.
    /// This is automatically calculated to represent the real min value,
    /// and is used when calculating the effective minimum.
    internal var _axisMinimum = Double(0)
    
    /// Do not touch this directly, instead, use axisMaximum.
    /// This is automatically calculated to represent the real max value,
    /// and is used when calculating the effective maximum.
    internal var _axisMaximum = Double(0)
    
    /// the total range of values this axis covers
    @objc open var axisRange = Double(0)
    
    /// The minumum number of labels on the axis
    @objc open var axisMinLabels = Int(2) {
        didSet { axisMinLabels = axisMinLabels > 0 ? axisMinLabels : oldValue }
    }
    
    /// The maximum number of labels on the axis
    @objc open var axisMaxLabels = Int(25) {
        didSet { axisMinLabels = axisMaxLabels > 0 ? axisMaxLabels : oldValue }
    }
    
    /// the number of label entries the axis should have
    /// max = 25,
    /// min = 2,
    /// default = 6,
    /// be aware that this number is not fixed and can only be approximated
    @objc open var labelCount: Int
    {
        get
        {
            return _labelCount
        }
        set
        {
            _labelCount = newValue
            
            if _labelCount > axisMaxLabels
            {
                _labelCount = axisMaxLabels
            }
            if _labelCount < axisMinLabels
            {
                _labelCount = axisMinLabels
            }
            
            forceLabelsEnabled = false
        }
    }
    
    @objc open func setLabelCount(_ count: Int, force: Bool)
    {
        self.labelCount = count
        forceLabelsEnabled = force
    }
    
    /// - returns: `true` if focing the y-label count is enabled. Default: false
    @objc open var isForceLabelsEnabled: Bool { return forceLabelsEnabled }
    
    /// Adds a new ChartLimitLine to this axis.
    @objc open func addLimitLine(_ line: ChartLimitLine)
    {
        _limitLines.append(line)
    }
    
    /// Removes the specified ChartLimitLine from the axis.
    @objc open func removeLimitLine(_ line: ChartLimitLine)
    {
        for i in 0 ..< _limitLines.count
        {
            if _limitLines[i] === line
            {
                _limitLines.remove(at: i)
                return
            }
        }
    }
    
    /// Removes all LimitLines from the axis.
    @objc open func removeAllLimitLines()
    {
        _limitLines.removeAll(keepingCapacity: false)
    }
    
    /// - returns: The LimitLines of this axis.
    @objc open var limitLines : [ChartLimitLine]
    {
        return _limitLines
    }
    
    // MARK: Custom axis ranges
    
    /// By calling this method, any custom minimum value that has been previously set is reseted, and the calculation is done automatically.
    @objc open func resetCustomAxisMin()
    {
        _customAxisMin = false
    }
    
    @objc open var isAxisMinCustom: Bool { return _customAxisMin }
    
    /// By calling this method, any custom maximum value that has been previously set is reseted, and the calculation is done automatically.
    @objc open func resetCustomAxisMax()
    {
        _customAxisMax = false
    }
    
    @objc open var isAxisMaxCustom: Bool { return _customAxisMax }
        
    /// The minimum value for this axis.
    /// If set, this value will not be calculated automatically depending on the provided data.
    /// Use `resetCustomAxisMin()` to undo this.
    @objc open var axisMinimum: Double
    {
        get
        {
            return _axisMinimum
        }
        set
        {
            _customAxisMin = true
            _axisMinimum = newValue
            axisRange = abs(_axisMaximum - newValue)
        }
    }
    
    /// The maximum value for this axis.
    /// If set, this value will not be calculated automatically depending on the provided data.
    /// Use `resetCustomAxisMax()` to undo this.
    @objc open var axisMaximum: Double
    {
        get
        {
            return _axisMaximum
        }
        set
        {
            _customAxisMax = true
            _axisMaximum = newValue
            axisRange = abs(newValue - _axisMinimum)
        }
    }
    
    /// Calculates the minimum, maximum and range values of the YAxis with the given minimum and maximum values from the chart data.
    /// - parameter dataMin: the y-min value according to chart data
    /// - parameter dataMax: the y-max value according to chart
    @objc open func calculate(min dataMin: Double, max dataMax: Double)
    {
        // if custom, use value as is, else use data value
        var min = _customAxisMin ? _axisMinimum : (dataMin - spaceMin)
        var max = _customAxisMax ? _axisMaximum : (dataMax + spaceMax)
        
        // temporary range (before calculations)
        let range = abs(max - min)
        
        // in case all values are equal
        if range == 0.0
        {
            max = max + 1.0
            min = min - 1.0
        }
        
        _axisMinimum = min
        _axisMaximum = max
        
        // actual range
        axisRange = abs(max - min)
    }
}
 | 
	e4db6c025063f8219081fa1edf8960fe | 31.202156 | 168 | 0.611199 | false | false | false | false | 
| 
	russbishop/swift | 
	refs/heads/master | 
	test/Interpreter/SDK/KVO.swift | 
	apache-2.0 | 
	1 | 
	// RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
var kvoContext = 0
class Model : NSObject {
  dynamic var name = ""
  dynamic var number = 0
}
class Observer : NSObject {
  let model = Model()
  override init() {
    super.init()
    model.addObserver(self, forKeyPath: "name", options: [], context: &kvoContext)
    self.addObserver(self, forKeyPath: "model.number", options: [], context: &kvoContext)
  }
  deinit {
    self.removeObserver(self, forKeyPath: "model.number")
    model.removeObserver(self, forKeyPath: "name")
  }
  func test() {
    model.name = "abc"
    model.number = 42
  }
  override func observeValue(forKeyPath keyPath: String?, of object: AnyObject?, change: [NSKeyValueChangeKey : AnyObject]?, context: UnsafeMutablePointer<Void>?) {
    if context != &kvoContext {
      // FIXME: we shouldn't need to unwrap these here, but it doesn't work on
      // older SDKs where these are non-optional types.
      return super.observeValue(forKeyPath: keyPath!, of: object!, change: change!, context: context)
    }
    print(object!.value(forKeyPath: keyPath!))
  }
}
// CHECK: abc
// CHECK-NEXT: 42
Observer().test()
class Foo: NSObject {
  let foo = 0
}
let foo = Foo()
foo.addObserver(foo, forKeyPath: "foo", options: [], context: &kvoContext)
let bar = foo.foo
// CHECK-NEXT: 0
print(bar)
 | 
	d35725c1d15321d0e4554954de10a1a5 | 23.561404 | 164 | 0.672857 | false | true | false | false | 
| 
	shuuchen/SwiftTips | 
	refs/heads/master | 
	nested_types.swift | 
	mit | 
	1 | 
	// nested types
// nest enumerations, classes, structures
// within the definition of the type they support
struct BlackjackCard {
   
    // nested Suit enumeration
    enum Suit: Character {
   
        case Spades = "♠", Hearts = "♡", Diamonds = "♢", Clubs = "♣"
    }
   
    // nested Rank enumeration
    enum Rank: Int {
   
        case Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten
        case Jack, Queen, King, Ace
       
        struct Values {
       
            let first: Int, second: Int?
        }
       
        var values: Values {
       
            switch self {
       
            case .Ace:
                return Values(first: 1, second: 11)
       
            case .Jack, .Queen, .King:
                return Values(first: 10, second: nil)
       
            default:
                return Values(first: self.rawValue, second: nil)
            }
        }
    }
   
    // BlackjackCard properties and methods
    let rank: Rank, suit: Suit
   
    var description: String {
   
        var output = "suit is \(suit.rawValue),"
        output += " value is \(rank.values.first)"
   
        if let second = rank.values.second {
   
            output += " or \(second)"
        }
       
        return output
    }
}
let theAceOfSpades = BlackjackCard(rank: .Ace, suit: .Spades)
print("theAceOfSpades: \(theAceOfSpades.description)")
// prints "theAceOfSpades: suit is ♠, value is 1 or 11"
// referring to nested types
// using a nested type outside of its definition context
let heartsSymbol = BlackjackCard.Suit.Hearts.rawValue
// heartsSymbol is "♡"
 | 
	a8a4af1d1ac78cd7d32fe8acfc125602 | 23.676923 | 69 | 0.547382 | false | false | false | false | 
| 
	atomkirk/TouchForms | 
	refs/heads/master | 
	TouchForms/Source/TextFieldFormElement.swift | 
	mit | 
	1 | 
	//
//  TextFieldFormElement.swift
//  TouchForms
//
//  Created by Adam Kirk on 7/25/15.
//  Copyright (c) 2015 Adam Kirk. All rights reserved.
//
import UIKit
public class TextFieldFormElement: FormElement {
    public var label: String?
    public init(label: String? = nil) {
        self.label = label
    }
    // MARK: - Overrides
    public override func populateCell() {
        if let cell = cell as? TextFieldFormCell, let label = label {
            cell.formTextField?.placeholder = label
        }
        super.populateCell()
    }
    public override func isEditable() -> Bool {
        return true
    }
    public override func beginEditing() {
        cell?.textInput?.becomeFirstResponder()
    }
}
 | 
	1190ee3c447b9ea6562c3c1c419211d5 | 18.184211 | 69 | 0.620027 | false | false | false | false | 
| 
	iWeslie/Ant | 
	refs/heads/master | 
	Ant/Ant/Main/NewsTableView.swift | 
	apache-2.0 | 
	2 | 
	//
//  NewsTableView.swift
//  AntDemo
//
//  Created by LiuXinQiang on 2017/7/3.
//  Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
import MJRefresh
import SDWebImage
import SVProgressHUD
//定义闭包类型
typealias  showNewsDetailType = (String?, NSURL?) -> ()
class NewsTableView: UITableView ,UITableViewDelegate, UITableViewDataSource{
    //定义跳转闭包
    var showNewsDetailClouse : showNewsDetailType?
    //定义页号p值
    var p = 1
    //定义加载的新闻分类号
    var cate_id  = 0
    var  tableView = UITableView()
    //模型数组
    lazy var  modelArray =  [NewsListModel]()
    //轮播新闻数组
    lazy var  rotaionArray = [NewsRotationModel]()
    let  imageArray = ["http://news.xinhuanet.com/photo/2017-07/07/1121277850_14993686707431n.jpg",
                       "https://imgsa.baidu.com/news/q%3D100/sign=b65364338826cffc6f2abbb289004a7d/a1ec08fa513d269758f81af75ffbb2fb4316d874.jpg",
                        "https://imgsa.baidu.com/news/q%3D100/sign=23c77afa3ea85edffc8cfa23795509d8/fd039245d688d43f18628258771ed21b0ff43b54.jpg"]
    
    //创建模型数组\
    let  cellID = "NewsOne"
    let  threeCellId = "threeCell"
    
    //天气控件
    lazy   var  weatherView  = UIView()
    
    var imageScrollView : TopScrollView?
  
    
    init(frame: CGRect, style: UITableViewStyle , cateID : Int) {
        super.init(frame: frame, style: style)
        tableView = self
        tableView.delegate = self
        tableView.dataSource = self
        tableView.showsHorizontalScrollIndicator = false
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        self.tableView.separatorStyle = .none
        // 注册单图片nib
        tableView.register(UINib.init(nibName: "NewsTypeTableCell", bundle: nil), forCellReuseIdentifier: cellID)
        //注册多图片nib
        tableView.register(UINib.init(nibName:"NewsThreeImageCell", bundle: nil), forCellReuseIdentifier: threeCellId)
          SVProgressHUD.show()
        NetWorkTool.shareInstance.newsList("\(cateID)", p: "\(p)") { (newsInfo, error) in
            
            weak var weakSelf  = self
            self.cate_id = cateID
            if error == nil {
                SVProgressHUD.dismiss()
                let result = newsInfo?["result"] as? NSDictionary
                let listArr = result?["list"] as? NSArray
                for i  in 0..<listArr!.count {
                    let dict = listArr?[i] as? NSDictionary
                    
                    let  newListModel = NewsListModel.mj_object(withKeyValues: dict)
                    if(newListModel != nil){
                        weakSelf?.modelArray.append(newListModel!)
                    }
                }
             weakSelf?.tableView.separatorStyle = .singleLine
                weakSelf?.reloadData()
            }
        }
        //设置回调
        //默认下拉刷新
        tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(NewsTableView.refresh))
        // 马上进入刷新状态
        self.tableView.mj_header.beginRefreshing()
        //上拉刷新
        tableView.mj_footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(NewsTableView.loadMore))
        // 设置自动切换透明度(在导航栏下面自动隐藏)
        self.tableView.mj_header.isAutomaticallyChangeAlpha = true
        //创建分页控制器
        creatPageVC(cateID: cateID)
    }
    
    func  loadMore() {
        self.p += 1
        NetWorkTool.shareInstance.newsList("\(cate_id)", p: "\(p)") { (newsInfo, error) in
            weak var weakSelf  = self
            if error == nil {
                 let result = newsInfo?["result"] as? NSDictionary
                 let listArr  = result?["list"] as? NSArray
                 let  arrayCount =  weakSelf?.modelArray.count
                for i  in 0..<listArr!.count {
                    let dict = listArr?[i] as? NSDictionary
                    let  newListModel = NewsListModel.mj_object(withKeyValues: dict)
                    if(newListModel != nil){
                        weakSelf?.modelArray.append(newListModel!)
                    }
                }
                if arrayCount ==  weakSelf?.modelArray.count{ //结束刷新
                    weakSelf?.mj_footer.endRefreshingWithNoMoreData()
                }else {
                    weakSelf?.mj_footer.endRefreshing()
                }
                //重新调用数据接口
                self.reloadData()
            }
        }
    }
    
    
    func  refresh() {
        weak var  weakself = self
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.8, execute: {
            //结束刷新
            weakself?.mj_header.endRefreshing()
            //重新调用数据接口
            self.reloadData()
        })
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //创建分页控制器
    func creatPageVC(cateID : Int) -> () {
        if cateID  == 1 {
        //网路请求url
        NetWorkTool.shareInstance.rotationList { [weak self](info, error) in
            if info?["code"] as? String == "200"{
                let result  = info?["result"] as? NSArray
                for  news  in result! {
                    let rotationModel = NewsRotationModel.mj_object(withKeyValues: news)
                    self?.rotaionArray.append(rotationModel!)
                }
         
                let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 160)
                self?.imageScrollView = TopScrollView(rotaionArray : (self?.rotaionArray)!, frame: frame, isAutoScroll: true)
                self?.imageScrollView?.imageClickedHandler = { i  in
                    let  model =  self?.rotaionArray[i]
                    let number = (model?.id)!
                    let url = NSURL.init(string: (model?.url!)!)
                    if self?.showNewsDetailClouse != nil {
                        
                        self?.showNewsDetailClouse!("\(String(describing: number))", url)
                    }
                }
                let   headerView = UIView(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: 190))
                headerView.addSubview((self?.imageScrollView!)!)
                self?.weatherView = (self?.createWheather())!
                headerView.addSubview((self?.weatherView)!)
                self?.tableView.tableHeaderView = headerView
    
            }
        }
     }
    }
    
    //创建天气显示界面
    func createWheather() -> (UIView) {
          let   weatherView =   UIView(frame: CGRect.init(x: 0, y: (self.imageScrollView?.frame.maxY)!, width: screenWidth, height: 30))
          weatherView.layer.borderWidth = 1
          weatherView.layer.borderColor = UIColor.lightGray.cgColor
           // 创建日期lable
           let dateLable = UILabel()
           dateLable.frame.size = CGSize.init(width: 70, height: 15)
           dateLable.center.y  = weatherView.frame.height / 2
           dateLable.textColor = UIColor.lightGray
           dateLable.frame.origin.x = 20
  
           dateLable.font = UIFont.systemFont(ofSize: 15)
            weatherView.addSubview(dateLable)
         //创建天气图标
          let  weatherImage = UIImageView.init()
          weatherImage.frame.size = CGSize.init(width: 25, height: 25)
          weatherImage.center.y = dateLable.center.y
          weatherImage.frame.origin.x = (screenWidth / 2) - 50
         weatherView.addSubview(weatherImage)
        // 创建天气button
          let weatherBtn = UIButton()
          weatherBtn.frame.size = CGSize.init(width: 90, height: 40)
          weatherBtn.contentHorizontalAlignment = .left
          weatherBtn.center.y = dateLable.center.y
          weatherBtn.frame.origin.x = (screenWidth / 2) - 15
          weatherBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
          weatherBtn.setTitleColor(UIColor.lightGray, for: .normal)
          weatherView.addSubview(weatherBtn)
      
        
        
           // 创建温度lable
        let tempLable = UILabel()
        tempLable.frame.size = CGSize.init(width: 50, height: 15)
        tempLable.center.y  = weatherView.frame.height / 2
        tempLable.frame.origin.x = screenWidth - 60
        tempLable.font = UIFont.systemFont(ofSize: 15)
        tempLable.textColor = UIColor.lightGray
        weatherView.addSubview(tempLable)
        
        NetWorkTool.shareInstance.weather("Canberra") { (weatherInfo, error) in
         
            if error == nil {
                let result = weatherInfo?["result"] as? NSDictionary
                let  weatherModel = WeatherModel.mj_object(withKeyValues: result)
                  dateLable.text = weatherModel?.time
                  weatherBtn.setTitle(weatherModel?.txt, for: .normal)
                  weatherImage.sd_setImage(with: NSURL.init(string: (weatherModel?.code!)!)! as URL)
                
                  tempLable.text = weatherModel?.tmp
            }
        }
        
        return weatherView
    }
    
    
  
}
//MARK: - tableview  代理方法
extension  NewsTableView {
  
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.modelArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
          var  cell : UITableViewCell?
         let  model =  self.modelArray[indexPath.row]
        if (model.picture?.count)! < 3 {
        let  cellone = tableView.dequeueReusableCell(withIdentifier: cellID) as! NewsTypeTableCell
        cellone.newsSource.text = model.source
        cellone.newsTitle.text = model.title
        cellone.newsImage.sd_setImage(with: NSURL.init(string: model.picture![0] as! String)! as URL, placeholderImage: UIImage.init(named: "moren"))
        cellone.newlistModel = self.modelArray[indexPath.row]
        cell = cellone
        }else {
         let   cellThree = tableView.dequeueReusableCell(withIdentifier: threeCellId) as? NewsThreeImageCell
         cellThree?.newsTitle.text = model.title
         cellThree?.scourceText.text = model.source
         cellThree?.newsFirstImageView.sd_setImage(with: NSURL.init(string: model.picture![0] as! String)! as URL, placeholderImage: UIImage.init(named: "moren"))
          
         cellThree?.newsSecondImageView.sd_setImage(with: NSURL.init(string: model.picture![1] as! String)! as URL, placeholderImage: UIImage.init(named: "moren"))
         cellThree?.newsThridImageView.sd_setImage(with: NSURL.init(string: model.picture![2] as! String)! as URL, placeholderImage: UIImage.init(named: "moren"))
         cell = cellThree
        }
        cell?.selectionStyle = .none
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        var  tempNum  :  CGFloat?
        let  model =  self.modelArray[indexPath.row]
        if (model.picture?.count)! < 3 {
         tempNum = 110
        }else {
            tempNum  = 150
        }
        return tempNum!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         let  model =  self.modelArray[indexPath.row]
          let number = model.id!
          let url = NSURL.init(string: model.url!)
        if self.showNewsDetailClouse != nil {
            self.showNewsDetailClouse!("\(String(describing: number))", url)
        }
        
    }
}
 | 
	1319caea7c75cb9d09acafd6b8c5852b | 38.346021 | 163 | 0.587811 | false | false | false | false | 
| 
	movabletype/smartphone-app | 
	refs/heads/master | 
	MT_iOS/MT_iOS/Classes/ViewController/EntryRichTextViewController.swift | 
	mit | 
	2 | 
	//
//  EntryRichTextViewController.swift
//  MT_iOS
//
//  Created by CHEEBOW on 2015/06/05.
//  Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
import ZSSRichTextEditor
class EntryRichTextViewController: MTRichTextEditor {
    var object: EntryTextAreaItem!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.whiteColor()
        
        self.title = object.label
        self.setHTML(object.text)
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "saveButtonPushed:")
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "back_arw"), left: true, target: self, action: "backButtonPushed:")
    }
    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.
    }
    */
    
    private func sourceView()-> ZSSTextView? {
        for view in self.view.subviews {
            if view is ZSSTextView {
                return view as? ZSSTextView
            }
        }
        return nil
    }
    
    @IBAction func saveButtonPushed(sender: UIBarButtonItem) {
        if let sourceView = self.sourceView() {
            if !sourceView.hidden {
                self.setHTML(sourceView.text)
            }
        }
        object.text = self.getHTML()
        object.isDirty = true
        self.navigationController?.popViewControllerAnimated(true)
    }
    @IBAction func backButtonPushed(sender: UIBarButtonItem) {
        if let sourceView = self.sourceView() {
            if !sourceView.hidden {
                self.setHTML(sourceView.text)
            }
        }
        if self.getHTML() == object.text {
            self.navigationController?.popViewControllerAnimated(true)
            return
        }
        
        Utils.confrimSave(self)
    }
}
 | 
	7033a0ae60d1c28c461336d78865d376 | 29.415584 | 156 | 0.632792 | false | false | false | false | 
| 
	sadawi/MagneticFields | 
	refs/heads/master | 
	Pod/Classes/operators.swift | 
	mit | 
	1 | 
	//
//  operators.swift
//  Pods
//
//  Created by Sam Williams on 11/27/15.
//
//
import Foundation
public func ==<T:Equatable>(left: Field<T>, right: T) -> Bool {
    return left.value == right
}
public func ==<T>(left: T, right: Field<T>) -> Bool {
    return left == right.value
}
 | 
	4629d81b359bd791ad6e23908abd2f80 | 15 | 63 | 0.600694 | false | false | false | false | 
| 
	ahoppen/swift | 
	refs/heads/main | 
	test/Concurrency/concurrent_value_checking.swift | 
	apache-2.0 | 
	2 | 
	// RUN: %target-typecheck-verify-swift  -disable-availability-checking -warn-concurrency -parse-as-library
// REQUIRES: concurrency
class NotConcurrent { } // expected-note 27{{class 'NotConcurrent' does not conform to the 'Sendable' protocol}}
// ----------------------------------------------------------------------
// Sendable restriction on actor operations
// ----------------------------------------------------------------------
actor A1 {
  let localLet: NotConcurrent = NotConcurrent()
  func synchronous() -> NotConcurrent? { nil }
  func asynchronous(_: NotConcurrent?) async { }
}
// Actor initializers and Sendable
actor A2 {
  var localVar: NotConcurrent
  init(value: NotConcurrent) {
    self.localVar = value
  }
  convenience init(forwardSync value: NotConcurrent) {
    self.init(value: value)
  }
  convenience init(delegatingSync value: NotConcurrent) {
    self.init(forwardSync: value)
  }
  init(valueAsync value: NotConcurrent) async {
    self.localVar = value
  }
  convenience init(forwardAsync value: NotConcurrent) async {
    await self.init(valueAsync: value)
  }
  nonisolated convenience init(nonisoAsync value: NotConcurrent, _ c: Int) async {
    if c == 0 {
      await self.init(valueAsync: value)
    } else {
      self.init(value: value)
    }
  }
  convenience init(delegatingAsync value: NotConcurrent, _ c: Int) async {
    if c == 0 {
      await self.init(valueAsync: value)
    } else if c == 1 {
      self.init(value: value)
    } else if c == 2 {
      await self.init(forwardAsync: value)
    } else {
      self.init(delegatingSync: value)
    }
  }
}
func testActorCreation(value: NotConcurrent) async {
  _ = A2(value: value) // expected-warning{{non-sendable type 'NotConcurrent' passed in call to nonisolated initializer 'init(value:)' cannot cross actor boundary}}
  _ = await A2(valueAsync: value) // expected-warning{{non-sendable type 'NotConcurrent' passed in call to actor-isolated initializer 'init(valueAsync:)' cannot cross actor boundary}}
  _ = A2(delegatingSync: value) // expected-warning{{non-sendable type 'NotConcurrent' passed in call to nonisolated initializer 'init(delegatingSync:)' cannot cross actor boundary}}
  _ = await A2(delegatingAsync: value, 9) // expected-warning{{non-sendable type 'NotConcurrent' passed in call to actor-isolated initializer 'init(delegatingAsync:_:)' cannot cross actor boundary}}
  _ = await A2(nonisoAsync: value, 3) // expected-warning{{non-sendable type 'NotConcurrent' passed in call to nonisolated initializer 'init(nonisoAsync:_:)' cannot cross actor boundary}}
}
extension A1 {
  func testIsolation(other: A1) async {
    // All within the same actor domain, so the Sendable restriction
    // does not apply.
    _ = localLet
    _ = synchronous()
    _ = await asynchronous(nil)
    _ = self.localLet
    _ = self.synchronous()
    _ = await self.asynchronous(nil)
    // Across to a different actor, so Sendable restriction is enforced.
    _ = other.localLet // expected-warning{{non-sendable type 'NotConcurrent' in asynchronous access to actor-isolated property 'localLet' cannot cross actor boundary}}
    _ = await other.synchronous() // expected-warning{{non-sendable type 'NotConcurrent?' returned by implicitly asynchronous call to actor-isolated instance method 'synchronous()' cannot cross actor boundary}}
    _ = await other.asynchronous(nil) // expected-warning{{non-sendable type 'NotConcurrent?' passed in call to actor-isolated instance method 'asynchronous' cannot cross actor boundary}}
  }
}
// ----------------------------------------------------------------------
// Sendable restriction on global actor operations
// ----------------------------------------------------------------------
actor TestActor {}
@globalActor
struct SomeGlobalActor {
  static var shared: TestActor { TestActor() }
}
@SomeGlobalActor
let globalValue: NotConcurrent? = nil
@SomeGlobalActor
func globalSync(_: NotConcurrent?) {
}
@SomeGlobalActor
func globalAsync(_: NotConcurrent?) async {
  await globalAsync(globalValue) // both okay because we're in the actor
  globalSync(nil)
}
func globalTest() async {
  let a = globalValue // expected-warning{{non-sendable type 'NotConcurrent?' in asynchronous access to global actor 'SomeGlobalActor'-isolated let 'globalValue' cannot cross actor boundary}}
  await globalAsync(a) // expected-warning{{non-sendable type 'NotConcurrent?' passed in implicitly asynchronous call to global actor 'SomeGlobalActor'-isolated function cannot cross actor boundary}}
  await globalSync(a)  // expected-warning{{non-sendable type 'NotConcurrent?' passed in call to global actor 'SomeGlobalActor'-isolated function cannot cross actor boundary}}
}
struct HasSubscript {
  @SomeGlobalActor
  subscript (i: Int) -> NotConcurrent? { nil }
}
class ClassWithGlobalActorInits { // expected-note 2{{class 'ClassWithGlobalActorInits' does not conform to the 'Sendable' protocol}}
  @SomeGlobalActor
  init(_: NotConcurrent) { }
  @SomeGlobalActor
  init() { }
}
@MainActor
func globalTestMain(nc: NotConcurrent) async {
  let a = globalValue // expected-warning{{non-sendable type 'NotConcurrent?' in asynchronous access to global actor 'SomeGlobalActor'-isolated let 'globalValue' cannot cross actor boundary}}
  await globalAsync(a) // expected-warning{{non-sendable type 'NotConcurrent?' passed in implicitly asynchronous call to global actor 'SomeGlobalActor'-isolated function cannot cross actor boundary}}
  await globalSync(a)  // expected-warning{{non-sendable type 'NotConcurrent?' passed in call to global actor 'SomeGlobalActor'-isolated function cannot cross actor boundary}}
  _ = await ClassWithGlobalActorInits(nc) // expected-warning{{non-sendable type 'NotConcurrent' passed in call to global actor 'SomeGlobalActor'-isolated function cannot cross actor boundary}}
  // expected-warning@-1{{non-sendable type 'ClassWithGlobalActorInits' returned by call to global actor 'SomeGlobalActor'-isolated function cannot cross actor boundary}}
  _ = await ClassWithGlobalActorInits() // expected-warning{{non-sendable type 'ClassWithGlobalActorInits' returned by call to global actor 'SomeGlobalActor'-isolated function cannot cross actor boundary}}
}
@SomeGlobalActor
func someGlobalTest(nc: NotConcurrent) {
  let hs = HasSubscript()
  let _ = hs[0] // okay
  _ = ClassWithGlobalActorInits(nc)
}
// ----------------------------------------------------------------------
// Sendable restriction on captures.
// ----------------------------------------------------------------------
func acceptNonConcurrent(_: () -> Void) { }
func acceptConcurrent(_: @Sendable () -> Void) { }
func testConcurrency() {
  let x = NotConcurrent()
  var y = NotConcurrent()
  y = NotConcurrent()
  acceptNonConcurrent {
    print(x) // okay
    print(y) // okay
  }
  acceptConcurrent {
    print(x) // expected-warning{{capture of 'x' with non-sendable type 'NotConcurrent' in a `@Sendable` closure}}
    print(y) // expected-warning{{capture of 'y' with non-sendable type 'NotConcurrent' in a `@Sendable` closure}}
    // expected-error@-1{{reference to captured var 'y' in concurrently-executing code}}
  }
}
@preconcurrency func acceptUnsafeSendable(_ fn: @Sendable () -> Void) { }
func testUnsafeSendableNothing() {
  var x = 5
  acceptUnsafeSendable {
    x = 17 // expected-error{{mutation of captured var 'x' in concurrently-executing code}}
  }
  print(x)
}
func testUnsafeSendableInAsync() async {
  var x = 5
  acceptUnsafeSendable {
    x = 17 // expected-error{{mutation of captured var 'x' in concurrently-executing code}}
  }
  print(x)
}
// ----------------------------------------------------------------------
// Sendable restriction on key paths.
// ----------------------------------------------------------------------
class NC: Hashable { // expected-note 2{{class 'NC' does not conform to the 'Sendable' protocol}}
  func hash(into: inout Hasher) { }
  static func==(_: NC, _: NC) -> Bool { true }
}
class HasNC {
  var dict: [NC: Int] = [:]
}
func testKeyPaths(dict: [NC: Int], nc: NC) {
  _ = \HasNC.dict[nc] // expected-warning{{cannot form key path that captures non-sendable type 'NC'}}
}
// ----------------------------------------------------------------------
// Sendable restriction on nonisolated declarations.
// ----------------------------------------------------------------------
actor ANI {
  nonisolated let nc = NC()
  nonisolated func f() -> NC? { nil }
}
func testANI(ani: ANI) async {
  _ = ani.nc // expected-warning{{non-sendable type 'NC' in asynchronous access to nonisolated property 'nc' cannot cross actor boundary}}
}
// ----------------------------------------------------------------------
// Sendable restriction on conformances.
// ----------------------------------------------------------------------
protocol AsyncProto {
  func asyncMethod(_: NotConcurrent) async
}
extension A1: AsyncProto {
  func asyncMethod(_: NotConcurrent) async { } // expected-warning{{non-sendable type 'NotConcurrent' in parameter of actor-isolated instance method 'asyncMethod' satisfying non-isolated protocol requirement cannot cross actor boundary}}
}
protocol MainActorProto {
  func asyncMainMethod(_: NotConcurrent) async
}
class SomeClass: MainActorProto {
  @SomeGlobalActor
  func asyncMainMethod(_: NotConcurrent) async { } // expected-warning{{non-sendable type 'NotConcurrent' in parameter of global actor 'SomeGlobalActor'-isolated instance method 'asyncMainMethod' satisfying non-isolated protocol requirement cannot cross actor boundary}}
}
// ----------------------------------------------------------------------
// Sendable restriction on concurrent functions.
// ----------------------------------------------------------------------
@Sendable func concurrentFunc() -> NotConcurrent? { nil }
// ----------------------------------------------------------------------
// No Sendable restriction on @Sendable function types.
// ----------------------------------------------------------------------
typealias CF = @Sendable () -> NotConcurrent?
typealias BadGenericCF<T> = @Sendable () -> T?
typealias GoodGenericCF<T: Sendable> = @Sendable () -> T? // okay
var concurrentFuncVar: (@Sendable (NotConcurrent) -> Void)? = nil
// ----------------------------------------------------------------------
// Sendable restriction on @Sendable closures.
// ----------------------------------------------------------------------
func acceptConcurrentUnary<T>(_: @Sendable (T) -> T) { }
func concurrentClosures<T>(_: T) {
  acceptConcurrentUnary { (x: T) in
    _ = x // ok
    acceptConcurrentUnary { _ in x } // expected-warning{{capture of 'x' with non-sendable type 'T' in a `@Sendable` closure}}
  }
}
// ----------------------------------------------------------------------
// Sendable checking
// ----------------------------------------------------------------------
struct S1: Sendable {
  var nc: NotConcurrent // expected-warning{{stored property 'nc' of 'Sendable'-conforming struct 'S1' has non-sendable type 'NotConcurrent'}}
}
struct S2<T>: Sendable {
  var nc: T // expected-warning{{stored property 'nc' of 'Sendable'-conforming generic struct 'S2' has non-sendable type 'T'}}
}
struct S3<T> {
  var c: T
  var array: [T]
}
extension S3: Sendable where T: Sendable { }
enum E1: Sendable {
  case payload(NotConcurrent) // expected-warning{{associated value 'payload' of 'Sendable'-conforming enum 'E1' has non-sendable type 'NotConcurrent'}}
}
enum E2<T> {
  case payload(T)
}
extension E2: Sendable where T: Sendable { }
final class C1: Sendable {
  let nc: NotConcurrent? = nil // expected-warning{{stored property 'nc' of 'Sendable'-conforming class 'C1' has non-sendable type 'NotConcurrent?'}}
  var x: Int = 0 // expected-warning{{stored property 'x' of 'Sendable'-conforming class 'C1' is mutable}}
  let i: Int = 0
}
final class C2: Sendable {
  let x: Int = 0
}
class C3 { }
class C4: C3, @unchecked Sendable {
  var y: Int = 0 // okay
}
class C5: @unchecked Sendable {
  var x: Int = 0 // okay
}
class C6: C5 {
  var y: Int = 0 // still okay, it's unsafe
}
final class C7<T>: Sendable { }
class C9: Sendable { } // expected-warning{{non-final class 'C9' cannot conform to 'Sendable'; use '@unchecked Sendable'}}
extension NotConcurrent {
  func f() { }
  func test() {
    Task {
      f() // expected-warning{{capture of 'self' with non-sendable type 'NotConcurrent' in a `@Sendable` closure}}
    }
    Task {
      self.f()  // expected-warning{{capture of 'self' with non-sendable type 'NotConcurrent' in a `@Sendable` closure}}
    }
    Task { [self] in
      f()  // expected-warning{{capture of 'self' with non-sendable type 'NotConcurrent' in a `@Sendable` closure}}
    }
    Task { [self] in
      self.f()  // expected-warning{{capture of 'self' with non-sendable type 'NotConcurrent' in a `@Sendable` closure}}
    }
  }
}
// ----------------------------------------------------------------------
// @unchecked Sendable disabling checking
// ----------------------------------------------------------------------
struct S11: @unchecked Sendable {
  var nc: NotConcurrent // okay
}
struct S12<T>: @unchecked Sendable {
  var nc: T // okay
}
enum E11<T>: @unchecked Sendable {
  case payload(NotConcurrent) // okay
  case other(T) // okay
}
class C11 { }
class C12: @unchecked C11 { } // expected-error{{'unchecked' attribute cannot apply to non-protocol type 'C11'}}
protocol P { }
protocol Q: @unchecked Sendable { } // expected-error{{'unchecked' attribute only applies in inheritance clauses}}
typealias TypeAlias1 = @unchecked P // expected-error{{'unchecked' attribute only applies in inheritance clauses}}
// ----------------------------------------------------------------------
// UnsafeSendable historical name
// ----------------------------------------------------------------------
enum E12<T>: UnsafeSendable { // expected-warning{{'UnsafeSendable' is deprecated: Use @unchecked Sendable instead}}
  case payload(NotConcurrent) // okay
  case other(T) // okay
}
// ----------------------------------------------------------------------
// @Sendable inference through optionals
// ----------------------------------------------------------------------
func testSendableOptionalInference(nc: NotConcurrent) {
  var fn: (@Sendable () -> Void)? = nil
  fn = {
    print(nc) // expected-warning{{capture of 'nc' with non-sendable type 'NotConcurrent' in a `@Sendable` closure}}
  }
  _ = fn
}
 | 
	d4cf2ff15cb5bbf78c0022a078639bef | 36.45478 | 270 | 0.620973 | false | false | false | false | 
| 
	honghaoz/CrackingTheCodingInterview | 
	refs/heads/master | 
	Swift/LeetCode/Tree/270_Closest Binary Search Tree Value.swift | 
	mit | 
	1 | 
	// 270_Closest Binary Search Tree Value
// https://leetcode.com/problems/closest-binary-search-tree-value/
//
// Created by Honghao Zhang on 9/16/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
//
//Note:
//
//Given target value is a floating point.
//You are guaranteed to have only one unique value in the BST that is closest to the target.
//Example:
//
//Input: root = [4,2,5,1,3], target = 3.714286
//
//    4
//   / \
//  2   5
// / \
//1   3
//
//Output: 4
//
import Foundation
// 在一个BST中寻找里target值最近的node的值
class Num270 {
  /// TODO: BST solutions
  // https://leetcode.com/problems/closest-binary-search-tree-value/solution/
  /// Binary search
  func closestValue_binarySearch(_ root: TreeNode?, _ target: Double) -> Int {
    guard root != nil else {
      return -1
    }
    var closest: Int?
    var p = root
    while p != nil {
      // 1) update result
      if closest == nil {
        closest = p!.val
      } else {
        // find a new closer value
        if abs(Double(p!.val) - target) < abs(Double(closest!) - target) {
          closest = p!.val
        }
      }
      // 2) traverse
      if Double(p!.val) < target {
        // go right
        p = p!.right
      }
      else if Double(p!.val) > target {
        // go left
        p = p!.left
      }
      else {
        // 0, is the most closest value
        return p!.val
      }
    }
    return closest!
  }
}
 | 
	8476ada60e0240b2165f436b55a58559 | 21.1 | 116 | 0.574661 | false | false | false | false | 
| 
	hejunbinlan/RealmResultsController | 
	refs/heads/master | 
	Example/RealmResultsController-iOSTests/RealmLoggerTests.swift | 
	mit | 
	1 | 
	//
//  RealmLoggerTests.swift
//  RealmResultsController
//
//  Created by Pol Quintana on 6/8/15.
//  Copyright © 2015 Redbooth.
//
import Foundation
import Quick
import Nimble
import RealmSwift
@testable import RealmResultsController
class NotificationListener {
    static let sharedInstance = NotificationListener()
    var array: [String : [RealmChange]] = [:]
    
    @objc func notificationReceived(notification: NSNotification) {
        array = notification.object as! [String : [RealmChange]]
    }
}
class NotificationObserver {
    
    var notificationReceived: Bool = false
    init() {
        NSNotificationCenter.defaultCenter().addObserverForName("Task-123", object: nil, queue: nil) { (notification) -> Void in
            self.notificationReceived = true
        }
    }
}
class RealmLoggerSpec: QuickSpec {
    override func spec() {
        var realm: Realm!
        var logger: RealmLogger!
        beforeSuite {
            let configuration = Realm.Configuration(inMemoryIdentifier: "testingRealm")
            realm = try! Realm(configuration: configuration)
            logger = RealmLogger(realm: realm)
        }
        
        describe("init(realm:)") {
            var newLogger: RealmLogger!
            beforeEach {
                newLogger = RealmLogger(realm: realm)
            }
            it("Should have a valid realm and a notificationToken") {
                expect(newLogger.realm) === realm
                expect(newLogger.notificationToken).toNot(beNil())
            }
        }
        
        describe("finishRealmTransaction()") {
            let newObject = RealmChange(type: Task.self, action: .Create, mirror: nil)
            let updatedObject = RealmChange(type: Task.self, action: .Update, mirror: nil)
            let deletedObject = RealmChange(type: Task.self, action: .Delete, mirror: nil)
            beforeEach {
                logger.cleanAll()
                logger.temporary.append(newObject)
                logger.temporary.append(updatedObject)
                logger.temporary.append(deletedObject)
                NSNotificationCenter.defaultCenter().addObserver(NotificationListener.sharedInstance, selector: "notificationReceived:", name: "realmChangesTest", object: nil)
                logger.finishRealmTransaction()
            }
            afterEach {
                NSNotificationCenter.defaultCenter().removeObserver(self)
            }
            it("Should have received a notification with a valid dictionary") {
                let notificationArray = NotificationListener.sharedInstance.array
                var createdObject: Bool = false
                var updatedObject: Bool = false
                var deletedObject: Bool = false
                for object: RealmChange in notificationArray[realm.path]! {
                    if object.action == RealmAction.Create { createdObject = true}
                    if object.action == RealmAction.Update { updatedObject = true}
                    if object.action == RealmAction.Delete { deletedObject = true}
                }
                expect(createdObject).to(beTruthy())
                expect(updatedObject).to(beTruthy())
                expect(deletedObject).to(beTruthy())
            }
        }
        
        describe("didAdd<T: Object>(object: T)") {
            var newObject: Task!
            beforeEach {
                newObject = Task()
                logger.cleanAll()
                newObject.name = "New Task"
                logger.didAdd(newObject)
            }
            afterEach {
                logger.cleanAll()
            }
            it("Should be added to the temporaryAdded array") {
                expect(logger.temporary.count).to(equal(1))
                expect(logger.temporary.first!.action).to(equal(RealmAction.Create))
            }
        }
        
        describe("didUpdate<T: Object>(object: T)") {
            var updatedObject: Task!
            beforeEach {
                updatedObject = Task()
                logger.cleanAll()
                updatedObject.name = "Updated Task"
                logger.didUpdate(updatedObject)
            }
            afterEach {
                logger.cleanAll()
            }
            it("Should be added to the temporaryAdded array") {
                expect(logger.temporary.count).to(equal(1))
                expect(logger.temporary.first!.action).to(equal(RealmAction.Update))
            }
        }
        
        describe("didDelete<T: Object>(object: T)") {
            var deletedObject: Task!
            beforeEach {
                deletedObject = Task()
                logger.cleanAll()
                deletedObject.name = "Deleted Task"
                logger.didDelete(deletedObject)
            }
            afterEach {
                logger.cleanAll()
            }
            it("Should be added to the temporaryAdded array") {
                expect(logger.temporary.count).to(equal(1))
                expect(logger.temporary.first!.action).to(equal(RealmAction.Delete))
            }
        }
        
        describe("finishRealmTransaction()") {
            let observer = NotificationObserver()
            var newObject: RealmChange!
            context("object without mirror") {
                beforeEach {
                    newObject = RealmChange(type: Task.self, action: .Create, mirror: nil)
                    logger.cleanAll()
                    logger.temporary.append(newObject)
                    logger.finishRealmTransaction()
                    logger.cleanAll()
                }
                it("Should remove all the objects in each temporary array") {
                    expect(logger.temporary.count).to(equal(0))
                }
                it("doesn;t send notification") {
                    expect(observer.notificationReceived).to(beFalsy())
                }
            }
            
            context("object with mirror without primaryKey") {
                beforeEach {
                    newObject = RealmChange(type: Task.self, action: .Create, mirror: Dummy())
                    logger.cleanAll()
                    logger.temporary.append(newObject)
                    logger.finishRealmTransaction()
                    logger.cleanAll()
                }
                it("Should remove all the objects in each temporary array") {
                    expect(logger.temporary.count).to(equal(0))
                }
                it("doesn;t send notification") {
                    expect(observer.notificationReceived).to(beFalsy())
                }
            }
            
            context("object with mirror and primaryKey") {
                beforeEach {
                    let task = Task()
                    task.id = 123
                    newObject = RealmChange(type: Task.self, action: .Create, mirror: task)
                    logger.cleanAll()
                    logger.temporary.append(newObject)
                    logger.finishRealmTransaction()
                    logger.cleanAll()
                }
                it("Should remove all the objects in each temporary array") {
                    expect(logger.temporary.count).to(equal(0))
                }
                it("doesn;t send notification") {
                    expect(observer.notificationReceived).to(beTruthy())
                }
            }
        }
    }
} | 
	03c3060b80f855292a88cba7f4988087 | 37.502591 | 175 | 0.532167 | false | false | false | false | 
| 
	dflax/Anagrams | 
	refs/heads/master | 
	Anagrams/Config.swift | 
	mit | 
	1 | 
	//
//  Config.swift
//  Anagrams
//
//  Created by Caroline on 1/08/2014.
//  Copyright (c) 2013 Underplot ltd. All rights reserved.
//
import Foundation
import UIKit
// Device type - true if iPad or iPad Simulator
let isPad: Bool = {
	if (UIDevice.currentDevice().userInterfaceIdiom == .Pad) {
		return true
	} else {
		return false
	}
	}()
//UI constants - will work for any sized screen
let ScreenWidth  = UIScreen.mainScreen().bounds.size.width
let ScreenHeight = UIScreen.mainScreen().bounds.size.height
let TileMargin:    CGFloat = 20.0
let TileYOffset:   UInt32 = 10
// Display HUD details
let FontHUD: UIFont = {
	if (isPad) {
		return UIFont(name:"comic andy", size: 62.0)!
	} else {
		return UIFont(name:"comic andy", size: 25.0)!
	}
}()
let FontHUDBig: UIFont = {
	if (isPad) {
		return UIFont(name:"comic andy", size:120.0)!
	} else {
		return UIFont(name:"comic andy", size: 45.0)!
	}
	}()
let MarginTop: CGFloat = {
	if (isPad) {
		return 100.0
	} else {
		return 40.0
	}
}()
//Random integer generator
func randomNumber(#minX:UInt32, #maxX:UInt32) -> Int {
	let result = (arc4random() % (maxX - minX + 1)) + minX
	return Int(result)
}
 | 
	8b1b96e5e4f2f852f8371c50a2455e14 | 19.315789 | 59 | 0.663212 | false | false | false | false | 
| 
	gauravkatoch007/banana | 
	refs/heads/master | 
	banana/banana.swift | 
	mit | 
	1 | 
	//
//  banana.swift
//  banana
//
//  Created by cdp  on 11/9/15.
//  Copyright © 2015 Katoch. All rights reserved.
//
import Foundation
import UIKit
public class banana : UIViewController, UIScrollViewDelegate {
    
    var imagePageControl: UIPageControl?
    var imageScrollView: UIScrollView!
    var pageImages: [UIImage] = []
    var pageViews: [UIImageView?] = []
    var timer : Timer = Timer()
    var imagesLoaded = false
    public var autoScrollTime : Double = 8
    public var imagesToLoadInMemory = 4
    
    public convenience init ( imageScrollView : UIScrollView, imagePageControl : UIPageControl? = nil){
        self.init()
        self.imageScrollView = imageScrollView
        self.imageScrollView.delegate = self
        self.imagePageControl = imagePageControl
        
    }
//    required public init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
    
    @nonobjc public func load(imagesArrayInput : [String]){
        let priority = DispatchQueue.GlobalQueuePriority.default
        DispatchQueue.global(priority: priority).async() {
            // do some task
            self.getScrollViewImages(imagesArray: imagesArrayInput)
            DispatchQueue.main.async {
                self.loadScrollViewImages()
            }
        }
    }
    
    @nonobjc public func load(imagesArrayInput : [UIImage]){
        let priority = DispatchQueue.GlobalQueuePriority.default
        DispatchQueue.global(priority: priority).async() {
            // do some task
            self.getScrollViewImages(imagesArray: imagesArrayInput)
            DispatchQueue.main.async {
                // update some UI
                self.loadScrollViewImages()
            }
        }
    }
    
    public func startScroll(){
        timer = Timer.scheduledTimer(timeInterval: autoScrollTime, target: self, selector: "autoScrollImage", userInfo: nil, repeats: true)
    }
    
    public func stopScroll(){
        timer.invalidate()
    }
    
    
    
    @nonobjc func getScrollViewImages(imagesArray : [String]){
        for image in imagesArray {
            if let url = NSURL(string: image) {
                if let data = NSData(contentsOf: url as URL){
                    pageImages.append(UIImage(data: data as Data)!)
                }
            }
        }
    }
    
    @nonobjc func getScrollViewImages(imagesArray : [UIImage]){
        for image in imagesArray {
            pageImages.append(image)
        }
    }
    
    func loadScrollViewImages(){
        let pageCount = pageImages.count
        
        // 2
        if imagePageControl != nil {
            imagePageControl!.currentPage = 1
            imagePageControl!.numberOfPages = pageCount
        }
        
        // 3
        for _ in 0..<pageCount {
            pageViews.append(nil)
        }
        
        // 4
        let pagesScrollViewSize = imageScrollView.frame.size
        imageScrollView.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(pageImages.count),
            height: pagesScrollViewSize.height)
        
        // 5
        self.imagesLoaded = true
        loadVisiblePages()
    }
    
    func loadPage(page: Int) {
        if page < 0 || page >= pageImages.count {
            // If it's outside the range of what you have to display, then do nothing
            return
        }
        
        // 1
        if let pageView = pageViews[page] {
            // Do nothing. The view is already loaded.
        } else {
            // 2
            var frame = imageScrollView.bounds
            frame.origin.x = frame.size.width * CGFloat(page)
            frame.origin.y = 0.0
            //            frame = CGRectInset(frame, 10.0, 0.0)
            
            // 3
            let newPageView = UIImageView(image: pageImages[page])
            newPageView.contentMode = .scaleAspectFit
            newPageView.frame = frame
            imageScrollView.addSubview(newPageView)
            
            // 4
            pageViews[page] = newPageView
        }
    }
    
    func purgePage(page: Int) {
        if page < 0 || page >= pageImages.count {
            // If it's outside the range of what you have to display, then do nothing
            return
        }
        
        // Remove a page from the scroll view and reset the container array
        if let pageView = pageViews[page] {
            pageView.removeFromSuperview()
            pageViews[page] = nil
        }
    }
    
    public func loadVisiblePages() {
        // First, determine which page is currently visible
        let pageWidth = imageScrollView.frame.size.width
        var page = Int(floor((imageScrollView.contentOffset.x * 1.0 + pageWidth) / (pageWidth * 1.0))) - 1
        if page >= pageImages.count {
            page = 0
        }
        // Update the page control
        if imagePageControl != nil {
            imagePageControl!.currentPage = page
        }
        
        // Work out which pages you want to load
        let firstPage = page - ( imagesToLoadInMemory / 2 )
        let lastPage = page + ( imagesToLoadInMemory / 2 )
        
        print("First Page ="+String(firstPage))
        print("Last Page ="+String(lastPage))
        
        // Purge anything before the first page
        for var index in 0 ..< firstPage {
            purgePage(page: index)
            index += 1
        }
        
        // Load pages in our range
        for index in firstPage...lastPage {
            loadPage(page: index)
        }
        
        // Purge anything after the last page
        for var index in lastPage+1 ..< pageImages.count {
            purgePage(page: index)
            index += 1
        }
    }
    
    
    @objc public func autoScrollImage (){
        
        let pageWidth:CGFloat = self.imageScrollView.frame.width
        let maxWidth:CGFloat = pageWidth * CGFloat(pageImages.count)
        let contentOffset:CGFloat = self.imageScrollView.contentOffset.x
        
        var slideToX = contentOffset + pageWidth
        
        if  contentOffset + pageWidth == maxWidth{
            slideToX = 0
        }
        
        self.imageScrollView.scrollRectToVisible(CGRect(x: slideToX, y: 0, width: pageWidth, height: self.imageScrollView.frame.height), animated: true)
    }
    
    public func assignTouchGesture(){
        let tapRecognizer = UITapGestureRecognizer(target: self, action: "scrollViewTapped:")
        
        tapRecognizer.numberOfTapsRequired = 1
        //        tapRecognizer.numberOfTouchesRequired = 1
        self.imageScrollView.addGestureRecognizer(tapRecognizer)
        
        let swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
        swipeRight.direction = UISwipeGestureRecognizer.Direction.right
        self.imageScrollView.addGestureRecognizer(swipeRight)
        
        let swipeLeft = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
        swipeLeft.direction = UISwipeGestureRecognizer.Direction.left
        self.imageScrollView.addGestureRecognizer(swipeLeft)
        
        let swipeUp = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
        swipeUp.direction = UISwipeGestureRecognizer.Direction.up
        self.imageScrollView.addGestureRecognizer(swipeUp)
        
        let swipeDown = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
        swipeDown.direction = UISwipeGestureRecognizer.Direction.down
        self.imageScrollView.addGestureRecognizer(swipeDown)
    }
    @objc public func scrollViewTapped(recognizer: UITapGestureRecognizer){
        timer.invalidate()
        if self.imagesLoaded == true {
            loadVisiblePages()
        }
    }
    
    @objc public func respondToSwipeGesture(gesture: UIGestureRecognizer) {
        timer.invalidate()
        if self.imagesLoaded == true {
            loadVisiblePages()
        }
    }
    
    @objc public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        if self.imagesLoaded == true {
            loadVisiblePages()
        }
    }
    
    @objc public func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
        if self.imagesLoaded == true {
            loadVisiblePages()
        }
    }
}
 | 
	4cb59f960ed52140df3fad6e2cc4406b | 32.276 | 152 | 0.596226 | false | false | false | false | 
| 
	lanjing99/iOSByTutorials | 
	refs/heads/master | 
	iOS 8 by tutorials/Chapter 23 - Handoff/ShopSnap-Starter/ShopSnap/ListViewController.swift | 
	mit | 
	1 | 
	/*
* Copyright (c) 2014 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
let AddItemSegueIdentifier  = "AddItemSegueIdentifier"
class ListViewController: UITableViewController, DetailViewControllerDelegate {
  
  // MARK: Public
  
  /** IndexPath of a selected item if any or nil. */
  var selectedItemIndexPath: NSIndexPath?
  
  /** Returns the currently selected item or empty string. */
  func selectedItem() -> String {
    if let indexPath = selectedItemIndexPath {
      return items[indexPath.row]
    }
    return ""
  }
  
  // MARK: Private
  let TableViewCellIdentifier = "TableViewCellIdentifier"
  let EditItemSegueIdentifier = "EditItemSegueIdentifier"
  var items: Array <String> = []
  
  // MARK: View Life Cycle
  
  override func viewDidLoad() {
    title = "Shopping List"
    weak var weakSelf = self
    PersistentStore.defaultStore().fetchItems({ (items:[String]) in
      if let unwrapped = weakSelf {
        unwrapped.items = items
        unwrapped.tableView.reloadData()
        if items.isEmpty == false {
          unwrapped.startUserActivity()
        }
      }
    })
    super.viewDidLoad()
  }
  
  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    let identifier = segue.identifier
    let controller = segue.destinationViewController as! DetailViewController
    controller.delegate = self
    if identifier == EditItemSegueIdentifier {
      controller.item = selectedItem()
    }
    else if identifier == AddItemSegueIdentifier {
      if let indexPath = selectedItemIndexPath {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
      }
      selectedItemIndexPath = nil
    }
    stopUserActivity()
  }
  
  // MARK: Helper
  
  /** A helper method to add a new item to items array, if the new item doesn't already exist. */
  func addItemToItemsIfUnique(item: String) {
    if item.isEmpty == false && (items as NSArray).containsObject(item) == false {
      items.append(item)
    }
  }
  
  /** If in a compact size class, e.g. iPhone once Detail View Controller calls back on its delegate, all we have to do is pop Detail View Controller from navigation stack. But for a regualr size class, e.g. iPad, popToViewController is a noop but we still have to clear previous edit. Since we make similar calls from muliple places in the code, this helper method refactors those calls. */
  func endEditingInDetailViewController(controller: DetailViewController) {
    navigationController!.popToViewController(self, animated: true)
    controller.item = nil
    controller.stopEditing()
  }
  
  // MARK: IBActions
  
  @IBAction func unwindDetailViewController(unwindSegue: UIStoryboardSegue) {
    endEditingInDetailViewController(unwindSegue.sourceViewController as! DetailViewController)
    if let indexPath = selectedItemIndexPath {
      tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    selectedItemIndexPath = nil
    startUserActivity()
  }
  
  // MARK: UITableViewDataSource
  
  override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items.count
  }
  
  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifier) as UITableViewCell!
    cell.textLabel!.text = items[indexPath.row]
    return cell
  }
  
  // MARK: UITableViewDelegate
  
  override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath {
    // We are going to display detail for an item. So ListViewController is not going to be active anymore. Stop broadcasting.
    selectedItemIndexPath = indexPath
    return indexPath
  }
  
  override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
  }
  
  override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
    return .Delete
  }
  
  override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    // Update data source and UI.
    let index = indexPath.row
    let itemToRemove = items[index]
    items.removeAtIndex(index)
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Left)
    
    // Update persistent store.
    PersistentStore.defaultStore().updateStoreWithItems(items)
    PersistentStore.defaultStore().commit()
    
    // If this was the selected index path, we need to do more clean up.
    if indexPath == selectedItemIndexPath {
      selectedItemIndexPath = nil
      if let viewControllers = splitViewController?.viewControllers {
        for controller: AnyObject in viewControllers {
          if controller.isKindOfClass(DetailViewController.self) {
            endEditingInDetailViewController(controller as! DetailViewController)
            break
          }
        }
      }
    }
    
    if items.isEmpty { stopUserActivity()
    } else {
      userActivity?.needsSave = true
    }
  }
  
  // MARK: DetailViewControllerDelegate
  
  func detailViewController(controller controller: DetailViewController, didFinishWithUpdatedItem item: String) {
    // Did user edit an item, or added a new item?
    if selectedItemIndexPath != nil {
      
      // If item is empty string, treat it as deletion of the item.
      let index = selectedItemIndexPath!.row
      if item.isEmpty {
        items.removeAtIndex(index)
      } else {
        items[index] = item
      }
      
    } else {
      
      // This is a new item. Add it to the list.
      addItemToItemsIfUnique(item)
    }
    
    selectedItemIndexPath = nil
    tableView.reloadData()
    endEditingInDetailViewController(controller)
    
    PersistentStore.defaultStore().updateStoreWithItems(items)
    PersistentStore.defaultStore().commit()
    if !items.isEmpty {
      startUserActivity()
    }
  }
  
  func startUserActivity(){
    let activity = NSUserActivity(activityType: ActivityTypeView)
    activity.title = "Viewing Shopping List"
    activity.userInfo = [ActivityItemsKey: items]
    userActivity = activity
    userActivity?.becomeCurrent()
  }
  
  func stopUserActivity(){
    userActivity?.invalidate()
  }
  
  override func updateUserActivityState(activity: NSUserActivity) {
    print("updateUserActivityState")
    activity.addUserInfoEntriesFromDictionary([ActivityItemsKey: items])
    super.updateUserActivityState(activity)
  }
  
  override func restoreUserActivityState(activity: NSUserActivity) {
      if let importedItems = activity.userInfo?[ActivityItemsKey] as? NSArray {
        for item in importedItems {
          addItemToItemsIfUnique(item as! String)
        }
        PersistentStore.defaultStore().updateStoreWithItems(items)
        PersistentStore.defaultStore().commit()
        tableView.reloadData()
      }
      
      super.restoreUserActivityState(activity)
  }
}
 | 
	fb9b089345ab788bdfb3beaf24968bc0 | 31.934959 | 391 | 0.718341 | false | false | false | false | 
| 
	xqz001/WWDC | 
	refs/heads/master | 
	WWDC/MainWindowController.swift | 
	bsd-2-clause | 
	1 | 
	//
//  MainWindowController.swift
//  WWDC
//
//  Created by Guilherme Rambo on 18/04/15.
//  Copyright (c) 2015 Guilherme Rambo. All rights reserved.
//
import Cocoa
class MainWindowController: NSWindowController {
    
    override func windowDidLoad() {
        super.windowDidLoad()
        
        configureWindowAppearance()
        
        NSNotificationCenter.defaultCenter().addObserverForName(NSWindowWillCloseNotification, object: nil, queue: nil) { _ in
            if let window = self.window {
                Preferences.SharedPreferences().mainWindowFrame = window.frame
            }
        }
    }
    
    override func showWindow(sender: AnyObject?) {
        restoreWindowSize()
        
        super.showWindow(sender)
    }
    
    private func configureWindowAppearance()
    {
        if let window = window {
            if let view = window.contentView as? NSView {
                view.wantsLayer = true
            }
            
            window.styleMask |= NSFullSizeContentViewWindowMask
            window.titleVisibility = .Hidden
            window.titlebarAppearsTransparent = true
        }
    }
    
    private func restoreWindowSize()
    {
        if let window = window {
            var savedFrame = Preferences.SharedPreferences().mainWindowFrame
            
            if savedFrame != NSZeroRect {
                if let screen = NSScreen.mainScreen() {
                    // if the screen's height changed between launches, the window can be too big
                    if savedFrame.size.height > screen.frame.size.height {
                        savedFrame.size.height = screen.frame.size.height
                    }
                }
                
                window.setFrame(savedFrame, display: true)
            }
        }
    }
}
 | 
	e6a029183e395915f28ddc2e0046eadc | 28.177419 | 126 | 0.5644 | false | false | false | false | 
| 
	welbesw/easypost-swift | 
	refs/heads/master | 
	Pod/Classes/EasyPostBuyResponse.swift | 
	mit | 
	1 | 
	//
//  EasyPostBuyResponse.swift
//  Pods
//
//  Created by William Welbes on 10/6/15.
//
//
import Foundation
open class EasyPostBuyResponse {
    
    open var postageLabel:EasyPostLabel?
    
    open var trackingCode:String?
    
    open var selectedRate:EasyPostRate?
    
    public init() {
        
    }
    
    public init(jsonDictionary: [String: Any]) {
        //Load the JSON dictionary
        
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"   //2013-04-22T05:40:57Z
        
        if let postageLabelDict = jsonDictionary["postage_label"] as? NSDictionary {
            postageLabel = EasyPostLabel(jsonDictionary: postageLabelDict)
        }
        
        if let stringValue = jsonDictionary["tracking_code"] as? String {
            trackingCode = stringValue
        }
        
        if let rateDict = jsonDictionary["selected_rate"] as? NSDictionary {
            selectedRate = EasyPostRate(jsonDictionary: rateDict)
        }
        
    }
}
 | 
	1d6a3d74b1e1a431beb32850527dfde7 | 24.534884 | 86 | 0.60929 | false | false | false | false | 
| 
	nmdias/FeedKit | 
	refs/heads/master | 
	Example iOS/Extensions/FeedTableViewController + TableViewLayout.swift | 
	mit | 
	1 | 
	//
//  FeedTableViewController + TableViewLayout.swift
//
//  Copyright (c) 2016 - 2018 Nuno Manuel Dias
//
//  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
extension FeedTableViewController {
    enum TableViewLayout {
        case title, link, description, date, items
        init?(indexPath: IndexPath) {
            switch indexPath.section {
            case 0:
                switch indexPath.row {
                case 0: self = .title
                case 1: self = .link
                case 2: self = .description
                case 3: self = .date
                default: return nil
                }
            case 1: self = .items
            default: return nil
            }
        }
    }
}
 | 
	a352f85377d5a2e691f5b376befd6780 | 38.466667 | 82 | 0.661036 | false | false | false | false | 
| 
	RocketChat/Rocket.Chat.iOS | 
	refs/heads/develop | 
	Rocket.Chat/Models/File.swift | 
	mit | 
	1 | 
	//
//  File.swift
//  Rocket.Chat
//
//  Created by Filipe Alvarenga on 11/04/18.
//  Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
import RealmSwift
final class File: BaseModel {
    @objc dynamic var name = ""
    @objc dynamic var rid = ""
    @objc dynamic var size: Double = 0
    @objc dynamic var type = ""
    @objc dynamic var fileDescription = ""
    @objc dynamic var store = ""
    @objc dynamic var isComplete = false
    @objc dynamic var isUploading = false
    @objc dynamic var fileExtension = ""
    @objc dynamic var progress: Int = 0
    @objc dynamic var user: User?
    @objc dynamic var uploadedAt: Date?
    @objc dynamic var url = ""
}
extension File {
    var username: String {
        return user?.username ?? ""
    }
    var isImage: Bool {
        return type.range(of: "image", options: .caseInsensitive) != nil
    }
    var isGif: Bool {
        let gifTypes = ["gif"]
        return gifTypes.compactMap { type.range(of: $0, options: .caseInsensitive) != nil ? true : nil }.first ?? false
    }
    var isVideo: Bool {
        return type.range(of: "video", options: .caseInsensitive) != nil
    }
    var isAudio: Bool {
        return type.range(of: "audio", options: .caseInsensitive) != nil
    }
    var isDocument: Bool {
        let documentTypes = ["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "application"]
        return documentTypes.compactMap { type.range(of: $0, options: .caseInsensitive) != nil ? true : nil }.first ?? false
    }
    var videoThumbPath: URL? {
        let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documents = path[0]
        let thumbName = url.replacingOccurrences(of: "/", with: "\\")
        return documents.appendingPathComponent("\(thumbName).png")
    }
    fileprivate static func fullURLWith(_ path: String?, auth: Auth? = nil) -> URL? {
        guard let path = path else { return nil }
        if path.contains("http://") || path.contains("https://") {
            return URL(string: path)
        }
        let pathClean = path.replacingOccurrences(of: "//", with: "/")
        guard
            let pathPercentEncoded = NSString(string: pathClean).addingPercentEncoding(withAllowedCharacters: .urlPathAllowed),
            let auth = auth ?? AuthManager.isAuthenticated(),
            let userId = auth.userId,
            let token = auth.token,
            let baseURL = auth.baseURL()
            else {
                return nil
        }
        let urlString = "\(baseURL)\(pathPercentEncoded)?rc_uid=\(userId)&rc_token=\(token)"
        return URL(string: urlString)
    }
    func fullFileURL(auth: Auth? = nil) -> URL? {
        return File.fullURLWith(url, auth: auth)
    }
}
 | 
	9aee613813b87b0052928821cc5d5c6a | 30.443182 | 127 | 0.602458 | false | false | false | false | 
| 
	cubixlabs/GIST-Framework | 
	refs/heads/master | 
	GISTFramework/Classes/GISTSocial/TutorialView/TutorialView.swift | 
	agpl-3.0 | 
	1 | 
	//
//  TutorialView.swift
//  SocialGIST
//
//  Created by Shoaib Abdul on 09/08/2016.
//  Copyright © 2017 Social Cubix Inc. All rights reserved.
//
import UIKit
public protocol TutorialViewLayout {
    func updateLayout(_ data:Any);
} //P.E.
public protocol TutorialViewDelegate {
    func tutorialViewPageDidChange(tutorialView:TutorialView, newPage:Int);
} //P.E.
open class TutorialView: BaseUIView, UIScrollViewDelegate {
    
    private var _delegate:TutorialViewDelegate?
    @IBOutlet public var delegate:AnyObject? {
        didSet {
            _delegate = delegate as? TutorialViewDelegate;
        }
    }
    
    @IBOutlet public var pageControl:UIPageControl? {
        didSet {
            pageControl?.numberOfPages = _layoutViews.count;
            
            self.updatePageControl();
        }
    }
    
    @IBInspectable public var dataPlistFileName:String! {
        didSet {
            self.updateTutorial();
        }
    }
    
    @IBInspectable public var layoutViewName:String! {
        didSet {
            self.updateTutorial();
        }
    }
    
    private var _currPage:Int = 0;
    public var currentPage:Int {
        get {
            return _currPage;
        }
        
        set {
            if (newValue != _currPage) {
                _currPage = newValue;
                
                self.pageControl?.currentPage = _currPage;
                
                //Scrolling to new Page
                self.scrollView.setContentOffset(CGPoint(x: (self.scrollView.contentSize.width /  CGFloat(self.numberOfPages)) * CGFloat(_currPage), y: 0), animated: true);
            }
        }
    }
    
    public var numberOfPages:Int {
        get {
            return _layoutViews.count;
        }
    }
    
    private var _scrollView:UIScrollView?;
    private var scrollView:UIScrollView {
        get {
            if (_scrollView == nil) {
                _scrollView = UIScrollView();
                _scrollView!.isPagingEnabled = true;
                _scrollView!.showsHorizontalScrollIndicator = false;
                _scrollView!.showsVerticalScrollIndicator = false;
                _scrollView!.delegate = self;
                self.addSubview(_scrollView!);
            }
            
            return _scrollView!;
        }
    }
    
    private var _layoutViews:[TutorialViewLayout] = [TutorialViewLayout]();
    
    override open func layoutSubviews() {
        super.layoutSubviews();
        
        self.updateFrames();
    } //F.E.
    
    //Scroll View Delegate Method
    open func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.updatePageControl();
    } //F.E.
    
    private func updateTutorial() {
        guard ((dataPlistFileName != nil) && (layoutViewName != nil)) else {
            return;
        }
        
        //Removing old views
        self.resetLayout();
        
        if let arr:NSArray = SyncEngine.objectForKey(dataPlistFileName) {
        
            for i:Int in 0 ..< arr.count {
                if let tView:TutorialViewLayout = UIView.loadWithNib(layoutViewName, viewIndex: 0, owner: self) as? TutorialViewLayout {
                    tView.updateLayout(arr[i] as AnyObject);
                    scrollView.addSubview(tView as! UIView);
                     _layoutViews.append(tView);
                } else {
                    assert(true, "Invalid layout: \(String(describing: layoutViewName)) must implement SCTutorialViewLayout protocol");
                }
            }
        } else {
            assert(true, "Invalid plist file.");
        }
        
        pageControl?.numberOfPages = _layoutViews.count;
    } //F.E.
    
    private func resetLayout() {
        for layoutView:TutorialViewLayout in _layoutViews {
            (layoutView as? UIView)?.removeFromSuperview();
        }
        
        _layoutViews.removeAll();
    } //F.E.
    
    private func updateFrames() {
        self.scrollView.frame = self.frame;
        
        self.scrollView.contentSize = CGSize(width: self.frame.width * CGFloat(_layoutViews.count),height: self.frame.height);
        
        for i:Int in 0 ..< _layoutViews.count {
            let tView:TutorialViewLayout = _layoutViews[i];
            (tView as! UIView).frame = CGRect(x: self.frame.width * CGFloat(i), y: 0, width: self.frame.width, height: self.frame.height);
        }
    } //F.E.
    
    private func updatePageControl () {
        let newPage = Int(floor((self.scrollView.contentOffset.x - self.bounds.size.width * 0.5) / self.bounds.size.width)) + 1
        
        if (newPage != _currPage) {
            _currPage = newPage;
            
            self.pageControl?.currentPage = _currPage;
            
            _delegate?.tutorialViewPageDidChange(tutorialView: self, newPage: _currPage);
        }
    } //F.E.
    
} //CLS END
 | 
	6a97a36efed7131d6d82a77e6e55e752 | 29.740506 | 172 | 0.559193 | false | false | false | false | 
| 
	jarocht/iOS-Bootcamp-Summer2015 | 
	refs/heads/master | 
	StopWatchDemo/StopWatchDemo/ViewController.swift | 
	gpl-2.0 | 
	1 | 
	//
//  ViewController.swift
//  StopWatchDemo
//
//  Created by X Code User on 7/14/15.
//  Copyright (c) 2015 gvsu.edu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
    @IBOutlet weak var timerText: UILabel!
    @IBOutlet weak var dayNightToggle: UIButton!
    @IBOutlet weak var startStopToggleBtn: UIButton!
    @IBOutlet weak var clearBtn: UIButton!
    
    var timerModel: TimerModel = TimerModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        self.timerModel.stopWatchTimer = NSTimer(timeInterval: 1.0/10.0, target: self, selector: "updateTimer", userInfo: nil, repeats: true)
        NSRunLoop.currentRunLoop().addTimer(self.timerModel.stopWatchTimer, forMode: NSRunLoopCommonModes)
    }
    
    func updateTimer(){
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func toggleMode(sender: UIButton) {
        if(!timerModel.nightDisplayMode){
            self.view.backgroundColor = UIColor.blackColor()
            timerText.textColor = UIColor.whiteColor()
            timerModel.nightDisplayMode = true
        } else {
            self.view.backgroundColor = UIColor.whiteColor()
            timerText.textColor = UIColor.blackColor()
            timerModel.nightDisplayMode = false
        }
        
        
    }
    @IBAction func startTimer(sender: UIButton) {
        if(!timerModel.running){
            timerModel.running = true
            clearBtn.enabled = false
            startStopToggleBtn.setTitle("Stop", forState: UIControlState.Normal)
        } else {
            timerModel.running = false
            clearBtn.enabled = true
            startStopToggleBtn.setTitle("Start", forState: UIControlState.Normal)
            self.view.backgroundColor = UIColor.whiteColor()
        }
        
    }
    @IBAction func clearTimer(sender: UIButton) {
        self.timerText.text = "00:00:00:000"
    }
}
 | 
	ab266562f50469ae5460a5b8e3e69a6f | 29.465753 | 141 | 0.63714 | false | false | false | false | 
| 
	wireapp/wire-ios-data-model | 
	refs/heads/develop | 
	Source/Model/User/ZMUser+Validation.swift | 
	gpl-3.0 | 
	1 | 
	//
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
public extension ZMUser {
    // Name
    static func validate(name: inout String?) throws -> Bool {
        var mutableName: Any? = name
        try ExtremeCombiningCharactersValidator.validateCharactersValue(&mutableName)
        // The backend limits to 128. We'll fly just a bit below the radar.
        let validate = try StringLengthValidator.validateStringValue(&mutableName, minimumStringLength: 2, maximumStringLength: 100, maximumByteLength: UInt32.max)
        name = mutableName as? String
        return name == nil || validate
    }
    // Accent color
    static func validate(accentColor: inout Int?) throws -> Bool {
        var mutableAccentColor: Any? = accentColor
        let result = try ZMAccentColorValidator.validateValue(&mutableAccentColor)
        accentColor = mutableAccentColor as? Int
        return result
    }
    // E-mail address
    static func validate(emailAddress: inout String?) throws -> Bool {
        var mutableEmailAddress: Any? = emailAddress
        let result = try ZMEmailAddressValidator.validateValue(&mutableEmailAddress)
        emailAddress = mutableEmailAddress as? String
        return result
    }
    // Password
    static func validate(password: inout String?) throws -> Bool {
        var mutablePassword: Any? = password
        let result = try StringLengthValidator.validateStringValue(&mutablePassword,
                                                                 minimumStringLength: 8,
                                                                 maximumStringLength: 120,
                                                                 maximumByteLength: UInt32.max)
        password = mutablePassword as? String
        return result
    }
    // Phone number
    static func validate(phoneNumber: inout String?) throws -> Bool {
        guard var mutableNumber: Any? = phoneNumber,
            phoneNumber?.count ?? 0 >= 1 else {
                return false
        }
        let result = try ZMPhoneNumberValidator.validateValue(&mutableNumber)
        phoneNumber = mutableNumber as? String
        return result
    }
    // Verification code
    static func validate(phoneVerificationCode: inout String?) throws -> Bool {
        var mutableCode: Any? = phoneVerificationCode
        let result = try StringLengthValidator.validateStringValue(&mutableCode, minimumStringLength: 6, maximumStringLength: 6, maximumByteLength: UInt32.max)
        phoneVerificationCode = mutableCode as? String
        return result
    }
}
 | 
	088110c91b78f30603db9b7346959151 | 34.648352 | 163 | 0.657213 | false | false | false | false | 
| 
	k-o-d-e-n/CGLayout | 
	refs/heads/master | 
	Sources/Classes/coordinate.cglayout.swift | 
	mit | 
	1 | 
	//
//  MultiCoordinateSpace.swift
//  CGLayout
//
//  Created by Denis Koryttsev on 08/09/2017.
//  Copyright © 2017 K-o-D-e-N. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#elseif os(Linux)
import Foundation
#endif
// MARK: LayoutCoordinateSpace
/// Common protocol for anyone `LayoutElement`.
/// Used for multi-converting coordinates between `LayoutElement` items.
/// Converting between UIView and CALayer has low performance in comparison converting with same type.
/// Therefore should UIView.layer property when creates constraint relationship between UIView and CALayer.
public protocol LayoutCoordinateSpace {
    func convert(point: CGPoint, to item: LayoutElement) -> CGPoint
    func convert(point: CGPoint, from item: LayoutElement) -> CGPoint
    func convert(rect: CGRect, to item: LayoutElement) -> CGRect
    func convert(rect: CGRect, from item: LayoutElement) -> CGRect
    var bounds: CGRect { get }
}
#if os(iOS) || os(tvOS)
extension LayoutCoordinateSpace where Self: UICoordinateSpace, Self: LayoutElement {
    public func convert(point: CGPoint, to element: LayoutElement) -> CGPoint {
        guard !(element is UICoordinateSpace) else { return syncGuard(mainThread: { convert(point, to: element as! UICoordinateSpace) }) }
        return Self.convert(point: point, from: self, to: element)
    }
    public func convert(point: CGPoint, from element: LayoutElement) -> CGPoint {
        guard !(element is UICoordinateSpace) else { return syncGuard(mainThread: { convert(point, from: element as! UICoordinateSpace) }) }
        return Self.convert(point: point, from: element, to: self)
    }
    public func convert(rect: CGRect, to element: LayoutElement) -> CGRect {
        guard !(element is UICoordinateSpace) else { return syncGuard(mainThread: { convert(rect, to: element as! UICoordinateSpace) }) }
        var rect = rect
        rect.origin = Self.convert(point: rect.origin, from: self, to: element)
        return rect
    }
    public func convert(rect: CGRect, from element: LayoutElement) -> CGRect {
        guard !(element is UICoordinateSpace) else { return syncGuard(mainThread: { convert(rect, from: element as! UICoordinateSpace) }) }
        var rect = rect
        rect.origin = Self.convert(point: rect.origin, from: element, to: self)
        return rect
    }
}
/// UIView.convert(_ point: CGPoint, to view: UIView?) faster than UICoordinateSpace.convert(_ point: CGPoint, to coordinateSpace: UICoordinateSpace)
/// Therefore makes extension for UIView.
extension LayoutCoordinateSpace where Self: UIView {
    public func convert(point: CGPoint, to element: LayoutElement) -> CGPoint {
        if let element = element as? UIView { return syncGuard(mainThread: { convert(point, to: element) }) }
        if let element = element as? CALayer { return syncGuard(mainThread: { layer.convert(point, to: element) }) }
        return Self.convert(point: point, from: self, to: element)
    }
    public func convert(point: CGPoint, from element: LayoutElement) -> CGPoint {
        if let element = element as? UIView { return syncGuard(mainThread: { convert(point, from: element) }) }
        if let element = element as? CALayer { return syncGuard(mainThread: { layer.convert(point, from: element) }) }
        return Self.convert(point: point, from: element, to: self)
    }
    public func convert(rect: CGRect, to element: LayoutElement) -> CGRect {
        if let element = element as? UIView { return syncGuard(mainThread: { convert(rect, to: element) }) }
        if let element = element as? CALayer { return syncGuard(mainThread: { layer.convert(rect, to: element) }) }
        var rect = rect
        rect.origin = Self.convert(point: rect.origin, from: self, to: element)
        return rect
    }
    public func convert(rect: CGRect, from element: LayoutElement) -> CGRect {
        if let element = element as? UIView { return syncGuard(mainThread: { convert(rect, from: element) }) }
        if let element = element as? CALayer { return syncGuard(mainThread: { layer.convert(rect, from: element) }) }
        var rect = rect
        rect.origin = Self.convert(point: rect.origin, from: element, to: self)
        return rect
    }
}
#endif
#if os(macOS) || os(iOS) || os(tvOS)
extension LayoutCoordinateSpace where Self: CALayer {
    public func convert(point: CGPoint, to item: LayoutElement) -> CGPoint {
        if let item = item as? CALayer { return syncGuard(mainThread: { convert(point, to: item) }) }
        return Self.convert(point: point, from: self, to: item)
    }
    public func convert(point: CGPoint, from item: LayoutElement) -> CGPoint {
        if let item = item as? CALayer { return syncGuard(mainThread: { convert(point, from: item) }) }
        return Self.convert(point: point, from: item, to: self)
    }
    public func convert(rect: CGRect, to item: LayoutElement) -> CGRect {
        if let item = item as? CALayer { return syncGuard(mainThread: { convert(rect, to: item) }) }
        var rect = rect
        rect.origin = Self.convert(point: rect.origin, from: self, to: item)
        return rect
    }
    public func convert(rect: CGRect, from item: LayoutElement) -> CGRect {
        if let item = item as? CALayer { return syncGuard(mainThread: { convert(rect, from: item) }) }
        var rect = rect
        rect.origin = Self.convert(point: rect.origin, from: item, to: self)
        return rect
    }
}
#endif
#if os(iOS) || os(tvOS)
@available(iOS 9.0, *)
extension LayoutCoordinateSpace where Self: UILayoutGuide {
    public func convert(point: CGPoint, to element: LayoutElement) -> CGPoint {
        guard !(element is UIView) else { return convert(point, to: element as! UIView) }
        return Self.convert(point: point, from: self, to: element)
    }
    public func convert(point: CGPoint, from element: LayoutElement) -> CGPoint {
        guard !(element is UIView) else { return convert(point, from: element as! UIView) }
        return Self.convert(point: point, from: element, to: self)
    }
    public func convert(rect: CGRect, to element: LayoutElement) -> CGRect {
        guard !(element is UIView) else { return convert(rect, to: element as! UIView) }
        var rect = rect
        rect.origin = Self.convert(point: rect.origin, from: self, to: element)
        return rect
    }
    public func convert(rect: CGRect, from element: LayoutElement) -> CGRect {
        guard !(element is UIView) else { return convert(rect, from: element as! UIView) }
        var rect = rect
        rect.origin = Self.convert(point: rect.origin, from: element, to: self)
        return rect
    }
    public func convert(_ point: CGPoint, to view: UIView) -> CGPoint {
        let pointInSuper = CGPoint(x: frame.origin.x + point.x, y: frame.origin.y + point.y)
        return owningView!.convert(pointInSuper, to: view)
    }
    public func convert(_ point: CGPoint, from view: UIView) -> CGPoint {
        let pointInSuper = owningView!.convert(point, from: view)
        return CGPoint(x: pointInSuper.x - frame.origin.x, y: pointInSuper.y - frame.origin.y)
    }
    public func convert(_ rect: CGRect, to view: UIView) -> CGRect {
        let rectInSuper = CGRect(x: frame.origin.x + rect.origin.x, y: frame.origin.y + rect.origin.y, width: rect.width, height: rect.height)
        return owningView!.convert(rectInSuper, to: view)
    }
    public func convert(_ rect: CGRect, from view: UIView) -> CGRect {
        let rectInSuper = owningView!.convert(rect, from: view)
        return CGRect(x: rectInSuper.origin.x - frame.origin.x, y: rectInSuper.origin.y - frame.origin.y, width: rectInSuper.width, height: rectInSuper.height)
    }
}
#endif
#if os(macOS)
    extension LayoutCoordinateSpace where Self: NSView {
        public func convert(point: CGPoint, to item: LayoutElement) -> CGPoint {
            if let item = item as? NSView { return syncGuard(mainThread: { convert(point, to: item) }) }
            if let item = item as? CALayer, let layer = layer { return syncGuard(mainThread: { layer.convert(point, to: item) }) }
            return Self.convert(point: point, from: self, to: item)
        }
        public func convert(point: CGPoint, from item: LayoutElement) -> CGPoint {
            if let item = item as? NSView { return syncGuard(mainThread: { convert(point, from: item) }) }
            if let item = item as? CALayer, let layer = layer { return syncGuard(mainThread: { layer.convert(point, from: item) }) }
            return Self.convert(point: point, from: item, to: self)
        }
        public func convert(rect: CGRect, to item: LayoutElement) -> CGRect {
            if let item = item as? NSView { return syncGuard(mainThread: { convert(rect, to: item) }) }
            if let item = item as? CALayer, let layer = layer { return syncGuard(mainThread: { layer.convert(rect, to: item) }) }
            var rect = rect
            rect.origin = Self.convert(point: rect.origin, from: self, to: item)
            return rect
        }
        public func convert(rect: CGRect, from item: LayoutElement) -> CGRect {
            if let item = item as? NSView { return syncGuard(mainThread: { convert(rect, from: item) }) }
            if let item = item as? CALayer, let layer = layer { return syncGuard(mainThread: { layer.convert(rect, from: item) }) }
            var rect = rect
            rect.origin = Self.convert(point: rect.origin, from: item, to: self)
            return rect
        }
    }
#endif
fileprivate struct LinkedList<T>: Sequence {
    private let startObject: T
    private let next: (T) -> T?
    init(start: T, next: @escaping (T) -> T?) {
        self.startObject = start
        self.next = next
    }
    func makeIterator() -> AnyIterator<T> {
        var current: T? = startObject
        return AnyIterator {
            let next = current
            current = current.flatMap { self.next($0) }
            return next
        }
    }
}
extension LayoutCoordinateSpace where Self: LayoutElement {
    fileprivate static func convert(point: CGPoint, from: LayoutElement, to: LayoutElement) -> CGPoint {
        let list1Iterator = LinkedList(start: from) { $0.inLayoutTime.superElement }.makeIterator()
        var list2Iterator = LinkedList(start: to) { $0.inLayoutTime.superElement }.reversed().makeIterator()
        var converted = point
        while let next = list1Iterator.next()?.inLayoutTime {
            converted.x = next.frame.origin.x + converted.x - next.bounds.origin.x
            converted.y = next.frame.origin.y + converted.y - next.bounds.origin.y
        }
        while let next = list2Iterator.next()?.inLayoutTime {
            converted.x = converted.x - next.frame.origin.x + next.bounds.origin.x
            converted.y = converted.y - next.frame.origin.y + next.bounds.origin.y
        }
        return converted
    }
    public func convert(point: CGPoint, to item: LayoutElement) -> CGPoint {
        return Self.convert(point: point, from: self, to: item)
    }
    public func convert(point: CGPoint, from item: LayoutElement) -> CGPoint {
        return Self.convert(point: point, from: item, to: self)
    }
    public func convert(rect: CGRect, to item: LayoutElement) -> CGRect {
        var rect = rect
        rect.origin = convert(point: rect.origin, to: item)
        return rect
    }
    public func convert(rect: CGRect, from item: LayoutElement) -> CGRect {
        var rect = rect
        rect.origin = convert(point: rect.origin, from: item)
        return rect
    }
}
// MARK: LayoutGuide conversions
#if os(iOS) || os(tvOS)
extension LayoutGuide where Super: UICoordinateSpace {
    public func convert(point: CGPoint, to element: LayoutElement) -> CGPoint {
        guard !(element is UICoordinateSpace) else { return convert(point, to: element as! UICoordinateSpace) }
        return LayoutGuide.convert(point: point, from: self, to: element)
    }
    public func convert(point: CGPoint, from element: LayoutElement) -> CGPoint {
        guard !(element is UICoordinateSpace) else { return convert(point, from: element as! UICoordinateSpace) }
        return LayoutGuide.convert(point: point, from: element, to: self)
    }
    public func convert(rect: CGRect, to element: LayoutElement) -> CGRect {
        guard !(element is UICoordinateSpace) else { return convert(rect, to: element as! UICoordinateSpace) }
        var rect = rect
        rect.origin = LayoutGuide.convert(point: rect.origin, from: self, to: element)
        return rect
    }
    public func convert(rect: CGRect, from element: LayoutElement) -> CGRect {
        guard !(element is UICoordinateSpace) else { return convert(rect, from: element as! UICoordinateSpace) }
        var rect = rect
        rect.origin = LayoutGuide.convert(point: rect.origin, from: element, to: self)
        return rect
    }
}
/// UIView.convert(_ point: CGPoint, to view: UIView?) faster than UICoordinateSpace.convert(_ point: CGPoint, to coordinateSpace: UICoordinateSpace)
/// Therefore makes extension for UIView.
extension LayoutGuide where Super: UIView {
    public func convert(point: CGPoint, to element: LayoutElement) -> CGPoint {
        if let element = element as? UIView { return convert(point, to: element) }
        if let element = element as? CALayer { return convert(point, to: element) }
        return LayoutGuide.convert(point: point, from: self, to: element)
    }
    public func convert(point: CGPoint, from element: LayoutElement) -> CGPoint {
        if let element = element as? UIView { return convert(point, from: element) }
        if let element = element as? CALayer { return convert(point, from: element) }
        return LayoutGuide.convert(point: point, from: element, to: self)
    }
    public func convert(rect: CGRect, to element: LayoutElement) -> CGRect {
        if let element = element as? UIView { return convert(rect, to: element) }
        if let element = element as? CALayer { return convert(rect, to: element) }
        var rect = rect
        rect.origin = LayoutGuide.convert(point: rect.origin, from: self, to: element)
        return rect
    }
    public func convert(rect: CGRect, from element: LayoutElement) -> CGRect {
        if let element = element as? UIView { return convert(rect, from: element) }
        if let element = element as? CALayer { return convert(rect, from: element) }
        var rect = rect
        rect.origin = LayoutGuide.convert(point: rect.origin, from: element, to: self)
        return rect
    }
}
#endif
#if os(macOS)
    extension LayoutGuide where Super: NSView {
        public func convert(point: CGPoint, to item: LayoutElement) -> CGPoint {
            if let item = item as? NSView { return convert(point, to: item) }
            if let item = item as? CALayer, let layer = ownerElement?.layer { return convert(point, to: item, superLayer: layer) }
            return LayoutGuide.convert(point: point, from: self, to: item)
        }
        public func convert(point: CGPoint, from item: LayoutElement) -> CGPoint {
            if let item = item as? NSView { return convert(point, from: item) }
            if let item = item as? CALayer, let layer = ownerElement?.layer { return convert(point, from: item, superLayer: layer) }
            return LayoutGuide.convert(point: point, from: item, to: self)
        }
        public func convert(rect: CGRect, to item: LayoutElement) -> CGRect {
            if let item = item as? NSView { return convert(rect, to: item) }
            if let item = item as? CALayer, let layer = ownerElement?.layer { return convert(rect, to: item, superLayer: layer) }
            var rect = rect
            rect.origin = LayoutGuide.convert(point: rect.origin, from: self, to: item)
            return rect
        }
        public func convert(rect: CGRect, from item: LayoutElement) -> CGRect {
            if let item = item as? NSView { return convert(rect, from: item) }
            if let item = item as? CALayer, let layer = ownerElement?.layer { return convert(rect, from: item, superLayer: layer) }
            var rect = rect
            rect.origin = LayoutGuide.convert(point: rect.origin, from: item, to: self)
            return rect
        }
    }
#endif
#if os(macOS) || os(iOS) || os(tvOS)
extension LayoutGuide where Super: CALayer {
    public func convert(point: CGPoint, to item: LayoutElement) -> CGPoint {
        guard !(item is CALayer) else { return convert(point, to: item as! CALayer) }
        return LayoutGuide.convert(point: point, from: self, to: item)
    }
    public func convert(point: CGPoint, from item: LayoutElement) -> CGPoint {
        guard !(item is CALayer) else { return convert(point, from: item as! CALayer) }
        return LayoutGuide.convert(point: point, from: item, to: self)
    }
    public func convert(rect: CGRect, to item: LayoutElement) -> CGRect {
        guard !(item is CALayer) else { return convert(rect, to: item as! CALayer) }
        var rect = rect
        rect.origin = LayoutGuide.convert(point: rect.origin, from: self, to: item)
        return rect
    }
    public func convert(rect: CGRect, from item: LayoutElement) -> CGRect {
        guard !(item is CALayer) else { return convert(rect, from: item as! CALayer) }
        var rect = rect
        rect.origin = LayoutGuide.convert(point: rect.origin, from: item, to: self)
        return rect
    }
}
#endif
#if os(iOS) || os(tvOS)
extension LayoutGuide where Super: UICoordinateSpace {
    @available(iOS 8.0, *)
    public func convert(_ point: CGPoint, to coordinateSpace: UICoordinateSpace) -> CGPoint {
        let pointInSuper = CGPoint(x: frame.origin.x + point.x - bounds.origin.x, y: frame.origin.y + point.y - bounds.origin.y)
        return syncGuard(mainThread: ownerElement!.convert(pointInSuper, to: coordinateSpace))
    }
    @available(iOS 8.0, *)
    public func convert(_ point: CGPoint, from coordinateSpace: UICoordinateSpace) -> CGPoint {
        let pointInSuper = syncGuard(mainThread: ownerElement!.convert(point, from: coordinateSpace))
        return CGPoint(x: pointInSuper.x - frame.origin.x + bounds.origin.x, y: pointInSuper.y - frame.origin.y + bounds.origin.y)
    }
    @available(iOS 8.0, *)
    public func convert(_ rect: CGRect, to coordinateSpace: UICoordinateSpace) -> CGRect {
        let rectInSuper = CGRect(x: frame.origin.x + rect.origin.x - bounds.origin.x, y: frame.origin.y + rect.origin.y - bounds.origin.y, width: rect.width, height: rect.height)
        return syncGuard(mainThread: ownerElement!.convert(rectInSuper, to: coordinateSpace))
    }
    @available(iOS 8.0, *)
    public func convert(_ rect: CGRect, from coordinateSpace: UICoordinateSpace) -> CGRect {
        let rectInSuper = syncGuard(mainThread: ownerElement!.convert(rect, from: coordinateSpace))
        return CGRect(x: rectInSuper.origin.x - frame.origin.x + bounds.origin.x, y: rectInSuper.origin.y - frame.origin.y + bounds.origin.y, width: rectInSuper.width, height: rectInSuper.height)
    }
}
extension LayoutGuide where Super: UIView {
    public func convert(_ point: CGPoint, to view: UIView) -> CGPoint {
        let pointInSuper = CGPoint(x: frame.origin.x + point.x - bounds.origin.x, y: frame.origin.y + point.y - bounds.origin.y)
        return syncGuard(mainThread: ownerElement!.convert(pointInSuper, to: view))
    }
    public func convert(_ point: CGPoint, from view: UIView) -> CGPoint {
        let pointInSuper = syncGuard(mainThread: ownerElement!.convert(point, from: view))
        return CGPoint(x: pointInSuper.x - frame.origin.x + bounds.origin.x, y: pointInSuper.y - frame.origin.y + bounds.origin.y)
    }
    public func convert(_ rect: CGRect, to view: UIView) -> CGRect {
        let rectInSuper = CGRect(x: frame.origin.x + rect.origin.x - bounds.origin.x, y: frame.origin.y + rect.origin.y - bounds.origin.y, width: rect.width, height: rect.height)
        return syncGuard(mainThread: ownerElement!.convert(rectInSuper, to: view))
    }
    public func convert(_ rect: CGRect, from view: UIView) -> CGRect {
        let rectInSuper = syncGuard(mainThread: ownerElement!.convert(rect, from: view))
        return CGRect(x: rectInSuper.origin.x - frame.origin.x + bounds.origin.x, y: rectInSuper.origin.y - frame.origin.y + bounds.origin.y, width: rectInSuper.width, height: rectInSuper.height)
    }
    public func convert(_ point: CGPoint, to layer: CALayer) -> CGPoint {
        let pointInSuper = CGPoint(x: frame.origin.x + point.x - bounds.origin.x, y: frame.origin.y + point.y - bounds.origin.y)
        return syncGuard(mainThread: ownerElement!.layer.convert(pointInSuper, to: layer))
    }
    public func convert(_ point: CGPoint, from layer: CALayer) -> CGPoint {
        let pointInSuper = syncGuard(mainThread: ownerElement!.layer.convert(point, from: layer))
        return CGPoint(x: pointInSuper.x - frame.origin.x + bounds.origin.x, y: pointInSuper.y - frame.origin.y + bounds.origin.y)
    }
    public func convert(_ rect: CGRect, to layer: CALayer) -> CGRect {
        let rectInSuper = CGRect(x: frame.origin.x + rect.origin.x - bounds.origin.x, y: frame.origin.y + rect.origin.y - bounds.origin.y, width: rect.width, height: rect.height)
        return syncGuard(mainThread: ownerElement!.layer.convert(rectInSuper, to: layer))
    }
    public func convert(_ rect: CGRect, from layer: CALayer) -> CGRect {
        let rectInSuper = syncGuard(mainThread: ownerElement!.layer.convert(rect, from: layer))
        return CGRect(x: rectInSuper.origin.x - frame.origin.x + bounds.origin.x, y: rectInSuper.origin.y - frame.origin.y + bounds.origin.y, width: rectInSuper.width, height: rectInSuper.height)
    }
}
#endif
#if os(macOS)
    extension LayoutGuide where Super: NSView {
        public func convert(_ point: CGPoint, to view: NSView) -> CGPoint {
            let pointInSuper = CGPoint(x: frame.origin.x + point.x - bounds.origin.x, y: frame.origin.y + point.y - bounds.origin.y)
            return syncGuard(mainThread: ownerElement!.convert(pointInSuper, to: view))
        }
        public func convert(_ point: CGPoint, from view: NSView) -> CGPoint {
            let pointInSuper = syncGuard(mainThread: ownerElement!.convert(point, from: view))
            return CGPoint(x: pointInSuper.x - frame.origin.x + bounds.origin.x, y: pointInSuper.y - frame.origin.y + bounds.origin.y)
        }
        public func convert(_ rect: CGRect, to view: NSView) -> CGRect {
            let rectInSuper = CGRect(x: frame.origin.x + rect.origin.x - bounds.origin.x, y: frame.origin.y + rect.origin.y - bounds.origin.y, width: rect.width, height: rect.height)
            return syncGuard(mainThread: ownerElement!.convert(rectInSuper, to: view))
        }
        public func convert(_ rect: CGRect, from view: NSView) -> CGRect {
            let rectInSuper = syncGuard(mainThread: ownerElement!.convert(rect, from: view))
            return CGRect(x: rectInSuper.origin.x - frame.origin.x + bounds.origin.x, y: rectInSuper.origin.y - frame.origin.y + bounds.origin.y, width: rectInSuper.width, height: rectInSuper.height)
        }
        public func convert(_ point: CGPoint, to layer: CALayer, superLayer: CALayer) -> CGPoint {
            let pointInSuper = CGPoint(x: frame.origin.x + point.x - bounds.origin.x, y: frame.origin.y + point.y - bounds.origin.y)
            return syncGuard(mainThread: superLayer.convert(pointInSuper, to: layer))
        }
        public func convert(_ point: CGPoint, from layer: CALayer, superLayer: CALayer) -> CGPoint {
            let pointInSuper = syncGuard(mainThread: superLayer.convert(point, from: layer))
            return CGPoint(x: pointInSuper.x - frame.origin.x + bounds.origin.x, y: pointInSuper.y - frame.origin.y + bounds.origin.y)
        }
        public func convert(_ rect: CGRect, to layer: CALayer, superLayer: CALayer) -> CGRect {
            let rectInSuper = CGRect(x: frame.origin.x + rect.origin.x - bounds.origin.x, y: frame.origin.y + rect.origin.y - bounds.origin.y, width: rect.width, height: rect.height)
            return syncGuard(mainThread: superLayer.convert(rectInSuper, to: layer))
        }
        public func convert(_ rect: CGRect, from layer: CALayer, superLayer: CALayer) -> CGRect {
            let rectInSuper = syncGuard(mainThread: superLayer.convert(rect, from: layer))
            return CGRect(x: rectInSuper.origin.x - frame.origin.x + bounds.origin.x, y: rectInSuper.origin.y - frame.origin.y + bounds.origin.y, width: rectInSuper.width, height: rectInSuper.height)
        }
    }
#endif
#if os(macOS) || os(iOS) || os(tvOS)
extension LayoutGuide where Super: CALayer {
    public func convert(_ point: CGPoint, to coordinateSpace: CALayer) -> CGPoint {
        let pointInSuper = CGPoint(x: frame.origin.x + point.x - bounds.origin.x, y: frame.origin.y + point.y - bounds.origin.y)
        return syncGuard(mainThread: ownerElement!.convert(pointInSuper, to: coordinateSpace))
    }
    public func convert(_ point: CGPoint, from coordinateSpace: CALayer) -> CGPoint {
        let pointInSuper = syncGuard(mainThread: ownerElement!.convert(point, from: coordinateSpace))
        return CGPoint(x: pointInSuper.x - frame.origin.x + bounds.origin.x, y: pointInSuper.y - frame.origin.y + bounds.origin.y)
    }
    public func convert(_ rect: CGRect, to coordinateSpace: CALayer) -> CGRect {
        let rectInSuper = CGRect(x: frame.origin.x + rect.origin.x - bounds.origin.x, y: frame.origin.y + rect.origin.y - bounds.origin.y, width: rect.width, height: rect.height)
        return syncGuard(mainThread: ownerElement!.convert(rectInSuper, to: coordinateSpace))
    }
    public func convert(_ rect: CGRect, from coordinateSpace: CALayer) -> CGRect {
        let rectInSuper = syncGuard(mainThread: ownerElement!.convert(rect, from: coordinateSpace))
        return CGRect(x: rectInSuper.origin.x - frame.origin.x + bounds.origin.x, y: rectInSuper.origin.y - frame.origin.y + bounds.origin.y, width: rectInSuper.width, height: rectInSuper.height)
    }
}
#endif
// MARK: CoordinateConvertable
/// Common protocol for anyone `LayoutElement` item that coordinates can be converted to other space.
/// Used for converting coordinates of UIView and CALayer.
/// Converting from UIView coordinate space to CALayer (or conversely) coordinate while not possible.
/// Therefore can use constraints only from same `LayoutElement` type space.
/*public protocol CoordinateConvertable {
    @available(iOS 8.0, *)
    func convert(_ point: CGPoint, to item: CoordinateConvertable?) -> CGPoint
    @available(iOS 8.0, *)
    func convert(_ point: CGPoint, from item: CoordinateConvertable?) -> CGPoint
    @available(iOS 8.0, *)
    func convert(_ rect: CGRect, to item: CoordinateConvertable?) -> CGRect
    @available(iOS 8.0, *)
    func convert(_ rect: CGRect, from item: CoordinateConvertable?) -> CGRect
}
extension UIView: CoordinateConvertable {
    public func convert(_ point: CGPoint, to item: CoordinateConvertable?) -> CGPoint {
        return convert(point, to: item as! UIView?)
    }
    public func convert(_ point: CGPoint, from item: CoordinateConvertable?) -> CGPoint {
        return convert(point, from: item as! UIView?)
    }
    public func convert(_ rect: CGRect, to item: CoordinateConvertable?) -> CGRect {
        return convert(rect, to: item as! UIView?)
    }
    public func convert(_ rect: CGRect, from item: CoordinateConvertable?) -> CGRect {
        return convert(rect, from: item as! UIView?)
    }
}
extension CALayer: CoordinateConvertable {
    public func convert(_ point: CGPoint, to item: CoordinateConvertable?) -> CGPoint {
        return convert(point, to: item as! CALayer?)
    }
    public func convert(_ point: CGPoint, from item: CoordinateConvertable?) -> CGPoint {
        return convert(point, from: item as! CALayer?)
    }
    public func convert(_ rect: CGRect, to item: CoordinateConvertable?) -> CGRect {
        return convert(rect, to: item as! CALayer?)
    }
    public func convert(_ rect: CGRect, from item: CoordinateConvertable?) -> CGRect {
        return convert(rect, from: item as! CALayer?)
    }
}*/
 | 
	593996ae08e8fbdf65de0c1041314be1 | 48.863958 | 199 | 0.665875 | false | false | false | false | 
| 
	mtviewdave/PhotoPicker | 
	refs/heads/master | 
	PhotoPicker/Util/ICPhotoAlbumAccess.swift | 
	apache-2.0 | 
	1 | 
	//
//  ICPhotoAlbumAccess.swift
//  PhotoPicker
//
//  Created by David Schreiber on 6/29/15.
//  Copyright (c) 2015 Metebelis Labs LLC. All rights reserved.
//
import UIKit
import Photos
import AssetsLibrary
private var icAlert : ICAlertView?
func authorizePhotoAlbumAccess(explainerText : String,completion : ((accessGranted : Bool)->()) ) {
    
    // iOS >= 8.0
    if objc_getClass("PHPhotoLibrary") != nil {
        switch PHPhotoLibrary.authorizationStatus() {
        case .NotDetermined:
            PHPhotoLibrary.requestAuthorization({ (authStatus) -> Void in
                completion(accessGranted: (authStatus == .Authorized))
            });
        case .Authorized:
            completion(accessGranted:true)
        case .Denied:
            // In iOS >= 8, you can take the user to their Settings to allow them to 
            // enable permissions
            let newICAlert = ICAlertView(title:"We need your permission",message:"Ingerchat does not have permission to access your photos. " + explainerText + ", you will need to go to the Settings app and give Ingerchat permission.", cancelButtonTitle: "Never Mind", otherButtonTitle: "Go to Settings",callback: { (result) -> () in
                if result == ICAlertViewResult.Other {
                    UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
                }
                icAlert = nil
            })
            icAlert = newICAlert
            newICAlert.show()
        case .Restricted:
            UIAlertView(title: nil, message: "You do not have permission to access the photo album.", delegate: nil, cancelButtonTitle: "OK").show()
        }
    } else {
        switch ALAssetsLibrary.authorizationStatus() {
        case .NotDetermined:
            completion(accessGranted: true)  // A clever lie; will cause authorization alert to appear
        case .Authorized:
            completion(accessGranted: true)
        case .Denied:
            UIAlertView(title: "We need your permission", message: "Ingerchat does not have permission to access your photos. " + explainerText + ", you will need to go to the Settings app and give Ingerchat permission.", delegate: nil, cancelButtonTitle: "OK").show()
        case .Restricted:
            UIAlertView(title: nil, message: "You do not have permission to access the photo album.", delegate: nil, cancelButtonTitle: "OK").show()
        }
    }
} | 
	0cd5a3eeacdbf5e3cd557f9165c74805 | 45.942308 | 333 | 0.643443 | false | false | false | false | 
| 
	quickthyme/PUTcat | 
	refs/heads/master | 
	PUTcat/Presentation/Transaction/TransactionViewController+TableView.swift | 
	apache-2.0 | 
	1 | 
	
import UIKit
extension TransactionViewController {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return self.viewData.section.count
    }
    
    override func tableView(_ tableView: UITableView,
                            numberOfRowsInSection section: Int) -> Int {
        return self.viewData.section[section].item.count
    }
    
    override func tableView(_ tableView: UITableView,
                            cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let item = self.getViewDataItem(forIndexPath: indexPath)
        let refID = item.refID
        let cell = tableView.dequeueReusableCell(withIdentifier: item.cellID, for: indexPath)
        if let cell = cell as? TransactionViewDataItemConfigurable { cell.configure(transactionViewDataItem: item) }
        if let cell = cell as? TransactionViewDataItemEditable {
            cell.textChanged =  { [weak self] newText in
                self?.updateViewDataItem(title: newText, forRefID: refID)
            }
        }
        return cell
    }
    
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.getViewDataSectionTitle(section: section)
    }
}
// MARK: - Editing
extension TransactionViewController {
    
    override func tableView(_ tableView: UITableView,
                            canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return (self.isCloning) ? .insert : .delete
    }
    
    override func tableView(_ tableView: UITableView,
                            commit editingStyle: UITableViewCellEditingStyle,
                            forRowAt indexPath: IndexPath) {
        
        if let cell = tableView.cellForRow(at: indexPath) as? TransactionViewDataItemEditable {
            cell.hideTextField()
        }
        switch (editingStyle) {
        case .insert:
            self.copyViewDataItem(indexPath: indexPath)
            let incrementedIndexPath = IndexPath(row: indexPath.row+1, section: indexPath.section)
            tableView.insertRows(at: [incrementedIndexPath], with: .top)
        case .delete:
            self.deleteViewDataItem(indexPath: indexPath)
            tableView.deleteRows(at: [indexPath], with: .left)
        default: break
        }
    }
}
// MARK: - Moving
extension TransactionViewController {
    
    override func tableView(_ tableView: UITableView,
                            canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    override func tableView(_ tableView: UITableView,
                            moveRowAt sourceIndexPath: IndexPath,
                            to destinationIndexPath: IndexPath) {
        
        self.moveViewDataItem(fromIndexPath: sourceIndexPath,
                              toIndexPath: destinationIndexPath)
    }
}
// MARK: - Selection
extension TransactionViewController {
    
    override func tableView(_ tableView: UITableView,
                            didSelectRowAt indexPath: IndexPath) {
        
        if self.isEditing {
            (tableView.cellForRow(at: indexPath) as? TransactionViewDataItemEditable)?
                .showTextField()
        }
        else {
            self.selectedViewDataItem = self.getViewDataItem(forIndexPath: indexPath)
            if let item = selectedViewDataItem {
                delegate?.viewController(self, didSelect: item)
            }
        }
    }
}
 | 
	f3242867a5254f708e2495fa58b43b1d | 33.913462 | 129 | 0.614156 | false | false | false | false | 
| 
	JARMourato/Moya-Marshal | 
	refs/heads/master | 
	Example/Example/ExampleAPI.swift | 
	mit | 
	1 | 
	import Foundation
import Moya
import Moya_Marshal
import ReactiveSwift
import Marshal
let provider = MoyaProvider<ExampleAPI>(stubClosure: MoyaProvider.immediatelyStub)
enum ExampleAPI {
    case object
    case array
}
extension ExampleAPI: TargetType {
    var baseURL: URL { return URL(string: "https://www.google.com")! }
    var path: String {
        switch self {
        case .object:
            return "object"
        case .array:
            return "array"
        }
    }
    var method: Moya.Method {
        return .get
    }
    var parameters: [String: Any]? {
        return nil
    }
    var sampleData: Data {
        let fileName: String
        switch self {
        case .object:
            fileName = "object"
        case .array:
            fileName =  "array"
        }
        guard
            let path = Bundle.main.path(forResource: fileName, ofType: "json", inDirectory: ""),
            let dataString = try? String(contentsOfFile: path),
            let data = dataString.data(using: String.Encoding.utf8)
        else { return Data() }
        return data
    }
    var task: Task {
        return Task.requestPlain
    }
    var headers: [String : String]? {
        return nil
    }
}
 | 
	2e4bf919f6bdaec29a20233651bc4e0e | 20.258621 | 96 | 0.571776 | false | false | false | false | 
| 
	marty-suzuki/QiitaWithFluxSample | 
	refs/heads/master | 
	QiitaWithFluxSample/Source/Common/Model/UIKeyboardInfo.swift | 
	mit | 
	1 | 
	//
//  UIKeyboardInfo.swift
//  QiitaWithFluxSample
//
//  Created by marty-suzuki on 2017/04/17.
//  Copyright © 2017年 marty-suzuki. All rights reserved.
//
import UIKit
struct UIKeyboardInfo {
    let frame: CGRect
    let animationDuration: TimeInterval
    let animationCurve: UIViewAnimationOptions
    
    init?(info: [AnyHashable : Any]) {
        guard
            let frame = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
            let duration = info[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval,
            let curve = info[UIKeyboardAnimationCurveUserInfoKey] as? UInt
            else {
                return nil
        }
        self.frame = frame
        self.animationDuration = duration
        self.animationCurve = UIViewAnimationOptions(rawValue: curve)
    }
}
 | 
	d70304460348ede35c72ec8877e7d334 | 28.285714 | 89 | 0.662195 | false | false | false | false | 
| 
	rajabishek/Beyond | 
	refs/heads/master | 
	Beyond/Note.swift | 
	mit | 
	1 | 
	//
//  Note.swift
//  Beyond
//
//  Created by Raj Abishek on 19/03/16.
//  Copyright © 2016 Raj Abishek. All rights reserved.
//
import Foundation
import CoreData
import UIKit
class Note:NSManagedObject {
    
    @NSManaged var title: String
    @NSManaged var content: String
    
    static let entityName = "Note"
    
    class func createNoteAndSave(title: String, content: String) -> Bool {
        
        if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
            let managedObjectContext = appDelegate.managedObjectContext
            if let note = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: managedObjectContext) as? Note {
                note.title = title
                note.content = content
                
                do {
                    try managedObjectContext.save()
                    return true
                } catch {
                    print(error)
                    return false
                }
            }
        }
        
        return false
    }
    
    class func getAllNotes() -> [Note]? {
        
        if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
            let managedObjectContext = appDelegate.managedObjectContext
            let fetchRequest = NSFetchRequest(entityName: entityName)
        
            do {
                return try managedObjectContext.executeFetchRequest(fetchRequest) as? [Note]
            } catch {
                print(error)
            }
        }
        
        return nil
    }
    
    func save() -> Bool{
        
        if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
            let managedObjectContext = appDelegate.managedObjectContext
            
            do {
                try managedObjectContext.save()
                return true
            } catch {
                print(error)
            }
        }
        
        return false
    }
    
    func remove() -> Bool {
        
        if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
            let managedObjectContext = appDelegate.managedObjectContext
            managedObjectContext.deleteObject(self)
            do {
                try managedObjectContext.save()
                return true
            } catch {
                print(error)
            }
        }
        
        return false
    }
}
 | 
	d4b1ae88104029120624ebfe8da85089 | 27.193182 | 146 | 0.539299 | false | false | false | false | 
| 
	borland/MTGLifeCounter2 | 
	refs/heads/master | 
	MTGLifeCounter2/Utility.swift | 
	mit | 
	1 | 
	//
//  Utility.swift
//  MTGLifeCounter2
//
//  Created by Orion Edwards on 4/09/14.
//  Copyright (c) 2014 Orion Edwards. All rights reserved.
//
import Foundation
import UIKit
public let GlobalTintColor = UIColor(red: 0.302, green: 0.102, blue: 0.702, alpha: 1)
// swift 2.2 compiler +'ing more than 3 arrays together takes minutes to COMPILE, so we don't + them
func concat<T>(_ arrays: [[T]]) -> [T] {
    var result = [T]()
    for array in arrays {
        result.append(contentsOf: array)
    }
    return result
}
extension UIView {
    func addConstraints(_ format:String, views:[String:UIView], metrics:[String:CGFloat]? = nil, options:NSLayoutConstraint.FormatOptions=NSLayoutConstraint.FormatOptions(rawValue: 0)) {
        let constraints = NSLayoutConstraint.constraints(
            withVisualFormat: format,
            options: options,
            metrics: metrics,
            views: views)
        
        self.addConstraints(constraints)
    }
    
    func addAllConstraints(_ constraints: [NSLayoutConstraint]...) {
        addConstraints(concat(constraints))
    }
    
    func removeAllConstraints(_ constraints: [NSLayoutConstraint]...) {
        removeConstraints(concat(constraints))
    }
}
extension Sequence where Iterator.Element == NSLayoutConstraint {
    func affectingView(_ view: UIView) -> [NSLayoutConstraint] {
        return filter {
            if let first = $0.firstItem as? UIView, first == view {
                return true
            }
            if let second = $0.secondItem as? UIView, second == view {
                return true
            }
            return false
        }
    }
}
//! The UInt is the number rolled on the dice face, the Bool is true if this is the "winning" value
func randomUntiedDiceRolls(_ numDice:Int, diceFaceCount:UInt) -> [(UInt, Bool)] {
    var values = Array(repeating: UInt(1), count: numDice)
    // find the indexes of values that have the highest value, and replace those values with randoms. Repeat until no ties
    while true {
        let maxVal = values.max()! // we only care if the highest dice rolls are tied (e.g. if there are 3 people and the dice go 7,2,2 that's fine)
        let tiedValueIndexes = findIndexes(values, value: maxVal)
        if tiedValueIndexes.count < 2 {
            break
        }
        
        for ix in tiedValueIndexes {
            values[ix] = UInt(arc4random_uniform(UInt32(diceFaceCount)) + 1)
        }
    }
    let maxVal = values.max()!
    return values.map{ x in (x, x == maxVal) }
}
func delay(_ seconds: TimeInterval, block: @escaping ()->()) -> () -> () {
    var canceled = false // volatile? lock?
    let dt = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
    DispatchQueue.main.asyncAfter(deadline: dt) {
        if !canceled {
            block()
        }
    }
    
    return {
        canceled = true
    }
}
func findIndexes<T : Equatable>(_ domain:[T], value:T) -> [Int] {
    return domain
        .enumerated()
        .filter{ (ix, obj) in obj == value }
        .map{ (ix, obj) in ix }
}
enum ContainerOrientation {
    case portrait, landscape
}
extension UIView {
    /** returns the "orientation" of the VIEW ITSELF, not neccessarily the screen */
//    var orientation : ScreenOrientation {
//        return bounds.size.orientation
//    }
}
extension CGSize {
    var orientation : ContainerOrientation {
        return (width > height) ? .landscape : .portrait
    }
}
 | 
	a054cb8e320c7de5a6eaeefc22b55bbc | 29.893805 | 186 | 0.618734 | false | false | false | false | 
| 
	groue/GRDB.swift | 
	refs/heads/master | 
	GRDB/QueryInterface/Request/Association/HasManyAssociation.swift | 
	mit | 
	1 | 
	/// The `HasManyAssociation` indicates a one-to-many connection between two
/// record types, such as each instance of the declaring record "has many"
/// instances of the other record.
///
/// For example, if your application includes authors and books, and each author
/// is assigned zero or more books, you'd declare the association this way:
///
/// ```swift
/// struct Book: TableRecord { }
/// struct Author: TableRecord {
///     static let books = hasMany(Book.self)
/// }
/// ```
///
/// A `HasManyAssociation` should be supported by an SQLite foreign key.
///
/// Foreign keys are the recommended way to declare relationships between
/// database tables because not only will SQLite guarantee the integrity of your
/// data, but GRDB will be able to use those foreign keys to automatically
/// configure your associations.
///
/// You define the foreign key when you create database tables. For example:
///
/// ```swift
/// try db.create(table: "author") { t in
///     t.autoIncrementedPrimaryKey("id")             // (1)
///     t.column("name", .text)
/// }
/// try db.create(table: "book") { t in
///     t.autoIncrementedPrimaryKey("id")
///     t.column("authorId", .integer)                // (2)
///         .notNull()                                // (3)
///         .indexed()                                // (4)
///         .references("author", onDelete: .cascade) // (5)
///     t.column("title", .text)
/// }
/// ```
///
/// 1. The author table has a primary key.
/// 2. The `book.authorId` column is used to link a book to the author it
///    belongs to.
/// 3. Make the `book.authorId` column not null if you want SQLite to guarantee
///    that all books have an author.
/// 4. Create an index on the `book.authorId` column in order to ease the
///    selection of an author's books.
/// 5. Create a foreign key from `book.authorId` column to `author.id`, so that
///    SQLite guarantees that no book refers to a missing author. The
///    `onDelete: .cascade` option has SQLite automatically delete all of an
///    author's books when that author is deleted.
///    See <https://sqlite.org/foreignkeys.html#fk_actions> for more information.
///
/// The example above uses auto-incremented primary keys. But generally
/// speaking, all primary keys are supported.
///
/// If the database schema does not define foreign keys between tables, you can
/// still use `HasManyAssociation`. But your help is needed to define the
/// missing foreign key:
///
/// ```swift
/// struct Author: TableRecord {
///     static let books = hasMany(Book.self, using: ForeignKey(...))
/// }
/// ```
public struct HasManyAssociation<Origin, Destination> {
    public var _sqlAssociation: _SQLAssociation
    
    init(
        to destinationRelation: SQLRelation,
        key: String?,
        using foreignKey: ForeignKey?)
    {
        let destinationTable = destinationRelation.source.tableName
        
        let foreignKeyCondition = SQLForeignKeyCondition(
            destinationTable: destinationTable,
            foreignKey: foreignKey,
            originIsLeft: false)
        
        let associationKey: SQLAssociationKey
        if let key = key {
            associationKey = .fixedPlural(key)
        } else {
            associationKey = .inflected(destinationTable)
        }
        
        _sqlAssociation = _SQLAssociation(
            key: associationKey,
            condition: .foreignKey(foreignKeyCondition),
            relation: destinationRelation,
            cardinality: .toMany)
    }
}
extension HasManyAssociation: AssociationToMany {
    public typealias OriginRowDecoder = Origin
    public typealias RowDecoder = Destination
}
 | 
	6b861901a9e6d76c6875236a29886460 | 37 | 81 | 0.639989 | false | false | false | false | 
| 
	pauljohanneskraft/Algorithms-and-Data-structures | 
	refs/heads/master | 
	AlgorithmsDataStructures/Classes/Graphs/Types/HashingGraph.swift | 
	mit | 
	1 | 
	//
//  HashingGraph.swift
//  Algorithms&DataStructures
//
//  Created by Paul Kraft on 09.08.16.
//  Copyright © 2016 pauljohanneskraft. All rights reserved.
//
// swiftlint:disable trailing_whitespace
public struct HashingGraph: Graph, CustomStringConvertible {
	
	// stored properties
	public var internalEdges: [Int: [Int: Int]]
    
	// initializers
	public init() { internalEdges = [:] }
	
	// computed properties
	public var edges: Set<GraphEdge> {
		get {
			return Set(internalEdges.flatMap { (key, value) in
                value.map { GraphEdge(start: key, end: $0.key, weight: $0.value) }
            })
		}
		set {
			internalEdges = [:]
			for e in newValue { self[e.start, e.end] = e.weight }
		}
	}
	
	public var vertices: Set<Int> {
        var set = Set<Int>()
        for e in internalEdges {
            set.insert(e.key)
            for edge in e.value { set.insert(edge.key) }
        }
        return set
    }
	
	public var description: String {
		var str = "Graph_Hashing:\n"
		for start in internalEdges.sorted(by: { $0.0 < $1.0 }) {
			str += "\tVertex \(start.key):\n"
			for end in start.value.sorted(by: { $0.0 < $1.0 }) {
				str += "\t\t- Vertex \(end.key): \(end.value)\n"
			}
		}
		return str
	}
	
	// subscripts
	public subscript(start: Int) -> [(end: Int, weight: Int)] {
		if internalEdges[start] == nil { return [] }
		return internalEdges[start]!.map { $0 }
	}
	
	public subscript(start: Int, end: Int) -> Int? {
		get { return internalEdges[start]?[end]		}
		set {
            if newValue != nil {
                if internalEdges [ start ] == nil { internalEdges [ start ] = [:] }
                if internalEdges [  end  ] == nil { internalEdges [  end  ] = [:] }
            }
			
            defer {
                if internalEdges[start]?.isEmpty ?? false { internalEdges[start] = nil }
                if internalEdges[ end ]?.isEmpty ?? false { internalEdges[ end ] = nil }
            }
            
			internalEdges [start]! [end] = newValue
		}
	}
}
 | 
	23f4fef5ee268fd8f7f55b213b0e7d42 | 26.081081 | 88 | 0.564371 | false | false | false | false | 
| 
	watson-developer-cloud/ios-sdk | 
	refs/heads/master | 
	Sources/DiscoveryV1/Models/Gateway.swift | 
	apache-2.0 | 
	1 | 
	/**
 * (C) Copyright IBM Corp. 2019, 2020.
 *
 * 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
/**
 Object describing a specific gateway.
 */
public struct Gateway: Codable, Equatable {
    /**
     The current status of the gateway. `connected` means the gateway is connected to the remotly installed gateway.
     `idle` means this gateway is not currently in use.
     */
    public enum Status: String {
        case connected = "connected"
        case idle = "idle"
    }
    /**
     The gateway ID of the gateway.
     */
    public var gatewayID: String?
    /**
     The user defined name of the gateway.
     */
    public var name: String?
    /**
     The current status of the gateway. `connected` means the gateway is connected to the remotly installed gateway.
     `idle` means this gateway is not currently in use.
     */
    public var status: String?
    /**
     The generated **token** for this gateway. The value of this field is used when configuring the remotly installed
     gateway.
     */
    public var token: String?
    /**
     The generated **token_id** for this gateway. The value of this field is used when configuring the remotly installed
     gateway.
     */
    public var tokenID: String?
    // Map each property name to the key that shall be used for encoding/decoding.
    private enum CodingKeys: String, CodingKey {
        case gatewayID = "gateway_id"
        case name = "name"
        case status = "status"
        case token = "token"
        case tokenID = "token_id"
    }
}
 | 
	f79824b24bf3a3d7fe8a2bf2ea78207d | 28.528571 | 120 | 0.665215 | false | false | false | false | 
| 
	duliodenis/musicvideos | 
	refs/heads/master | 
	Music Videos/Music Videos/Controllers/MusicVideoTableViewCell.swift | 
	mit | 
	1 | 
	//
//  MusicVideoTableViewCell.swift
//  Music Videos
//
//  Created by Dulio Denis on 2/20/16.
//  Copyright © 2016 Dulio Denis. All rights reserved.
//
import UIKit
class MusicVideoTableViewCell: UITableViewCell {
    @IBOutlet weak var videoImageView: UIImageView!
    @IBOutlet weak var videoArtist: UILabel!
    @IBOutlet weak var videoTitle: UILabel!
    
    
    var video: MusicVideos? {
        didSet {
            updateCell()
        }
    }
    
    
    func updateCell() {
        // Use Preferred for for Accessibility
        videoTitle.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
        videoArtist.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
        
        videoTitle.text = video?.name
        videoArtist.text = video?.artist
        
        if video!.imageData != nil {
            // get data from array
            videoImageView.image = UIImage(data: video!.imageData!)
        } else {
            getVideoImages(video!, imageView: videoImageView)
        }
    }
    
    
    func getVideoImages(video: MusicVideos, imageView: UIImageView) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            let data = NSData(contentsOfURL: NSURL(string: video.imageURL)!)
            
            var image: UIImage?
            
            if data != nil {
                video.imageData = data
                image = UIImage(data: data!)
            }
            
            // back to the main queue
            dispatch_async(dispatch_get_main_queue()) {
                imageView.image = image
            }
        }
    }
}
 | 
	9269708bd9ceb8240953b18c38e4ba3c | 27.050847 | 87 | 0.580665 | false | false | false | false | 
| 
	hironytic/Moltonf-iOS | 
	refs/heads/master | 
	Moltonf/Model/ImageCache/ImageCacheDB.swift | 
	mit | 
	1 | 
	//
// ImageCacheDB.swift
// Moltonf
//
// Copyright (c) 2016 Hironori Ichimiya <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import RealmSwift
private let IMAGE_CACHE_DIR = "images"
private let IMAGE_CACHE_DB = "images.realm"
public class ImageCacheDB {
    public static let shared = ImageCacheDB()
    
    public let imageCacheDirURL: URL
    
    private init() {
        let cachesDir = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
        imageCacheDirURL = URL(fileURLWithPath: cachesDir).appendingPathComponent(IMAGE_CACHE_DIR)
        _ = try? FileManager.default.createDirectory(at: imageCacheDirURL, withIntermediateDirectories: true, attributes: nil)
    }
    
    private func createRealm() -> Realm {
        let imageCacheDBURL = imageCacheDirURL.appendingPathComponent(IMAGE_CACHE_DB)
        let config = Realm.Configuration(fileURL: imageCacheDBURL, objectTypes: [CachedImage.self])
        return try! Realm(configuration: config)
    }
    
    private func withRealm<Result>(_ proc: (Realm) throws -> Result) rethrows -> Result {
        return try proc(createRealm())
    }
    
    public func imageData(forURL url: URL) -> Data? {
        let urlString = url.absoluteString
        let cacheFileNameOrNil = withRealm { realm -> String? in
            let cachedImages = realm.objects(CachedImage.self)
                .filter(NSPredicate(format: "url = %@", urlString))
            
            return cachedImages.first?.cacheFileName
        }
        guard let cacheFileName = cacheFileNameOrNil else { return nil }
        
        let cacheFileURL = imageCacheDirURL.appendingPathComponent(cacheFileName)
        return try? Data(contentsOf: cacheFileURL)
    }
    
    public func putImageData(forURL url: URL, data: Data) throws {
        let baseName = UUID().uuidString
        let ext = url.pathExtension
        let cacheFileName = (baseName as NSString).appendingPathExtension(ext) ?? baseName
        let cacheFileURL = imageCacheDirURL.appendingPathComponent(cacheFileName)
        try data.write(to: cacheFileURL, options: [.atomic])
        try withRealm { realm in
            let cachedImage = CachedImage()
            cachedImage.url = url.absoluteString
            cachedImage.cacheFileName = cacheFileName
            try realm.write {
                realm.add(cachedImage)
            }
        }
    }
}
 | 
	322ea40121c86f57794526a8332e90ad | 41.268293 | 126 | 0.696769 | false | false | false | false | 
| 
	huangboju/Moots | 
	refs/heads/master | 
	算法学习/LeetCode/LeetCode/MaxProfit.swift | 
	mit | 
	1 | 
	//
//  MaxProfit.swift
//  LeetCode
//
//  Created by xiAo_Ju on 2020/3/23.
//  Copyright © 2020 伯驹 黄. All rights reserved.
//
import Foundation
func maxProfit(_ prices: [Int]) -> Int {
    if prices.isEmpty { return 0 }
    var minPrice = prices[0]
    var maxProfit = 0
    for price in prices {
        let profit = price - minPrice
        if profit > maxProfit {
            maxProfit = profit
        }
        minPrice = min(minPrice, price)
    }
    return maxProfit
}
func maxProfitII(_ prices: [Int]) -> Int {
    guard prices.count > 1 else { return 0 }
    var maxProfit = 0
    for i in 1 ..< prices.count {
        let profit = prices[i] - prices[i - 1]
        if profit > 0 {
            maxProfit += profit
        }
    }
    return maxProfit
}
 | 
	2c96f72f9c9805d846ae94e1f1d8b5d6 | 17.428571 | 47 | 0.556848 | false | false | false | false | 
| 
	CodaFi/swift | 
	refs/heads/main | 
	validation-test/compiler_crashers_fixed/01509-bool-edited.swift | 
	apache-2.0 | 
	65 | 
	// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
// This test was tweaked slightly from the original 1509-bool.swift, because an
// unrelated change happened to avoid the crash.
ance(x) { self.c]
var b {
}
case ..d<T>, U, (c == {
return self.h == e? = {
}
for c : Sequence where f: C {
func b: Int
}
}
}
protocol a {
func b(Any] = "a<T) {
typealias A : A {
 | 
	f54e803438690b2ed846c4968546714e | 28.416667 | 79 | 0.6983 | false | false | false | false | 
| 
	bitboylabs/selluv-ios | 
	refs/heads/master | 
	selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab5MyPage/SLV_9113_MyPageFaqController.swift | 
	mit | 
	1 | 
	//
//  SLV_9113_MyPageFaqController.swift
//  selluv-ios
//
//  Created by 김택수 on 2017. 6. 29..
//  Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import UIKit
class SLV_9113_MyPageFaqController: SLVBaseStatusShowController {
    //MARK:
    //MARK: Life Cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initUI()
        self.settingUI()
        self.loadData()
    }
    
    //MARK:
    //MARK: Private
    
    func initUI() {
    }
    
    func settingUI() {
        tabController.animationTabBarHidden(true)
        tabController.hideFab()
        
        self.title = "FAQ"
        self.navigationItem.hidesBackButton = true
        
        let back = UIButton()
        back.setImage(UIImage(named:"ic-back-arrow.png"), for: .normal)
        back.frame = CGRect(x: 17, y: 23, width: 12+32, height: 20)
        back.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 26)
        back.addTarget(self, action: #selector(SLV_9113_MyPageFaqController.clickBackButton(_:)), for: .touchUpInside)
        let item = UIBarButtonItem(customView: back)
        self.navigationItem.leftBarButtonItem = item
    }
    
    func loadData() {
        
    }
    
    //MARK:
    //MARK: IBAction
    
    func clickBackButton(_ sender:UIButton) {
        self.navigationController?.popViewController()
    }
}
 | 
	6e905f31f2ea5ecea86f79a2b8816c15 | 24.018182 | 118 | 0.600291 | false | false | false | false | 
| 
	trident10/TDMediaPicker | 
	refs/heads/master | 
	TDMediaPicker/Classes/Model/DataModel/Config/TDConfigPermissionScreen.swift | 
	mit | 
	1 | 
	//
//  TDConfigPermissionScreen.swift
//  Pods
//
//  Created by abhimanyujindal10 on 07/19/2017.
//  Copyright (c) 2017 abhimanyujindal10. All rights reserved.
//
import Foundation
open class TDConfigPermissionScreen: NSObject{
    
    open var customView: TDConfigView?
    open var standardView: TDConfigView?
    open var caption: TDConfigLabel?
    open var settingButton: TDConfigButton?
    open var cancelButton: TDConfigButton?
    
    public init(customView: TDConfigViewCustom){
        super.init()
        self.customView = customView
    }
    
    public init(standardView: TDConfigViewStandard? = nil, caption: TDConfigLabel? = nil, settingButton: TDConfigButton? = nil, cancelButton: TDConfigButton? = nil){
        super.init()
        self.standardView = standardView
        self.caption = caption
        self.settingButton = settingButton
        self.cancelButton = cancelButton
    }
}
 | 
	672a9dcf27b200f40ccf8c7b360ef94b | 28.483871 | 165 | 0.699125 | false | true | false | false | 
| 
	qualaroo/QualarooSDKiOS | 
	refs/heads/master | 
	QualarooTests/Filters/CustomPropertiesFilterSpec.swift | 
	mit | 
	1 | 
	//
//  CustomPropertiesFilterSpec.swift
//  QualarooTests
//
//  Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved.
//
//  Please refer to the LICENSE.md file for the terms and conditions
//  under which redistribution and use of this file is permitted.
//
import Foundation
import Quick
import Nimble
@testable import Qualaroo
class CustomPropertiesFilterSpec: QuickSpec {
  
  func buildFilter(_ properties: [String: String]) -> CustomPropertiesFilter {
    return CustomPropertiesFilter(customProperties: CustomProperties(properties))
  }
  
  override func spec() {
    super.spec()
    
    describe("CustomPropertiesFilter") {
      var filter: CustomPropertiesFilter!
      beforeEach {
        filter = CustomPropertiesFilter(customProperties: CustomProperties([:]))
      }
      
      it("matches basic cases") {
        expect(filter.check(rule: nil, surveyId: 1)).to(beTrue())
        expect(filter.check(rule: "", surveyId: 1)).to(beTrue())
        expect(filter.check(rule: " ", surveyId: 1)).to(beTrue())
        expect(filter.check(rule: "\"something\" == \"something\"", surveyId: 1)).to(beTrue())
        expect(filter.check(rule: "2", surveyId: 1)).to(beTrue())
        expect(filter.check(rule: "2 > 2", surveyId: 1)).to(beFalse())
        expect(filter.check(rule: "2 != 2", surveyId: 1)).to(beFalse())
        expect(filter.check(rule: "\"something\"||2==2", surveyId: 1)).to(beTrue())
        expect(filter.check(rule: "\"something\"&&2==2", surveyId: 1)).to(beTrue())
      }
      
      it("ignores empty spaces") {
        expect(filter.check(rule: "1==1", surveyId: 0)).to(beTrue())
        expect(filter.check(rule: "1 == 1", surveyId: 0)).to(beTrue())
        expect(filter.check(rule: " 1==      1", surveyId: 0)).to(beTrue())
      }
      
      it("matches based on custom properties") {
        expect(filter.check(rule: "premium==\"true\"", surveyId: 0)).to(beFalse())
        
        filter = self.buildFilter(["premium": "true"])
        expect(filter.check(rule: "premium==\"true\"", surveyId: 0)).to(beTrue())
        expect(filter.check(rule: "premium == \"true\" && age > 18", surveyId: 0)).to(beFalse())
        
        filter = self.buildFilter(["premium": "true", "age": "18"])
        expect(filter.check(rule: "premium == \"true\" && age > 18", surveyId: 0)).to(beFalse())
        
        filter = self.buildFilter(["premium": "true", "age": "19"])
        expect(filter.check(rule: "premium == \"true\" && age > 18", surveyId: 0)).to(beTrue())
        expect(filter.check(rule: "(premium==\"true\" && age > 18) && name=\"Joe\"", surveyId: 0)).to(beFalse())
        
        filter = self.buildFilter(["premium": "true", "age": "19", "name": "Joe"])
        expect(filter.check(rule: "(premium==\"true\" && age > 18) && name==\"Joe\"", surveyId: 0)).to(beTrue())
      
        
        filter = self.buildFilter(["premium": "true", "age": "16", "name": "Joe"])
        expect(filter.check(rule: "((premium==\"true\" && age > 18) && name==\"Joe\") || job == \"ceo\"", surveyId: 0)).to(beFalse())
        
        filter = self.buildFilter(["premium": "true", "age": "16", "name": "Joe", "job": "ceo"])
        expect(filter.check(rule: "((premium==\"true\" && age > 18) && name==\"Joe\") || job == \"ceo\"", surveyId: 0)).to(beTrue())
        
        filter = self.buildFilter(["platform": "iOS"])
        expect(filter.check(rule: "platform==\"Android\"", surveyId: 0)).to(beFalse())
        
        filter = self.buildFilter(["android": "android"])
        expect(filter.check(rule: "android==\"android\"", surveyId: 0)).to(beTrue())
      }
    }
  }
}
 | 
	a15920968b4635c30143fd0b255bd90d | 43.109756 | 133 | 0.579762 | false | false | false | false | 
| 
	jaredsinclair/sodes-audio-example | 
	refs/heads/master | 
	Sodes/SodesFoundation/DownloadOperation.swift | 
	mit | 
	1 | 
	//
//  DownloadOperation.swift
//  SodesFoundation
//
//  Created by Jared Sinclair on 7/9/16.
//
//
import Foundation
public class DownloadOperation: WorkOperation {
    
    public enum Result {
        case tempUrl(URL, HTTPURLResponse)
        case error(HTTPURLResponse?, Error?)
    }
    
    private let internals: DownloadOperationInternals
    
    public init(url: URL, session: URLSession, completion: @escaping (Result) -> Void) {
        let internals = DownloadOperationInternals(
            request: URLRequest(url: url),
            session: session
        )
        self.internals = internals
        super.init {
            completion(internals.result)
        }
    }
    
    public init(request: URLRequest, session: URLSession, completion: @escaping (Result) -> Void) {
        let internals = DownloadOperationInternals(
            request: request,
            session: session
        )
        self.internals = internals
        super.init {
            completion(internals.result)
        }
    }
    
    override public func work(_ finish: @escaping () -> Void) {
        internals.task = internals.session.downloadTask(with: internals.request) { (tempUrl, response, error) in
            guard !self.isCancelled else {return}
            // TODO: [MEDIUM] Consider how to handle redirects (POST vs GET e.g.)
            guard
                let r = response as? HTTPURLResponse,
                let tempUrl = tempUrl,
                200 <= r.statusCode && r.statusCode <= 299 else
            {
                self.internals.result = .error((response as? HTTPURLResponse), error)
                finish()
                return
            }
            self.internals.result = .tempUrl(tempUrl, r)
            finish()
        }
        internals.task?.resume()
    }
    
    override public func cancel() {
        internals.task?.cancel()
        super.cancel()
    }
    
}
private class DownloadOperationInternals {
    
    let request: URLRequest
    let session: URLSession
    var task: URLSessionDownloadTask?
    var result: DownloadOperation.Result = .error(nil, nil)
    
    init(request: URLRequest, session: URLSession) {
        self.request = request
        self.session = session
    }
    
}
 | 
	31678476eb3fbef033d516149d89692f | 27.2 | 112 | 0.58289 | false | false | false | false | 
| 
	OliverCulleyDeLange/WeClimbRocks-IOS | 
	refs/heads/master | 
	wcr/AppDelegate.swift | 
	mit | 
	1 | 
	//
//  AppDelegate.swift
//  wcr
//
//  Created by Oliver Culley De Lange on 08/09/2015.
//  Copyright (c) 2015 Oliver Culley De Lange. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }
    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }
    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }
    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }
    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }
    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }
    // MARK: - Core Data stack
    lazy var applicationDocumentsDirectory: NSURL = {
        // The directory the application uses to store the Core Data store file. This code uses a directory named "uk.co.oliverdelange.wcr" in the application's documents Application Support directory.
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        return urls[urls.count-1] as! NSURL
    }()
    lazy var managedObjectModel: NSManagedObjectModel = {
        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
        let modelURL = NSBundle.mainBundle().URLForResource("wcr", withExtension: "momd")!
        return NSManagedObjectModel(contentsOfURL: modelURL)!
    }()
    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
        // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
        // Create the coordinator and store
        var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("wcr.sqlite")
        var error: NSError? = nil
        var failureReason = "There was an error creating or loading the application's saved data."
        if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
            coordinator = nil
            // Report any error we got.
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
            dict[NSLocalizedFailureReasonErrorKey] = failureReason
            dict[NSUnderlyingErrorKey] = error
            error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
            // Replace this with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog("Unresolved error \(error), \(error!.userInfo)")
            abort()
        }
        
        return coordinator
    }()
    lazy var managedObjectContext: NSManagedObjectContext? = {
        // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
        let coordinator = self.persistentStoreCoordinator
        if coordinator == nil {
            return nil
        }
        var managedObjectContext = NSManagedObjectContext()
        managedObjectContext.persistentStoreCoordinator = coordinator
        return managedObjectContext
    }()
    // MARK: - Core Data Saving support
    func saveContext () {
        if let moc = self.managedObjectContext {
            var error: NSError? = nil
            if moc.hasChanges && !moc.save(&error) {
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                NSLog("Unresolved error \(error), \(error!.userInfo)")
                abort()
            }
        }
    }
}
 | 
	f2cdf5da59eb92692e3ff5d6e5747941 | 54.27027 | 290 | 0.715077 | false | false | false | false | 
| 
	DigitalRogues/DisneyWatch | 
	refs/heads/master | 
	DisneyWatchApp Extension/ComplicationController.swift | 
	mit | 
	1 | 
	//
//  ComplicationController.swift
//  DisneyWatcher WatchKit Extension
//
//  Created by punk on 9/19/15.
//  Copyright © 2015 Digital Rogues. All rights reserved.
//
import ClockKit
class ComplicationController: NSObject, CLKComplicationDataSource {
    
    // MARK: - Timeline Configuration
    var lastUpdated = ""
    
    func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) {
        handler([.None])
    }
    
    func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
        let now = NSDate()
        handler(now)
    }
    
    func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
        let now = NSDate()
        handler(now)
    }
    
    func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) {
        handler(.ShowOnLockScreen)
    }
    
    // MARK: - Timeline Population
    
    func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
        // Call the handler with the current timeline entry
        let api = IndexGet()
        api.drGET(NSURL(string: "https://disney.digitalrecall.net/json")!) { (magicObj, error) -> Void in
            
            self.lastUpdated = magicObj!.lastUpdated
            
            let entry =  self.createTimeLineEntry(magicObj!, compFamily: complication)
            handler(entry)
        }
        
    }
    
    func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
        // Call the handler with the timeline entries prior to the given date
        handler(nil)
    }
    
    func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
        // Call the handler with the timeline entries after to the given date
        handler(nil)
    }
    
    // MARK: - Update Scheduling
    
    func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) {
        // Call the handler with the date when you would next like to be given the opportunity to update your complication content
        //runs 30 minutes after the time of the update so if update was at 10, it'll run at 10:30 then 11 then 11:30 etc
        let lastDate = NSDate(timeIntervalSince1970: Double(self.lastUpdated)!)
        let updateTime = lastDate + 30.minutes
        print(updateTime)
        handler(updateTime);
    }
    
    func requestedUpdateDidBegin() {
        print("requestedUpdated")
        let complicationServer = CLKComplicationServer.sharedInstance()
                for complication in complicationServer.activeComplications {
                    complicationServer.reloadTimelineForComplication(complication)
                }
    }
    
    // MARK: - Placeholder Templates
    
    func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) {
        
        let dlrText =  CLKSimpleTextProvider(text: "DLR:Loading...", shortText: "0")
        let dcaText =  CLKSimpleTextProvider(text: "DCA:Loading...", shortText: "0")
        
        let temp = createTemplate(dlrText, dcaText: dcaText, compFamily: complication)
        handler(temp)
        }
    
    func createTimeLineEntry(magicObj:MagicIndexObject, compFamily:CLKComplication)->CLKComplicationTimelineEntry
    {
        let dlrText = CLKSimpleTextProvider(text: "DLR:\(magicObj.dlrIndex)", shortText: magicObj.dlrIndex)
        let dcaText = CLKSimpleTextProvider(text: "DCA:\(magicObj.dcaIndex)", shortText: magicObj.dcaIndex)
        print(dlrText)
        print(dcaText)
        
        let entTemplate = createTemplate(dlrText, dcaText:dcaText, compFamily: compFamily)
        
        // Create the entry.
        let entryDate = NSDate(timeIntervalSince1970: Double(magicObj.lastUpdated)!)
        let entry = CLKComplicationTimelineEntry(date: entryDate, complicationTemplate: entTemplate)
        return entry
    }
    
    func createTemplate(dlrText:CLKSimpleTextProvider, dcaText:CLKSimpleTextProvider, compFamily:CLKComplication) -> CLKComplicationTemplate{
       
        var entTemplate = CLKComplicationTemplate()
        switch (compFamily.family) {
        case (.ModularLarge):
            let textTemplate = CLKComplicationTemplateModularLargeStandardBody()
            textTemplate.headerTextProvider = CLKSimpleTextProvider(text:"DisneyWatch")
            textTemplate.body1TextProvider = dlrText
            textTemplate.body2TextProvider = dcaText
            entTemplate = textTemplate
            
        case (.CircularSmall):
            let textTemplate = CLKComplicationTemplateCircularSmallStackText()
            textTemplate.line1TextProvider = dlrText
            textTemplate.line2TextProvider = dcaText
            entTemplate = textTemplate
            
        case (.UtilitarianSmall):
            let textTemplate = CLKComplicationTemplateUtilitarianSmallFlat()
            let string = "D:\(dlrText.shortText!) • C:\(dcaText.shortText!)"
            textTemplate.textProvider = CLKSimpleTextProvider(text: string)
            entTemplate = textTemplate
            
        default:
            print("somethings broke")
        }
        
        return entTemplate
    }
    
    func returnTopOfHour() -> NSDate{
        let now = NSDate()
        let beginHour = now.beginningOfHour
        return beginHour
    }
    
}
 | 
	ced1c8a7eaf7e566a9dcc41f9138a6de | 38.496599 | 178 | 0.669997 | false | false | false | false | 
| 
	pluralsight/PSOperations | 
	refs/heads/master | 
	PSOperations/DispatchQoS.QoSClass+.swift | 
	apache-2.0 | 
	1 | 
	import Foundation
extension DispatchQoS.QoSClass {
    init(qos: QualityOfService) {
        switch qos {
        case .userInteractive:
            self = .userInteractive
        case .userInitiated:
            self = .userInitiated
        case .utility:
            self = .utility
        case .background:
            self = .background
        case .default:
            self = .default
        @unknown default:
            self = .default
        }
    }
}
 | 
	6ef443b7fa54df3c4591060157baaf54 | 22.4 | 35 | 0.523504 | false | false | false | false | 
| 
	psobot/hangover | 
	refs/heads/master | 
	Hangover/ChatTypingView.swift | 
	mit | 
	1 | 
	//
//  ChatTypingView.swift
//  Hangover
//
//  Created by Peter Sobot on 6/19/15.
//  Copyright © 2015 Peter Sobot. All rights reserved.
//
import Cocoa
class ChatTypingView : NSTableCellView {
    enum Orientation {
        case Left
        case Right
    }
    var backgroundView: NSImageView!
    var orientation: Orientation = .Left
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        backgroundView = NSImageView(frame: NSZeroRect)
        backgroundView.imageScaling = .ScaleAxesIndependently
        backgroundView.image = NSImage(named: "gray_bubble_left")
        addSubview(backgroundView)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func configureWithTypingStatus() {
        orientation = .Left
        backgroundView.image = NSImage(named: orientation == .Right ? "gray_bubble_right" : "gray_bubble_left")
    }
    override var frame: NSRect {
        didSet {
            var backgroundFrame = frame
            backgroundFrame.size.width = 40
            switch (orientation) {
            case .Left:
                backgroundFrame.origin.x = frame.origin.x
            case .Right:
                backgroundFrame.origin.x = frame.size.width - backgroundFrame.size.width
            }
            backgroundView.frame = backgroundFrame
        }
    }
    class func heightForWidth(width: CGFloat) -> CGFloat {
        return 33
    }
}
 | 
	dc689f218c7c0fe8a8b03e9ab44e3b51 | 24.465517 | 111 | 0.617468 | false | false | false | false | 
| 
	Marquis103/RecipeFinder | 
	refs/heads/master | 
	RecipeFinder/RecipeAPI.swift | 
	gpl-3.0 | 
	1 | 
	//
//  RecipeManager.swift
//  RecipeFinder
//
//  Created by Marquis Dennis on 5/7/16.
//  Copyright © 2016 Marquis Dennis. All rights reserved.
//
import Foundation
class RecipeAPI {
	static let sharedAPI = RecipeAPI()
	
	let client = RecipeClient.sharedClient
	
	private (set) var recipes:[Recipe] = {
		return [Recipe]()
	}()
	
	private (set) var searchTerm:String = {
		return String.Empty
	}()
	
	func getRecipes(forFoodWithName name:String, isUpdatingQuery:Bool, completionHandler: (error:ErrorType?)-> Void) {
		
		evaluateSearchTerm(name, isUpdatingQuery: isUpdatingQuery)
		
		do {
			try client.executeRecipeSearch(withQuery: searchTerm, completionHandler: { (recipes, error) in
				guard let recipes = recipes else {
					completionHandler(error: nil)
					return
				}
				
				guard error == nil else {
					print(error)
					completionHandler(error: error)
					return
				}
				
				self.addRecipes(recipes)
				
				completionHandler(error: nil)
			})
		} catch let error {
			print(error)
			completionHandler(error: error)
		}
	}
	
	private func evaluateSearchTerm(query:String, isUpdatingQuery:Bool) {
		//clear dataset if different than previous search
		if searchTerm != query {
			//edge case -- User scrolls to the bottom expecting more results from previous query but the text has changed
			//current implementation will continue to scroll with the current dataset and not reset query value
			if !isUpdatingQuery {
				clearRecipes()
				searchTerm = query
				client.pageCount = 0
			} else {
				client.pageCount += 1
			}
			
		} else {
			if isUpdatingQuery {
				client.pageCount += 1
			} else {
				clearRecipes()
				client.pageCount = 0
			}
		}
	}
	
	private func addRecipes(recipes:[Recipe]) {
		for recipe in recipes {
			self.recipes.append(recipe)
		}
	}
	
	private func clearRecipes() {
		self.recipes.removeAll()
	}
} | 
	bd0b922daacfaf1ebd419c81a8633b40 | 21.445783 | 115 | 0.680451 | false | false | false | false | 
| 
	KYawn/myiOS | 
	refs/heads/master | 
	SignUp/SignUp/ViewController.swift | 
	apache-2.0 | 
	1 | 
	//
//  ViewController.swift
//  SignUp
//
//  Created by K.Yawn Xoan on 3/18/15.
//  Copyright (c) 2015 K.Yawn Xoan. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
    
    @IBOutlet weak var myPasswordConfirm: UITextField!
    @IBOutlet weak var myPassword: UITextField!
    @IBOutlet weak var myEmail: UITextField!
    @IBOutlet weak var username: UITextField!
    @IBAction func SubmitClick(sender: AnyObject) {
        
        
        var req = NSMutableURLRequest(URL: NSURL(string: "http://www.azfs.com.cn/Login/iossignup.php")!)
        req.HTTPMethod = "POST"
        req.HTTPBody = NSString(string: "username=\(username.text)&email=\(myEmail.text)&password=\(myPassword.text)&password-confirm=\(myPasswordConfirm.text)").dataUsingEncoding(NSUTF8StringEncoding)
        NSURLConnection.sendAsynchronousRequest(req, queue: NSOperationQueue()) { (req:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
            if let d = data{
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    
                    var result = NSString(data: data, encoding: NSUTF8StringEncoding)!
                    UIAlertView(title: "Notice", message: "\(result)", delegate: self, cancelButtonTitle: "OK").show()
                    
                })
                
            }
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}
 | 
	63efcbbfa418884bb16a8e8f30d76610 | 34.354167 | 201 | 0.612846 | false | false | false | false | 
| 
	AgaKhanFoundation/WCF-iOS | 
	refs/heads/master | 
	Steps4Impact/DashboardV2/Views/ActivityTimeView.swift | 
	bsd-3-clause | 
	1 | 
	/**
* Copyright © 2019 Aga Khan Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
*    this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The name of the author may not be used to endorse or promote products
*    derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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
protocol ActivityTimeViewDelegate: AnyObject {
  func activityTimeViewTapped(time: ActivityTime)
}
class ActivityTimeView: View {
  private let dayButton = Button(style: .plain)
  private let weekButton = Button(style: .plain)
  private let underlineView = View()
  
  weak var delegate: ActivityTimeViewDelegate?
  
  override func commonInit() {
    super.commonInit()
    dayButton.title = "Day"
    weekButton.title = "Week"
    dayButton.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
    weekButton.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
    underlineView.backgroundColor = Style.Colors.FoundationGreen
    
    addSubview(dayButton) {
      $0.top.bottom.leading.equalToSuperview()
      $0.width.equalToSuperview().dividedBy(2)
    }
    
    addSubview(weekButton) {
      $0.top.bottom.trailing.equalToSuperview()
      $0.width.equalToSuperview().dividedBy(2)
      $0.leading.equalTo(dayButton.snp.trailing)
    }
    
    addSubview(underlineView) {
      $0.height.equalTo(1)
      $0.bottom.equalToSuperview()
      $0.leading.trailing.equalTo(dayButton)
    }
  }
  
  func configure(state: ActivityState) {
    underlineView.snp.remakeConstraints {
      $0.height.equalTo(1)
      $0.bottom.equalToSuperview()
      switch state.time {
      case .day: $0.leading.trailing.equalTo(dayButton)
      case .week: $0.leading.trailing.equalTo(weekButton)
      }
    }
    
    setNeedsLayout()
    UIView.animate(withDuration: 0.3, delay: 0.0, options: [.beginFromCurrentState], animations: {
      self.layoutIfNeeded()
    }, completion: nil)
  }
  
  @objc
  func buttonTapped(_ sender: Button) {
    switch sender {
    case dayButton:
      delegate?.activityTimeViewTapped(time: .day)
    case weekButton:
      delegate?.activityTimeViewTapped(time: .week)
    default:
      break
    }
  }
}
 | 
	02d1cc86e09636abf12ff4048b3f56af | 33.84375 | 98 | 0.720478 | false | false | false | false | 
| 
	nferocious76/NFImageView | 
	refs/heads/master | 
	Example/Pods/Alamofire/Source/RetryPolicy.swift | 
	mit | 
	2 | 
	//
//  RetryPolicy.swift
//
//  Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/)
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//
import Foundation
/// A retry policy that retries requests using an exponential backoff for allowed HTTP methods and HTTP status codes
/// as well as certain types of networking errors.
open class RetryPolicy: RequestInterceptor {
    /// The default retry limit for retry policies.
    public static let defaultRetryLimit: UInt = 2
    /// The default exponential backoff base for retry policies (must be a minimum of 2).
    public static let defaultExponentialBackoffBase: UInt = 2
    /// The default exponential backoff scale for retry policies.
    public static let defaultExponentialBackoffScale: Double = 0.5
    /// The default HTTP methods to retry.
    /// See [RFC 2616 - Section 9.1.2](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html) for more information.
    public static let defaultRetryableHTTPMethods: Set<HTTPMethod> = [.delete, // [Delete](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7) - not always idempotent
                                                                      .get, // [GET](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3) - generally idempotent
                                                                      .head, // [HEAD](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4) - generally idempotent
                                                                      .options, // [OPTIONS](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2) - inherently idempotent
                                                                      .put, // [PUT](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6) - not always idempotent
                                                                      .trace // [TRACE](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.8) - inherently idempotent
    ]
    /// The default HTTP status codes to retry.
    /// See [RFC 2616 - Section 10](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10) for more information.
    public static let defaultRetryableHTTPStatusCodes: Set<Int> = [408, // [Request Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.9)
                                                                   500, // [Internal Server Error](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1)
                                                                   502, // [Bad Gateway](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.3)
                                                                   503, // [Service Unavailable](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4)
                                                                   504 // [Gateway Timeout](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5)
    ]
    /// The default URL error codes to retry.
    public static let defaultRetryableURLErrorCodes: Set<URLError.Code> = [// [Security] App Transport Security disallowed a connection because there is no secure network connection.
        //   - [Disabled] ATS settings do not change at runtime.
        // .appTransportSecurityRequiresSecureConnection,
        // [System] An app or app extension attempted to connect to a background session that is already connected to a
        // process.
        //   - [Enabled] The other process could release the background session.
        .backgroundSessionInUseByAnotherProcess,
                                                                           
        // [System] The shared container identifier of the URL session configuration is needed but has not been set.
        //   - [Disabled] Cannot change at runtime.
        // .backgroundSessionRequiresSharedContainer,
        // [System] The app is suspended or exits while a background data task is processing.
        //   - [Enabled] App can be foregrounded or launched to recover.
        .backgroundSessionWasDisconnected,
                                                                           
        // [Network] The URL Loading system received bad data from the server.
        //   - [Enabled] Server could return valid data when retrying.
        .badServerResponse,
                                                                           
        // [Resource] A malformed URL prevented a URL request from being initiated.
        //   - [Disabled] URL was most likely constructed incorrectly.
        // .badURL,
        // [System] A connection was attempted while a phone call is active on a network that does not support
        // simultaneous phone and data communication (EDGE or GPRS).
        //   - [Enabled] Phone call could be ended to allow request to recover.
        .callIsActive,
                                                                           
        // [Client] An asynchronous load has been canceled.
        //   - [Disabled] Request was cancelled by the client.
        // .cancelled,
        // [File System] A download task couldn’t close the downloaded file on disk.
        //   - [Disabled] File system error is unlikely to recover with retry.
        // .cannotCloseFile,
        // [Network] An attempt to connect to a host failed.
        //   - [Enabled] Server or DNS lookup could recover during retry.
        .cannotConnectToHost,
                                                                           
        // [File System] A download task couldn’t create the downloaded file on disk because of an I/O failure.
        //   - [Disabled] File system error is unlikely to recover with retry.
        // .cannotCreateFile,
        // [Data] Content data received during a connection request had an unknown content encoding.
        //   - [Disabled] Server is unlikely to modify the content encoding during a retry.
        // .cannotDecodeContentData,
        // [Data] Content data received during a connection request could not be decoded for a known content encoding.
        //   - [Disabled] Server is unlikely to modify the content encoding during a retry.
        // .cannotDecodeRawData,
        // [Network] The host name for a URL could not be resolved.
        //   - [Enabled] Server or DNS lookup could recover during retry.
        .cannotFindHost,
                                                                           
        // [Network] A request to load an item only from the cache could not be satisfied.
        //   - [Enabled] Cache could be populated during a retry.
        .cannotLoadFromNetwork,
                                                                           
        // [File System] A download task was unable to move a downloaded file on disk.
        //   - [Disabled] File system error is unlikely to recover with retry.
        // .cannotMoveFile,
        // [File System] A download task was unable to open the downloaded file on disk.
        //   - [Disabled] File system error is unlikely to recover with retry.
        // .cannotOpenFile,
        // [Data] A task could not parse a response.
        //   - [Disabled] Invalid response is unlikely to recover with retry.
        // .cannotParseResponse,
        // [File System] A download task was unable to remove a downloaded file from disk.
        //   - [Disabled] File system error is unlikely to recover with retry.
        // .cannotRemoveFile,
        // [File System] A download task was unable to write to the downloaded file on disk.
        //   - [Disabled] File system error is unlikely to recover with retry.
        // .cannotWriteToFile,
        // [Security] A client certificate was rejected.
        //   - [Disabled] Client certificate is unlikely to change with retry.
        // .clientCertificateRejected,
        // [Security] A client certificate was required to authenticate an SSL connection during a request.
        //   - [Disabled] Client certificate is unlikely to be provided with retry.
        // .clientCertificateRequired,
        // [Data] The length of the resource data exceeds the maximum allowed.
        //   - [Disabled] Resource will likely still exceed the length maximum on retry.
        // .dataLengthExceedsMaximum,
        // [System] The cellular network disallowed a connection.
        //   - [Enabled] WiFi connection could be established during retry.
        .dataNotAllowed,
                                                                           
        // [Network] The host address could not be found via DNS lookup.
        //   - [Enabled] DNS lookup could succeed during retry.
        .dnsLookupFailed,
                                                                           
        // [Data] A download task failed to decode an encoded file during the download.
        //   - [Enabled] Server could correct the decoding issue with retry.
        .downloadDecodingFailedMidStream,
                                                                           
        // [Data] A download task failed to decode an encoded file after downloading.
        //   - [Enabled] Server could correct the decoding issue with retry.
        .downloadDecodingFailedToComplete,
                                                                           
        // [File System] A file does not exist.
        //   - [Disabled] File system error is unlikely to recover with retry.
        // .fileDoesNotExist,
        // [File System] A request for an FTP file resulted in the server responding that the file is not a plain file,
        // but a directory.
        //   - [Disabled] FTP directory is not likely to change to a file during a retry.
        // .fileIsDirectory,
        // [Network] A redirect loop has been detected or the threshold for number of allowable redirects has been
        // exceeded (currently 16).
        //   - [Disabled] The redirect loop is unlikely to be resolved within the retry window.
        // .httpTooManyRedirects,
        // [System] The attempted connection required activating a data context while roaming, but international roaming
        // is disabled.
        //   - [Enabled] WiFi connection could be established during retry.
        .internationalRoamingOff,
                                                                           
        // [Connectivity] A client or server connection was severed in the middle of an in-progress load.
        //   - [Enabled] A network connection could be established during retry.
        .networkConnectionLost,
                                                                           
        // [File System] A resource couldn’t be read because of insufficient permissions.
        //   - [Disabled] Permissions are unlikely to be granted during retry.
        // .noPermissionsToReadFile,
        // [Connectivity] A network resource was requested, but an internet connection has not been established and
        // cannot be established automatically.
        //   - [Enabled] A network connection could be established during retry.
        .notConnectedToInternet,
                                                                           
        // [Resource] A redirect was specified by way of server response code, but the server did not accompany this
        // code with a redirect URL.
        //   - [Disabled] The redirect URL is unlikely to be supplied during a retry.
        // .redirectToNonExistentLocation,
        // [Client] A body stream is needed but the client did not provide one.
        //   - [Disabled] The client will be unlikely to supply a body stream during retry.
        // .requestBodyStreamExhausted,
        // [Resource] A requested resource couldn’t be retrieved.
        //   - [Disabled] The resource is unlikely to become available during the retry window.
        // .resourceUnavailable,
        // [Security] An attempt to establish a secure connection failed for reasons that can’t be expressed more
        // specifically.
        //   - [Enabled] The secure connection could be established during a retry given the lack of specificity
        //     provided by the error.
        .secureConnectionFailed,
                                                                           
        // [Security] A server certificate had a date which indicates it has expired, or is not yet valid.
        //   - [Enabled] The server certificate could become valid within the retry window.
        .serverCertificateHasBadDate,
                                                                           
        // [Security] A server certificate was not signed by any root server.
        //   - [Disabled] The server certificate is unlikely to change during the retry window.
        // .serverCertificateHasUnknownRoot,
        // [Security] A server certificate is not yet valid.
        //   - [Enabled] The server certificate could become valid within the retry window.
        .serverCertificateNotYetValid,
                                                                           
        // [Security] A server certificate was signed by a root server that isn’t trusted.
        //   - [Disabled] The server certificate is unlikely to become trusted within the retry window.
        // .serverCertificateUntrusted,
        // [Network] An asynchronous operation timed out.
        //   - [Enabled] The request timed out for an unknown reason and should be retried.
        .timedOut
        // [System] The URL Loading System encountered an error that it can’t interpret.
        //   - [Disabled] The error could not be interpreted and is unlikely to be recovered from during a retry.
        // .unknown,
        // [Resource] A properly formed URL couldn’t be handled by the framework.
        //   - [Disabled] The URL is unlikely to change during a retry.
        // .unsupportedURL,
        // [Client] Authentication is required to access a resource.
        //   - [Disabled] The user authentication is unlikely to be provided by retrying.
        // .userAuthenticationRequired,
        // [Client] An asynchronous request for authentication has been canceled by the user.
        //   - [Disabled] The user cancelled authentication and explicitly took action to not retry.
        // .userCancelledAuthentication,
        // [Resource] A server reported that a URL has a non-zero content length, but terminated the network connection
        // gracefully without sending any data.
        //   - [Disabled] The server is unlikely to provide data during the retry window.
        // .zeroByteResource,
    ]
    /// The total number of times the request is allowed to be retried.
    public let retryLimit: UInt
    /// The base of the exponential backoff policy (should always be greater than or equal to 2).
    public let exponentialBackoffBase: UInt
    /// The scale of the exponential backoff.
    public let exponentialBackoffScale: Double
    /// The HTTP methods that are allowed to be retried.
    public let retryableHTTPMethods: Set<HTTPMethod>
    /// The HTTP status codes that are automatically retried by the policy.
    public let retryableHTTPStatusCodes: Set<Int>
    /// The URL error codes that are automatically retried by the policy.
    public let retryableURLErrorCodes: Set<URLError.Code>
    /// Creates an `ExponentialBackoffRetryPolicy` from the specified parameters.
    ///
    /// - Parameters:
    ///   - retryLimit:               The total number of times the request is allowed to be retried. `2` by default.
    ///   - exponentialBackoffBase:   The base of the exponential backoff policy. `2` by default.
    ///   - exponentialBackoffScale:  The scale of the exponential backoff. `0.5` by default.
    ///   - retryableHTTPMethods:     The HTTP methods that are allowed to be retried.
    ///                               `RetryPolicy.defaultRetryableHTTPMethods` by default.
    ///   - retryableHTTPStatusCodes: The HTTP status codes that are automatically retried by the policy.
    ///                               `RetryPolicy.defaultRetryableHTTPStatusCodes` by default.
    ///   - retryableURLErrorCodes:   The URL error codes that are automatically retried by the policy.
    ///                               `RetryPolicy.defaultRetryableURLErrorCodes` by default.
    public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit,
                exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase,
                exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale,
                retryableHTTPMethods: Set<HTTPMethod> = RetryPolicy.defaultRetryableHTTPMethods,
                retryableHTTPStatusCodes: Set<Int> = RetryPolicy.defaultRetryableHTTPStatusCodes,
                retryableURLErrorCodes: Set<URLError.Code> = RetryPolicy.defaultRetryableURLErrorCodes) {
        precondition(exponentialBackoffBase >= 2, "The `exponentialBackoffBase` must be a minimum of 2.")
        self.retryLimit = retryLimit
        self.exponentialBackoffBase = exponentialBackoffBase
        self.exponentialBackoffScale = exponentialBackoffScale
        self.retryableHTTPMethods = retryableHTTPMethods
        self.retryableHTTPStatusCodes = retryableHTTPStatusCodes
        self.retryableURLErrorCodes = retryableURLErrorCodes
    }
    open func retry(_ request: Request,
                    for session: Session,
                    dueTo error: Error,
                    completion: @escaping (RetryResult) -> Void) {
        if
            request.retryCount < retryLimit,
            let httpMethod = request.request?.method,
            retryableHTTPMethods.contains(httpMethod),
            shouldRetry(response: request.response, error: error) {
            let timeDelay = pow(Double(exponentialBackoffBase), Double(request.retryCount)) * exponentialBackoffScale
            completion(.retryWithDelay(timeDelay))
        } else {
            completion(.doNotRetry)
        }
    }
    private func shouldRetry(response: HTTPURLResponse?, error: Error) -> Bool {
        if let statusCode = response?.statusCode, retryableHTTPStatusCodes.contains(statusCode) {
            return true
        } else {
            let errorCode = (error as? URLError)?.code
            let afErrorCode = (error.asAFError?.underlyingError as? URLError)?.code
            if let code = errorCode ?? afErrorCode, retryableURLErrorCodes.contains(code) {
                return true
            } else {
                return false
            }
        }
    }
}
// MARK: -
/// A retry policy that automatically retries idempotent requests for network connection lost errors. For more
/// information about retrying network connection lost errors, please refer to Apple's
/// [technical document](https://developer.apple.com/library/content/qa/qa1941/_index.html).
open class ConnectionLostRetryPolicy: RetryPolicy {
    /// Creates a `ConnectionLostRetryPolicy` instance from the specified parameters.
    ///
    /// - Parameters:
    ///   - retryLimit:              The total number of times the request is allowed to be retried.
    ///                              `RetryPolicy.defaultRetryLimit` by default.
    ///   - exponentialBackoffBase:  The base of the exponential backoff policy.
    ///                              `RetryPolicy.defaultExponentialBackoffBase` by default.
    ///   - exponentialBackoffScale: The scale of the exponential backoff.
    ///                              `RetryPolicy.defaultExponentialBackoffScale` by default.
    ///   - retryableHTTPMethods:    The idempotent http methods to retry.
    ///                              `RetryPolicy.defaultRetryableHTTPMethods` by default.
    public init(retryLimit: UInt = RetryPolicy.defaultRetryLimit,
                exponentialBackoffBase: UInt = RetryPolicy.defaultExponentialBackoffBase,
                exponentialBackoffScale: Double = RetryPolicy.defaultExponentialBackoffScale,
                retryableHTTPMethods: Set<HTTPMethod> = RetryPolicy.defaultRetryableHTTPMethods) {
        super.init(retryLimit: retryLimit,
                   exponentialBackoffBase: exponentialBackoffBase,
                   exponentialBackoffScale: exponentialBackoffScale,
                   retryableHTTPMethods: retryableHTTPMethods,
                   retryableHTTPStatusCodes: [],
                   retryableURLErrorCodes: [.networkConnectionLost])
    }
}
 | 
	9384a86323a4079ebc4638a32e57bbe3 | 57.817439 | 182 | 0.618873 | false | false | false | false | 
| 
	hanhailong/practice-swift | 
	refs/heads/master | 
	playgrounds/LinkedList.playground/Contents.swift | 
	mit | 
	2 | 
	// LinkedList
// Source: http://goo.gl/ysg92v
import Foundation
// Double LinkedList structure
class LLNode<T> {
    var key: T?
    var next: LLNode?
    var previous: LLNode?
}
public class LinkedList<T: Equatable>{
    // create a new LLNode instance
    private var head: LLNode<T> = LLNode<T>()
    
    // The number of linked items
    var count: Int{
        get{
            if (head.key == nil) {
                return 0
            }else{
                var current: LLNode = head
                var result: Int = 1
                
                while ((current.next) != nil) {
                    current = current.next!
                    result++
                }
                return result
            }
        }
    }
    
    // Append a new item to a linked list
    func addLink(key:T){
        // establish the head node
        if (head.key == nil) {
            head.key = key
            return;
        }
        
        // establish the iteration variables
        var current: LLNode? = head
        
        while (current != nil) {
            if (current?.next == nil) {
                
                var childToUse: LLNode = LLNode<T>()
                
                childToUse.key = key
                childToUse.previous = current
                current!.next = childToUse
                break;
            }
            
            current = current?.next
        }
    }
    
    // Remove a link at a specific index
    func removeLinkAtIndex(index: Int){
        
        var current: LLNode<T>? = head
        var trailer: LLNode<T>?
        var listIndex: Int = 0
        
        // Determine if the removal is at the head
        if (index == 0){
            current = current?.next
            head = current!
            return
        }
        
        // Iterate through the remaining items
        while (current != nil){
            
            if (listIndex == index){
                // Redirect the trailer and next pointers
                trailer!.next = current?.next
                current = nil
                break
            }
            
            // Update the assignments
            trailer = current
            current = current?.next
            listIndex++
        }
    }
    
    // Print all keys for the class
    func printAllKeys(){
        var current: LLNode! = head
        
        // assign the next instance
        while (current != nil) {
            println("link item is: \(current.key)")
            current = current.next
        }
    }
} | 
	60d4b568d9ff3c8471cc9f6d78adaf96 | 23.825243 | 57 | 0.450313 | false | false | false | false | 
| 
	divljiboy/IOSChatApp | 
	refs/heads/master | 
	Quick-Chat/MagicChat/UI/Cell/ConversationsTableViewCell.swift | 
	mit | 
	1 | 
	//
//  ConversationsTableViewCell.swift
//  MagicChat
//
//  Created by Ivan Divljak on 6/14/18.
//  Copyright © 2018 Mexonis. All rights reserved.
//
import UIKit
class ConversationsTableViewCell: UITableViewCell {
    @IBOutlet weak var profilePic: RoundedImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var messageLabel: UILabel!
    @IBOutlet weak var timeLabel: UILabel!
    
    func clearCellData() {
        self.nameLabel.font = UIFont(name: "AvenirNext-Regular", size: 17.0)
        self.messageLabel.font = UIFont(name: "AvenirNext-Regular", size: 14.0)
        self.timeLabel.font = UIFont(name: "AvenirNext-Regular", size: 13.0)
        self.profilePic.layer.borderColor = UIColor.mtsNavigationBarColor.cgColor
        self.messageLabel.textColor = UIColor.red
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.profilePic.layer.borderWidth = 2
        self.profilePic.layer.borderColor = UIColor.mtsNavigationBarColor.cgColor
    }
    
}
 | 
	b589ee83d18b3dec65eb1eb0277fcdf3 | 30.8125 | 81 | 0.695481 | false | false | false | false | 
| 
	PureSwift/LittleCMS | 
	refs/heads/master | 
	Sources/LittleCMS/Tag.swift | 
	mit | 
	1 | 
	//
//  Tag.swift
//  LittleCMS
//
//  Created by Alsey Coleman Miller on 6/4/17.
//
//
import struct Foundation.Data
import CLCMS
// MARK: - Tag Signature
public typealias Tag = cmsTagSignature
public extension Tag {
    
    var isValid: Bool {
        
        return self.rawValue != 0
    }
}
// MARK: - Tag View
public extension Profile {
    
    /// Creates a new profile, replacing all tags with the specified new ones.
    public init(profile: Profile, tags: TagView) {
        
        self.internalReference = profile.internalReference
        self.tags = tags
    }
    
    /// A collection of the profile's tags.
    public var tags: TagView {
        
        get { return TagView(profile: self) }
        
        mutating set {
            
            // set new tags
            
        }
    }
    
    /// A representation of the profile's contents as a collection of tags.
    public struct TagView {
        
        // MARK: - Properties
        
        internal private(set) var internalReference: CopyOnWrite<Profile.Reference>
        
        // MARK: - Initialization
        
        internal init(_ internalReference: Profile.Reference) {
            
            self.internalReference = CopyOnWrite(internalReference)
        }
        
        /// Create from the specified profile.
        public init(profile: Profile) {
            
            self.init(profile.internalReference.reference)
        }
        
        // MARK: - Accessors
        
        public var count: Int {
            
            return internalReference.reference.tagCount
        }
        
        // MARK: - Methods
        
        // Returns `true` if a tag with signature sig is found on the profile.
        /// Useful to check if a profile contains a given tag.
        public func contains(_ tag: Tag) -> Bool {
            
            return internalReference.reference.contains(tag)
        }
        
        /// Creates a directory entry on tag sig that points to same location as tag destination.
        /// Using this function you can collapse several tag entries to the same block in the profile.
        public mutating func link(_ tag: Tag, to destination: Tag) -> Bool {
            
            return internalReference.mutatingReference.link(tag, to: destination)
        }
        
        /// Returns the tag linked to, in the case two tags are sharing same resource,
        /// or `nil` if the tag is not linked to any other tag.
        public func tagLinked(to tag: Tag) -> Tag? {
            
            return internalReference.reference.tagLinked(to: tag)
        }
        
        /// Returns the signature of a tag located at the specified index.
        public func tag(at index: Int) -> Tag? {
            
            return internalReference.reference.tag(at: index)
        }
        
        @inline(__always)
        fileprivate func pointer(for tag: Tag) -> UnsafeMutableRawPointer? {
            
            return cmsReadTag(internalReference.reference.internalPointer, tag)
        }
        
        /// Reads the tag value and attempts to get value from pointer.
        fileprivate func readCasting(_ tag: Tag, to valueType: TagValueConvertible.Type) -> TagValueConvertible? {
            
            guard let pointer = pointer(for: tag)
                else { return nil }
            
            return valueType.init(tagValue: pointer)
        }
        
        /// Reads the tag value and attempts to get value from pointer.
        fileprivate func readCasting<Value: TagValueConvertible>(_ tag: Tag) -> Value? {
            
            guard let pointer = pointer(for: tag)
                else { return nil }
            
            return Value(tagValue: pointer)
        }
        
        /// Reads the tag value and attempts to get value from pointer.
        public func read(_ tag: Tag) -> TagValue? {
            
            // invalid tag
            guard let valueType = tag.valueType as? TagValueConvertible.Type
                else { return nil }
            
            return readCasting(tag, to: valueType) as TagValue?
        }
    }
}
// MARK: - Collection
/* Sequence seems broken in Swift 4
extension Profile.TagView: RandomAccessCollection {
    
    public subscript(index: Int) -> TagValue {
        
        get {
            
            guard let tag = tag(at: index)
                else { fatalError("No tag at index \(index)") }
            
            guard let value = read(tag)
                else { fatalError("No value for tag \(tag) at index \(index)") }
            
            return value
        }
    }
    
    public subscript(bounds: Range<Int>) -> RandomAccessSlice<Profile.TagView> {
        
        return RandomAccessSlice<Profile.TagView>(base: self, bounds: bounds)
    }
    
    /// The start `Index`.
    public var startIndex: Int {
        
        return 0
    }
    
    /// The end `Index`.
    ///
    /// This is the "one-past-the-end" position, and will always be equal to the `count`.
    public var endIndex: Int {
        
        return count
    }
    
    public func index(before i: Int) -> Int {
        return i - 1
    }
    
    public func index(after i: Int) -> Int {
        return i + 1
    }
    
    public func makeIterator() -> IndexingIterator<Profile.TagView> {
        
        return IndexingIterator(_elements: self)
    }
}*/
// MARK: - Supporting Type
/// Any value that can be retrieved for a tag.
public protocol TagValue { }
fileprivate protocol TagValueConvertible: TagValue {
    
    init(tagValue pointer: UnsafeMutableRawPointer)
}
extension TagValueConvertible {
    
    /// Initializes value by casting pointer.
    init(tagValue pointer: UnsafeMutableRawPointer) {
        
        let pointer = pointer.assumingMemoryBound(to: Self.self)
        
        self = pointer[0]
    }
}
extension TagValueConvertible where Self: ReferenceConvertible, Self.Reference: DuplicableHandle {
    
    /// Initializes value by casting pointer to handle type, creating object wrapper, and then Swift struct.
    init(tagValue pointer: UnsafeMutableRawPointer) {
        
        let pointer = pointer.assumingMemoryBound(to: Self.Reference.InternalPointer.self)
        
        let internalPointer = pointer[0]
        
        // create copy to not corrupt profile handle internals
        guard let newInternalPointer = Self.Reference.cmsDuplicate(internalPointer)
            else { fatalError("Could not create duplicate \(Self.self)") }
        
        let reference = Self.Reference.init(newInternalPointer)
        
        self.init(reference)
    }
}
public extension Tag {
    
    /// The valye type for the specified tag.
    var valueType: TagValue.Type? {
        
        switch self {
            
        case cmsSigAToB0Tag: return Pipeline.self
        case cmsSigAToB1Tag: return Pipeline.self
        case cmsSigAToB2Tag: return Pipeline.self
        case cmsSigBlueColorantTag: return cmsCIEXYZ.self
        case cmsSigBlueMatrixColumnTag: return cmsCIEXYZ.self
            
        default: return nil
        }
    }
}
extension Pipeline: TagValueConvertible { }
extension cmsCIEXYZ: TagValueConvertible { }
// MARK: - Tag Properties
public extension Profile.TagView {
    
    // TODO: implement all tags
    
    public var aToB0: Pipeline? {
        
        return readCasting(cmsSigAToB0Tag)
    }
    
    public var blueColorant: cmsCIEXYZ? {
        
        return readCasting(cmsSigBlueColorantTag)
    }
}
 | 
	b0130323c05e2ce99c59fabbd1dcfb32 | 27.209738 | 114 | 0.581917 | false | false | false | false | 
| 
	skarppi/cavok | 
	refs/heads/master | 
	CAVOK/Map/Location/LastLocation.swift | 
	mit | 
	1 | 
	//
//  LastLocation.swift
//  CAVOK
//
//  Created by Juho Kolehmainen on 15.10.16.
//  Copyright © 2016 Juho Kolehmainen. All rights reserved.
//
import Foundation
class LastLocation {
    class func load() -> MaplyCoordinate? {
        if let location = UserDefaults.standard.dictionary(forKey: "LastLocation") {
            if let longitude = location["longitude"] as? Float,
               let latitude = location["latitude"] as? Float {
                return MaplyCoordinateMakeWithDegrees(longitude, latitude)
            }
        }
        return nil
    }
    class func save(location: MaplyCoordinate) {
        let lastLocation: [String: Any] = [
            "longitude": location.deg.x,
            "latitude": location.deg.y,
            "date": Date()
        ]
        let defaults = UserDefaults.standard
        defaults.set(lastLocation, forKey: "LastLocation")
        defaults.synchronize()
    }
}
 | 
	3dd7f71870f47f280e9bb0f6b512fe3b | 27 | 84 | 0.600649 | false | false | false | false | 
| 
	weirenxin/Swift30day | 
	refs/heads/master | 
	2-CustomFont/2-CustomFont/ViewController.swift | 
	apache-2.0 | 
	1 | 
	//
//  ViewController.swift
//  2-CustomFont
//
//  Created by weirenxin on 2016/12/23.
//  Copyright © 2016年 广西家饰宝科技有限公司. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    private var data = ["30 Days Swift", "这些字体特别适合打「奋斗」和「理想」", "谢谢「造字工房」,本案例不涉及商业使用", "使用到造字工房劲黑体,致黑体,童心体", "呵呵,再见🤗 See you next Project", "微博 @Allen朝辉",
                "测试测试测试测试测试测试",
                "123",
                "Alex",
                "@@@@@@"]
    
    private var fontNames = ["MFTongXin_Noncommercial-Regular", "MFJinHei_Noncommercial-Regular", "MFZhiHei_Noncommercial-Regular", "edundot", "Gaspar Regular"]
    
    private var fonRowIndex = 0
    
    @IBOutlet weak var fontTableView: UITableView!
    @IBOutlet weak var changeFontButton: UIButton!
    @IBAction func changeFontDidTouch(_ sender: Any) {
        fonRowIndex = (fonRowIndex + 1) % 5
        print(fontNames[fonRowIndex])
        fontTableView.reloadData()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        for family in UIFont.familyNames {
            for font in UIFont.fontNames(forFamilyName: family) {
                print(font)
            }
        }
        changeFontButton.layer.cornerRadius = 5.0;
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 35
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = fontTableView.dequeueReusableCell(withIdentifier: "FontCell", for: indexPath)
        
        let text = data[indexPath.row]
        cell.textLabel?.text = text
        cell.textLabel?.textColor = UIColor.white
        cell.textLabel?.font = UIFont(name: self.fontNames[fonRowIndex], size: 16)
        return cell
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
 | 
	56c5fac7b17bed2f7862bc97c2b04b81 | 28.4875 | 160 | 0.625265 | false | false | false | false | 
| 
	wikimedia/wikipedia-ios | 
	refs/heads/main | 
	WikipediaUnitTests/MockCLLocationManager.swift | 
	mit | 
	1 | 
	import Foundation
import CoreLocation
/// A `CLLocationManager` subclass allowing mocking in tests.
final class MockCLLocationManager: CLLocationManager {
    private var _heading: CLHeading?
    override var heading: CLHeading? { _heading }
    private var _location: CLLocation?
    override var location: CLLocation? { _location }
    override class func locationServicesEnabled() -> Bool { true }
    private var _authorizationStatus: CLAuthorizationStatus = .authorizedAlways
    override var authorizationStatus: CLAuthorizationStatus {
        return _authorizationStatus
    }
    override func startUpdatingLocation() {
        isUpdatingLocation = true
    }
    override func stopUpdatingLocation() {
        isUpdatingLocation = false
    }
    override func startUpdatingHeading() {
        isUpdatingHeading = true
    }
    override func stopUpdatingHeading() {
        isUpdatingHeading = false
    }
    override func requestWhenInUseAuthorization() {
        isRequestedForAuthorization = true
    }
    // Empty overrides preventing the real interaction with the superclass.
    override func requestAlwaysAuthorization() { }
    override func startMonitoringSignificantLocationChanges() { }
    override func stopMonitoringSignificantLocationChanges() { }
    // MARK: - Test properties
    var isUpdatingLocation: Bool = false
    var isUpdatingHeading: Bool = false
    var isRequestedForAuthorization: Bool?
    /// Simulates a new location being emitted. Updates the `location` property
    /// and notifies the delegate.
    ///
    /// - Parameter location: The new location used.
    ///
    func simulateUpdate(location: CLLocation) {
        _location = location
        delegate?.locationManager?(self, didUpdateLocations: [location])
    }
    /// Simulates a new heading being emitted. Updates the `heading` property
    /// and notifies the delegate.
    ///
    /// - Parameter heading: The new heading used.
    ///
    func simulateUpdate(heading: CLHeading) {
        _heading = heading
        delegate?.locationManager?(self, didUpdateHeading: heading)
    }
    /// Simulates the location manager failing with an error. Notifies the delegate with
    /// the provided error.
    ///
    /// - Parameter error: The error used for the delegate callback.
    ///
    func simulate(error: Error) {
        delegate?.locationManager?(self, didFailWithError: error)
    }
    /// Updates the `authorizationStatus` value and notifies the delegate.
    ///
    /// - Important: ⚠️ `authorizationStatus` is a static variable. Calling
    /// the `simulate(authorizationStatus:)` function will change the value for all
    /// instances of `MockCLLocationManager`. The `didChangeAuthorization` delegate
    /// method is called only on the delegate of this instance.
    ///
    /// - Parameter authorizationStatus: The new authorization status.
    ///
    func simulate(authorizationStatus: CLAuthorizationStatus) {
        _authorizationStatus = authorizationStatus
        delegate?.locationManagerDidChangeAuthorization?(self)
    }   
}
 | 
	a877ca30db1f3ba189499554fac2a485 | 31.882979 | 88 | 0.695891 | false | false | false | false | 
| 
	loiwu/SCoreData | 
	refs/heads/master | 
	UnCloudNotes/UnCloudNotes/NotesListViewController.swift | 
	mit | 
	1 | 
	//
//  NotesListViewController.swift
//  UnCloudNotes
//
//  Created by loi on 1/28/15.
//  Copyright (c) 2015 GWrabbit. All rights reserved.
//
import UIKit
import CoreData
//@objc (NotesListViewController)
class NotesListViewController: UITableViewController, NSFetchedResultsControllerDelegate {
    lazy var stack : CoreDataStack = CoreDataStack(modelName:"UnCloudNotesDataModel", storeName:"UnCloudNotes", options:[NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: false])
    
    var _notes : NSFetchedResultsController? = nil
    var notes : NSFetchedResultsController {
        if _notes == nil {
            let request = NSFetchRequest(entityName: "Note")
            request.sortDescriptors = [NSSortDescriptor(key: "dateCreated", ascending: false)]
            
            let notes = NSFetchedResultsController(fetchRequest: request, managedObjectContext: stack.context, sectionNameKeyPath: nil, cacheName: nil)
            notes.delegate = self
            _notes = notes
        }
        return _notes!
    }
    
    override func viewWillAppear(animated: Bool){
        super.viewWillAppear(animated)
        notes.performFetch(nil)
        tableView.reloadData()
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var objects = notes.fetchedObjects
        if let objects = objects
        {
            return objects.count
        }
        return 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let note = notes.fetchedObjects![indexPath.row] as Note
        var identifier = "NoteCell"
        if note.image != nil {
            identifier = "NoteCellImage"
        }
        var cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as NoteTableViewCell;
        cell.note = notes.fetchedObjects![indexPath.row] as? Note
        return cell
    }
    
    func controllerWillChangeContent(controller: NSFetchedResultsController) {
        
    }
    
    func controller(controller: NSFetchedResultsController!, didChangeObject anObject: AnyObject!, atIndexPath indexPath: NSIndexPath!, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath!) {
        switch type
        {
        case .Insert:
            tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Automatic)
        case .Delete:
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
        default:
            break
        }
    }
    
    func controllerDidChangeContent(controller: NSFetchedResultsController!) {
        
    }
    
    @IBAction
    func unwindToNotesList(segue:UIStoryboardSegue) {
        NSLog("Unwinding to Notes List")
        var error : NSErrorPointer = nil
        if stack.context.hasChanges
        {
            if stack.context.save(error) == false
            {
                print("Error saving \(error)")
            }
        }
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "createNote"
        {
            let context = NSManagedObjectContext(concurrencyType: .ConfinementConcurrencyType)
            context.parentContext = stack.context
            let navController = segue.destinationViewController as UINavigationController
            let nextViewController = navController.topViewController as CreateNoteViewController
            nextViewController.managedObjectContext = context
        }
        if segue.identifier == "showNoteDetail" {
            let detailView = segue.destinationViewController as NoteDetailViewController
            if let selectedIndex = tableView.indexPathForSelectedRow() {
                if let objects = notes.fetchedObjects {
                    detailView.note = objects[selectedIndex.row] as? Note
                }
            }
        }
    }
}
 | 
	ed26f8fc38b2955ba8fb217195532bf0 | 36.12963 | 220 | 0.658105 | false | false | false | false | 
| 
	drewag/Swiftlier | 
	refs/heads/master | 
	Sources/Swiftlier/Model/Containers/BinarySearchTree.swift | 
	mit | 
	1 | 
	//
//  BinarySearchTree.swift
//  SwiftlieriOS
//
//  Created by Andrew J Wagner on 5/31/17.
//  Copyright © 2017 Drewag. All rights reserved.
//
public class BinarySearchTree<Element: Comparable>: Sequence, CustomStringConvertible {
    fileprivate enum Parent {
        case none
        case left(BinarySearchTree<Element>)
        case right(BinarySearchTree<Element>)
    }
    fileprivate var element: Element?
    fileprivate var parent: Parent
    fileprivate var left: BinarySearchTree<Element>?
    fileprivate var right: BinarySearchTree<Element>?
    public convenience init() {
        self.init(parent: .none, element: nil)
    }
    public convenience init(values: [Element]) {
        self.init()
        for value in values {
            self.insert(value)
        }
    }
    fileprivate init(parent: Parent, element: Element?) {
        self.parent = parent
        self.element = element
    }
    public var count: Int {
        guard self.element != nil else {
            return 0
        }
        return 1 + (self.left?.count ?? 0) + (self.right?.count ?? 0)
    }
    public var min: Element? {
        return self.sink()?.element
    }
    public var max: Element? {
        guard self.element != nil else {
            return nil
        }
        return self.right?.max ?? self.element
    }
    public func makeIterator() -> BinarySearchTreeIterator<Element> {
        return BinarySearchTreeIterator(node: self.sink())
    }
    public func insert(_ element: Element) {
        guard let existing = self.element else {
            self.element = element
            return
        }
        if element < existing {
            guard let left = self.left else {
                self.left = BinarySearchTree<Element>(parent: .left(self), element: element)
                return
            }
            left.insert(element)
        }
        else {
            guard let right = self.right else {
                self.right = BinarySearchTree<Element>(parent: .right(self), element: element)
                return
            }
            right.insert(element)
        }
    }
    public func elements(between min: Element, and max: Element) -> [Element] {
        var output = [Element]()
        var node = self.firstNode(greatThan: min)
        repeat {
            guard let element = node?.element
                , element < max
                else
            {
                return output
            }
            output.append(element)
            node = node?.next()
        } while node != nil
        return output
    }
    public var description: String {
        return self.description(indentedBy: 0, asLast: true)
    }
}
private extension BinarySearchTree {
    func climb() -> BinarySearchTree<Element>? {
        switch self.parent {
        case .none:
            return nil
        case .left(let parent):
            return parent
        case .right(let parent):
            return parent.climb()
        }
    }
    func sink() -> BinarySearchTree<Element>? {
        guard let left = self.left else {
            return self
        }
        return left.sink()
    }
    func next() -> BinarySearchTree<Element>? {
        guard self.element != nil else {
            // This is only possible on the root node
            return nil
        }
        if let right = self.right {
            return right.sink()
        }
        else {
            return self.climb()
        }
    }
    func description(indentedBy: Int, asLast: Bool) -> String {
        var output = ""
        output.append(" ".repeating(nTimes: indentedBy))
        if asLast {
            output += "└"
        }
        else {
            output += "├"
        }
        output += "── "
        guard let element = self.element else {
            output += "∅"
            return output
        }
        output += "\(element)\n"
        if let left = self.left {
            output += left.description(indentedBy: indentedBy + 4, asLast: false)
        }
        else if self.right != nil {
            output += " ".repeating(nTimes: indentedBy + 4) + "├── ∅\n"
        }
        if let right = self.right {
            output += right.description(indentedBy: indentedBy + 4, asLast: true)
        }
        else if self.left != nil {
            output += " ".repeating(nTimes: indentedBy + 4) + "└── ∅\n"
        }
        return output
    }
    func firstNode(greatThan element: Element) -> BinarySearchTree? {
        guard let existingElement = self.element else {
            // This is only possible on the root node
            return nil
        }
        if element < existingElement {
            return self.left?.firstNode(greatThan: element) ?? self
        }
        else {
            return self.right?.firstNode(greatThan: element)
        }
    }
}
public struct BinarySearchTreeIterator<Element: Comparable>: IteratorProtocol {
    fileprivate var node: BinarySearchTree<Element>?
    public mutating func next() -> Element? {
        guard let element = self.node?.element else {
            // This is only possible on the root node
            return nil
        }
        self.node = self.node?.next()
        return element
    }
}
 | 
	4a87e7dbb69b78110ebb9c615df793a9 | 25.39899 | 94 | 0.53855 | false | false | false | false | 
| 
	mukeshthawani/Swift-Algo-DS | 
	refs/heads/master | 
	BinarySearchTree/BinarySearchTree.playground/Contents.swift | 
	mit | 
	1 | 
	//: Playground - noun: a place where people can play
import Cocoa
public class BinarySearchTree<T: Comparable> {
  var parent: BinarySearchTree?
  var left: BinarySearchTree?
  var right: BinarySearchTree?
  var data: T
  init(data: T) {
    self.data = data
  }
  
  public func hasBothChildren() -> Bool {
    return (right != nil && left != nil)
  }
  public func hasRightChild() -> Bool {
    return (right != nil)
  }
  public func hasLeftChild() -> Bool {
    return (left != nil)
  }
  
  public func findMaximum() -> T {
    var node: BinarySearchTree? = self
    while ((node?.right) != nil) {
      node = node?.right
    }
    return (node?.data)!
  }
  
  public func findMinimum() -> T {
    var node: BinarySearchTree? = self
    while (node?.left != nil) {
      node = node?.left
    }
    return (node?.data)!
  }
}
extension BinarySearchTree {
  /// Searches the BinarySearchTree for a given key.
  public func search(key: T) -> BinarySearchTree? {
    var node: BinarySearchTree? = self
    while let n = node {
      if key < n.data {
        node = n.left
      }else if key > n.data {
        node = n.right
      }else {
        return node
      }
    }
    return nil
  }
}
extension BinarySearchTree {
  public func insert(key: T) -> T?{
    let data = insertKey(node: self, key: key)
    return data
  }
  /// Inserts a key at a leaf node.
  private func insertKey(node: BinarySearchTree?, key: T) -> T? {
    guard let node = node else {
      return nil
    }
      if key < node.data {
        // check if the left node is empty then add the new node.
        if let left = node.left {
          return insertKey(node: left, key: key)
        } else {
          node.left = BinarySearchTree(data: key)
          return node.left?.data
        }
      } else {
        // check if the right node is empty then add the new node.
        if let right = node.right {
          return insertKey(node: right, key: key)
        } else {
          node.right = BinarySearchTree(data: key)
          return node.right?.data
        }
      }
  }
}
extension BinarySearchTree {
  public func deleteNode(node: BinarySearchTree?, key: T) -> BinarySearchTree? {
    guard let node = node else {
      return nil
    }
    if node.data == key {
      if node.hasLeftChild() && node.hasRightChild() {
        // When both present.
        
        let successor = findSuccessor(node: node.right!)
        
        // Remove successor from its earlier position.
        deleteNode(node: node, key: successor.data)
        
        // Move both the childrens of node to be deleted to its successor.
        successor.left = node.left
        successor.right = node.right
    
        // If node to be deleted is left child of its parent then its successor will replace that position.
        updateParent(node: node, currentChild: successor)
        return successor
        
      } else if node.hasLeftChild() || node.hasRightChild() {
        
        // Has only one child
        let currentChild = getLeftOrRightChild(node: node)
        updateParent(node: node, currentChild: currentChild!)
        return currentChild
      } else {
        // leaf
        updateParent(node: node, currentChild: nil)
        return nil
      }
    } else {
      if key > node.data {
        node.right?.parent = node
        return deleteNode(node: node.right, key: key)
      } else {
        node.left?.parent = node
        return deleteNode(node: node.left, key: key)
      }
    }
  }
  
  private func getLeftOrRightChild(node: BinarySearchTree) -> BinarySearchTree? {
    if node.hasLeftChild() {
      return node.left
    } else {
      return node.right
    }
  }
  
  private func updateParent(node: BinarySearchTree, currentChild: BinarySearchTree?) -> BinarySearchTree? {
    
    // Check which node to move.
    let parent = node.parent
    
    // Update to new position.
    if parent?.left?.data == node.data {
      parent?.left = currentChild
    } else {
      parent?.right = currentChild
    }
    return parent
  }
  
  private func findSuccessor(node: BinarySearchTree) -> BinarySearchTree {
    guard let leftNode = node.left else {
      return node
    }
    leftNode.parent = node
    return findSuccessor(node: leftNode)
  }
}
extension BinarySearchTree {
  
  /// Inorder traversal of a given BST.
  public func inorder() {
    let node: BinarySearchTree? = self
    inorderTraversal(node: node)
  }
  
  private func inorderTraversal(node: BinarySearchTree?) {
    guard let node = node else {
      return
    }
    inorderTraversal(node: node.left)
    print(node.data)
    inorderTraversal(node: node.right)
  }
}
extension BinarySearchTree {
  
  /// Checks if given BT is a valid BST or not.
  public func isValid() -> Bool{
    return nodeIsValid(node: self, min: self.findMinimum(), max: self.findMaximum())
  }
  
  private func nodeIsValid(node: BinarySearchTree?, min: T, max: T) -> Bool{
    guard let node = node else {
      return true
    }
    if node.data < min || node.data > max {
      return false
    }
    return (nodeIsValid(node: node.left, min: min, max: node.data) && nodeIsValid(node: node.right, min: node.data, max: max))
  }
}
let binTree = BinarySearchTree<Int>(data: 3)
binTree.left = BinarySearchTree<Int>(data: 2)
binTree.left?.left = BinarySearchTree<Int>(data: 1)
binTree.right = BinarySearchTree<Int>(data: 7)
binTree.right?.left = BinarySearchTree<Int>(data: 6)
binTree.right?.right = BinarySearchTree<Int>(data: 8)
print(binTree.search(key: 5)?.data)                       // 5
//print(binTree.insert(key: 6))                             // 6
print(binTree.right?.right?.right?.data)                  // 6
print(binTree.hasRightChild())                            // true
print(binTree.hasLeftChild())                             // true
//let newRoot = binTree.deleteNode(node: binTree, key: 6)
binTree.inorder()
print(binTree.isValid())
binTree.findMaximum()                                     // 8
binTree.findMinimum()                                     // 1
 | 
	7e201bd214f5d9ece5006288750f2bc5 | 25.827434 | 126 | 0.597889 | false | false | false | false | 
| 
	superk589/CGSSGuide | 
	refs/heads/master | 
	DereGuide/Unit/Simulation/Controller/UnitAdvanceOptionsController.swift | 
	mit | 
	2 | 
	//
//  UnitAdvanceOptionsController.swift
//  DereGuide
//
//  Created by zzk on 2017/6/3.
//  Copyright © 2017 zzk. All rights reserved.
//
import UIKit
import SnapKit
class UnitAdvanceOptionsController: UITableViewController {
    var staticCells = [UnitAdvanceOptionsTableViewCell]()
    
    let option1 = SwitchOption()
    let option2 = StepperOption()
    let option3 = TextFieldOption()
    let option4 = TextFieldOption()
    let option5 = TextFieldOption()
    
    let option6 = TextFieldOption()
    
    let option7 = TextFieldOption()
    
    private func prepareStaticCells() {
        
        option1.switch.isOn = false
        option1.addTarget(self, action: #selector(option1ValueChanged(_:)), for: .valueChanged)
        let option1Label = option1.label
        option1Label.text = NSLocalizedString("Groove模式中,若队伍可发动生命恢复效果,起始状态就拥有两倍生命值。", comment: "")
        
        option2.addTarget(self, action: #selector(option2ValueChanged(_:)), for: .valueChanged)
        option2.setup(title: NSLocalizedString("小屋加成%", comment: ""), minValue: 0, maxValue: 10, currentValue: 0)
        
        option3.label.text = NSLocalizedString("GREAT占比%(不考虑专注技能只加成PERFECT的因素)", comment: "")
        option3.addTarget(self, action: #selector(option3TextFieldEndEditing(_:)), for: .editingDidEnd)
        option3.addTarget(self, action: #selector(option3TextFieldEndEditing(_:)), for: .editingDidEndOnExit)
        option4.label.text = NSLocalizedString("模拟次数", comment: "")
        option4.addTarget(self, action: #selector(option4TextFieldEndEditing(_:)), for: .editingDidEnd)
        option4.addTarget(self, action: #selector(option4TextFieldEndEditing(_:)), for: .editingDidEndOnExit)
        
        option5.label.text = NSLocalizedString("挂机模式中,手动打前 x 秒", comment: "")
        option5.addTarget(self, action: #selector(option5TextFieldEndEditing(_:)), for: .editingDidEnd)
        option5.addTarget(self, action: #selector(option5TextFieldEndEditing(_:)), for: .editingDidEndOnExit)
        option6.label.text = NSLocalizedString("挂机模式中,手动打前 x combo", comment: "")
        option6.addTarget(self, action: #selector(option6TextFieldEndEditing(_:)), for: .editingDidEnd)
        option6.addTarget(self, action: #selector(option6TextFieldEndEditing(_:)), for: .editingDidEndOnExit)
        
        option7.label.text = NSLocalizedString("挂机模式模拟次数", comment: "")
        option7.addTarget(self, action: #selector(option7TextFieldEndEditing(_:)), for: .editingDidEnd)
        option7.addTarget(self, action: #selector(option7TextFieldEndEditing(_:)), for: .editingDidEndOnExit)
        let cell1 = UnitAdvanceOptionsTableViewCell(optionStyle: .switch(option1))
        let cell2 = UnitAdvanceOptionsTableViewCell(optionStyle: .stepper(option2))
        let cell3 = UnitAdvanceOptionsTableViewCell(optionStyle: .textField(option3))
        let cell4 = UnitAdvanceOptionsTableViewCell(optionStyle: .textField(option4))
        let cell5 = UnitAdvanceOptionsTableViewCell(optionStyle: .textField(option5))
        let cell6 = UnitAdvanceOptionsTableViewCell(optionStyle: .textField(option6))
        let cell7 = UnitAdvanceOptionsTableViewCell(optionStyle: .textField(option7))
        staticCells.append(contentsOf: [cell1, cell2, cell3, cell4, cell7, cell5, cell6])
        
        setupWithUserDefaults()
    }
    
    private func prepareNaviBar() {
        let resetItem = UIBarButtonItem.init(title: NSLocalizedString("重置", comment: "导航栏按钮"), style: .plain, target: self, action: #selector(resetAction))
        navigationItem.rightBarButtonItem = resetItem
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = NSLocalizedString("高级选项", comment: "")
        prepareStaticCells()
        prepareNaviBar()
        
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 44
        tableView.cellLayoutMarginsFollowReadableWidth = true
        tableView.keyboardDismissMode = .onDrag
        tableView.tableFooterView = UIView()
        
        tableView.register(UnitAdvanceOptionsTableViewCell.self, forCellReuseIdentifier: UnitAdvanceOptionsTableViewCell.description())
    }
    
    @objc private func resetAction() {
        LiveSimulationAdvanceOptionsManager.default.reset()
        setupWithUserDefaults()
        tableView.reloadData()
    }
    
    @objc private func option1ValueChanged(_ sender: UISwitch) {
        LiveSimulationAdvanceOptionsManager.default.startGrooveWithDoubleHP = option1.switch.isOn
    }
    
    @objc private func option2ValueChanged(_ sender: ValueStepper) {
        LiveSimulationAdvanceOptionsManager.default.roomUpValue = Int(option2.stepper.value)
    }
    
    func setupWithUserDefaults() {
        option1.switch.isOn = LiveSimulationAdvanceOptionsManager.default.startGrooveWithDoubleHP
        option2.stepper.value = Double(LiveSimulationAdvanceOptionsManager.default.roomUpValue)
        option3.textField.text = String(LiveSimulationAdvanceOptionsManager.default.greatPercent)
        option4.textField.text = String(LiveSimulationAdvanceOptionsManager.default.simulationTimes)
        option5.textField.text = String(LiveSimulationAdvanceOptionsManager.default.afkModeStartSeconds)
        option6.textField.text = String(LiveSimulationAdvanceOptionsManager.default.afkModeStartCombo)
        option7.textField.text = String(LiveSimulationAdvanceOptionsManager.default.afkModeSimulationTimes)
    }
    
    private func validateOption3TextField() {
        if let value = Double(option3.textField.text ?? ""), value >= 0 && value <= 100 {
            option3.textField.text = String(Double(value))
        } else {
            option3.textField.text = "0.0"
        }
    }
    
    @objc private func option3TextFieldEndEditing(_ sender: UITextField) {
        validateOption3TextField()
        LiveSimulationAdvanceOptionsManager.default.greatPercent = Double(option3.textField.text!)!
    }
    
    private func validateOption4TextField() {
        if let value = Int(option4.textField.text ?? ""), value >= 1 && value <= Int.max {
            option4.textField.text = String(value)
        } else {
            option4.textField.text = "10000"
        }
    }
    
    @objc private func option4TextFieldEndEditing(_ sender: UITextField) {
        validateOption4TextField()
        LiveSimulationAdvanceOptionsManager.default.simulationTimes = Int(option4.textField.text!)!
    }
    
    private func validateOption5TextField() {
        if let value = Float(option5.textField.text ?? ""), value >= 0 && value <= Float.greatestFiniteMagnitude {
            option5.textField.text = String(value)
        } else {
            option5.textField.text = "0"
        }
    }
    
    @objc private func option5TextFieldEndEditing(_ sender: UITextField) {
        validateOption5TextField()
        LiveSimulationAdvanceOptionsManager.default.afkModeStartSeconds = Float(option5.textField.text!)!
    }
    
    private func validateOption6TextField() {
        if let value = Int(option6.textField.text ?? ""), value >= 0 && value <= Int.max {
            option6.textField.text = String(value)
        } else {
            option6.textField.text = "0"
        }
    }
    
    @objc private func option6TextFieldEndEditing(_ sender: UITextField) {
        validateOption6TextField()
        LiveSimulationAdvanceOptionsManager.default.afkModeStartCombo = Int(option6.textField.text!)!
    }
    
    private func validateOption7TextField() {
        if let value = Int(option7.textField.text ?? ""), value >= 1 && value <= Int.max {
            option7.textField.text = String(value)
        } else {
            option7.textField.text = "1000"
        }
    }
    
    @objc private func option7TextFieldEndEditing(_ sender: UITextField) {
        validateOption7TextField()
        LiveSimulationAdvanceOptionsManager.default.afkModeSimulationTimes = Int(option7.textField.text!)!
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return staticCells.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = staticCells[indexPath.row]
        return cell
    }
}
 | 
	d0e3ecc416b54bddcb7ef98641ba4ca8 | 42.502591 | 155 | 0.688304 | false | false | false | false | 
| 
	WeltN24/Carlos | 
	refs/heads/master | 
	Example/Example/PooledCacheSampleViewController.swift | 
	mit | 
	1 | 
	import Foundation
import UIKit
import Carlos
import Combine
final class PooledCacheSampleViewController: BaseCacheViewController {
  private var cache: PoolCache<BasicCache<URL, NSData>>!
  private var cancellables = Set<AnyCancellable>()
  override func fetchRequested() {
    super.fetchRequested()
    let timestamp = Date().timeIntervalSince1970
    eventsLogView.text = "\(eventsLogView.text!)Request timestamp: \(timestamp)\n"
    cache.get(URL(string: urlKeyField?.text ?? "")!)
      .receive(on: DispatchQueue.main)
      .sink(receiveCompletion: { _ in }, receiveValue: { _ in
        self.eventsLogView.text = "\(self.eventsLogView.text!)Request with timestamp \(timestamp) succeeded\n"
      }).store(in: &cancellables)
  }
  override func titleForScreen() -> String {
    "Pooled cache"
  }
  override func setupCache() {
    super.setupCache()
    cache = delayedNetworkCache().pooled()
  }
}
 | 
	49dfa431adaa26ff2a6445de628bc451 | 28.451613 | 110 | 0.706462 | false | false | false | false | 
| 
	juliangrosshauser/MotionActivityDisplay | 
	refs/heads/master | 
	MotionActivityDisplay/Source/Classes/View Controllers/HistoryTableViewController.swift | 
	mit | 
	1 | 
	//
//  HistoryTableViewController.swift
//  MotionActivityDisplay
//
//  Created by Julian Grosshauser on 19/06/15.
//  Copyright (c) 2015 Julian Grosshauser. All rights reserved.
//
import UIKit
import CoreMotion
//MARK: NSDate Operators
func > (lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.compare(rhs) == .OrderedDescending
}
class HistoryTableViewCell: UITableViewCell {
    //MARK: Initialization
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: .Subtitle, reuseIdentifier: reuseIdentifier)
    }
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}
class HistoryTableViewController: UITableViewController {
    //MARK: Properties
    private let motionActivityManager = CMMotionActivityManager()
    private let cellIdentifier = "historyCell"
    private var activities = [CMMotionActivity]() {
        didSet {
            tableView.reloadData()
        }
    }
    //MARK: Initialization
    init() {
        super.init(nibName: nil, bundle: nil)
        title = "History"
        let closeButton = UIBarButtonItem(title: "Close", style: .Plain, target: self, action: "close:")
        navigationItem.leftBarButtonItem = closeButton
    }
    required init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)
    }
    //MARK: UIViewController
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.registerClass(HistoryTableViewCell.self, forCellReuseIdentifier: cellIdentifier)
        if CMMotionActivityManager.isActivityAvailable() {
            let now = NSDate()
            let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
            let yesterday = calendar.dateByAddingUnit(.CalendarUnitDay, value: -1, toDate: now, options: .allZeros)
            let motionActivityQueryHandler: CMMotionActivityQueryHandler = { [unowned self] (activities: [AnyObject]!, error: NSError!) in
                if let activities = activities as? [CMMotionActivity] where error == nil {
                    self.activities = activities.sorted { $0.startDate > $1.startDate }
                }
            }
            motionActivityManager.queryActivityStartingFromDate(yesterday, toDate: now, toQueue: NSOperationQueue.mainQueue(), withHandler: motionActivityQueryHandler)
        }
    }
    //MARK: Button Actions
    @objc
    private func close(sender: AnyObject) {
        presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
    }
}
//MARK: UITableViewDataSource
extension HistoryTableViewController: UITableViewDataSource {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return activities.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! HistoryTableViewCell
        let activity = activities[indexPath.row]
        let motionTypes = join(", ", activity.motionTypes)
        cell.textLabel?.text = motionTypes
        cell.detailTextLabel?.text = "\(activity.printableDate), \(activity.printableConfidence)"
        return cell
    }
}
 | 
	908c28576139a44cbe66c1442505f649 | 29.398148 | 167 | 0.687786 | false | false | false | false | 
| 
	WhisperSystems/Signal-iOS | 
	refs/heads/master | 
	Signal/src/ViewControllers/MediaGallery/MediaPageViewController.swift | 
	gpl-3.0 | 
	1 | 
	//
//  Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import UIKit
import PromiseKit
// Objc wrapper for the MediaGalleryItem struct
@objc
public class GalleryItemBox: NSObject {
    public let value: MediaGalleryItem
    init(_ value: MediaGalleryItem) {
        self.value = value
    }
    @objc
    public var attachmentStream: TSAttachmentStream {
        return value.attachmentStream
    }
}
fileprivate extension MediaDetailViewController {
    var galleryItem: MediaGalleryItem {
        return self.galleryItemBox.value
    }
}
class MediaPageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, MediaDetailViewControllerDelegate, MediaGalleryDataSourceDelegate {
    private weak var mediaGalleryDataSource: MediaGalleryDataSource?
    private weak var mediaPageViewDelegate: MediaPageViewDelegate?
    var mediaInteractiveDismiss: MediaInteractiveDismiss!
    private var cachedPages: [MediaGalleryItem: MediaDetailViewController] = [:]
    private var initialPage: MediaDetailViewController!
    public var currentViewController: MediaDetailViewController {
        return viewControllers!.first as! MediaDetailViewController
    }
    public var currentItem: MediaGalleryItem! {
        return currentViewController.galleryItemBox.value
    }
    public func setCurrentItem(_ item: MediaGalleryItem, direction: UIPageViewController.NavigationDirection, animated isAnimated: Bool) {
        guard let galleryPage = self.buildGalleryPage(galleryItem: item) else {
            owsFailDebug("unexpectedly unable to build new gallery page")
            return
        }
        updateTitle(item: item)
        updateCaption(item: item)
        setViewControllers([galleryPage], direction: direction, animated: isAnimated)
        updateFooterBarButtonItems(isPlayingVideo: false)
        updateMediaRail()
    }
    private let showAllMediaButton: Bool
    private let sliderEnabled: Bool
    init(initialItem: MediaGalleryItem,
         mediaGalleryDataSource: MediaGalleryDataSource,
         mediaPageViewDelegate: MediaPageViewDelegate,
         options: MediaGalleryOption) {
        self.mediaGalleryDataSource = mediaGalleryDataSource
        self.mediaPageViewDelegate = mediaPageViewDelegate
        self.showAllMediaButton = options.contains(.showAllMediaButton)
        self.sliderEnabled = options.contains(.sliderEnabled)
        let kSpacingBetweenItems: CGFloat = 20
        let pageViewOptions: [UIPageViewController.OptionsKey: Any] = [.interPageSpacing: kSpacingBetweenItems]
        super.init(transitionStyle: .scroll,
                   navigationOrientation: .horizontal,
                   options: pageViewOptions)
        self.dataSource = self
        self.delegate = self
        guard let initialPage = self.buildGalleryPage(galleryItem: initialItem) else {
            owsFailDebug("unexpectedly unable to build initial gallery item")
            return
        }
        self.initialPage = initialPage
        self.setViewControllers([initialPage], direction: .forward, animated: false, completion: nil)
    }
    @available(*, unavailable, message: "Unimplemented")
    required init?(coder: NSCoder) {
        notImplemented()
    }
    deinit {
        Logger.debug("deinit")
    }
    // MARK: - Dependencies
    var databaseStorage: SDSDatabaseStorage {
        return SDSDatabaseStorage.shared
    }
    // MARK: - Subview
    // MARK: Bottom Bar
    var bottomContainer: UIView!
    var footerBar: UIToolbar!
    let captionContainerView: CaptionContainerView = CaptionContainerView()
    var galleryRailView: GalleryRailView = GalleryRailView()
    var pagerScrollView: UIScrollView!
    // MARK: UIViewController overrides
    // HACK: Though we don't have an input accessory view, the VC we are presented above (ConversationVC) does.
    // If the app is backgrounded and then foregrounded, when OWSWindowManager calls mainWindow.makeKeyAndVisible
    // the ConversationVC's inputAccessoryView will appear *above* us unless we'd previously become first responder.
    override public var canBecomeFirstResponder: Bool {
        return true
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Navigation
        // Note: using a custom leftBarButtonItem breaks the interactive pop gesture, but we don't want to be able
        // to swipe to go back in the pager view anyway, instead swiping back should show the next page.
        let backButton = OWSViewController.createOWSBackButton(withTarget: self, selector: #selector(didPressDismissButton))
        self.navigationItem.leftBarButtonItem = backButton
        mediaInteractiveDismiss = MediaInteractiveDismiss(mediaPageViewController: self)
        mediaInteractiveDismiss.addGestureRecognizer(to: view)
        self.navigationItem.titleView = portraitHeaderView
        if showAllMediaButton {
            self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: MediaStrings.allMedia, style: .plain, target: self, action: #selector(didPressAllMediaButton))
        }
        // Even though bars are opaque, we want content to be layed out behind them.
        // The bars might obscure part of the content, but they can easily be hidden by tapping
        // The alternative would be that content would shift when the navbars hide.
        self.extendedLayoutIncludesOpaqueBars = true
        self.automaticallyAdjustsScrollViewInsets = false
        // Get reference to paged content which lives in a scrollView created by the superclass
        // We show/hide this content during presentation
        for view in self.view.subviews {
            if let pagerScrollView = view as? UIScrollView {
                self.pagerScrollView = pagerScrollView
            }
        }
        // Hack to avoid "page" bouncing when not in gallery view.
        // e.g. when getting to media details via message details screen, there's only
        // one "Page" so the bounce doesn't make sense.
        pagerScrollView.isScrollEnabled = sliderEnabled
        pagerScrollViewContentOffsetObservation = pagerScrollView.observe(\.contentOffset, options: [.new]) { [weak self] _, change in
            guard let strongSelf = self else { return }
            strongSelf.pagerScrollView(strongSelf.pagerScrollView, contentOffsetDidChange: change)
        }
        // Views
        view.backgroundColor = Theme.darkThemeBackgroundColor
        captionContainerView.delegate = self
        updateCaptionContainerVisibility()
        galleryRailView.delegate = self
        galleryRailView.autoSetDimension(.height, toSize: 72)
        let footerBar = self.makeClearToolbar()
        self.footerBar = footerBar
        footerBar.tintColor = .white
        let bottomContainer = UIView()
        self.bottomContainer = bottomContainer
        bottomContainer.backgroundColor = UIColor.ows_black.withAlphaComponent(0.4)
        let bottomStack = UIStackView(arrangedSubviews: [captionContainerView, galleryRailView, footerBar])
        bottomStack.axis = .vertical
        bottomContainer.addSubview(bottomStack)
        bottomStack.autoPinEdgesToSuperviewEdges()
        self.view.addSubview(bottomContainer)
        bottomContainer.autoPinWidthToSuperview()
        bottomContainer.autoPinEdge(toSuperviewEdge: .bottom)
        footerBar.autoPin(toBottomLayoutGuideOf: self, withInset: 0)
        footerBar.autoSetDimension(.height, toSize: 44)
        updateTitle()
        updateCaption(item: currentItem)
        updateMediaRail()
        updateFooterBarButtonItems(isPlayingVideo: true)
        // Gestures
        let verticalSwipe = UISwipeGestureRecognizer(target: self, action: #selector(didSwipeView))
        verticalSwipe.direction = [.up, .down]
        view.addGestureRecognizer(verticalSwipe)
    }
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        let isLandscape = size.width > size.height
        self.navigationItem.titleView = isLandscape ? nil : self.portraitHeaderView
    }
    override func didReceiveMemoryWarning() {
        Logger.info("")
        super.didReceiveMemoryWarning()
        self.cachedPages = [:]
    }
    // MARK: KVO
    var pagerScrollViewContentOffsetObservation: NSKeyValueObservation?
    func pagerScrollView(_ pagerScrollView: UIScrollView, contentOffsetDidChange change: NSKeyValueObservedChange<CGPoint>) {
        guard let newValue = change.newValue else {
            owsFailDebug("newValue was unexpectedly nil")
            return
        }
        let width = pagerScrollView.frame.size.width
        guard width > 0 else {
            return
        }
        let ratioComplete = abs((newValue.x - width) / width)
        captionContainerView.updatePagerTransition(ratioComplete: ratioComplete)
    }
    // MARK: View Helpers
    public func willBePresentedAgain() {
        updateFooterBarButtonItems(isPlayingVideo: false)
    }
    public func wasPresented() {
        let currentViewController = self.currentViewController
        if currentViewController.galleryItem.isVideo {
            currentViewController.playVideo()
        }
    }
    private func makeClearToolbar() -> UIToolbar {
        let toolbar = UIToolbar()
        toolbar.backgroundColor = UIColor.clear
        // Making a toolbar transparent requires setting an empty uiimage
        toolbar.setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default)
        // hide 1px top-border
        toolbar.clipsToBounds = true
        return toolbar
    }
    private var shouldHideToolbars: Bool = false {
        didSet {
            if (oldValue == shouldHideToolbars) {
                return
            }
            // Hiding the status bar affects the positioning of the navbar. We don't want to show that in an animation, it's
            // better to just have everythign "flit" in/out.
            UIApplication.shared.setStatusBarHidden(shouldHideToolbars, with: .none)
            self.navigationController?.setNavigationBarHidden(shouldHideToolbars, animated: false)
            UIView.animate(withDuration: 0.1) {
                self.currentViewController.setShouldHideToolbars(self.shouldHideToolbars)
                self.bottomContainer.isHidden = self.shouldHideToolbars
            }
        }
    }
    // MARK: Bar Buttons
    lazy var shareBarButton: UIBarButtonItem = {
        let shareBarButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(didPressShare))
        shareBarButton.tintColor = Theme.darkThemePrimaryColor
        return shareBarButton
    }()
    lazy var deleteBarButton: UIBarButtonItem = {
        let deleteBarButton = UIBarButtonItem(barButtonSystemItem: .trash,
                                              target: self,
                                              action: #selector(didPressDelete))
        deleteBarButton.tintColor = Theme.darkThemePrimaryColor
        return deleteBarButton
    }()
    func buildFlexibleSpace() -> UIBarButtonItem {
        return UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    }
    lazy var videoPlayBarButton: UIBarButtonItem = {
        let videoPlayBarButton = UIBarButtonItem(barButtonSystemItem: .play, target: self, action: #selector(didPressPlayBarButton))
        videoPlayBarButton.tintColor = Theme.darkThemePrimaryColor
        return videoPlayBarButton
    }()
    lazy var videoPauseBarButton: UIBarButtonItem = {
        let videoPauseBarButton = UIBarButtonItem(barButtonSystemItem: .pause, target: self, action:
            #selector(didPressPauseBarButton))
        videoPauseBarButton.tintColor = Theme.darkThemePrimaryColor
        return videoPauseBarButton
    }()
    private func updateFooterBarButtonItems(isPlayingVideo: Bool) {
        // TODO do we still need this? seems like a vestige
        // from when media detail view was used for attachment approval
        if self.footerBar == nil {
            owsFailDebug("No footer bar visible.")
            return
        }
        var toolbarItems: [UIBarButtonItem] = [
            shareBarButton,
            buildFlexibleSpace()
        ]
        if (self.currentItem.isVideo) {
            toolbarItems += [
                isPlayingVideo ? self.videoPauseBarButton : self.videoPlayBarButton,
                buildFlexibleSpace()
            ]
        }
        toolbarItems.append(deleteBarButton)
        self.footerBar.setItems(toolbarItems, animated: false)
    }
    func updateMediaRail() {
        guard let currentItem = self.currentItem else {
            owsFailDebug("currentItem was unexpectedly nil")
            return
        }
        galleryRailView.configureCellViews(itemProvider: currentItem.album,
                                           focusedItem: currentItem,
                                           cellViewBuilder: { _ in return GalleryRailCellView() })
    }
    // MARK: Actions
    @objc
    public func didPressAllMediaButton(sender: Any) {
        Logger.debug("")
        guard let mediaPageViewDelegate = self.mediaPageViewDelegate else {
            owsFailDebug("mediaGalleryDataSource was unexpectedly nil")
            return
        }
        mediaPageViewDelegate.mediaPageViewControllerDidTapAllMedia(self)
    }
    @objc
    public func didSwipeView(sender: Any) {
        Logger.debug("")
        self.dismissSelf(animated: true)
    }
    @objc
    public func didPressDismissButton(_ sender: Any) {
        dismissSelf(animated: true)
    }
    @objc
    public func didPressShare(_ sender: Any) {
        guard let currentViewController = self.viewControllers?[0] as? MediaDetailViewController else {
            owsFailDebug("currentViewController was unexpectedly nil")
            return
        }
        let attachmentStream = currentViewController.galleryItem.attachmentStream
        AttachmentSharing.showShareUI(forAttachment: attachmentStream)
    }
    @objc
    public func didPressDelete(_ sender: Any) {
        guard let currentViewController = self.viewControllers?[0] as? MediaDetailViewController else {
            owsFailDebug("currentViewController was unexpectedly nil")
            return
        }
        guard let mediaGalleryDataSource = self.mediaGalleryDataSource else {
            owsFailDebug("mediaGalleryDataSource was unexpectedly nil")
            return
        }
        let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let deleteAction = UIAlertAction(title: NSLocalizedString("TXT_DELETE_TITLE", comment: ""),
                                         style: .destructive) { _ in
                                            let deletedItem = currentViewController.galleryItem
                                            mediaGalleryDataSource.delete(items: [deletedItem], initiatedBy: self)
        }
        actionSheet.addAction(OWSAlerts.cancelAction)
        actionSheet.addAction(deleteAction)
        self.presentAlert(actionSheet)
    }
    // MARK: MediaGalleryDataSourceDelegate
    func mediaGalleryDataSource(_ mediaGalleryDataSource: MediaGalleryDataSource, willDelete items: [MediaGalleryItem], initiatedBy: AnyObject) {
        Logger.debug("")
        guard let currentItem = self.currentItem else {
            owsFailDebug("currentItem was unexpectedly nil")
            return
        }
        guard items.contains(currentItem) else {
            Logger.debug("irrelevant item")
            return
        }
        // If we setCurrentItem with (animated: true) while this VC is in the background, then
        // the next/previous cache isn't expired, and we're able to swipe back to the just-deleted vc.
        // So to get the correct behavior, we should only animate these transitions when this
        // vc is in the foreground
        let isAnimated = initiatedBy === self
        if !self.sliderEnabled {
            // In message details, which doesn't use the slider, so don't swap pages.
        } else if let nextItem = mediaGalleryDataSource.galleryItem(after: currentItem) {
            self.setCurrentItem(nextItem, direction: .forward, animated: isAnimated)
        } else if let previousItem = mediaGalleryDataSource.galleryItem(before: currentItem) {
            self.setCurrentItem(previousItem, direction: .reverse, animated: isAnimated)
        } else {
            // else we deleted the last piece of media, return to the conversation view
            self.dismissSelf(animated: true)
        }
    }
    func mediaGalleryDataSource(_ mediaGalleryDataSource: MediaGalleryDataSource, deletedSections: IndexSet, deletedItems: [IndexPath]) {
        // no-op
    }
    @objc
    public func didPressPlayBarButton(_ sender: Any) {
        guard let currentViewController = self.viewControllers?[0] as? MediaDetailViewController else {
            owsFailDebug("currentViewController was unexpectedly nil")
            return
        }
        currentViewController.didPressPlayBarButton(sender)
    }
    @objc
    public func didPressPauseBarButton(_ sender: Any) {
        guard let currentViewController = self.viewControllers?[0] as? MediaDetailViewController else {
            owsFailDebug("currentViewController was unexpectedly nil")
            return
        }
        currentViewController.didPressPauseBarButton(sender)
    }
    // MARK: UIPageViewControllerDelegate
    var pendingViewController: MediaDetailViewController?
    public func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
        Logger.debug("")
        assert(pendingViewControllers.count == 1)
        pendingViewControllers.forEach { viewController in
            guard let pendingViewController = viewController as? MediaDetailViewController else {
                owsFailDebug("unexpected mediaDetailViewController: \(viewController)")
                return
            }
            self.pendingViewController = pendingViewController
            if let pendingCaptionText = pendingViewController.galleryItem.captionForDisplay, pendingCaptionText.count > 0 {
                self.captionContainerView.pendingText = pendingCaptionText
            } else {
                self.captionContainerView.pendingText = nil
            }
            // Ensure upcoming page respects current toolbar status
            pendingViewController.setShouldHideToolbars(self.shouldHideToolbars)
        }
    }
    public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted: Bool) {
        Logger.debug("")
        assert(previousViewControllers.count == 1)
        previousViewControllers.forEach { viewController in
            guard let previousPage = viewController as? MediaDetailViewController else {
                owsFailDebug("unexpected mediaDetailViewController: \(viewController)")
                return
            }
            // Do any cleanup for the no-longer visible view controller
            if transitionCompleted {
                pendingViewController = nil
                // This can happen when trying to page past the last (or first) view controller
                // In that case, we don't want to change the captionView.
                if (previousPage != currentViewController) {
                    captionContainerView.completePagerTransition()
                }
                updateTitle()
                updateMediaRail()
                previousPage.zoomOut(animated: false)
                previousPage.stopAnyVideo()
                updateFooterBarButtonItems(isPlayingVideo: false)
            } else {
                captionContainerView.pendingText = nil
            }
        }
    }
    // MARK: UIPageViewControllerDataSource
    public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        Logger.debug("")
        guard let previousDetailViewController = viewController as? MediaDetailViewController else {
            owsFailDebug("unexpected viewController: \(viewController)")
            return nil
        }
        guard let mediaGalleryDataSource = self.mediaGalleryDataSource else {
            owsFailDebug("mediaGalleryDataSource was unexpectedly nil")
            return nil
        }
        let previousItem = previousDetailViewController.galleryItem
        guard let nextItem: MediaGalleryItem = mediaGalleryDataSource.galleryItem(before: previousItem) else {
            return nil
        }
        guard let nextPage: MediaDetailViewController = buildGalleryPage(galleryItem: nextItem) else {
            return nil
        }
        return nextPage
    }
    public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        Logger.debug("")
        guard let previousDetailViewController = viewController as? MediaDetailViewController else {
            owsFailDebug("unexpected viewController: \(viewController)")
            return nil
        }
        guard let mediaGalleryDataSource = self.mediaGalleryDataSource else {
            owsFailDebug("mediaGalleryDataSource was unexpectedly nil")
            return nil
        }
        let previousItem = previousDetailViewController.galleryItem
        guard let nextItem = mediaGalleryDataSource.galleryItem(after: previousItem) else {
            // no more pages
            return nil
        }
        guard let nextPage: MediaDetailViewController = buildGalleryPage(galleryItem: nextItem) else {
            return nil
        }
        return nextPage
    }
    private func buildGalleryPage(galleryItem: MediaGalleryItem) -> MediaDetailViewController? {
        if let cachedPage = cachedPages[galleryItem] {
            Logger.debug("cache hit.")
            return cachedPage
        }
        Logger.debug("cache miss.")
        var fetchedItem: ConversationViewItem?
        databaseStorage.uiRead { transaction in
            let message = galleryItem.message
            let thread = message.thread(transaction: transaction)
            let conversationStyle = ConversationStyle(thread: thread)
            fetchedItem = ConversationInteractionViewItem(interaction: message,
                                                          thread: thread,
                                                          transaction: transaction,
                                                          conversationStyle: conversationStyle)
        }
        guard let viewItem = fetchedItem else {
            owsFailDebug("viewItem was unexpectedly nil")
            return nil
        }
        let viewController = MediaDetailViewController(galleryItemBox: GalleryItemBox(galleryItem), viewItem: viewItem)
        viewController.delegate = self
        cachedPages[galleryItem] = viewController
        return viewController
    }
    public func dismissSelf(animated isAnimated: Bool, completion: (() -> Void)? = nil) {
        // Swapping mediaView for presentationView will be perceptible if we're not zoomed out all the way.
        currentViewController.zoomOut(animated: true)
        currentViewController.stopAnyVideo()
        UIApplication.shared.setStatusBarHidden(false, with: .none)
        self.navigationController?.setNavigationBarHidden(false, animated: false)
        guard let mediaPageViewDelegate = self.mediaPageViewDelegate else {
            owsFailDebug("mediaGalleryDataSource was unexpectedly nil")
            self.presentingViewController?.dismiss(animated: true)
            return
        }
        mediaPageViewDelegate.mediaPageViewControllerRequestedDismiss(self,
                                                                      animated: isAnimated,
                                                                      completion: completion)
    }
    // MARK: MediaDetailViewControllerDelegate
    @objc
    public func mediaDetailViewControllerDidTapMedia(_ mediaDetailViewController: MediaDetailViewController) {
        Logger.debug("")
        self.shouldHideToolbars = !self.shouldHideToolbars
    }
    public func mediaDetailViewController(_ mediaDetailViewController: MediaDetailViewController, requestDelete attachment: TSAttachment) {
        guard let mediaGalleryDataSource = self.mediaGalleryDataSource else {
            owsFailDebug("mediaGalleryDataSource was unexpectedly nil")
            self.presentingViewController?.dismiss(animated: true)
            return
        }
        guard let galleryItem = self.mediaGalleryDataSource?.galleryItems.first(where: { $0.attachmentStream == attachment }) else {
            owsFailDebug("galleryItem was unexpectedly nil")
            self.presentingViewController?.dismiss(animated: true)
            return
        }
        dismissSelf(animated: true) {
            mediaGalleryDataSource.delete(items: [galleryItem], initiatedBy: self)
        }
    }
    public func mediaDetailViewController(_ mediaDetailViewController: MediaDetailViewController, isPlayingVideo: Bool) {
        guard mediaDetailViewController == currentViewController else {
            Logger.verbose("ignoring stale delegate.")
            return
        }
        self.shouldHideToolbars = isPlayingVideo
        self.updateFooterBarButtonItems(isPlayingVideo: isPlayingVideo)
    }
    // MARK: Dynamic Header
    private var contactsManager: OWSContactsManager {
        return Environment.shared.contactsManager
    }
    private func senderName(message: TSMessage) -> String {
        switch message {
        case let incomingMessage as TSIncomingMessage:
            return self.contactsManager.displayName(for: incomingMessage.authorAddress)
        case is TSOutgoingMessage:
            return NSLocalizedString("MEDIA_GALLERY_SENDER_NAME_YOU", comment: "Short sender label for media sent by you")
        default:
            owsFailDebug("Unknown message type: \(type(of: message))")
            return ""
        }
    }
    private lazy var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .short
        formatter.timeStyle = .short
        return formatter
    }()
    lazy private var portraitHeaderNameLabel: UILabel = {
        let label = UILabel()
        label.textColor = Theme.darkThemePrimaryColor
        label.font = UIFont.ows_regularFont(withSize: 17)
        label.textAlignment = .center
        label.adjustsFontSizeToFitWidth = true
        label.minimumScaleFactor = 0.8
        return label
    }()
    lazy private var portraitHeaderDateLabel: UILabel = {
        let label = UILabel()
        label.textColor = Theme.darkThemePrimaryColor
        label.font = UIFont.ows_regularFont(withSize: 12)
        label.textAlignment = .center
        label.adjustsFontSizeToFitWidth = true
        label.minimumScaleFactor = 0.8
        return label
    }()
    private lazy var portraitHeaderView: UIView = {
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.alignment = .center
        stackView.spacing = 0
        stackView.distribution = .fillProportionally
        stackView.addArrangedSubview(portraitHeaderNameLabel)
        stackView.addArrangedSubview(portraitHeaderDateLabel)
        let containerView = UIView()
        containerView.layoutMargins = UIEdgeInsets(top: 2, left: 8, bottom: 4, right: 8)
        containerView.addSubview(stackView)
        stackView.autoPinEdge(toSuperviewMargin: .top, relation: .greaterThanOrEqual)
        stackView.autoPinEdge(toSuperviewMargin: .trailing, relation: .greaterThanOrEqual)
        stackView.autoPinEdge(toSuperviewMargin: .bottom, relation: .greaterThanOrEqual)
        stackView.autoPinEdge(toSuperviewMargin: .leading, relation: .greaterThanOrEqual)
        stackView.setContentHuggingHigh()
        stackView.autoCenterInSuperview()
        return containerView
    }()
    private func updateTitle() {
        guard let currentItem = self.currentItem else {
            owsFailDebug("currentItem was unexpectedly nil")
            return
        }
        updateTitle(item: currentItem)
    }
    private func updateCaption(item: MediaGalleryItem) {
        captionContainerView.currentText = item.captionForDisplay
    }
    private func updateTitle(item: MediaGalleryItem) {
        let name = senderName(message: item.message)
        portraitHeaderNameLabel.text = name
        // use sent date
        let date = Date(timeIntervalSince1970: Double(item.message.timestamp) / 1000)
        let formattedDate = dateFormatter.string(from: date)
        portraitHeaderDateLabel.text = formattedDate
        let landscapeHeaderFormat = NSLocalizedString("MEDIA_GALLERY_LANDSCAPE_TITLE_FORMAT", comment: "embeds {{sender name}} and {{sent datetime}}, e.g. 'Sarah on 10/30/18, 3:29'")
        let landscapeHeaderText = String(format: landscapeHeaderFormat, name, formattedDate)
        self.title = landscapeHeaderText
        self.navigationItem.title = landscapeHeaderText
        if #available(iOS 11, *) {
            // Do nothing, on iOS11+, autolayout grows the stack view as necessary.
        } else {
            // Size the titleView to be large enough to fit the widest label,
            // but no larger. If we go for a "full width" label, our title view
            // will not be centered (since the left and right bar buttons have different widths)            
            portraitHeaderNameLabel.sizeToFit()
            portraitHeaderDateLabel.sizeToFit()
            let width = max(portraitHeaderNameLabel.frame.width, portraitHeaderDateLabel.frame.width)
            let headerFrame: CGRect = CGRect(x: 0, y: 0, width: width, height: 44)
            portraitHeaderView.frame = headerFrame
        }
    }
}
extension MediaGalleryItem: GalleryRailItem {
    public func buildRailItemView() -> UIView {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.image = getRailImage()
        return imageView
    }
    public func getRailImage() -> UIImage? {
        return self.thumbnailImageSync()
    }
}
extension MediaGalleryAlbum: GalleryRailItemProvider {
    var railItems: [GalleryRailItem] {
        return self.items
    }
}
extension MediaPageViewController: GalleryRailViewDelegate {
    func galleryRailView(_ galleryRailView: GalleryRailView, didTapItem imageRailItem: GalleryRailItem) {
        guard let targetItem = imageRailItem as? MediaGalleryItem else {
            owsFailDebug("unexpected imageRailItem: \(imageRailItem)")
            return
        }
        let direction: UIPageViewController.NavigationDirection
        direction = currentItem.albumIndex < targetItem.albumIndex ? .forward : .reverse
        self.setCurrentItem(targetItem, direction: direction, animated: true)
    }
}
extension MediaPageViewController: CaptionContainerViewDelegate {
    func captionContainerViewDidUpdateText(_ captionContainerView: CaptionContainerView) {
        updateCaptionContainerVisibility()
    }
    // MARK: Helpers
    func updateCaptionContainerVisibility() {
        if let currentText = captionContainerView.currentText, currentText.count > 0 {
            captionContainerView.isHidden = false
            return
        }
        if let pendingText = captionContainerView.pendingText, pendingText.count > 0 {
            captionContainerView.isHidden = false
            return
        }
        captionContainerView.isHidden = true
    }
}
extension MediaPageViewController: MediaPresentationContextProvider {
    func mediaPresentationContext(galleryItem: MediaGalleryItem, in coordinateSpace: UICoordinateSpace) -> MediaPresentationContext? {
        let mediaView = currentViewController.mediaView
        guard let mediaSuperview = mediaView.superview else {
            owsFailDebug("superview was unexpectedly nil")
            return nil
        }
        let presentationFrame = coordinateSpace.convert(mediaView.frame, from: mediaSuperview)
        // TODO better match the corner radius
        return MediaPresentationContext(mediaView: mediaView, presentationFrame: presentationFrame, cornerRadius: 0)
    }
    func snapshotOverlayView(in coordinateSpace: UICoordinateSpace) -> (UIView, CGRect)? {
        view.layoutIfNeeded()
        guard let snapshot = bottomContainer.snapshotView(afterScreenUpdates: true) else {
            owsFailDebug("snapshot was unexpectedly nil")
            return nil
        }
        let presentationFrame = coordinateSpace.convert(bottomContainer.frame,
                                                        from: bottomContainer.superview!)
        return (snapshot, presentationFrame)
    }
}
 | 
	1c515b21697eba4702d1a4d54b8c32a8 | 37.292824 | 187 | 0.670848 | false | false | false | false | 
| 
	laurennicoleroth/Tindergram | 
	refs/heads/master | 
	Tindergram/SwipeView.swift | 
	mit | 
	2 | 
	//
//  SwipeView.swift
//  Tindergram
//
//  Created by thomas on 3/31/15.
//  Copyright (c) 2015 thomas. All rights reserved.
//
import Foundation
import UIKit
protocol SwipeViewDelegate: class {
  func swipedLeft()
  func swipedRight()
}
class SwipeView: UIView {
  
  enum Direction {
    case None
    case Right
    case Left
  }
  
  weak var delegate: SwipeViewDelegate?
  
  let overlay: UIImageView = UIImageView()
  var direction: Direction?
  
  var innerView: UIView? {
    didSet {
      if let v = innerView {
        insertSubview(v, belowSubview: overlay)
        v.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
      }
    }
  }
  
  private var originalPoint: CGPoint?
  
  required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    initialize()
  }
  
  override init(frame: CGRect) {
    super.init(frame: frame)
    initialize()
  }
  
  private func initialize() {
    backgroundColor = UIColor.clearColor()
    
    addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "dragged:"))
    
    overlay.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
    addSubview(overlay)
  }
  
  func dragged(gestureRecognizer: UIPanGestureRecognizer) {
    let distance = gestureRecognizer.translationInView(self)
    
    switch gestureRecognizer.state {
    
    case .Began:
      originalPoint = center
    
    case .Changed:
      let rotationPercentage = min(distance.x/(self.superview!.frame.width/2), 1)
      let rotationAngle = (CGFloat(2*M_PI/16)*rotationPercentage)
      
      transform = CGAffineTransformMakeRotation(rotationAngle)
      center = CGPointMake(originalPoint!.x + distance.x, originalPoint!.y + distance.y)
      updateOverlay(distance.x)
    
    case .Ended:
      if abs(distance.x) < frame.width/4 {
        resetViewPositionAndTransformations()
      } else {
        swipeDirection(distance.x > 0 ? .Right : .Left) // ternary operator - if true, first condition, otherwise second
      }
    
    default:
      println("Default triggered for GestureRecognizer")
      break
    }
  }
  
  func swipeDirection(s: Direction) {
    if s == .None {
      return
    }
    var parentWidth = superview!.frame.size.width
    if s == .Left {
      parentWidth *= -1
    }
    
    UIView.animateWithDuration(0.2, animations: {
      self.center.x = self.frame.origin.x + parentWidth
      }, completion: {
        success in
        if let d = self.delegate {
          s == .Right ? d.swipedRight() : d.swipedLeft() // protocol functions
        }
    })
  }
  
  private func updateOverlay(distance: CGFloat) {
    var newDirection: Direction
    newDirection = distance < 0 ? .Left : .Right
    
    if newDirection != direction {
      direction = newDirection
      overlay.image = direction == .Right ? UIImage(named: "yeah-stamp") : UIImage(named: "nah-stamp")
    }
    overlay.alpha = abs(distance) / (superview!.frame.width / 2)
  }
  
  private func resetViewPositionAndTransformations() {
    UIView.animateWithDuration(0.2, animations: { () -> Void in
      self.center = self.originalPoint!
      self.transform = CGAffineTransformMakeRotation(0)
      
      self.overlay.alpha = 0
    })
  }
  
}
 | 
	62ed0cce63681e29daefe32a494f46e5 | 24.226563 | 120 | 0.638897 | false | false | false | false | 
| 
	t-ballz/coopclocker-osx | 
	refs/heads/master | 
	CoopClocker-osx/Source/Extensions.swift | 
	bsd-3-clause | 
	1 | 
	//
//  Extensions.swift
//  StatusBarPomodoro
//
//  Created by TaileS Ballz on 23/10/15.
//  Copyright (c) 2015 ballz. All rights reserved.
//
import Cocoa
import RxSwift
import RxCocoa
extension NSView
{
    
    func setBorder(width: CGFloat = 1.0, color: NSColor = NSColor.blackColor())
    {
        self.layer?.borderWidth = width
        self.layer?.borderColor = color.CGColor
    }
    
    func viewWithTagAs<T:NSView>(tag: Int) -> T? {
        return self.viewWithTag(tag) as? T
    }
    
}
extension NSDate
{
    func minutes_seconds() -> (Int, Int)
    {
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(NSCalendarUnit.CalendarUnitMinute | .CalendarUnitSecond, fromDate: self)
        return (components.minute, components.second)
    }
}
// RX helpers
extension Observable
{
    class func rx_return<T>(value: T) -> Observable<T>
    {
        return create { sink in
            sendNext(sink, value)
            sendCompleted(sink)
            
            return NopDisposable.instance
        }
    }
}
infix operator <~ {}
func <~<T>(variable: Variable<T>, value: T)
{
    variable.next(value)
}
func <~<T>(variable: Variable<T>, signal: Observable<T>) -> Disposable
{
    return signal.subscribe(variable)
}
infix operator ~> {}
func ~><T>(signal: Observable<T>, nextBlock:(T) -> ())
{
    signal >- subscribeNext(nextBlock)
}
infix operator *~> {}
func *~><T>(signal: Observable<T>, completedBlock: () -> ())
{
    signal >- subscribeCompleted(completedBlock)
}
extension NSButton
{
    func bindToHandler<T>(handler: (NSView) -> Observable<T>) -> Observable<Observable<T>>
    {
        return self.rx_tap >- map { handler(self) }
    }
}
 | 
	883f3497b7d71c62c5e64c715241d2e2 | 19.97561 | 117 | 0.623256 | false | false | false | false | 
| 
	himadrisj/SiriPay | 
	refs/heads/dev | 
	Client/SiriPay/SiriPay/AppDelegate.swift | 
	mit | 
	1 | 
	//
//  AppDelegate.swift
//  SiriPay
//
//  Created by Himadri Sekhar Jyoti on 10/09/16.
//  Copyright
//
import UIKit
import Contacts
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    let contactStore = CNContactStore()
    var backgroundTask: UIBackgroundTaskIdentifier?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        SPPaymentController.sharedInstance.initializeSDK()
        
        if UserDefaults.standard.bool(forKey: kDefaults_SignedIn) {
            let navController = self.window?.rootViewController as! UINavigationController
            navController.topViewController?.performSegue(withIdentifier: "SiriPaySegueIdentifier", sender: nil)
        }
        
        return true
    }
    
    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }
    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        self.startBackgroundTask()
    }
    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        self.endBackgroundTask()
    }
    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }
    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    class func getAppDelegate() -> AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }
    
    private func startBackgroundTask() {
        self.backgroundTask = UIApplication.shared.beginBackgroundTask {
            [unowned self] in
            self.endBackgroundTask()
        }
        
        assert(self.backgroundTask != UIBackgroundTaskInvalid, "Appdelegate startBackgroundTask invalid task state")
    }
    
    private func endBackgroundTask() {
        if let bgTask = self.backgroundTask {
            if(bgTask != UIBackgroundTaskInvalid) {
                UIApplication.shared.endBackgroundTask(bgTask)
                self.backgroundTask = UIBackgroundTaskInvalid
            }
        }
    }
    
    
}
extension AppDelegate {
    
    func requestForAccess(_ completionHandler: @escaping (_ accessGranted: Bool) -> Void) {
        let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
        
        switch authorizationStatus {
        case .authorized:
            completionHandler(true)
            
        case .denied, .notDetermined:
            self.contactStore.requestAccess(for: CNEntityType.contacts, completionHandler: { (access, accessError) -> Void in
                if access {
                    completionHandler(access)
                }
                else {
                    if authorizationStatus == CNAuthorizationStatus.denied {
                        DispatchQueue.main.async(execute: { () -> Void in
                            let message = "\(accessError!.localizedDescription)\n\nPlease allow the app to access your contacts through the Settings."
                            self.showMessage(message)
                        })
                    }
                }
            })
            
        default:
            completionHandler(false)
        }
    }
    
    func showMessage(_ message: String) {
        let alertController = UIAlertController(title: "SiriPay", message: message, preferredStyle: UIAlertControllerStyle.alert)
        
        let dismissAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (action) -> Void in
        }
        
        alertController.addAction(dismissAction)
        
        let pushedViewControllers = (self.window?.rootViewController as! UINavigationController).viewControllers
        let presentedViewController = pushedViewControllers[pushedViewControllers.count - 1]
        
        presentedViewController.present(alertController, animated: true, completion: nil)
    }
    
    
    
    
}
 | 
	cd7c79211ac9e7f3a29f77e1460ec35b | 39.710938 | 285 | 0.669545 | false | false | false | false | 
| 
	festrs/DesignSwift | 
	refs/heads/master | 
	ToDoAssignment3/ToDoAssignment3/MyTableViewCell.swift | 
	mit | 
	1 | 
	//
//  MyTableViewCell.swift
//  ToDoAssignment3
//
//  Created by Felipe Dias Pereira on 2016-04-08.
//  Copyright © 2016 Felipe Dias Pereira. All rights reserved.
//
import UIKit
class MyTableViewCell: UITableViewCell {
    var myLocalToDoEntity:ToDoEntity?
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var titleLabel: UILabel!
    
    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
    }
    
    func setInternalFields(toDoEntity: ToDoEntity){
        
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = .ShortStyle
        dateFormatter.timeStyle = .ShortStyle
        self.myLocalToDoEntity = toDoEntity
        self.titleLabel.text = toDoEntity.toDoTitle
        if let date = toDoEntity.toDoDueDate{
            self.dateLabel.text = dateFormatter.stringFromDate(date)
        }
    }
}
 | 
	9337849d687d9fa4a58b69b896c20dd4 | 25.775 | 68 | 0.672269 | false | false | false | false | 
| 
	barteljan/VISPER | 
	refs/heads/master | 
	VISPER-Objc/Classes/PresenterProviderObjc.swift | 
	mit | 
	1 | 
	//
//  PresenterProviderObjc.swift
//  VISPER-Wireframe-Objc
//
//  Created by bartel on 12.12.17.
//
import Foundation
import VISPER_Core
@objc public protocol PresenterProviderObjcType {
    
    func isResponsible(routeResult: RouteResultObjc,controller: UIViewController) -> Bool
    func makePresenters(routeResult: RouteResultObjc,controller: UIViewController) throws -> [PresenterObjc]
    
}
@objc open class PresenterProviderObjc : NSObject,PresenterProvider,PresenterProviderObjcType{
    
    open var presenterProvider : PresenterProvider?
    open var presenterProviderObjc : PresenterProviderObjcType?
    
    public init(presenterProvider : PresenterProvider) {
        self.presenterProvider = presenterProvider
        self.presenterProviderObjc = nil
        super.init()
    }
    
    @objc public init(presenterProvider : PresenterProviderObjcType) {
        
        if let presenterProvider = presenterProvider as? PresenterProviderObjc {
            self.presenterProvider = presenterProvider.presenterProvider
            self.presenterProviderObjc = nil
        } else {
            self.presenterProviderObjc = presenterProvider
            self.presenterProvider = nil
        }
        
        super.init()
    }
    
    
    open func isResponsible( routeResult: RouteResult, controller: UIViewController) -> Bool {
        
        guard presenterProvider != nil || presenterProviderObjc != nil else {
            fatalError("there should be a presenterProvider or a presenterProviderObjc")
        }
        
        if let presenterProvider = self.presenterProvider {
            return presenterProvider.isResponsible(routeResult: routeResult, controller: controller)
        } else if let presenterProviderObjc = self.presenterProviderObjc {
            let routeResultObjC = ObjcWrapper.wrapperProvider.routeResult(routeResult: routeResult)
            return presenterProviderObjc.isResponsible(routeResult: routeResultObjC, controller: controller)
        }
        
        return false
    }
    
    public func isResponsible(routeResult: RouteResultObjc, controller: UIViewController) -> Bool {
    
        guard presenterProvider != nil || presenterProviderObjc != nil else {
            fatalError("there should be a presenterProvider or a presenterProviderObjc")
        }
    
        if let presenterProvider = self.presenterProvider {
            return presenterProvider.isResponsible(routeResult: routeResult,controller: controller)
        } else if let presenterProviderObjc = self.presenterProviderObjc {
            return presenterProviderObjc.isResponsible(routeResult: routeResult,controller: controller)
        }
        
        return false
    }
    
    open func makePresenters( routeResult: RouteResult, controller: UIViewController) throws -> [Presenter]{
        
        guard presenterProvider != nil || presenterProviderObjc != nil else {
            fatalError("there should be a presenterProvider or a presenterProviderObjc")
        }
        
        if let presenterProvider = self.presenterProvider {
            return try presenterProvider.makePresenters(routeResult:routeResult,controller:controller)
        } else if let presenterProviderObjc = self.presenterProviderObjc {
            let routeResultObjC = ObjcWrapper.wrapperProvider.routeResult(routeResult: routeResult)
            return try presenterProviderObjc.makePresenters(routeResult: routeResultObjC, controller: controller)
        }
        
        return [Presenter]()
    }
    
    open func makePresenters(routeResult: RouteResultObjc,controller: UIViewController) throws -> [PresenterObjc] {
        
        guard presenterProvider != nil || presenterProviderObjc != nil else {
            fatalError("there should be a presenterProvider or a presenterProviderObjc")
        }
        
        if let presenterProvider = self.presenterProvider {
            return try presenterProvider.makePresenters(routeResult: routeResult, controller: controller).map({ presenter -> PresenterObjc in
                return PresenterObjc(presenter: presenter)
            })
        } else if let presenterProviderObjc = self.presenterProviderObjc {
            return try presenterProviderObjc.makePresenters(routeResult:routeResult,controller:controller)
        }
        
        return [PresenterObjc]()
    }
    
}
 | 
	d55260cec2a06176deaeae6dc066ca33 | 38.745455 | 141 | 0.689387 | false | false | false | false | 
| 
	mohamede1945/quran-ios | 
	refs/heads/master | 
	Quran/DefaultAyahInfoRetriever.swift | 
	gpl-3.0 | 
	1 | 
	//
//  DefaultAyahInfoPersistence.swift
//  Quran
//
//  Created by Mohamed Afifi on 4/22/16.
//
//  Quran for iOS is a Quran reading application for iOS.
//  Copyright (C) 2017  Quran.com
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
import PromiseKit
struct DefaultAyahInfoRetriever: AyahInfoRetriever {
    let persistence: AyahInfoPersistence
    func retrieveAyahs(in page: Int) -> Promise<[AyahNumber: [AyahInfo]]> {
        return DispatchQueue.default
            .promise2 { try self.persistence.getAyahInfoForPage(page) }
            .then { self.processAyahInfo($0) }
    }
    fileprivate func processAyahInfo(_ info: [AyahNumber: [AyahInfo]]) -> [AyahNumber: [AyahInfo]] {
        var result = [AyahNumber: [AyahInfo]]()
        for (ayah, pieces) in info where !pieces.isEmpty {
            var ayahResult: [AyahInfo] = []
            ayahResult += [pieces[0]]
            var lastAyah = ayahResult[0]
            for i in 1..<pieces.count {
                if pieces[i].line != lastAyah.line {
                    lastAyah = pieces[i]
                    ayahResult += [ pieces[i] ]
                } else {
                    ayahResult += [ ayahResult.removeLast().engulf(pieces[i]) ]
                }
            }
            result[ayah] = ayahResult
        }
        return result
    }
}
 | 
	9f67ddadde3df1092518cded0002d264 | 33.384615 | 100 | 0.618009 | false | false | false | false | 
| 
	prebid/prebid-mobile-ios | 
	refs/heads/master | 
	Example/PrebidDemo/PrebidDemoSwift/Examples/MAX/MAXDisplayInterstitialViewController.swift | 
	apache-2.0 | 
	1 | 
	/*   Copyright 2019-2022 Prebid.org, Inc.
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
import UIKit
import PrebidMobile
import PrebidMobileMAXAdapters
import AppLovinSDK
fileprivate let storedImpDisplayInterstitial = "imp-prebid-display-interstitial-320-480"
fileprivate let storedResponseDisplayInterstitial = "response-prebid-display-interstitial-320-480"
fileprivate let maxAdUnitDisplayInterstitial = "98e49039f26d7f00"
class MAXDisplayInterstitialViewController: InterstitialBaseViewController, MAAdDelegate {
    
    // Prebid
    private var maxAdUnit: MediationInterstitialAdUnit!
    private var maxMediationDelegate: MAXMediationInterstitialUtils!
    
    // MAX
    private var maxInterstitial: MAInterstitialAd!
    override func loadView() {
        super.loadView()
        
        Prebid.shared.storedAuctionResponse = storedResponseDisplayInterstitial
        createAd()
    }
    
    func createAd() {
        // 1. Create a MAInterstitialAd
        maxInterstitial = MAInterstitialAd(adUnitIdentifier: maxAdUnitDisplayInterstitial)
        
        // 2. Create a MAXMediationInterstitialUtils
        maxMediationDelegate = MAXMediationInterstitialUtils(interstitialAd: maxInterstitial)
        
        // 3. Create a MediationInterstitialAdUnit
        maxAdUnit = MediationInterstitialAdUnit(configId: storedImpDisplayInterstitial, mediationDelegate: maxMediationDelegate)
        
        // 4. Make a bid request to Prebid Server
        maxAdUnit.fetchDemand(completion: { [weak self] result in
            PrebidDemoLogger.shared.info("Prebid demand fetch result \(result.name())")
            guard let self = self else { return }
            
            // 5. Load the interstitial ad
            self.maxInterstitial.delegate = self
            self.maxInterstitial.load()
        })
    }
    
    // MARK: - MAAdDelegate
    
    func didLoad(_ ad: MAAd) {
        if let maxInterstitial = maxInterstitial, maxInterstitial.isReady {
            maxInterstitial.show()
        }
    }
    
    func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) {
        PrebidDemoLogger.shared.error("\(error.message)")
    }
    
    func didFail(toDisplay ad: MAAd, withError error: MAError) {
        PrebidDemoLogger.shared.error("\(error.message)")
    }
    
    func didDisplay(_ ad: MAAd) {}
    
    func didHide(_ ad: MAAd) {}
    
    func didClick(_ ad: MAAd) {}
}
 | 
	a6f5263816bbb2d919cfc2922ac6a761 | 34.361446 | 128 | 0.702555 | false | false | false | false | 
| 
	omnypay/omnypay-sdk-ios | 
	refs/heads/master | 
	ExampleApp/OmnyPayAllSdkDemo/OmnyPayAllSdkDemo/ViewController.swift | 
	apache-2.0 | 
	1 | 
	/**
	Copyright 2017 OmnyPay Inc.
	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at
	   http://www.apache.org/licenses/LICENSE-2.0
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
import UIKit
import OmnyPayAPI
import KVNProgress
/**
 * This class initializes example app with all the prerequisites for e.g. Merchant Id and User account
 * required for the app.
 * Please set merchant id, username and password in Constants.swift file
 */
class ViewController: UIViewController {
  var merchantShopperId: String?
  var merchantAuthToken: String?
  @IBOutlet weak var btnProceed: UIButton!
  
  override func viewDidLoad() {
    super.viewDidLoad()
    btnProceed.isHidden = true
    title = Constants.appTitle
  }
  @IBAction func initializeApp(_ sender: UIButton) {
    
    KVNProgress.show(withStatus: "Initializing SDK")
    
    /**
     * The initializeSDK method initializes merchantId. If merchantId exists in OmnyPay system,
     * then user is created and authenticated. If not, error is returned back. Replace
     * merchantId with the your merchant_id.
     */
    omnypayApi.initialize(withMerchantId: Constants.merchantId,
                          merchantApiKey: Constants.merchantApiKey,
                          merchantApiSecret: Constants.merchantApiSecret,
                          configuration: [
                            "host": ApiWrapper.getBaseApiUrl(),
                            "correlation-id": Constants.correlationId
    ]){ (status, error) in
      if status {
        // create merchant shopper
        ApiWrapper.createMerchantShopper() { merchantShopper in
          if merchantShopper["error"] != nil || (merchantShopper["status"] ?? "") as! String == "error" {
            print("shopper could not be created")
            KVNProgress.showError(withStatus: "Shopper could not be created")
          } else {
            /**
             * Use your identity service to authenticate the shopper. This method shows how to use OmnyPay's
             * identity service for shopper authentication.
             *
             * After authentication pass on the auth-token and shopper id to OmnyPay service.
             */
            ApiWrapper.authenticateShopperForMerchant() { shopperAuth in
              if shopperAuth["error"] != nil {
                print("shopper not authenticated with merchant")
                KVNProgress.showError(withStatus: "Invalid shopper")
              } else {
                self.merchantShopperId = shopperAuth["merchant-shopper-id"] as? String
                self.merchantAuthToken = shopperAuth["merchant-auth-token"] as? String
                DispatchQueue.main.async {
                  KVNProgress.dismiss()
                  self.btnProceed.isHidden = false
                }
              }
            }
          }
        }
      } else {
        print("Merchant initialization failed: ", error as Any)
        KVNProgress.showError(withStatus: "Initialization failed")
      }
    }
  }
  
  @IBAction func proceedToFetchCards(_ sender: UIButton) {
    KVNProgress.show(withStatus: "Authenticating shopper")
    /**
     * This method shows how a user is authenticated with current session by passing your
     * user/shopper id and auth token. authenticateShopper is the method defined is OmnyPayAPI
     * which is responsible for authenticating a shopper with OmnyPay service.
     */
    omnypayApi.authenticateShopper(withShopperId: self.merchantShopperId!, authToken: self.merchantAuthToken!){ (session, error) in
      if error == nil {
        KVNProgress.dismiss()
        self.performSegue(withIdentifier: "fetchCards", sender: self)
      } else {
        KVNProgress.showError(withStatus: "Shopper could not be authenticated")
        print("Shopper authentication failed: ", error as Any)
      }
    }
  }
}
 | 
	07e93f2efdf7197bbaadff4471782d1d | 36.981982 | 131 | 0.650854 | false | false | false | false | 
| 
	zyuanming/YMStretchableHeaderTabViewController | 
	refs/heads/master | 
	Demo/YMStretchableHeaderTabViewController/SampleHeaderView.swift | 
	mit | 
	1 | 
	//
//  SampleHeaderView.swift
//  YMStretchableHeaderTabViewController
//
//  Created by Zhang Yuanming on 5/2/17.
//  Copyright © 2017 None. All rights reserved.
//
import UIKit
class SampleHeaderView: StretchableHeaderView, StretchableHeaderViewDelegate, UIGestureRecognizerDelegate {
    lazy var button: UIButton = {
        let button = UIButton(type: .contactAdd)
        return button
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        delegate = self
        addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        addConstraints([
            NSLayoutConstraint(item: button, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0),
            NSLayoutConstraint(item: button, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0)
        ])
        isUserInteractionEnabled = true
        let tagGesture = UITapGestureRecognizer(target: self, action: #selector(handleTagGesture(_:)))
        tagGesture.delegate = self
        addGestureRecognizer(tagGesture)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func interactiveSubviews(in headerView: StretchableHeaderView) -> [UIView] {
        return [button, self]
    }
    @objc func handleTagGesture(_ gestureRecognizer: UITapGestureRecognizer) {
        print("tag.....")
    }
}
 | 
	0b8eb0219164c2e47ebf69b254d81b2b | 30.3125 | 152 | 0.675981 | false | false | false | false | 
| 
	goRestart/restart-backend-app | 
	refs/heads/develop | 
	Sources/FluentStorage/Model/Location/LocationDiskModel.swift | 
	gpl-3.0 | 
	1 | 
	import FluentProvider
extension LocationDiskModel {
 
    static var name: String = "location"
    
    struct Field {
        static let latitude = "latitude"
        static let longitude = "longitude"
        static let city = "city"
        static let country = "country"
        static let zip = "zip"
        static let ip = "ip"
    }
}
final class LocationDiskModel: Entity, Timestampable {
    
    let storage = Storage()
    
    var latitude: Double?
    var longitude: Double?
    var city: String?
    var country: String?
    var zip: String?
    var ip: String?
    
    init(row: Row) throws {
        latitude = try row.get(Field.latitude)
        longitude = try row.get(Field.longitude)
        city = try row.get(Field.city)
        country = try row.get(Field.country)
        zip = try row.get(Field.zip)
        ip = try row.get(Field.ip)
        id = try row.get(idKey)
    }
    
    func makeRow() throws -> Row {
        var row = Row()
        try row.set(Field.latitude, latitude)
        try row.set(Field.longitude, longitude)
        try row.set(Field.city, city)
        try row.set(Field.country, country)
        try row.set(Field.zip, zip)
        try row.set(Field.ip, ip)
        try row.set(idKey, id)
        return row
    }
}
// MARK: - Preparations
extension LocationDiskModel: Preparation {
    static func prepare(_ database: Fluent.Database) throws {
        try database.create(self) { creator in
            creator.id()
            creator.double(Field.latitude)
            creator.double(Field.longitude)
            creator.string(Field.city)
            creator.string(Field.country)
            creator.string(Field.zip)
            creator.string(Field.ip)
        }
    }
    
    static func revert(_ database: Fluent.Database) throws {
        try database.delete(self)
    }
}
 | 
	0a53ebebf0ca458254c448c74bc99118 | 25.3 | 61 | 0.588267 | false | false | false | false | 
| 
	jay18001/brickkit-ios | 
	refs/heads/master | 
	Tests/Interactive/InteractiveTests.swift | 
	apache-2.0 | 
	1 | 
	//
//  InteractiveTests.swift
//  BrickKit
//
//  Created by Ruben Cagnie on 9/30/16.
//  Copyright © 2016 Wayfair LLC. All rights reserved.
//
import XCTest
@testable import BrickKit
class InteractiveTests: XCTestCase {
    
    var brickView: BrickCollectionView!
    let LabelBrickIdentifier = "Label"
    let DummyBrickIdentifier = "Dummy"
    let CollectionBrickIdentifier = "Collection"
    let RootSectionIdentifier = "RootSection"
    var labelModel: LabelBrickCellModel!
    override func setUp() {
        super.setUp()
        continueAfterFailure = false
        brickView = BrickCollectionView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
        labelModel = LabelBrickCellModel(text: "A")
    }
    //MARK: invalidateRepeatCounts
    func testInvalidateRepeatCounts() {
        brickView.registerBrickClass(LabelBrick.self)
        let section = BrickSection(bricks: [
            LabelBrick(LabelBrickIdentifier, height: .fixed(size: 10), dataSource: labelModel)
            ])
        let fixedCount = FixedRepeatCountDataSource(repeatCountHash: [LabelBrickIdentifier: 1])
        section.repeatCountDataSource = fixedCount
        brickView.setSection(section)
        brickView.layoutIfNeeded()
        XCTAssertEqual(brickView.subviews.count, 2)
        fixedCount.repeatCountHash[LabelBrickIdentifier] = 5
        let indexPathSort: (IndexPath, IndexPath) -> Bool = { indexPath1, indexPath2  in
            if indexPath1.section == indexPath2.section {
                return indexPath1.item < indexPath2.item
            } else {
                return indexPath1.section < indexPath2.section
            }
        }
        let addedExpectation = expectation(description: "Added Bricks")
        self.brickView.invalidateRepeatCounts { (completed, insertedIndexPaths, deletedIndexPaths) in
            XCTAssertEqual(insertedIndexPaths.sorted(by: indexPathSort), [
                IndexPath(item: 1, section: 1),
                IndexPath(item: 2, section: 1),
                IndexPath(item: 3, section: 1),
                IndexPath(item: 4, section: 1),
                ])
            XCTAssertEqual(deletedIndexPaths, [])
            addedExpectation.fulfill()
        }
        waitForExpectations(timeout: 5, handler: nil)
        XCTAssertEqual(brickView.visibleCells.count, 6)
        fixedCount.repeatCountHash[LabelBrickIdentifier] = 1
        let removedExpectation = expectation(description: "Removed Bricks")
        self.brickView.invalidateRepeatCounts { (completed, insertedIndexPaths, deletedIndexPaths) in
            XCTAssertEqual(insertedIndexPaths, [])
            XCTAssertEqual(deletedIndexPaths.sorted(by: indexPathSort), [
                IndexPath(item: 1, section: 1),
                IndexPath(item: 2, section: 1),
                IndexPath(item: 3, section: 1),
                IndexPath(item: 4, section: 1),
                ])
            removedExpectation.fulfill()
        }
        waitForExpectations(timeout: 5, handler: nil)
        XCTAssertEqual(brickView.visibleCells.count, 2)
    }
    func testInvalidateRepeatCountsLess() {
        brickView.registerBrickClass(LabelBrick.self)
        let section = BrickSection(bricks: [
            BrickSection(bricks: [
                LabelBrick("Brick1", height: .fixed(size: 10), dataSource: labelModel),
                ]),
            LabelBrick("Brick2", height: .fixed(size: 10), dataSource: labelModel),
            BrickSection(bricks: [
                LabelBrick("Brick3", height: .fixed(size: 10), dataSource: labelModel),
                ]),
            ])
        let fixedCount = FixedRepeatCountDataSource(repeatCountHash: ["Brick1": 5, "Brick2": 5, "Brick3": 5])
        section.repeatCountDataSource = fixedCount
        brickView.setSection(section)
        brickView.layoutIfNeeded()
        XCTAssertEqual(brickView.visibleCells.count, 18)
        fixedCount.repeatCountHash = ["Brick1": 2, "Brick2": 2, "Brick3": 2]
        let addedExpectation = expectation(description: "Added Bricks")
        self.brickView.invalidateRepeatCounts { (completed) in
            addedExpectation.fulfill()
        }
        waitForExpectations(timeout: 5, handler: nil)
        XCTAssertEqual(brickView.visibleCells.count, 9)
        let flow = brickView.layout 
        XCTAssertEqual(flow.sections?[3]?.sectionAttributes?.indexPath, IndexPath(item: 3, section: 1))
    }
    func testInvalidateRepeatCountsMultiSections() {
        brickView.registerBrickClass(DummyBrick.self)
        let section = BrickSection(bricks: [
            DummyBrick("Brick1", height: .fixed(size: 10)),
            BrickSection(bricks: [
                DummyBrick("Brick2", height: .fixed(size: 10)),
                BrickSection(bricks: [
                    DummyBrick("Brick3", height: .fixed(size: 10))
                    ])
                ]),
            BrickSection(bricks: [
                DummyBrick("Brick4", height: .fixed(size: 10))
                ])
            ])
        let fixed = FixedRepeatCountDataSource(repeatCountHash: ["Brick1": 5, "Brick2": 4, "Brick3": 3, "Brick4": 2])
        section.repeatCountDataSource = fixed
        brickView.setSection(section)
        brickView.layoutIfNeeded()
        XCTAssertEqual(brickView.visibleCells.count, 18)
        fixed.repeatCountHash["Brick1"] = 3
        fixed.repeatCountHash["Brick2"] = 2
        fixed.repeatCountHash["Brick3"] = 1
        fixed.repeatCountHash["Brick4"] = 0
        let repeatCountExpectation = expectation(description: "RepeatCount")
        self.brickView.invalidateRepeatCounts { (completed) in
            repeatCountExpectation.fulfill()
        }
        waitForExpectations(timeout: 5, handler: nil)
        XCTAssertEqual(brickView.visibleCells.count, 10)
    }
    //MARK: reloadBricksWithIdentifiers
    func testReloadBricksWithIdentifiersNotReloadCell() {
        brickView.registerBrickClass(LabelBrick.self)
        let section = BrickSection(bricks: [
            LabelBrick(LabelBrickIdentifier, dataSource: labelModel)
            ])
        brickView.setSection(section)
        brickView.layoutIfNeeded()
        labelModel.text = "B"
        let expectation = self.expectation(description: "Reload")
        brickView.reloadBricksWithIdentifiers([LabelBrickIdentifier], shouldReloadCell: false) { (completed) in
            expectation.fulfill()
        }
        waitForExpectations(timeout: 5, handler: nil)
        let label = brickView.cellForItem(at: IndexPath(item: 0, section: 1)) as? LabelBrickCell
        XCTAssertNotNil(label)
        XCTAssertEqual(label?.label.text, "B")
    }
    func testReloadBricksWithIdentifiersNotReloadCellOffScreen() {
        brickView.registerBrickClass(LabelBrick.self)
        let section = BrickSection(bricks: [
            LabelBrick(LabelBrickIdentifier, dataSource: labelModel)
            ], edgeInsets: UIEdgeInsets(top: 1000, left: 0, bottom: 0, right: 0))
        brickView.setSection(section)
        brickView.layoutIfNeeded()
        labelModel.text = "B"
        let expectation = self.expectation(description: "Reload")
        brickView.reloadBricksWithIdentifiers([LabelBrickIdentifier], shouldReloadCell: false) { (completed) in
            expectation.fulfill()
        }
        waitForExpectations(timeout: 5, handler: nil)
        var label = brickView.cellForItem(at: IndexPath(item: 0, section: 1)) as? LabelBrickCell
        XCTAssertNil(label)
        brickView.contentOffset.y = 1000
        brickView.layoutIfNeeded()
        label = brickView.cellForItem(at: IndexPath(item: 0, section: 1)) as? LabelBrickCell
        XCTAssertNotNil(label)
        XCTAssertEqual(label?.label.text, "B")
    }
    func testReloadBricksWithIdentifiersReloadCell() {
        brickView.registerBrickClass(LabelBrick.self)
        let section = BrickSection(bricks: [
            LabelBrick(LabelBrickIdentifier, dataSource: labelModel)
            ])
        brickView.setSection(section)
        brickView.layoutIfNeeded()
        labelModel.text = "B"
        let expectation = self.expectation(description: "Reload")
        brickView.reloadBricksWithIdentifiers([LabelBrickIdentifier], shouldReloadCell: true) { (completed) in
            expectation.fulfill()
        }
        waitForExpectations(timeout: 5, handler: nil)
        let label = brickView.cellForItem(at: IndexPath(item: 0, section: 1)) as? LabelBrickCell
        XCTAssertNotNil(label)
        XCTAssertEqual(label?.label.text, "B")
    }
    func testReloadBricksWithIdentifiersReloadCellMultiSectionAdd() {
        brickView.registerBrickClass(LabelBrick.self)
        let section = BrickSection(RootSectionIdentifier, bricks: [
            LabelBrick(LabelBrickIdentifier, height: .fixed(size: 10), dataSource: labelModel)
            ])
        let fixedCount = FixedRepeatCountDataSource(repeatCountHash: [LabelBrickIdentifier: 1])
        section.repeatCountDataSource = fixedCount
        brickView.setSection(section)
        brickView.layoutIfNeeded()
        XCTAssertEqual(brickView.subviews.count, 2)
        fixedCount.repeatCountHash[LabelBrickIdentifier] = 5
        let expectation = self.expectation(description: "Reload")
        brickView.reloadBricksWithIdentifiers([RootSectionIdentifier], shouldReloadCell: true) { (completed) in
            expectation.fulfill()
        }
        waitForExpectations(timeout: 5, handler: nil)
        XCTAssertEqual(brickView.visibleCells.count, 6)
    }
    func testReloadBricksWithIdentifiersReloadCellMultiSectionRemove() {
        brickView.registerBrickClass(LabelBrick.self)
        let section = BrickSection(RootSectionIdentifier, bricks: [
            LabelBrick(LabelBrickIdentifier, height: .fixed(size: 10), dataSource: labelModel)
            ])
        let fixedCount = FixedRepeatCountDataSource(repeatCountHash: [LabelBrickIdentifier: 5])
        section.repeatCountDataSource = fixedCount
        brickView.setSection(section)
        brickView.layoutIfNeeded()
        XCTAssertEqual(brickView.visibleCells.count, 6)
        fixedCount.repeatCountHash[LabelBrickIdentifier] = 1
        let expectation = self.expectation(description: "Reload")
        brickView.reloadBricksWithIdentifiers([RootSectionIdentifier], shouldReloadCell: true) { (completed) in
            expectation.fulfill()
        }
        waitForExpectations(timeout: 5, handler: nil)
        XCTAssertEqual(brickView.visibleCells.count, 2)
    }
    // Mark: - ReloadBricksWithIdentifier
    func testReloadBricksWithIdentifier() {
        brickView.registerBrickClass(LabelBrick.self)
        let section = BrickSection(bricks: [
            LabelBrick(LabelBrickIdentifier, dataSource: labelModel)
            ])
        brickView.setSection(section)
        brickView.layoutIfNeeded()
        labelModel.text = "B"
        brickView.reloadBrickWithIdentifier(LabelBrickIdentifier, andIndex: 0)
        brickView.layoutIfNeeded()
        let label = brickView.cellForItem(at: IndexPath(item: 0, section: 1)) as? LabelBrickCell
        XCTAssertNotNil(label)
        XCTAssertEqual(label?.label.text, "B")
    }
    func testReloadBricksWithIdentifierChangeWidth() {
        brickView.registerBrickClass(LabelBrick.self)
        let brick = LabelBrick(LabelBrickIdentifier, height: .fixed(size: 100), dataSource: labelModel)
        let section = BrickSection(bricks: [
            brick
            ])
        brickView.setSection(section)
        brickView.layoutIfNeeded()
        var label: LabelBrickCell
        label = brickView.cellForItem(at: IndexPath(item: 0, section: 1)) as! LabelBrickCell
        XCTAssertNotNil(label)
        XCTAssertEqual(label.frame, CGRect(x: 0, y: 0, width: 320, height: 100))
        brick.size.width = .ratio(ratio: 1/2)
        let expectation = self.expectation(description: "Reload")
        brickView.performBatchUpdates({ 
            self.brickView.reloadBrickWithIdentifier(self.LabelBrickIdentifier, andIndex: 0)
            }) { (completed) in
                self.brickView.collectionViewLayout.invalidateLayout()
                expectation.fulfill()
        }
        waitForExpectations(timeout: 5, handler: nil)
        brickView.layoutSubviews()
        XCTAssertEqual(brickView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: 0, section: 1))?.frame, CGRect(x: 0, y: 0, width: 160, height: 100))
        XCTAssertEqual(brickView.layoutAttributesForItem(at: IndexPath(item: 0, section: 1))?.frame, CGRect(x: 0, y: 0, width: 160, height: 100))
        label = brickView.cellForItem(at: IndexPath(item: 0, section: 1)) as! LabelBrickCell
        XCTAssertNotNil(label)
        XCTAssertEqual(label.frame, CGRect(x: 0, y: 0, width: 160, height: 100))
    }
    //MARK: reloadBricksWithIdentifiers
    func testReloadBricksWithIdentifiersCollectionBrick() {
        brickView.registerBrickClass(CollectionBrick.self)
        let collectionSection = BrickSection(bricks: [
            LabelBrick(LabelBrickIdentifier, dataSource: labelModel)
            ])
        let section = BrickSection(bricks: [
            CollectionBrick(CollectionBrickIdentifier, dataSource: CollectionBrickCellModel(section: collectionSection, configureHandler: { (cell) in
                cell.brickCollectionView.registerBrickClass(LabelBrick.self)
            }))
            ])
        brickView.setSection(section)
        brickView.layoutIfNeeded()
        labelModel.text = "B"
        brickView.reloadBricksWithIdentifiers([LabelBrickIdentifier], inCollectionBrickWithIdentifier: CollectionBrickIdentifier)
        let cell = brickView.cellForItem(at: IndexPath(item: 0, section: 1)) as? CollectionBrickCell
        XCTAssertNotNil(cell)
        let label = cell!.brickCollectionView.cellForItem(at: IndexPath(item: 0, section: 1)) as? LabelBrickCell
        XCTAssertNotNil(label)
        XCTAssertEqual(label?.label.text, "B")
        
    }
    func testReloadBricksWithIdentifiersCollectionBrickOffscreen() {
        brickView.registerBrickClass(CollectionBrick.self)
        let collectionSection = BrickSection(bricks: [
            LabelBrick(LabelBrickIdentifier, dataSource: labelModel)
            ])
        let section = BrickSection(bricks: [
            CollectionBrick(CollectionBrickIdentifier, dataSource: CollectionBrickCellModel(section: collectionSection, configureHandler: { (cell) in
                cell.brickCollectionView.registerBrickClass(LabelBrick.self)
            }))
            ], edgeInsets: UIEdgeInsets(top: 1000, left: 0, bottom: 0, right: 0))
        brickView.setSection(section)
        brickView.layoutIfNeeded()
        labelModel.text = "B"
        brickView.reloadBricksWithIdentifiers([LabelBrickIdentifier], inCollectionBrickWithIdentifier: CollectionBrickIdentifier)
        var cell = brickView.cellForItem(at: IndexPath(item: 0, section: 1)) as? CollectionBrickCell
        XCTAssertNil(cell)
        brickView.contentOffset.y = 1000
        brickView.layoutIfNeeded()
        cell = brickView.cellForItem(at: IndexPath(item: 0, section: 1)) as? CollectionBrickCell
        XCTAssertNotNil(cell)
        let label = cell!.brickCollectionView.cellForItem(at: IndexPath(item: 0, section: 1)) as? LabelBrickCell
        XCTAssertNotNil(label)
        XCTAssertEqual(label?.label.text, "B")
    }
    func testReloadBricksWithIdentifiersCollectionBrickAtIndex() {
        brickView.registerBrickClass(CollectionBrick.self)
        let collectionSection = BrickSection(bricks: [
            LabelBrick(LabelBrickIdentifier, dataSource: labelModel)
            ])
        let section = BrickSection(bricks: [
            CollectionBrick(CollectionBrickIdentifier, dataSource: CollectionBrickCellModel(section: collectionSection, configureHandler: { (cell) in
                cell.brickCollectionView.registerBrickClass(LabelBrick.self)
            }))
            ])
        let repeatCountDataSource = FixedRepeatCountDataSource(repeatCountHash: [CollectionBrickIdentifier: 5])
        section.repeatCountDataSource = repeatCountDataSource
        brickView.setSection(section)
        brickView.layoutIfNeeded()
        labelModel.text = "B"
        brickView.reloadBricksWithIdentifiers([LabelBrickIdentifier], inCollectionBrickWithIdentifier: CollectionBrickIdentifier, andIndex: 2)
        let cell1 = brickView.cellForItem(at: IndexPath(item: 0, section: 1)) as? CollectionBrickCell
        XCTAssertNotNil(cell1)
        let label1 = cell1!.brickCollectionView.cellForItem(at: IndexPath(item: 0, section: 1)) as? LabelBrickCell
        XCTAssertNotNil(label1)
        XCTAssertEqual(label1!.label.text, "A")
        let cell2 = brickView.cellForItem(at: IndexPath(item: 2, section: 1)) as? CollectionBrickCell
        XCTAssertNotNil(cell2)
        let label2 = cell2!.brickCollectionView.cellForItem(at: IndexPath(item: 0, section: 1)) as? LabelBrickCell
        XCTAssertNotNil(label2)
        XCTAssertEqual(label2!.label.text, "B")
    }
    // Mark: - Invalidate while sticky
    func testInvalidateWhileSticky() {
        brickView.registerBrickClass(DummyBrick.self)
        brickView.registerBrickClass(LabelBrick.self)
        let section = BrickSection(bricks: [
            DummyBrick(height: .fixed(size: 50)),
            BrickSection(bricks: [
                LabelBrick(DummyBrickIdentifier, text: "", configureCellBlock: { cell in
                    var text = "Brick"
                    for _ in 0..<cell.index {
                        text += "\nBrick"
                    }
                    cell.label.text = text
                })
                ])
            ])
        
        let fixedStickyLayout = FixedStickyLayoutBehaviorDataSource(indexPaths: [IndexPath(item: 0, section: 1)])
        let repeatCountDataSource = FixedRepeatCountDataSource(repeatCountHash: [DummyBrickIdentifier: 30])
        section.repeatCountDataSource = repeatCountDataSource
        let sticky = StickyLayoutBehavior(dataSource: fixedStickyLayout)
        brickView.layout.behaviors.insert(sticky)
        brickView.setSection(section)
        brickView.layoutSubviews()
        brickView.contentOffset.y += brickView.frame.size.height
        brickView.collectionViewLayout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling))
        brickView.layoutIfNeeded()
        let cell1 = brickView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: 1, section: 1))
        XCTAssertEqual(cell1?.frame.origin.y, 50)
        let cell2 = brickView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: 0, section: 1))
        XCTAssertEqual(cell2?.frame, CGRect(x: 0, y: brickView.contentOffset.y, width: 320, height: 50))
    }
    // Mark: - Shouldn't crash
    func testShouldNotCrashOnReloadBricks() {
        // we should check if the indexpath exists before adding it...
        brickView.registerBrickClass(DummyBrick.self)
        let section = BrickSection(bricks: [
            BrickSection("Section", bricks: [
                DummyBrick("Item", width: .ratio(ratio: 1/2), height: .fixed(size: 38)),
                ], inset: 5, edgeInsets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)),
            ])
        let repeatCount = FixedRepeatCountDataSource(repeatCountHash: ["Item": 0])
        section.repeatCountDataSource = repeatCount
        
        brickView.setSection(section)
        brickView.layoutSubviews()
        var expectation: XCTestExpectation!
        repeatCount.repeatCountHash["Item"] = 30
        expectation = self.expectation(description: "Invalidate bricks")
        brickView.invalidateBricks { (completed) in
            expectation.fulfill()
        }
        waitForExpectations(timeout: 5, handler: nil)
        repeatCount.repeatCountHash["Item"] = 0
        expectation = self.expectation(description: "Invalidate bricks")
        brickView.invalidateBricks { (completed) in
            expectation.fulfill()
        }
        waitForExpectations(timeout: 5, handler: nil)
    }
    func testThatInvalidateRepeatCountsSetCorrectIdentifiers() {
        let section = BrickSection(bricks: [
            DummyBrick("Brick1", height: .fixed(size: 50)),
            DummyBrick("Brick2", height: .fixed(size: 50))
            ])
        let repeatCount = FixedRepeatCountDataSource(repeatCountHash: ["Brick1": 1])
        section.repeatCountDataSource = repeatCount
        brickView.setupSectionAndLayout(section)
        repeatCount.repeatCountHash = ["Brick1": 2]
        let expecation = expectation(description: "Invalidate Repeat Counts")
        brickView.invalidateRepeatCounts(reloadAllSections: false) { (completed, insertedIndexPaths, deletedIndexPaths) in
            expecation.fulfill()
        }
        waitForExpectations(timeout: 5, handler: nil)
        let attributes = brickView.layout.layoutAttributesForItem(at: IndexPath(item: 1, section: 1)) as? BrickLayoutAttributes
        XCTAssertEqual(attributes?.identifier, "Brick1")
    }
    func testThatInvalidateRepeatCountsHasCorrectValues() {
        continueAfterFailure = true
        
        let repeatDataSource = FixedRepeatCountDataSource(repeatCountHash: ["Brick2": 1])
        let section = BrickSection(bricks: [
            LabelBrick("Brick1", height: .fixed(size: 50), text: "Label 1"),
            LabelBrick("Brick2", height: .fixed(size: 10), text: "Label 2"),
            LabelBrick("Brick3", height: .fixed(size: 50), text: "Label 3"),
            ])
        section.repeatCountDataSource = repeatDataSource
        brickView.setupSectionAndLayout(section)
        
        repeatDataSource.repeatCountHash = ["Brick2": 3]
        let invalidateVisibilityExpectation = expectation(description: "Wait for invalidateVisibility")
        brickView.invalidateRepeatCounts(reloadAllSections: true) { (completed, insertedIndexPaths, deletedIndexPaths) in
            invalidateVisibilityExpectation.fulfill()
        }
        waitForExpectations(timeout:  5, handler: nil)
        brickView.layoutIfNeeded()
        
        XCTAssertEqual(brickView.cellForItem(at: IndexPath(item: 0, section: 1))?.frame.height, 50)
        XCTAssertEqual(brickView.cellForItem(at: IndexPath(item: 1, section: 1))?.frame.height, 10)
        XCTAssertEqual(brickView.cellForItem(at: IndexPath(item: 2, section: 1))?.frame.height, 10)
        XCTAssertEqual(brickView.cellForItem(at: IndexPath(item: 3, section: 1))?.frame.height, 10)
        XCTAssertEqual(brickView.cellForItem(at: IndexPath(item: 4, section: 1))?.frame.height, 50)
    }
}
 | 
	29536d5d8ae18440d9c3b45527845840 | 37.707692 | 166 | 0.662736 | false | false | false | false | 
| 
	JGiola/swift | 
	refs/heads/main | 
	test/decl/protocol/req/associated_type_inference.swift | 
	apache-2.0 | 
	1 | 
	// RUN: %target-typecheck-verify-swift
protocol P0 {
  associatedtype Assoc1 : PSimple // expected-note{{ambiguous inference of associated type 'Assoc1': 'Double' vs. 'Int'}}
  // expected-note@-1{{ambiguous inference of associated type 'Assoc1': 'Double' vs. 'Int'}}
  // expected-note@-2{{unable to infer associated type 'Assoc1' for protocol 'P0'}}
  // expected-note@-3{{unable to infer associated type 'Assoc1' for protocol 'P0'}}
  func f0(_: Assoc1)
  func g0(_: Assoc1)
}
protocol PSimple { }
extension Int : PSimple { }
extension Double : PSimple { }
struct X0a : P0 { // okay: Assoc1 == Int
  func f0(_: Int) { }
  func g0(_: Int) { }
}
struct X0b : P0 { // expected-error{{type 'X0b' does not conform to protocol 'P0'}}
  func f0(_: Int) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Int'}}
  func g0(_: Double) { } // expected-note{{matching requirement 'g0' to this declaration inferred associated type to 'Double'}}
}
struct X0c : P0 { // okay: Assoc1 == Int
  func f0(_: Int) { }
  func g0(_: Float) { }
  func g0(_: Int) { }
}
struct X0d : P0 { // okay: Assoc1 == Int
  func f0(_: Int) { }
  func g0(_: Double) { } // viable, but no corresponding f0
  func g0(_: Int) { }
}
struct X0e : P0 { // expected-error{{type 'X0e' does not conform to protocol 'P0'}}
  func f0(_: Double) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Double}}
  func f0(_: Int) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Int'}}
  func g0(_: Double) { }
  func g0(_: Int) { } 
}
struct X0f : P0 { // okay: Assoc1 = Int because Float doesn't conform to PSimple
  func f0(_: Float) { }
  func f0(_: Int) { }
  func g0(_: Float) { }
  func g0(_: Int) { }
}
struct X0g : P0 { // expected-error{{type 'X0g' does not conform to protocol 'P0'}}
  func f0(_: Float) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
  func g0(_: Float) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
}
struct X0h<T : PSimple> : P0 {
  func f0(_: T) { }
}
extension X0h {
  func g0(_: T) { }
}
struct X0i<T : PSimple> {
}
extension X0i {
  func g0(_: T) { }
}
extension X0i : P0 { }
extension X0i {
  func f0(_: T) { }
}
// Protocol extension used to infer requirements
protocol P1 {
}
extension P1 {
  func f0(_ x: Int) { }
  func g0(_ x: Int) { }
}
struct X0j : P0, P1 { }
protocol P2 {
  associatedtype P2Assoc
  func h0(_ x: P2Assoc)
}
extension P2 where Self.P2Assoc : PSimple {
  func f0(_ x: P2Assoc) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
  func g0(_ x: P2Assoc) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
}
struct X0k : P0, P2 {
  func h0(_ x: Int) { }
}
struct X0l : P0, P2 { // expected-error{{type 'X0l' does not conform to protocol 'P0'}}
  func h0(_ x: Float) { }
}
// Prefer declarations in the type to those in protocol extensions
struct X0m : P0, P2 {
  func f0(_ x: Double) { }
  func g0(_ x: Double) { }
  func h0(_ x: Double) { }
}
// Inference from properties.
protocol PropertyP0 {
  associatedtype Prop : PSimple // expected-note{{unable to infer associated type 'Prop' for protocol 'PropertyP0'}}
  var property: Prop { get }
}
struct XProp0a : PropertyP0 { // okay PropType = Int
  var property: Int
}
struct XProp0b : PropertyP0 { // expected-error{{type 'XProp0b' does not conform to protocol 'PropertyP0'}}
  var property: Float // expected-note{{candidate would match and infer 'Prop' = 'Float' if 'Float' conformed to 'PSimple'}}
}
// Inference from subscripts
protocol SubscriptP0 {
  associatedtype Index
  // expected-note@-1 2 {{protocol requires nested type 'Index'; do you want to add it?}}
  associatedtype Element : PSimple
  // expected-note@-1 {{unable to infer associated type 'Element' for protocol 'SubscriptP0'}}
  // expected-note@-2 2 {{protocol requires nested type 'Element'; do you want to add it?}}
  subscript (i: Index) -> Element { get }
}
struct XSubP0a : SubscriptP0 {
  subscript (i: Int) -> Int { get { return i } }
}
struct XSubP0b : SubscriptP0 {
// expected-error@-1{{type 'XSubP0b' does not conform to protocol 'SubscriptP0'}}
  subscript (i: Int) -> Float { get { return Float(i) } } // expected-note{{candidate would match and infer 'Element' = 'Float' if 'Float' conformed to 'PSimple'}}
}
struct XSubP0c : SubscriptP0 {
// expected-error@-1 {{type 'XSubP0c' does not conform to protocol 'SubscriptP0'}}
  subscript (i: Index) -> Element { get { } }
}
struct XSubP0d : SubscriptP0 {
// expected-error@-1 {{type 'XSubP0d' does not conform to protocol 'SubscriptP0'}}
  subscript (i: XSubP0d.Index) -> XSubP0d.Element { get { } }
}
// Inference from properties and subscripts
protocol CollectionLikeP0 {
  associatedtype Index
  // expected-note@-1 {{protocol requires nested type 'Index'; do you want to add it?}}
  associatedtype Element
  // expected-note@-1 {{protocol requires nested type 'Element'; do you want to add it?}}
  var startIndex: Index { get }
  var endIndex: Index { get }
  subscript (i: Index) -> Element { get }
}
struct SomeSlice<T> { }
struct XCollectionLikeP0a<T> : CollectionLikeP0 {
  var startIndex: Int
  var endIndex: Int
  subscript (i: Int) -> T { get { fatalError("blah") } }
  subscript (r: Range<Int>) -> SomeSlice<T> { get { return SomeSlice() } }
}
struct XCollectionLikeP0b : CollectionLikeP0 {
// expected-error@-1 {{type 'XCollectionLikeP0b' does not conform to protocol 'CollectionLikeP0'}}
  var startIndex: XCollectionLikeP0b.Index
  // There was an error @-1 ("'startIndex' used within its own type"),
  // but it disappeared and doesn't seem like much of a loss.
  var startElement: XCollectionLikeP0b.Element
}
// rdar://problem/21304164
public protocol Thenable {
    associatedtype T // expected-note{{protocol requires nested type 'T'}}
    func then(_ success: (_: T) -> T) -> Self
}
public class CorePromise<U> : Thenable { // expected-error{{type 'CorePromise<U>' does not conform to protocol 'Thenable'}}
    public func then(_ success: @escaping (_ t: U, _: CorePromise<U>) -> U) -> Self {
        return self.then() { (t: U) -> U in // expected-error{{contextual closure type '(U, CorePromise<U>) -> U' expects 2 arguments, but 1 was used in closure body}}
            return success(t: t, self)
            // expected-error@-1 {{extraneous argument label 't:' in call}}
        }
    }
}
// rdar://problem/21559670
protocol P3 {
  associatedtype Assoc = Int
  associatedtype Assoc2
  func foo(_ x: Assoc2) -> Assoc?
}
protocol P4 : P3 { }
extension P4 {
  func foo(_ x: Int) -> Float? { return 0 }
}
extension P3 where Assoc == Int {
  func foo(_ x: Int) -> Assoc? { return nil }
}
struct X4 : P4 { }
// rdar://problem/21738889
protocol P5 {
  associatedtype A = Int
}
struct X5<T : P5> : P5 {
  typealias A = T.A
}
protocol P6 : P5 {
  associatedtype A : P5 = X5<Self>
}
extension P6 where A == X5<Self> { }
// rdar://problem/21774092
protocol P7 {
  associatedtype A
  associatedtype B
  func f() -> A
  func g() -> B
}
struct X7<T> { }
extension P7 {
  func g() -> X7<A> { return X7() }
}
struct Y7<T> : P7 {
  func f() -> Int { return 0 }
}
struct MyAnySequence<Element> : MySequence {
  typealias SubSequence = MyAnySequence<Element>
  func makeIterator() -> MyAnyIterator<Element> {
    return MyAnyIterator<Element>()
  }
}
struct MyAnyIterator<T> : MyIteratorType {
  typealias Element = T
}
protocol MyIteratorType {
  associatedtype Element
}
protocol MySequence {
  associatedtype Iterator : MyIteratorType
  associatedtype SubSequence
  func foo() -> SubSequence
  func makeIterator() -> Iterator
}
extension MySequence {
  func foo() -> MyAnySequence<Iterator.Element> {
    return MyAnySequence()
  }
}
struct SomeStruct<Element> : MySequence {
  let element: Element
  init(_ element: Element) {
    self.element = element
  }
  func makeIterator() -> MyAnyIterator<Element> {
    return MyAnyIterator<Element>()
  }
}
// rdar://problem/21883828 - ranking of solutions
protocol P8 {
}
protocol P9 : P8 {
}
protocol P10 {
  associatedtype A
  func foo() -> A
}
struct P8A { }
struct P9A { }
extension P8 {
  func foo() -> P8A { return P8A() }
}
extension P9 {
  func foo() -> P9A { return P9A() }
}
struct Z10 : P9, P10 {
}
func testZ10() -> Z10.A {
  var zA: Z10.A
  zA = P9A()
  return zA
}
// rdar://problem/21926788
protocol P11 {
  associatedtype A
  associatedtype B
  func foo() -> B
}
extension P11 where A == Int {
  func foo() -> Int { return 0 }
}
protocol P12 : P11 {
}
extension P12 {
  func foo() -> String { return "" }
}
struct X12 : P12 {
  typealias A = String
}
// Infinite recursion -- we would try to use the extension
// initializer's argument type of 'Dough' as a candidate for
// the associated type
protocol Cookie {
  associatedtype Dough
  // expected-note@-1 {{protocol requires nested type 'Dough'; do you want to add it?}}
  init(t: Dough)
}
extension Cookie {
  init(t: Dough?) {}
}
struct Thumbprint : Cookie {}
// expected-error@-1 {{type 'Thumbprint' does not conform to protocol 'Cookie'}}
// Looking through typealiases
protocol Vector {
  associatedtype Element
  typealias Elements = [Element]
  func process(elements: Elements)
}
struct Int8Vector : Vector {
  func process(elements: [Int8]) { }
}
// SR-4486
protocol P13 {
  associatedtype Arg // expected-note{{protocol requires nested type 'Arg'; do you want to add it?}}
  func foo(arg: Arg)
}
struct S13 : P13 { // expected-error{{type 'S13' does not conform to protocol 'P13'}}
  func foo(arg: inout Int) {}
}
// "Infer" associated type from generic parameter.
protocol P14 {
  associatedtype Value
}
struct P14a<Value>: P14 { }
struct P14b<Value> { }
extension P14b: P14 { }
// Associated type defaults in overridden associated types.
struct X15 { }
struct OtherX15 { }
protocol P15a {
  associatedtype A = X15
}
protocol P15b : P15a {
  associatedtype A
}
protocol P15c : P15b {
  associatedtype A
}
protocol P15d {
  associatedtype A = X15
}
protocol P15e : P15b, P15d {
  associatedtype A
}
protocol P15f {
  associatedtype A = OtherX15
}
protocol P15g: P15c, P15f {
  associatedtype A // expected-note{{protocol requires nested type 'A'; do you want to add it?}}
}
struct X15a : P15a { }
struct X15b : P15b { }
struct X15c : P15c { }
struct X15d : P15d { }
// Ambiguity.
// FIXME: Better diagnostic here?
struct X15g : P15g { } // expected-error{{type 'X15g' does not conform to protocol 'P15g'}}
// Associated type defaults in overidden associated types that require
// substitution.
struct X16<T> { }
protocol P16 {
  associatedtype A = X16<Self>
}
protocol P16a : P16 {
  associatedtype A
}
protocol P16b : P16a {
  associatedtype A
}
struct X16b : P16b { }
// Refined protocols that tie associated types to a fixed type.
protocol P17 {
  associatedtype T
}
protocol Q17 : P17 where T == Int { }
struct S17 : Q17 { }
// Typealiases from protocol extensions should not inhibit associated type
// inference.
protocol P18 {
  associatedtype A
}
protocol P19 : P18 {
  associatedtype B
}
extension P18 where Self: P19 {
  typealias A = B
}
struct X18<A> : P18 { }
// rdar://problem/16316115
protocol HasAssoc {
  associatedtype Assoc
}
struct DefaultAssoc {}
protocol RefinesAssocWithDefault: HasAssoc {
  associatedtype Assoc = DefaultAssoc
}
struct Foo: RefinesAssocWithDefault {
}
protocol P20 {
  associatedtype T // expected-note{{protocol requires nested type 'T'; do you want to add it?}}
  typealias TT = T?
}
struct S19 : P20 {  // expected-error{{type 'S19' does not conform to protocol 'P20'}}
  typealias TT = Int?
}
// rdar://problem/44777661
struct S30<T> where T : P30 {}
protocol P30 {
  static func bar()
}
protocol P31 {
  associatedtype T : P30
}
extension S30 : P31 where T : P31 {}
extension S30 {
  func foo() {
    T.bar()
  }
}
protocol P32 {
  associatedtype A
  associatedtype B
  associatedtype C
  func foo(arg: A) -> C
  var bar: B { get }
}
protocol P33 {
  associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
  var baz: A { get }
}
protocol P34 {
  associatedtype A  // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
  func boo() -> A
}
struct S31<T> {}
extension S31: P32 where T == Int {} // OK
extension S31 where T == Int {
  func foo(arg: Never) {}
}
extension S31 where T: Equatable {
  var bar: Bool { true }
}
extension S31: P33 where T == Never {} // expected-error {{type 'S31<T>' does not conform to protocol 'P33'}}
extension S31 where T == String {
  var baz: Bool { true }
}
extension S31: P34 {} // expected-error {{type 'S31<T>' does not conform to protocol 'P34'}}
extension S31 where T: P32 {
  func boo() -> Void {}
}
// SR-12707
class SR_12707_C<T> {}
// Inference in the adoptee
protocol SR_12707_P1 {
  associatedtype A
  associatedtype B: SR_12707_C<(A, Self)>
  func foo(arg: B)
}
struct SR_12707_Conform_P1: SR_12707_P1 {
  typealias A = Never
  func foo(arg: SR_12707_C<(A, SR_12707_Conform_P1)>) {}
}
// Inference in protocol extension
protocol SR_12707_P2: SR_12707_P1 {}
extension SR_12707_P2 {
  func foo(arg: SR_12707_C<(A, Self)>) {}
}
struct SR_12707_Conform_P2: SR_12707_P2 {
  typealias A = Never
}
// SR-13172: Inference when witness is an enum case
protocol SR_13172_P1 {
  associatedtype Bar
  static func bar(_ value: Bar) -> Self
}
enum SR_13172_E1: SR_13172_P1 {
  case bar(String) // Okay
}
protocol SR_13172_P2 {
  associatedtype Bar
  static var bar: Bar { get }
}
enum SR_13172_E2: SR_13172_P2 {
  case bar // Okay
}
/** References to type parameters in type witnesses. */
// Circular reference through a fixed type witness.
protocol P35a {
  associatedtype A = Array<B> // expected-note {{protocol requires nested type 'A'}}
  associatedtype B // expected-note {{protocol requires nested type 'B'}}
}
protocol P35b: P35a where B == A {}
// expected-error@+2 {{type 'S35' does not conform to protocol 'P35a'}}
// expected-error@+1 {{type 'S35' does not conform to protocol 'P35b'}}
struct S35: P35b {}
// Circular reference through a value witness.
protocol P36a {
  associatedtype A // expected-note {{protocol requires nested type 'A'}}
  func foo(arg: A)
}
protocol P36b: P36a {
  associatedtype B = (Self) -> A // expected-note {{protocol requires nested type 'B'}}
}
// expected-error@+2 {{type 'S36' does not conform to protocol 'P36a'}}
// expected-error@+1 {{type 'S36' does not conform to protocol 'P36b'}}
struct S36: P36b {
  func foo(arg: Array<B>) {}
}
// Test that we can resolve abstract type witnesses that reference
// other abstract type witnesses.
protocol P37 {
  associatedtype A = Array<B>
  associatedtype B: Equatable = Never
}
struct S37: P37 {}
protocol P38a {
  associatedtype A = Never
  associatedtype B: Equatable
}
protocol P38b: P38a where B == Array<A> {}
struct S38: P38b {}
protocol P39 where A: Sequence {
  associatedtype A = Array<B>
  associatedtype B
}
struct S39<B>: P39 {}
// Test that we can handle an analogous complex case involving all kinds of
// type witness resolution.
//
// FIXME: Except there's too much circularity here, and this really can't
// work. The problem is that S40 conforms to P40c, and we can't check the
// conformance without computing the requirement signature of P40c, but the
// requirement signature computation depends on the conformance, via the
// 'D == S40<Never>' requirement.
protocol P40a {
  associatedtype A
  associatedtype B: P40a
  func foo(arg: A)
}
protocol P40b: P40a {
  associatedtype C = (A, B.A, D.D, E) -> Self // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
  associatedtype D: P40b // expected-note {{protocol requires nested type 'D'; do you want to add it?}}
  associatedtype E: Equatable // expected-note {{protocol requires nested type 'E'; do you want to add it?}}
}
protocol P40c: P40b where D == S40<Never> {}
struct S40<E: Equatable>: P40c {
  // expected-error@-1 {{type 'S40<E>' does not conform to protocol 'P40b'}}
  // expected-error@-2 {{type 'S40<E>' does not conform to protocol 'P40c'}}
  func foo(arg: Never) {}
  typealias B = Self
}
protocol P41a {
  associatedtype A
  associatedtype B
  func bar(_: B) -> A?
}
protocol P42b: P41a {
  associatedtype A
  associatedtype B
  func foo(_: A, _: B)
}
extension P42b {
  func bar(_: B) -> A? {}
}
do {
  class Conformer: P42b {
    func foo(_: Bool, _: String) {}
  }
}
// Fails to find the fixed type witness B == FIXME_S1<A>.
protocol FIXME_P1a {
  associatedtype A: Equatable = Never // expected-note {{protocol requires nested type 'A'}}
  associatedtype B: FIXME_P1a // expected-note {{protocol requires nested type 'B'}}
}
protocol FIXME_P1b: FIXME_P1a where B == FIXME_S1<A> {}
// expected-error@+2 {{type 'FIXME_S1<T>' does not conform to protocol 'FIXME_P1a'}}
// expected-error@+1 {{type 'FIXME_S1<T>' does not conform to protocol 'FIXME_P1b'}}
struct FIXME_S1<T: Equatable>: FIXME_P1b {}
 | 
	5d67e108cdb2b89431fb2d371097e109 | 23.02095 | 167 | 0.668469 | false | false | false | false | 
| 
	josve05a/wikipedia-ios | 
	refs/heads/develop | 
	WMF Framework/PeriodicWorker.swift | 
	mit | 
	4 | 
	import Foundation
@objc(WMFPeriodicWorker) public protocol PeriodicWorker: NSObjectProtocol {
    func doPeriodicWork(_ completion: @escaping () -> Void)
}
@objc(WMFPeriodicWorkerController) public class PeriodicWorkerController: WorkerController {
    let interval: TimeInterval
    let initialDelay: TimeInterval
    let leeway: TimeInterval
    
    lazy var workTimer: RepeatingTimer = {
        assert(Thread.isMainThread)
        return RepeatingTimer(interval, afterDelay: initialDelay, leeway: leeway) { [weak self] in
            self?.doPeriodicWork()
        }
    }()
    
    @objc(initWithInterval:initialDelay:leeway:) public required init(_ interval: TimeInterval, initialDelay: TimeInterval, leeway: TimeInterval) {
        self.interval = interval
        self.initialDelay = initialDelay
        self.leeway = leeway
    }
    
    var workers = [PeriodicWorker]()
    
    @objc public func add(_ worker: PeriodicWorker) {
        workers.append(worker)
    }
    
    @objc public func start() {
        workTimer.resume()
    }
    
    @objc public func stop() {
        workTimer.pause()
    }
    
    @objc public func doPeriodicWork(_ completion: (() -> Void)? = nil) {
        let identifier = UUID().uuidString
        delegate?.workerControllerWillStart(self, workWithIdentifier: identifier)
        workers.asyncForEach({ (worker, completion) in
            worker.doPeriodicWork(completion)
        }) { [weak self] () in
            completion?()
            guard let strongSelf = self else {
                return
            }
            strongSelf.delegate?.workerControllerDidEnd(strongSelf, workWithIdentifier: identifier)
        }
    }
}
 | 
	9f7b294bad0f1376167d55aed02d373b | 31.384615 | 147 | 0.64133 | false | false | false | false | 
| 
	WhisperSystems/Signal-iOS | 
	refs/heads/master | 
	Signal/src/ViewControllers/ConversationView/ConversationViewController+OWS.swift | 
	gpl-3.0 | 
	1 | 
	//
//  Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
extension ConversationViewController {
    @objc
    func ensureIndexPath(of interaction: TSMessage) -> IndexPath? {
        return databaseStorage.uiReadReturningResult { transaction in
            self.conversationViewModel.ensureLoadWindowContainsInteractionId(interaction.uniqueId,
                                                                             transaction: transaction)
        }
    }
}
extension ConversationViewController: MediaPresentationContextProvider {
    func mediaPresentationContext(galleryItem: MediaGalleryItem, in coordinateSpace: UICoordinateSpace) -> MediaPresentationContext? {
        guard let indexPath = ensureIndexPath(of: galleryItem.message) else {
            owsFailDebug("indexPath was unexpectedly nil")
            return nil
        }
        // `indexPath(of:)` can change the load window which requires re-laying out our view
        // in order to correctly determine:
        //  - `indexPathsForVisibleItems`
        //  - the correct presentation frame
        collectionView.layoutIfNeeded()
        guard let visibleIndex = collectionView.indexPathsForVisibleItems.firstIndex(of: indexPath) else {
            // This could happen if, after presenting media, you navigated within the gallery
            // to media not withing the collectionView's visible bounds.
            return nil
        }
        guard let messageCell = collectionView.visibleCells[safe: visibleIndex] as? OWSMessageCell else {
            owsFailDebug("messageCell was unexpectedly nil")
            return nil
        }
        guard let mediaView = messageCell.messageBubbleView.albumItemView(forAttachment: galleryItem.attachmentStream) else {
            owsFailDebug("itemView was unexpectedly nil")
            return nil
        }
        guard let mediaSuperview = mediaView.superview else {
            owsFailDebug("mediaSuperview was unexpectedly nil")
            return nil
        }
        let presentationFrame = coordinateSpace.convert(mediaView.frame, from: mediaSuperview)
        // TODO exactly match corner radius for collapsed cells - maybe requires passing a masking view?
        return MediaPresentationContext(mediaView: mediaView, presentationFrame: presentationFrame, cornerRadius: kOWSMessageCellCornerRadius_Small * 2)
    }
    func snapshotOverlayView(in coordinateSpace: UICoordinateSpace) -> (UIView, CGRect)? {
        return nil
    }
    func mediaWillDismiss(toContext: MediaPresentationContext) {
        guard let messageBubbleView = toContext.messageBubbleView else { return }
        // To avoid flicker when transition view is animated over the message bubble,
        // we initially hide the overlaying elements and fade them in.
        messageBubbleView.footerView.alpha = 0
        messageBubbleView.bodyMediaGradientView?.alpha = 0.0
    }
    func mediaDidDismiss(toContext: MediaPresentationContext) {
        guard let messageBubbleView = toContext.messageBubbleView else { return }
        // To avoid flicker when transition view is animated over the message bubble,
        // we initially hide the overlaying elements and fade them in.
        let duration: TimeInterval = kIsDebuggingMediaPresentationAnimations ? 1.5 : 0.2
        UIView.animate(
            withDuration: duration,
            animations: {
                messageBubbleView.footerView.alpha = 1.0
                messageBubbleView.bodyMediaGradientView?.alpha = 1.0
        })
    }
}
private extension MediaPresentationContext {
    var messageBubbleView: OWSMessageBubbleView? {
        guard let messageBubbleView = mediaView.firstAncestor(ofType: OWSMessageBubbleView.self) else {
            owsFailDebug("unexpected mediaView: \(mediaView)")
            return nil
        }
        return messageBubbleView
    }
}
extension OWSMessageBubbleView {
    func albumItemView(forAttachment attachment: TSAttachmentStream) -> UIView? {
        guard let mediaAlbumCellView = bodyMediaView as? MediaAlbumCellView else {
            owsFailDebug("mediaAlbumCellView was unexpectedly nil")
            return nil
        }
        guard let albumItemView = (mediaAlbumCellView.itemViews.first { $0.attachment == attachment }) else {
            assert(mediaAlbumCellView.moreItemsView != nil)
            return mediaAlbumCellView.moreItemsView
        }
        return albumItemView
    }
}
 | 
	11ddd1b62bf2d26ae3a58541dbbe0ed2 | 40.148148 | 152 | 0.680693 | false | false | false | false | 
| 
	grandiere/box | 
	refs/heads/master | 
	box/Model/Store/Purchases/MStorePurchaseNetwork.swift | 
	mit | 
	1 | 
	import Foundation
class MStorePurchaseNetwork:MStoreItem
{
    private let kStorePurchaseId:String = "iturbide.box.network"
    
    init()
    {
        let title:String = NSLocalizedString("MStorePurchaseNetwork_title", comment:"")
        let descr:String = NSLocalizedString("MStorePurchaseNetwork_descr", comment:"")
        
        super.init(
            purchaseId:kStorePurchaseId,
            title:title,
            descr:descr)
    }
    
    override func purchaseAction()
    {
        MSession.sharedInstance.settings?.user?.addNetwork()
    }
    
    override func buyingError() -> String?
    {
        guard
            
            let network:Int16 = MSession.sharedInstance.settings?.user?.network
            
        else
        {
            return nil
        }
        
        if network >= DUser.kMaxStats
        {
            let error:String = NSLocalizedString("MStorePurchaseNetwork_buyingError", comment:"")
            
            return error
        }
        else
        {
            return nil
        }
    }
}
 | 
	98d9e8327c06c2048c79a0d9147a2aef | 22.533333 | 97 | 0.546742 | false | false | false | false | 
| 
	JayMobile/Strength | 
	refs/heads/master | 
	Charts/Classes/Charts/HorizontalBarChartView.swift | 
	apache-2.0 | 
	13 | 
	//
//  HorizontalBarChartView.swift
//  Charts
//
//  Created by Daniel Cohen Gindi on 4/3/15.
//
//  Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
//  A port of MPAndroidChart for iOS
//  Licensed under Apache License 2.0
//
//  https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
/// BarChart with horizontal bar orientation. In this implementation, x- and y-axis are switched.
public class HorizontalBarChartView: BarChartView
{
    internal override func initialize()
    {
        super.initialize()
        
        _leftAxisTransformer = ChartTransformerHorizontalBarChart(viewPortHandler: _viewPortHandler)
        _rightAxisTransformer = ChartTransformerHorizontalBarChart(viewPortHandler: _viewPortHandler)
        
        renderer = HorizontalBarChartRenderer(dataProvider: self, animator: _animator, viewPortHandler: _viewPortHandler)
        _leftYAxisRenderer = ChartYAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer)
        _rightYAxisRenderer = ChartYAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer)
        _xAxisRenderer = ChartXAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer, chart: self)
        
        _highlighter = HorizontalBarChartHighlighter(chart: self)
    }
    
    internal override func calculateOffsets()
    {
        var offsetLeft: CGFloat = 0.0,
        offsetRight: CGFloat = 0.0,
        offsetTop: CGFloat = 0.0,
        offsetBottom: CGFloat = 0.0
        
        // setup offsets for legend
        if (_legend !== nil && _legend.isEnabled)
        {
            if (_legend.position == .RightOfChart
                || _legend.position == .RightOfChartCenter)
            {
                offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0
            }
            else if (_legend.position == .LeftOfChart
                || _legend.position == .LeftOfChartCenter)
            {
                offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0
            }
            else if (_legend.position == .BelowChartLeft
                || _legend.position == .BelowChartRight
                || _legend.position == .BelowChartCenter)
            {
                // It's possible that we do not need this offset anymore as it
                //   is available through the extraOffsets, but changing it can mean
                //   changing default visibility for existing apps.
                let yOffset = _legend.textHeightMax
                
                offsetBottom += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent)
            }
            else if (_legend.position == .AboveChartLeft
                || _legend.position == .AboveChartRight
                || _legend.position == .AboveChartCenter)
            {
                // It's possible that we do not need this offset anymore as it
                //   is available through the extraOffsets, but changing it can mean
                //   changing default visibility for existing apps.
                let yOffset = _legend.textHeightMax
                
                offsetTop += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent)
            }
        }
        
        // offsets for y-labels
        if (_leftAxis.needsOffset)
        {
            offsetTop += _leftAxis.getRequiredHeightSpace()
        }
        
        if (_rightAxis.needsOffset)
        {
            offsetBottom += _rightAxis.getRequiredHeightSpace()
        }
        
        let xlabelwidth = _xAxis.labelRotatedWidth
        
        if (_xAxis.isEnabled)
        {
            // offsets for x-labels
            if (_xAxis.labelPosition == .Bottom)
            {
                offsetLeft += xlabelwidth
            }
            else if (_xAxis.labelPosition == .Top)
            {
                offsetRight += xlabelwidth
            }
            else if (_xAxis.labelPosition == .BothSided)
            {
                offsetLeft += xlabelwidth
                offsetRight += xlabelwidth
            }
        }
        
        offsetTop += self.extraTopOffset
        offsetRight += self.extraRightOffset
        offsetBottom += self.extraBottomOffset
        offsetLeft += self.extraLeftOffset
        
        _viewPortHandler.restrainViewPort(
            offsetLeft: max(self.minOffset, offsetLeft),
            offsetTop: max(self.minOffset, offsetTop),
            offsetRight: max(self.minOffset, offsetRight),
            offsetBottom: max(self.minOffset, offsetBottom))
        
        prepareOffsetMatrix()
        prepareValuePxMatrix()
    }
    
    internal override func prepareValuePxMatrix()
    {
        _rightAxisTransformer.prepareMatrixValuePx(chartXMin: _rightAxis.axisMinimum, deltaX: CGFloat(_rightAxis.axisRange), deltaY: _deltaX, chartYMin: _chartXMin)
        _leftAxisTransformer.prepareMatrixValuePx(chartXMin: _leftAxis.axisMinimum, deltaX: CGFloat(_leftAxis.axisRange), deltaY: _deltaX, chartYMin: _chartXMin)
    }
    internal override func calcModulus()
    {
        _xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelRotatedHeight) / (_viewPortHandler.contentHeight * viewPortHandler.touchMatrix.d)))
        
        if (_xAxis.axisLabelModulus < 1)
        {
            _xAxis.axisLabelModulus = 1
        }
    }
    
    public override func getBarBounds(e: BarChartDataEntry) -> CGRect!
    {
        let set = _data.getDataSetForEntry(e) as! BarChartDataSet!
        
        if (set === nil)
        {
            return nil
        }
        
        let barspace = set.barSpace
        let y = CGFloat(e.value)
        let x = CGFloat(e.xIndex)
        
        let spaceHalf = barspace / 2.0
        let top = x - 0.5 + spaceHalf
        let bottom = x + 0.5 - spaceHalf
        let left = y >= 0.0 ? y : 0.0
        let right = y <= 0.0 ? y : 0.0
        
        var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top)
        
        getTransformer(set.axisDependency).rectValueToPixel(&bounds)
        
        return bounds
    }
    
    public override func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint
    {
        var vals = CGPoint(x: CGFloat(e.value), y: CGFloat(e.xIndex))
        
        getTransformer(axis).pointValueToPixel(&vals)
        
        return vals
    }
    public override func getHighlightByTouchPoint(pt: CGPoint) -> ChartHighlight?
    {
        if (_dataNotSet || _data === nil)
        {
            print("Can't select by touch. No data set.", terminator: "\n")
            return nil
        }
        
        return _highlighter?.getHighlight(x: Double(pt.y), y: Double(pt.x))
    }
    
    public override var lowestVisibleXIndex: Int
    {
        let step = CGFloat(_data.dataSetCount)
        let div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace
        
        var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentBottom)
        getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt)
        
        return Int(((pt.y <= 0.0) ? 0.0 : pt.y / div) + 1.0)
    }
    
    public override var highestVisibleXIndex: Int
    {
        let step = CGFloat(_data.dataSetCount)
        let div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace
        
        var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentTop)
        getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt)
        
        return Int((pt.y >= CGFloat(chartXMax)) ? CGFloat(chartXMax) / div : (pt.y / div))
    }
} | 
	369b5edbd0f25db26fdec5befa05e859 | 37.1875 | 166 | 0.598338 | false | false | false | false | 
| 
	007HelloWorld/DouYuZhiBo | 
	refs/heads/develop | 
	Apps/Forum17/2017/Pods/Alamofire/Source/SessionDelegate.swift | 
	apache-2.0 | 
	117 | 
	//
//  SessionDelegate.swift
//
//  Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//
import Foundation
/// Responsible for handling all delegate callbacks for the underlying session.
open class SessionDelegate: NSObject {
    // MARK: URLSessionDelegate Overrides
    /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`.
    open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)?
    /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`.
    open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
    /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`.
    open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)?
    /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`.
    open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)?
    // MARK: URLSessionTaskDelegate Overrides
    /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`.
    open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
    /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and
    /// requires the caller to call the `completionHandler`.
    open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void)?
    /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`.
    open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
    /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and
    /// requires the caller to call the `completionHandler`.
    open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)?
    /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`.
    open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
    /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and
    /// requires the caller to call the `completionHandler`.
    open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, @escaping (InputStream?) -> Void) -> Void)?
    /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`.
    open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
    /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`.
    open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)?
    // MARK: URLSessionDataDelegate Overrides
    /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`.
    open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
    /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and
    /// requires caller to call the `completionHandler`.
    open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, @escaping (URLSession.ResponseDisposition) -> Void) -> Void)?
    /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`.
    open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
    /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`.
    open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
    /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`.
    open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
    /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and
    /// requires caller to call the `completionHandler`.
    open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, @escaping (CachedURLResponse?) -> Void) -> Void)?
    // MARK: URLSessionDownloadDelegate Overrides
    /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`.
    open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)?
    /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`.
    open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
    /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`.
    open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
    // MARK: URLSessionStreamDelegate Overrides
#if !os(watchOS)
    /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`.
    @available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
    open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? {
        get {
            return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void
        }
        set {
            _streamTaskReadClosed = newValue
        }
    }
    /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`.
    @available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
    open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? {
        get {
            return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void
        }
        set {
            _streamTaskWriteClosed = newValue
        }
    }
    /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`.
    @available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
    open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? {
        get {
            return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void
        }
        set {
            _streamTaskBetterRouteDiscovered = newValue
        }
    }
    /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`.
    @available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
    open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? {
        get {
            return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void
        }
        set {
            _streamTaskDidBecomeInputStream = newValue
        }
    }
    var _streamTaskReadClosed: Any?
    var _streamTaskWriteClosed: Any?
    var _streamTaskBetterRouteDiscovered: Any?
    var _streamTaskDidBecomeInputStream: Any?
#endif
    // MARK: Properties
    var retrier: RequestRetrier?
    weak var sessionManager: SessionManager?
    private var requests: [Int: Request] = [:]
    private let lock = NSLock()
    /// Access the task delegate for the specified task in a thread-safe manner.
    open subscript(task: URLSessionTask) -> Request? {
        get {
            lock.lock() ; defer { lock.unlock() }
            return requests[task.taskIdentifier]
        }
        set {
            lock.lock() ; defer { lock.unlock() }
            requests[task.taskIdentifier] = newValue
        }
    }
    // MARK: Lifecycle
    /// Initializes the `SessionDelegate` instance.
    ///
    /// - returns: The new `SessionDelegate` instance.
    public override init() {
        super.init()
    }
    // MARK: NSObject Overrides
    /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond
    /// to a specified message.
    ///
    /// - parameter selector: A selector that identifies a message.
    ///
    /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`.
    open override func responds(to selector: Selector) -> Bool {
        #if !os(macOS)
            if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) {
                return sessionDidFinishEventsForBackgroundURLSession != nil
            }
        #endif
        #if !os(watchOS)
            if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) {
                switch selector {
                case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)):
                    return streamTaskReadClosed != nil
                case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)):
                    return streamTaskWriteClosed != nil
                case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)):
                    return streamTaskBetterRouteDiscovered != nil
                case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)):
                    return streamTaskDidBecomeInputAndOutputStreams != nil
                default:
                    break
                }
            }
        #endif
        switch selector {
        case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)):
            return sessionDidBecomeInvalidWithError != nil
        case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)):
            return (sessionDidReceiveChallenge != nil  || sessionDidReceiveChallengeWithCompletion != nil)
        case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)):
            return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil)
        case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)):
            return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil)
        default:
            return type(of: self).instancesRespond(to: selector)
        }
    }
}
// MARK: - URLSessionDelegate
extension SessionDelegate: URLSessionDelegate {
    /// Tells the delegate that the session has been invalidated.
    ///
    /// - parameter session: The session object that was invalidated.
    /// - parameter error:   The error that caused invalidation, or nil if the invalidation was explicit.
    open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
        sessionDidBecomeInvalidWithError?(session, error)
    }
    /// Requests credentials from the delegate in response to a session-level authentication request from the
    /// remote server.
    ///
    /// - parameter session:           The session containing the task that requested authentication.
    /// - parameter challenge:         An object that contains the request for authentication.
    /// - parameter completionHandler: A handler that your delegate method must call providing the disposition
    ///                                and credential.
    open func urlSession(
        _ session: URLSession,
        didReceive challenge: URLAuthenticationChallenge,
        completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
    {
        guard sessionDidReceiveChallengeWithCompletion == nil else {
            sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
            return
        }
        var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
        var credential: URLCredential?
        if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
            (disposition, credential) = sessionDidReceiveChallenge(session, challenge)
        } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
            let host = challenge.protectionSpace.host
            if
                let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
                let serverTrust = challenge.protectionSpace.serverTrust
            {
                if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
                    disposition = .useCredential
                    credential = URLCredential(trust: serverTrust)
                } else {
                    disposition = .cancelAuthenticationChallenge
                }
            }
        }
        completionHandler(disposition, credential)
    }
#if !os(macOS)
    /// Tells the delegate that all messages enqueued for a session have been delivered.
    ///
    /// - parameter session: The session that no longer has any outstanding requests.
    open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
        sessionDidFinishEventsForBackgroundURLSession?(session)
    }
#endif
}
// MARK: - URLSessionTaskDelegate
extension SessionDelegate: URLSessionTaskDelegate {
    /// Tells the delegate that the remote server requested an HTTP redirect.
    ///
    /// - parameter session:           The session containing the task whose request resulted in a redirect.
    /// - parameter task:              The task whose request resulted in a redirect.
    /// - parameter response:          An object containing the server’s response to the original request.
    /// - parameter request:           A URL request object filled out with the new location.
    /// - parameter completionHandler: A closure that your handler should call with either the value of the request
    ///                                parameter, a modified URL request object, or NULL to refuse the redirect and
    ///                                return the body of the redirect response.
    open func urlSession(
        _ session: URLSession,
        task: URLSessionTask,
        willPerformHTTPRedirection response: HTTPURLResponse,
        newRequest request: URLRequest,
        completionHandler: @escaping (URLRequest?) -> Void)
    {
        guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
            taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
            return
        }
        var redirectRequest: URLRequest? = request
        if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
            redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
        }
        completionHandler(redirectRequest)
    }
    /// Requests credentials from the delegate in response to an authentication request from the remote server.
    ///
    /// - parameter session:           The session containing the task whose request requires authentication.
    /// - parameter task:              The task whose request requires authentication.
    /// - parameter challenge:         An object that contains the request for authentication.
    /// - parameter completionHandler: A handler that your delegate method must call providing the disposition
    ///                                and credential.
    open func urlSession(
        _ session: URLSession,
        task: URLSessionTask,
        didReceive challenge: URLAuthenticationChallenge,
        completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
    {
        guard taskDidReceiveChallengeWithCompletion == nil else {
            taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
            return
        }
        if let taskDidReceiveChallenge = taskDidReceiveChallenge {
            let result = taskDidReceiveChallenge(session, task, challenge)
            completionHandler(result.0, result.1)
        } else if let delegate = self[task]?.delegate {
            delegate.urlSession(
                session,
                task: task,
                didReceive: challenge,
                completionHandler: completionHandler
            )
        } else {
            urlSession(session, didReceive: challenge, completionHandler: completionHandler)
        }
    }
    /// Tells the delegate when a task requires a new request body stream to send to the remote server.
    ///
    /// - parameter session:           The session containing the task that needs a new body stream.
    /// - parameter task:              The task that needs a new body stream.
    /// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream.
    open func urlSession(
        _ session: URLSession,
        task: URLSessionTask,
        needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
    {
        guard taskNeedNewBodyStreamWithCompletion == nil else {
            taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
            return
        }
        if let taskNeedNewBodyStream = taskNeedNewBodyStream {
            completionHandler(taskNeedNewBodyStream(session, task))
        } else if let delegate = self[task]?.delegate {
            delegate.urlSession(session, task: task, needNewBodyStream: completionHandler)
        }
    }
    /// Periodically informs the delegate of the progress of sending body content to the server.
    ///
    /// - parameter session:                  The session containing the data task.
    /// - parameter task:                     The data task.
    /// - parameter bytesSent:                The number of bytes sent since the last time this delegate method was called.
    /// - parameter totalBytesSent:           The total number of bytes sent so far.
    /// - parameter totalBytesExpectedToSend: The expected length of the body data.
    open func urlSession(
        _ session: URLSession,
        task: URLSessionTask,
        didSendBodyData bytesSent: Int64,
        totalBytesSent: Int64,
        totalBytesExpectedToSend: Int64)
    {
        if let taskDidSendBodyData = taskDidSendBodyData {
            taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
        } else if let delegate = self[task]?.delegate as? UploadTaskDelegate {
            delegate.URLSession(
                session,
                task: task,
                didSendBodyData: bytesSent,
                totalBytesSent: totalBytesSent,
                totalBytesExpectedToSend: totalBytesExpectedToSend
            )
        }
    }
#if !os(watchOS)
    /// Tells the delegate that the session finished collecting metrics for the task.
    ///
    /// - parameter session: The session collecting the metrics.
    /// - parameter task:    The task whose metrics have been collected.
    /// - parameter metrics: The collected metrics.
    @available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
    @objc(URLSession:task:didFinishCollectingMetrics:)
    open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
        self[task]?.delegate.metrics = metrics
    }
#endif
    /// Tells the delegate that the task finished transferring data.
    ///
    /// - parameter session: The session containing the task whose request finished transferring data.
    /// - parameter task:    The task whose request finished transferring data.
    /// - parameter error:   If an error occurred, an error object indicating how the transfer failed, otherwise nil.
    open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        /// Executed after it is determined that the request is not going to be retried
        let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in
            guard let strongSelf = self else { return }
            strongSelf.taskDidComplete?(session, task, error)
            strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error)
            NotificationCenter.default.post(
                name: Notification.Name.Task.DidComplete,
                object: strongSelf,
                userInfo: [Notification.Key.Task: task]
            )
            strongSelf[task] = nil
        }
        guard let request = self[task], let sessionManager = sessionManager else {
            completeTask(session, task, error)
            return
        }
        // Run all validations on the request before checking if an error occurred
        request.validations.forEach { $0() }
        // Determine whether an error has occurred
        var error: Error? = error
        if request.delegate.error != nil {
            error = request.delegate.error
        }
        /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request
        /// should be retried. Otherwise, complete the task by notifying the task delegate.
        if let retrier = retrier, let error = error {
            retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in
                guard shouldRetry else { completeTask(session, task, error) ; return }
                DispatchQueue.utility.after(timeDelay) { [weak self] in
                    guard let strongSelf = self else { return }
                    let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false
                    if retrySucceeded, let task = request.task {
                        strongSelf[task] = request
                        return
                    } else {
                        completeTask(session, task, error)
                    }
                }
            }
        } else {
            completeTask(session, task, error)
        }
    }
}
// MARK: - URLSessionDataDelegate
extension SessionDelegate: URLSessionDataDelegate {
    /// Tells the delegate that the data task received the initial reply (headers) from the server.
    ///
    /// - parameter session:           The session containing the data task that received an initial reply.
    /// - parameter dataTask:          The data task that received an initial reply.
    /// - parameter response:          A URL response object populated with headers.
    /// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
    ///                                constant to indicate whether the transfer should continue as a data task or
    ///                                should become a download task.
    open func urlSession(
        _ session: URLSession,
        dataTask: URLSessionDataTask,
        didReceive response: URLResponse,
        completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
    {
        guard dataTaskDidReceiveResponseWithCompletion == nil else {
            dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
            return
        }
        var disposition: URLSession.ResponseDisposition = .allow
        if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
            disposition = dataTaskDidReceiveResponse(session, dataTask, response)
        }
        completionHandler(disposition)
    }
    /// Tells the delegate that the data task was changed to a download task.
    ///
    /// - parameter session:      The session containing the task that was replaced by a download task.
    /// - parameter dataTask:     The data task that was replaced by a download task.
    /// - parameter downloadTask: The new download task that replaced the data task.
    open func urlSession(
        _ session: URLSession,
        dataTask: URLSessionDataTask,
        didBecome downloadTask: URLSessionDownloadTask)
    {
        if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {
            dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
        } else {
            self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask)
        }
    }
    /// Tells the delegate that the data task has received some of the expected data.
    ///
    /// - parameter session:  The session containing the data task that provided data.
    /// - parameter dataTask: The data task that provided data.
    /// - parameter data:     A data object containing the transferred data.
    open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        if let dataTaskDidReceiveData = dataTaskDidReceiveData {
            dataTaskDidReceiveData(session, dataTask, data)
        } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate {
            delegate.urlSession(session, dataTask: dataTask, didReceive: data)
        }
    }
    /// Asks the delegate whether the data (or upload) task should store the response in the cache.
    ///
    /// - parameter session:           The session containing the data (or upload) task.
    /// - parameter dataTask:          The data (or upload) task.
    /// - parameter proposedResponse:  The default caching behavior. This behavior is determined based on the current
    ///                                caching policy and the values of certain received headers, such as the Pragma
    ///                                and Cache-Control headers.
    /// - parameter completionHandler: A block that your handler must call, providing either the original proposed
    ///                                response, a modified version of that response, or NULL to prevent caching the
    ///                                response. If your delegate implements this method, it must call this completion
    ///                                handler; otherwise, your app leaks memory.
    open func urlSession(
        _ session: URLSession,
        dataTask: URLSessionDataTask,
        willCacheResponse proposedResponse: CachedURLResponse,
        completionHandler: @escaping (CachedURLResponse?) -> Void)
    {
        guard dataTaskWillCacheResponseWithCompletion == nil else {
            dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler)
            return
        }
        if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
            completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
        } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate {
            delegate.urlSession(
                session,
                dataTask: dataTask,
                willCacheResponse: proposedResponse,
                completionHandler: completionHandler
            )
        } else {
            completionHandler(proposedResponse)
        }
    }
}
// MARK: - URLSessionDownloadDelegate
extension SessionDelegate: URLSessionDownloadDelegate {
    /// Tells the delegate that a download task has finished downloading.
    ///
    /// - parameter session:      The session containing the download task that finished.
    /// - parameter downloadTask: The download task that finished.
    /// - parameter location:     A file URL for the temporary file. Because the file is temporary, you must either
    ///                           open the file for reading or move it to a permanent location in your app’s sandbox
    ///                           container directory before returning from this delegate method.
    open func urlSession(
        _ session: URLSession,
        downloadTask: URLSessionDownloadTask,
        didFinishDownloadingTo location: URL)
    {
        if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
            downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
        } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
            delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
        }
    }
    /// Periodically informs the delegate about the download’s progress.
    ///
    /// - parameter session:                   The session containing the download task.
    /// - parameter downloadTask:              The download task.
    /// - parameter bytesWritten:              The number of bytes transferred since the last time this delegate
    ///                                        method was called.
    /// - parameter totalBytesWritten:         The total number of bytes transferred so far.
    /// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
    ///                                        header. If this header was not provided, the value is
    ///                                        `NSURLSessionTransferSizeUnknown`.
    open func urlSession(
        _ session: URLSession,
        downloadTask: URLSessionDownloadTask,
        didWriteData bytesWritten: Int64,
        totalBytesWritten: Int64,
        totalBytesExpectedToWrite: Int64)
    {
        if let downloadTaskDidWriteData = downloadTaskDidWriteData {
            downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
        } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
            delegate.urlSession(
                session,
                downloadTask: downloadTask,
                didWriteData: bytesWritten,
                totalBytesWritten: totalBytesWritten,
                totalBytesExpectedToWrite: totalBytesExpectedToWrite
            )
        }
    }
    /// Tells the delegate that the download task has resumed downloading.
    ///
    /// - parameter session:            The session containing the download task that finished.
    /// - parameter downloadTask:       The download task that resumed. See explanation in the discussion.
    /// - parameter fileOffset:         If the file's cache policy or last modified date prevents reuse of the
    ///                                 existing content, then this value is zero. Otherwise, this value is an
    ///                                 integer representing the number of bytes on disk that do not need to be
    ///                                 retrieved again.
    /// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
    ///                                 If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
    open func urlSession(
        _ session: URLSession,
        downloadTask: URLSessionDownloadTask,
        didResumeAtOffset fileOffset: Int64,
        expectedTotalBytes: Int64)
    {
        if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
            downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
        } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
            delegate.urlSession(
                session,
                downloadTask: downloadTask,
                didResumeAtOffset: fileOffset,
                expectedTotalBytes: expectedTotalBytes
            )
        }
    }
}
// MARK: - URLSessionStreamDelegate
#if !os(watchOS)
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
extension SessionDelegate: URLSessionStreamDelegate {
    /// Tells the delegate that the read side of the connection has been closed.
    ///
    /// - parameter session:    The session.
    /// - parameter streamTask: The stream task.
    open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) {
        streamTaskReadClosed?(session, streamTask)
    }
    /// Tells the delegate that the write side of the connection has been closed.
    ///
    /// - parameter session:    The session.
    /// - parameter streamTask: The stream task.
    open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) {
        streamTaskWriteClosed?(session, streamTask)
    }
    /// Tells the delegate that the system has determined that a better route to the host is available.
    ///
    /// - parameter session:    The session.
    /// - parameter streamTask: The stream task.
    open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) {
        streamTaskBetterRouteDiscovered?(session, streamTask)
    }
    /// Tells the delegate that the stream task has been completed and provides the unopened stream objects.
    ///
    /// - parameter session:      The session.
    /// - parameter streamTask:   The stream task.
    /// - parameter inputStream:  The new input stream.
    /// - parameter outputStream: The new output stream.
    open func urlSession(
        _ session: URLSession,
        streamTask: URLSessionStreamTask,
        didBecome inputStream: InputStream,
        outputStream: OutputStream)
    {
        streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream)
    }
}
#endif
 | 
	e938eb270848729462f6b0fb11bc9f3c | 48.112656 | 192 | 0.67504 | false | false | false | false | 
| 
	sonsongithub/reddift | 
	refs/heads/master | 
	application/String+reddift.swift | 
	mit | 
	1 | 
	//
//  String+reddift.swift
//  reddift
//
//  Created by sonson on 2016/07/18.
//  Copyright © 2016年 sonson. All rights reserved.
//
import Foundation
import JavaScriptCore
private let regexFor404: NSRegularExpression! = {
    do {
        return try NSRegularExpression(pattern: "<title>.*?404.*?</title>", options: NSRegularExpression.Options.caseInsensitive)
    } catch {
        assert(true, "Fatal error: \(#file) \(#line)")
        return nil
    }
}()
private let imgurImageURLFromHeaderMetaTag: NSRegularExpression! = {
    do {
        return try NSRegularExpression(pattern: "<meta(\\s+)property=\"og:image\"(\\s+)content=\"(.+?)(\\?.+){0,1}\"(\\s+)/>", options: NSRegularExpression.Options.caseInsensitive)
    } catch {
        assert(true, "Fatal error: \(#file) \(#line)")
        return nil
    }
    
}()
private let imgurVideoURLFromHeaderMetaTag: NSRegularExpression! = {
    do {
        return try NSRegularExpression(pattern: "<meta(\\s+)property=\"og:video\"(\\s+)content=\"(.+?)(\\?.+){0,1}\"(\\s+)/>", options: NSRegularExpression.Options.caseInsensitive)
    } catch {
        assert(true, "Fatal error: \(#file) \(#line)")
        return nil
    }
    
}()
private let regexForImageJSON: NSRegularExpression! = {
    do {
        return try NSRegularExpression(pattern: "window.runSlots = (\\{.+?\\};)", options: [.caseInsensitive, .dotMatchesLineSeparators])
    } catch {
        assert(false, "Fatal error: \(#file) \(#line) - \(error)")
        return nil
    }
}()
extension NSString {
    var fullRange: NSRange {
        get {
            return NSRange(location: 0, length: self.length)
        }
    }
}
extension String {
    
    var md5: String {
        let str = self.cString(using: String.Encoding.utf8)
        let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        
        CC_MD5(str!, strLen, result)
        
        let hash = NSMutableString()
        for i in 0..<digestLen {
            hash.appendFormat("%02x", result[i])
        }
        
        result.deallocate()
        
        return String(format: hash as String)
    }
    
    /**
    */
    var fullRange: NSRange {
        get {
            return NSRange(location: 0, length: self.utf16.count)
        }
    }
    
    /**
     Check whether this string includes "```<title>.*?404.*?</title>```" or not.
    */
    var is404OfImgurcom: Bool {
        get {
            let results404 = regexFor404.matches(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count))
            return (results404.count > 0)
        }
    }
    
    /**
     */
    func extractImgurImageURLFromAlbum(parentID: String) -> [Thumbnail] {
        guard let result = regexForImageJSON.firstMatch(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count)) else { return [] }
        
        let json = (self as NSString).substring(with: result.range(at: 1))
        let script = "var dict = \(json)"
        let js = JSContext()
        guard let _ = js?.evaluateScript(script), let dict = js?.objectForKeyedSubscript("dict").toDictionary() else { return [] }
        guard let items = dict["_item"] as? [String: AnyObject],
            let albumItems = items["album_images"] as? [String: AnyObject],
            let images = albumItems["images"] as? [[String: AnyObject]],
            let _ = albumItems["count"] else { return [] }
        return images.compactMap({
            if let hash = $0["hash"] as? String, let ext = $0["ext"] as? String {
                return "https://i.imgur.com/\(hash)\(ext)" as String
            }
            return nil
        }).compactMap({
            URL(string: $0)
        }).compactMap({
            Thumbnail.Image(imageURL: $0, parentID: parentID)
        })
    }
    
    /**
     */
    func extractImgurImageURLFromSingleImage(parentID: String) -> [Thumbnail] {
        guard let result = imgurImageURLFromHeaderMetaTag.firstMatch(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count)) else { return [] }
        let range = result.range(at: 3)
        let urlstring = (self as NSString).substring(with: range)
        return [URL(string: urlstring)].compactMap({$0}).compactMap({
            Thumbnail.Image(imageURL: $0, parentID: parentID)
        })
    }
    
    func extractImgurMovieOrImageURL(parentID: String) -> Thumbnail? {
        var thumbnailURL: URL?
        var movieURL: URL?
        
        if let result = imgurImageURLFromHeaderMetaTag.firstMatch(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count)) {
            let range = result.range(at: 3)
            let urlstring = (self as NSString).substring(with: range)
            thumbnailURL = URL(string: urlstring)
        }
        
        if let result = imgurVideoURLFromHeaderMetaTag.firstMatch(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count)) {
            let range = result.range(at: 3)
            let urlstring = (self as NSString).substring(with: range)
            movieURL = URL(string: urlstring)
        }
        
        if let thumbnailURL = thumbnailURL, let movieURL = movieURL {
            return Thumbnail.Movie(movieURL: movieURL, thumbnailURL: thumbnailURL, parentID: parentID)
        } else if let thumbnailURL = thumbnailURL {
            return Thumbnail.Image(imageURL: thumbnailURL, parentID: parentID)
        }
        return nil
    }
    
    /**
     Extract image URL from html text of imgur.com.
     Strictly speaking, this method parses javascript source code of html using JavascriptCore.framework.
     - parameter html: HTML text which is downloaded from imgur.com and has image url list.
     - returns: Array of ThumbnailInfo objects. They include image urls.
     */
    func extractImgurImageURL(parentID: String) -> [Thumbnail] {
        let urls = extractImgurImageURLFromAlbum(parentID: parentID)
        if urls.count > 0 {
            return urls
        }
        if let thumbnail = extractImgurMovieOrImageURL(parentID: parentID) {
            return [thumbnail]
        }
        return []
    }
}
 | 
	d2263c44eae7f6d3fda3886d6c5a9e80 | 35.366279 | 180 | 0.597922 | false | false | false | false | 
| 
	ChrisAU/Swacman | 
	refs/heads/master | 
	Swacman/GameScene.swift | 
	mit | 
	1 | 
	//
//  GameScene.swift
//  Swacman
//
//  Created by Chris Nevin on 21/06/2015.
//  Copyright (c) 2015 CJNevin. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
	enum Direction {
		case Left
		case Right
		case Up
		case Down
	}
	class Swacman {
		lazy var openDirectionPaths = [Direction: UIBezierPath]()
		lazy var closedDirectionPaths = [Direction: UIBezierPath]()
		lazy var wasClosedPath = false
		lazy var needsToUpdateDirection = false
		lazy var direction = Direction.Right
		lazy var lastChange: NSTimeInterval = NSDate().timeIntervalSince1970
		let sprite = SKShapeNode(circleOfRadius: 15)
		init(_ position: CGPoint) {
			let radius: CGFloat = 15, diameter: CGFloat = 30, center = CGPoint(x:radius, y:radius)
			func createPaths(startDegrees: CGFloat, endDegrees: CGFloat, inout dictionary dic: [Direction: UIBezierPath]) {
				var path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startDegrees.toRadians(), endAngle: endDegrees.toRadians(), clockwise: true)
				path.addLineToPoint(center)
				path.closePath()
				dic[.Right] = path
				for d: Direction in [.Up, .Left, .Down] {
					path = path.pathByRotating(90)
					dic[d] = path
				}
			}
			createPaths(35, endDegrees: 315, dictionary: &openDirectionPaths)
			createPaths(1, endDegrees: 359, dictionary: &closedDirectionPaths)
			sprite.position = position
			sprite.fillColor = UIColor.yellowColor()
			sprite.lineWidth = 2
			if let path = openDirectionPaths[.Right] {
				sprite.path = path.CGPath
			}
			sprite.strokeColor = UIColor.blackColor()
			updateDirection()
		}
		
		func animateChomp() {
			if needsToUpdateDirection || NSDate().timeIntervalSince1970 - lastChange > 0.25 {
				if let path = wasClosedPath ? openDirectionPaths[direction]?.CGPath : closedDirectionPaths[direction]?.CGPath {
					sprite.path = path
				}
				wasClosedPath = !wasClosedPath
				lastChange = NSDate().timeIntervalSince1970
			}
		}
		
		func handleSwipe(from touchStartPoint: CGPoint, to touchEndPoint: CGPoint) {
			if touchStartPoint == touchEndPoint {
				return
			}
			let degrees = atan2(touchStartPoint.x - touchEndPoint.x,
				touchStartPoint.y - touchEndPoint.y).toDegrees()
			let oldDirection = direction
			switch Int(degrees) {
			case -135...(-45):	direction = .Right
			case -45...45:		direction = .Down
			case 45...135:		direction = .Left
			default:			direction = .Up
			}
			if (oldDirection != direction) {
				needsToUpdateDirection = true
			}
		}
		
		func updateDirection() {
			if !needsToUpdateDirection {
				return
			}
			sprite.removeActionForKey("Move")
			func actionForDirection() -> SKAction {
				let Delta: CGFloat = 25
				switch (direction) {
				case .Up:
					return SKAction.moveByX(0.0, y: Delta, duration: 0.1)
				case .Down:
					return SKAction.moveByX(0.0, y: -Delta, duration: 0.1)
				case .Right:
					return SKAction.moveByX(Delta, y: 0.0, duration: 0.1)
				default:
					return SKAction.moveByX(-Delta, y: 0.0, duration: 0.1)
				}
			}
			let action = SKAction.repeatActionForever(actionForDirection())
			sprite.runAction(action, withKey: "Move")
			needsToUpdateDirection = false
		}
	}
	
	var touchBeganPoint: CGPoint?
	var swacman: Swacman?
	
    override func didMoveToView(view: SKView) {
		let swac = Swacman(CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)))
		self.addChild(swac.sprite)
		swacman = swac
    }
	
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
		touchBeganPoint = positionOfTouch(inTouches: touches)
	}
	
	override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
		if let touchStartPoint = touchBeganPoint, touchEndPoint = positionOfTouch(inTouches: touches), swac = swacman {
			if touchStartPoint == touchEndPoint {
				return
			}
			swac.handleSwipe(from: touchStartPoint, to: touchEndPoint)
			touchBeganPoint = nil
		}
	}
	
	override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
		touchBeganPoint = nil
	}
   
    override func update(currentTime: CFTimeInterval) {
        if let nodes = self.children as? [SKShapeNode], swac = swacman {
			for node in nodes {
				let p = node.position
				let s = node.frame.size
				if p.x - s.width > self.size.width {
					node.position.x = -s.width
				}
				if p.y - s.height > self.size.height {
					node.position.y = -s.height
				}
				if p.x < -s.width {
					node.position.x = self.size.width + (s.width / 2)
				}
				if p.y < -s.height {
					node.position.y = self.size.height + (s.height / 2)
				}
				if node == swac.sprite {
					swac.animateChomp()
					swac.updateDirection()
				}
			}
		}
    }
	
	// MARK:- Helpers
	
	func positionOfTouch(inTouches touches: Set<NSObject>) -> CGPoint? {
		for touch in (touches as! Set<UITouch>) {
			let location = touch.locationInNode(self)
			return location
		}
		return nil
	}
}
 | 
	acc79edc755094163b5dfea97691bfac | 28.852761 | 151 | 0.680641 | false | false | false | false | 
| 
	motocodeltd/MCAssertReflectiveEqual | 
	refs/heads/master | 
	Example/Tests/Tester.swift | 
	mit | 
	1 | 
	//
// Created by Stefanos Zachariadis first name at last name dot net
// Copyright (c) 2017 motocode ltd. All rights reserved. MIT license
//
import Foundation
@testable import MCAssertReflectiveEqual
class Tester {
    private var equal: Bool?
    private func failFunction(message: String, file: StaticString, line: UInt) {
        equal = false
    }
    private func nsObjectCheckFunction(expected: NSObject, actual: NSObject, message: String, file: StaticString, line: UInt) {
        if let equal = equal {
            if (!equal) {
                return
            }
        }
        equal = actual == expected
    }
    private func optionalStringFunction(expected: String?, actual: String?, message: String, file: StaticString, line: UInt) {
        if let equal = equal {
            if (!equal) {
                return
            }
        }
        equal = actual == expected
    }
    func areEqual<T>(_ expected: T, _ actual: T, matchers: [Matcher] = []) -> Bool {
        equal = nil
        internalMCAssertReflectiveEqual(expected, actual, matchers: matchers,
                nsObjectCheckFunction: nsObjectCheckFunction,
                optionalStringEqualsFunction: optionalStringFunction,
                failFunction: failFunction)
        return equal ?? true
    }
} | 
	e6fbc55236ebcf77da7019b7695490d8 | 29.97619 | 127 | 0.611538 | false | false | false | false | 
| 
	msahins/myTV | 
	refs/heads/master | 
	SwiftRadio/InfoDetailViewController.swift | 
	mit | 
	1 | 
	
import UIKit
class InfoDetailViewController: UIViewController {
    
    @IBOutlet weak var stationImageView: UIImageView!
    @IBOutlet weak var stationNameLabel: UILabel!
    @IBOutlet weak var stationDescLabel: UILabel!
    @IBOutlet weak var stationLongDescTextView: UITextView!
    @IBOutlet weak var okayButton: UIButton!
    
    var currentStation: RadioStation!
    var downloadTask: NSURLSessionDownloadTask?
    //*****************************************************************
    // MARK: - ViewDidLoad
    //*****************************************************************
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupStationText()
        setupStationLogo()
    }
    deinit {
        // Be a good citizen.
        downloadTask?.cancel()
        downloadTask = nil
    }
    
    //*****************************************************************
    // MARK: - UI Helpers
    //*****************************************************************
    
    func setupStationText() {
        
        // Display Station Name & Short Desc
        stationNameLabel.text = currentStation.stationName
        stationDescLabel.text = currentStation.stationDesc
        
        // Display Station Long Desc
        if currentStation.stationLongDesc == "" {
            loadDefaultText()
        } else {
            stationLongDescTextView.text = currentStation.stationLongDesc
        }
    }
    
    func loadDefaultText() {
        // Add your own default ext
        stationLongDescTextView.text = "Swift TV izliyorsunuz. Bu tatlı küçük projeyi hemen arkadaşlarınıza söyleyin!"
    }
    
    func setupStationLogo() {
        
        // Display Station Image/Logo
        let imageURL = currentStation.stationImageURL
        
        if imageURL.rangeOfString("http") != nil {
            // Get station image from the web, iOS should cache the image
            if let url = NSURL(string: currentStation.stationImageURL) {
                downloadTask = stationImageView.loadImageWithURL(url) { _ in }
            }
            
        } else if imageURL != "" {
            // Get local station image
            stationImageView.image = UIImage(named: imageURL)
            
        } else {
            // Use default image if station image not found
            stationImageView.image = UIImage(named: "stationImage")
        }
        
        // Apply shadow to Station Image
        stationImageView.applyShadow()
    }
    
    //*****************************************************************
    // MARK: - IBActions
    //*****************************************************************
    
    @IBAction func okayButtonPressed(sender: UIButton) {
        navigationController?.popViewControllerAnimated(true)
    }
    
}
 | 
	bb0f8f5aad84475921d1dd0f9c40fa15 | 31.252874 | 118 | 0.515681 | false | false | false | false | 
| 
	atuooo/notGIF | 
	refs/heads/master | 
	notGIF/Views/Base/NavigationTitleLabel.swift | 
	mit | 
	1 | 
	//
//  NavigationTitleLabel.swift
//  notGIF
//
//  Created by Atuooo on 23/07/2017.
//  Copyright © 2017 xyz. All rights reserved.
//
import UIKit
class NavigationTitleLabel: UILabel {
    override var text: String? {
        didSet {
            super.text = text
            sizeToFit()
            layoutIfNeeded()
        }
    }
    
    init(title: String? = "") {
        super.init(frame: .zero)
        
        text = title
        textColor = UIColor.textTint
        textAlignment = .center
        font = UIFont.localized(ofSize: 18)
        numberOfLines = 0
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
 | 
	018268c8b10fb7312bcc98e2d7e00efa | 20.242424 | 59 | 0.560628 | false | false | false | false | 
| 
	blockchain/My-Wallet-V3-iOS | 
	refs/heads/master | 
	Modules/Platform/Sources/PlatformKit/Models/Balance/PairExchangeService.swift | 
	lgpl-3.0 | 
	1 | 
	// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import MoneyKit
import RxRelay
import RxSwift
public protocol PairExchangeServiceAPI: AnyObject {
    /// The current fiat exchange price.
    /// The implementer should implement this as a `.shared(replay: 1)`
    /// resource for efficiency among multiple clients.
    func fiatPrice(at time: PriceTime) -> Observable<FiatValue>
    /// A trigger that force the service to fetch the updated price.
    /// Handy to call on currency type and value changes
    var fetchTriggerRelay: PublishRelay<Void> { get }
}
public final class PairExchangeService: PairExchangeServiceAPI {
    // TODO: Network failure
    /// Fetches the fiat price, and shares its stream with other
    /// subscribers to keep external API usage count in check.
    /// Also handles currency code change
    public func fiatPrice(at time: PriceTime) -> Observable<FiatValue> {
        Observable
            .combineLatest(
                fiatCurrencyService.displayCurrencyPublisher.asObservable(),
                fetchTriggerRelay.asObservable().startWith(())
            )
            .throttle(.milliseconds(250), scheduler: ConcurrentDispatchQueueScheduler(qos: .background))
            .map(\.0)
            .flatMapLatest(weak: self) { (self, fiatCurrency) -> Observable<PriceQuoteAtTime> in
                self.priceService
                    .price(of: self.currency, in: fiatCurrency, at: time)
                    .asSingle()
                    .catchAndReturn(
                        PriceQuoteAtTime(
                            timestamp: time.date,
                            moneyValue: .zero(currency: fiatCurrency),
                            marketCap: nil
                        )
                    )
                    .asObservable()
            }
            // There MUST be a fiat value here
            .map { $0.moneyValue.fiatValue! }
            .catchError(weak: self) { (self, _) -> Observable<FiatValue> in
                self.zero
            }
            .distinctUntilChanged()
            .share(replay: 1)
    }
    private var zero: Observable<FiatValue> {
        fiatCurrencyService
            .displayCurrencyPublisher
            .map(FiatValue.zero)
            .asObservable()
    }
    /// A trigger for a fetch
    public let fetchTriggerRelay = PublishRelay<Void>()
    // MARK: - Services
    /// The exchange service
    private let priceService: PriceServiceAPI
    /// The currency service
    private let fiatCurrencyService: FiatCurrencyServiceAPI
    /// The associated currency
    private let currency: Currency
    // MARK: - Setup
    public init(
        currency: Currency,
        priceService: PriceServiceAPI = resolve(),
        fiatCurrencyService: FiatCurrencyServiceAPI
    ) {
        self.currency = currency
        self.priceService = priceService
        self.fiatCurrencyService = fiatCurrencyService
    }
}
 | 
	2a8a055c9370ebde9c98dc92fe874425 | 32.280899 | 104 | 0.604659 | false | false | false | false | 
| 
	yulingtianxia/Spiral | 
	refs/heads/master | 
	Spiral/Background.swift | 
	apache-2.0 | 
	1 | 
	//
//  Background.swift
//  Spiral
//
//  Created by 杨萧玉 on 14-10-10.
//  Copyright (c) 2014年 杨萧玉. All rights reserved.
//
import SpriteKit
/**
*  游戏背景绘制
*/
class Background: SKSpriteNode {
    init(size:CGSize, imageName:String?=nil){
        let imageString:String
        if imageName == nil {
            switch Data.sharedData.currentMode {
            case .ordinary:
                imageString = "bg_ordinary"
            case .zen:
                imageString = "bg_zen"
            case .maze:
                imageString = "bg_maze"
            }
        }
        else{
            imageString = imageName!
        }
        
        var resultTexture = SKTexture(imageNamed: imageString)
        if let bgImage = UIImage(named: imageString) {
            let xScale = size.width / bgImage.size.width
            let yScale = size.height / bgImage.size.height
            let scale = max(xScale, yScale)
            let scaleSize = CGSize(width: xScale / scale, height: yScale / scale)
            let scaleOrigin = CGPoint(x: (1 - scaleSize.width) / 2, y: (1 - scaleSize.height) / 2)
            if let cgimage = bgImage.cgImage?.cropping(to: CGRect(origin: CGPoint(x: scaleOrigin.x * bgImage.size.width, y: scaleOrigin.y * bgImage.size.height), size: CGSize(width: scaleSize.width * bgImage.size.width, height: scaleSize.height * bgImage.size.height))) {
                resultTexture = SKTexture(cgImage: cgimage)
            }
        }
        
        
        super.init(texture: resultTexture, color:SKColor.clear, size: size)
        normalTexture = resultTexture.generatingNormalMap(withSmoothness: 0.2, contrast: 2.5)
        zPosition = -100
        alpha = 0.5
        let light = SKLightNode()
        switch Data.sharedData.currentMode {
        case .ordinary:
            light.lightColor = SKColor.black
            light.ambientColor = SKColor.black
        case .zen:
            light.lightColor = SKColor.brown
            light.ambientColor = SKColor.brown
        case .maze:
            light.lightColor = SKColor.black
            light.ambientColor = SKColor.black
        }
        
        light.categoryBitMask = bgLightCategory
        lightingBitMask = playerLightCategory|killerLightCategory|scoreLightCategory|shieldLightCategory|bgLightCategory|reaperLightCategory
        addChild(light)
    }
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
 | 
	44e9442135c1b3d615b816ffcf79e35e | 34.623188 | 271 | 0.599268 | false | false | false | false | 
| 
	mozilla-mobile/firefox-ios | 
	refs/heads/main | 
	Client/Frontend/Reader/View/ReaderModeStyleViewModel.swift | 
	mpl-2.0 | 
	1 | 
	// 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
// MARK: - ReaderModeStyleViewModel
struct ReaderModeStyleViewModel {
    static let RowHeight = 50.0
    // For top or bottom presentation
    static let PresentationSpace = 13.0
    static let SeparatorLineThickness = 1.0
    static let Width = 270.0
    static let Height = 4.0 * RowHeight + 3.0 * SeparatorLineThickness
    static let BrightnessSliderWidth = 140
    static let BrightnessIconOffset = 10
    var isBottomPresented: Bool
    var readerModeStyle: ReaderModeStyle = DefaultReaderModeStyle
    var fontTypeOffset: CGFloat {
        return isBottomPresented ? 0 : ReaderModeStyleViewModel.PresentationSpace
    }
    var brightnessRowOffset: CGFloat {
        return isBottomPresented ? -ReaderModeStyleViewModel.PresentationSpace : 0
    }
}
 | 
	d6d86c2be585f40e593883aabb971f94 | 30.774194 | 82 | 0.732995 | false | false | false | false | 
| 
	wuhduhren/Mr-Ride-iOS | 
	refs/heads/master | 
	Mr-Ride-iOS/Model/CoreData/RunDataModel.swift | 
	mit | 
	1 | 
	//
//  RunData.swift
//  Mr-Ride-iOS
//
//  Created by Eph on 2016/6/3.
//  Copyright © 2016年 AppWorks School WuDuhRen. All rights reserved.
//
import Foundation
import CoreData
class RunDataModel {
    
    class runDataStruct {
        var date: NSDate?
        var distance: Double?
        var speed: Double?
        var calories: Double?
        var time: String?
        var polyline: NSData?
        var objectID: NSManagedObjectID?
    }
    
    private let context = DataController().managedObjectContext
    var runDataStructArray: [runDataStruct] = []
    
    
    func getData() -> [runDataStruct] {
        do {
            let getRequest = NSFetchRequest(entityName: "Entity")
            let sortDesriptor = NSSortDescriptor(key: "date", ascending: true)
            getRequest.sortDescriptors = [sortDesriptor]
            
            let data = try context.executeFetchRequest(getRequest)
            runDataStructArray = [] //reset
            for eachData in data {
                let tempStruct = runDataStruct()
                tempStruct.date = eachData.valueForKey("date")! as? NSDate
                tempStruct.distance = eachData.valueForKey("distance")! as? Double
                tempStruct.speed = eachData.valueForKey("speed")! as? Double
                tempStruct.calories = eachData.valueForKey("calories")! as? Double
                tempStruct.time = eachData.valueForKey("time")! as? String
                tempStruct.polyline = eachData.valueForKey("polyline")! as? NSData
                tempStruct.objectID = eachData.objectID
                runDataStructArray.append(tempStruct)
            }
            
            return runDataStructArray
        } catch {
            fatalError("error appear when fetching")
        }
    }
   
}
 | 
	ec51f6ad051eac163d55591993fa7c89 | 31.436364 | 82 | 0.59417 | false | false | false | false | 
| 
	ShamylZakariya/Squizit | 
	refs/heads/master | 
	Squizit/ViewControllers/GalleryViewController.swift | 
	mit | 
	1 | 
	//
//  GalleryCollectionViewController.swift
//  Squizit
//
//  Created by Shamyl Zakariya on 8/29/14.
//  Copyright (c) 2014 Shamyl Zakariya. All rights reserved.
//
import Foundation
import UIKit
let LOG_THUMBNAIL_RENDERING_LIFECYCLE = true
// MARK: - GalleryViewControllerDelegate
protocol GalleryViewControllerDelegate : class {
	func galleryDidDismiss( galleryViewController:AnyObject )
}
// MARK: - GalleryCollectionViewCell
let WigglePhaseDuration:NSTimeInterval = 0.2
let WiggleAngleMax = 0.75 * M_PI / 180.0
class GalleryCollectionViewCell : UICollectionViewCell {
	class func identifier() -> String { return "GalleryCollectionViewCell" }
	@IBOutlet weak var deleteButton: UIImageView!
	@IBOutlet weak var imageView: UIImageView!
	@IBOutlet weak var label: UILabel!
	@IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
	@IBOutlet weak var imageViewWidthConstraint: NSLayoutConstraint!
	private var deleting:Bool = false
	private let cycleOffset:NSTimeInterval = drand48() * M_PI_2
	private var phase:NSTimeInterval = 0
	private var wiggleAnimationDisplayLink:CADisplayLink?
	var drawing:GalleryDrawing?
	var indexInCollection:Int = 0
	var onLongPress:((( cell:GalleryCollectionViewCell )->())?)
	var onDeleteButtonTapped:((( cell:GalleryCollectionViewCell )->())?)
	var deleteButtonVisible:Bool = false {
		didSet {
			if deleteButtonVisible != oldValue {
				if deleteButtonVisible {
					self.showDeleteButton()
					startWiggling()
				} else {
					self.hideDeleteButton()
					stopWiggling()
				}
			}
		}
	}
	var thumbnail:UIImage? { return imageView.image }
	override func awakeFromNib() {
		super.awakeFromNib()
		clipsToBounds = false
		// uncomment to help debug layout
		//backgroundColor = UIColor(hue: CGFloat(drand48()), saturation: 1, brightness: 0.5, alpha: 0.5)
		deleteButton.alpha = 0
		deleteButton.hidden = true
		//imageView.clipsToBounds = true
		imageView.contentMode = UIViewContentMode.ScaleAspectFit
		// add shadows because we're a little skeumorphic here
		imageView.layer.shouldRasterize = true
		imageView.layer.shadowColor = UIColor.blackColor().CGColor
		imageView.layer.shadowOffset = CGSize(width: 0, height: 2)
		imageView.layer.shadowOpacity = 1
		imageView.layer.shadowRadius = 4
		addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(GalleryCollectionViewCell.longPress(_:))))
		deleteButton.userInteractionEnabled = true
		deleteButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(GalleryCollectionViewCell.deleteButtonTapped(_:))))
		// common initialization
		prepareForReuse()
	}
	override func prepareForReuse() {
		drawing = nil
		// reset layer transform and nil the image
		layer.transform = CATransform3DIdentity
		layer.opacity = 1
		setThumbnail(nil, animate: false)
	}
	func setThumbnail(thumbnail:UIImage?,animate:Bool) {
		imageView.image = thumbnail
		if let thumbnail = thumbnail {
			setNeedsLayout()
			layoutIfNeeded()
			let padding:CGFloat = 10
			let aspect = thumbnail.size.width / thumbnail.size.height
			let maxImageViewWidth = frame.width - 2*padding
			let maxImageViewHeight = frame.height - imageView.frame.minY - 72
			var imageHeight = label.frame.minY - padding - imageView.frame.minY
			var imageWidth = imageHeight * aspect
			if imageWidth > maxImageViewWidth {
				imageWidth = maxImageViewWidth
				imageHeight = imageWidth / aspect
			}
			if imageHeight > maxImageViewHeight {
				let scale = maxImageViewHeight / imageHeight
				imageHeight *= scale
				imageWidth *= scale
			}
			imageViewHeightConstraint.constant = imageHeight
			imageViewWidthConstraint.constant = imageWidth
			if animate {
				UIView.animateWithDuration(0.3) {
					self.imageView.alpha = 1
				}
			} else {
				imageView.alpha = 1
			}
		} else {
			imageView.alpha = 0
		}
		setNeedsLayout()
	}
	dynamic func longPress( gr:UILongPressGestureRecognizer ) {
		switch gr.state {
			case UIGestureRecognizerState.Began:
				self.onLongPress?(cell:self)
			default: break;
		}
	}
	dynamic func deleteButtonTapped( tr:UITapGestureRecognizer ) {
		// flag that we're deleting - this halts the wiggle animation which would override our scale transform
		deleting = true
		let layer = self.layer
		let onDeleteButtonTapped = self.onDeleteButtonTapped
		UIView.animateWithDuration(0.2,
			animations: {
				let scale = CATransform3DMakeScale(0.1, 0.1, 1)
				layer.transform = CATransform3DConcat(layer.transform, scale)
				layer.opacity = 0
			}) {
				(complete:Bool) -> Void in
				onDeleteButtonTapped?(cell:self)
			}
	}
	func showDeleteButton() {
		let deleteButton = self.deleteButton
		UIView.animateWithDuration(0.2, animations: { () -> Void in
			deleteButton.hidden = false
			deleteButton.alpha = 1
		})
	}
	func hideDeleteButton() {
		let deleteButton = self.deleteButton
		UIView.animateWithDuration(0.2,
			animations: {
				deleteButton.alpha = 0
			},
			completion:{
				(complete:Bool) -> Void in
				if complete {
					deleteButton.hidden = true
				}
			})
	}
	func startWiggling() {
		wiggleAnimationDisplayLink = CADisplayLink(target: self, selector: #selector(GalleryCollectionViewCell.updateWiggleAnimation))
		wiggleAnimationDisplayLink!.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
	}
	dynamic func updateWiggleAnimation() {
		if deleting {
			return
		}
		let now = NSDate().timeIntervalSinceReferenceDate
		let cycle = now / WigglePhaseDuration
		let sign = (indexInCollection % 2 == 0) ? +1.0 : -1.0
		let phase = sin(cycle * M_PI + cycleOffset * M_PI ) * sign
		let angle = CGFloat(phase * WiggleAngleMax)
		let layer = self.layer
		UIView.performWithoutAnimation { () -> Void in
			layer.transform = CATransform3DMakeRotation( angle, 0, 0, 1)
		}
	}
	func stopWiggling() {
		if let displayLink = wiggleAnimationDisplayLink {
			displayLink.invalidate()
			wiggleAnimationDisplayLink = nil
		}
		let layer = self.layer
		layer.removeAllAnimations()
		UIView.animateWithDuration( WigglePhaseDuration, animations: {
			layer.transform = CATransform3DIdentity
		})
	}
}
// MARK: - GalleryOverviewCollectionViewDataSource
class GalleryCollectionViewDataSource : BasicGalleryCollectionViewDataSource {
	private var thumbnailCompositorQueue = dispatch_queue_create("com.zakariya.squizit.GalleryThumbnailCompositorQueue", nil)
	private var thumbnailBackgroundColor = SquizitTheme.thumbnailBackgroundColor()
	private var renderedIconCache = NSCache()
	override init( store:GalleryStore, collectionView:UICollectionView ) {
		super.init(store: store, collectionView:collectionView)
	}
	var editMode:Bool = false {
		didSet {
			for cell in collectionView.visibleCells() {
				(cell as! GalleryCollectionViewCell).deleteButtonVisible = editMode
			}
			editModeChanged?( inEditMode: editMode )
		}
	}
	var editModeChanged:((inEditMode:Bool)->Void)?
	override var cellIdentifier:String {
		return GalleryCollectionViewCell.identifier()
	}
	override var fetchBatchSize:Int {
		return 16
	}
	var artistNameFilter:String? {
		didSet {
			var predicate:NSPredicate? = nil
			if artistNameFilter != oldValue {
				if let filter = artistNameFilter {
					if !filter.isEmpty {
						predicate = NSPredicate(format: "SUBQUERY(artists, $artist, $artist.name CONTAINS[cd] \"\(filter)\").@count > 0")
					}
				}
			}
			self.filterPredicate = predicate
		}
	}
	// MARK: UICollectionViewDelegate
	var galleryDrawingTapped:((drawing:GalleryDrawing,indexPath:NSIndexPath)->Void)?
	func collectionView(collectionView: UICollectionView!, didSelectItemAtIndexPath indexPath: NSIndexPath!) {
		collectionView.deselectItemAtIndexPath(indexPath, animated: true)
		if !editMode {
			if let handler = galleryDrawingTapped, drawing = self.fetchedResultsController.objectAtIndexPath(indexPath) as? GalleryDrawing {
				handler( drawing: drawing, indexPath: indexPath )
			}
		}
	}
	override func configureCell( cell:UICollectionViewCell, atIndexPath indexPath:NSIndexPath ) {
		if let drawing = self.fetchedResultsController.objectAtIndexPath(indexPath) as? GalleryDrawing {
			let galleryCell = cell as! GalleryCollectionViewCell
			galleryCell.drawing = drawing
			let nameAttrs = [
				NSFontAttributeName: UIFont(name: "Baskerville", size: 12)!,
				NSForegroundColorAttributeName: UIColor.whiteColor()
			]
			let dateAttrs = [
				NSFontAttributeName: UIFont(name: "Baskerville-Italic", size: 12)!,
				NSForegroundColorAttributeName: UIColor.whiteColor().colorWithAlphaComponent(0.7)
			]
			let attributedText = NSMutableAttributedString(string: drawing.artistDisplayNames, attributes: nameAttrs)
			attributedText.appendAttributedString(NSAttributedString(string: "\n" + dateFormatter.stringFromDate(NSDate(timeIntervalSinceReferenceDate: drawing.date)),attributes: dateAttrs))
			galleryCell.label.attributedText = attributedText
			galleryCell.deleteButtonVisible = self.editMode
			// set the index in collection to aid in wiggle cycle direction (odd/even wiggle in different directions)
			galleryCell.indexInCollection = indexPath.item
			galleryCell.onLongPress = {
				[weak self]
				(cell:GalleryCollectionViewCell)->() in
				if let sself = self {
					if !sself.editMode {
						sself.editMode = true
					}
				}
			}
			galleryCell.onDeleteButtonTapped = {
				[weak self]
				(cell:GalleryCollectionViewCell)->() in
				if let sself = self {
					sself.store.managedObjectContext?.deleteObject(drawing)
					sself.store.save()
				}
			}
			let cache = renderedIconCache
			if let thumbnail = cache.objectForKey(drawing.uuid) as? UIImage {
				// no need to animate, since the thumbnail is already available
				galleryCell.setThumbnail(thumbnail, animate: false)
			} else {
				let flowLayout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
				let itemSize = flowLayout.itemSize
				let thumbnailHeight = itemSize.height
				let queue = thumbnailCompositorQueue
				dispatch_async( queue ) {
					// render a thumbnail that is the max possible size for our layout
					var thumbnail = UIImage( data: drawing.thumbnail )!
					let size = CGSize( width: round(thumbnail.size.width * thumbnailHeight / thumbnail.size.height), height: thumbnailHeight )
					let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
					thumbnail = thumbnail.imageByScalingToSize(size, contentMode: .ScaleAspectFit, scale: 0)
					UIGraphicsBeginImageContextWithOptions(size, true, 0)
					self.thumbnailBackgroundColor.set()
					UIRectFillUsingBlendMode(rect, CGBlendMode.Normal)
					thumbnail.drawAtPoint(CGPoint.zero, blendMode: CGBlendMode.Multiply, alpha: 1)
					thumbnail = UIGraphicsGetImageFromCurrentImageContext()
					UIGraphicsEndImageContext()
					// we're done - add to icon cache and finish
					cache.setObject(thumbnail, forKey: drawing.uuid)
					dispatch_main {
						// only assign if the cell wasn't recycled while we rendered
						if galleryCell.drawing === drawing {
							// animate, because we had to wait for rendering to complete
							galleryCell.setThumbnail(thumbnail, animate: true)
						}
					}
				}
			}
		} else {
			assertionFailure("Unable to vend a GalleryDrawing for index path")
		}
	}
	lazy var dateFormatter:NSDateFormatter = {
		let dateFormatter = NSDateFormatter()
		dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
		dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
		return dateFormatter
	}()
}
// MARK: - GalleryViewController
class GalleryViewController : UIViewController, UITextFieldDelegate {
	@IBOutlet weak var collectionView: UICollectionView!
	var store:GalleryStore!
	weak var delegate:GalleryViewControllerDelegate?
	private var dataSource:GalleryCollectionViewDataSource!
	private var searchField = SquizitThemeSearchField(frame: CGRect.zero )
	private var fixedHeaderView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Dark))
	private let fixedHeaderHeight:CGFloat = 60
	required init?(coder aDecoder: NSCoder) {
		super.init( coder: aDecoder )
		self.title = "Gallery"
	}
	deinit {
		NSNotificationCenter.defaultCenter().removeObserver(self)
	}
	override func viewDidLoad() {
		super.viewDidLoad()
		collectionView.backgroundColor = SquizitTheme.galleryBackgroundColor()
		dataSource = GalleryCollectionViewDataSource(store: store, collectionView: collectionView )
		dataSource.editModeChanged = {
			[weak self] ( inEditMode:Bool ) -> Void in
			if let sself = self {
				if inEditMode {
					sself.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: sself, action: #selector(GalleryViewController.onDoneEditing(_:)))
				} else {
					sself.navigationItem.rightBarButtonItem = nil
				}
			}
		}
		dataSource.galleryDrawingTapped = {
			[weak self] ( drawing:GalleryDrawing, indexPath:NSIndexPath ) in
			if let sself = self {
				sself.showDetail( drawing, indexPath:indexPath )
			}
		}
		self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Close", style: .Done, target: self, action: #selector(GalleryViewController.onClose(_:)))
		//
		//	Create the fixed header view
		//
		searchField.delegate = self
		searchField.placeholder = "Who drew..."
		searchField.returnKeyType = UIReturnKeyType.Search
		searchField.addTarget(self, action: #selector(GalleryViewController.searchTextChanged(_:)), forControlEvents: UIControlEvents.EditingChanged)
		fixedHeaderView.addSubview(searchField)
		view.addSubview(fixedHeaderView)
		//
		//	Make room for fixed header
		//
		collectionView.contentInset = UIEdgeInsets(top: fixedHeaderHeight, left: 0, bottom: 0, right: 0)
		//
		//	Listen for keyboard did dismiss to resign first responder - this handles when user hits the 
		//	keyboard dismiss key. I want the search field to lose focus
		//
		NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GalleryViewController.keyboardDidDismiss(_:)), name: UIKeyboardDidHideNotification, object: nil)
	}
	private var suggestedItemWidth:CGFloat {
		if traitCollection.horizontalSizeClass == .Compact || traitCollection.verticalSizeClass == .Compact {
			return 160
		} else {
			return 256
		}
	}
	override func viewWillLayoutSubviews() {
		super.viewWillLayoutSubviews()
		let aspect:CGFloat = 360.0 / 300.0
		let suggestedItemWidth = self.suggestedItemWidth
		let suggestedItemSize = CGSize(width:suggestedItemWidth, height: suggestedItemWidth*aspect)
		let itemWidth = floor(view.bounds.width / round(view.bounds.width / suggestedItemSize.width))
		let itemHeight = round(suggestedItemSize.height)
		let flowLayout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
		flowLayout.itemSize = CGSize(width:itemWidth, height:itemHeight)
		collectionView.reloadData()
		//	Layout the fixed-position header containing the search field
		let headerFrame = CGRect(x:0, y: self.topLayoutGuide.length, width: self.view.bounds.width, height: fixedHeaderHeight)
		fixedHeaderView.frame = headerFrame
		let bounds = fixedHeaderView.bounds
		let margin:CGFloat = 20
		let searchFieldHeight:CGFloat = searchField.intrinsicContentSize().height
		let searchFieldFrame = CGRect(x: margin, y: bounds.midY - searchFieldHeight/2, width: bounds.width-2*margin, height: searchFieldHeight)
		searchField.frame = searchFieldFrame
	}
	override func preferredStatusBarStyle() -> UIStatusBarStyle {
		return UIStatusBarStyle.LightContent
	}
	override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
		if segue.identifier == "showPageDetail" {
			if let detailVC = segue.destinationViewController as? GalleryDetailPageViewController {
				if let indexPath = sender as? NSIndexPath {
					detailVC.store = store
					detailVC.filterPredicate = dataSource.filterPredicate
					detailVC.initialIndex = indexPath.item
				} else {
					assertionFailure("Didn't pass indexPath")
				}
			} else {
				assertionFailure("coun't grab the detail vc from segue")
			}
		}
	}
	// MARK: IBActions
	dynamic func onClose(sender: AnyObject) {
		delegate?.galleryDidDismiss(self)
	}
	dynamic func onDoneEditing( sender:AnyObject ) {
		dataSource.editMode = false
	}
	// MARK: UITextFieldDelegate
	dynamic func searchTextChanged( sender:UITextField ) {
		if sender === searchField {
			artistFilter = searchField.text ?? ""
		}
	}
	func textFieldShouldEndEditing(textField: UITextField) -> Bool {
		if textField === searchField {}
		return true
	}
	func textFieldShouldReturn(textField: UITextField) -> Bool {
		if textField === searchField {
			textField.resignFirstResponder()
		}
		return true
	}
	func textFieldDidEndEditing(textField: UITextField) {
		if textField === searchField {
			textField.resignFirstResponder()
		}
	}
	func textFieldShouldClear(textField: UITextField) -> Bool {
		if textField === searchField {
			textField.resignFirstResponder()
		}
		return true
	}
	// MARK: Keyboard Handling
	dynamic func keyboardDidDismiss( note:NSNotification ) {
		view.endEditing(true)
	}
	// MARK: Private
	func showDetail( drawing:GalleryDrawing, indexPath:NSIndexPath ) {
		self.performSegueWithIdentifier("showPageDetail", sender: indexPath)
	}
	var artistFilter:String = "" {
		didSet {
			if _debouncedArtistFilterApplicator == nil {
				_debouncedArtistFilterApplicator = debounce(0.1) {
					[weak self] () -> () in
					if let sself = self {
						sself.dataSource.artistNameFilter = sself.artistFilter
							.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
							.capitalizedStringWithLocale(NSLocale.currentLocale())
					}
				}
			}
			_debouncedArtistFilterApplicator!()
		}
	}
	var _debouncedArtistFilterApplicator:((()->())?)
}
 | 
	036977cbd2f03c131801c3094d8bea28 | 28.289735 | 181 | 0.741846 | false | false | false | false | 
| 
	YoungGary/Sina | 
	refs/heads/master | 
	Sina/Sina/Classes/Profile我/ProfileViewController.swift | 
	apache-2.0 | 
	1 | 
	//
//  ProfileViewController.swift
//  Sina
//
//  Created by YOUNG on 16/9/4.
//  Copyright © 2016年 Young. All rights reserved.
//
import UIKit
class ProfileViewController: BaseViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
       visitorView.setupVisitorViewInfo("visitordiscover_image_profile", text: "登录后,你的微博,相册,个人资料,会显示在这里 展示给别人")
    }
    
    // MARK: - Table view data source
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 0
    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 0
    }
    /*
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
        // Configure the cell...
        return cell
    }
    */
    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */
    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */
    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
    }
    */
    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */
    /*
    // MARK: - Navigation
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
}
 | 
	d164a64f566fbbf7b634bc1bcfb1e7c3 | 31.431818 | 157 | 0.6822 | false | false | false | false | 
| 
	OneBusAway/onebusaway-iphone | 
	refs/heads/develop | 
	Carthage/Checkouts/SwiftEntryKit/Source/MessageViews/Notes/EKAccessoryNoteMessageView.swift | 
	apache-2.0 | 
	3 | 
	//
//  EKAccessoryNoteMessageView.swift
//  SwiftEntryKit
//
//  Created by Daniel Huri on 5/4/18.
//
import UIKit
public class EKAccessoryNoteMessageView: UIView {
    // MARK: Props
    private let contentView = UIView()
    private var noteMessageView: EKNoteMessageView!
    var accessoryView: UIView!
    func setup(with content: EKProperty.LabelContent) {
        clipsToBounds = true
        
        addSubview(contentView)
        contentView.layoutToSuperview(.centerX, .top, .bottom)
        contentView.layoutToSuperview(.left, relation: .greaterThanOrEqual, offset: 16)
        contentView.layoutToSuperview(.right, relation: .lessThanOrEqual, offset: -16)
        
        noteMessageView = EKNoteMessageView(with: content)
        noteMessageView.horizontalOffset = 8
        noteMessageView.verticalOffset = 7
        contentView.addSubview(noteMessageView)
        noteMessageView.layoutToSuperview(.top, .bottom, .trailing)
        
        contentView.addSubview(accessoryView)
        accessoryView.layoutToSuperview(.leading, .centerY)
        accessoryView.layout(.trailing, to: .leading, of: noteMessageView)
    }
}
 | 
	4601ef8c6e02defe22de3a1d119a2fc2 | 31.685714 | 87 | 0.697552 | false | false | false | false | 
| 
	nvh/DataSourceable | 
	refs/heads/master | 
	DataSourceable/CollectionViewDataSource.swift | 
	mit | 
	1 | 
	//
//  CollectionViewDataSource.swift
//  DataSourceable
//
//  Created by Niels van Hoorn on 29/12/15.
//  Copyright © 2015 Zeker Waar. All rights reserved.
//
public protocol CollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView
    func collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool
    func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath)
}
public extension CollectionViewDataSource {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        return collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "", forIndexPath: indexPath)
    }
    func collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }
    func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
    }
}
public extension CollectionViewDataSource where Self: Sectionable {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return numberOfItems(inSection: section)
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return numberOfSections
    }
}
public extension CollectionViewDataSource where Self: Sectionable, Self: CollectionViewCellProviding, Self.CollectionViewCellType.ItemType == Self.Section.Data.Element {
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let identifier = reuseIdentifier(forIndexPath: indexPath)
        guard let item = item(atIndexPath: indexPath) else {
            return UICollectionViewCell()
        }
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath)
        if let cell = cell as? CollectionViewCellType, view = collectionView as? CollectionViewCellType.ContainingViewType {
            cell.configure(forItem: item, inView: view)
        }
        return cell
    }
}
 | 
	d61fc1f459497548332a9c2948b481b6 | 51.709091 | 171 | 0.779579 | false | false | false | false | 
| 
	mrdepth/EVEUniverse | 
	refs/heads/master | 
	Legacy/Neocom/Neocom/NCFittingImplantSetViewController.swift | 
	lgpl-2.1 | 
	2 | 
	//
//  NCFittingImplantSetViewController.swift
//  Neocom
//
//  Created by Artem Shimanski on 21.08.17.
//  Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import CoreData
import EVEAPI
import Futures
class NCImplantSetRow: NCFetchedResultsObjectNode<NCImplantSet> {
	
	required init(object: NCImplantSet) {
		super.init(object: object)
		cellIdentifier = Prototype.NCDefaultTableViewCell.default.reuseIdentifier
	}
	
	lazy var subtitle: NSAttributedString? = {
		guard let invTypes = NCDatabase.sharedDatabase?.invTypes else {return nil}
		let font = UIFont.preferredFont(forTextStyle: .footnote)
		
		var ids = self.object.data?.implantIDs ?? []
		ids.append(contentsOf: self.object.data?.boosterIDs ?? [])
		
		
		return ids.compactMap { typeID -> NSAttributedString? in
			guard let type = invTypes[typeID] else {return nil}
			guard let typeName = type.typeName else {return nil}
			if let image = type.icon?.image?.image ?? NCDBEveIcon.defaultType.image?.image {
				return NSAttributedString(image: image, font: font) + typeName
			}
			else {
				return NSAttributedString(string: typeName)
			}
			}.reduce((NSAttributedString(), 0), { (a, b) -> (NSAttributedString, Int) in
				let i = a.1
				let a = a.0
				return i == 3 ? (a + "\n" + "...", i + 1) :
					i > 3 ? (a, i + 1) :
					i == 0 ? (b, 1) :
					(a + "\n" + b, i + 1)
			}).0
	}()
	
	override func configure(cell: UITableViewCell) {
		guard let cell = cell as? NCDefaultTableViewCell else {return}
		cell.titleLabel?.text = object.name
		cell.subtitleLabel?.attributedText = (subtitle?.length ?? 0) > 0 ? subtitle : NSAttributedString(string: NSLocalizedString("Empty", comment: ""))
	}
}
class NCImplantSetSection: FetchedResultsNode<NCImplantSet> {
	init(managedObjectContext: NSManagedObjectContext) {
		let request = NSFetchRequest<NCImplantSet>(entityName: "ImplantSet")
		request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
		let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
		super.init(resultsController: results, sectionNode: nil, objectNode: NCImplantSetRow.self)
//		cellIdentifier = Prototype.NCHeaderTableViewCell.empty.reuseIdentifier
	}
}
class NCFittingImplantSetViewController: NCTreeViewController {
	
	var implantSetData: NCImplantSetData?
	var completionHandler: ((NCFittingImplantSetViewController, NCImplantSet) -> Void)?
	
	enum Mode {
		case load
		case save
	}
	
	var mode: Mode = .load
	
	override func viewDidLoad() {
		super.viewDidLoad()
		
		navigationItem.rightBarButtonItem = editButtonItem
		
		tableView.register([Prototype.NCActionTableViewCell.default,
		                    Prototype.NCDefaultTableViewCell.default,
		                    Prototype.NCHeaderTableViewCell.empty])
	}
	
	override func didReceiveMemoryWarning() {
		super.didReceiveMemoryWarning()
		// Dispose of any resources that can be recreated.
	}
	
	override func content() -> Future<TreeNode?> {
		var sections = [TreeNode]()
		if mode == .save {
			let save = NCActionRow(title: NSLocalizedString("Create New Implant Set", comment: "").uppercased())
			sections.append(RootNode([save]))
		}
		
		sections.append(NCImplantSetSection(managedObjectContext: NCStorage.sharedStorage!.viewContext))
		return .init(RootNode(sections))
	}
	
	override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) {
		super.treeController(treeController, didSelectCellWithNode: node)
		
		if node is NCActionRow {
			guard let implantSetData = implantSetData else {return}
			guard let context = NCStorage.sharedStorage?.viewContext else {return}
			
			let controller = UIAlertController(title: NSLocalizedString("Enter Implant Set Name", comment: ""), message: nil, preferredStyle: .alert)
			
			var textField: UITextField?
			
			controller.addTextField(configurationHandler: {
				textField = $0
				textField?.clearButtonMode = .always
			})
			
			controller.addAction(UIAlertAction(title: NSLocalizedString("Create", comment: ""), style: .default, handler: { [weak self] _ in
				let implantSet = NCImplantSet(entity: NSEntityDescription.entity(forEntityName: "ImplantSet", in: context)!, insertInto: context)
				implantSet.data = implantSetData
				implantSet.name = textField?.text
				if context.hasChanges {
					try? context.save()
				}
				
				self?.dismiss(animated: true, completion: nil)
				
			}))
			
			controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil))
			
			self.present(controller, animated: true, completion: nil)
		}
		else if let row = node as? NCImplantSetRow {
			let implantSet = row.object
			if isEditing {
				let controller = UIAlertController(title: NSLocalizedString("Rename", comment: ""), message: nil, preferredStyle: .alert)
				
				var textField: UITextField?
				
				controller.addTextField(configurationHandler: {
					textField = $0
					textField?.text = implantSet.name
					textField?.clearButtonMode = .always
				})
				
				controller.addAction(UIAlertAction(title: NSLocalizedString("Save", comment: ""), style: .default, handler: { _ in
					implantSet.name = textField?.text
					if implantSet.managedObjectContext?.hasChanges == true {
						try? implantSet.managedObjectContext?.save()
					}
					
				}))
				
				controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil))
				present(controller, animated: true, completion: nil)
			}
			else {
				if mode == .save {
					guard let implantSetData = implantSetData else {return}
					
					let controller = UIAlertController(title: nil, message: NSLocalizedString("Are you sure you want to replace this set?", comment: ""), preferredStyle: .alert)
					
					controller.addAction(UIAlertAction(title: NSLocalizedString("Replace", comment: ""), style: .default, handler: { [weak self] _ in
						implantSet.data = implantSetData
						if implantSet.managedObjectContext?.hasChanges == true {
							try? implantSet.managedObjectContext?.save()
						}
						
						self?.dismiss(animated: true, completion: nil)
						
					}))
					
					controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil))
					
					present(controller, animated: true, completion: nil)
					
				}
				else {
					completionHandler?(self, implantSet)
				}
			}
		}
		
		
	}
	
	func treeController(_ treeController: TreeController, editActionsForNode node: TreeNode) -> [UITableViewRowAction]? {
		guard let row = node as? NCImplantSetRow else {return nil}
		let object = row.object
		return [UITableViewRowAction(style: .destructive, title: NSLocalizedString("Delete", comment: "")) { _,_  in
			object.managedObjectContext?.delete(object)
			if object.managedObjectContext?.hasChanges == true {
				try? object.managedObjectContext?.save()
			}
		}]
	}
}
 | 
	2694509d92328fc2eef3162b8c4b4200 | 33.701493 | 162 | 0.705233 | false | false | false | false | 
| 
	abertelrud/swift-package-manager | 
	refs/heads/main | 
	Sources/Commands/PackageTools/APIDiff.swift | 
	apache-2.0 | 
	2 | 
	//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import ArgumentParser
import Basics
import CoreCommands
import Dispatch
import PackageGraph
import PackageModel
import SourceControl
import TSCBasic
struct DeprecatedAPIDiff: ParsableCommand {
    static let configuration = CommandConfiguration(commandName: "experimental-api-diff",
                                                    abstract: "Deprecated - use `swift package diagnose-api-breaking-changes` instead",
                                                    shouldDisplay: false)
    @Argument(parsing: .unconditionalRemaining)
    var args: [String] = []
    func run() throws {
        print("`swift package experimental-api-diff` has been renamed to `swift package diagnose-api-breaking-changes`")
        throw ExitCode.failure
    }
}
struct APIDiff: SwiftCommand {
    static let configuration = CommandConfiguration(
        commandName: "diagnose-api-breaking-changes",
        abstract: "Diagnose API-breaking changes to Swift modules in a package",
        discussion: """
        The diagnose-api-breaking-changes command can be used to compare the Swift API of \
        a package to a baseline revision, diagnosing any breaking changes which have \
        been introduced. By default, it compares every Swift module from the baseline \
        revision which is part of a library product. For packages with many targets, this \
        behavior may be undesirable as the comparison can be slow. \
        The `--products` and `--targets` options may be used to restrict the scope of \
        the comparison.
        """)
    @OptionGroup(_hiddenFromHelp: true)
    var globalOptions: GlobalOptions
    @Option(help: """
    The path to a text file containing breaking changes which should be ignored by the API comparison. \
    Each ignored breaking change in the file should appear on its own line and contain the exact message \
    to be ignored (e.g. 'API breakage: func foo() has been removed').
    """)
    var breakageAllowlistPath: AbsolutePath?
    @Argument(help: "The baseline treeish to compare to (e.g. a commit hash, branch name, tag, etc.)")
    var treeish: String
    @Option(parsing: .upToNextOption,
            help: "One or more products to include in the API comparison. If present, only the specified products (and any targets specified using `--targets`) will be compared.")
    var products: [String] = []
    @Option(parsing: .upToNextOption,
            help: "One or more targets to include in the API comparison. If present, only the specified targets (and any products specified using `--products`) will be compared.")
    var targets: [String] = []
    @Option(name: .customLong("baseline-dir"),
            help: "The path to a directory used to store API baseline files. If unspecified, a temporary directory will be used.")
    var overrideBaselineDir: AbsolutePath?
    @Flag(help: "Regenerate the API baseline, even if an existing one is available.")
    var regenerateBaseline: Bool = false
    func run(_ swiftTool: SwiftTool) throws {
        let apiDigesterPath = try swiftTool.getDestinationToolchain().getSwiftAPIDigester()
        let apiDigesterTool = SwiftAPIDigester(fileSystem: swiftTool.fileSystem, tool: apiDigesterPath)
        let packageRoot = try globalOptions.locations.packageDirectory ?? swiftTool.getPackageRoot()
        let repository = GitRepository(path: packageRoot)
        let baselineRevision = try repository.resolveRevision(identifier: treeish)
        // We turn build manifest caching off because we need the build plan.
        let buildSystem = try swiftTool.createBuildSystem(explicitBuildSystem: .native, cacheBuildManifest: false)
        let packageGraph = try buildSystem.getPackageGraph()
        let modulesToDiff = try determineModulesToDiff(
            packageGraph: packageGraph,
            observabilityScope: swiftTool.observabilityScope
        )
        // Build the current package.
        try buildSystem.build()
        // Dump JSON for the baseline package.
        let baselineDumper = try APIDigesterBaselineDumper(
            baselineRevision: baselineRevision,
            packageRoot: swiftTool.getPackageRoot(),
            buildParameters: try buildSystem.buildPlan.buildParameters,
            apiDigesterTool: apiDigesterTool,
            observabilityScope: swiftTool.observabilityScope
        )
        let baselineDir = try baselineDumper.emitAPIBaseline(
            for: modulesToDiff,
            at: overrideBaselineDir,
            force: regenerateBaseline,
            logLevel: swiftTool.logLevel,
            swiftTool: swiftTool
        )
        let results = ThreadSafeArrayStore<SwiftAPIDigester.ComparisonResult>()
        let group = DispatchGroup()
        let semaphore = DispatchSemaphore(value: Int(try buildSystem.buildPlan.buildParameters.jobs))
        var skippedModules: Set<String> = []
        for module in modulesToDiff {
            let moduleBaselinePath = baselineDir.appending(component: "\(module).json")
            guard swiftTool.fileSystem.exists(moduleBaselinePath) else {
                print("\nSkipping \(module) because it does not exist in the baseline")
                skippedModules.insert(module)
                continue
            }
            semaphore.wait()
            DispatchQueue.sharedConcurrent.async(group: group) {
                do {
                    if let comparisonResult = try apiDigesterTool.compareAPIToBaseline(
                        at: moduleBaselinePath,
                        for: module,
                        buildPlan: try buildSystem.buildPlan,
                        except: breakageAllowlistPath
                    ) {
                        results.append(comparisonResult)
                    }
                } catch {
                    swiftTool.observabilityScope.emit(error: "failed to compare API to baseline: \(error)")
                }
                semaphore.signal()
            }
        }
        group.wait()
        let failedModules = modulesToDiff
            .subtracting(skippedModules)
            .subtracting(results.map(\.moduleName))
        for failedModule in failedModules {
            swiftTool.observabilityScope.emit(error: "failed to read API digester output for \(failedModule)")
        }
        for result in results.get() {
            try self.printComparisonResult(result, observabilityScope: swiftTool.observabilityScope)
        }
        guard failedModules.isEmpty && results.get().allSatisfy(\.hasNoAPIBreakingChanges) else {
            throw ExitCode.failure
        }
    }
    private func determineModulesToDiff(packageGraph: PackageGraph, observabilityScope: ObservabilityScope) throws -> Set<String> {
        var modulesToDiff: Set<String> = []
        if products.isEmpty && targets.isEmpty {
            modulesToDiff.formUnion(packageGraph.apiDigesterModules)
        } else {
            for productName in products {
                guard let product = packageGraph
                        .rootPackages
                        .flatMap(\.products)
                        .first(where: { $0.name == productName }) else {
                    observabilityScope.emit(error: "no such product '\(productName)'")
                    continue
                }
                guard product.type.isLibrary else {
                    observabilityScope.emit(error: "'\(productName)' is not a library product")
                    continue
                }
                modulesToDiff.formUnion(product.targets.filter { $0.underlyingTarget is SwiftTarget }.map(\.c99name))
            }
            for targetName in targets {
                guard let target = packageGraph
                        .rootPackages
                        .flatMap(\.targets)
                        .first(where: { $0.name == targetName }) else {
                    observabilityScope.emit(error: "no such target '\(targetName)'")
                    continue
                }
                guard target.type == .library else {
                    observabilityScope.emit(error: "'\(targetName)' is not a library target")
                    continue
                }
                guard target.underlyingTarget is SwiftTarget else {
                    observabilityScope.emit(error: "'\(targetName)' is not a Swift language target")
                    continue
                }
                modulesToDiff.insert(target.c99name)
            }
            guard !observabilityScope.errorsReported else {
                throw ExitCode.failure
            }
        }
        return modulesToDiff
    }
    private func printComparisonResult(
        _ comparisonResult: SwiftAPIDigester.ComparisonResult,
        observabilityScope: ObservabilityScope
    ) throws {
        for diagnostic in comparisonResult.otherDiagnostics {
            let metadata = try diagnostic.location.map { location -> ObservabilityMetadata in
                var metadata = ObservabilityMetadata()
                metadata.fileLocation = .init(
                    try .init(validating: location.filename),
                    line: location.line < Int.max ? Int(location.line) : .none
                )
                return metadata
            }
            switch diagnostic.level {
            case .error, .fatal:
                observabilityScope.emit(error: diagnostic.text, metadata: metadata)
            case .warning:
                observabilityScope.emit(warning: diagnostic.text, metadata: metadata)
            case .note:
                observabilityScope.emit(info: diagnostic.text, metadata: metadata)
            case .remark:
                observabilityScope.emit(info: diagnostic.text, metadata: metadata)
            case .ignored:
                break
            }
        }
        let moduleName = comparisonResult.moduleName
        if comparisonResult.apiBreakingChanges.isEmpty {
            print("\nNo breaking changes detected in \(moduleName)")
        } else {
            let count = comparisonResult.apiBreakingChanges.count
            print("\n\(count) breaking \(count > 1 ? "changes" : "change") detected in \(moduleName):")
            for change in comparisonResult.apiBreakingChanges {
                print("  💔 \(change.text)")
            }
        }
    }
}
 | 
	b6518e556d87e2f74ffe4730774b0cfc | 42.96748 | 179 | 0.608635 | false | false | false | false | 
| 
	almcintyre/PagingMenuController | 
	refs/heads/master | 
	Example/PagingMenuControllerDemo2/RootViewControoler.swift | 
	mit | 
	3 | 
	//
//  RootViewControoler.swift
//  PagingMenuControllerDemo
//
//  Created by Cheng-chien Kuo on 5/14/16.
//  Copyright © 2016 kitasuke. All rights reserved.
//
import UIKit
import PagingMenuController
private struct PagingMenuOptions: PagingMenuControllerCustomizable {
    private let viewController1 = ViewController1()
    private let viewController2 = ViewController2()
    
    fileprivate var componentType: ComponentType {
        return .all(menuOptions: MenuOptions(), pagingControllers: pagingControllers)
    }
    
    fileprivate var pagingControllers: [UIViewController] {
        return [viewController1, viewController2]
    }
    
    fileprivate struct MenuOptions: MenuViewCustomizable {
        var displayMode: MenuDisplayMode {
            return .segmentedControl
        }
        var itemsOptions: [MenuItemViewCustomizable] {
            return [MenuItem1(), MenuItem2()]
        }
    }
    
    fileprivate struct MenuItem1: MenuItemViewCustomizable {
        var displayMode: MenuItemDisplayMode {
            return .text(title: MenuItemText(text: "First Menu"))
        }
    }
    fileprivate struct MenuItem2: MenuItemViewCustomizable {
        var displayMode: MenuItemDisplayMode {
            return .text(title: MenuItemText(text: "Second Menu"))
        }
    }
}
class RootViewControoler: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        view.backgroundColor = UIColor.white
        
        let options = PagingMenuOptions()
        let pagingMenuController = PagingMenuController(options: options)
        pagingMenuController.view.frame.origin.y += 64
        pagingMenuController.view.frame.size.height -= 64
        pagingMenuController.onMove = { state in
            switch state {
            case let .willMoveController(menuController, previousMenuController):
                print(previousMenuController)
                print(menuController)
            case let .didMoveController(menuController, previousMenuController):
                print(previousMenuController)
                print(menuController)
            case let .willMoveItem(menuItemView, previousMenuItemView):
                print(previousMenuItemView)
                print(menuItemView)
            case let .didMoveItem(menuItemView, previousMenuItemView):
                print(previousMenuItemView)
                print(menuItemView)
            case .didScrollStart:
                print("Scroll start")
            case .didScrollEnd:
                print("Scroll end")
            }
        }
        
        addChildViewController(pagingMenuController)
        view.addSubview(pagingMenuController.view)
        pagingMenuController.didMove(toParentViewController: self)
    }
}
 | 
	d114d8f0e92ad24aec6e1ac5cca001a3 | 34.5 | 85 | 0.653873 | false | false | false | false | 
| 
	JohnSansoucie/MyProject2 | 
	refs/heads/master | 
	BlueCapKit/External/SimpleFutures/FutureStream.swift | 
	mit | 
	1 | 
	//
//  FutureStream.swift
//  BlueCapKit
//
//  Created by Troy Stribling on 12/7/14.
//  Copyright (c) 2014 gnos.us. All rights reserved.
//
import Foundation
public class StreamPromise<T> {
    public let future : FutureStream<T>
    
    public init() {
        self.future = FutureStream<T>()
    }
    
    public init(capacity:Int) {
        self.future = FutureStream<T>(capacity:capacity)
    }
    
    public func complete(result:Try<T>) {
        self.future.complete(result)
    }
    
    public func completeWith(future:Future<T>) {
        self.completeWith(self.future.defaultExecutionContext, future:future)
    }
    
    public func completeWith(executionContext:ExecutionContext, future:Future<T>) {
        future.completeWith(future)
    }
    public func success(value:T) {
        self.future.success(value)
    }
    
    public func failure(error:NSError) {
        self.future.failure(error)
    }
    public func completeWith(stream:FutureStream<T>) {
        self.completeWith(self.future.defaultExecutionContext, stream:stream)
    }
    
    public func completeWith(executionContext:ExecutionContext, stream:FutureStream<T>) {
        future.completeWith(stream)
    }
    
}
public class FutureStream<T> {
    
    private var futures         = [Future<T>]()
    private typealias InFuture  = Future<T> -> Void
    private var saveCompletes   = [InFuture]()
    private var capacity        : Int?
    
    internal let defaultExecutionContext: ExecutionContext  = QueueContext.main
    public var count : Int {
        return futures.count
    }
    
    public init() {
    }
    
    public init(capacity:Int) {
        self.capacity = capacity
    }
    
    // Futureable protocol
    public func onComplete(executionContext:ExecutionContext, complete:Try<T> -> Void) {
        Queue.simpleFutureStreams.sync {
            let futureComplete : InFuture = {future in
                future.onComplete(executionContext, complete)
            }
            self.saveCompletes.append(futureComplete)
            for future in self.futures {
                futureComplete(future)
            }
        }
    }
    internal func complete(result:Try<T>) {
        let future = Future<T>()
        future.complete(result)
        Queue.simpleFutureStreams.sync {
            self.addFuture(future)
            for complete in self.saveCompletes {
                complete(future)
            }
        }
    }
    
    // should be future mixin
    public func onComplete(complete:Try<T> -> Void) {
        self.onComplete(self.defaultExecutionContext, complete)
    }
    
    public func onSuccess(success:T -> Void) {
        self.onSuccess(self.defaultExecutionContext, success:success)
    }
    public func onSuccess(executionContext:ExecutionContext, success:T -> Void) {
        self.onComplete(executionContext) {result in
            switch result {
            case .Success(let resultBox):
                success(resultBox.value)
            default:
                break
            }
        }
    }
    public func onFailure(failure:NSError -> Void) {
        self.onFailure(self.defaultExecutionContext, failure:failure)
    }
    public func onFailure(executionContext:ExecutionContext, failure:NSError -> Void) {
        self.onComplete(executionContext) {result in
            switch result {
            case .Failure(let error):
                failure(error)
            default:
                break
            }
        }
    }
    
    public func map<M>(mapping:T -> Try<M>) -> FutureStream<M> {
        return self.map(self.defaultExecutionContext, mapping)
    }
    
    public func map<M>(executionContext:ExecutionContext, mapping:T -> Try<M>) -> FutureStream<M> {
        let future : FutureStream<M> = self.createWithCapacity()
        self.onComplete(executionContext) {result in
            future.complete(result.flatmap(mapping))
        }
        return future
    }
    
    public func flatmap<M>(mapping:T -> FutureStream<M>) -> FutureStream<M> {
        return self.flatMap(self.defaultExecutionContext, mapping)
    }
    
    public func flatMap<M>(executionContext:ExecutionContext, mapping:T -> FutureStream<M>) -> FutureStream<M> {
        let future : FutureStream<M> = self.createWithCapacity()
        self.onComplete(executionContext) {result in
            switch result {
            case .Success(let resultBox):
                future.completeWith(executionContext, stream:mapping(resultBox.value))
            case .Failure(let error):
                future.failure(error)
            }
        }
        return future
    }
    public func andThen(complete:Try<T> -> Void) -> FutureStream<T> {
        return self.andThen(self.defaultExecutionContext, complete:complete)
    }
    
    public func andThen(executionContext:ExecutionContext, complete:Try<T> -> Void) -> FutureStream<T> {
        let future : FutureStream<T> = self.createWithCapacity()
        future.onComplete(executionContext, complete:complete)
        self.onComplete(executionContext) {result in
            future.complete(result)
        }
        return future
    }
    
    public func recover(recovery:NSError -> Try<T>) -> FutureStream<T> {
        return self.recover(self.defaultExecutionContext, recovery:recovery)
    }
    
    public func recover(executionContext:ExecutionContext, recovery:NSError -> Try<T>) -> FutureStream<T> {
        let future : FutureStream<T> = self.createWithCapacity()
        self.onComplete(executionContext) {result in
            future.complete(result.recoverWith(recovery))
        }
        return future
    }
    
    public func recoverWith(recovery:NSError -> FutureStream<T>) -> FutureStream<T> {
        return self.recoverWith(self.defaultExecutionContext, recovery:recovery)
    }
    
    public func recoverWith(executionContext:ExecutionContext, recovery:NSError -> FutureStream<T>) -> FutureStream<T> {
        let future : FutureStream<T> = self.createWithCapacity()
        self.onComplete(executionContext) {result in
            switch result {
            case .Success(let resultBox):
                future.success(resultBox.value)
            case .Failure(let error):
                future.completeWith(executionContext, stream:recovery(error))
            }
        }
        return future
    }
    public func withFilter(filter:T -> Bool) -> FutureStream<T> {
        return self.withFilter(self.defaultExecutionContext, filter:filter)
    }
    
    public func withFilter(executionContext:ExecutionContext, filter:T -> Bool) -> FutureStream<T> {
        let future : FutureStream<T> = self.createWithCapacity()
        self.onComplete(executionContext) {result in
            future.complete(result.filter(filter))
        }
        return future
    }
    public func foreach(apply:T -> Void) {
        self.foreach(self.defaultExecutionContext, apply:apply)
    }
    
    public func foreach(executionContext:ExecutionContext, apply:T -> Void) {
        self.onComplete(executionContext) {result in
            result.foreach(apply)
        }
    }
    internal func completeWith(stream:FutureStream<T>) {
        self.completeWith(self.defaultExecutionContext, stream:stream)
    }
    
    internal func completeWith(executionContext:ExecutionContext, stream:FutureStream<T>) {
        stream.onComplete(executionContext) {result in
            self.complete(result)
        }
    }
    
    internal func success(value:T) {
        self.complete(Try(value))
    }
    
    internal func failure(error:NSError) {
        self.complete(Try<T>(error))
    }
    
    // future stream extensions
    public func flatmap<M>(mapping:T -> Future<M>) -> FutureStream<M> {
        return self.flatMap(self.defaultExecutionContext, mapping)
    }
    
    public func flatMap<M>(executionContext:ExecutionContext, mapping:T -> Future<M>) -> FutureStream<M> {
        let future : FutureStream<M> = self.createWithCapacity()
        self.onComplete(executionContext) {result in
            switch result {
            case .Success(let resultBox):
                future.completeWith(executionContext, future:mapping(resultBox.value))
            case .Failure(let error):
                future.failure(error)
            }
        }
        return future
    }
    public func recoverWith(recovery:NSError -> Future<T>) -> FutureStream<T> {
        return self.recoverWith(self.defaultExecutionContext, recovery:recovery)
    }
    
    public func recoverWith(executionContext:ExecutionContext, recovery:NSError -> Future<T>) -> FutureStream<T> {
        let future : FutureStream<T> = self.createWithCapacity()
        self.onComplete(executionContext) {result in
            switch result {
            case .Success(let resultBox):
                future.success(resultBox.value)
            case .Failure(let error):
                future.completeWith(executionContext, future:recovery(error))
            }
        }
        return future
    }
    
    internal func completeWith(future:Future<T>) {
        self.completeWith(self.defaultExecutionContext, future:future)
    }
    
    internal func completeWith(executionContext:ExecutionContext, future:Future<T>) {
        future.onComplete(executionContext) {result in
            self.complete(result)
        }
    }
    
    private func addFuture(future:Future<T>) {
        if let capacity = self.capacity {
            if self.futures.count >= capacity {
                self.futures.removeAtIndex(0)
            }
        }
        self.futures.append(future)
    }
    
    private func createWithCapacity<M>() -> FutureStream<M> {
        if let capacity = capacity {
            return FutureStream<M>(capacity:capacity)
        } else {
            return FutureStream<M>()
        }
    }
} | 
	06152547cb4a1f02fae1426e016c703d | 31.289474 | 120 | 0.619664 | false | false | false | false | 
| 
	jwfriese/FrequentFlyer | 
	refs/heads/master | 
	FrequentFlyer/Authentication/TokenValidationService.swift | 
	apache-2.0 | 
	1 | 
	import Foundation
import RxSwift
class TokenValidationService {
    var httpClient = HTTPClient()
    let disposeBag = DisposeBag()
    func validate(token: Token, forConcourse concourseURLString: String, completion: ((Error?) -> ())?) {
        guard let url = URL(string: "\(concourseURLString)/api/v1/containers") else {
            Logger.logError(
                InitializationError.serviceURL(functionName: #function,
                                               data: ["concourseURL" : concourseURLString]
                )
            )
            return
        }
        guard let completion = completion else { return }
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue(token.authValue, forHTTPHeaderField: "Authorization")
        httpClient.perform(request: request)
            .subscribe(
                onNext: {  _ in completion(nil) },
                onError: { error in completion(error) },
                onCompleted: nil,
                onDisposed: nil
        )
        .disposed(by: disposeBag)
    }
}
 | 
	6fa6ff48cac75dbab4259837a28b7166 | 32.542857 | 105 | 0.574957 | false | false | false | false | 
| 
	lenssss/whereAmI | 
	refs/heads/master | 
	Whereami/Controller/Game/GameMainViewController.swift | 
	mit | 
	1 | 
	//
//  GameMainViewController.swift
//  Whereami
//
//  Created by WuQifei on 16/2/16.
//  Copyright © 2016年 WuQifei. All rights reserved.
//
import UIKit
import GoogleMobileAds
import PureLayout
import MJRefresh
import SVProgressHUD
import SocketIOClientSwift
class GameMainViewController: UIViewController,HHPanningTableViewCellDelegate,GADBannerViewDelegate,GADInterstitialDelegate,UITableViewDelegate,UITableViewDataSource,BannerViewDelegate,UINavigationControllerDelegate {
    
    var tempConstraint:NSLayoutConstraint? = nil
    private var adBannerView:GADBannerView? = nil
    private var adInterstitial:GADInterstitial? = nil
    private var assetsItems:AssetsItemsView? = nil
    var tableView:UITableView? = nil
    
    var battleList:BattleAllModel? = nil //战斗列表
    var life:Int = 0 //生命
    var chance:Int = 0 //机会
    var diamond:Int = 0 //钻石
    var gold:Int = 0 //金币
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setConfig()
        
//        self.title = NSLocalizedString("Game",tableName:"Localizable", comment: "")
        self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName:UIFont.customFontWithStyle("Bold", size:18.0)!,NSForegroundColorAttributeName:UIColor.whiteColor()]
        
        // Do any additional setup after loading the view.
        self.setupAD()
        self.setupUI()
        self.navigationController!.delegate = self
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        guard UserModel.getCurrentUser() != nil else{
            return
        }
        self.setTableViewHeight()
        self.getBattleList()
        self.getAccItems()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        guard self.adBannerView!.hidden else{
            self.adBannerView!.hidden = false
            return
        }
        SVProgressHUD.dismiss()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if self.adBannerView!.hidden {
            self.adBannerView!.hidden = false
        }
        
        LNotificationCenter().postNotificationName(KNotificationMainViewDidShow, object: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
// MARK: UI
    //设置广告 
    func setupAD() {
        self.adBannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
        self.navigationController?.navigationBar.addSubview(self.adBannerView!)
        self.adBannerView?.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 0)
        self.adBannerView?.autoPinEdgeToSuperviewEdge(.Left, withInset: 0)
        self.adBannerView?.autoPinEdgeToSuperviewEdge(.Right, withInset: 0)
        self.adBannerView?.autoSetDimension(.Height, toSize: 44)
        
        self.adBannerView?.delegate = self
        self.adBannerView?.adUnitID = "ca-app-pub-3940256099942544/2934735716"
        self.adBannerView?.rootViewController = self
        self.adBannerView?.loadRequest(GADRequest())
        
        self.adInterstitial = GADInterstitial(adUnitID:"ca-app-pub-3940256099942544/4411468910")
        self.adInterstitial?.delegate = self
        self.adInterstitial?.loadRequest(GADRequest())
    }
    
    //设置UI
    func setupUI() {
        assetsItems = AssetsItemsView()
        self.updateAssetsItemsView()
        self.view.addSubview(assetsItems!)
        
        self.assetsItems?.autoPinEdgeToSuperviewEdge(.Top, withInset: 0)
        self.assetsItems?.autoPinEdgeToSuperviewEdge(.Left, withInset: 0)
        self.assetsItems?.autoPinEdgeToSuperviewEdge(.Right, withInset: 0)
        self.assetsItems?.autoSetDimension(.Height, toSize: 44)
        
        let header = MJRefreshNormalHeader()
        header.setRefreshingTarget(self, refreshingAction: #selector(self.getBattleList))
        
        self.tableView = UITableView()
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        self.tableView?.separatorStyle = .None
        self.tableView?.mj_header = header
        self.view.addSubview(self.tableView!)
        
        self.tableView?.autoPinEdgeToSuperviewEdge(.Left)
        self.tableView?.autoPinEdgeToSuperviewEdge(.Right)
        self.tableView?.autoPinEdge(.Top, toEdge: .Bottom, ofView: self.assetsItems!)
        
        self.tableView?.registerClass(ScrollBannersTableViewCell.self, forCellReuseIdentifier: "ScrollBannersTableViewCell")
        self.tableView?.registerClass(RankTableViewCell.self, forCellReuseIdentifier: "RankTableViewCell")
        self.tableView?.registerClass(GameStatusTableViewCell.self, forCellReuseIdentifier: "GameStatusTableViewCell")
        self.tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: "GameMoreStatusTableViewCell")
    }
    
    func updateAssetsItemsView(){
        assetsItems?.assetsButton1?.count?.text = "\(life)"
        assetsItems?.assetsButton2?.count?.text = "\(chance)"
        assetsItems?.assetsButton3?.count?.text = "\(diamond)"
        assetsItems?.assetsButton4?.count?.text = "\(gold)"
    }
    
    func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool){
        if viewController.isKindOfClass(GameMainViewController.self) {
            self.adBannerView?.hidden = false
            self.navigationController?.navigationBar.backgroundColor = UIColor.getNavigationBarColor()
            self.navigationController?.navigationBar.barTintColor = UIColor.getNavigationBarColor()
        }else {
            self.adBannerView?.hidden = true
            self.navigationController?.navigationBar.backgroundColor = UIColor.getGameColor()
            self.navigationController?.navigationBar.barTintColor = UIColor.getGameColor()
        }
    }
    
    func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool){
        if viewController.isKindOfClass(GameMainViewController.self) {
            self.adBannerView?.hidden = false
            self.navigationController?.navigationBar.backgroundColor = UIColor.getNavigationBarColor()
            self.navigationController?.navigationBar.barTintColor = UIColor.getNavigationBarColor()
        }else {
            self.adBannerView?.hidden = true
            self.navigationController?.navigationBar.backgroundColor = UIColor.getGameColor()
            self.navigationController?.navigationBar.barTintColor = UIColor.getGameColor()
        }
    }
    
    func setTableViewHeight(){
        let tabbarH = CGRectGetHeight((self.tabBarController?.tabBar.frame)!)
        let screenH = UIScreen.mainScreen().bounds.height
        let viewH = screenH-64-tabbarH-44
        self.tableView?.autoSetDimension(.Height, toSize: viewH)
    }
    
// MARK: GetDataSource
    //获取战斗列表
    func getBattleList(){
        var dict = [String: AnyObject]()
        dict["accountId"] = UserModel.getCurrentUser()?.id
        dict["page"] = 1
        dict["type"] = "all"
        
        SocketManager.sharedInstance.sendMsg("queryBattleList", data: dict, onProto: "queryBattleListed") { (code, objs) in
            if code == statusCode.Normal.rawValue{
                self.battleList = BattleAllModel.getModelFromObject(objs)
                self.runInMainQueue({
                    self.tableView?.reloadData()
                    self.tableView?.mj_header.endRefreshing()
                })
            }
        }
    }
    
    //战斗列表分类
    func getModelArray(slideItemView:SlideItemView) -> [AnyObject] {
        var modelArray = [AnyObject]()
        if slideItemView.section == 2{
            modelArray = (self.battleList?.battle)!
        }
        else if slideItemView.section == 3{
            modelArray = (self.battleList?.turn)!
        }
        else{
            modelArray = (self.battleList?.ends)!
        }
        return modelArray
    }
    
    //获取个人道具
    func getAccItems(){
        AccItems.getAccItemsWithCompletion { (items) in
            for item in items! {
                if item.itemCode == "life" {
                    self.life = item.itemNum!
                }
            }
            self.updateAssetsItemsView()
        }
    }
    
// MARK: UITableViewDataSource,UITableViewDelegate
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard UserModel.getCurrentUser() != nil else{
            return 0
        }
        
        if section == 0 || section == 1 {
            return 1
        }else{
            if battleList != nil{
                if section == 2 {
                    if battleList?.battle?.count > 3 {
                        return 3
                    }
                    return (battleList?.battle?.count)!
                }
                else if section == 3 {
                    if battleList?.turn?.count > 3 {
                        return 3
                    }
                    return (battleList?.turn?.count)!
                }
                else{
                    if battleList?.ends?.count > 3 {
                        return 3
                    }
                    return (battleList?.ends?.count)!
                }
            }
            return 0
        }
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2 + 3
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section == 2 {
            if battleList?.battle?.count != 0{
                return 40
            }
            return 0
        }else  if section == 3 {
            if battleList?.turn?.count != 0{
                return 40
            }
            return 0
        }else  if section == 4 {
            if battleList?.ends?.count != 0{
                return 40
            }
            return 0
        }
        
        return 0
    }
    
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            return 61
        }
        return 0
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 2 || section == 3 || section == 4 {
            let view:UIView = UIView()
            view.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 40)
            
            let label:UILabel = UILabel(frame: CGRect(x: 14, y: 0, width: 100, height: 40))
            label.textColor = UIColor.whiteColor()
            label.font = UIFont.systemFontOfSize(14.0)
            view .addSubview(label)
            
            let screenW = UIScreen.mainScreen().bounds.width
            let btn = UIButton(type: .System)
            btn.frame = CGRect(x: screenW-70, y: 0, width: 60, height: 40)
            btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
            btn.setTitle(NSLocalizedString("moreStatus",tableName:"Localizable",comment: ""), forState: .Normal)
            btn.rac_signalForControlEvents(.TouchUpInside).subscribeNext({ (button) in
                let moreStatusVC = GameMoreStatusViewController()
                moreStatusVC.hidesBottomBarWhenPushed = true
                if section == 2 {
                    moreStatusVC.status = "myturn"
                    self.navigationController?.pushViewController(moreStatusVC, animated: true)
                }
                else if section == 3 {
                    moreStatusVC.status = "valid"
                    self.navigationController?.pushViewController(moreStatusVC, animated: true)
                }
                else{
                    moreStatusVC.status = "end"
                    self.navigationController?.pushViewController(moreStatusVC, animated: true)
                }
            })
            view .addSubview(btn)
            
            if section == 2 {
                if battleList?.battle?.count <= 3 {
                    btn.hidden = true
                }
                label.text = NSLocalizedString("yourTurn",tableName:"Localizable", comment: "")
                view.backgroundColor = UIColor(red:118/255.0, green: 198/255.0, blue: 32/255.0,alpha: 1.0)
                return view
            }else  if section == 3 {
                if battleList?.turn?.count <= 3 {
                    btn.hidden = true
                }
                label.text = NSLocalizedString("wait",tableName:"Localizable", comment: "")
                view.backgroundColor = UIColor(red:63/255.0, green: 157/255.0, blue: 236/255.0,alpha: 1.0)
                return view
            }else  if section == 4 {
                if battleList?.ends?.count <= 3 {
                    btn.hidden = true
                }
                label.text = NSLocalizedString("end",tableName:"Localizable", comment: "")
                view.backgroundColor = UIColor(red:255/255.0, green: 0/255.0, blue: 0/255.0,alpha: 1.0)
                return view
            }
        }
        return nil
    }
    
    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 0 {
            let view = UIView()
            view.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 61)
            
            let newGameButton = UIButton()
            newGameButton.setTitle(NSLocalizedString("newGame",tableName:"Localizable",comment: ""), forState: .Normal)
            newGameButton.layer.masksToBounds = true
            newGameButton.layer.cornerRadius = 4.0
            newGameButton.backgroundColor = UIColor(red: 71/255.0, green: 95/255.0, blue: 161/255.0, alpha: 1.0)
            newGameButton.frame = CGRect(x: 16, y: 7, width: (view.frame.width - 32), height: (view.frame.height - 14))
            newGameButton.rac_signalForControlEvents(.TouchUpInside).subscribeNext({ (button) -> Void in
                let gameNewVC = GameNewGameViewController()
                gameNewVC.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(gameNewVC, animated: true)
            })
            
            view.addSubview(newGameButton)
            return view
        }
        return nil
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 150
        } else if indexPath.section == 1 {
            return 180
        }
        else{
            if indexPath.row == 3{
                return 40
            }
            return 100
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCellWithIdentifier("ScrollBannersTableViewCell", forIndexPath: indexPath) as! ScrollBannersTableViewCell
            var urls:[NSURL]? = [NSURL]()
            urls?.append(NSURL(string: "http://img.hb.aicdn.com/9a1153e7396c48cefa48e218b1f748805e9a3097bea0-nE1eIE_fw658")!)
            urls?.append(NSURL(string: "http://img.hb.aicdn.com/35114dc52b7c89398fdc6dabefe92b2c052fc27810c5f-HOApcr_fw658")!)
            urls?.append(NSURL(string: "http://img.hb.aicdn.com/aa8daab776a09fe01ccb06faa22a79930bfe3e70421d9-nLaQvA_fw658")!)
            cell.viewInit(self, imageURLs:urls!, placeholderImage: "temp001.jpg", timeInterval: 1, currentPageIndicatorTintColor: UIColor.whiteColor(), pageIndicatorTintColor: UIColor.grayColor())
            return cell
        }else if(indexPath.section == 1) {
            let cell = tableView.dequeueReusableCellWithIdentifier("RankTableViewCell", forIndexPath: indexPath)
            return cell
        }else {
//            if indexPath.row == 3{
//                let cell = tableView.dequeueReusableCellWithIdentifier("GameMoreStatusTableViewCell", forIndexPath: indexPath)
//                cell.selectionStyle = .None
//                cell.textLabel?.text = NSLocalizedString("moreStatus",tableName:"Localizable",comment: "")
//                cell.textLabel?.textAlignment = .Center
//                return cell
//            }
//            else{
                let cell = tableView.dequeueReusableCellWithIdentifier("GameStatusTableViewCell", forIndexPath: indexPath) as! GameStatusTableViewCell
                cell.selectionStyle = .None
                var modelArray = [AnyObject]()
                if indexPath.section == 2{
                    modelArray = (self.battleList?.battle)!
                }
                else if indexPath.section == 3{
                    modelArray = (self.battleList?.turn)!
                }
                else{
                    modelArray = (self.battleList?.ends)!
                }
                let model = modelArray[indexPath.row] as! BattleDetailModel
                UserManager.sharedInstance.getUserByIdWithBlock(model.launchId!, completition: { (user) in
                    let avatar = user.headPortraitUrl != nil ? user.headPortraitUrl:""
                    cell.avatar?.kf_setImageWithURL(NSURL(string:avatar!)!, placeholderImage: UIImage(named: "avator.png"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
                })
                cell.levelBadge?.text = "\(Int(model.launchleve!))"
                cell.username?.text = model.launch
                cell.missionDescription?.text = model.battleTitle
                cell.timeDescription?.text = model.battleType
                cell.score?.text = model.scoreDetail
                
                cell.delegate = self
                cell.directionMask = HHPanningTableViewCellDirectionLeft
                cell.shadowViewEnabled = false
                
                if indexPath.section == 2 || indexPath.section == 3{
                    cell.drawerView = self.rightSlideView(3,section:indexPath.section,row:indexPath.row)
                    
                    
                }else {
                    cell.drawerView = self.rightSlideView(section:indexPath.section,row:indexPath.row)
                }
                return cell
//            }
        }
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        var modelArray = [AnyObject]()
        if indexPath.section == 2{
            modelArray = (self.battleList?.battle)!
        }
        else if indexPath.section == 3{
            modelArray = (self.battleList?.turn)!
        }
        else{
            modelArray = (self.battleList?.ends)!
        }
        let model = modelArray[indexPath.row] as! BattleDetailModel
        let battleId = model.battleId
        
        let moreStatusVC = GameMoreStatusViewController()
        moreStatusVC.hidesBottomBarWhenPushed = true
        
        if indexPath.section == 2 {
            let alertController = UIAlertController(title: "", message: NSLocalizedString("enter",tableName:"Localizable", comment: ""), preferredStyle: .Alert)
            let confirmAction = UIAlertAction(title: NSLocalizedString("go",tableName:"Localizable", comment: ""), style: .Default, handler:{(UIAlertAction) -> Void in
                if model.battleType == "challengeFri" || model.battleType == "challengeRan" {
                        self.presentToPlayRoomVC(battleId!)
                }
                else{
                    self.presentToBattleDetailsVC(battleId!)
                }
            })
            let cancelAction = UIAlertAction(title: NSLocalizedString("later",tableName:"Localizable", comment: ""), style: .Cancel, handler: {(UIAlertAction) -> Void in
                self.getBattleList()
                self.tableView?.reloadData()
            })
            alertController.addAction(confirmAction)
            alertController.addAction(cancelAction)
            self.presentViewController(alertController, animated: true, completion: nil)
        }
        else if indexPath.section == 3 {
            if model.battleType == "challengeFri" || model.battleType == "challengeRan" {
                self.presentToWaitingDetailsVC(battleId!,type: "challenge")
            }
            else{
                self.presentToWaitingDetailsVC(battleId!,type: "classic")
            }
        }
        else if indexPath.section == 4 {
            let viewController = GameEndGameViewController()
            viewController.battleId = battleId
            viewController.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(viewController, animated: true)
        }
    }
    
// MARK: Function
    //跳转战斗详情界面
    func presentToBattleDetailsVC(battleId:String){
        var dict = [String: AnyObject]()
        dict["battleId"] = battleId
        dict["accountId"] = UserModel.getCurrentUser()?.id
        self.runInMainQueue {
            SVProgressHUD.show()
            SVProgressHUD.setDefaultMaskType(.Gradient)
        }
        
        SocketManager.sharedInstance.sendMsg("startBattle", data: dict, onProto: "startBattleed", callBack: { (code, objs) in
            self.runInMainQueue({
                SVProgressHUD.dismiss()
            })
            if code == statusCode.Normal.rawValue {
                if objs[0]["problemId"] as! String != "" {
                    let matchDetailModel = MatchDetailModel.getModelFromDictionary(objs[0] as! [String : AnyObject])
                    self.runInMainQueue({
                        let battleDetailsVC = GameClassicBattleDetailsViewController()
                        battleDetailsVC.matchDetailModel = matchDetailModel
                        battleDetailsVC.hidesBottomBarWhenPushed = true
                        let nav = GameMainNavigationViewController(rootViewController: battleDetailsVC)
                        let window = LApplication().keyWindow?.rootViewController
                        window!.presentViewController(nav, animated: true, completion: nil)
                    })
                }
            }
            else if code == statusCode.Complete.rawValue {
                self.presentCompleteAlert()
            }
            else if code ==  statusCode.Overtime.rawValue {
                self.presentOvertimeAlert()
            }
            else if code == statusCode.Error.rawValue {
                self.presentErrorAlert()
            }
        })
    }
    
    //跳转等待页面
    func presentToWaitingDetailsVC(battleId:String,type:String){
        var dic = [String:AnyObject]()
        dic["battleId"] = battleId
        self.runInMainQueue {
            SVProgressHUD.show()
            SVProgressHUD.setDefaultMaskType(.Gradient)
        }
        
        SocketManager.sharedInstance.sendMsg("getBattleDetails", data: dic, onProto: "getBattleDetailsed") { (code, objs) in
            self.runInMainQueue({
                SVProgressHUD.dismiss()
            })
            if code == statusCode.Normal.rawValue {
                let battleEndModel = BattleEndModel.getModelFromObject(objs)
                self.runInMainQueue({
                    if type == "classic" {
                        let battleDetailsVC = GameClassicBattleDetailsViewController()
                        battleDetailsVC.isWaiting = true
                        battleDetailsVC.waitingDetails = battleEndModel
                        battleDetailsVC.hidesBottomBarWhenPushed = true
                        let nav = GameMainNavigationViewController(rootViewController: battleDetailsVC)
                        let window = LApplication().keyWindow?.rootViewController
                        window!.presentViewController(nav, animated: true, completion: nil)
                    }
                    else{
                        let viewController = GameEndGameViewController()
                        viewController.battleId = battleId
                        viewController.hidesBottomBarWhenPushed = true
                        self.navigationController?.pushViewController(viewController, animated: true)
                        viewController.restartButton?.hidden = true
                    }
                })
            }
            else if code == statusCode.Complete.rawValue {
                self.presentCompleteAlert()
            }
            else if code ==  statusCode.Overtime.rawValue {
                self.presentOvertimeAlert()
            }
            else if code == statusCode.Error.rawValue {
                self.presentErrorAlert()
            }
        }
    }
    
    //跳转答题页面
    func presentToPlayRoomVC(battleId:String){
        var dict = [String: AnyObject]()
        dict["battleId"] = battleId
        dict["accountId"] = UserModel.getCurrentUser()?.id
        self.runInMainQueue({
            SVProgressHUD.show()
            SVProgressHUD.setDefaultMaskType(.Gradient)
        })
        SocketManager.sharedInstance.sendMsg("startBattle", data: dict, onProto: "startBattleed", callBack: { (code, objs) in
            self.runInMainQueue({
                SVProgressHUD.dismiss()
            })
            print(objs)
            if code == statusCode.Normal.rawValue {
                if objs[0]["problemId"] as! String != "" {
                    var dict = [String: AnyObject]()
                    dict["battleId"] = objs[0]["battleId"]
                    dict["questionId"] = objs[0]["problemId"]
                    
                    SocketManager.sharedInstance.sendMsg("queryProblemById", data: dict, onProto: "queryProblemByIded") { (code, objs) in
                        let battleModel = BattleModel.getModelFromDictionary(objs[0] as! NSDictionary)
                        self.runInMainQueue({
                            let playRoomVC = GameQuestionPlayRoomViewController()
                            playRoomVC.battleModel = battleModel
                            playRoomVC.hidesBottomBarWhenPushed = true
                            let nav = GameMainNavigationViewController(rootViewController: playRoomVC)
                            let window = LApplication().keyWindow?.rootViewController
                            window?.presentViewController(nav, animated: true, completion: nil)
                        })
                    }
                }
            }
            else if code == statusCode.Complete.rawValue {
                self.presentCompleteAlert()
            }
            else if code == statusCode.Overtime.rawValue {
                self.presentOvertimeAlert()
            }
            else if code == statusCode.Error.rawValue {
                self.presentErrorAlert()
            }
        })
    }
    
    func deleteGameStatusItem(tapGesture:UITapGestureRecognizer) {
        let slideItemView:SlideItemView = tapGesture.view as! SlideItemView
        print("delete section: \(slideItemView.section) row: \(slideItemView.row)")
        var modelArray = self.getModelArray(slideItemView)
        let model = modelArray[slideItemView.row] as! BattleDetailModel
        var dict = [String: AnyObject]()
        dict["battleId"] = model.battleId
        dict["accountId"] = UserModel.getCurrentUser()?.id
        SocketManager.sharedInstance.sendMsg("quitBattle", data: dict, onProto: "quitBattleed") { (code, objs) in
            if code == statusCode.Normal.rawValue {
                self.getBattleList()
            }
            else if code == statusCode.Complete.rawValue {
                self.getBattleList()
            }
        }
    }
    
    func chatGameStatusItem(tapGesture:UITapGestureRecognizer) {
        let slideItemView:SlideItemView = tapGesture.view as! SlideItemView
        let cell = tableView?.cellForRowAtIndexPath(NSIndexPath(forRow: slideItemView.row,inSection: slideItemView.section)) as! GameStatusTableViewCell
        var modelArray = self.getModelArray(slideItemView)
        let model = modelArray[slideItemView.row] as! BattleDetailModel
        
        let friend = FriendsModel()
        friend.friendId = model.launchId
        friend.nickname = model.launch
        friend.headPortrait = cell.avatar?.image?.image2String()
        
        createConversation(friend)
    }
    
    func personalGameStatusItem(tapGesture:UITapGestureRecognizer) {
        let slideItemView:SlideItemView = tapGesture.view as! SlideItemView
        var modelArray = self.getModelArray(slideItemView)
        let model = modelArray[slideItemView.row] as! BattleDetailModel
        let personalVC = TourRecordsViewController()
        personalVC.userId = model.launchId
        personalVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(personalVC, animated: true)
        self.adBannerView?.hidden = true
    }
    
    func againGameStatusItem(tapGesture:UITapGestureRecognizer) {
        let slideItemView:SlideItemView = tapGesture.view as! SlideItemView
        print("again section: \(slideItemView.section) row: \(slideItemView.row)")
    }
    
    
    func rightSlideView(totalView:Int = 4,section:Int,row:Int) ->UIView {
        let view:UIView = UIView()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 100)
        view.backgroundColor = UIColor.clearColor()
        for i in 0..<totalView {
            let buttonWidth = UIScreen.mainScreen().bounds.width / CGFloat(totalView)
            let slideItemView:SlideItemView = SlideItemView(frame: CGRect(x: CGFloat(i) * buttonWidth, y: 0, width: buttonWidth, height: 100))
            slideItemView.row = row
            slideItemView.section = section
            let tapGesture = UITapGestureRecognizer()
            tapGesture.numberOfTapsRequired = 1
            tapGesture.numberOfTouchesRequired = 1
            
            slideItemView.addGestureRecognizer(tapGesture)
           
            view.addSubview(slideItemView)
            
            if i == 0 {
                slideItemView.viewDescription!.text = NSLocalizedString("Delete",tableName:"Localizable",comment: "")
                slideItemView.viewIcon!.image = UIImage(named:"new_game_scroll_giveup");
                tapGesture.addTarget(self, action: #selector(self.deleteGameStatusItem(_:)))
            } else if i == 1 {
                slideItemView.viewDescription!.text = NSLocalizedString("Chat",tableName:"Localizable",comment: "")
                slideItemView.viewIcon!.image = UIImage(named:"new_game_scroll_chat")
                tapGesture.addTarget(self, action: #selector(self.chatGameStatusItem(_:)))
            } else if i == 2 {
                slideItemView.viewDescription!.text = NSLocalizedString("Personal",tableName:"Localizable", comment: "")
                slideItemView.viewIcon!.image = UIImage(named:"new_game_scroll_personal")
                tapGesture.addTarget(self, action: #selector(self.personalGameStatusItem(_:)))
            } else if i == 3 {
                slideItemView.viewDescription!.text = NSLocalizedString("Again",tableName:"Localizable", comment: "")
                slideItemView.viewIcon!.image = UIImage(named:"new_game_scroll_again")
                tapGesture.addTarget(self, action: #selector(self.againGameStatusItem(_:)))
            }
        }
        return view
    }
    func bannerViewDidClicked(index:Int) {
        print("clicked: \(index)")
    }
    
    func interstitialDidReceiveAd(ad: GADInterstitial!) {
        let status = SocketManager.sharedInstance.socket?.status
        if status == SocketIOClientStatus.Connected {
            self.adInterstitial?.presentFromRootViewController(self)
        }
    }
    
    func createConversation(model:FriendsModel){
        let friendModel:FriendsModel = model
        let currentUser = UserModel.getCurrentUser()
        let guestUser = ChattingUserModel()
        let hostUser = ChattingUserModel()
        
        guestUser.accountId = friendModel.friendId
        guestUser.headPortrait = friendModel.headPortrait
        guestUser.nickname = friendModel.nickname
        
        hostUser.accountId = currentUser?.id
        hostUser.headPortrait = currentUser?.headPortraitUrl
        hostUser.nickname = currentUser?.nickname
        
        LeanCloudManager.sharedInstance.createConversitionWithClientIds(guestUser.accountId!, clientIds: [guestUser.accountId!]) { (succed, conversion) in
            if(succed) {
                CoreDataConversationManager.sharedInstance.increaseOrCreateUnreadCountByConversation( conversion!, lastMsg: "", msgType: kAVIMMessageMediaTypeText)
                
                self.push2ConversationVC(conversion!, hostUser: hostUser, guestUser: guestUser)
            }
        }
    }
    
    func push2ConversationVC(conversion:AVIMConversation,hostUser:ChattingUserModel,guestUser:ChattingUserModel) {
        let conversationVC = ConversationViewController()
        conversationVC.conversation = conversion
        conversationVC.hostModel = hostUser
        conversationVC.guestModel = guestUser
        conversationVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(conversationVC, animated: true)
    }
    
    func presentOvertimeAlert(){
        self.runInMainQueue { 
            let alertController = UIAlertController(title: NSLocalizedString("warning",tableName:"Localizable", comment: ""), message: NSLocalizedString("overtime",tableName:"Localizable", comment: ""), preferredStyle: .Alert)
            let confirmAction = UIAlertAction(title: NSLocalizedString("ok",tableName:"Localizable", comment: ""), style: .Default, handler: { (action) in
                self.getBattleList()
            })
            alertController.addAction(confirmAction)
            self.presentViewController(alertController, animated: true, completion: nil)
        }
    }
    
    func presentCompleteAlert(){
        self.runInMainQueue { 
            let alertController = UIAlertController(title: NSLocalizedString("warning",tableName:"Localizable", comment: ""), message: NSLocalizedString("complete",tableName:"Localizable", comment: ""), preferredStyle: .Alert)
            let confirmAction = UIAlertAction(title: NSLocalizedString("ok",tableName:"Localizable", comment: ""), style: .Default, handler: { (action) in
                self.getBattleList()
            })
            alertController.addAction(confirmAction)
            self.presentViewController(alertController, animated: true, completion: nil)
        }
    }
    
    func presentErrorAlert(){
        self.runInMainQueue { 
            let alertController = UIAlertController(title: NSLocalizedString("warning",tableName:"Localizable", comment: ""), message: NSLocalizedString("error",tableName:"Localizable", comment: ""), preferredStyle: .Alert)
            let confirmAction = UIAlertAction(title: NSLocalizedString("ok",tableName:"Localizable", comment: ""), style: .Default, handler: { (action) in
                self.getBattleList()
            })
            alertController.addAction(confirmAction)
            self.presentViewController(alertController, animated: true, completion: nil)
        }
    }
    
    func SVProgressDismiss(){
        SVProgressHUD.dismiss()
    }
    
    /*
    // 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.
    }
    */
}
 | 
	13ce8328e340951c12a9d5719fe346c8 | 43.960957 | 226 | 0.604359 | false | false | false | false | 
			Subsets and Splits
				
	
				
			
				
No community queries yet
The top public SQL queries from the community will appear here once available.