| repo_name
				 stringlengths 6 91 | path
				 stringlengths 8 968 | copies
				 stringclasses 210
				values | size
				 stringlengths 2 7 | content
				 stringlengths 61 1.01M | license
				 stringclasses 15
				values | hash
				 stringlengths 32 32 | line_mean
				 float64 6 99.8 | line_max
				 int64 12 1k | alpha_frac
				 float64 0.3 0.91 | ratio
				 float64 2 9.89 | autogenerated
				 bool 1
				class | config_or_test
				 bool 2
				classes | has_no_keywords
				 bool 2
				classes | has_few_assignments
				 bool 1
				class | 
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 
	lioonline/v2ex-lio | 
	V2ex/V2ex/APIURL.swift | 
	1 | 
	796 | 
	//
//  APIURL.swift
//  V2ex
//
//  Created by Cocoa Lee on 9/29/15.
//  Copyright © 2015 lio. All rights reserved.
//
import Foundation
//最新主题
let V2_NEW:String = "https://www.v2ex.com/api/topics/latest.json"
//最热主题
let V2_HOT:String = "https://www.v2ex.com/api/topics/hot.json"
//节点信息 参数 name
let V2_POINT:String = "https://www.v2ex.com/api/nodes/show.json"
//用户主页 参数 username || id
let V2_ :String = "https://www.v2ex.com/api/members/show.json"
//base 
let V2_BASE :String = "http:"
//主题信息
let V2_CONTENT:String = "https://www.v2ex.com/api/topics/show.json"
//主题回复
let V2_CONTENT_REPLY:String = "https://www.v2ex.com/api/replies/show.json"
//用户信息
let V2_USERINFO:String  = "https://www.v2ex.com/api/members/show.json?username=" | 
	mit | 
	4060a1d25cff5d8aff08b7124c45fcec | 28.28 | 80 | 0.69357 | 2.436667 | false | false | false | false | 
| 
	peferron/algo | 
	EPI/Strings/The look-and-say problem/swift/main.swift | 
	1 | 
	807 | 
	// swiftlint:disable variable_name
public func lookAndSay(index n: Int) -> String {
    var sequence: [Character] = ["1"]
    for _ in stride(from: 1, through: n, by: 1) {
        sequence = next(sequence)
    }
    return String(sequence)
}
func next(_ sequence: [Character]) -> [Character] {
    var nextSequence = [Character]()
    var streakCount = 1
    var streakCharacter = sequence.first!
    for character in sequence.dropFirst(1) {
        if character == streakCharacter {
            streakCount += 1
        } else {
            nextSequence += String(streakCount) + [streakCharacter]
            streakCharacter = character
            streakCount = 1
        }
    }
    // Append the final streak.
    nextSequence += String(streakCount) + [streakCharacter]
    return nextSequence
}
 | 
	mit | 
	bb518d3ca2ae455936e3473f713240fb | 24.21875 | 67 | 0.608426 | 4.225131 | false | false | false | false | 
| 
	JP-KIM/Acruz | 
	LoginViewController.swift | 
	1 | 
	3428 | 
	//
//  LoginViewController.swift
//  Acruz
//
//  Created by 김정표 on 2016. 6. 30..
//  Copyright © 2016년 Acruz corp. All rights reserved.
//
import UIKit
import FirebaseAuth
import FBSDKLoginKit
class LoginViewController: UIViewController, FBSDKLoginButtonDelegate {
    
    @IBOutlet weak var tvEmail: UITextField!
    @IBOutlet weak var tvPassword: UITextField!
    @IBAction func onLoginClicked(sender: AnyObject) {
        
        
    }
    @IBAction func onAnonymousLoginClicked(sender: AnyObject) {
        FIRAuth.auth()?.signInAnonymouslyWithCompletion( { (user, error) in
            
            print("Firebase anonymous login succeed")
            self.performSegueWithIdentifier("TabView", sender: self)
        })
    }
    
    @IBOutlet weak var FBLoginButton: FBSDKLoginButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        self.FBLoginButton.delegate = self
        
        self.FBLoginButton.readPermissions = ["public_profile", "email", "user_friends"]
    
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        view.endEditing(true)
    }
    
    
    // MARK:: FACEBOOK LOGIN BUTTON
    func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
        if ((error) != nil) {
            // Process error
            print("process error")
        }
        else if result.isCancelled {
            // Handle cancellations
            print("cancelled")
        }
        else {
            // Navigate to other view
            print("succeed, navigate to Main")
            //queryUserData()
            if result.grantedPermissions.contains("email")
            {
                print("couldn't get email")
                // Do work
            }
            
            let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString)
            FIRAuth.auth()?.signInWithCredential(credential, completion: { (user, error) in
                // If succeed to add account to Firebase, move to next controller
                print("Firebase facebook login succeed")
                self.performSegueWithIdentifier("TabView", sender: self)
            })
        }
    }
    
    func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
        print("User Logged Out")
    }
    
    // MARK:: FACEBOOK USER QUERY
    func queryUserData() {
        let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
        graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
            
            if error != nil {
                // Process error
                print("Error: \(error)")
            } else {
                print("fetched user: \(result)")
                if let userName = result.valueForKey("name") {
                    print("User Name is: \(userName)")
                }
                if let userEmail = result.valueForKey("email") {
                    print("User Email is: \(userEmail)")
                }
            }
        })
        
    }
}
 | 
	mit | 
	1ce0c9f9575cfcd3b442fb452c3d71be | 31.561905 | 132 | 0.580872 | 5.496785 | false | false | false | false | 
| 
	ChinaPicture/ZXYRefresh | 
	RefreshDemo/ViewController.swift | 
	1 | 
	4054 | 
	//
//  ViewController.swift
//  RefreshDemo
//
//  Created by developer on 15/03/2017.
//  Copyright © 2017 developer. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
    @IBOutlet weak var tvCurrent: UITableView!
    var subVi: UIView?
    var sVI: UIView?
    var data: [String] = []
    var layer : CAShapeLayer = CAShapeLayer.init()
    var count = 0
    var footView: UIView?
    var headView: UIView?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.data.append(contentsOf: ["1" ])
        self.tvCurrent.headerView = SampleRefreshHeaderView.init(activeOff: 50, action: { [weak self](status) in
            if status == .load {
                
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.seconds(2), execute: {
                    self?.data.append(contentsOf: ["1" , "1" ])
                    self?.tvCurrent.reloadData()
                    self?.tvCurrent.headerView?.state = .finish
                })
                
            }
        })
//
        self.tvCurrent.footerView = SimpleRefreshFooterView.init(activeOff: 50, action: { (state) in
            if state == .load {
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.seconds(2), execute: {
                    self.data.append(contentsOf: ["4" , "4" ])
                    self.tvCurrent.reloadData()
                    self.tvCurrent.footerView?.state = .finish
                })
                
            }
        })
//        
//        self.tvCurrent.footerView = SimpleRefreshFooterView.init(activeOff: 50, action: { [weak self](state) in
//            if state == .load {
//                
//                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.seconds(6), execute: {
//                    self?.data.append(contentsOf: ["4" , "5" , "6"])
//                    self?.tvCurrent.reloadData()
//                    self?.tvCurrent.footerView?.state = .finish
//                })
//                
//            }
//
//        }, loadModel: .footerLoadModeAtBottom)
        
        
        let right = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 40))
        right.addTarget(self, action: #selector(self.testFinish), for: .touchUpInside)
        right.setTitle("点击", for: .normal)
        let i = UIBarButtonItem.init(customView: right)
        self.navigationItem.rightBarButtonItem = i
        let left = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 40))
        left.addTarget(self, action: #selector(self.testInitial), for: .touchUpInside)
        left.setTitle("点击", for: .normal)
        let k = UIBarButtonItem.init(customView: left)
        self.navigationItem.leftBarButtonItem = k
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }
    
    func testFinish(){
//        self.tvCurrent.headerView?.state = .finish
        self.tvCurrent.footerView = nil
    }
    
    func testInitial() {
        self.tvCurrent.headerView = nil
    }
}
extension ViewController : UITableViewDelegate , UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.data.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "id")
        let lbl = cell?.viewWithTag(11) as! UILabel
        let current = self.data[indexPath.row]
        lbl.text = current
        return cell!
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
}
 | 
	apache-2.0 | 
	11a49656593a6f2f11b3c7902895924f | 35.116071 | 122 | 0.58665 | 4.660138 | false | false | false | false | 
| 
	alessiobrozzi/firefox-ios | 
	ClientTests/ClientTests.swift | 
	1 | 
	3965 | 
	/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import XCTest
import Shared
import Storage
import WebKit
import Alamofire
@testable import Client
class ClientTests: XCTestCase {
    func testSyncUA() {
        let ua = UserAgent.syncUserAgent
        let device = DeviceInfo.deviceModel()
        let systemVersion = UIDevice.current.systemVersion
        let expectedRegex = "^Firefox-iOS-Sync/[0-9]\\.[0-9]b*[0-9] \\(\(device); iPhone OS \(systemVersion)\\) \\([-_A-Za-z0-9= \\(\\)]+\\)$"
        let loc = ua.range(of: expectedRegex, options: NSString.CompareOptions.regularExpression)
        XCTAssertTrue(loc != nil, "Sync UA is as expected. Was \(ua)")
    }
    // Simple test to make sure the WKWebView UA matches the expected FxiOS pattern.
    func testUserAgent() {
        let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
        let compare: (String) -> Bool = { ua in
            let range = ua.range(of: "^Mozilla/5\\.0 \\(.+\\) AppleWebKit/[0-9\\.]+ \\(KHTML, like Gecko\\) FxiOS/\(appVersion)b*[0-9] Mobile/[A-Za-z0-9]+ Safari/[0-9\\.]+$", options: NSString.CompareOptions.regularExpression)
            return range != nil
        }
        XCTAssertTrue(compare(UserAgent.defaultUserAgent()), "User agent computes correctly.")
        XCTAssertTrue(compare(UserAgent.cachedUserAgent(checkiOSVersion: true)!), "User agent is cached correctly.")
        let expectation = self.expectation(description: "Found Firefox user agent")
        let webView = WKWebView()
        webView.evaluateJavaScript("navigator.userAgent") { result, error in
            let userAgent = result as! String
            if compare(userAgent) {
                expectation.fulfill()
            } else {
                XCTFail("User agent did not match expected pattern! \(userAgent)")
            }
        }
        waitForExpectations(timeout: 5, handler: nil)
    }
    func testDesktopUserAgent() {
        let compare: (String) -> Bool = { ua in
            let range = ua.range(of: "^Mozilla/5\\.0 \\(Macintosh; Intel Mac OS X [0-9_]+\\) AppleWebKit/[0-9\\.]+ \\(KHTML, like Gecko\\) Safari/[0-9\\.]+$", options: NSString.CompareOptions.regularExpression)
            return range != nil
        }
        XCTAssertTrue(compare(UserAgent.desktopUserAgent()), "Desktop user agent computes correctly.")
    }
    /// Our local server should only accept whitelisted hosts (localhost and 127.0.0.1).
    /// All other localhost equivalents should return 403.
    func testDisallowLocalhostAliases() {
        // Allowed local hosts. The first two are equivalent since iOS forwards an
        // empty host to localhost.
        [ "localhost",
            "",
            "127.0.0.1",
            ].forEach { XCTAssert(hostIsValid($0), "\($0) host should be valid.") }
        // Disallowed local hosts. WKWebView will direct them to our server, but the server
        // should reject them.
        [ "[::1]",
            "2130706433",
            "0",
            "127.00.00.01",
            "017700000001",
            "0x7f.0x0.0x0.0x1"
            ].forEach { XCTAssertFalse(hostIsValid($0), "\($0) host should not be valid.") }
    }
    fileprivate func hostIsValid(_ host: String) -> Bool {
        let expectation = self.expectation(description: "Validate host for \(host)")
        let request = URLRequest(url: URL(string: "http://\(host):6571/about/license")!)
        var response: HTTPURLResponse?
        Alamofire.request(request).authenticate(usingCredential: WebServer.sharedInstance.credentials).response { (res) -> Void in
            response = res.response
            expectation.fulfill()
        }
        waitForExpectations(timeout: 100, handler: nil)
        return response?.statusCode == 200
    }
}
 | 
	mpl-2.0 | 
	3ba35d3662c4883db185d7c869e9beff | 41.180851 | 226 | 0.623203 | 4.430168 | false | true | false | false | 
| 
	apple/swift-lldb | 
	packages/Python/lldbsuite/test/lang/swift/foundation_value_types/url/main.swift | 
	2 | 
	898 | 
	// main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
import Foundation
func main() {
  var url = URL(string: "http://www.apple.com")!
  print("done!") //% self.expect("frame variable url", substrs=['www.apple.com'])
   //% self.expect("expression -d run -- url", substrs=['www.apple.com'])
}
var g_url = URL(string: "http://www.apple.com")!
main() //% self.expect("target variable g_url", substrs=['www.apple.com'])
       //% self.expect("expression -d run -- g_url", substrs=['www.apple.com'])
 | 
	apache-2.0 | 
	dfdeb5a77252cb42e5e16fa5eb60330a | 38.043478 | 81 | 0.616927 | 3.854077 | false | false | false | false | 
| 
	DylanSecreast/uoregon-cis-portfolio | 
	uoregon-cis-399/examples/LendingLibrary/LendingLibrary/Source/Controller/CategoryDetailViewController.swift | 
	1 | 
	3335 | 
	//
//  CategoryDetailViewController.swift
//  LendingLibrary
//
//  Created by Charles Augustine.
//
//
import UIKit
class CategoryDetailViewController: UITableViewController, UITextFieldDelegate {
	// MARK: IBAction
	@IBAction private func cancel(_ sender: AnyObject) {
		delegate.categoryDetailViewControllerDidFinish(self)
	}
	@IBAction private func save(_ sender: AnyObject) {
		let orderIndex = delegate.numberOfCategoriesForCategoryDetailViewController(self)
		do {
			try LendingLibraryService.shared.addCategory(withName: name, andOrderIndex: orderIndex)
			delegate.categoryDetailViewControllerDidFinish(self)
		}
		catch _ {
			let alertController = UIAlertController(title: "Save failed", message: "Failed to save the new lent item", preferredStyle: .alert)
			alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
			present(alertController, animated: true, completion: nil)
		}
	}
	// MARK: UITableViewDelegate
	override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
		nameTextField.becomeFirstResponder()
	}
	// MARK: UITextFieldDelegate
	func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
		name = ((textField.text ?? "") as NSString).replacingCharacters(in: range, with: string)
		return true
	}
	func textFieldShouldClear(_ textField: UITextField) -> Bool {
		return true
	}
	func textFieldShouldReturn(_ textField: UITextField) -> Bool {
		nameTextField.resignFirstResponder()
		return false
	}
	// MARK: View Management
	override func viewWillAppear(_ animated: Bool) {
		super.viewWillAppear(animated)
		if selectedCategory != nil {
			navigationItem.title = "Edit Category"
			navigationItem.leftBarButtonItem = nil
			navigationItem.rightBarButtonItem = nil
		}
		else {
			navigationItem.title = "Add Category"
			navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(CategoryDetailViewController.cancel(_:)))
			navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(CategoryDetailViewController.save(_:)))
		}
		nameTextField.text = name
	}
	override func viewWillDisappear(_ animated: Bool) {
		if let someCategory = selectedCategory {
			do {
				try LendingLibraryService.shared.renameCategory(someCategory, withNewName: name)
			}
			catch _ {
				let alertController = UIAlertController(title: "Save failed", message: "Failed to save the new lent item", preferredStyle: .alert)
				alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
				present(alertController, animated: true, completion: nil)
			}
		}
		super.viewWillDisappear(animated)
	}
	// MARK: Properties
	var selectedCategory: Category? {
		didSet {
			if let someCategory = selectedCategory {
				name = someCategory.name!
			}
			else {
				name = CategoryDetailViewController.defaultName
			}
		}
	}
	var delegate: CategoryDetailViewControllerDelegate!
	// MARK: Properties (Private)
	private var name = CategoryDetailViewController.defaultName
	// MARK: Properties (IBOutlet)
	@IBOutlet private weak var nameTextField: UITextField!
	// MARK: Properties (Private Static Constant)
	private static let defaultName = "New Category"
}
 | 
	gpl-3.0 | 
	ad4f5038562cb6dd19d5a33893dbb685 | 29.59633 | 157 | 0.753823 | 4.393939 | false | false | false | false | 
| 
	BlenderSleuth/Unlokit | 
	Unlokit/Nodes/LockNode.swift | 
	1 | 
	2100 | 
	//
//  LockNode.swift
//  Unlokit
//
//  Created by Ben Sutherland on 23/1/17.
//  Copyright © 2017 blendersleuthdev. All rights reserved.
//
import SpriteKit
class LockNode: SKSpriteNode, NodeSetup {
	required init?(coder aDecoder: NSCoder) {
		super.init(coder: aDecoder)
	}
	
	func setup(scene: GameScene) {
		lightingBitMask = Category.controllerLight | Category.toolLight | Category.lockLight
		
		physicsBody = SKPhysicsBody(circleOfRadius: size.width / 2)
		physicsBody?.isDynamic = false
		physicsBody?.density = 0.01
		physicsBody?.categoryBitMask = Category.lock
		physicsBody?.contactTestBitMask = Category.zero
		physicsBody?.collisionBitMask = Category.blocks | Category.ball | Category.bounds
		getDataFromParent()
	}
	func addLight() {
		let light = SKLightNode()
		light.falloff = 4
		light.categoryBitMask = Category.lockLight
		addChild(light)
	}
	private func getDataFromParent() {
		var data: NSDictionary?
		// Find user data from parents
		var tempNode: SKNode = self
		while !(tempNode is SKScene) {
			if let userData = tempNode.userData {
				data = userData
			}
			tempNode = tempNode.parent!
		}
		// Set instance properties
		if let dynamic = data?["dynamic"] as? Bool {
			physicsBody?.isDynamic = dynamic
			if dynamic, let gravity = data?["gravity"] as? Bool {
				physicsBody?.affectedByGravity = gravity
				if !gravity {
					// To set gravity later
					physicsBody?.contactTestBitMask = Category.tools | Category.ball
				}
			}
		}
		if let attached = data?["attached"] as? Bool, attached {
			physicsBody?.collisionBitMask = Category.ball | Category.bounds
			
			var block: BlockNode?
			
			// Find block
			var tempNode: SKNode = self
			while !(tempNode is SKScene) {
				if let blockNode = tempNode as? BlockNode {
					block = blockNode
					break
				}
				tempNode = tempNode.parent!
			}
			if let blockPhysicsBody = block?.physicsBody, let scene = scene {
				let pin = SKPhysicsJointFixed.joint(withBodyA: blockPhysicsBody, bodyB: self.physicsBody!, anchor: scene.convert(CGPoint.zero, from: self))
				scene.physicsWorld.add(pin)
			}
		}
	}
}
 | 
	gpl-3.0 | 
	2da659ddeb0b5deb4cfed6e60b8a37ea | 26.618421 | 143 | 0.699381 | 3.823315 | false | false | false | false | 
| 
	gstatton/virtualcones | 
	vCones/AppDelegate.swift | 
	2 | 
	12926 | 
	//
//  AppDelegate.swift
//  AppDelegate
//
//  Created by gstatton on 5/19/15.
//
//
import UIKit
import CoreLocation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
    
    var window: UIWindow?
    var locationManager: CLLocationManager?
    var lastProximity: CLProximity?
    var lastDistance: CLLocationAccuracy?
    
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
        
        locationManager = CLLocationManager()
        
        if(locationManager!.respondsToSelector("requestAlwaysAuthorization")) {
            locationManager!.requestAlwaysAuthorization()
        }
        
        locationManager!.delegate = self
        locationManager!.pausesLocationUpdatesAutomatically = false
        
       // let uuidString = ["A4951234-C5B1-4B44-B512-1370F02D74DE","A4950929-C5B1-4B44-B512-1370F02D74DE"]
        let uuidString = "A4951234-C5B1-4B44-B512-1370F02D74DE"
        let beaconIdentifier = "3Wandel"
        
        //for id in uuidString{
            NSLog("monitoring for UUID: \(uuidString)")
            let beaconUUID:NSUUID = NSUUID(UUIDString: uuidString)!
            let beaconRegion:CLBeaconRegion = CLBeaconRegion(proximityUUID: beaconUUID,
                identifier: beaconIdentifier)
        
        
            
            NSLog("beaconRegion: \(beaconRegion)")
            locationManager!.startMonitoringForRegion(beaconRegion)
            locationManager!.startRangingBeaconsInRegion(beaconRegion)
            locationManager!.startUpdatingLocation()
            
        //}
        
        if(application.respondsToSelector("registerUserNotificationSettings:")) {
            application.registerUserNotificationSettings(
                UIUserNotificationSettings(
                    forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Sound,
                    categories: 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 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:.
    }
    
    
}
extension AppDelegate: CLLocationManagerDelegate {
    
    func put(params : Dictionary<String, Bool>, url : String, postCompleted : (succeeded: Bool, msg: String) -> ()) {
        var request = NSMutableURLRequest(URL: NSURL(string: url)!)
        var session = NSURLSession.sharedSession()
        request.HTTPMethod = "PUT"
        
        var err: NSError?
        request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        
        var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            println("Response: \(response)")
            var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("Body: \(strData)")
            var err: NSError?
            var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
            
            var msg = "No message"
            
            // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
            if(err != nil) {
                println(err!.localizedDescription)
                let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                println("Error could not parse JSON: '\(jsonStr)'")
                postCompleted(succeeded: false, msg: "Error")
            }
            else {
                // The JSONObjectWithData constructor didn't return an error. But, we should still
                // check and make sure that json has a value using optional binding.
                if let parseJSON = json {
                    // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                    if let success = parseJSON["success"] as? Bool {
                        println("Succes: \(success)")
                        postCompleted(succeeded: success, msg: "Logged in.")
                    }
                    return
                }
                else {
                    // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                    let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                    println("Error could not parse JSON: \(jsonStr)")
                    postCompleted(succeeded: false, msg: "Error")
                }
            }
        })
        
        task.resume()
    }
    func get(params : Dictionary<String, Bool>, url : String, postCompleted : (succeeded: Bool, msg: String) -> ()) {
        var request = NSMutableURLRequest(URL: NSURL(string: url)!)
        var session = NSURLSession.sharedSession()
        request.HTTPMethod = "GET"
        
        var err: NSError?
        request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        
        var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            println("Response: \(response)")
            var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("Body: \(strData)")
            var err: NSError?
            var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
            
            var msg = "No message"
            
            // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
            if(err != nil) {
                println(err!.localizedDescription)
                let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                println("Error could not parse JSON: '\(jsonStr)'")
                postCompleted(succeeded: false, msg: "Error")
            }
            else {
                // The JSONObjectWithData constructor didn't return an error. But, we should still
                // check and make sure that json has a value using optional binding.
                if let parseJSON = json {
                    // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                    if let success = parseJSON["success"] as? Bool {
                        println("Succes: \(success)")
                        postCompleted(succeeded: success, msg: "Logged in.")
                    }
                    return
                }
                else {
                    // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                    let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                    println("Error could not parse JSON: \(jsonStr)")
                    postCompleted(succeeded: false, msg: "Error")
                }
            }
        })
        
        task.resume()
    }
    
    
    func sendLocalNotificationWithMessage(message: String!, turnLights: Bool, groups: Int!) {
        let notification:UILocalNotification = UILocalNotification()
        notification.alertBody = message
        UIApplication.sharedApplication().scheduleLocalNotification(notification)
        
        if(turnLights) {
            //Turn on Lights
            self.put(["on":true], url: "http://10.0.0.3/api/newdeveloper/groups/\(groups)/action") { (succeeded: Bool, msg: String) -> () in
            }
            
        } else {
            //Turn off Lights
            self.put(["on":false], url: "http://10.0.0.3/api/newdeveloper/groups/\(groups)/action") { (succeeded: Bool, msg: String) -> () in
                
            }
            
        }
    }
    
    
    
    func locationManager(manager: CLLocationManager!,
        didRangeBeacons beacons: [AnyObject]!,
        inRegion region: CLBeaconRegion!) {
            
            let viewController:ViewController = window!.rootViewController as! ViewController
            viewController.beacons = beacons as! [CLBeacon]?
            viewController.tableView!.reloadData()
            
            NSLog("didRangeBeacons: \(beacons)");
            NSLog("Region: \(region)")
            
            var message:String = ""
            var turnLights = false
            var groups = 0
            
            NSLog("Beacon Count: \(beacons.count)")
            
            if(beacons.count > 0) {
                let nearestBeacon:CLBeacon = beacons[0] as! CLBeacon
                NSLog("This is the nearest beacon: \(beacons[0].major)")
                let beaconMajor = beacons[0].major
                
                if(nearestBeacon.proximity == lastProximity ||
                    nearestBeacon.proximity == CLProximity.Unknown) {
                        return;
                }
                lastProximity = nearestBeacon.proximity;
                //switch nearestBeacon.accuracy {
                switch beaconMajor {
                    case 1:
                        message = "You're in the Living Room"
                        turnLights = true
                        groups = 4
                        self.put(["on":false], url: "http://10.0.0.3/api/newdeveloper/groups/5/action"){ (succeeded: Bool, msg: String) -> () in}
                    case 2:
                        message = "You're in the Hallway"
                        turnLights = true
                        groups = 5
                        self.put(["on":false], url: "http://10.0.0.3/api/newdeveloper/groups/4/action"){ (succeeded: Bool, msg: String) -> () in}
                    default:
                        turnLights = false
                        groups = 0
                }
            }else {
                
                if(lastProximity == CLProximity.Unknown) {
                    return;
                }
                
                message = "No beacons are nearby"
                
                turnLights = false
                lastProximity = CLProximity.Unknown
            }
            
            NSLog("%@", message)
            sendLocalNotificationWithMessage(message, turnLights: turnLights, groups: groups)
    }
    
    
    func locationManager(manager: CLLocationManager!,
        didEnterRegion region: CLRegion!) {
            manager.startRangingBeaconsInRegion(region as! CLBeaconRegion)
            manager.startUpdatingLocation()
            
            NSLog("You entered the region")
            
          //  sendLocalNotificationWithMessage("You entered the region", turnLights: true, groups: 4)
            
    }
    
    func locationManager(manager: CLLocationManager!,
        didExitRegion region: CLRegion!) {
            manager.stopRangingBeaconsInRegion(region as! CLBeaconRegion)
            manager.stopUpdatingLocation()
            
            NSLog("You exited the region")
            
          //  sendLocalNotificationWithMessage("You exited the region", turnLights: false, groups: 4)
            
    }
    
}
 | 
	mit | 
	148bd24636782429b486739108694018 | 42.668919 | 285 | 0.581618 | 5.739787 | false | false | false | false | 
| 
	zype/ZypeAppleTVBase | 
	ZypeAppleTVBase/Models/ConsumerModel.swift | 
	1 | 
	1373 | 
	//
//  ConsumerModel.swift
//  Zype
//
//  Created by Ilya Sorokin on 10/14/15.
//  Copyright © 2015 Eugene Lizhnyk. All rights reserved.
//
import UIKit
open class ConsumerModel: NSObject {
    
    fileprivate (set) open var ID:String = ""
    fileprivate (set) open var emailString:String = ""
    fileprivate (set) open var nameString:String = ""
    fileprivate (set) internal var passwordString: String = ""
    fileprivate (set) open var subscriptionCount: Int = 0
    fileprivate (set) open var subscriptionIds: Array<AnyObject> = []
    
    public init(name: String = "", email: String = "", password: String = "", subscription: Int = 0)
    {
        super.init()
        self.nameString = name
        self.emailString = email
        self.passwordString = password
        self.subscriptionCount = subscription
    }
    
    open var isLoggedIn: Bool {
        return ID.isEmpty == false
    }
    
    func setData(_ consumerId: String, email: String, name: String, subscription: Int, subscriptions: Array<AnyObject>)
    {
        ID = consumerId
        emailString = email
        nameString = name
        subscriptionCount = subscription
        subscriptionIds = subscriptions
    }
    
    func reset()
    {
        ID = ""
        emailString = ""
        nameString = ""
        subscriptionCount = 0
        subscriptionIds = []
    }
    
}
 | 
	mit | 
	0131778cc8e330d1fc6f67625496d10a | 25.384615 | 119 | 0.610058 | 4.498361 | false | false | false | false | 
| 
	grandiere/box | 
	box/View/Help/VHelpCell.swift | 
	1 | 
	2893 | 
	import UIKit
class VHelpCell:UICollectionViewCell
{
    private weak var imageView:UIImageView!
    private weak var label:UILabel!
    private weak var layoutLabelHeight:NSLayoutConstraint!
    private let drawingOptions:NSStringDrawingOptions
    private let labelMargin2:CGFloat
    private let kLabelMargin:CGFloat = 20
    private let kLabelMaxHeight:CGFloat = 900
    private let kImageHeight:CGFloat = 240
    
    override init(frame:CGRect)
    {
        drawingOptions = NSStringDrawingOptions([
            NSStringDrawingOptions.usesLineFragmentOrigin,
            NSStringDrawingOptions.usesFontLeading])
        labelMargin2 = kLabelMargin + kLabelMargin
        
        super.init(frame:frame)
        clipsToBounds = true
        backgroundColor = UIColor.clear
        isUserInteractionEnabled = false
        
        let imageView:UIImageView = UIImageView()
        imageView.isUserInteractionEnabled = false
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.contentMode = UIViewContentMode.center
        imageView.clipsToBounds = true
        self.imageView = imageView
        
        let label:UILabel = UILabel()
        label.isUserInteractionEnabled = false
        label.translatesAutoresizingMaskIntoConstraints = false
        label.backgroundColor = UIColor.clear
        label.textAlignment = NSTextAlignment.center
        label.numberOfLines = 0
        self.label = label
        
        addSubview(label)
        addSubview(imageView)
        
        NSLayoutConstraint.topToTop(
            view:imageView,
            toView:self)
        NSLayoutConstraint.height(
            view:imageView,
            constant:kImageHeight)
        NSLayoutConstraint.equalsHorizontal(
            view:imageView,
            toView:self)
        
        NSLayoutConstraint.topToBottom(
            view:label,
            toView:imageView)
        layoutLabelHeight = NSLayoutConstraint.height(
            view:label)
        NSLayoutConstraint.equalsHorizontal(
            view:label,
            toView:self,
            margin:kLabelMargin)
    }
    
    required init?(coder:NSCoder)
    {
        return nil
    }
    
    //MARK: public
    
    func config(model:MHelpProtocol)
    {
        imageView.image = model.image
        
        let attributedText:NSAttributedString = model.message
        label.attributedText = model.message
        
        let width:CGFloat = bounds.maxX
        let usableWidth:CGFloat = width - labelMargin2
        let usableSize:CGSize = CGSize(
            width:usableWidth,
            height:kLabelMaxHeight)
        let textRect:CGRect = attributedText.boundingRect(
            with:usableSize,
            options:drawingOptions,
            context:nil)
        let textHeight:CGFloat = ceil(textRect.size.height)
        layoutLabelHeight.constant = textHeight
    }
}
 | 
	mit | 
	e0b9dad484ddbfe634434c145e2bb66e | 30.791209 | 67 | 0.64224 | 6.103376 | false | false | false | false | 
| 
	MihaiDamian/Dixi | 
	Dixi/Demo.playground/contents.swift | 
	1 | 
	1761 | 
	
import Dixi
import UIKit
let view1 = UIView()
let view2 = UIView()
let view3 = UIView()
let superview = UIView()
superview.addSubview(view1)
superview.addSubview(view2)
superview.addSubview(view3)
// Dixi operators are designed to closely imitate Apple's visual format syntax. The syntax is not identical, though.
let standardHorizontalSpacingConstraint = view1 - view2
// Dixi represents constraints as a custom opaque type. You can transform it to a NSLayoutConstraint or use the UIView
// extension convenience methods to add them directly to a view as NSLayoutConstraints.
superview.addConstraint(standardHorizontalSpacingConstraint)
// Unlike the visual format syntax, you can't create multiple constraints form a single Dixi expression.
// Instead you can easily create an array of constraints.
let constraints = [view1 - view2, view2 - view3]
superview.addConstraints(constraints)
let customHorizontalDistanceConstraint = view1 |- 10 -| view2
let flushViewsConstraint = view1 || view2
let widthGreaterThanConstraint = view1 >= 50
// By default Dixi constraints are declared for the horizontal axis.
// Use the ^ operator to use the vertical axis on any Dixi constraint.
let heightGreaterThanConstraint = ^(view1 >= 50)
// If you want to be explicit you can use the > operator to indicate you want to use the horizontal axis.
let explicitAxisConstraint = >(view1 >= 50)
let equalWidthsConstraint = view1 == view2
// With Dixi it's an error to create a constraint between a view and a superview if that view does not have a superview.
// This is why view1 was added to a superview beforehand.
let leadingSpaceToSuperviewConstraint = 50 |-| view1
let trailingSpaceToSuperviewConstraint = view1 |-| 50
let priorityConstraint = (view1 <= 50) ~ 20
 | 
	mit | 
	56750f55c1d763d174b40b93ecfefa43 | 39.022727 | 120 | 0.783078 | 4.358911 | false | false | false | false | 
| 
	RoverPlatform/rover-ios-beta | 
	Sources/Extensions/URLRequest.swift | 
	1 | 
	2234 | 
	//
//  URLRequest.swift
//  Rover
//
//  Created by Andrew Clunis on 2019-05-31.
//  Copyright © 2019 Rover Labs Inc. All rights reserved.
//
import Foundation
import UIKit
extension URLRequest {
    /// Replace the standard CFNetwork-created User Agent with a more useful one.
    mutating func setRoverUserAgent() {
        // we want to add the Rover SDK version to the User Agent. Sadly, we cannot get our hands on the default user agent sent by CFNetwork, so we have to start from scratch, including reproducing the fields in the stock user agent:
        
        // AppName/$version. (a value exists for this by default, but this version is a bit better than the stock version of this value, which has the app build number rather than version)
        let appBundleDict = Bundle.main.infoDictionary
        let appName = appBundleDict?["CFBundleName"] as? String ?? "unknown"
        let appVersion = appBundleDict?["CFBundleShortVersionString"] as? String ?? "unknown"
        let appDescriptor = appName + "/" + appVersion
        
        // CFNetwork/$version (reproducing it; it exists in the standard iOS user agent, and perhaps some ops tooling will benefit from it being stock)
        let cfNetworkInfo = Bundle(identifier: "com.apple.CFNetwork")?.infoDictionary
        let cfNetworkVersion = cfNetworkInfo?["CFBundleShortVersionString"] as? String ?? "unknown"
        let cfNetworkDescriptor = "CFNetwork/\(cfNetworkVersion)"
        
        // Darwin/$version (reproducing it; it exists in the standard iOS user agent, and perhaps some ops tooling will benefit from it being stock)
        var sysinfo = utsname()
        uname(&sysinfo)
        let dv = String(bytes: Data(bytes: &sysinfo.release, count: Int(_SYS_NAMELEN)), encoding: .ascii)?.trimmingCharacters(in: .controlCharacters) ?? "unknown"
        let darwinDescriptor = "Darwin/\(dv)"
        
        // iOS/$ios-version
        let osDescriptor = "iOS/" + UIDevice.current.systemVersion
        
        // RoverSDK/$rover-sdk-version
        let roverVersion = Meta.SDKVersion
        self.setValue("\(appDescriptor) \(cfNetworkDescriptor) \(darwinDescriptor) \(osDescriptor) RoverSDK/\(roverVersion)", forHTTPHeaderField: "User-Agent")
    }
}
 | 
	mit | 
	08200a20ab5d11735417c20266cb31c6 | 53.463415 | 234 | 0.690551 | 4.661795 | false | false | false | false | 
| 
	sanvital/swift-2048 | 
	swift-2048/Views/TileView.swift | 
	1 | 
	1253 | 
	//
//  TileView.swift
//  swift-2048
//
//  Created by Austin Zheng on 6/3/14.
//  Copyright (c) 2014 Austin Zheng. Released under the terms of the MIT license.
//
import UIKit
/// A view representing a single swift-2048 tile.
class TileView : UIView {
  var value : Int = 0 {
    didSet {
      backgroundColor = delegate.tileColor(value)
      numberLabel.textColor = delegate.numberColor(value)
      numberLabel.text = "\(value)"
    }
  }
  unowned let delegate : AppearanceProviderProtocol
  let numberLabel : UILabel
  required init(coder: NSCoder) {
    fatalError("NSCoding not supported")
  }
    
  init(position: CGPoint, width: CGFloat, value: Int, radius: CGFloat, delegate d: AppearanceProviderProtocol) {
    delegate = d
    numberLabel = UILabel(frame: CGRectMake(0, 0, width, width))
    numberLabel.textAlignment = NSTextAlignment.Center
    numberLabel.minimumScaleFactor = 0.5
    numberLabel.font = delegate.fontForNumbers()
    super.init(frame: CGRectMake(position.x, position.y, width, width))
    addSubview(numberLabel)
    layer.cornerRadius = radius
    self.value = value
    backgroundColor = delegate.tileColor(value)
    numberLabel.textColor = delegate.numberColor(value)
    numberLabel.text = "\(value)"
  }
}
 | 
	mit | 
	d6358a93d5705baad03e7060491ce3c9 | 27.477273 | 112 | 0.701516 | 4.32069 | false | false | false | false | 
| 
	alexktchen/ExchangeRate | 
	SampleKeyboard/BackgroundHighlightedButton.swift | 
	1 | 
	1439 | 
	//
//  BackgroundHighlightedButton.swift
//  ExchangeRate
//
//  Created by Alex Chen on 2015/9/22.
//  Copyright © 2015 Alex Chen. All rights reserved.
//
import Foundation
import UIKit
class BackgroundHighlightedButton: UIButton {
    
    
    @IBInspectable var highlightedBackgroundColor :UIColor?
    @IBInspectable var nonHighlightedBackgroundColor :UIColor?
    
    override var highlighted :Bool {
        get {
            return super.highlighted
        }
        set {
            
            if newValue {
                self.backgroundColor = self.highlightedBackgroundColor
            }
            else {
                self.backgroundColor = self.nonHighlightedBackgroundColor
                
            }
            super.highlighted = newValue
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func drawRect(rect: CGRect) {
        self.layer.cornerRadius = self.bounds.size.width/2.0
        self.layer.borderWidth = 1.0
        self.layer.borderColor =  UIColor.whiteColor().CGColor
        self.titleLabel!.alpha = 1.0
        self.layer.masksToBounds = true
        self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)
        
    }
    
} | 
	mit | 
	eb23d6894b609564a8e2297d24fedabb | 25.648148 | 86 | 0.611266 | 5.045614 | false | false | false | false | 
| 
	rambler-digital-solutions/rambler-it-ios | 
	Carthage/Checkouts/rides-ios-sdk/source/UberRidesTests/RidesMocks.swift | 
	1 | 
	12304 | 
	//
//  RidesMocks.swift
//  UberRides
//
//  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 WebKit
@testable import UberRides
class RideRequestViewMock : RideRequestView {
    var testClosure: (() -> ())?
    init(rideRequestView: RideRequestView, testClosure: (() -> ())?) {
        self.testClosure = testClosure
        super.init(rideParameters: rideRequestView.rideParameters, accessToken: rideRequestView.accessToken, frame: rideRequestView.frame)
    }
    
    required init(rideParameters: RideParameters?, accessToken: AccessToken?, frame: CGRect) {
        fatalError("init(rideParameters:accessToken:frame:) has not been implemented")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func load() {
        self.testClosure?()
    }
    
    override func cancelLoad() {
        self.testClosure?()
    }
}
class RideRequestViewControllerMock : RideRequestViewController {
    var loadClosure: (() -> ())?
    var networkClosure: (() -> ())?
    var notSupportedClosure: (() -> ())?
    var presentViewControllerClosure: ((UIViewController, Bool, (() -> Void)?) -> ())?
    var executeNativeClosure: (() -> ())?
    
    init(rideParameters: RideParameters, loginManager: LoginManager, loadClosure: (() -> ())? = nil, networkClosure: (() -> ())? = nil, presentViewControllerClosure: ((UIViewController, Bool, (() -> Void)?) -> ())? = nil, notSupportedClosure: (() -> ())? = nil) {
        self.loadClosure = loadClosure
        self.networkClosure = networkClosure
        self.notSupportedClosure = notSupportedClosure
        self.presentViewControllerClosure = presentViewControllerClosure
        super.init(rideParameters: rideParameters, loginManager: loginManager)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func load() {
        if let loadClosure = loadClosure {
            loadClosure()
        } else {
            super.load()
        }
    }
    
    override func displayNetworkErrorAlert() {
        if let networkClosure = networkClosure {
            networkClosure()
        } else {
            super.displayNetworkErrorAlert()
        }
    }
    
    override func displayNotSupportedErrorAlert() {
        if let notSupportedClosure = notSupportedClosure {
            notSupportedClosure()
        } else {
            super.displayNotSupportedErrorAlert()
        }
    }
    
    override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)?) {
        if let presentViewControllerClosure = presentViewControllerClosure {
            presentViewControllerClosure(viewControllerToPresent, flag, completion)
        } else {
            super.present(viewControllerToPresent, animated: flag, completion: completion)
        }
    }
    
    override func executeNativeLogin() {
        if let closure = executeNativeClosure {
            closure()
        } else {
            super.executeNativeLogin()
        }
    }
}
class LoginViewMock : LoginView {
    var testClosure: (() -> ())?
    init(loginBehavior: LoginViewAuthenticator, testClosure: (() -> ())?) {
        self.testClosure = testClosure
        super.init(loginAuthenticator: loginBehavior, frame: CGRect.zero)
    }
    
    required override init(loginAuthenticator: LoginViewAuthenticator, frame: CGRect) {
        fatalError("init(scopes:frame:) has not been implemented")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func load() {
        self.testClosure?()
    }
    
    override func cancelLoad() {
        self.testClosure?()
    }
}
class OAuthViewControllerMock : OAuthViewController {
    var presentViewControllerClosure: ((UIViewController, Bool, (() -> Void)?) -> ())?
    
    init(loginView: LoginView, presentViewControllerClosure: ((UIViewController, Bool, (() -> Void)?) -> ())?) {
        self.presentViewControllerClosure = presentViewControllerClosure
        super.init(loginAuthenticator: loginView.loginAuthenticator)
        self.loginView = loginView
    }
    @objc required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)?) {
        if let presentViewControllerClosure = presentViewControllerClosure {
            presentViewControllerClosure(viewControllerToPresent, flag, completion)
        } else {
            super.present(viewControllerToPresent, animated: flag, completion: completion)
        }
    }
}
class WebViewMock : WKWebView {
    var testClosure: ((URLRequest) -> ())?
    init(frame: CGRect, configuration: WKWebViewConfiguration, testClosure: ((URLRequest) -> ())?) {
        self.testClosure = testClosure
        super.init(frame: frame, configuration: configuration)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func load(_ request: URLRequest) -> WKNavigation? {
        testClosure?(request)
        return nil
    }
}
class RequestDeeplinkMock : RequestDeeplink {
    var testClosure: ((URL?) -> (Bool))?
    init(rideParameters: RideParameters, testClosure: ((URL?) -> (Bool))?) {
        self.testClosure = testClosure
        super.init(rideParameters: rideParameters)
    }
    
    override func execute(completion: ((NSError?) -> ())? = nil) {
        guard let testClosure = testClosure else {
            completion?(nil)
            return
        }
        _ = testClosure(deeplinkURL)
    }
}
class DeeplinkRequestingBehaviorMock: DeeplinkRequestingBehavior {
    var testClosure: ((URL?) -> (Bool))?
    init(testClosure: ((URL?) -> (Bool))?) {
        self.testClosure = testClosure
        super.init()
    }
    
    override func createDeeplink(rideParameters: RideParameters) -> RequestDeeplink {
        return RequestDeeplinkMock(rideParameters: rideParameters, testClosure: testClosure)
    }
}
@objc class RideRequestViewControllerDelegateMock : NSObject, RideRequestViewControllerDelegate {
    let testClosure: (RideRequestViewController, NSError) -> ()
    init(testClosure: @escaping (RideRequestViewController, NSError) -> ()) {
        self.testClosure = testClosure
    }
    @objc func rideRequestViewController(_ rideRequestViewController: RideRequestViewController, didReceiveError error: NSError) {
        self.testClosure(rideRequestViewController, error)
    }
}
@objc class DeeplinkingProtocolMock : NSObject, Deeplinking {
    
    let deeplinkingObject: Deeplinking
    
    var executeClosure: ((((NSError?) -> ())?) -> ())?
    var backingScheme: String?
    var backingDomain: String?
    var backingPath: String?
    var backingQueryItems: [URLQueryItem]?
    var backingDeeplinkURL: URL?
    
    var overrideExecute: Bool = false
    var overrideExecuteValue: NSError? = nil
    var scheme: String {
        get {
            return backingScheme ?? deeplinkingObject.scheme
        }
        set(newScheme) {
            backingScheme = newScheme
        }
    }
    
    var domain: String {
        get {
            return backingDomain ?? deeplinkingObject.domain
        }
        set(newDomain) {
            backingDomain = newDomain
        }
    }
    
    var path: String {
        get {
            return backingPath ?? deeplinkingObject.path
        }
        set(newPath) {
            backingPath = newPath
        }
    }
    
    var queryItems: [URLQueryItem]? {
        get {
            return backingQueryItems ?? deeplinkingObject.queryItems
        }
        set(newQueryItems) {
            backingQueryItems = newQueryItems
        }
    }
    
    var deeplinkURL: URL {
        get {
            return backingDeeplinkURL ?? deeplinkingObject.deeplinkURL
        }
        set(newDeeplinkURL) {
            backingDeeplinkURL = newDeeplinkURL
        }
    }
    @objc func execute(completion: ((NSError?) -> ())?) {
        if let closure = executeClosure {
            closure(completion)
        } else if overrideExecute {
            completion?(overrideExecuteValue)
        } else {
            deeplinkingObject.execute(completion: completion)
        }
    }
    
    init(deeplinkingObject: Deeplinking) {
        self.deeplinkingObject = deeplinkingObject
        super.init()
    }
}
@objc class LoginManagingProtocolMock : NSObject, LoginManaging {
    
    var loginClosure: (([RidesScope], UIViewController?, ((_ accessToken: AccessToken?, _ error: NSError?) -> Void)?) -> Void)?
    var openURLClosure: ((UIApplication, URL, String?, Any?) -> Bool)?
    var didBecomeActiveClosure: (() -> ())?
    var backingManager: LoginManaging?
    
    init(loginManaging: LoginManaging? = nil) {
        backingManager = loginManaging
        super.init()
    }
    
    func login(requestedScopes scopes: [RidesScope], presentingViewController: UIViewController?, completion: ((_ accessToken: AccessToken?, _ error: NSError?) -> Void)?) {
        if let closure = loginClosure {
            closure(scopes, presentingViewController, completion)
        } else if let manager = backingManager {
            manager.login(requestedScopes: scopes, presentingViewController: presentingViewController, completion: completion)
        }
    }
    
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        if let closure = openURLClosure {
            return closure(application, url, sourceApplication, annotation)
        } else if let manager = backingManager {
            return manager.application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
        } else {
            return false
        }
    }
    @available(iOS 9.0, *)
    public func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
        let sourceApplication = options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String
        let annotation = options[.annotation] as Any
        return application(app, open: url, sourceApplication: sourceApplication, annotation: annotation)
    }
    func applicationDidBecomeActive() {
        if let closure = didBecomeActiveClosure {
            closure()
        } else if let manager = backingManager {
            manager.applicationDidBecomeActive()
        }
    }
}
class LoginManagerPartialMock : LoginManager {
    
    var executeLoginClosure: (() -> ())?
    
    override func executeLogin() {
        if let closure = executeLoginClosure {
            closure()
        } else {
            super.executeLogin()
        }
    }
}
class NativeAuthenticatorPartialMock : NativeAuthenticator {
    
    var handleRedirectClosure: ((URLRequest) -> (Bool))?
    
    override func handleRedirect(for request: URLRequest) -> Bool {
        if let closure = handleRedirectClosure {
            return closure(request)
        } else {
            return super.handleRedirect(for: request)
        }
    }
    
}
 | 
	mit | 
	81b9d9bf5dfe0e7c07e706a7092aec66 | 33.177778 | 263 | 0.645237 | 5.384683 | false | true | false | false | 
| 
	kunitoku/RssReader | 
	RssReaderSwift4/DetailViewController.swift | 
	1 | 
	1718 | 
	
import UIKit
import WebKit
import RealmSwift
class DetailViewController: UIViewController {
    
    @IBOutlet weak var webView: WKWebView!
    var item: Item?
    
    // loadView()が完了した際に呼ばれるメソッド
    override func viewDidLoad() {
        super.viewDidLoad()
        
        guard let i = item else {
            return
        }
        
        if let url = URL(string: i.link) {
            let request = URLRequest(url: url)
            webView.load(request)
        }
    }
    
    // ブックマークボタンを押した時に呼ばれるメソッド
    @IBAction func addBookmark(_ sender: Any) {
        
        // 確認用のアラート
        let alert = UIAlertController(title: "確認", message: "ブックマークに追加しますか?", preferredStyle: UIAlertControllerStyle.alert)
        
        let okAction = UIAlertAction(title: "はい", style: UIAlertActionStyle.default) {
            (action: UIAlertAction) in
            
            guard let i = self.item else {
                return
            }
            
            let bookmark = Bookmark()
            bookmark.title = i.title
            bookmark.detail = i.detail
            bookmark.link = i.link
            bookmark.date = NSDate()
            
            // ブックマーク追加
            let realm = try! Realm()
            try! realm.write {
                realm.add(bookmark)
            }
        }
        let cancelButton = UIAlertAction(title: "いいえ", style: UIAlertActionStyle.cancel, handler: nil)
        
        alert.addAction(okAction)
        alert.addAction(cancelButton)
        
        present(alert,animated: true, completion: nil)
    }
}
 | 
	mit | 
	e99ba187b3a5f13f1c147cfd3797eb00 | 26.508772 | 123 | 0.538903 | 4.795107 | false | false | false | false | 
| 
	dreamsxin/swift | 
	stdlib/public/core/StringBridge.swift | 
	2 | 
	10930 | 
	//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
#if _runtime(_ObjC)
// Swift's String bridges NSString via this protocol and these
// variables, allowing the core stdlib to remain decoupled from
// Foundation.
/// Effectively an untyped NSString that doesn't require foundation.
public typealias _CocoaString = AnyObject
public // @testable
func _stdlib_binary_CFStringCreateCopy(
  _ source: _CocoaString
) -> _CocoaString {
  let result = _swift_stdlib_CFStringCreateCopy(nil, source)
  Builtin.release(result)
  return result
}
public // @testable
func _stdlib_binary_CFStringGetLength(
  _ source: _CocoaString
) -> Int {
  return _swift_stdlib_CFStringGetLength(source)
}
public // @testable
func _stdlib_binary_CFStringGetCharactersPtr(
  _ source: _CocoaString
) -> UnsafeMutablePointer<UTF16.CodeUnit>? {
  return UnsafeMutablePointer(_swift_stdlib_CFStringGetCharactersPtr(source))
}
/// Bridges `source` to `Swift.String`, assuming that `source` has non-ASCII
/// characters (does not apply ASCII optimizations).
@inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
func _cocoaStringToSwiftString_NonASCII(
  _ source: _CocoaString
) -> String {
  let cfImmutableValue = _stdlib_binary_CFStringCreateCopy(source)
  let length = _stdlib_binary_CFStringGetLength(cfImmutableValue)
  let start = _stdlib_binary_CFStringGetCharactersPtr(cfImmutableValue)
  return String(_StringCore(
    baseAddress: OpaquePointer(start),
    count: length,
    elementShift: 1,
    hasCocoaBuffer: true,
    owner: unsafeBitCast(cfImmutableValue, to: Optional<AnyObject>.self)))
}
/// Loading Foundation initializes these function variables
/// with useful values
/// Produces a `_StringBuffer` from a given subrange of a source
/// `_CocoaString`, having the given minimum capacity.
@inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
internal func _cocoaStringToContiguous(
  source: _CocoaString, range: Range<Int>, minimumCapacity: Int
) -> _StringBuffer {
  _sanityCheck(_swift_stdlib_CFStringGetCharactersPtr(source) == nil,
    "Known contiguously stored strings should already be converted to Swift")
  let startIndex = range.lowerBound
  let count = range.upperBound - startIndex
  let buffer = _StringBuffer(capacity: max(count, minimumCapacity), 
                             initialSize: count, elementWidth: 2)
  _swift_stdlib_CFStringGetCharacters(
    source, _swift_shims_CFRange(location: startIndex, length: count), 
    UnsafeMutablePointer<_swift_shims_UniChar>(buffer.start))
  
  return buffer
}
/// Reads the entire contents of a _CocoaString into contiguous
/// storage of sufficient capacity.
@inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
internal func _cocoaStringReadAll(
  _ source: _CocoaString, _ destination: UnsafeMutablePointer<UTF16.CodeUnit>
) {
  _swift_stdlib_CFStringGetCharacters(
    source, _swift_shims_CFRange(
      location: 0, length: _swift_stdlib_CFStringGetLength(source)), destination)
}
@inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
internal func _cocoaStringSlice(
  _ target: _StringCore, _ bounds: Range<Int>
) -> _StringCore {
  _sanityCheck(target.hasCocoaBuffer)
  
  let cfSelf: _swift_shims_CFStringRef = target.cocoaBuffer.unsafelyUnwrapped
  
  _sanityCheck(
    _swift_stdlib_CFStringGetCharactersPtr(cfSelf) == nil,
    "Known contiguously stored strings should already be converted to Swift")
  let cfResult: AnyObject = _swift_stdlib_CFStringCreateWithSubstring(
    nil, cfSelf, _swift_shims_CFRange(
      location: bounds.lowerBound, length: bounds.count))
  return String(_cocoaString: cfResult)._core
}
@_versioned
@inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
internal func _cocoaStringSubscript(
  _ target: _StringCore, _ position: Int
) -> UTF16.CodeUnit {
  let cfSelf: _swift_shims_CFStringRef = target.cocoaBuffer.unsafelyUnwrapped
  _sanityCheck(_swift_stdlib_CFStringGetCharactersPtr(cfSelf) == nil,
    "Known contiguously stored strings should already be converted to Swift")
  return _swift_stdlib_CFStringGetCharacterAtIndex(cfSelf, position)
}
//
// Conversion from NSString to Swift's native representation
//
internal var kCFStringEncodingASCII : _swift_shims_CFStringEncoding {
  return 0x0600
}
extension String {
  @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
  public // SPI(Foundation)
  init(_cocoaString: AnyObject) {
    if let wrapped = _cocoaString as? _NSContiguousString {
      self._core = wrapped._core
      return
    }
    // "copy" it into a value to be sure nobody will modify behind
    // our backs.  In practice, when value is already immutable, this
    // just does a retain.
    let cfImmutableValue: _swift_shims_CFStringRef
      = _stdlib_binary_CFStringCreateCopy(_cocoaString)
    let length = _swift_stdlib_CFStringGetLength(cfImmutableValue)
    // Look first for null-terminated ASCII
    // Note: the code in clownfish appears to guarantee
    // nul-termination, but I'm waiting for an answer from Chris Kane
    // about whether we can count on it for all time or not.
    let nulTerminatedASCII = _swift_stdlib_CFStringGetCStringPtr(
      cfImmutableValue, kCFStringEncodingASCII)
    // start will hold the base pointer of contiguous storage, if it
    // is found.
    var start: OpaquePointer?
    let isUTF16 = (nulTerminatedASCII == nil)
    if isUTF16 {
      let utf16Buf = _swift_stdlib_CFStringGetCharactersPtr(cfImmutableValue)
      start = OpaquePointer(utf16Buf)
    } else {
      start = OpaquePointer(nulTerminatedASCII)
    }
    self._core = _StringCore(
      baseAddress: start,
      count: length,
      elementShift: isUTF16 ? 1 : 0,
      hasCocoaBuffer: true,
      owner: unsafeBitCast(cfImmutableValue, to: Optional<AnyObject>.self))
  }
}
// At runtime, this class is derived from `_SwiftNativeNSStringBase`,
// which is derived from `NSString`.
//
// The @_swift_native_objc_runtime_base attribute
// This allows us to subclass an Objective-C class and use the fast Swift
// memory allocator.
@objc @_swift_native_objc_runtime_base(_SwiftNativeNSStringBase)
public class _SwiftNativeNSString {}
@objc
public protocol _NSStringCore :
    _NSCopying, _NSFastEnumeration {
  // The following methods should be overridden when implementing an
  // NSString subclass.
  func length() -> Int
  func characterAtIndex(_ index: Int) -> UInt16
  // We also override the following methods for efficiency.
}
/// An `NSString` built around a slice of contiguous Swift `String` storage.
public final class _NSContiguousString : _SwiftNativeNSString {
  public init(_ _core: _StringCore) {
    _sanityCheck(
      _core.hasContiguousStorage,
      "_NSContiguousString requires contiguous storage")
    self._core = _core
    super.init()
  }
  init(coder aDecoder: AnyObject) {
    _sanityCheckFailure("init(coder:) not implemented for _NSContiguousString")
  }
  func length() -> Int {
    return _core.count
  }
  func characterAtIndex(_ index: Int) -> UInt16 {
    return _core[index]
  }
  @inline(__always) // Performance: To save on reference count operations.
  func getCharacters(
    _ buffer: UnsafeMutablePointer<UInt16>,
    range aRange: _SwiftNSRange) {
    _precondition(aRange.location + aRange.length <= Int(_core.count))
    if _core.elementWidth == 2 {
      UTF16._copy(
        source: _core.startUTF16 + aRange.location,
        destination: UnsafeMutablePointer<UInt16>(buffer),
        count: aRange.length)
    }
    else {
      UTF16._copy(
        source: _core.startASCII + aRange.location,
        destination: UnsafeMutablePointer<UInt16>(buffer),
        count: aRange.length)
    }
  }
  @objc
  func _fastCharacterContents() -> UnsafeMutablePointer<UInt16>? {
    return _core.elementWidth == 2 ? _core.startUTF16 : nil
  }
  //
  // Implement sub-slicing without adding layers of wrapping
  //
  func substringFromIndex(_ start: Int) -> _NSContiguousString {
    return _NSContiguousString(_core[Int(start)..<Int(_core.count)])
  }
  func substringToIndex(_ end: Int) -> _NSContiguousString {
    return _NSContiguousString(_core[0..<Int(end)])
  }
  func substringWithRange(_ aRange: _SwiftNSRange) -> _NSContiguousString {
    return _NSContiguousString(
      _core[Int(aRange.location)..<Int(aRange.location + aRange.length)])
  }
  func copy() -> AnyObject {
    // Since this string is immutable we can just return ourselves.
    return self
  }
  /// The caller of this function guarantees that the closure 'body' does not
  /// escape the object referenced by the opaque pointer passed to it or
  /// anything transitively reachable form this object. Doing so
  /// will result in undefined behavior.
  @_semantics("self_no_escaping_closure")
  func _unsafeWithNotEscapedSelfPointer<Result>(
    _ body: @noescape (OpaquePointer) throws -> Result
  ) rethrows -> Result {
    let selfAsPointer = unsafeBitCast(self, to: OpaquePointer.self)
    defer {
      _fixLifetime(self)
    }
    return try body(selfAsPointer)
  }
  /// The caller of this function guarantees that the closure 'body' does not
  /// escape either object referenced by the opaque pointer pair passed to it or
  /// transitively reachable objects. Doing so will result in undefined
  /// behavior.
  @_semantics("pair_no_escaping_closure")
  func _unsafeWithNotEscapedSelfPointerPair<Result>(
    _ rhs: _NSContiguousString,
    _ body: @noescape (OpaquePointer, OpaquePointer) throws -> Result
  ) rethrows -> Result {
    let selfAsPointer = unsafeBitCast(self, to: OpaquePointer.self)
    let rhsAsPointer = unsafeBitCast(rhs, to: OpaquePointer.self)
    defer {
      _fixLifetime(self)
      _fixLifetime(rhs)
    }
    return try body(selfAsPointer, rhsAsPointer)
  }
  public let _core: _StringCore
}
extension String {
  /// Same as `_bridgeToObjectiveC()`, but located inside the core standard
  /// library.
  public func _stdlib_binary_bridgeToObjectiveCImpl() -> AnyObject {
    if let ns = _core.cocoaBuffer where _swift_stdlib_CFStringGetLength(ns) == _core.count {
      return ns
    }
    _sanityCheck(_core.hasContiguousStorage)
    return _NSContiguousString(_core)
  }
  @inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
  public func _bridgeToObjectiveCImpl() -> AnyObject {
    return _stdlib_binary_bridgeToObjectiveCImpl()
  }
}
#endif
 | 
	apache-2.0 | 
	86176345df23e444510feb6576eb98a5 | 32.323171 | 92 | 0.70796 | 4.55227 | false | false | false | false | 
| 
	qkrqjadn/SoonChat | 
	source/FirebaseAPI.swift | 
	1 | 
	1891 | 
	//
//  InfoCellNetApi.swift
//  soonchat
//
//  Created by 박범우 on 2017. 1. 10..
//  Copyright © 2017년 bumwoo. All rights reserved.
//
import Foundation
import Firebase
class FirebaseAPI : NSObject
{
    static let sharedInstance = FirebaseAPI()
    
    let dateString : String = {
        let today = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-DD"
        return dateFormatter.string(from: today)
    }()
    
    lazy var dataBaseForInfo : FIRDatabaseReference = {
        let db = FIRDatabase.database().reference(fromURL: "https://soonchat-840b5.firebaseio.com/").child("infomation")
        return db
    }()
   
    let dataBaseRef : FIRDatabaseReference = {
       let db = FIRDatabase.database().reference(fromURL: "https://soonchat-840b5.firebaseio.com/")
        return db
    }()
    
    let dataStorageRef : FIRStorageReference = {
       let ds = FIRStorage.storage().reference(forURL: "gs://soonchat-840b5.appspot.com")
        return ds
    }()
    
    func addChild(_ PathString : String...) -> FIRDatabaseReference
    {
        var database = dataBaseRef
        for path in PathString
        {
            database = database.child(path)
        }
        return database
    }
    
    let cache = NSCache<AnyObject, AnyObject>()
    func getUserProfileImageUrlForUID(FIRUser:String) -> String?
    {
        if let cache = cache.object(forKey: FIRUser as AnyObject)
        {
            return cache as! String
        }
        var imgurl:String?
        dataBaseRef.child("users").child(FIRUser).child("profileImage").observeSingleEvent(of: .value, with: {[weak self](snapshot) in
            if let `self` = self?.cache.setObject(snapshot.value as AnyObject, forKey: FIRUser as AnyObject){
                imgurl = snapshot.value as? String
            }
        })
        return imgurl
    }
  
}
 | 
	mit | 
	3af4ac2f8938f922ea75f236c4c32baa | 27.953846 | 134 | 0.613709 | 4.34642 | false | false | false | false | 
| 
	LockLight/Weibo_Demo | 
	SinaWeibo/SinaWeibo/Tools/Date+extension.swift | 
	1 | 
	1924 | 
	//
//  Date+extension.swift
//  SinaWeibo
//
//  Created by locklight on 17/4/7.
//  Copyright © 2017年 LockLight. All rights reserved.
//
import UIKit
//DateFormatter,Calendar消耗性能,作为全局变量仅创建一次,oc中作单例
let dateFormatter = DateFormatter()
let calendar = Calendar.current
extension Date{
    static func requiredTimeStr(ServerTime:String) -> String{
        let date = Date.serverTimeToDate(ServerTime: ServerTime)
        return date.dateToRequiredTimeStr()
    }
    
    //结构体的类方法使用static修饰
    //用新浪返回的时间字符串创建date对象
    static func serverTimeToDate(ServerTime:String) -> Date{
        let formatStr = "EEE MMM dd HH:mm:ss zzz yyyy"
        dateFormatter.locale = Locale(identifier: "en")
        dateFormatter.dateFormat = formatStr
        
        return dateFormatter.date(from: ServerTime)!
    }
    
    //将date对象转化为需要的时间字符串
    func dateToRequiredTimeStr ()->String{
        let seconds:Int64 = Int64(Date().timeIntervalSince(self))
        
        if seconds < 60 {
            return "刚刚"
        }
        if seconds < 3600{
            return "\(seconds/60)分钟前"
        }
        if seconds < 3600 * 24 {
            return "\(seconds/3600)小时前"
        }
        
        var formatStr = ""
        if calendar.isDateInToday(self){
            formatStr = "昨天 HH:mm"
        }else{
            let dateYear = calendar.component(.year, from: self)
            let currentYear = calendar.component(.year, from: Date())
            
            if dateYear == currentYear {
                formatStr = "MM-dd HH:mm"
            }else{
                formatStr = "yyyy-MM-dd HH:mm"
            }
        }
        dateFormatter.locale = Locale(identifier: "en")
        dateFormatter.dateFormat = formatStr
        
        return dateFormatter.string(from: self)
    }
}
 | 
	mit | 
	1c4b50a7a245fb45df17295d2c6cf21a | 27.301587 | 69 | 0.584969 | 4.225118 | false | false | false | false | 
| 
	tottokotkd/ColorPack | 
	ColorPack/src/common/library/Function.swift | 
	1 | 
	3252 | 
	//
//  Function.swift
//  ColorPack
//
//  Created by Shusuke Tokuda on 2016/10/28.
//  Copyright © 2016年 tottokotkd. All rights reserved.
//
import Foundation
/// RGB [0% ~ 100%] -> (Hue [0 ~ 360 degree], Saturation & Lightness [0% ~ 100%])
public func getHSL(red: Percentage, green: Percentage, blue: Percentage) -> (hue: Degree?, saturation: Percentage, lightness: Percentage) {
    func getHue(red: Percentage, green: Percentage, blue: Percentage) -> (chroma: Percentage, hue: Degree?) {
        let maxColor = max(red, green, blue)
        let minColor = min(red, green, blue)
        let chroma = maxColor - minColor
        let ratio = degreeMax / 6
        switch (chroma, maxColor) {
        case (0, _):
            return (chroma, nil)
        case (_, red):
            let h = ((green - blue) / chroma).truncatingRemainder(dividingBy: 6)
            return (chroma, h * ratio)
        case (_, green):
            let h = ((blue - red) / chroma) + 2
            return (chroma, h * ratio)
        case (_, blue):
            let h = ((red - green) / chroma) + 4
            return (chroma, h * ratio)
        default:
            return (chroma, nil)
        }
    }
    func getLightness(red: Percentage, green: Percentage, blue: Percentage) -> Percentage {
        let maxColor = max(red, green, blue)
        let minColor = min(red, green, blue)
        return (maxColor + minColor) / 2
    }
    func getSaturation(chroma: Percentage, lightness: Percentage) -> Percentage {
        if lightness == percentageMax || lightness == 0 {
            return 0
        } else {
            return chroma / (percentageMax - abs(2 * lightness - percentageMax)) * percentageMax
        }
    }
    let (chroma, hue) = getHue(red: red, green: green, blue: blue)
    let lightness = getLightness(red: red, green: green, blue: blue)
    let saturation = getSaturation(chroma: chroma, lightness: lightness)
    return (hue: hue?.asDegree, saturation: saturation, lightness: lightness)
}
/// (Hue [0 ~ 360 degree], Saturation & Lightness [0% ~ 100%]) -> RGB [0% ~ 100%]
public func getRGB(hue: Degree?, saturation: Percentage, lightness: Percentage) -> (red: Percentage, green: Percentage, blue: Percentage) {
    func getBaseRGB(hue: Degree?, chroma: Percentage) -> (red: Percentage, green: Percentage, blue: Percentage) {
        if let hue = hue {
            let h = hue / degreeMax * 6
            let mid = chroma * (1 - abs(h.truncatingRemainder(dividingBy: 2) - 1))
            switch h {
            case 0..<1:
                return (chroma, mid, 0)
            case 0..<2:
                return (mid, chroma, 0)
            case 0..<3:
                return (0, chroma, mid)
            case 0..<4:
                return (0, mid, chroma)
            case 0..<5:
                return (mid, 0, chroma)
            case 0..<6:
                return (chroma, 0, mid)
            default:
                return (0, 0, 0)
            }
        } else {
            return (0, 0, 0)
        }
    }
    let chroma = (percentageMax - abs(2 * lightness - percentageMax)) * saturation / percentageMax
    let (r, g, b) = getBaseRGB(hue: hue, chroma: chroma)
    let min = lightness - chroma / 2
    return (r + min, g + min, b + min)
}
 | 
	mit | 
	2b1eda2f21315f1a2435f90e46b54122 | 38.621951 | 139 | 0.552478 | 4.001232 | false | false | false | false | 
| 
	reactive-swift/UV | 
	UV/Timer.swift | 
	1 | 
	3107 | 
	//===--- Timer.swift -------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//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 CUV
import Boilerplate
public typealias uv_timer_p = UnsafeMutablePointer<uv_timer_t>
public typealias TimerCallback = (Timer) -> Void
public class Timer : Handle<uv_timer_p> {
    fileprivate let callback:TimerCallback
    
    public init(loop:Loop, callback:@escaping TimerCallback) throws {
        self.callback = callback
        try super.init { handle in
            uv_timer_init(loop.loop, handle.portable)
        }
    }
    
    //uv_timer_start
    open func start(timeout:Timeout, repeatTimeout:Timeout? = nil) throws {
        try doWithHandle { handle in
            let repeatTimeout = repeatTimeout ?? .Immediate
            try ccall(Error.self) {
                uv_timer_start(handle, timer_cb, timeout.uvTimeout, repeatTimeout.uvTimeout)
            }
        }
    }
    
    //uv_timer_stop
    open func stop() throws {
        try doWithHandle { handle in
            try ccall(Error.self) {
                uv_timer_stop(handle)
            }
        }
    }
    
    //uv_timer_again
    open func again() throws {
        try doWithHandle { handle in
            try ccall(Error.self) {
                uv_timer_again(handle)
            }
        }
    }
    
    open var repeatTimeout:Timeout {
        //uv_timer_get_repeat
        get {
            return handle.isNil ? .Immediate : Timeout(uvTimeout: uv_timer_get_repeat(handle.portable))
        }
        //uv_timer_set_repeat
        set {
            if !handle.isNil {
                uv_timer_set_repeat(handle.portable, newValue.uvTimeout)
            }
        }
    }
    
}
private func _timer_cb(handle:uv_timer_p?) {
    let timer:Timer = Timer.from(handle: handle)
    timer.callback(timer)
}
private func timer_cb(handle:uv_timer_p?) {
    _timer_cb(handle: handle)
}
extension Timeout {
    init(uvTimeout:UInt64) {
        switch uvTimeout {
        case 0:
            self = .Immediate
        case UInt64.max:
            self = .Infinity
        default:
            self = .In(timeout: Double(uvTimeout) / 1000)
        }
    }
    
    var uvTimeout:UInt64 {
        get {
            switch self {
            case .Immediate:
                return 0
            case .Infinity:
                return UInt64.max
            case .In(let timeout):
                return UInt64(timeout * 1000)
            }
        }
    }
}
 | 
	apache-2.0 | 
	28686dc80f423c476c612f83e4369e45 | 26.990991 | 103 | 0.556807 | 4.41963 | false | false | false | false | 
| 
	raphaelhanneken/iconizer | 
	Iconizer/Helper/Constants.swift | 
	1 | 
	1838 | 
	//
// Constants.swift
// Iconizer
// https://github.com/raphaelhanneken/iconizer
//
struct Constants {
    // MARK: - Directory names
    struct Directory {
        static let root = "Iconizer Assets"
        static let appIcon = root + "/App Icons"
        static let iMessageIcon = root + "/iMessage Icons"
        static let launchImage = root + "/Launch Images"
        static let imageSet = root + "/Image Sets"
    }
    struct AssetExtension {
        static let appIcon = "appiconset"
        static let iMessageIcon = "stickersiconset"
        static let imageSet = "imageset"
        static let launchImage = "launchimage"
    }
    // MARK: - Keys to access the user defaults
    struct SettingKeys {
        /// Generate an AppIcon for the Apple Watch.
        static let generateAppIconForAppleWatchKey = "generateAppIconForAppleWatch"
        /// Generate an AppIcon for the iPhone.
        static let generateAppIconForIPhoneKey = "generateAppIconForIPhone"
        /// Generate an AppIcon for the iPad.
        static let generateAppIconForIPadKey = "generateAppIconForIPad"
        /// Generate an AppIcon for OS X.
        static let generateAppIconForMacKey = "generateAppIconForMac"
        /// Generate an AppIcon for CarPlay
        static let generateAppIconForCarKey = "generateAppIconForCar"
        /// Generate an AppIcon for CarPlay
        static let generateMessagesIconKey = "generateIMessageIconKey"
        /// Selected ExportTypeViewController (NSSegmentedControl)
        static let selectedExportTypeKey = "selectedExportType"
        /// Generate a LaunchImage for the iPhone.
        static let generateLaunchImageForIPhoneKey = "generateLaunchImageForIPhone"
        /// Generate a LaunchImage for the iPad.
        static let generateLaunchImageForIPadKey = "generateLaunchImageForIPad"
    }
}
 | 
	mit | 
	52a45525a8e26dae9c4424096d7de4c3 | 39.844444 | 83 | 0.683896 | 5.19209 | false | false | false | false | 
| 
	OpenSourceContributions/SwiftOCR | 
	framework/SwiftOCR/GPUImage2-master/framework/Source/iOS/MovieOutput.swift | 
	4 | 
	11376 | 
	import AVFoundation
public protocol AudioEncodingTarget {
    func activateAudioTrack()
    func processAudioBuffer(_ sampleBuffer:CMSampleBuffer)
}
public class MovieOutput: ImageConsumer, AudioEncodingTarget {
    public let sources = SourceContainer()
    public let maximumInputs:UInt = 1
    
    let assetWriter:AVAssetWriter
    let assetWriterVideoInput:AVAssetWriterInput
    var assetWriterAudioInput:AVAssetWriterInput?
    let assetWriterPixelBufferInput:AVAssetWriterInputPixelBufferAdaptor
    let size:Size
    let colorSwizzlingShader:ShaderProgram
    private var isRecording = false
    private var videoEncodingIsFinished = false
    private var audioEncodingIsFinished = false
    private var startTime:CMTime?
    private var previousFrameTime = kCMTimeNegativeInfinity
    private var previousAudioTime = kCMTimeNegativeInfinity
    private var encodingLiveVideo:Bool
    var pixelBuffer:CVPixelBuffer? = nil
    var renderFramebuffer:Framebuffer!
    
    public init(URL:Foundation.URL, size:Size, fileType:String = AVFileTypeQuickTimeMovie, liveVideo:Bool = false, settings:[String:AnyObject]? = nil) throws {
        if sharedImageProcessingContext.supportsTextureCaches() {
            self.colorSwizzlingShader = sharedImageProcessingContext.passthroughShader
        } else {
            self.colorSwizzlingShader = crashOnShaderCompileFailure("MovieOutput"){try sharedImageProcessingContext.programForVertexShader(defaultVertexShaderForInputs(1), fragmentShader:ColorSwizzlingFragmentShader)}
        }
        
        self.size = size
        assetWriter = try AVAssetWriter(url:URL, fileType:fileType)
        // Set this to make sure that a functional movie is produced, even if the recording is cut off mid-stream. Only the last second should be lost in that case.
        assetWriter.movieFragmentInterval = CMTimeMakeWithSeconds(1.0, 1000)
        
        var localSettings:[String:AnyObject]
        if let settings = settings {
            localSettings = settings
        } else {
            localSettings = [String:AnyObject]()
        }
        
        localSettings[AVVideoWidthKey] = localSettings[AVVideoWidthKey] ?? NSNumber(value:size.width)
        localSettings[AVVideoHeightKey] = localSettings[AVVideoHeightKey] ?? NSNumber(value:size.height)
        localSettings[AVVideoCodecKey] =  localSettings[AVVideoCodecKey] ?? AVVideoCodecH264 as NSString
        
        assetWriterVideoInput = AVAssetWriterInput(mediaType:AVMediaTypeVideo, outputSettings:localSettings)
        assetWriterVideoInput.expectsMediaDataInRealTime = liveVideo
        encodingLiveVideo = liveVideo
        
        // You need to use BGRA for the video in order to get realtime encoding. I use a color-swizzling shader to line up glReadPixels' normal RGBA output with the movie input's BGRA.
        let sourcePixelBufferAttributesDictionary:[String:AnyObject] = [kCVPixelBufferPixelFormatTypeKey as String:NSNumber(value:Int32(kCVPixelFormatType_32BGRA)),
                                                                        kCVPixelBufferWidthKey as String:NSNumber(value:size.width),
                                                                        kCVPixelBufferHeightKey as String:NSNumber(value:size.height)]
        
        assetWriterPixelBufferInput = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput:assetWriterVideoInput, sourcePixelBufferAttributes:sourcePixelBufferAttributesDictionary)
        assetWriter.add(assetWriterVideoInput)
    }
    
    public func startRecording() {
        startTime = nil
        sharedImageProcessingContext.runOperationSynchronously{
            self.isRecording = self.assetWriter.startWriting()
            
            CVPixelBufferPoolCreatePixelBuffer(nil, self.assetWriterPixelBufferInput.pixelBufferPool!, &self.pixelBuffer)
            
            /* AVAssetWriter will use BT.601 conversion matrix for RGB to YCbCr conversion
             * regardless of the kCVImageBufferYCbCrMatrixKey value.
             * Tagging the resulting video file as BT.601, is the best option right now.
             * Creating a proper BT.709 video is not possible at the moment.
             */
            CVBufferSetAttachment(self.pixelBuffer!, kCVImageBufferColorPrimariesKey, kCVImageBufferColorPrimaries_ITU_R_709_2, .shouldPropagate)
            CVBufferSetAttachment(self.pixelBuffer!, kCVImageBufferYCbCrMatrixKey, kCVImageBufferYCbCrMatrix_ITU_R_601_4, .shouldPropagate)
            CVBufferSetAttachment(self.pixelBuffer!, kCVImageBufferTransferFunctionKey, kCVImageBufferTransferFunction_ITU_R_709_2, .shouldPropagate)
            
            let bufferSize = GLSize(self.size)
            var cachedTextureRef:CVOpenGLESTexture? = nil
            let _ = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault, sharedImageProcessingContext.coreVideoTextureCache, self.pixelBuffer!, nil, GLenum(GL_TEXTURE_2D), GL_RGBA, bufferSize.width, bufferSize.height, GLenum(GL_BGRA), GLenum(GL_UNSIGNED_BYTE), 0, &cachedTextureRef)
            let cachedTexture = CVOpenGLESTextureGetName(cachedTextureRef!)
            
            self.renderFramebuffer = try! Framebuffer(context:sharedImageProcessingContext, orientation:.portrait, size:bufferSize, textureOnly:false, overriddenTexture:cachedTexture)
        }
    }
    
    public func finishRecording(_ completionCallback:(() -> Void)? = nil) {
        sharedImageProcessingContext.runOperationSynchronously{
            self.isRecording = false
            
            if (self.assetWriter.status == .completed || self.assetWriter.status == .cancelled || self.assetWriter.status == .unknown) {
                sharedImageProcessingContext.runOperationAsynchronously{
                    completionCallback?()
                }
                return
            }
            if ((self.assetWriter.status == .writing) && (!self.videoEncodingIsFinished)) {
                self.videoEncodingIsFinished = true
                self.assetWriterVideoInput.markAsFinished()
            }
            if ((self.assetWriter.status == .writing) && (!self.audioEncodingIsFinished)) {
                self.audioEncodingIsFinished = true
                self.assetWriterAudioInput?.markAsFinished()
            }
            
            // Why can't I use ?? here for the callback?
            if let callback = completionCallback {
                self.assetWriter.finishWriting(completionHandler: callback)
            } else {
                self.assetWriter.finishWriting{}
                
            }
        }
    }
    
    public func newFramebufferAvailable(_ framebuffer:Framebuffer, fromSourceIndex:UInt) {
        defer {
            framebuffer.unlock()
        }
        guard isRecording else { return }
        // Ignore still images and other non-video updates (do I still need this?)
        guard let frameTime = framebuffer.timingStyle.timestamp?.asCMTime else { return }
        // If two consecutive times with the same value are added to the movie, it aborts recording, so I bail on that case
        guard (frameTime != previousFrameTime) else { return }
        
        if (startTime == nil) {
            if (assetWriter.status != .writing) {
                assetWriter.startWriting()
            }
            
            assetWriter.startSession(atSourceTime: frameTime)
            startTime = frameTime
        }
        
        // TODO: Run the following on an internal movie recording dispatch queue, context
        guard (assetWriterVideoInput.isReadyForMoreMediaData || (!encodingLiveVideo)) else {
            debugPrint("Had to drop a frame at time \(frameTime)")
            return
        }
        
        if !sharedImageProcessingContext.supportsTextureCaches() {
            let pixelBufferStatus = CVPixelBufferPoolCreatePixelBuffer(nil, assetWriterPixelBufferInput.pixelBufferPool!, &pixelBuffer)
            guard ((pixelBuffer != nil) && (pixelBufferStatus == kCVReturnSuccess)) else { return }
        }
        
        renderIntoPixelBuffer(pixelBuffer!, framebuffer:framebuffer)
        
        if (!assetWriterPixelBufferInput.append(pixelBuffer!, withPresentationTime:frameTime)) {
            debugPrint("Problem appending pixel buffer at time: \(frameTime)")
        }
        
        CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue:CVOptionFlags(0)))
        if !sharedImageProcessingContext.supportsTextureCaches() {
            pixelBuffer = nil
        }
    }
    
    func renderIntoPixelBuffer(_ pixelBuffer:CVPixelBuffer, framebuffer:Framebuffer) {
        if !sharedImageProcessingContext.supportsTextureCaches() {
            renderFramebuffer = sharedImageProcessingContext.framebufferCache.requestFramebufferWithProperties(orientation:framebuffer.orientation, size:GLSize(self.size))
            renderFramebuffer.lock()
        }
        
        renderFramebuffer.activateFramebufferForRendering()
        clearFramebufferWithColor(Color.black)
        CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue:CVOptionFlags(0)))
        renderQuadWithShader(colorSwizzlingShader, uniformSettings:ShaderUniformSettings(), vertices:standardImageVertices, inputTextures:[framebuffer.texturePropertiesForOutputRotation(.noRotation)])
        
        if sharedImageProcessingContext.supportsTextureCaches() {
            glFinish()
        } else {
            glReadPixels(0, 0, renderFramebuffer.size.width, renderFramebuffer.size.height, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), CVPixelBufferGetBaseAddress(pixelBuffer))
            renderFramebuffer.unlock()
        }
    }
    
    // MARK: -
    // MARK: Audio support
    public func activateAudioTrack() {
        // TODO: Add ability to set custom output settings
        assetWriterAudioInput = AVAssetWriterInput(mediaType:AVMediaTypeAudio, outputSettings:nil)
        assetWriter.add(assetWriterAudioInput!)
        assetWriterAudioInput?.expectsMediaDataInRealTime = encodingLiveVideo
    }
    
    public func processAudioBuffer(_ sampleBuffer:CMSampleBuffer) {
        guard let assetWriterAudioInput = assetWriterAudioInput else { return }
        
        sharedImageProcessingContext.runOperationSynchronously{
            let currentSampleTime = CMSampleBufferGetOutputPresentationTimeStamp(sampleBuffer)
            if (self.startTime == nil) {
                if (self.assetWriter.status != .writing) {
                    self.assetWriter.startWriting()
                }
                
                self.assetWriter.startSession(atSourceTime: currentSampleTime)
                self.startTime = currentSampleTime
            }
            
            guard (assetWriterAudioInput.isReadyForMoreMediaData || (!self.encodingLiveVideo)) else {
                return
            }
            
            if (!assetWriterAudioInput.append(sampleBuffer)) {
                print("Trouble appending audio sample buffer")
            }
        }
    }
}
public extension Timestamp {
    public init(_ time:CMTime) {
        self.value = time.value
        self.timescale = time.timescale
        self.flags = TimestampFlags(rawValue:time.flags.rawValue)
        self.epoch = time.epoch
    }
    
    public var asCMTime:CMTime {
        get {
            return CMTimeMakeWithEpoch(value, timescale, epoch)
        }
    }
}
 | 
	apache-2.0 | 
	eb5ed54fd977dc2aaff8fef2f6c5d624 | 48.676856 | 295 | 0.675281 | 5.839836 | false | false | false | false | 
| 
	mrdepth/Neocom | 
	Legacy/Neocom/Neocom/NCSolarSystemsViewController.swift | 
	2 | 
	2687 | 
	//
//  NCSolarSystemsViewController.swift
//  Neocom
//
//  Created by Artem Shimanski on 01.08.17.
//  Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import CoreData
import EVEAPI
import Futures
class NCSolarSystemRow: NCFetchedResultsObjectNode<NCDBMapSolarSystem> {
	
	lazy var title: NSAttributedString = {
		return NCLocation(self.object).displayName
	}()
	
	required init(object: NCDBMapSolarSystem) {
		super.init(object: object)
		cellIdentifier = Prototype.NCDefaultTableViewCell.noImage.reuseIdentifier
	}
	
	override func configure(cell: UITableViewCell) {
		guard let cell = cell as? NCDefaultTableViewCell else {return}
		cell.titleLabel?.attributedText = title
	}
}
class NCSolarSystemsViewController: NCTreeViewController, NCSearchableViewController {
	
	var region: NCDBMapRegion?
	
	override func viewDidLoad() {
		super.viewDidLoad()
		
		tableView.register([Prototype.NCDefaultTableViewCell.noImage,
		                    Prototype.NCHeaderTableViewCell.default])
		title = region?.regionName
		
		let controller = self.storyboard!.instantiateViewController(withIdentifier: "NCLocationSearchResultsViewController") as! NCLocationSearchResultsViewController
		controller.region = region
		setupSearchController(searchResultsController: controller)
	}
	
	override func content() -> Future<TreeNode?> {
		guard let region = region else {return .init(nil)}
		let request = NSFetchRequest<NCDBMapSolarSystem>(entityName: "MapSolarSystem")
		request.predicate = NSPredicate(format: "constellation.region == %@", region)
		request.sortDescriptors = [NSSortDescriptor(key: "solarSystemName", ascending: true)]
		let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: NCDatabase.sharedDatabase!.viewContext, sectionNameKeyPath: nil, cacheName: nil)
		
		return .init(FetchedResultsNode(resultsController: results, sectionNode: nil, objectNode: NCSolarSystemRow.self))
	}
	
	//MARK: - TreeControllerDelegate
	
	override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) {
		super.treeController(treeController, didSelectCellWithNode: node)
		guard let row = node as? NCSolarSystemRow else {return}
		guard let picker = navigationController as? NCLocationPickerViewController else {return}
		picker.completionHandler(picker, row.object)
	}
	
	//MARK: NCSearchableViewController
	
	var searchController: UISearchController?
	
	func updateSearchResults(for searchController: UISearchController) {
		guard let controller = searchController.searchResultsController as? NCLocationSearchResultsViewController else {return}
		controller.updateSearchResults(for: searchController)
	}
}
 | 
	lgpl-2.1 | 
	4a623cc1b769a78f3f8c1c400ebf5d5d | 35.297297 | 168 | 0.791139 | 4.91042 | false | false | false | false | 
| 
	petrmanek/revolver | 
	Sources/Individual.swift | 
	1 | 
	1336 | 
	
/// A single individual of a population.
open class Individual<Chromosome: ChromosomeType>: Randomizable, FitnessType, ChromosomeType, Copyable {
    
    /// Genetic information of the individual.
    open let chromosome: Chromosome
    
    /// Fitness evaluation of the individual.
    open var fitness: Fitness?
    
    /**
     Construct a new random individual.
     
     - parameter generator: Provider of randomness.
     
     - returns: New individual with random chromosome.
     */
    public required init(generator: EntropyGenerator) {
        self.chromosome = Chromosome(generator: generator)
        self.fitness = nil
    }
    
    /**
     Construct a new individual with a specific chromosome.
     
     - parameter chromosome: Genetic information to initialize.
     
     - returns: New individual with given chromosome.
     */
    public init(chromosome: Chromosome) {
        self.chromosome = chromosome
        self.fitness = nil
    }
    
    /**
     Construct a copy of other individual.
     
     - parameter original: The individual to copy.
     
     - returns: Identical copy of the original individual.
     */
    public required init(original: Individual<Chromosome>) {
        self.chromosome = Chromosome(original: original.chromosome)
        self.fitness = original.fitness
    }
    
}
 | 
	mit | 
	3f90088a2014acb9a656d6de2a946233 | 27.425532 | 104 | 0.651946 | 5.408907 | false | false | false | false | 
| 
	wanliming11/MurlocAlgorithms | 
	Last/Algorithms/SwiftAligorithmsTesting.playground/Contents.swift | 
	1 | 
	8922 | 
	//: Playground - noun: a place where people can play
import UIKit
typealias Condition<T> = (T, T)->Bool
/**
 插入排序
 [1,5,6]
 
 [1] is sorted
 ^ insert 5
 [1, 5]
 ^ 5 > 1 == true
 [1, 5]
  <--> swap
 [5, 1]
     ^ insert 6
 [5, 1, 6]
     ^ 6 > 1 == true
 [5, 1, 6]
     <--> swap
 [5, 6, 1]
 ^ 6>5 == true
 [5, 6 ,1]
 <--> swap
 [6, 5, 1] index = 0 end sorted
 
 1. 把后面的元素不断插入到前面已经有序的数组中去,不断让1,2,...,n-1 个数组有序
 2. 注意永远都是相邻元素的交换,后面的元素同前一个进行比较,如果不符合顺序则交换
*/
/*typealias Criteria<T> = (T, T)->Bool
func insertionSortof<T:Comparable>(_ coll:Array<T>, byCriteria:Criteria<T> = {$0 < $1})->Array<T>{
    guard coll.count > 1 else {
        return coll
    }
    var result = coll
    for x in 1..<coll.count {
        //记录需要排序的position
        var position = x
        //记录对应的key
        let key = result[position]
        //从后往前相邻的位置进行交换
        while position>0 && byCriteria(key, result[position-1]) {
            print("------")
            print("Remove \(key) at pos:\(position)")
            print("Insert \(key) at pos: \(position-1)")
            print("------")
            
            
            //可以使用数组操作或者是交换函数
            swap(&result[position], &result[position-1])
//            result.remove(at: position)
//            result.insert(key, at: position-1)
            position -= 1
        }
    }
    return result
}
let a = [1,5,6]
insertionSortof(a, byCriteria:>)*/
//Rewrite
//先定义一个比较的alias, 用于对元素进行比较,可以执行升序或降序
typealias ConditionInsertion<T> = (T, T)->Bool
//函数名为插入排序, 第一个参数如果带lable放到参数名之后
//指定类型里面的T 泛型是需要支持Comparable协议的,这样才可以支持比较操作
//直接指定比较条件是前面元素和后面元素的比较
func insectionSortOf<T:Comparable>(_ coll:Array<T>, by condition:Condition<T> = {$0>$1})->Array<T> {
    //guard 护卫 保证护卫的条件,else 执行其他
    guard coll.count > 1 else {
        return coll
    }
    
    var resultArray = coll
    ///从第一个元素开始比较,从后往前相邻交换
    for x in 1..<coll.count{
        var comparedIndex = x; //因为需要从后往前进行比较,这个索引会变,所以记录下来
        //满足条件才进行交换
        while comparedIndex>0 && condition(resultArray[comparedIndex], resultArray[comparedIndex-1]) {
            swap(&resultArray[comparedIndex], &resultArray[comparedIndex-1])
            comparedIndex -= 1;
        }
    }
    return resultArray
}
let beSortArray:Array<Int> = [2,1,4,3]
insectionSortOf(beSortArray)
insectionSortOf(beSortArray, by: <)
//希尔排序
/***************=======================无敌分割线===================================*************/
//选择排序
/**
    不断从未排序的队列中选择数据放到已排序的数组中
 [ | 1,5,7, 6]
     *<-->*
 [ | 7,5,1, 6]
   ^ -->
 [7, |, 5, 1, 6]
        *<---->
 */
typealias ConditionSelection<T> = (T, T)->Bool
func selectionOrderOf<T:Comparable>(_ coll:Array<T>, byCondition:Condition<T> = {$0>$1})->Array<T> {
    guard coll.count>1 else {
        return coll
    }
    var result = coll
    //每次循环固定一个数据到已排序最末端
    for x in 0..<result.count {
        //记录住这个需要排序的元素位置
        print("-------")
        print("sorted array \(result[0..<x])")
        print("unsorted array \(result[x..<result.count])")
        //从下一位开始选择出需要进行交换的元素
        //之所以给初始值,因为如果找不到,则相当于不动,自身交换
        var markIndex = x
        for y in x+1..<result.count {
            if byCondition(result[markIndex], result[y]) {
                markIndex = y
            }
        }
        
        if (markIndex != x){
            swap(&result[x], &result[markIndex])
            print("=== move index \(markIndex)")
        }
    }
    return result
}
let unorderedArray = [1,3,4,7]
selectionOrderOf(unorderedArray)
selectionOrderOf(unorderedArray, byCondition: <)
//堆排序
/**
    基于大小顶堆(父节点比左右child都要大或小)
    二叉树的基本知识:1+2+4+8+16.。。
    则第i层至多有2^(i-1)个节点
    深度为k的二叉树至多有2^k -1 个节点
 */
/***************=======================无敌分割线===================================*************/
//冒泡排序
/** 
 [1, 2, 1, 11, 9, 6]
  ^
 [1, 2, 1, 11, 9, 6]
               <--> 9 > 6 swap
 [1, 2, 1, 11, 6, 9]
            <--> 11 > 6 swap
 [1, 2, 1, 6, 11, 9]
 [1, 2, 1, 6, 11 ,9]
 [1, 1, 2, 6, 11, 9]
  ^-->
 [1, 1, 2, 6, 11, 9]
     ^
 [1, 1, 2, 6, 11, 9] 
               <-->
 ....
*/
func bubbleSortArrayOf<T:Comparable>(_ coll:Array<T>, byCondition:Condition<T> = {$0>$1})->Array<T>{
    guard coll.count > 1 else {
        return coll
    }
    var resultColl = coll
    var isSorted = true   //这里是做了一个优化标记,如果一趟内部的排序已经有序了,则不需继续再比较了,因为比较是基于相邻两个的,既然相邻的都有序了,那还比较什么
    for markedPositon in 0..<coll.count-1 {  //只需要固定前面的count-1个即确定了所有
        for x in (markedPositon..<coll.count).reversed(){
            if (x != 0){
                if byCondition(resultColl[x], resultColl[x-1]) {
                    swap(&resultColl[x], &resultColl[x-1])
                    isSorted = false
                }
            }
        }
        if isSorted {
            break
        }
    }
    return resultColl
}
let beBubbleArray = [1, 1, 2, 6, 11, 9]
bubbleSortArrayOf(beBubbleArray)
bubbleSortArrayOf(beBubbleArray, byCondition: <)
//快速排序
/**
    假设降序
    快排三个基础,一个left, 一个right, 一个base数,一般等于left,既然等于left,则从右边开始找,找到比left大的
    则丢给left,这样就满足了左边的第一个数满足排序
   [1, 11, 0, 6, 9, 8]   //提取base = 1,从右边找到比1大的停止,然后把这个数给base赋予的位置
   [8, 11, 0, 6, 9, 8]   //base = 1
    left            right
   [8, 11, 0, 6, 9, 8]   //left 往右走,找比base小的,找到就停止,然后把right赋予找到的
   [8, 11, 0, 6, 9, 0]
           left     right
   [8, 11, 9, 6, 9, 0]
           left  right
   [8, 11, 9, 6, 9, 0]
                 ^相遇 则base 交换
   [8, 11, 9, 6, 1, 0]
    
    然后分为两部分
    [8, 11, 9, 6] [0]   //执行上面一样的操作
    例如降序
    快排目的: 快速的找到基准数应该放在的位置,而找到比基准数大的则交给left,然后换一遍继续,直到相遇,把相遇的点就是基准数的位置
    三部:
    传人左右位置,分为两部分继续递归
  */
//找到最应该插入的位置
func searchQuickSortPositon<T:Comparable>(_ coll:inout Array<T>, left:Int, right:Int, byCondition:Condition<T>) -> Int {
    guard left < right else {
        return left
    }
    
    var left = left
    var right = right
    let base = coll[left]
    while left < right {
        //一直找到一个right >= base 停止, 即byCondition(coll[right], base), 非的情况下才循环
        while left<right && !byCondition(coll[right], base) {
            right = right - 1;
        }
        //找到的给左边
        coll[left]  = coll[right]
        
        //找到left<= base 停止,即byCondition(coll[left], base) 继续循环
        while left<right && byCondition(coll[left], base) {
            left = left + 1;
        }
        coll[right] = coll[left]
    }
    
    coll[left] = base
    return left
}
//递归函数里面分为两部分来执行
func quickSortOf<T:Comparable>(_ coll:inout Array<T>, left:Int, right:Int, byCondition:Condition<T>) -> Array<T> {
    guard left < right else {
        return coll
    }
    
    //找到最开始的位置
    let findPosition = searchQuickSortPositon(&coll, left: left, right: right, byCondition:byCondition)
    quickSortOf(&coll, left: left, right:findPosition-1, byCondition:byCondition)
    quickSortOf(&coll, left: findPosition+1, right:right, byCondition:byCondition)
    return coll
}
func quickSortOf<T:Comparable>(_ coll:inout Array<T>, byCondition:Condition<T> = {$0 >= $1})-> Array<T>{
    guard coll.count > 1 else {
        return coll
    }
    
    return quickSortOf(&coll, left: 0, right: coll.count-1, byCondition:byCondition)
}
//var beQuickSortArray = [1, 3, 2, 6, 8, 9]
var beQuickSortArray = Array([1, 3, 2, 6, 8, 9].reversed())
//var beQuickSortArray = [1, 1, 1, 1, 1, 1]
//var beQuickSortArray = [1]
let splitedArray = quickSortOf(&beQuickSortArray,byCondition: <)
 | 
	mit | 
	b7423d60ea0248e6c46464786011aca6 | 25.064516 | 120 | 0.55198 | 2.97545 | false | false | false | false | 
| 
	devandsev/theTVDB-iOS | 
	tvShows/Source/Services/SessionService.swift | 
	1 | 
	2045 | 
	//
//  SessionService.swift
//  tvShows
//
//  Created by Andrey Sevrikov on 21/08/2017.
//  Copyright © 2017 devandsev. All rights reserved.
//
import Foundation
import KeychainAccess
protocol HasSessionService {
    var sessionService: SessionService { get }
}
class SessionService: HasDependencies {
    
    typealias Dependencies = HasApiService & HasConfigService & HasAPI
    var di: Dependencies!
    
    private let keychain = Keychain(service: KeychainKeys.keychainService)
    
    private struct KeychainKeys {
        static let keychainService = "tvShows.keychain"
        static let authToken = "session.authToken"
    }
    
    func restore(success: @escaping () -> Void,
                 failure: @escaping (APIError) -> Void) {
        
        guard let authToken = keychain[KeychainKeys.authToken] else {
            self.reset(success: { 
                success()
            }, failure: { error in
                failure(error)
            })
            
            return
        }
        
        self.di.apiService.authToken = authToken
        success()
    }
    
    func reset(success: @escaping () -> Void,
               failure: @escaping (APIError) -> Void) {
        
        self.di.api.authentication.login(apiKey: self.di.configService.apiKey, userKey: nil, userName: nil, success: { token in
            self.keychain[KeychainKeys.authToken] = token
            self.di.apiService.authToken = token
            success()
        }) { error in
            failure(error)
        }
    }
    
    func updateIfNeeded(error: APIError,
                        success: @escaping () -> Void,
                        failure: @escaping (APIError) -> Void) {
        
        guard case let APIError.httpError(httpError) = error,
        case let HTTPError.serverError(_, code) = httpError,
        code == 401 else {
            failure(error)
            return
        }
        
        self.reset(success: { 
            success()
        }) { error in
            failure(error)
        }
    }
}
 | 
	mit | 
	4f857553db2925f7392a07bc282308ae | 26.621622 | 127 | 0.555284 | 4.866667 | false | false | false | false | 
| 
	mvader/advent-of-code | 
	2020/12/01.swift | 
	1 | 
	1525 | 
	import Foundation
struct Instruction {
  let action: String
  let value: Int
}
let directions: [Direction] = [.north, .east, .south, .west]
enum Direction {
  case north, south, west, east
  func advance(_ x: Int, _ y: Int, n: Int) -> (Int, Int) {
    switch self {
    case .north: return (x, y + n)
    case .south: return (x, y - n)
    case .west: return (x - n, y)
    case .east: return (x + n, y)
    }
  }
  func rotate(_ angle: Int) -> Direction {
    let dir = angle > 0 ? directions : directions.reversed()
    return dir[(Int(dir.firstIndex(of: self)!) + (abs(angle) / 90)) % dir.count]
  }
}
struct Position {
  var x: Int
  var y: Int
}
func navigate(_ instructions: [Instruction]) -> (Int, Int) {
  var dir = Direction.east
  var (x, y) = (0, 0)
  for i in instructions {
    switch i.action {
    case "N": (x, y) = Direction.north.advance(x, y, n: i.value)
    case "S": (x, y) = Direction.south.advance(x, y, n: i.value)
    case "E": (x, y) = Direction.east.advance(x, y, n: i.value)
    case "W": (x, y) = Direction.west.advance(x, y, n: i.value)
    case "L": dir = dir.rotate(-i.value)
    case "R": dir = dir.rotate(i.value)
    case "F": (x, y) = dir.advance(x, y, n: i.value)
    default: continue
    }
  }
  return (x, y)
}
let instructions = try String(contentsOfFile: "./input.txt", encoding: .utf8)
  .components(separatedBy: "\n")
  .map { s in Instruction(action: String(s.prefix(1)), value: Int(String(s.dropFirst()))!) }
let (x, y) = navigate(instructions)
print(abs(x) + abs(y))
 | 
	mit | 
	2b07ad75517373e71974ed156e23e3dd | 25.293103 | 92 | 0.593443 | 2.893738 | false | false | false | false | 
| 
	debugsquad/Hyperborea | 
	Hyperborea/Model/Search/MSearchResultsItem.swift | 
	1 | 
	3554 | 
	import UIKit
class MSearchResultsItem
{
    private static let kReplaceA:String = "á"
    private static let kReplaceE:String = "é"
    private static let kReplaceI:String = "í"
    private static let kReplaceO:String = "ó"
    private static let kReplaceU:String = "ú"
    private static let kReplaceExcalamation:String = "¡"
    private static let kReplaceDiagonal:String = "%2F"
    private static let kReplaceUnderscore:String = "_"
    private static let kNormalA:String = "a"
    private static let kNormalE:String = "e"
    private static let kNormalI:String = "i"
    private static let kNormalO:String = "o"
    private static let kNormalU:String = "u"
    private static let kNormalExclamation:String = "%C2%A1"
    private static let kNormalDiagonal:String = "%2F"
    private static let kNormalUnderscore:String = " "
    
    let wordId:String
    let word:String
    let matchType:String
    let region:String?
    let languageRaw:Int16
    var attributedString:NSAttributedString?
    var cellWidth:CGFloat
    var cellHeight:CGFloat
    private let kKeyWord:String = "word"
    private let kKeyWordId:String = "id"
    private let kKeyRegion:String = "region"
    private let kKeyMathType:String = "matchType"
    
    private class func normalizeWordId(wordId:String) -> String
    {
        var newWordId:String = wordId
        
        newWordId = newWordId.replacingOccurrences(
            of:kReplaceA,
            with:kNormalA)
        newWordId = newWordId.replacingOccurrences(
            of:kReplaceE,
            with:kNormalE)
        newWordId = newWordId.replacingOccurrences(
            of:kReplaceI,
            with:kNormalI)
        newWordId = newWordId.replacingOccurrences(
            of:kReplaceO,
            with:kNormalO)
        newWordId = newWordId.replacingOccurrences(
            of:kReplaceU,
            with:kNormalU)
        newWordId = newWordId.replacingOccurrences(
            of:kReplaceExcalamation,
            with:kNormalExclamation)
        newWordId = newWordId.replacingOccurrences(
            of:kReplaceDiagonal,
            with:kNormalDiagonal)
        newWordId = newWordId.replacingOccurrences(
            of:kNormalUnderscore,
            with:kReplaceUnderscore)
        
        return newWordId
    }
    
    private class func normalizeWord(word:String) -> String
    {
        var newWord:String = word
        
        if let decodeWord:String = newWord.removingPercentEncoding
        {
            newWord = decodeWord
        }
        
        newWord = newWord.replacingOccurrences(
            of:kReplaceUnderscore,
            with:kNormalUnderscore)
        
        return newWord
    }
    
    init?(
        json:Any,
        language:MLanguage)
    {
        let jsonMap:[String:Any]? = json as? [String:Any]
        
        guard
            
            let rawWordId:String = jsonMap?[kKeyWordId] as? String,
            let matchType:String = jsonMap?[kKeyMathType] as? String,
            let rawWord:String = jsonMap?[kKeyWord] as? String
            
        else
        {
            return nil
        }
        
        let wordId:String = MSearchResultsItem.normalizeWordId(
            wordId:rawWordId)
        let word:String = MSearchResultsItem.normalizeWord(
            word:rawWord)
        
        cellWidth = 0
        cellHeight = 0
        languageRaw = language.rawValue
        self.region = jsonMap?[kKeyRegion] as? String
        self.wordId = wordId
        self.word = word
        self.matchType = matchType
    }
}
 | 
	mit | 
	71523fc247502becbda80f721850b232 | 30.39823 | 69 | 0.614994 | 4.893793 | false | false | false | false | 
| 
	narner/AudioKit | 
	Playgrounds/AudioKitPlaygrounds/Playgrounds/Synthesis.playground/Pages/Vocal Tract Operation.xcplaygroundpage/Contents.swift | 
	1 | 
	1090 | 
	//: ## Vocal Tract Operation
//:
//: Sometimes as audio developers, we just like to have some fun.
import AudioKitPlaygrounds
import AudioKit
let playRate = 2.0
let generator = AKOperationGenerator { _ in
    let frequency = AKOperation.sineWave(frequency: 1).scale(minimum: 100, maximum: 300)
    let jitter = AKOperation.jitter(amplitude: 300, minimumFrequency: 1, maximumFrequency: 3)
    let position = AKOperation.sineWave(frequency: 0.1).scale()
    let diameter = AKOperation.sineWave(frequency: 0.2).scale()
    let tenseness = AKOperation.sineWave(frequency: 0.3).scale()
    let nasality = AKOperation.sineWave(frequency: 0.35).scale()
    return AKOperation.vocalTract(frequency: frequency + jitter,
                                  tonguePosition: position,
                                  tongueDiameter: diameter,
                                  tenseness: tenseness,
                                  nasality: nasality)
}
AudioKit.output = generator
AudioKit.start()
generator.start()
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
 | 
	mit | 
	e11a69ca633382492ebfbad678393025 | 37.928571 | 93 | 0.668807 | 4.678112 | false | false | false | false | 
| 
	stephentyrone/swift | 
	test/AutoDiff/validation-test/simple_math.swift | 
	1 | 
	12231 | 
	// RUN: %target-run-simple-swift
// NOTE(TF-813): verify that enabling forward-mode does not affect reverse-mode.
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-forward-mode-differentiation)
// RUN: %target-swift-frontend -Xllvm -sil-print-after=differentiation %s -emit-sil -o /dev/null -module-name null 2>&1 | %FileCheck %s
// REQUIRES: executable_test
import StdlibUnittest
import DifferentiationUnittest
var SimpleMathTests = TestSuite("SimpleMath")
SimpleMathTests.test("Arithmetics") {
  func foo1(x: Float, y: Float) -> Float {
    return x * y
  }
  expectEqual((4, 3), gradient(at: 3, 4, in: foo1))
  func foo2(x: Float, y: Float) -> Float {
    return -x * y
  }
  expectEqual((-4, -3), gradient(at: 3, 4, in: foo2))
  func foo3(x: Float, y: Float) -> Float {
    return -x + y
  }
  expectEqual((-1, 1), gradient(at: 3, 4, in: foo3))
}
SimpleMathTests.test("Fanout") {
  func foo1(x: Float) -> Float {
     x - x
  }
  expectEqual(0, gradient(at: 100, in: foo1))
  func foo2(x: Float) -> Float {
     x + x
  }
  expectEqual(2, gradient(at: 100, in: foo2))
  func foo3(x: Float, y: Float) -> Float {
    x + x + x * y
  }
  expectEqual((4, 3), gradient(at: 3, 2, in: foo3))
}
SimpleMathTests.test("FunctionCall") {
  func foo(_ x: Float, _ y: Float) -> Float {
    return 3 * x + { $0 * 3 }(3) * y
  }
  expectEqual((3, 9), gradient(at: 3, 4, in: foo))
  expectEqual(3, gradient(at: 3) { x in foo(x, 4) })
}
SimpleMathTests.test("ResultSelection") {
  func foo(_ x: Float, _ y: Float) -> (Float, Float) {
    return (x + 1, y + 2)
  }
  expectEqual((1, 0), gradient(at: 3, 3, in: { x, y in foo(x, y).0 }))
  expectEqual((0, 1), gradient(at: 3, 3, in: { x, y in foo(x, y).1 }))
}
SimpleMathTests.test("CaptureLocal") {
  let z: Float = 10
  func foo(_ x: Float) -> Float {
    return z * x
  }
  expectEqual(10, gradient(at: 0, in: foo))
}
var globalVar: Float = 10
SimpleMathTests.test("CaptureGlobal") {
  func foo(x: Float) -> Float {
    globalVar += 20
    return globalVar * x
  }
  expectEqual(30, gradient(at: 0, in: foo))
}
var foo_diffable: @differentiable (Float) -> (Float)
  = differentiableFunction { x in (x * x, { v in 2 * x * v }) }
SimpleMathTests.test("GlobalDiffableFunc") {
  expectEqual(2, gradient(at: 1, in: foo_diffable))
  expectEqual(2, gradient(at: 1, in: { x in foo_diffable(x) }))
  expectEqual(1, gradient(at: 1, in: { (x: Float) -> Float in
    foo_diffable = { x in x + 1 }
    return foo_diffable(x)
  }))
  expectEqual(1, gradient(at: 1, in: foo_diffable))
}
SimpleMathTests.test("Mutation") {
  func fourthPower(x: Float) -> Float {
    var a = x
    a = a * x
    a = a * x
    return a * x
  }
  expectEqual(4 * 27, gradient(at: 3, in: fourthPower))
}
SimpleMathTests.test("Tuple") {
  // TF-945: Nested tuple projections.
  func nested(_ x: Float) -> Float {
    var tuple = (1, 1, ((x, 1), 1))
    return tuple.2.0.0
  }
  expectEqual(1, gradient(at: 3, in: nested))
}
SimpleMathTests.test("TupleMutation") {
  func foo(_ x: Float) -> Float {
    var tuple = (x, x)
    tuple.0 = tuple.0 * x
    return x * tuple.0
  }
  expectEqual(27, gradient(at: 3, in: foo))
  func fifthPower(_ x: Float) -> Float {
    var tuple = (x, x)
    tuple.0 = tuple.0 * x
    tuple.1 = tuple.0 * x
    return tuple.0 * tuple.1
  }
  expectEqual(405, gradient(at: 3, in: fifthPower))
  func nested(_ x: Float) -> Float {
    var tuple = ((x, x), x)
    tuple.0.0 = tuple.0.0 * x
    tuple.0.1 = tuple.0.0 * x
    return tuple.0.0 * tuple.0.1
  }
  expectEqual(405, gradient(at: 3, in: nested))
  func generic<T: Differentiable & AdditiveArithmetic>(_ x: T) -> T {
    var tuple = (x, x)
    return tuple.0
  }
  expectEqual(1, gradient(at: 3.0, in: generic))
  // FIXME(TF-1033): Fix forward-mode ownership error for tuple with non-active
  // initial values.
  /*
  func genericInitialNonactive<T: Differentiable & AdditiveArithmetic>(
    _ x: T
  ) -> T {
    var tuple = (T.zero, T.zero)
    tuple.0 = x
    tuple.1 = x
    return tuple.0
  }
  expectEqual(1, gradient(at: 3.0, in: genericInitialNonactive))
  */
}
// Tests TF-321.
SimpleMathTests.test("TupleNonDifferentiableElements") {
  // TF-964: Test tuple with non-tuple-typed adjoint value.
  func tupleLet(_ x: Tracked<Float>) -> Tracked<Float> {
    let tuple = (2 * x, 1)
    return tuple.0
  }
  expectEqual((8, 2), valueWithGradient(at: 4, in: tupleLet))
  func tupleVar(_ x: Tracked<Float>) -> Tracked<Float> {
    var tuple = (x, 1)
    tuple.0 = x
    tuple.1 = 1
    return tuple.0
  }
  expectEqual((3, 1), valueWithGradient(at: 3, in: tupleVar))
  func nested(_ x: Tracked<Float>) -> Tracked<Float> {
    // Convoluted function computing `x * x`.
    var tuple: (Int, (Int, Tracked<Float>), Tracked<Float>) = (1, (1, 0), 0)
    tuple.0 = 1
    tuple.1.0 = 1
    tuple.1.1 = x
    tuple.2 = x
    return tuple.1.1 * tuple.2
  }
  expectEqual((16, 8), valueWithGradient(at: 4, in: nested))
  struct Wrapper<T> {
    @differentiable(where T : Differentiable)
    func baz(_ x: T) -> T {
      var tuple = (1, 1, x, 1)
      tuple.0 = 1
      tuple.2 = x
      tuple.3 = 1
      return tuple.2
    }
  }
  func wrapper(_ x: Tracked<Float>) -> Tracked<Float> {
    let w = Wrapper<Tracked<Float>>()
    return w.baz(x)
  }
  expectEqual((3, 1), valueWithGradient(at: 3, in: wrapper))
}
// Tests TF-21.
SimpleMathTests.test("StructMemberwiseInitializer") {
  struct Foo : AdditiveArithmetic, Differentiable {
    var stored: Float
    var computed: Float {
      return stored * stored
    }
  }
  // Test direct `init` reference.
  expectEqual(10, pullback(at: 4, in: Foo.init)(.init(stored: 10)))
  let 𝛁foo = pullback(at: Float(4), in: { input -> Foo in
    let foo = Foo(stored: input)
    let foo2 = foo + foo
    return Foo(stored: foo2.stored)
  })(Foo.TangentVector(stored: 1))
  expectEqual(2, 𝛁foo)
  let 𝛁computed = gradient(at: Float(4)) { input -> Float in
    let foo = Foo(stored: input)
    return foo.computed
  }
  expectEqual(8, 𝛁computed)
  let 𝛁product = gradient(at: Float(4)) { input -> Float in
    let foo = Foo(stored: input)
    return foo.computed * foo.stored
  }
  expectEqual(48, 𝛁product)
  struct Custom : AdditiveArithmetic, Differentiable {
    var x: Float
    // Custom initializer with `@differentiable`.
    @differentiable
    init(x: Float) {
      self.x = x
    }
  }
  let 𝛁custom = pullback(at: Float(4), in: { input -> Custom in
    let foo = Custom(x: input)
    return foo + foo
  })(Custom.TangentVector(x: 1))
  expectEqual(2, 𝛁custom)
}
// Tests TF-319: struct with non-differentiable constant stored property.
SimpleMathTests.test("StructConstantStoredProperty") {
  struct TF_319 : Differentiable {
    var x: Float
    @noDerivative let constant = Float(2)
    @differentiable
    init(x: Float) {
      self.x = x
    }
    @differentiable(wrt: (self, input))
    func applied(to input: Float) -> Float {
      return x * constant * input
    }
  }
  func testStructInit(to input: Float) -> Float {
    let model = TF_319(x: 10)
    return model.applied(to: input)
  }
  expectEqual(TF_319.TangentVector(x: 6),
              gradient(at: TF_319(x: 10), in: { $0.applied(to: 3) }))
  expectEqual(20, gradient(at: 3, in: testStructInit))
}
SimpleMathTests.test("StructMutation") {
  struct Point : AdditiveArithmetic, Differentiable {
    var x: Float
    var y: Float
    var z: Float
  }
  func double(_ input: Float) -> Point {
    let point = Point(x: input, y: input, z: input)
    return point + point
  }
  expectEqual(6, pullback(at: 4, in: double)(Point(x: 1, y: 1, z: 1)))
  func fifthPower(_ input: Float) -> Float {
    var point = Point(x: input, y: input, z: input)
    point.x = point.x * input
    point.y = point.x * input
    return point.x * point.y
  }
  expectEqual(405, gradient(at: 3, in: fifthPower))
  func mix(_ input: Float) -> Float {
    var tuple = (point: Point(x: input, y: input, z: input), float: input)
    tuple.point.x = tuple.point.x * tuple.float
    tuple.point.y = tuple.point.x * input
    return tuple.point.x * tuple.point.y
  }
  expectEqual(405, gradient(at: 3, in: mix))
  // Test TF-282.
  struct Add : Differentiable {
    var bias: Float
    func applied(to input: Float) -> Float {
      var tmp = input
      tmp = tmp + bias
      return tmp
    }
  }
  let model = Add(bias: 1)
  expectEqual(Add.TangentVector(bias: 1),
              gradient(at: model) { m in m.applied(to: 1) })
}
SimpleMathTests.test("StructGeneric") {
  struct Generic<T : AdditiveArithmetic & Differentiable> : AdditiveArithmetic, Differentiable {
    var x: T
    var y: T
    var z: T
  }
  let 𝛁generic = pullback(at: Float(3), in: { input -> Generic<Float> in
    var generic = Generic(x: input, y: input, z: input)
    return generic
  })(Generic<Float>.TangentVector(x: 1, y: 1, z: 1))
  expectEqual(3, 𝛁generic)
  func fifthPower(_ input: Float) -> Float {
    var generic = Generic(x: input, y: input, z: input)
    generic.x = generic.x * input
    generic.y = generic.x * input
    return generic.x * generic.y
  }
  expectEqual(405, gradient(at: 3, in: fifthPower))
}
SimpleMathTests.test("StructWithNoDerivativeProperty") {
  struct NoDerivativeProperty : Differentiable {
    var x: Float
    @noDerivative var y: Float
  }
  expectEqual(
    NoDerivativeProperty.TangentVector(x: 1),
    gradient(at: NoDerivativeProperty(x: 1, y: 1)) { s -> Float in
      var tmp = s
      tmp.y = tmp.x
      return tmp.x
    }
  )
}
SimpleMathTests.test("SubsetIndices") {
  func grad(_ lossFunction: @differentiable (Float, Float) -> Float) -> Float {
    return gradient(at: 1) { x in lossFunction(x * x, 10.0) }
  }
  expectEqual(2, grad { x, y in x + y })
  func gradWRTNonDiff(_ lossFunction: @differentiable (Float, @noDerivative Int) -> Float) -> Float {
    return gradient(at: 2) { x in lossFunction(x * x, 10) }
  }
  expectEqual(4, gradWRTNonDiff { x, y in x + Float(y) })
}
SimpleMathTests.test("ForceUnwrapping") {
  func forceUnwrap<T: Differentiable & FloatingPoint>(_ t: T)
    -> (T, Float) where T == T.TangentVector {
    gradient(at: t, Float(1)) { (x, y) in
      (x as! Float) * y
    }
  }
  expectEqual((1, 2), forceUnwrap(Float(2)))
}
SimpleMathTests.test("Adjoint value accumulation for aggregate lhs and concrete rhs") {
  // TF-943: Test adjoint value accumulation for aggregate lhs and concrete rhs.
  struct SmallTestModel : Differentiable {
    public var stored: Float = 3.0
    @differentiable public func callAsFunction() -> Float { return stored }
  }
  func doubled(_ model: SmallTestModel) -> Float{
    return model() + model.stored
  }
  let grads = gradient(at: SmallTestModel(), in: doubled)
  expectEqual(2.0, grads.stored)
}
// CHECK-LABEL: sil private [ossa] @AD__${{.*}}doubled{{.*}}pullback_src_0_wrt_0 : $@convention(thin) (Float, @owned {{.*}}) -> SmallTestModel.TangentVector {
// CHECK: bb0([[DX:%.*]] : $Float, [[PB_STRUCT:%.*]] : {{.*}}):
// CHECK:   ([[PB0:%.*]], [[PB1:%.*]]) = destructure_struct [[PB_STRUCT]]
// CHECK:   [[ADJ_TUPLE:%.*]] = apply [[PB1]]([[DX]]) : $@callee_guaranteed (Float) -> (Float, Float)
// CHECK:   ([[TMP0:%.*]], [[ADJ_CONCRETE:%.*]]) = destructure_tuple [[ADJ_TUPLE]] : $(Float, Float)
// CHECK:   [[TMP1:%.*]] = apply [[PB0]]([[TMP0]]) : $@callee_guaranteed (Float) -> SmallTestModel.TangentVector
// CHECK:   [[ADJ_STRUCT_FIELD:%.*]] = destructure_struct [[TMP1]] : $SmallTestModel.TangentVector
// CHECK:   [[TMP_RES:%.*]] = alloc_stack $Float
// CHECK:   [[TMP_ADJ_STRUCT_FIELD:%.*]] = alloc_stack $Float
// CHECK:   [[TMP_ADJ_CONCRETE:%.*]] = alloc_stack $Float
// CHECK:   store [[ADJ_STRUCT_FIELD]] to [trivial] [[TMP_ADJ_STRUCT_FIELD]] : $*Float
// CHECK:   store [[ADJ_CONCRETE]] to [trivial] [[TMP_ADJ_CONCRETE]] : $*Float
// CHECK:   [[PLUS_EQUAL:%.*]] = witness_method $Float, #AdditiveArithmetic."+"
// CHECK:   %{{.*}} = apply [[PLUS_EQUAL]]<Float>([[TMP_RES]], [[TMP_ADJ_CONCRETE]], [[TMP_ADJ_STRUCT_FIELD]], {{.*}})
// CHECK:   [[RES:%.*]] = load [trivial] [[TMP_RES]] : $*Float
// CHECK:   [[RES_STRUCT:%.*]] = struct $SmallTestModel.TangentVector ([[RES]] : $Float)
// CHECK:   return [[RES_STRUCT]] : $SmallTestModel.TangentVector
// CHECK: }
runAllTests()
 | 
	apache-2.0 | 
	a4a8a1e42cf589af8ea919458ef258ae | 29.200495 | 158 | 0.616343 | 3.293117 | false | true | false | false | 
| 
	ViennaRSS/vienna-rss | 
	Vienna/Sources/Parsing/FeedDiscoverer.swift | 
	3 | 
	8325 | 
	//
//  FeedDiscoverer.swift
//  Vienna
//
//  Copyright 2020-2021 Eitot
//
//  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
//
//  https://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
import Foundation
import libxml2
import os.log
@objc(VNAFeedDiscoverer)
final class FeedDiscoverer: NSObject {
    /// A data object containing the HTML document.
    @objc let data: Data
    /// The base URL of the HTML document.
    @objc let baseURL: URL
    // MARK: Initialization
    // This static property ensures that xmlInitParser() is called only once,
    // even if this class is instantiated multiple times.
    private static let htmlParser: Void = xmlInitParser()
    /// Initializes a parser with the HTML contents encapsulated in a given data
    /// object.
    ///
    /// - Parameters:
    ///   - data: A data object containing the HTML document.
    ///   - baseURL: The base URL of the HTML document.
    @objc
    init(data: Data, baseURL: URL) {
        // Call the static initializer of xmlInitParser().
        FeedDiscoverer.htmlParser
        self.data = data
        self.baseURL = baseURL
    }
    // MARK: Parsing
    private lazy var results: [FeedURL] = []
    private var abortOnFirstResult = false
    /// Searches the HTML document for feed URLs.
    @objc
    func documentHasFeeds() -> Bool {
        abortOnFirstResult = true
        parse()
        return !results.isEmpty
    }
    /// Extracts feed URLs from the HTML document.
    /// - Returns: An array of feed URLs.
    @objc
    func feedURLs() -> [FeedURL] {
        abortOnFirstResult = false
        parse()
        return results
    }
    private var parserContext: htmlParserCtxtPtr?
    private func parse() {
        guard parserContext == nil else {
            return
        }
        data.withUnsafeBytes { buffer in
            // According to the UnsafeRawBufferPointer documentation, each byte
            // is addressed as a UInt8 value.
            guard let baseAddress = buffer.baseAddress?.assumingMemoryBound(to: UInt8.self) else {
                os_log("Buffer base address is nil", log: .discoverer, type: .fault)
                return
            }
            let numberOfBytes = Int32(buffer.count)
            // Even if the base address is not nil, the byte count can be 0.
            guard numberOfBytes > 0 else {
                os_log("Buffer data count is 0", log: .discoverer, type: .fault)
                return
            }
            // Set up the HTML parser.
            var handler = htmlParserHandler()
            let parser = Unmanaged.passUnretained(self).toOpaque()
            let address = UnsafeRawPointer(baseAddress).bindMemory(to: Int8.self, capacity: 1)
            let encoding = xmlDetectCharEncoding(baseAddress, numberOfBytes)
            parserContext = htmlCreatePushParserCtxt(&handler, parser, address, numberOfBytes, nil, encoding)
            let opts = Int32(HTML_PARSE_RECOVER.rawValue | HTML_PARSE_NOBLANKS.rawValue | HTML_PARSE_NONET.rawValue)
            htmlCtxtUseOptions(parserContext, opts)
            // Parse the document.
            htmlParseDocument(parserContext)
            // Clean up the parser.
            htmlFreeParserCtxt(parserContext)
            self.parserContext = nil
        }
    }
    fileprivate func parser(_ parser: FeedDiscoverer, didStartElement elementName: String, attributes: [String: String]) {
        guard validateElement(elementName: elementName, attributes: attributes) else {
            return
        }
        guard let absoluteURL = formatURL(attributes: attributes, baseURL: parser.baseURL) else {
            return
        }
        let feedURL = FeedURL(url: absoluteURL, title: attributes["title"])
        parser.results.append(feedURL)
        if parser.abortOnFirstResult {
            xmlStopParser(parserContext)
            return
        }
    }
    // MARK: Validating
    // Verifies whether an HTML element refers to a feed.
    //
    // The validation is based upon the HTML5 living standard, last accessed on
    // 4th January 2021 at: https://html.spec.whatwg.org/multipage/links.html\.
    //
    // See also:
    // https://validator.w3.org/feed/docs/warning/UnexpectedContentType.html\.
    private func validateElement(elementName: String, attributes: [String: String]) -> Bool {
        // The link element and alternate relation represent external content.
        guard elementName == "link" && attributes["rel"]?.lowercased() == "alternate" else {
            return false
        }
        switch attributes["type"]?.lowercased() {
        // These types are recommended, requiring no further validation.
        case "application/rss+xml",
             "application/atom+xml":
            return true
        // These types are not sanctioned, but nevertheless used. They require
        // further validation to rule out false-positives.
        case "application/xml",
             "application/rdf+xml",
             "text/xml":
            break
        default:
            return false
        }
        // At this point, the link could refer to any type of XML document. The
        // document name can be the final clue.
        switch attributes["href"]?.lowercased() {
        case .some(let urlString) where urlString.contains("feed") || urlString.contains("rss"):
            return true
        default:
            return false
        }
    }
    // Formats the href attribute into an absolute URL, if possible.
    private func formatURL(attributes: [String: String], baseURL: URL) -> URL? {
        guard let urlString = attributes["href"] else {
            return nil
        }
        guard let components = URLComponents(string: urlString) else {
            return nil
        }
        guard let absoluteFeedURL = components.url(relativeTo: baseURL) else {
            return nil
        }
        return absoluteFeedURL.absoluteURL
    }
}
// MARK: - Nested types
@objc(VNAFeedURL)
final class FeedURL: NSObject {
    @objc let absoluteURL: URL
    @objc let title: String?
    @objc(initWithURL:title:)
    init(url: URL, title: String?) {
        absoluteURL = url
        self.title = title
    }
}
// MARK: - libxml2 handlers
private func htmlParserHandler() -> htmlSAXHandler {
    var handler = libxml2.htmlSAXHandler()
    handler.startElement = htmlParserElementStart
    return handler
}
private func htmlParserElementStart(_ parser: UnsafeMutableRawPointer?, elementName: UnsafePointer<xmlChar>?, attributesArray: UnsafeMutablePointer<UnsafePointer<xmlChar>?>?) {
    guard let pointer = parser, let cString = elementName else {
        os_log("Parser returned nil pointers", log: .discoverer, type: .fault)
        return
    }
    // Each element of the C array consists of two NULL terminated C strings.
    var attributes: [String: String] = [:]
    var currentAttributeIndex = 0
    var currentAttributeKey: String?
    while true {
        guard let attribute = attributesArray?[currentAttributeIndex] else {
            break
        }
        // If the key is present, parse the attribute value.
        if let arrayKey = currentAttributeKey {
            attributes[arrayKey] = String(cString: attribute)
                .trimmingCharacters(in: .whitespacesAndNewlines)
            currentAttributeKey = nil
        // No key is present, therefore parse a key first.
        } else {
            currentAttributeKey = String(cString: attribute)
        }
        currentAttributeIndex += 1
    }
    let parser = Unmanaged<FeedDiscoverer>.fromOpaque(pointer).takeUnretainedValue()
    let elementName = String(cString: cString)
    parser.parser(parser, didStartElement: elementName, attributes: attributes)
}
// MARK: - Public extensions
extension OSLog {
    static let discoverer = OSLog(subsystem: "--", category: "FeedDiscoverer")
}
 | 
	apache-2.0 | 
	a80facce8feff6495434e226bdc5824c | 31.019231 | 176 | 0.636276 | 4.74359 | false | false | false | false | 
| 
	wireapp/wire-ios-data-model | 
	Source/Utilis/ZMUpdateEvent.swift | 
	1 | 
	4765 | 
	//
// Wire
// Copyright (C) 2020 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
extension ZMUpdateEvent {
    public var messageNonce: UUID? {
        switch type {
        case .conversationMessageAdd,
             .conversationAssetAdd,
             .conversationKnock:
            return payload.dictionary(forKey: "data")?["nonce"] as? UUID
        case .conversationClientMessageAdd,
             .conversationOtrMessageAdd,
             .conversationOtrAssetAdd:
            let message = GenericMessage(from: self)
            guard let messageID = message?.messageID else {
                return nil
            }
            return UUID(uuidString: messageID)
        default:
            return nil
        }
    }
    public var userIDs: [UUID] {
        guard let dataPayload = (payload as NSDictionary).dictionary(forKey: "data"),
            let userIds = dataPayload["user_ids"] as? [String] else {
                return []
        }
        return userIds.compactMap({ UUID.init(uuidString: $0)})
    }
    public var qualifiedUserIDs: [QualifiedID]? {
        qualifiedUserIDsFromQualifiedIDList() ?? qualifiedUserIDsFromUserList()
    }
    private func qualifiedUserIDsFromUserList() -> [QualifiedID]? {
        guard let dataPayload = (payload as NSDictionary).dictionary(forKey: "data"),
              let userDicts = dataPayload["users"] as? [NSDictionary] else {
                return nil
        }
        let qualifiedIDs: [QualifiedID] = userDicts.compactMap({
            let qualifiedID = $0.optionalDictionary(forKey: "qualified_id") as NSDictionary?
            guard
                let uuid = $0.optionalUuid(forKey: "id") ?? qualifiedID?.optionalUuid(forKey: "id"),
                let domain = qualifiedID?.string(forKey: "domain")
            else {
                return nil
            }
            return QualifiedID(uuid: uuid, domain: domain)
        })
        if !qualifiedIDs.isEmpty {
            return qualifiedIDs
        } else {
            return nil
        }
    }
    private func qualifiedUserIDsFromQualifiedIDList() -> [QualifiedID]? {
        guard let dataPayload = (payload as NSDictionary).dictionary(forKey: "data"),
              let userDicts = dataPayload["qualified_user_ids"] as? [NSDictionary] else {
                return nil
        }
        let qualifiedIDs: [QualifiedID] = userDicts.compactMap({
            guard
                let uuid = $0.uuid(forKey: "id"),
                let domain = $0.string(forKey: "domain")
            else {
                return nil
            }
            return QualifiedID(uuid: uuid, domain: domain)
        })
        if !qualifiedIDs.isEmpty {
            return qualifiedIDs
        } else {
            return nil
        }
    }
    public func users(in context: NSManagedObjectContext, createIfNeeded: Bool) -> [ZMUser] {
        if let qualifiedUserIDs = qualifiedUserIDs {
            if createIfNeeded {
                return qualifiedUserIDs.map { ZMUser.fetchOrCreate(with: $0.uuid,
                                                                   domain: $0.domain,
                                                                   in: context) }
            } else {
                return qualifiedUserIDs.compactMap { ZMUser.fetch(with: $0.uuid,
                                                                  domain: $0.domain,
                                                                  in: context) }
            }
        } else {
            if createIfNeeded {
                return userIDs.map { ZMUser.fetchOrCreate(with: $0, domain: nil, in: context) }
            } else {
                return userIDs.compactMap { ZMUser.fetch(with: $0, domain: nil, in: context) }
            }
        }
    }
    public var participantsRemovedReason: ZMParticipantsRemovedReason {
        guard let dataPayload = (payload as NSDictionary).dictionary(forKey: "data"),
              let reasonString = dataPayload["reason"] as? String else {
            return ZMParticipantsRemovedReason.none
        }
        return ZMParticipantsRemovedReason(reasonString)
    }
}
 | 
	gpl-3.0 | 
	c3538139524ba4eafe40880269b69b57 | 35.098485 | 100 | 0.564533 | 5.063762 | false | false | false | false | 
| 
	radvansky-tomas/NutriFacts | 
	nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Data/BarChartDataSet.swift | 
	3 | 
	3767 | 
	//
//  BarChartDataSet.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 CoreGraphics.CGBase
import UIKit.UIColor
public class BarChartDataSet: BarLineScatterCandleChartDataSet
{
    /// space indicator between the bars in percentage of the whole width of one value (0.15 == 15% of bar width)
    public var barSpace: CGFloat = 0.15
    
    /// the maximum number of bars that are stacked upon each other, this value
    /// is calculated from the Entries that are added to the DataSet
    private var _stackSize = 1
    
    /// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value
    public var barShadowColor = UIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0)
    
    /// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque)
    public var highLightAlpha = CGFloat(120.0 / 255.0)
    
    /// the overall entry count, including counting each stack-value individually
    private var _entryCountStacks = 0
    
    /// array of labels used to describe the different values of the stacked bars
    public var stackLabels: [String] = ["Stack"]
    
    public override init(yVals: [ChartDataEntry]?, label: String)
    {
        super.init(yVals: yVals, label: label);
        
        self.highlightColor = UIColor.blackColor();
        
        self.calcStackSize(yVals as! [BarChartDataEntry]?);
        self.calcEntryCountIncludingStacks(yVals as! [BarChartDataEntry]?);
    }
    
    // MARK: NSCopying
    
    public override func copyWithZone(zone: NSZone) -> AnyObject
    {
        var copy = super.copyWithZone(zone) as! BarChartDataSet;
        copy.barSpace = barSpace;
        copy._stackSize = _stackSize;
        copy.barShadowColor = barShadowColor;
        copy.highLightAlpha = highLightAlpha;
        copy._entryCountStacks = _entryCountStacks;
        copy.stackLabels = stackLabels;
        return copy;
    }
    
    /// Calculates the total number of entries this DataSet represents, including
    /// stacks. All values belonging to a stack are calculated separately.
    private func calcEntryCountIncludingStacks(yVals: [BarChartDataEntry]!)
    {
        _entryCountStacks = 0;
        
        for (var i = 0; i < yVals.count; i++)
        {
            var vals = yVals[i].values;
            
            if (vals == nil)
            {
                _entryCountStacks++;
            }
            else
            {
                _entryCountStacks += vals.count;
            }
        }
    }
    
    /// calculates the maximum stacksize that occurs in the Entries array of this DataSet
    private func calcStackSize(yVals: [BarChartDataEntry]!)
    {
        for (var i = 0; i < yVals.count; i++)
        {
            var vals = yVals[i].values;
            
            if (vals != nil && vals.count > _stackSize)
            {
                _stackSize = vals.count;
            }
        }
    }
    
    /// Returns the maximum number of bars that can be stacked upon another in this DataSet.
    public var stackSize: Int
    {
        return _stackSize;
    }
    
    /// Returns true if this DataSet is stacked (stacksize > 1) or not.
    public var isStacked: Bool
    {
        return _stackSize > 1 ? true : false;
    }
    
    /// returns the overall entry count, including counting each stack-value individually
    public var entryCountStacks: Int
    {
        return _entryCountStacks;
    }
} | 
	gpl-2.0 | 
	b496fd4048c146018d6e34d689e576fa | 31.765217 | 148 | 0.621184 | 4.786531 | false | false | false | false | 
| 
	meteochu/Alamofire | 
	Source/ServerTrustPolicy.swift | 
	1 | 
	13141 | 
	//
//  ServerTrustPolicy.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 managing the mapping of `ServerTrustPolicy` objects to a given host.
public class ServerTrustPolicyManager {
    /// The dictionary of policies mapped to a particular host.
    public let policies: [String: ServerTrustPolicy]
    /**
        Initializes the `ServerTrustPolicyManager` instance with the given policies.
        Since different servers and web services can have different leaf certificates, intermediate and even root 
        certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This 
        allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key 
        pinning for host3 and disabling evaluation for host4.
        - parameter policies: A dictionary of all policies mapped to a particular host.
        - returns: The new `ServerTrustPolicyManager` instance.
    */
    public init(policies: [String: ServerTrustPolicy]) {
        self.policies = policies
    }
    /**
        Returns the `ServerTrustPolicy` for the given host if applicable.
        By default, this method will return the policy that perfectly matches the given host. Subclasses could override
        this method and implement more complex mapping implementations such as wildcards.
        - parameter host: The host to use when searching for a matching policy.
        - returns: The server trust policy for the given host if found.
    */
    public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? {
        return policies[host]
    }
}
// MARK: -
extension URLSession {
    private struct AssociatedKeys {
        static var ManagerKey = "NSURLSession.ServerTrustPolicyManager"
    }
    var serverTrustPolicyManager: ServerTrustPolicyManager? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager
        }
        set (manager) {
            objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}
// MARK: - ServerTrustPolicy
/**
    The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when 
    connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust 
    with a given set of criteria to determine whether the server trust is valid and the connection should be made.
    Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other 
    vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged 
    to route all communication over an HTTPS connection with pinning enabled.
    - PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to 
                                validate the host provided by the challenge. Applications are encouraged to always 
                                validate the host in production environments to guarantee the validity of the server's 
                                certificate chain.
    - PinCertificates:          Uses the pinned certificates to validate the server trust. The server trust is
                                considered valid if one of the pinned certificates match one of the server certificates. 
                                By validating both the certificate chain and host, certificate pinning provides a very 
                                secure form of server trust validation mitigating most, if not all, MITM attacks. 
                                Applications are encouraged to always validate the host and require a valid certificate 
                                chain in production environments.
    - PinPublicKeys:            Uses the pinned public keys to validate the server trust. The server trust is considered
                                valid if one of the pinned public keys match one of the server certificate public keys. 
                                By validating both the certificate chain and host, public key pinning provides a very 
                                secure form of server trust validation mitigating most, if not all, MITM attacks. 
                                Applications are encouraged to always validate the host and require a valid certificate 
                                chain in production environments.
    - DisableEvaluation:        Disables all evaluation which in turn will always consider any server trust as valid.
    - CustomEvaluation:         Uses the associated closure to evaluate the validity of the server trust.
*/
public enum ServerTrustPolicy {
    case PerformDefaultEvaluation(validateHost: Bool)
    case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool)
    case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool)
    case DisableEvaluation
    case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool)
    // MARK: - Bundle Location
    /**
        Returns all certificates within the given bundle with a `.cer` file extension.
        - parameter bundle: The bundle to search for all `.cer` files.
        - returns: All certificates within the given bundle.
    */
    public static func certificatesInBundle(bundle: Bundle = Bundle.main()) -> [SecCertificate] {
        var certificates: [SecCertificate] = []
        let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in
            bundle.pathsForResources(ofType: fileExtension, inDirectory: nil)
        }.flatten())
        for path in paths {
            if let
                certificateData = NSData(contentsOfFile: path),
                certificate = SecCertificateCreateWithData(nil, certificateData)
            {
                certificates.append(certificate)
            }
        }
        return certificates
    }
    /**
        Returns all public keys within the given bundle with a `.cer` file extension.
        - parameter bundle: The bundle to search for all `*.cer` files.
        - returns: All public keys within the given bundle.
    */
    public static func publicKeysInBundle(bundle: Bundle = Bundle.main()) -> [SecKey] {
        var publicKeys: [SecKey] = []
        for certificate in certificatesInBundle(bundle: bundle) {
            if let publicKey = publicKeyForCertificate(certificate: certificate) {
                publicKeys.append(publicKey)
            }
        }
        return publicKeys
    }
    // MARK: - Evaluation
    /**
        Evaluates whether the server trust is valid for the given host.
        - parameter serverTrust: The server trust to evaluate.
        - parameter host:        The host of the challenge protection space.
        - returns: Whether the server trust is valid.
    */
    public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool {
        var serverTrustIsValid = false
        switch self {
        case let .PerformDefaultEvaluation(validateHost):
            let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
            SecTrustSetPolicies(serverTrust, [policy!] as NSArray)
            serverTrustIsValid = trustIsValid(trust: serverTrust)
        case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
            if validateCertificateChain {
                let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
                SecTrustSetPolicies(serverTrust, [policy!] as NSArray)
                SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates)
                SecTrustSetAnchorCertificatesOnly(serverTrust, true)
                serverTrustIsValid = trustIsValid(trust: serverTrust)
            } else {
                let serverCertificatesDataArray = certificateDataForTrust(trust: serverTrust)
                let pinnedCertificatesDataArray = certificateDataForCertificates(certificates: pinnedCertificates)
                outerLoop: for serverCertificateData in serverCertificatesDataArray {
                    for pinnedCertificateData in pinnedCertificatesDataArray {
                        if serverCertificateData.isEqual(to: pinnedCertificateData as Data) {
                            serverTrustIsValid = true
                            break outerLoop
                        }
                    }
                }
            }
        case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost):
            var certificateChainEvaluationPassed = true
            if validateCertificateChain {
                let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
                SecTrustSetPolicies(serverTrust, [policy!] as NSArray)
                certificateChainEvaluationPassed = trustIsValid(trust: serverTrust)
            }
            if certificateChainEvaluationPassed {
                outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(trust: serverTrust) as [AnyObject] {
                    for pinnedPublicKey in pinnedPublicKeys as [AnyObject] {
                        if serverPublicKey.isEqual(pinnedPublicKey) {
                            serverTrustIsValid = true
                            break outerLoop
                        }
                    }
                }
            }
        case .DisableEvaluation:
            serverTrustIsValid = true
        case let .CustomEvaluation(closure):
            serverTrustIsValid = closure(serverTrust: serverTrust, host: host)
        }
        return serverTrustIsValid
    }
    // MARK: - Private - Trust Validation
    private func trustIsValid(trust: SecTrust) -> Bool {
        var isValid = false
        var result = SecTrustResultType.invalid
        let status = SecTrustEvaluate(trust, &result)
        if status == errSecSuccess {
            let unspecified = SecTrustResultType.unspecified
            let proceed = SecTrustResultType.proceed
            isValid = result == unspecified || result == proceed
        }
        return isValid
    }
    // MARK: - Private - Certificate Data
    private func certificateDataForTrust(trust: SecTrust) -> [NSData] {
        var certificates: [SecCertificate] = []
        for index in 0..<SecTrustGetCertificateCount(trust) {
            if let certificate = SecTrustGetCertificateAtIndex(trust, index) {
                certificates.append(certificate)
            }
        }
        return certificateDataForCertificates(certificates: certificates)
    }
    private func certificateDataForCertificates(certificates: [SecCertificate]) -> [NSData] {
        return certificates.map { SecCertificateCopyData($0) as NSData }
    }
    // MARK: - Private - Public Key Extraction
    private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] {
        var publicKeys: [SecKey] = []
        for index in 0..<SecTrustGetCertificateCount(trust) {
            if let
                certificate = SecTrustGetCertificateAtIndex(trust, index),
                publicKey = publicKeyForCertificate(certificate: certificate)
            {
                publicKeys.append(publicKey)
            }
        }
        return publicKeys
    }
    private static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey? {
        var publicKey: SecKey?
        let policy = SecPolicyCreateBasicX509()
        var trust: SecTrust?
        let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
        if let trust = trust where trustCreationStatus == errSecSuccess {
            publicKey = SecTrustCopyPublicKey(trust)
        }
        return publicKey
    }
}
 | 
	mit | 
	77dca4fa667f827c19c6fa3d465eaa54 | 42.226974 | 123 | 0.659691 | 6.011436 | false | false | false | false | 
| 
	TwilioDevEd/api-snippets | 
	video/rooms/specify-constraints/specify-constraints.swift | 
	2 | 
	530 | 
	if (self.localVideoTrack == nil) {
    self.camera = TVICameraCapturer()
    self.localVideoTrack = TVILocalVideoTrack.init(capturer: self.camera!)
}
if (self.localAudioTrack == nil) {
    self.localAudioTrack = TVILocalAudioTrack.init()
}
let connectOptions = TVIConnectOptions.init(token: accessToken) { (builder) in
    builder.roomName = "my-room"
    builder.audioTracks = [ self.localAudioTrack! ]
    builder.videoTracks = [ self.localVideoTrack! ]
}
var room = TwilioVideo.connect(with: connectOptions, delegate: self)
 | 
	mit | 
	6b3a18d46db488ccc0fee4c48a048d60 | 32.125 | 78 | 0.732075 | 4.045802 | false | false | false | false | 
| 
	spritekitbook/flappybird-swift | 
	Chapter 8/Start/FloppyBird/FloppyBird/GameScene.swift | 
	2 | 
	4350 | 
	//
//  GameScene.swift
//  FloppyBird
//
//  Created by Jeremy Novak on 9/24/16.
//  Copyright © 2016 SpriteKit Book. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
    
    // MARK: - Private enum
    private enum State {
        case tutorial, running, paused, gameOver
    }
    
    // MARK: - Private class constants
    private let cloudController = CloudController()
    private let hills = Hills()
    private let ground = Ground()
    private let tutorial = Tutorial()
    private let floppy = Floppy()
    private let logController = LogController()
    private let scoreLabel = ScoreLabel()
    
    // MARK: - Private class variables
    private var lastUpdateTime:TimeInterval = 0.0
    private var state:State = .tutorial
    private var previousState:State = .tutorial
    
    // MARK: - Init
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override init(size: CGSize) {
        super.init(size: size)
    }
    
    override func didMove(to view: SKView) {
        setup()
    }
    
    // MARK: - Setup
    private func setup() {
        self.backgroundColor = Colors.colorFrom(rgb: Colors.sky)
        
        self.addChild(scoreLabel)
        self.addChild(cloudController)
        self.addChild(hills)
        self.addChild(logController)
        self.addChild(ground)
        self.addChild(tutorial)
        self.addChild(floppy)
        
        self.physicsWorld.contactDelegate = self
        self.physicsWorld.gravity = CGVector.zero
        
        self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)
        self.physicsBody?.affectedByGravity = false
        self.physicsBody?.categoryBitMask = Contact.scene
        self.physicsBody?.collisionBitMask = 0x0
        self.physicsBody?.contactTestBitMask = 0x0
    }
    
    // MARK: - Update
    override func update(_ currentTime: TimeInterval) {
        let delta = currentTime - lastUpdateTime
        lastUpdateTime = currentTime
        
        cloudController.update(delta: delta)
        
        if state != .running {
            return
        } else {
            floppy.update()
            logController.update(delta: delta)
        }
    }
    
    // MARK: - Touch Events
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch:UITouch = touches.first! as UITouch
        let touchLocation = touch.location(in: self)
        
        if state == .tutorial {
            if tutorial.contains(touchLocation) {
                tutorial.tapepd()
                running()
            }
        } else if state == .running {
            floppy.fly()
        }
    }
    
    // MARK: - Contact
    func didBegin(_ contact: SKPhysicsContact) {
        if state != .running {
            return
        } else {
            // Which body is not Floppy?
            let other = contact.bodyA.categoryBitMask == Contact.floppy ? contact.bodyB : contact.bodyA
            
            if other.categoryBitMask == Contact.scene {
                // Player hit the ground or the ceiling
                gameOver()
            }
            
            if other.categoryBitMask == Contact.log {
                // Player hit a log
                gameOver()
            }
            
            if other.categoryBitMask == Contact.score {
                floppy.updateScore()
                scoreLabel.updateScore(score: floppy.getScore())
            }
            
        }
    }
    
    // MARK: - State
    private func running() {
        state = .running
        
        self.physicsWorld.gravity = CGVector(dx: 0, dy: -10)
    }
    
    func paused() {
        previousState = state
        state = .paused
    }
    
    func resume() {
        state = .running
    }
    
    func gameOver() {
        state = .gameOver
        
        floppy.gameOver()
        
        self.run(SKAction.wait(forDuration: 2.0), completion: {
            [weak self] in
            self?.loadScene()
        })
    }
    
    // MARK: - Load Scene
    private func loadScene() {
        let scene = GameOverScene(size: kViewSize, score: floppy.getScore())
        let transition = SKTransition.fade(with: SKColor.black, duration: 0.5)
        
        self.view?.presentScene(scene, transition: transition)
    }
}
 | 
	apache-2.0 | 
	ae07a01c9b53d96cd4dc60cb452be310 | 26.700637 | 103 | 0.560359 | 5.004603 | false | false | false | false | 
| 
	acevest/acecode | 
	learn/AcePlay/AcePlay.playground/Pages/Basics.xcplaygroundpage/Contents.swift | 
	1 | 
	3720 | 
	//: Playground - noun: a place where people can play
import UIKit
// String values can be constructed by passing an array of Character values
let catCharacters: [Character] = ["C", "a", "t", " ", "猫"]
let catString = String(catCharacters)
print(catString)
// Character 加到String的方法
var welcome = "Hello World"
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
print(welcome)
// ############# Type Alias ################
typealias AudioSample = UInt
let maxAmplitudeFound = AudioSample.max
// ############# Tuple ################
let http404Error = (404, "Page Not Found")
let (httpRetCode, _) = http404Error
print("Http RetCode \(httpRetCode) Error Message \(http404Error.1)")
let httpStatus = (statusCode: 200, description: "OK")
print("Http RetCode \(httpStatus.statusCode) Message \(httpStatus.description)")
// ############# Optionals ################
let possibleNumber = "123"
let convertNumber : Int? = Int(possibleNumber) // of type Int?
if convertNumber != nil {
    print("ConvertNumber is \(convertNumber)")
    print("ConvertNumber is \(convertNumber!)")
} else {
    print("ConvertNumber is nil")
}
// ############# Optionals Binding ################
if let actualNumber = Int(possibleNumber) {
    print("\"\(possibleNumber)\" has an integer of \(actualNumber)")
} else {
    print("\"\(possibleNumber)\" could not to be converted to an integer")
}
if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
    print("\(firstNumber) < \(secondNumber) < 100")
}
// ############# Implicitly Unwrapped Optionals ################
let possibleString: String? = "An Optional String"
let forcedString: String = possibleString!
let assumedString: String! = "An Implicitly Unwrapped Optional String"
let implicitString: String = assumedString
print("\(possibleString!) \(forcedString) \(assumedString) \(implicitString)")
// ############# Nil-Coalescing Operator ################
let defaultColorName = "yellow"
var userDefinedColorName: String?
// 等价于 userDefinedColorName == nil ? defaultColorName : userDefinedColorName
var colorNameToUse = userDefinedColorName ?? defaultColorName
print(colorNameToUse)
userDefinedColorName = "red"
colorNameToUse = userDefinedColorName ?? defaultColorName
print(colorNameToUse)
// ############# Nil-Coalescing Operator ################
for index in 1...5 {
    print("Closed Range Operator \(index) of [1,5]")
}
for index in 0..<5 {
    print("Half-Open Range Operator \(index) of [0,5)")
}
var word = "cafe"
print("the number of characters of \(word) is \(word.characters.count)");
word += "\u{301}"
print("the number of characters of \(word) is \(word.characters.count)");
let str = "Hello, playground.小狗:🐶 锤子:🔨"
// Index
var strInx:String.Index = str.startIndex
str.index(after: strInx)
print(str[strInx])
for strInx in str.characters.indices {
    print("\(str[strInx])", terminator: "")
}
print()
// utf8 编码格式
for c in str.utf8 {
    print(c, terminator: "-")
}
print()
// unicode
for c in str.unicodeScalars {
    print("\(c)\t\(c.value)")
}
welcome.insert("~", at: welcome.endIndex)
print(welcome)
// contentsOf 是一个 Collection 所以要加 .characters
welcome.insert(contentsOf: " Hello Swift".characters, at: welcome.index(before: welcome.endIndex))
print(welcome)
welcome.remove(at: welcome.index(before: welcome.endIndex))
print(welcome)
let range = welcome.index(welcome.endIndex, offsetBy: -12)..<welcome.endIndex
welcome.removeSubrange(range)
print(welcome)
// ############# Working with Characters ################
for c in str.characters {
    print(c, terminator: "")
}
print()
print("The String is: \(str)")
 | 
	gpl-2.0 | 
	b525298c417c873f43cb203cea073a22 | 26.772727 | 111 | 0.670486 | 3.967532 | false | false | false | false | 
| 
	allbto/ios-swiftility | 
	Swiftility/Sources/Extensions/UIKit/UICollectionViewExtensions.swift | 
	2 | 
	1644 | 
	//
//  UICollectionViewExtensions.swift
//  Swiftility
//
//  Created by Allan Barbato on 6/7/16.
//  Copyright © 2016 Allan Barbato. All rights reserved.
//
import Foundation
extension UICollectionView
{
    public func targetCenteredContentOffset(proposedContentOffset offset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint
    {
        let cvBounds = self.bounds
        let halfWidth = cvBounds.size.width * 0.5
        let proposedContentOffsetCenterX = offset.x + halfWidth
        
        guard let attributesForVisibleCells = self.collectionViewLayout.layoutAttributesForElements(in: cvBounds) else { return offset }
        
        var candidateAttributes: UICollectionViewLayoutAttributes?
        
        for attributes in attributesForVisibleCells {
            
            guard let candAttrs = candidateAttributes else {
                candidateAttributes = attributes
                continue
            }
            
            let a = attributes.center.x - proposedContentOffsetCenterX
            let b = candAttrs.center.x - proposedContentOffsetCenterX
            
            if fabsf(Float(a)) < fabsf(Float(b)) {
                candidateAttributes = attributes
            }
        }
        
        return CGPoint(x: round(candidateAttributes!.center.x - halfWidth), y: offset.y)
    }
}
extension UICollectionView
{
    public func indexPathForItemAtCenter() -> IndexPath?
    {
        let point = CGPoint(
            x: self.center.x + self.contentOffset.x,
            y: self.center.y + self.contentOffset.y
        )
        
        return self.indexPathForItem(at: point)
    }
}
 | 
	mit | 
	b4bebc0464d76594740a3892ff237011 | 30 | 136 | 0.628728 | 5.317152 | false | false | false | false | 
| 
	rsmoz/swift-package-manager | 
	Tests/Functional/TestMiscellaneous.swift | 
	1 | 
	12143 | 
	import XCTest
import XCTestCaseProvider
import func libc.fclose
import func libc.sleep
import enum POSIX.Error
import func POSIX.fopen
import func POSIX.fputs
import func POSIX.popen
import struct sys.Path
class MiscellaneousTestCase: XCTestCase, XCTestCaseProvider {
    var allTests : [(String, () throws -> Void)] {
        return [
            ("testPrintsSelectedDependencyVersion", testPrintsSelectedDependencyVersion),
            ("testManifestExcludes1", testManifestExcludes1),
            ("testManifestExcludes2", testManifestExcludes2),
            ("testTestDependenciesSimple", testTestDependenciesSimple),
            ("testTestDependenciesComplex", testTestDependenciesComplex),
            ("testPassExactDependenciesToBuildCommand", testPassExactDependenciesToBuildCommand),
            ("testCanBuildMoreThanTwiceWithExternalDependencies", testCanBuildMoreThanTwiceWithExternalDependencies),
            ("testNoArgumentsExitsWithOne", testNoArgumentsExitsWithOne),
            ("testCompileFailureExitsGracefully", testCompileFailureExitsGracefully),
            ("testDependenciesWithVPrefixTagsWork", testDependenciesWithVPrefixTagsWork),
            ("testCanBuildIfADependencyAlreadyCheckedOut", testCanBuildIfADependencyAlreadyCheckedOut),
            ("testCanBuildIfADependencyClonedButThenAborted", testCanBuildIfADependencyClonedButThenAborted),
            ("testTipHasNoPackageSwift", testTipHasNoPackageSwift),
            ("testFailsIfVersionTagHasNoPackageSwift", testFailsIfVersionTagHasNoPackageSwift),
            ("testPackageManagerDefine", testPackageManagerDefine),
            ("testInternalDependencyEdges", testInternalDependencyEdges),
            ("testExternalDependencyEdges1", testExternalDependencyEdges1),
            ("testExternalDependencyEdges2", testExternalDependencyEdges2),
        ]
    }
    func testPrintsSelectedDependencyVersion() {
        // verifies the stdout contains information about 
        // the selected version of the package
        fixture(name: "DependencyResolution/External/Simple", tags: ["1.3.5"]) { prefix in
            let output = try executeSwiftBuild("\(prefix)/Bar")
            let lines = output.characters.split("\n").map(String.init)
            XCTAssertTrue(lines.contains("Using version 1.3.5 of package Foo"))
        }
    }
    func testManifestExcludes1() {
        // Tests exclude syntax where no target customization is specified
        fixture(name: "Miscellaneous/ExcludeDiagnostic1") { prefix in
            XCTAssertBuilds(prefix)
            XCTAssertFileExists(prefix, ".build", "debug", "BarLib.a")
            XCTAssertFileExists(prefix, ".build", "debug", "FooBarLib.a")
            XCTAssertNoSuchPath(prefix, ".build", "debug", "FooLib.a")
        }
    }
    func testManifestExcludes2() {
        // Tests exclude syntax where target customization is also specified
        // Refs: https://github.com/apple/swift-package-manager/pull/83
        fixture(name: "Miscellaneous/ExcludeDiagnostic2") { prefix in
            XCTAssertBuilds(prefix)
            XCTAssertFileExists(prefix, ".build", "debug", "BarLib.a")
            XCTAssertFileExists(prefix, ".build", "debug", "FooBarLib.a")
            XCTAssertNoSuchPath(prefix, ".build", "debug", "FooLib.a")
        }
    }
    func testTestDependenciesSimple() {
        fixture(name: "TestDependencies/Simple") { prefix in
            XCTAssertBuilds(prefix, "App")
            XCTAssertDirectoryExists(prefix, "App/Packages/TestingLib-1.2.3")
            XCTAssertFileExists(prefix, "App/.build/debug/Foo.a")
            XCTAssertFileExists(prefix, "App/.build/debug/TestingLib.a")
        }
    }
    func testTestDependenciesComplex() {
        // verifies that testDependencies of dependencies are not fetched or built
        fixture(name: "TestDependencies/Complex") { prefix in
            XCTAssertBuilds(prefix, "App")
            XCTAssertDirectoryExists(prefix, "App/Packages/TestingLib-1.2.3")
            XCTAssertDirectoryExists(prefix, "App/Packages/Foo-1.2.3")
            XCTAssertFileExists(prefix, "App/.build/debug/App")
            XCTAssertFileExists(prefix, "App/.build/debug/Foo.a")
            XCTAssertFileExists(prefix, "App/.build/debug/TestingLib.a")
            XCTAssertNoSuchPath(prefix, "App/Packages/PrivateFooLib-1.2.3")
            XCTAssertNoSuchPath(prefix, "App/Packages/TestingFooLib-1.2.3")
            XCTAssertNoSuchPath(prefix, "App/.build/debug/PrivateFooLib.a")
            XCTAssertNoSuchPath(prefix, "App/.build/debug/TestingFooLib.a")
        }
    }
    func testPassExactDependenciesToBuildCommand() {
        // regression test to ensure that dependencies of other dependencies
        // are not passed into the build-command.
        fixture(name: "Miscellaneous/ExactDependencies") { prefix in
            XCTAssertBuilds(prefix, "app")
            XCTAssertFileExists(prefix, "app/.build/debug/FooExec")
            XCTAssertFileExists(prefix, "app/.build/debug/FooLib1.a")
            XCTAssertFileExists(prefix, "app/.build/debug/FooLib2.a")
        }
    }
    func testCanBuildMoreThanTwiceWithExternalDependencies() {
        // running `swift build` multiple times should not fail
        // subsequent executions to an unmodified source tree
        // should immediately exit with exit-status: `0`
        fixture(name: "DependencyResolution/External/Complex") { prefix in
            XCTAssertBuilds(prefix, "app")
            XCTAssertBuilds(prefix, "app")
            XCTAssertBuilds(prefix, "app")
        }
    }
    func testDependenciesWithVPrefixTagsWork() {
        fixture(name: "DependencyResolution/External/Complex", tags: ["v1.2.3"]) { prefix in
            XCTAssertBuilds(prefix, "app")
        }
    }
    func testNoArgumentsExitsWithOne() {
        var foo = false
        do {
            try executeSwiftBuild("/")
        } catch POSIX.Error.ExitStatus(let code, _) {
            // if our code crashes we'll get an exit code of 256
            XCTAssertEqual(code, Int32(1))
            foo = true
        } catch {
            XCTFail()
        }
        XCTAssertTrue(foo)
    }
    func testCompileFailureExitsGracefully() {
        fixture(name: "Miscellaneous/CompileFails") { prefix in
            var foo = false
            do {
                try executeSwiftBuild(prefix)
            } catch POSIX.Error.ExitStatus(let code, _) {
                // if our code crashes we'll get an exit code of 256
                XCTAssertEqual(code, Int32(1))
                foo = true
            } catch {
                XCTFail()
            }
            XCTAssertTrue(foo)
        }
    }
    func testCanBuildIfADependencyAlreadyCheckedOut() {
        fixture(name: "DependencyResolution/External/Complex") { prefix in
            try system("git", "clone", Path.join(prefix, "deck-of-playing-cards"), Path.join(prefix, "app/Packages/DeckOfPlayingCards-1.2.3"))
            XCTAssertBuilds(prefix, "app")
        }
    }
    func testCanBuildIfADependencyClonedButThenAborted() {
        fixture(name: "DependencyResolution/External/Complex") { prefix in
            try system("git", "clone", Path.join(prefix, "deck-of-playing-cards"), Path.join(prefix, "app/Packages/DeckOfPlayingCards"))
            XCTAssertBuilds(prefix, "app")
        }
    }
    // if HEAD of the default branch has no Package.swift it is still
    // valid provided the selected version tag has a Package.swift
    func testTipHasNoPackageSwift() {
        fixture(name: "DependencyResolution/External/Complex") { prefix in
            let path = Path.join(prefix, "FisherYates")
            // required for some Linux configurations
            try system("git", "-C", path, "config", "user.email", "[email protected]")
            try system("git", "-C", path, "config", "user.name", "Example Example")
            try system("git", "-C", path, "rm", "Package.swift")
            try system("git", "-C", path, "commit", "-mwip")
            XCTAssertBuilds(prefix, "app")
        }
    }
    // if a tag does not have a valid Package.swift, the build fails
    func testFailsIfVersionTagHasNoPackageSwift() {
        fixture(name: "DependencyResolution/External/Complex") { prefix in
            let path = Path.join(prefix, "FisherYates")
            try system("git", "-C", path, "config", "user.email", "[email protected]")
            try system("git", "-C", path, "config", "user.name", "Example McExample")
            try system("git", "-C", path, "rm", "Package.swift")
            try system("git", "-C", path, "commit", "--message", "wip")
            try system("git", "-C", path, "tag", "--force", "1.2.3")
            XCTAssertBuildFails(prefix, "app")
        }
    }
    func testPackageManagerDefine() {
        fixture(name: "Miscellaneous/-DSWIFT_PACKAGE") { prefix in
            XCTAssertBuilds(prefix)
        }
    }
    /**
     Tests that modules that are rebuilt causes
     any executables that link to that module to be relinked.
    */
    func testInternalDependencyEdges() {
        fixture(name: "Miscellaneous/DependencyEdges/Internal") { prefix in
            let execpath = [Path.join(prefix, ".build/debug/Foo")]
            XCTAssertBuilds(prefix)
            var output = try popen(execpath)
            XCTAssertEqual(output, "Hello\n")
            // we need to sleep at least one second otherwise
            // llbuild does not realize the file has changed
            sleep(1)
            let fp = try fopen(prefix, "Bar/Bar.swift", mode: .Write)
            try POSIX.fputs("public let bar = \"Goodbye\"\n", fp)
            fclose(fp)
            XCTAssertBuilds(prefix)
            output = try popen(execpath)
            XCTAssertEqual(output, "Goodbye\n")
        }
    }
    /**
     Tests that modules from other packages that are rebuilt causes
     any executables that link to that module in the root package.
    */
    func testExternalDependencyEdges1() {
        fixture(name: "DependencyResolution/External/Complex") { prefix in
            let execpath = [Path.join(prefix, "app/.build/debug/Dealer")]
            XCTAssertBuilds(prefix, "app")
            var output = try popen(execpath)
            XCTAssertEqual(output, "♣︎K\n♣︎Q\n♣︎J\n♣︎10\n♣︎9\n♣︎8\n♣︎7\n♣︎6\n♣︎5\n♣︎4\n")
            // we need to sleep at least one second otherwise
            // llbuild does not realize the file has changed
            sleep(1)
            let fp = try fopen(prefix, "app/Packages/FisherYates-1.2.3/src/Fisher-Yates_Shuffle.swift", mode: .Write)
            try POSIX.fputs("public extension CollectionType{ func shuffle() -> [Generator.Element] {return []} }\n\npublic extension MutableCollectionType where Index == Int { mutating func shuffleInPlace() { for (i, _) in enumerate() { self[i] = self[0] } }}\n\npublic let shuffle = true", fp)
            fclose(fp)
            XCTAssertBuilds(prefix, "app")
            output = try popen(execpath)
            XCTAssertEqual(output, "♠︎A\n♠︎A\n♠︎A\n♠︎A\n♠︎A\n♠︎A\n♠︎A\n♠︎A\n♠︎A\n♠︎A\n")
        }
    }
    /**
     Tests that modules from other packages that are rebuilt causes
     any executables for another external package to be rebuilt.
     */
    func testExternalDependencyEdges2() {
        fixture(name: "Miscellaneous/DependencyEdges/External") { prefix in
            let execpath = [Path.join(prefix, "root/.build/debug/dep2")]
            XCTAssertBuilds(prefix, "root")
            var output = try popen(execpath)
            XCTAssertEqual(output, "Hello\n")
            // we need to sleep at least one second otherwise
            // llbuild does not realize the file has changed
            sleep(1)
            let fp = try fopen(prefix, "root/Packages/dep1-1.2.3/Foo.swift", mode: .Write)
            try POSIX.fputs("public let foo = \"Goodbye\"", fp)
            fclose(fp)
            XCTAssertBuilds(prefix, "root")
            output = try popen(execpath)
            XCTAssertEqual(output, "Goodbye\n")
        }
    }
}
 | 
	apache-2.0 | 
	d7c540912fce9111c01e0c538821ec32 | 39.344482 | 295 | 0.627207 | 4.655731 | false | true | false | false | 
| 
	blstream/StudyBox_iOS | 
	Pods/Swifternalization/Swifternalization/Regex.swift | 
	1 | 
	3519 | 
	//
//  Regex.swift
//  Swifternalization
//
//  Created by Tomasz Szulc on 27/06/15.
//  Copyright (c) 2015 Tomasz Szulc. All rights reserved.
//
import Foundation
/**
Class uses NSRegularExpression internally and simplifies its usability.
*/
final class Regex {
    
    /**
    Return match in a string. Optionally with index of capturing group
    
    :param: str A string that will be matched.
    :param: pattern A regex pattern.
    :returns: `String` that matches pattern or nil.
    */
    class func matchInString(str: String, pattern: String, capturingGroupIdx: Int?) -> String? {
        var resultString: String?
        
        let range = NSMakeRange(0, str.startIndex.distanceTo(str.endIndex))
        regexp(pattern)?.enumerateMatchesInString(str, options: NSMatchingOptions.ReportCompletion, range: range, usingBlock: { result, flags, stop in
            if let result = result {
                if let capturingGroupIdx = capturingGroupIdx where result.numberOfRanges > capturingGroupIdx {
                    resultString = self.substring(str, range: result.rangeAtIndex(capturingGroupIdx))
                } else {
                    resultString = self.substring(str, range: result.range)
                }
            }
        })
        
        return resultString
    }
    
    
    /**
    Return first match in a string.
    
    :param: str A string that will be matched.
    :param: pattern A regexp pattern.
    :returns: `String` that matches pattern or nil.
    */
    class func firstMatchInString(str: String, pattern: String) -> String? {
        if let result = regexp(pattern)?.firstMatchInString(str, options: .ReportCompletion, range: NSMakeRange(0, str.startIndex.distanceTo(str.endIndex))) {
            return substring(str, range: result.range)
        }
        return nil
    }
    
    /**
    Return all matches in a string.
    
    :param: str A string that will be matched.
    :param: pattern A regexp pattern.
    :returns: Array of `Strings`s. If nothing found empty array is returned.
    */
    class func matchesInString(str: String, pattern: String) -> [String] {
        var matches = [String]()
        if let results = regexp(pattern)?.matchesInString(str, options: .ReportCompletion, range: NSMakeRange(0, str.startIndex.distanceTo(str.endIndex))) {
            for result in results {
                matches.append(substring(str, range: result.range))
            }
        }
        
        return matches
    }
    
    /**
    Returns new `NSRegularExpression` object.
    
    :param: pattern A regexp pattern.
    :returns: `NSRegularExpression` object or nil if it cannot be created.
    */
    private class func regexp(pattern: String) -> NSRegularExpression? {
        do {
            return try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
        } catch let error as NSError {
            print(error)
        }
        return nil
    }
    
    /**
    Method that substring string with passed range.
    
    :param: str A string that is source of substraction.
    :param: range A range that tells which part of `str` will be substracted.
    :returns: A string contained in `range`.
    */
    private class func substring(str: String, range: NSRange) -> String {
        let startRange = str.startIndex.advancedBy(range.location)
        let endRange = startRange.advancedBy(range.length)
        
        return str.substringWithRange(Range(start: startRange, end: endRange))
    }
} | 
	apache-2.0 | 
	1f030febf3b618183758ebc999515cbd | 33.851485 | 158 | 0.635692 | 4.78125 | false | false | false | false | 
| 
	andrea-prearo/SwiftExamples | 
	SmoothScrolling/Client/CollectionView/CollectionView/MainViewController.swift | 
	1 | 
	7512 | 
	//
//  MainViewController.swift
//  CollectionView
//
//  Created by Andrea Prearo on 8/19/16.
//  Copyright © 2016 Andrea Prearo. All rights reserved.
//
import UIKit
class MainViewController: UICollectionViewController {
    private static let sectionInsets = UIEdgeInsets.init(top: 0, left: 2, bottom: 0, right: 2)
    private let userViewModelController = UserViewModelController()
    // Pre-Fetching Queue
    private let imageLoadQueue = OperationQueue()
    private var imageLoadOperations = [IndexPath: ImageLoadOperation]()
    override func viewDidLoad() {
        super.viewDidLoad()
        Feature.initFromPList()
        if Feature.clearCaches.isEnabled {
            let cachesFolderItems = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
            for item in cachesFolderItems {
                try? FileManager.default.removeItem(atPath: item)
            }
        }
        if #available(iOS 10.0, *) {
            collectionView?.prefetchDataSource = self
        }
        userViewModelController.retrieveUsers { [weak self] (success, error) in
            guard let strongSelf = self else { return }
            if !success {
                DispatchQueue.main.async {
                    let title = "Error"
                    if let error = error {
                        strongSelf.showError(title, message: error.localizedDescription)
                    } else {
                        strongSelf.showError(title, message: NSLocalizedString("Can't retrieve contacts.", comment: "Can't retrieve contacts."))
                    }
                }
            } else {
                DispatchQueue.main.async {
                    strongSelf.collectionView?.reloadData()
                }
            }
        }
    }
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate(alongsideTransition: { [weak self] context in
            self?.collectionView?.collectionViewLayout.invalidateLayout()
        }, completion: nil)
    }
    @IBAction func displayOverlayTapped(_ sender: Any) {
        showDebuggingInformationOverlay()
    }
}
// MARK: -
private extension MainViewController {
    func showDebuggingInformationOverlay() {
        let overlayClass = NSClassFromString("UIDebuggingInformationOverlay") as? UIWindow.Type
        _ = overlayClass?.perform(NSSelectorFromString("prepareDebuggingOverlay"))
        let overlay = overlayClass?.perform(NSSelectorFromString("overlay")).takeUnretainedValue() as? UIWindow
        _ = overlay?.perform(NSSelectorFromString("toggleVisibility"))    }
}
// MARK: UICollectionViewDataSource
extension MainViewController {
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return userViewModelController.viewModelsCount
    }
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UserCell", for: indexPath) as! UserCell
        if let viewModel = userViewModelController.viewModel(at: indexPath.row) {
            cell.configure(viewModel)
            if let imageLoadOperation = imageLoadOperations[indexPath],
                let image = imageLoadOperation.image {
                cell.avatar.setRoundedImage(image)
            } else {
                let imageLoadOperation = ImageLoadOperation(url: viewModel.avatarUrl)
                imageLoadOperation.completionHandler = { [weak self] (image) in
                    guard let strongSelf = self else {
                        return
                    }
                    cell.avatar.setRoundedImage(image)
                    strongSelf.imageLoadOperations.removeValue(forKey: indexPath)
                }
                imageLoadQueue.addOperation(imageLoadOperation)
                imageLoadOperations[indexPath] = imageLoadOperation
            }
        }
        if Feature.debugCellLifecycle.isEnabled {
            print(String.init(format: "cellForRowAt #%i", indexPath.row))
        }
        return cell
    }
    override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if Feature.debugCellLifecycle.isEnabled {
            print(String.init(format: "willDisplay #%i", indexPath.row))
        }
    }
    override func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        guard let imageLoadOperation = imageLoadOperations[indexPath] else {
            return
        }
        imageLoadOperation.cancel()
        imageLoadOperations.removeValue(forKey: indexPath)
        
        if Feature.debugCellLifecycle.isEnabled {
            print(String.init(format: "didEndDisplaying #%i", indexPath.row))
        }
    }
}
// MARK: UICollectionViewDelegateFlowLayout protocol methods
extension MainViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        let columns: Int = {
            var count = 2
            if traitCollection.horizontalSizeClass == .regular {
                count = count + 1
            }
            if collectionView.bounds.width > collectionView.bounds.height {
                count = count + 1
            }
            return count
        }()
        let totalSpace = flowLayout.sectionInset.left
            + flowLayout.sectionInset.right
            + (flowLayout.minimumInteritemSpacing * CGFloat(columns - 1))
        let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(columns))
        return CGSize(width: size, height: 90)
    }
}
// MARK: UICollectionViewDataSourcePrefetching
extension MainViewController: UICollectionViewDataSourcePrefetching {
    func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
        for indexPath in indexPaths {
            if let _ = imageLoadOperations[indexPath] {
                return
            }
            if let viewModel = userViewModelController.viewModel(at: (indexPath as NSIndexPath).row) {
                let imageLoadOperation = ImageLoadOperation(url: viewModel.avatarUrl)
                imageLoadQueue.addOperation(imageLoadOperation)
                imageLoadOperations[indexPath] = imageLoadOperation
            }
            
            if Feature.debugCellLifecycle.isEnabled {
                print(String.init(format: "prefetchItemsAt #%i", indexPath.row))
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath]) {
        for indexPath in indexPaths {
            guard let imageLoadOperation = imageLoadOperations[indexPath] else {
                return
            }
            imageLoadOperation.cancel()
            imageLoadOperations.removeValue(forKey: indexPath)
            
            if Feature.debugCellLifecycle.isEnabled {
                print(String.init(format: "cancelPrefetchingForItemsAt #%i", indexPath.row))
            }
        }
    }
}
 | 
	mit | 
	fe5dbe7b3ed4d29221b930519dceb3fd | 40.497238 | 160 | 0.644255 | 6.023256 | false | false | false | false | 
| 
	EBGToo/SBVariables | 
	SBVariables.playground/Contents.swift | 
	1 | 
	2960 | 
	//: Playground - noun: a place where people can play
import SBCommons
import SBBasics
import SBUnits
import SBVariables
var theTime = Quantity<Time>(value: 0.0, unit: second)
// 'Room Temperature'
// Range - Values up to 75.0 C
var theTemperatureRange = ContiguousRange<Quantity<Temperature>>(maximum: Quantity<Temperature>(value: 75.0, unit: celsius))
theTemperatureRange.contains(Quantity<Temperature>(value: 70.0, unit: celsius))
theTemperatureRange.contains(Quantity<Temperature>(value: 80.0, unit: celsius))
// RangeDomain - Values up to 75.0 C
var theTemperatureDomain = RangeDomain<Quantity<Temperature>>(range: theTemperatureRange)
theTemperatureDomain.contains(Quantity<Temperature>(value: 70.0, unit: celsius))
theTemperatureDomain.contains(Quantity<Temperature>(value: 80.0, unit: celsius))
// Variable
var roomTemperature = Variable<Quantity<Temperature>>(name: "OfficeTemperature", time: theTime,
  value: Quantity<Temperature>(value: 50.0, unit: celsius),
  domain: AlwaysDomain<Quantity<Temperature>>(result: true),
  history: History<Quantity<Temperature>>(capacity: 3))!
// Monitor
var roomTemperatureMonitor = DomainMonitor<Quantity<Temperature>>(domain: RangeDomain<Quantity<Temperature>>(
  range: ContiguousRange<Quantity<Temperature>>(maximum: Quantity<Temperature>(value: 75.0, unit: celsius))))
roomTemperatureMonitor.isReportable(Quantity<Temperature>(value: 70.0, unit: celsius))
roomTemperatureMonitor.isReportable(Quantity<Temperature>(value: 80.0, unit: celsius))
roomTemperature.addMonitor(roomTemperatureMonitor)
// Variable -- Assigne Values
roomTemperature.assign(Quantity<Temperature>(value: 60.0, unit: celsius),
  time: Quantity<Time>(value: 1.0, unit: second))
roomTemperatureMonitor.isReportable(roomTemperature.value)
roomTemperature.assign(Quantity<Temperature>(value: 70.0, unit: celsius),
  time: Quantity<Time>(value: 2.0, unit: second))
roomTemperatureMonitor.isReportable(roomTemperature.value)
roomTemperature.assign(Quantity<Temperature>(value: 80.0, unit: celsius),
  time: Quantity<Time>(value: 3.0, unit: second))
roomTemperatureMonitor.isReportable(roomTemperature.value)
// 'Person Mass'
var personMass = QuantityVariable<Mass>(name: "PersonMass", time: theTime,
  value: Quantity<Mass>(value: 175.0, unit: pound),
  domain: AlwaysDomain<Quantity<Mass>>(result: true))!
var personMassAssignments = [Quantity<Mass>]()
var personMassDelegate = VariableDelegate<Quantity<Mass>>()
personMassDelegate.didAssign = { (variable: Variable<Quantity<Mass>>, value:Quantity<Mass>) -> Void in
  print (value)
  personMassAssignments.append(value)
  return
}
personMass.delegate = personMassDelegate
personMass.assign(Quantity<Mass>(value: 180.0, unit: pound),
  time: Quantity<Time>(value: 2.0, unit: second))
personMass.value
personMassAssignments
personMass.assign(Quantity<Mass>(value: 185.0, unit: pound),
  time: Quantity<Time>(value: 2.0, unit: second))
personMass.value
personMassAssignments
 | 
	mit | 
	7b3f23dd32da9b012a34f039e4bd3623 | 36.948718 | 124 | 0.779054 | 3.915344 | false | false | false | false | 
| 
	piscoTech/MBLibrary | 
	Shared/FadedLayer.swift | 
	1 | 
	4962 | 
	//
//  FadedLayer.swift
//  MBLibrary
//
//  Created by Marco Boschi on 08/08/2017.
//  Copyright © 2017 Marco Boschi. All rights reserved.
//
import QuartzCore
///A layer of a white rectangle with faded sides intented to be used as a mask for other layers.
public class FadedLayer: CALayer {
	
	///The size in point of the fade. Setting this property to a non-nil or non-negative value overrides `fadePercentage`.
	public var fadeSize: CGFloat? {
		didSet {
			if let val = fadeSize {
				if val >= 0 {
					fadePercentage = nil
				} else {
					fadeSize = nil
				}
			}
		}
	}
	
	///The size in percentage of the fade, if the dimensions are not equals, i.e. not a square, the percentage is calculed on the shortest side. Setting this property to a non-nil or non-negative value overrides `fadeSize`.
	public var fadePercentage: CGFloat? {
		didSet {
			if let val = fadePercentage {
				if val >= 0 {
					fadeSize = nil
				} else {
					fadePercentage = nil
				}
			}
		}
	}
	override public convenience init(layer: Any) {
		self.init()
		
		if let fade = layer as? FadedLayer {
			self.fadeSize = fade.fadeSize
			self.fadePercentage = fade.fadePercentage
		}
	}
	
	override public init() {
		super.init()
		
		backgroundColor = nil
		setNeedsDisplay()
	}
	
	required public init?(coder aDecoder: NSCoder) {
		fatalError("init(coder:) has not been implemented")
	}
	
	override public func draw(in ctx: CGContext) {
		let white = CGColor.createWithComponents(gray: 1)
		let clear = CGColor.createWithComponents(gray: 1, alpha: 0)
		ctx.setFillColor(white)
		
		guard let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceGray(), colors: [white, clear] as CFArray, locations: [0, 1]) else {
			fatalError("Something went horribly wrong for not beeing able to create the gradient")
		}
		let fadeSize = self.fadeSize ?? (min(bounds.width, bounds.height) * (self.fadePercentage ?? 0))
		
		// Middle part full opaque
		let middle = CGRect(x: fadeSize, y: fadeSize,
		                    width: bounds.width - 2*fadeSize, height: bounds.height - 2*fadeSize)
		ctx.fill(middle)
		
		// Top
		ctx.saveGState()
		let top = CGRect(x: fadeSize, y: 0, width: middle.size.width, height: fadeSize)
		ctx.addRect(top)
		ctx.clip()
		ctx.drawLinearGradient(gradient, start: CGPoint(x: fadeSize, y: fadeSize), end: CGPoint(x: fadeSize, y: 0), options: [])
		ctx.restoreGState()
		
		// Bottom
		ctx.saveGState()
		let bottom = CGRect(origin: CGPoint(x: fadeSize, y: fadeSize + middle.size.height),
		                    size: top.size)
		ctx.addRect(bottom)
		ctx.clip()
		ctx.drawLinearGradient(gradient, start: bottom.origin, end: CGPoint(x: fadeSize, y: bounds.height), options: [])
		ctx.restoreGState()
		
		// Left
		ctx.saveGState()
		let left = CGRect(x: 0, y: fadeSize, width: fadeSize, height: middle.size.height)
		ctx.addRect(left)
		ctx.clip()
		ctx.drawLinearGradient(gradient, start: CGPoint(x: fadeSize, y: fadeSize), end: CGPoint(x: 0, y: fadeSize), options: [])
		ctx.restoreGState()
		
		// Right
		ctx.saveGState()
		let right = CGRect(origin: CGPoint(x: fadeSize + middle.size.width, y: fadeSize),
		                   size: left.size)
		ctx.addRect(right)
		ctx.clip()
		ctx.drawLinearGradient(gradient, start: right.origin, end: CGPoint(x: bounds.width, y: fadeSize), options: [])
		ctx.restoreGState()
		
		var center: CGPoint
		
		// Top Left
		ctx.saveGState()
		let topLeft = CGRect(origin: .zero, size: CGSize(width: fadeSize, height: fadeSize))
		ctx.addRect(topLeft)
		ctx.clip()
		center = CGPoint(x: fadeSize, y: fadeSize)
		ctx.drawRadialGradient(gradient, startCenter: center, startRadius: 0, endCenter: center, endRadius: fadeSize, options: .drawsAfterEndLocation)
		ctx.restoreGState()
		
		// Top Right
		ctx.saveGState()
		let topRight = CGRect(origin: CGPoint(x: fadeSize + middle.size.width, y: 0), size: topLeft.size)
		ctx.addRect(topRight)
		ctx.clip()
		center = CGPoint(x: fadeSize + middle.size.width, y: fadeSize)
		ctx.drawRadialGradient(gradient, startCenter: center, startRadius: 0, endCenter: center, endRadius: fadeSize, options: .drawsAfterEndLocation)
		ctx.restoreGState()
		
		// Bottom Left
		ctx.saveGState()
		let bottomLeft = CGRect(origin: CGPoint(x: 0, y: fadeSize + middle.size.height), size: topLeft.size)
		ctx.addRect(bottomLeft)
		ctx.clip()
		center = CGPoint(x: fadeSize, y: fadeSize + middle.size.height)
		ctx.drawRadialGradient(gradient, startCenter: center, startRadius: 0, endCenter: center, endRadius: fadeSize, options: .drawsAfterEndLocation)
		ctx.restoreGState()
		
		// Bottom Right
		ctx.saveGState()
		let bottomRight = CGRect(origin: CGPoint(x: fadeSize + middle.size.width, y: fadeSize + middle.size.height), size: topLeft.size)
		ctx.addRect(bottomRight)
		ctx.clip()
		center = bottomRight.origin
		ctx.drawRadialGradient(gradient, startCenter: center, startRadius: 0, endCenter: center, endRadius: fadeSize, options: .drawsAfterEndLocation)
		ctx.restoreGState()
	}
	
}
 | 
	mit | 
	40ae6c5668258796d281b99b17b63537 | 32.52027 | 220 | 0.69482 | 3.60276 | false | false | false | false | 
| 
	toioski/ios-stopwatch | 
	Stopwatch/ViewController.swift | 
	1 | 
	6991 | 
	//
//  ViewController.swift
//  Stopwatch
//
//  Created by Vittorio Morganti on 21/01/16.
//  Copyright © 2016 toioski. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var bigTimerLabel: UILabel!
    @IBOutlet weak var smallTimerLabel: UILabel!
    @IBOutlet weak var startButton: DesignableButton!
    @IBOutlet weak var resetButton: DesignableButton!
    @IBOutlet weak var lapTableView: UITableView!
    @IBOutlet weak var tableContainerView: DesignableView!
    
    var startDate: NSDate?
    var stopTimer: NSTimer = NSTimer()
    var isRunning = false
    var pauseDate: NSDate?
    var laps: [String] = []
    var lapDate: NSDate?
    
    var red: UIColor = UIColor(red:0.9, green:0.23, blue:0.18, alpha:1)
    var green: UIColor = UIColor(red:0.51, green:0.92, blue:0.2, alpha:1)
    var disableGreyBackColor: UIColor = UIColor(red:0.894, green:0.894, blue:0.894, alpha:1)
    var disableTextColor: UIColor = UIColor(red:0.534, green:0.534, blue:0.534, alpha:1)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Setting monospace font is necessary, otherwise label 
        //will start "shrinking" when its label will be updated by the NSTimer
        bigTimerLabel.font = UIFont.monospacedDigitSystemFontOfSize(68, weight: UIFontWeightUltraLight)
        smallTimerLabel.font = UIFont.monospacedDigitSystemFontOfSize(24, weight: UIFontWeightUltraLight)
        
        bigTimerLabel.text = "00:00,00"
        smallTimerLabel.text = "00:00,00"
        
        //Button configs
        startButton.clipsToBounds = true
        resetButton.clipsToBounds = true
        startButton.setBackgroundImage(UIImage.imageWithColor(UIColor.grayColor()), forState: .Highlighted)
        resetButton.setBackgroundImage(UIImage.imageWithColor(UIColor.grayColor()), forState: .Highlighted)
        resetButton.setBackgroundImage(UIImage.imageWithColor(disableGreyBackColor), forState: .Disabled)
        resetButton.setTitleColor(disableTextColor, forState: .Disabled)
        resetButton.enabled = false
        
    }
    
    //This function is triggered when the device change orientation
    override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
        
        if UIView.viewOrientationForSize(size) == ViewOrientation.Landscape {
            bigTimerLabel.font = UIFont.monospacedDigitSystemFontOfSize(54, weight: UIFontWeightUltraLight)
            smallTimerLabel.font = UIFont.monospacedDigitSystemFontOfSize(20, weight: UIFontWeightUltraLight)
        } else {
            bigTimerLabel.font = UIFont.monospacedDigitSystemFontOfSize(68, weight: UIFontWeightUltraLight)
            smallTimerLabel.font = UIFont.monospacedDigitSystemFontOfSize(24, weight: UIFontWeightUltraLight)
        }
    }
    
    
    @IBAction func startTimer(sender: AnyObject) {
        if (!isRunning) {
            isRunning = true
            
            resetButton.enabled = true
            resetButton.setBackgroundImage(UIImage.imageWithColor(UIColor.whiteColor()), forState: .Normal)
            resetButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
            
            if (pauseDate != nil) {
                let secondsBetween = pauseDate!.timeIntervalSinceDate(startDate!)
                startDate = NSDate(timeIntervalSinceNow: (-1)*secondsBetween)
            } else {
                startDate = NSDate()
            }
            
            sender.setTitle("Stop", forState: .Normal)
            sender.setTitleColor(red, forState: .Normal)
            resetButton.setTitle("Giro", forState: .Normal)
            
            stopTimer = NSTimer.scheduledTimerWithTimeInterval(1.0/100.0, target: self, selector: Selector("updateTimer"), userInfo: nil, repeats: true)
            //This line prevent the timer to stop when scrolling
            NSRunLoop.mainRunLoop().addTimer(stopTimer, forMode: NSRunLoopCommonModes)
        } else {
            isRunning = false
            sender.setTitle("Start", forState: .Normal)
            sender.setTitleColor(green, forState: .Normal)
            resetButton.setTitle("Reset", forState: .Normal)
            resetButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
            resetButton.setBackgroundImage(UIImage.imageWithColor(red), forState: .Normal)
            stopTimer.invalidate()
            pauseDate = NSDate()
        }
    }
    
    //Business logic
    func updateTimer() {
        let currentDate = NSDate()
        let timeInterval = currentDate.timeIntervalSinceDate(startDate!)
        let timerDate = NSDate(timeIntervalSince1970: timeInterval)
        
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "mm:ss,SS"
        dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
        let timeString = dateFormatter.stringFromDate(timerDate)
        bigTimerLabel.text = timeString
        
        if (lapDate != nil) {
            let anotherTimeInterval = currentDate.timeIntervalSinceDate(lapDate!)
            let lapTimerDate = NSDate(timeIntervalSince1970: anotherTimeInterval)
            let lapTimerString = dateFormatter.stringFromDate(lapTimerDate)
            smallTimerLabel.text = lapTimerString
        } else {
            smallTimerLabel.text = timeString
        }
    }
    
    @IBAction func resetPressed(sender: AnyObject) {
        if (!isRunning) {
            //Reset all parameters
            
            stopTimer.invalidate()
            pauseDate = nil
            lapDate = nil
            bigTimerLabel.text = "00:00,00"
            smallTimerLabel.text = "00:00,00"
            startButton.setTitle("Start", forState: .Normal)
            startButton.setTitleColor(green, forState: .Normal)
            isRunning = false
            resetButton.enabled = false
            laps.removeAll()
            lapTableView.reloadData()
        } else {
            //Add lap
            
            lapDate = NSDate()
            laps.insert(bigTimerLabel.text!, atIndex: 0)
            lapTableView.reloadData()
        }
    }
    
    //TableView
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier("LapCell") as! LapTableViewCell
        cell.backgroundColor = UIColor.clearColor()
        
        //La numerazione dei giri è inversa rispetto a quella delle righe della tabella
        let lapNumber = laps.count - indexPath.row
        cell.label!.text = "Giro \(lapNumber)"
        cell.time!.text = laps[indexPath.row]
        
        return cell
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return laps.count
    }
}
 | 
	gpl-3.0 | 
	1efefa0b1b3cc670d66485516da3d56d | 40.60119 | 152 | 0.65274 | 5.306758 | false | false | false | false | 
| 
	onekiloparsec/SwiftAA | 
	Sources/SwiftAA/ScientificConstants.swift | 
	1 | 
	10329 | 
	//
//  ScientificConstants.swift
//  SwiftAA
//
//  Created by Cédric Foellmi on 17/12/2016.
//  MIT Licence. See LICENCE file.
//
import Foundation
import ObjCAA
/// Constant value substracted from Julian Day to create so-called modified julian days.
public let ModifiedJulianDayZero: Double = 2400000.5
/// The length of Julian Years, in days.
public let JulianYear: Day = 365.25            // See p.133 of AA.
/// The length of Besselian Years, in days.
public let BesselianYear: Day = 365.2421988    // See p.133 of AA.
/// The new standard epoch, as decided by the IAU in 1984.
public let StandardEpoch_J2000_0: JulianDay = 2451545.0 // See p.133 of AA.
public let StandardEpoch_B1950_0: JulianDay = 2433282.4235 // See p.133 of AA.
/// Mean value of the lunar equator inclination, relative to the ecliptic.
public let MeanLunarEquatorInclination: Degree = 1.54242 // Relative, to Ecliptic. See p. 372 of AA.
public typealias Kilogram=Double
public typealias Celsius=Double
public typealias Millibar=Double
/// Conversion factor from radians to degrees.
public let rad2deg = 180.0/Double.pi
/// Conversion factor from degrees to radians.
public let deg2rad = Double.pi/180.0
/// Conversion factor from radians to hours.
public let rad2hour = 3.8197186342054880584532103209403
/// Conversion factor from hours to radians.
public let hour2rad = 0.26179938779914943653855361527329
/// Conversion factor from Astronomical Unit to parsecs.
public let AU2pc: Double = tan(1.0/3600.0/deg2rad)
/// Conversion factor from Astronomical Unit to meters.
public let AU2m: Double = 149597870700.0 // Wikipedia
/// Conversion factor from Astronomical Unit to light-years.
public let AU2ly: Double = 1.0/206264.8
/// Standard eqpoch values. Note: equinoxes are directions, epochs are point in time.
public enum Epoch: CustomStringConvertible {
    
    /// The mean epoch of the date.
    case epochOfTheDate(JulianDay)
    
    /// The standard 2000 epoch: January 1st, 2000, in the Julian calendar (1 year = 365.25 days).
    case J2000
    
    /// The standard 1950 epoch: January 1st, 1950, in the Besselian calendar
    /// (1 year = 365.2421988 days in AD1900, that is, the length of the tropical year).
    case B1950
    
    /// The value of the epoch, in Julian Days.
    var julianDay: JulianDay {
        switch self {
        case .epochOfTheDate(let julianDay):
            return julianDay
        case .J2000:
            return StandardEpoch_J2000_0
        case .B1950:
            return StandardEpoch_B1950_0
        }
    }
    
    public var description: String {
        switch self {
        case .epochOfTheDate(let julianDay):
            return julianDay.description
        case .J2000:
            return "J2000.0"
        case .B1950:
            return "B1950.0"
        }
    }
}
/// Standard equinox values. Note: equinoxes are directions, epochs are point in time.
/// The vernal equinox, which is the zero point of both right ascension and celestial longitude, is defined
/// to be in the direction of the ascending node of the ecliptic on the equator.
/// Of course, at the standard epoch of J2000 corresponds to a specific (and thus standard) equinox.
public enum Equinox: CustomStringConvertible {
    
    /// The mean equinox of the date is the intersection of the ecliptic of the date with the mean equator of the date.
    case meanEquinoxOfTheDate(JulianDay)
    
    /// The standard 2000 equinox: January 1st, 2000, in the Julian calendar (1 year = 365.25 days).
    case standardJ2000
    
    /// The standard 1950 equinox: January 1st, 1950, in the Besselian calendar 
    /// (1 year = 365.2421988 days in AD1900, that is, the length of the tropical year).
    case standardB1950
    
    /// The Julian Day of the given equinox.
    var julianDay: JulianDay {
        switch self {
        case .meanEquinoxOfTheDate(let julianDay):
            return julianDay
        case .standardJ2000:
            return StandardEpoch_J2000_0
        case .standardB1950:
            return StandardEpoch_B1950_0
        }
    }
    
    public var description: String { return self.julianDay.description }
}
/// Earth seasons
///
/// - spring: Spring
/// - summer: Summer
/// - autumn: Autumn
/// - winter: Winter
public enum Season {
    case spring
    case summer
    case autumn
    case winter
}
/// Moon phases
///
/// - new: New Moon
/// - firstQuarter: First Quarter
/// - full: Full Moon
/// - lastQuarter: Last Quarter
public enum MoonPhase {
    case newMoon
    case firstQuarter
    case fullMoon
    case lastQuarter
}
/// Error used when computing Rise Transit and Set times (see Earth twilights and planetary rise, transit and set times).
///
/// - alwaysBelowAltitude: The object is always below the given altitude.
/// - alwaysAboveAltitude: The object is always above the given altitude.
public enum CelestialBodyTransitError: Error {
    case alwaysBelowAltitude
    case alwaysAboveAltitude
    case undefinedPlanetaryObject
}
// Check nested types in https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html
/// KPCAAPlanet is an enum for all historical 9 planets, that is, including Pluto.
extension KPCAAPlanet: CustomStringConvertible {
    
    /// Return the KPCAAPlanet enum value from a planet name string.
    ///
    /// - Parameter string: The planet name.
    /// - Returns: The KPCAAPlanet enum value
    public static func fromString(_ string: String) -> KPCAAPlanet {
        if string == "Mercury" {
            return .Mercury
        }
        else if string == "Venus" {
            return .Venus
        }
        else if string == "Earth" {
            return .Earth
        }
        else if string == "Mars" {
            return .Mars
        }
        else if string == "Jupiter" {
            return .Jupiter
        }
        else if string == "Saturn" {
            return .Saturn
        }
        else if string == "Uranus" {
            return .Uranus
        }
        else if string == "Neptune" {
            return .Neptune
        }
        else if string == "Pluto" {
            return .Pluto
        }
        else {
            return .Undefined
        }
    }
    
    /// Return the planet name according to the enum value.
    public var description: String {
        switch self {
        case .Mercury:
            return "Mercury"
        case .Venus:
            return "Venus"
        case .Earth:
            return "Earth"
        case .Mars:
            return "Mars"
        case .Jupiter:
            return "Jupiter"
        case .Saturn:
            return "Saturn"
        case .Uranus:
            return "Uranus"
        case .Neptune:
            return "Neptune"
        case .Pluto:
            return "Pluto"
        case .Undefined:
            return ""
        @unknown default:
            return ""
        }
    }
}
// Tricky Swiftness tricks to use the 3 partly-overlapping enums with as few
// code lines as possible. There must be some other way round to force correct
// planet enum parameters in Obj-C functions. The code here is the consequence of
// choosing to make switch statments inside Obj-C layer, rather than in Swift one.
/// KPCAAPlanetStrict is an enum for all true planets, that is, excluding the now official
/// Dwarf Planet category, that is, Pluto.
public extension KPCAAPlanetStrict {
    
    /// Return the equivalent KPCAAPlanetStrict enum value from the KPCAAPlanet enum.
    ///
    /// - Parameter planet: The KPCAAPlanet enum value
    /// - Returns: The equivalent KPCAAPlanetStrict enum value
    static func fromPlanet(_ planet: KPCAAPlanet) -> KPCAAPlanetStrict {
        switch planet {
        case .Pluto:
            return .undefined
        default:
            return KPCAAPlanetStrict(rawValue: planet.rawValue)!
        }
    }
}
/// KPCPlanetaryObject is an enum for all planets, excluding Earth and Pluto.
public extension KPCPlanetaryObject {
    
    /// Returns the planetary object index from a given planet index.
    ///
    /// - Parameter planet: The planet index.
    /// - Returns: The corresponding planetary object index.
    static func fromPlanet(_ planet: KPCAAPlanet) -> KPCPlanetaryObject {
        switch planet {
        case .Mercury:
            return .MERCURY
        case .Venus:
            return .VENUS
        case .Mars:
            return .MARS
        case .Jupiter:
            return .JUPITER
        case .Saturn:
            return .SATURN
        case .Uranus:
            return .URANUS
        case .Neptune:
            return .NEPTUNE
        default:
            return .UNDEFINED
        }
    }
    
    /// Returns the SwiftAA Class type for the given planetary object.
    var objectType: Planet.Type? {
        switch self {
        case .MERCURY:
            return SwiftAA.Mercury.self
        case .VENUS:
            return SwiftAA.Venus.self
        case .MARS:
            return SwiftAA.Mars.self
        case .JUPITER:
            return SwiftAA.Jupiter.self
        case .SATURN:
            return SwiftAA.Saturn.self
        case .URANUS:
            return SwiftAA.Uranus.self
        case .NEPTUNE:
            return SwiftAA.Neptune.self
        case .UNDEFINED:
            return nil
        @unknown default:
            return nil
        }
    }
}
/// KPCAAEllipticalObject is an enum for the Sun, all planets, excluding Earth but including Pluto.
public extension KPCAAEllipticalObject {
    
    /// Returns the elliptical object index from a given planet index.
    ///
    /// - Parameter planet: The planet index.
    /// - Returns: The corresponding elliptical object index. The Sun must be handled individually.
    static func fromPlanet(_ planet: KPCAAPlanet) -> KPCAAEllipticalObject {
        switch planet {
        case .Mercury:
            return .MERCURY_elliptical
        case .Venus:
            return .VENUS_elliptical
        case .Mars:
            return .MARS_elliptical
        case .Jupiter:
            return .JUPITER_elliptical
        case .Saturn:
            return .SATURN_elliptical
        case .Uranus:
            return .URANUS_elliptical
        case .Neptune:
            return .NEPTUNE_elliptical
        default:
            return .UNDEFINED_elliptical
        }
    }
}
 | 
	mit | 
	c086e639bb4cc74ac3709df6e033c8ff | 30.202417 | 138 | 0.632068 | 4.459413 | false | false | false | false | 
| 
	jmfieldman/Mortar | 
	Mortar/Mortar.swift | 
	1 | 
	18300 | 
	//
//  Mortar
//
//  Copyright (c) 2016-Present Jason Fieldman - https://github.com/jmfieldman/Mortar
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
public typealias MortarView = UIView
public typealias MortarAliasLayoutPriority = UILayoutPriority
public typealias MortarAliasLayoutRelation = NSLayoutConstraint.Relation
public typealias MortarAliasLayoutAttribute = NSLayoutConstraint.Attribute
#else
import AppKit
public typealias MortarView = NSView
public typealias MortarAliasLayoutPriority = NSLayoutConstraint.Priority
public typealias MortarAliasLayoutRelation = NSLayoutConstraint.Relation
public typealias MortarAliasLayoutAttribute = NSLayoutConstraint.Attribute
#endif
public let MortarAliasLayoutPriorityDefaultLow      = MortarAliasLayoutPriority.defaultLow
public let MortarAliasLayoutPriorityDefaultMedium   = MortarAliasLayoutPriority(rawValue: (Float(MortarAliasLayoutPriority.defaultHigh.rawValue) + Float(MortarAliasLayoutPriority.defaultLow.rawValue)) / 2)
public let MortarAliasLayoutPriorityDefaultHigh     = MortarAliasLayoutPriority.defaultHigh
public let MortarAliasLayoutPriorityDefaultRequired = MortarAliasLayoutPriority.required
internal enum MortarLayoutAttribute {
    case left
    case right
    case top
    case bottom
    case leading
    case trailing
    case width
    case height
    case centerX
    case centerY
    case baseline
    #if os(iOS) || os(tvOS)
    case firstBaseline
    case lastBaseline
    case leftMargin
    case rightMargin
    case topMargin
    case bottomMargin
    case leadingMargin
    case trailingMargin
    case centerXWithinMargins
    case centerYWithinMargins
    #endif
    case notAnAttribute
    case sides
    case caps
    case size
    case cornerTL
    case cornerTR
    case cornerBL
    case cornerBR
    case edges
    case frame
    case center
    
    #if os(iOS) || os(tvOS)
    func nsLayoutAttribute() -> MortarAliasLayoutAttribute? {
        switch self {
        case .left:                     return .left
        case .right:                    return .right
        case .top:                      return .top
        case .bottom:                   return .bottom
        case .leading:                  return .leading
        case .trailing:                 return .trailing
        case .width:                    return .width
        case .height:                   return .height
        case .centerX:                  return .centerX
        case .centerY:                  return .centerY
        case .baseline:                 return .lastBaseline
        case .firstBaseline:            return .firstBaseline
        case .lastBaseline:             return .lastBaseline
        case .leftMargin:               return .leftMargin
        case .rightMargin:              return .rightMargin
        case .topMargin:                return .topMargin
        case .bottomMargin:             return .bottomMargin
        case .leadingMargin:            return .leadingMargin
        case .trailingMargin:           return .trailingMargin
        case .centerXWithinMargins:     return .centerXWithinMargins
        case .centerYWithinMargins:     return .centerYWithinMargins
        case .notAnAttribute:           return .notAnAttribute
        default:                        return nil
        }
    }
    #else
    func nsLayoutAttribute() -> MortarAliasLayoutAttribute? {
        switch self {
        case .left:                     return .left
        case .right:                    return .right
        case .top:                      return .top
        case .bottom:                   return .bottom
        case .leading:                  return .leading
        case .trailing:                 return .trailing
        case .width:                    return .width
        case .height:                   return .height
        case .centerX:                  return .centerX
        case .centerY:                  return .centerY
        case .baseline:                 return .lastBaseline
        case .notAnAttribute:           return .notAnAttribute
        default:                        return nil
        }
    }
    #endif
    
    #if os(iOS) || os(tvOS)
    func componentAttributes() -> [MortarLayoutAttribute] {
        switch self {
        case .left:                     return [.left                                   ]
        case .right:                    return [.right                                  ]
        case .top:                      return [.top                                    ]
        case .bottom:                   return [.bottom                                 ]
        case .leading:                  return [.leading                                ]
        case .trailing:                 return [.trailing                               ]
        case .width:                    return [.width                                  ]
        case .height:                   return [.height                                 ]
        case .centerX:                  return [.centerX                                ]
        case .centerY:                  return [.centerY                                ]
        case .baseline:                 return [.lastBaseline                           ]
        case .firstBaseline:            return [.firstBaseline                          ]
        case .lastBaseline:             return [.lastBaseline                           ]
        case .leftMargin:               return [.leftMargin                             ]
        case .rightMargin:              return [.rightMargin                            ]
        case .topMargin:                return [.topMargin                              ]
        case .bottomMargin:             return [.bottomMargin                           ]
        case .leadingMargin:            return [.leadingMargin                          ]
        case .trailingMargin:           return [.trailingMargin                         ]
        case .centerXWithinMargins:     return [.centerXWithinMargins                   ]
        case .centerYWithinMargins:     return [.centerYWithinMargins                   ]
        case .notAnAttribute:           return [.notAnAttribute                         ]
            
        case .sides:                    return [.left,    .right                        ]
        case .caps:                     return [.top,     .bottom                       ]
        case .size:                     return [.width,   .height                       ]
        case .cornerTL:                 return [.top,     .left                         ]
        case .cornerTR:                 return [.top,     .right                        ]
        case .cornerBL:                 return [.bottom,  .left                         ]
        case .cornerBR:                 return [.bottom,  .right                        ]
        case .edges:                    return [.top,     .left,    .bottom,  .right    ]
        case .frame:                    return [.left,    .top,     .width,   .height   ]
        case .center:                   return [.centerX, .centerY                      ]            
        }
    }
    #else
    func componentAttributes() -> [MortarLayoutAttribute] {
        switch self {
        case .left:                     return [.left                                   ]
        case .right:                    return [.right                                  ]
        case .top:                      return [.top                                    ]
        case .bottom:                   return [.bottom                                 ]
        case .leading:                  return [.leading                                ]
        case .trailing:                 return [.trailing                               ]
        case .width:                    return [.width                                  ]
        case .height:                   return [.height                                 ]
        case .centerX:                  return [.centerX                                ]
        case .centerY:                  return [.centerY                                ]
        case .baseline:                 return [.baseline                               ]
        case .notAnAttribute:           return [.notAnAttribute                         ]
        
        case .sides:                    return [.left,    .right                        ]
        case .caps:                     return [.top,     .bottom                       ]
        case .size:                     return [.width,   .height                       ]
        case .cornerTL:                 return [.top,     .left                         ]
        case .cornerTR:                 return [.top,     .right                        ]
        case .cornerBL:                 return [.bottom,  .left                         ]
        case .cornerBR:                 return [.bottom,  .right                        ]
        case .edges:                    return [.top,     .left,    .bottom,  .right    ]
        case .frame:                    return [.left,    .top,     .width,   .height   ]
        case .center:                   return [.centerX, .centerY                      ]
        }
    }
    #endif
    
    #if os(iOS) || os(tvOS)
    func implicitSuperviewBaseline() -> MortarAliasLayoutAttribute {
        switch self {
        case .left:                     return .left
        case .right:                    return .left
        case .top:                      return .top
        case .bottom:                   return .top
        case .centerX:                  return .left
        case .centerY:                  return .top
        case .centerXWithinMargins:     return .left
        case .centerYWithinMargins:     return .top
        default:                        return .notAnAttribute
        }
    }
    #else
    func implicitSuperviewBaseline() -> MortarAliasLayoutAttribute {
        switch self {
        case .left:                     return .left
        case .right:                    return .left
        case .top:                      return .top
        case .bottom:                   return .top
        case .centerX:                  return .left
        case .centerY:                  return .top
        default:                        return .notAnAttribute
        }
    }
    #endif
    
    func insetConstantModifier() -> CGFloat {
        switch self {
        case .right:                    return -1
        case .bottom:                   return -1
        default:                        return 1
        }
    }
}
public enum MortarLayoutPriority {
    case low, medium, high, req
    
    // As of v1.1, the actual default priority is .required.  
    // "default" is a misleading term for this enum.
    // Medium is a better term for the priority between low and high.
    @available(*, deprecated, message: "The default priority enumeration has been renamed medium")
    case `default`
    
    @inline(__always) public func layoutPriority() -> MortarAliasLayoutPriority {
        switch self {
        case .low:      return MortarAliasLayoutPriorityDefaultLow
        case .medium:   return MortarAliasLayoutPriorityDefaultMedium
        case .high:     return MortarAliasLayoutPriorityDefaultHigh
        case .req:      return MortarAliasLayoutPriorityDefaultRequired
        
        // Please note that this is a misleading enum value that remains MortarAliasLayoutPriorityDefaultMedium
        // for compatibility reasons.  The actual default priority of a constraint is now 1000/.required
        case .default:  return MortarAliasLayoutPriorityDefaultMedium
        }
    }
}
public enum MortarActivationState {
    case activated, deactivated
}
public protocol MortarCGFloatable: MortarAliasLayoutPriorityAble {
    @inline(__always) func m_cgfloatValue() -> CGFloat
}
extension CGFloat : MortarCGFloatable {
    @inline(__always) public func m_cgfloatValue() -> CGFloat {
        return self
    }
    
    @inline(__always) public func m_intoPriority() -> MortarAliasLayoutPriority {
        return MortarAliasLayoutPriority(rawValue: Float(self))
    }
}
extension Int : MortarCGFloatable {
    @inline(__always) public func m_cgfloatValue() -> CGFloat {
        return CGFloat(self)
    }
    
    @inline(__always) public func m_intoPriority() -> MortarAliasLayoutPriority {
        return MortarAliasLayoutPriority(rawValue: Float(self))
    }
}
extension UInt : MortarCGFloatable {
    @inline(__always) public func m_cgfloatValue() -> CGFloat {
        return CGFloat(self)
    }
    
    @inline(__always) public func m_intoPriority() -> MortarAliasLayoutPriority {
        return MortarAliasLayoutPriority(rawValue: Float(self))
    }
}
extension Int64 : MortarCGFloatable {
    @inline(__always) public func m_cgfloatValue() -> CGFloat {
        return CGFloat(self)
    }
    
    @inline(__always) public func m_intoPriority() -> MortarAliasLayoutPriority {
        return MortarAliasLayoutPriority(rawValue: Float(self))
    }
}
extension UInt64 : MortarCGFloatable {
    @inline(__always) public func m_cgfloatValue() -> CGFloat {
        return CGFloat(self)
    }
    
    @inline(__always) public func m_intoPriority() -> MortarAliasLayoutPriority {
        return MortarAliasLayoutPriority(rawValue: Float(self))
    }
}
extension UInt32 : MortarCGFloatable {
    @inline(__always) public func m_cgfloatValue() -> CGFloat {
        return CGFloat(self)
    }
    
    @inline(__always) public func m_intoPriority() -> MortarAliasLayoutPriority {
        return MortarAliasLayoutPriority(rawValue: Float(self))
    }
}
extension Int32 : MortarCGFloatable {
    @inline(__always) public func m_cgfloatValue() -> CGFloat {
        return CGFloat(self)
    }
    
    @inline(__always) public func m_intoPriority() -> MortarAliasLayoutPriority {
        return MortarAliasLayoutPriority(rawValue: Float(self))
    }
}
extension Double : MortarCGFloatable {
    @inline(__always) public func m_cgfloatValue() -> CGFloat {
        return CGFloat(self)
    }
    
    @inline(__always) public func m_intoPriority() -> MortarAliasLayoutPriority {
        return MortarAliasLayoutPriority(rawValue: Float(self))
    }
}
extension Float : MortarCGFloatable {
    @inline(__always) public func m_cgfloatValue() -> CGFloat {
        return CGFloat(self)
    }
    
    @inline(__always) public func m_intoPriority() -> MortarAliasLayoutPriority {
        return MortarAliasLayoutPriority(rawValue: Float(self))
    }
}
public protocol MortarAttributable {
    @inline(__always) func m_intoAttribute() -> MortarAttribute
}
extension CGFloat : MortarAttributable {
    public func m_intoAttribute() -> MortarAttribute {
        return MortarAttribute(constant: self)
    }
}
extension Int : MortarAttributable {
    public func m_intoAttribute() -> MortarAttribute {
        return MortarAttribute(constant: self)
    }
}
extension Double : MortarAttributable {
    public func m_intoAttribute() -> MortarAttribute {
        return MortarAttribute(constant: self)
    }
}
extension Float : MortarAttributable {
    public func m_intoAttribute() -> MortarAttribute {
        return MortarAttribute(constant: self)
    }
}
extension MortarView : MortarAttributable {
    public func m_intoAttribute() -> MortarAttribute {
        return MortarAttribute(item: self)
    }
}
#if os(iOS) || os(tvOS)
    extension UILayoutGuide : MortarAttributable {
        public func m_intoAttribute() -> MortarAttribute {
            return MortarAttribute(item: self)
        }
    }
#endif
extension MortarAttribute : MortarAttributable {
    @inline(__always) public func m_intoAttribute() -> MortarAttribute {
        return self
    }
}
public protocol MortarAliasLayoutPriorityAble {
    @inline(__always) func m_intoPriority() -> MortarAliasLayoutPriority
}
extension MortarAliasLayoutPriority: MortarAliasLayoutPriorityAble {
    public func m_intoPriority() -> MortarAliasLayoutPriority {
        return self
    }
}
extension MortarAliasLayoutPriorityAble {
    public var rawValue: Float {
        return self.m_intoPriority().rawValue
    }
}
public typealias MortarConstTwo  = (MortarCGFloatable, MortarCGFloatable)
public typealias MortarConstFour = (MortarCGFloatable, MortarCGFloatable, MortarCGFloatable, MortarCGFloatable)
public typealias MortarTwople  = (MortarAttributable, MortarAttributable)
public typealias MortarFourple = (MortarAttributable, MortarAttributable, MortarAttributable, MortarAttributable)
public typealias MortarTuple   = ([MortarAttribute], MortarAliasLayoutPriority?)
@inline(__always) internal func MortarConvertTwople(_ twople: MortarTwople) -> MortarTuple {
    return ([twople.0.m_intoAttribute(), twople.1.m_intoAttribute()], MortarDefault.priority.current())
}
@inline(__always) internal func MortarConvertFourple(_ fourple: MortarFourple) -> MortarTuple {
    return ([fourple.0.m_intoAttribute(), fourple.1.m_intoAttribute(), fourple.2.m_intoAttribute(), fourple.3.m_intoAttribute()], MortarDefault.priority.current())
}
public enum MortarAxis {
    case horizontal, vertical
}
 | 
	mit | 
	8f84721b88cce3754fea14699929b3cb | 40.780822 | 205 | 0.555956 | 5.681465 | false | false | false | false | 
| 
	googlearchive/science-journal-ios | 
	ScienceJournal/UI/MaterialHeaderViewController.swift | 
	1 | 
	6302 | 
	/*
 *  Copyright 2019 Google LLC. All Rights Reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
import UIKit
import third_party_objective_c_material_components_ios_components_AppBar_AppBar
import third_party_objective_c_material_components_ios_components_Dialogs_ColorThemer
import third_party_objective_c_material_components_ios_components_private_Overlay_Overlay
/// Boilerplate view controller for setting up a Material header view.
class MaterialHeaderViewController: ScienceJournalViewController, UIScrollViewDelegate,
                                    UIGestureRecognizerDelegate {
  // MARK: - Properties
  let appBar = MDCAppBar()
  var trackedScrollView: UIScrollView? { return nil }
  @objc private(set) lazy var scrollViewContentObserver =
    ScrollViewContentObserver(scrollView: trackedScrollView)
  private weak var existingInteractivePopGestureRecognizerDelegate : UIGestureRecognizerDelegate?
  // MARK: - MaterialHeader
  override var hasMaterialHeader: Bool { return true }
  // MARK: - Public
  override func viewDidLoad() {
    super.viewDidLoad()
    appBar.configure(attachTo: self, scrollView: trackedScrollView)
    trackedScrollView?.delegate = appBar.headerViewController
    MDCAlertColorThemer.apply(ViewConstants.alertColorScheme)
  }
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    if let popDelegate = navigationController?.interactivePopGestureRecognizer?.delegate {
      // When using MDCFlexibileHeaderController within a UINavigationController, setting the
      // UINavigationController's navigationBarHidden property to YES results in the loss of the
      // swipe-to-go-back feature associated with the controller.
      //
      // To re-enable this feature when hiding the navigation controller's navigationBar,
      // set a pointer to the current interactivePopGestureRecognizer's delegate before setting
      // the navigationBarHidden property to YES, set the interactivePopGestureRecognizer's delegate
      // to nil while MDCFlexibileHeaderController's parent controller is actively on-screen in
      // viewDidAppear:, then re-set the interactivePopGestureRecognizer's delegate to the stored
      // pointer in viewWillDisappear: (see below).
      //
      // See https://goo.gl/BU5fmO for more details.
      existingInteractivePopGestureRecognizerDelegate = popDelegate
    }
    navigationController?.setNavigationBarHidden(true, animated: animated)
    // Bring the app bar to the front.
    view.bringSubviewToFront(appBar.headerViewController.headerView)
  }
  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    // Watch for back swipe events so subclasses can do stuff before pops if necessary.
    navigationController?.interactivePopGestureRecognizer?.delegate = self
  }
  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    if let popDelegate = existingInteractivePopGestureRecognizerDelegate {
      // Return interactivePopGestureRecognizer delegate to previously held object.
      navigationController?.interactivePopGestureRecognizer?.delegate = popDelegate
    }
  }
  override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    MDCOverlayObserver(for: .main).removeTarget(self)
  }
  override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
  }
  override func viewWillTransition(to size: CGSize,
                                   with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    if #available(iOS 10.0, *) { return }
    // In iOS 9, a bug in MDCNavigationBar will cause right bar items to disappear on rotation
    // unless we layout the subviews once rotation animation is complete.
    coordinator.animate(alongsideTransition: nil) { _ in
      self.appBar.navigationBar.layoutSubviews()
    }
  }
  // MARK: - UIGestureRecognizerDelegate
  func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    if gestureRecognizer == navigationController?.interactivePopGestureRecognizer {
      return interactivePopGestureShouldBegin()
    }
    return true
  }
  /// Subclasses can override this if they need to do something before the pop occurs.
  func interactivePopGestureShouldBegin() -> Bool {
    return true
  }
  // MARK: - UIScrollViewDelegate
  func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView == appBar.headerViewController.headerView.trackingScrollView {
      appBar.headerViewController.headerView.trackingScrollDidScroll()
    }
  }
  func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    if scrollView == appBar.headerViewController.headerView.trackingScrollView {
      appBar.headerViewController.headerView.trackingScrollDidEndDecelerating()
    }
  }
  func scrollViewDidEndDragging(_ scrollView: UIScrollView,
                                willDecelerate decelerate: Bool) {
    if scrollView == appBar.headerViewController.headerView.trackingScrollView {
      let headerView = appBar.headerViewController.headerView
      headerView.trackingScrollDidEndDraggingWillDecelerate(decelerate)
    }
  }
  func scrollViewWillEndDragging(_ scrollView: UIScrollView,
                                 withVelocity velocity: CGPoint,
                                 targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    if scrollView == appBar.headerViewController.headerView.trackingScrollView {
      let headerView = appBar.headerViewController.headerView
      headerView.trackingScrollWillEndDragging(withVelocity: velocity,
                                               targetContentOffset: targetContentOffset)
    }
  }
}
 | 
	apache-2.0 | 
	4b96099ed639811173fc4ca07fbd87c5 | 40.189542 | 100 | 0.74278 | 5.652018 | false | false | false | false | 
| 
	jovito-royeca/Decktracker | 
	ios/old/Decktracker/View/More/MoreViewController.swift | 
	1 | 
	4890 | 
	//
//  MoreViewController.swift
//  Decktracker
//
//  Created by Jovit Royeca on 10/17/14.
//  Copyright (c) 2014 Jovito Royeca. All rights reserved.
//
import UIKit
class MoreViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, ReaderViewControllerDelegate {
    
    var tblMore:UITableView!
    let arrayData = [["Rules": ["Basic Rulebook", "Comprehensive Rules"]],
                     ["": ["Settings"]]]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let height = view.frame.size.height - tabBarController!.tabBar.frame.size.height
        let frame = CGRect(x:0, y:0, width:view.frame.width, height:height)
        tblMore = UITableView(frame: frame, style: UITableViewStyle.Grouped)
        tblMore.delegate = self
        tblMore.dataSource = self
        
        view.addSubview(tblMore)
        self.navigationItem.title = "More"
#if !DEBUG
        // send the screen to Google Analytics
        if let tracker = GAI.sharedInstance().defaultTracker {
            tracker.set(kGAIScreenName, value: "More")
            tracker.send(GAIDictionaryBuilder.createScreenView().build() as [NSObject : AnyObject])
        }
#endif
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
//    MARK: UITableViewDataSource
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        let row = arrayData[section]
        let key = Array(row.keys)[0]
        let dict = row[key]!
        return dict.count
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return arrayData.count
    }
    
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
    {
        let row = arrayData[section]
        return Array(row.keys)[0]
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        var cell:UITableViewCell?
        
        if let x = tableView.dequeueReusableCellWithIdentifier("DefaultCell") as UITableViewCell! {
            cell = x
        } else  {
            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "DefaultCell")
            cell!.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
        }
        let row = arrayData[indexPath.section]
        let key = Array(row.keys)[0]
        let dict = row[key]!
        let value = dict[indexPath.row]
        
        cell!.textLabel!.text = value
        cell!.imageView!.image = nil
        
        if value == "Card Quiz" {
            cell!.imageView!.image = UIImage(named: "questions.png")
        }
        else if value == "Settings" {
            cell!.imageView!.image = UIImage(named: "settings.png")
        }
        return cell!
    }
    
//    MARK: UITableViewDelegate
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        let row = arrayData[indexPath.section]
        let key = Array(row.keys)[0]
        let dict = row[key]!
        let value = dict[indexPath.row]
        
        var newView:UIViewController?
        var fullScreen = false
        
        if value == "Basic Rulebook" {
            let pdfs = NSBundle.mainBundle().pathsForResourcesOfType("pdf", inDirectory:"rules")
            let file = pdfs[indexPath.row]
            let document = ReaderDocument.withDocumentFilePath(file, password: nil)
            let readerView = ReaderViewController(readerDocument:document)
            readerView.delegate = self
            newView = readerView
            newView!.hidesBottomBarWhenPushed = true
            navigationController?.setNavigationBarHidden(true, animated:true)
            
        } else if value == "Comprehensive Rules" {
            let compView = ComprehensiveRulesViewController()
            newView = compView
            
        } else if value == "Card Quiz" {
            newView = CardQuizHomeViewController()
            fullScreen = true
            
        } else if value == "Life Counter" {
            
        } else if value == "Settings" {
            newView = SettingsViewController()
        }
        
        if let v = newView {
            if fullScreen {
                self.presentViewController(v, animated: false, completion: nil)
            } else {
                navigationController?.pushViewController(v, animated:true)
            }
        }
    }
    
//    MARK: ReaderViewControllerDelegate
    func dismissReaderViewController(viewController:ReaderViewController)
    {
        navigationController?.popViewControllerAnimated(true);
        navigationController?.setNavigationBarHidden(false, animated:true)
    }
}
 | 
	apache-2.0 | 
	b868d44de52453c689049cef984cb2e2 | 33.680851 | 118 | 0.616769 | 5.258065 | false | false | false | false | 
| 
	blomma/stray | 
	stray/AnimationExtension.swift | 
	1 | 
	1507 | 
	import Foundation
import UIKit
extension UIButton {
    func animate() {
        let pathFrame: CGRect = CGRect(x: -bounds.midY, y: -bounds.midY, width: bounds.size.height, height: bounds.size.height)
        let path: UIBezierPath = UIBezierPath(roundedRect: pathFrame, cornerRadius:pathFrame.size.height / 2)
        let shapePosition: CGPoint = convert(center, from:superview)
        let circleShape: CAShapeLayer = CAShapeLayer()
        circleShape.path        = path.cgPath
        circleShape.position    = shapePosition
        circleShape.fillColor   = UIColor.clear.cgColor
        circleShape.opacity     = 0
        circleShape.strokeColor = titleLabel?.textColor.cgColor
        circleShape.lineWidth   = 2
        layer.addSublayer(circleShape)
        let scaleAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.scale")
        scaleAnimation.fromValue = NSValue(caTransform3D: CATransform3DIdentity)
        scaleAnimation.toValue   = NSValue(caTransform3D:CATransform3DMakeScale(3, 3, 1))
        let alphaAnimation: CABasicAnimation = CABasicAnimation(keyPath: "opacity")
        alphaAnimation.fromValue = 1
        alphaAnimation.toValue   = 0
        let animation: CAAnimationGroup = CAAnimationGroup()
        animation.animations     = [scaleAnimation, alphaAnimation]
        animation.duration       = 0.5
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
        circleShape.add(animation, forKey: nil)
    }
}
 | 
	gpl-3.0 | 
	eb6545006e229265e4d7eac47c80ce38 | 40.861111 | 127 | 0.698739 | 5.160959 | false | false | false | false | 
| 
	GianniCarlo/Audiobook-Player | 
	BookPlayer/Services/ActionParserService.swift | 
	1 | 
	4272 | 
	//
//  ActionParserService.swift
//  BookPlayer
//
//  Created by Gianni Carlo on 4/5/20.
//  Copyright © 2020 Tortuga Power. All rights reserved.
//
import BookPlayerKit
import Foundation
import Intents
import TelemetryClient
class ActionParserService {
    public class func process(_ url: URL) {
        guard let action = CommandParser.parse(url) else { return }
        self.handleAction(action)
    }
    public class func process(_ activity: NSUserActivity) {
        guard let action = CommandParser.parse(activity) else { return }
        self.handleAction(action)
    }
    public class func process(_ intent: INIntent) {
        guard let action = CommandParser.parse(intent) else { return }
        self.handleAction(action)
    }
    public class func handleAction(_ action: Action) {
        switch action.command {
        case .play:
            self.handlePlayAction(action)
        case .download:
            self.handleDownloadAction(action)
        case .sleep:
            self.handleSleepAction(action)
        case .refresh:
            WatchConnectivityService.sharedManager.sendApplicationContext()
        case .skipRewind:
            PlayerManager.shared.rewind()
        case .skipForward:
            PlayerManager.shared.forward()
        case .widget:
            self.handleWidgetAction(action)
        }
        // avoid registering actions not (necessarily) initiated by the user
        if action.command != .refresh {
            TelemetryManager.shared.send(TelemetrySignal.urlSchemeAction.rawValue, with: action.getParametersDictionary())
        }
    }
    private class func handleSleepAction(_ action: Action) {
        guard let value = action.getQueryValue(for: "seconds"),
            let seconds = Double(value) else {
            return
        }
        switch seconds {
        case -1:
            SleepTimer.shared.reset()
        case -2:
            SleepTimer.shared.sleep(in: .endChapter)
        default:
            SleepTimer.shared.sleep(in: seconds)
        }
    }
    private class func handlePlayAction(_ action: Action) {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        if let value = action.getQueryValue(for: "showPlayer"),
            let showPlayer = Bool(value),
            showPlayer {
            appDelegate.showPlayer()
        }
        if let value = action.getQueryValue(for: "autoplay"),
            let autoplay = Bool(value),
            !autoplay {
            return
        }
        guard let bookIdentifier = action.getQueryValue(for: "identifier") else {
            appDelegate.playLastBook()
            return
        }
        if let loadedBook = PlayerManager.shared.currentBook, loadedBook.identifier == bookIdentifier {
            PlayerManager.shared.play()
            return
        }
        guard let library = try? DataManager.getLibrary(),
              let book = DataManager.getBook(with: bookIdentifier, from: library) else { return }
        guard let libraryVC = appDelegate.getLibraryVC() else {
            return
        }
        libraryVC.setupPlayer(book: book)
        NotificationCenter.default.post(name: .bookChange,
                                        object: nil,
                                        userInfo: ["book": book])
    }
    private class func handleDownloadAction(_ action: Action) {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate,
            let libraryVC = appDelegate.getLibraryVC() else {
            return
        }
        libraryVC.navigationController?.dismiss(animated: true, completion: nil)
        if let url = action.getQueryValue(for: "url")?.replacingOccurrences(of: "\"", with: "") {
            libraryVC.downloadBook(from: url)
        }
    }
    private class func handleWidgetAction(_ action: Action) {
        if action.getQueryValue(for: "autoplay") != nil {
            let playAction = Action(command: .play, parameters: action.parameters)
            self.handleAction(playAction)
        }
        if action.getQueryValue(for: "seconds") != nil {
            let sleepAction = Action(command: .sleep, parameters: action.parameters)
            self.handleAction(sleepAction)
        }
    }
}
 | 
	gpl-3.0 | 
	e04ece99516952a84492ac3c32e53629 | 30.637037 | 122 | 0.605011 | 4.943287 | false | false | false | false | 
| 
	ABTSoftware/SciChartiOSTutorial | 
	v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/ManipulateSeries/AddPointsPerformance/AddPointsPerformanceChartView.swift | 
	1 | 
	2275 | 
	//******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales:   [email protected]
//
// AddPointsPerformanceChartView.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
class AddPointsPerformanceChartView: AddPointsPerformanceLayout {
    
    override func commonInit() {
        weak var wSelf = self
        self.append10K = { wSelf?.appendPoints(10000) }
        self.append100K = { wSelf?.appendPoints(100000) }
        self.append1Mln = { wSelf?.appendPoints(1000000) }
        self.clear = { wSelf?.clearSeries() }
    }
    
    override func initExample() {
        surface.xAxes.add(SCINumericAxis())
        surface.yAxes.add(SCINumericAxis())
        surface.chartModifiers = SCIChartModifierCollection(childModifiers: [SCIPinchZoomModifier(), SCIZoomPanModifier(), SCIZoomExtentsModifier()])
    }
    fileprivate func appendPoints(_ count: Int32) {
        let doubleSeries = RandomWalkGenerator().setBias(randf(0.0, 1.0) / 100).getRandomWalkSeries(count)
        let dataSeries = SCIXyDataSeries(xType: .double, yType: .double)
        dataSeries.appendRangeX(doubleSeries!.xValues, y: doubleSeries!.yValues, count: doubleSeries!.size)
        
        let rSeries = SCIFastLineRenderableSeries()
        rSeries.dataSeries = dataSeries
        rSeries.strokeStyle = SCISolidPenStyle(colorCode: UIColor.init(red: CGFloat(randf(0, 1)), green: CGFloat(randf(0, 1)), blue: CGFloat(randf(0, 1)), alpha: CGFloat(randf(0, 1))).colorARGBCode(), withThickness: 1)
        
        surface.renderableSeries.add(rSeries)
        surface.animateZoomExtents(0.5)
    }
    
    fileprivate func clearSeries() {
        surface.renderableSeries.clear()
    }
}
 | 
	mit | 
	3a0c4b536f586c412a3c44d5f4e3dbba | 45.367347 | 218 | 0.650528 | 4.608519 | false | false | false | false | 
| 
	wilkinsona/marching-tetrahedra | 
	MarchingTetrahedra/MarchingTetrahedraViewController.swift | 
	1 | 
	2162 | 
	import UIKit
import SceneKit
class MarchingTetrahedraViewController: UIViewController {
    @IBOutlet private var sceneView: SCNView!
    @IBOutlet private var polygonLabel: UILabel!
    override func viewDidLoad() {
        let surface = Surface(width: 20, height:20, depth:20, cubeSize: 0.5, sources: [
            PointSource(position: SCNVector3(x: -2.5, y: 2, z: 0), radius: 2),
            PointSource(position: SCNVector3(x: 2.5, y: 2, z: 0), radius: 2),
            PointSource(position: SCNVector3(x: -2.5, y: 2, z: 1), radius: -1),
            PointSource(position: SCNVector3(x: 2.5, y: 2, z: 1), radius: -1),
            PointSource(position: SCNVector3(x: 0, y: -1, z: 0), radius: 6),
            PointSource(position: SCNVector3(x: 0, y: -1, z: 3.25), radius: 1)
        ])
        let (geometry, triangleCount) = surface.createGeometry()
        let material = SCNMaterial()
        material.diffuse.contents = UIColor.yellowColor()
        material.specular.contents = UIColor.yellowColor()
        geometry.materials = [material]
        let surfaceNode = SCNNode(geometry: geometry)
        let scene = SCNScene()
        scene.rootNode.addChildNode(surfaceNode)
        let diffuseLight = SCNLight()
        diffuseLight.color = UIColor.lightGrayColor()
        diffuseLight.type = SCNLightTypeOmni
        let lightNode = SCNNode()
        lightNode.light = diffuseLight
        lightNode.position = SCNVector3(x: -30, y:30, z:30)
        scene.rootNode.addChildNode(lightNode)
        let ambientLight = SCNLight()
        ambientLight.type = SCNLightTypeAmbient
        let ambientLightNode = SCNNode()
        ambientLight.color = UIColor(white: 0.3, alpha: 1)
        ambientLightNode.light = ambientLight
        scene.rootNode.addChildNode(ambientLightNode)
        let camera = SCNCamera()
        camera.xFov = 45
        camera.yFov = 45
        let cameraNode = SCNNode()
        cameraNode.camera = camera
        cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)
        scene.rootNode.addChildNode(cameraNode)
        self.sceneView.scene = scene
        self.polygonLabel.text = "\(triangleCount) triangles"
    }
} | 
	mit | 
	6e673ccfc7afbf2cb32177c2cddd5283 | 36.947368 | 87 | 0.634598 | 4.198058 | false | false | false | false | 
| 
	PureSwift/Bluetooth | 
	Sources/BluetoothGAP/GAPLERole.swift | 
	1 | 
	2187 | 
	//
//  GAPLERole.swift
//  Bluetooth
//
//  Created by Carlos Duclos on 6/14/18.
//  Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// The LE Role data type defines the LE role capabilities of the device.
/// The LE Role data type size is 1 octet.
@frozen
public enum GAPLERole: UInt8, GAPData {
    
    public static var dataType: GAPDataType { return .lowEnergyRole }
    
    /// Only Peripheral Role supported.
    case onlyPeripheralRoleSupported = 0x00
    
    /// Only Central Role supported.
    case onlyCentralRoleSupported = 0x01
    
    /// Peripheral and Central Role supported, Peripheral Role preferred for connection establishment.
    case bothSupportedPeripheralPreferred = 0x02
    
    /// Peripheral and Central Role supported, Central Role preferred for connection establishment.
    case bothSupportedCentralPreferred = 0x03
}
public extension GAPLERole {
    
    init?(data: Data) {
        
        guard data.count == 1
            else { return nil }
        
        self.init(rawValue: data[0])
    }
    
    func append(to data: inout Data) {
        data += rawValue
    }
    
    var dataLength: Int {
        return 1
    }
}
// MARK: - Supporting Types
public extension GAPLERole {
    
    /// Bluetooth LE Role (e.g. Central or peripheral).
    enum Role: UInt8, BitMaskOption, CaseIterable { // not part of BT spec
        
        case central = 0b01
        case peripheral = 0b10
    }
}
public extension GAPLERole {
    
    var supported: BitMaskOptionSet<Role> {
        
        switch self {
        case .onlyPeripheralRoleSupported:
            return [.peripheral]
        case .onlyCentralRoleSupported:
            return [.central]
        case .bothSupportedPeripheralPreferred,
             .bothSupportedCentralPreferred:
            return [.central, .peripheral]
        }
    }
    
    var preferred: Role {
        
        switch self {
        case .onlyPeripheralRoleSupported,
             .bothSupportedPeripheralPreferred:
            return .peripheral
        case .onlyCentralRoleSupported,
             .bothSupportedCentralPreferred:
            return .central
        }
    }
}
 | 
	mit | 
	0599423d5821459c3f49ca6f9eaea5b5 | 23.840909 | 102 | 0.623971 | 4.79386 | false | false | false | false | 
| 
	stripe/stripe-ios | 
	StripeCardScan/StripeCardScan/Source/CardVerify/Api/STPAPIClient+CardImageVerification.swift | 
	1 | 
	3647 | 
	//
//  STPAPIClient+CardImageVerification.swift
//  StripeCardScan
//
//  Created by Jaime Park on 9/15/21.
//
import Foundation
@_spi(STP) import StripeCore
extension STPAPIClient {
    /// Request used in the beginning of the scan flow to gather CIV details and update the UI with last4 and issuer
    func fetchCardImageVerificationDetails(
        cardImageVerificationSecret: String,
        cardImageVerificationId: String
    ) -> Promise<CardImageVerificationDetailsResponse> {
        let parameters: [String: Any] = ["client_secret": cardImageVerificationSecret]
        let endpoint = APIEndpoints.fetchCardImageVerificationDetails(id: cardImageVerificationId)
        return self.post(resource: endpoint, parameters: parameters)
    }
    /// Request used to complete the verification flow by submitting the verification frames
    func submitVerificationFrames(
        cardImageVerificationId: String,
        verifyFrames: VerifyFrames
    ) -> Promise<EmptyResponse> {
        let endpoint = APIEndpoints.submitVerificationFrames(id: cardImageVerificationId)
        return self.post(resource: endpoint, object: verifyFrames)
    }
    func submitVerificationFrames(
        cardImageVerificationId: String,
        cardImageVerificationSecret: String,
        verificationFramesData: [VerificationFramesData]
    ) -> Promise<EmptyResponse> {
        do {
            /// TODO: Replace this with writing the JSON to a string instead of a data
            /// Encode the array of verification frames data into JSON
            let jsonEncoder = JSONEncoder()
            jsonEncoder.keyEncodingStrategy = .convertToSnakeCase
            let jsonVerificationFramesData = try jsonEncoder.encode(verificationFramesData)
            /// Turn the JSON data into a string
            let verificationFramesDataString =
                String(data: jsonVerificationFramesData, encoding: .utf8) ?? ""
            /// Create a `VerifyFrames` object
            let verifyFrames = VerifyFrames(
                clientSecret: cardImageVerificationSecret,
                verificationFramesData: verificationFramesDataString
            )
            return self.submitVerificationFrames(
                cardImageVerificationId: cardImageVerificationId,
                verifyFrames: verifyFrames
            )
        } catch (let error) {
            let promise = Promise<EmptyResponse>()
            promise.reject(with: error)
            return promise
        }
    }
    /// Request used to upload analytics of a card scanning session
    /// This will be a fire-and-forget request
    @discardableResult
    func uploadScanStats(
        cardImageVerificationId: String,
        cardImageVerificationSecret: String,
        scanAnalyticsPayload: ScanAnalyticsPayload
    ) -> Promise<EmptyResponse> {
        /// Create URL with endpoint
        let endpoint = APIEndpoints.uploadScanStats(id: cardImageVerificationId)
        /// Create scan stats payload with secret key
        let payload = ScanStatsPayload(
            clientSecret: cardImageVerificationSecret,
            payload: scanAnalyticsPayload
        )
        return self.post(resource: endpoint, object: payload)
    }
}
private struct APIEndpoints {
    static func fetchCardImageVerificationDetails(id: String) -> String {
        return "card_image_verifications/\(id)/initialize_client"
    }
    static func submitVerificationFrames(id: String) -> String {
        return "card_image_verifications/\(id)/verify_frames"
    }
    static func uploadScanStats(id: String) -> String {
        return "card_image_verifications/\(id)/scan_stats"
    }
}
 | 
	mit | 
	a7b6a1bfcf6c52a8dfe9d3be2ee0a932 | 37.389474 | 116 | 0.677543 | 5.636785 | false | false | false | false | 
| 
	dunkelstern/SwiftyRegex | 
	SwiftyRegex/regex.swift | 
	1 | 
	5528 | 
	//
//  regex.swift
//  SwiftyRegex
//
//  Created by Johannes Schriewer on 06/12/15.
//  Copyright © 2015 Johannes Schriewer. All rights reserved.
//
import pcre
/// internal extension to convert a string to an integer array
extension SequenceType where Generator.Element == CChar {
    static func fromString(string: String) -> [CChar] {
        var temp = [CChar]()
        temp.reserveCapacity(string.utf8.count)
        for c in string.utf8 {
            temp.append(CChar(c))
        }
        temp.append(CChar(0))
        return temp
    }
}
/// Regular expression matcher based on pcre
public class RegEx {
    private let compiled: COpaquePointer
    public let pattern: String
    public let namedCaptureGroups:[String:Int]
    public let numCaptureGroups:Int
    /// Errors that may be thrown by initializer
    public enum Error: ErrorType {
        /// Invalid pattern, contains error offset and error message from pcre engine
        case InvalidPattern(errorOffset: Int, errorMessage: String)
    }
    /// Initialize RegEx with pattern
    ///
    /// - parameter pattern: Regular Expression pattern
    /// - throws: RegEx.Error.InvalidPattern when pattern is invalid
    public init(pattern: String) throws {
        self.pattern = pattern
        var tmp = [CChar].fromString(pattern)
        var error = UnsafePointer<CChar>(bitPattern: 0)
        var errorOffset:Int32 = 0
        compiled = pcre_compile(&tmp, 0, &error, &errorOffset, nil)
        if compiled == nil {
            let errorMessage = String.fromCString(error)!
            self.namedCaptureGroups = [String:Int]()
            self.numCaptureGroups = 0
            throw RegEx.Error.InvalidPattern(errorOffset: Int(errorOffset), errorMessage: errorMessage)
        }
        // number of capture groups
        var patternCount: Int = 0
        pcre_fullinfo(self.compiled, nil, Int32(PCRE_INFO_CAPTURECOUNT), &patternCount)
        self.numCaptureGroups = patternCount
        // named capture groups
        var named = [String:Int]()
        pcre_fullinfo(self.compiled, nil, Int32(PCRE_INFO_NAMECOUNT), &patternCount)
        if patternCount > 0 {
            var name_table = UnsafeMutablePointer<UInt8>()
            var name_entry_size: Int = 0
            pcre_fullinfo(self.compiled, nil, Int32(PCRE_INFO_NAMETABLE), &name_table)
            pcre_fullinfo(self.compiled, nil, Int32(PCRE_INFO_NAMEENTRYSIZE), &name_entry_size)
            for i: Int in 0..<patternCount {
                let offset = name_entry_size * i
                let num = (Int(name_table.advancedBy(offset).memory) << 8) + Int(name_table.advancedBy(offset + 1).memory)
                // pattern name
                var patternName = [UInt8](count: name_entry_size + 1, repeatedValue: 0)
                for idx in (name_entry_size * i + 2)..<(name_entry_size * (i + 1)) {
                    patternName[idx - (name_entry_size * i + 2)] = name_table[idx]
                }
                guard let patternNameString = String.fromCString(UnsafePointer<CChar>(patternName)) else {
                    continue
                }
                named[patternNameString] = num
            }
        }
        self.namedCaptureGroups = named
    }
    deinit {
        pcre_free(UnsafeMutablePointer<Void>(self.compiled))
    }
    /// Match a string against the pattern
    ///
    /// - parameter string: the string to match
    /// - returns: tuple with matches, named parameters are returned as numbered matches too
    public func match(string: String) -> (numberedParams:[String], namedParams:[String:String]) {
	    var outVector = [Int32](count: 30, repeatedValue: 0)
        let subject = [CChar].fromString(string)
        // pcre_exec does not like zero terminated strings (???)
        let resultCount = pcre_exec(self.compiled, nil, subject, Int32(subject.count-1), 0, 0, &outVector, 30)
        if resultCount < 0 {
            // no match or error
            return ([], [String:String]())
        }
	    if resultCount == 0 {
		    // ovector too small
            // TODO: Avoid this
            return ([], [String:String]())
	    }
        // get numbered results
        var params = [String]()
        for i: Int in 0..<Int(resultCount) {
            let startOffset = outVector[i * 2]
            let length = outVector[i * 2 + 1]
            if length == 0 {
                params.append("")
                continue
            }
            var subString = [CChar](count: Int(length) + 1, repeatedValue: 0)
            for idx in startOffset..<length {
                subString[Int(idx-startOffset)] = subject[Int(idx)]
            }
            if let match = String.fromCString(UnsafePointer<CChar>(subString)) {
                params.append(match)
            }
        }
        // named results
        var named = [String:String]()
        for (grp, num) in self.namedCaptureGroups {
            let startOffset = outVector[2 * num]
            let length = outVector[2 * num + 1]
            if length == 0 {
                named[grp] = ""
                continue
            }
            var subString = [CChar](count: Int(length) + 1, repeatedValue: 0)
            for idx in startOffset..<length {
                subString[Int(idx-startOffset)] = subject[Int(idx)]
            }
            if let match = String.fromCString(UnsafePointer<CChar>(subString)) {
                named[grp] = match
            }
        }
        return (numberedParams: params, namedParams: named)
    }
}
 | 
	bsd-3-clause | 
	ef7500b38d16adeaf99e5fe3edec9052 | 33.117284 | 122 | 0.578071 | 4.457258 | false | false | false | false | 
| 
	6ag/BaoKanIOS | 
	BaoKanIOS/Classes/Module/News/Model/JFArticleDetailModel.swift | 
	1 | 
	5473 | 
	//
//  JFArticleDetailModel.swift
//  BaoKanIOS
//
//  Created by jianfeng on 16/2/19.
//  Copyright © 2016年 六阿哥. All rights reserved.
//
import UIKit
/// 资讯正文模型 - 图库通用
class JFArticleDetailModel: NSObject {
    
    /// 顶贴数
    var top: String?
    
    /// 踩帖数
    var down: String?
    
    /// 文章标题
    var title: String?
    
    /// 发布时间戳
    var newstime: String?
    
    /// 文章内容
    var newstext: String?
    
    /// 文章url
    var titleurl: String?
    
    /// 文章id
    var id: String?
    
    /// 当前子分类id
    var classid: String?
    
    /// 评论数量
    var plnum: String?
    
    /// 是否收藏 1收藏  0未收藏
    var havefava: String?
    
    /// 文章简介
    var smalltext: String?
    
    /// 标题图片
    var titlepic: String?
    
    /// 信息来源 - 如果没有则返回空字符串,所以可以直接强拆
    var befrom: String?
    
    /// 是否赞过
    var isStar = false
    
    // 图片详情
    var morepics: [JFPhotoDetailModel]?
    
    /// 相关链接
    var otherLinks: [JFOtherLinkModel]?
    
    /// 所有正文配图
    var allphoto: [JFInsetPhotoModel]?
    
    /**
     字典转模型构造方法
     */
    init(dict: [String : AnyObject]) {
        super.init()
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {}
    
    
    /**
     KVC赋值每个属性的时候都会来,在这里手动转子模型
     
     - parameter value: 值
     - parameter key:   键
     */
    override func setValue(_ value: Any?, forKey key: String) {
        if key == "morepic" {
            if let array = value as? [[String: AnyObject]] {
                var morepicModels = [JFPhotoDetailModel]()
                for dict in array {
                    let morepicModel = JFPhotoDetailModel(dict: dict)
                    morepicModels.append(morepicModel)
                }
                morepics = morepicModels
            }
            return
        } else if key == "otherLink" {
            if let array = value as? [[String: AnyObject]] {
                var otherModels = [JFOtherLinkModel]()
                for dict in array {
                    let otherModel = JFOtherLinkModel(dict: dict)
                    otherModels.append(otherModel)
                }
                otherLinks = otherModels
            }
            return
        } else if key == "allphoto" {
            if let array = value as? [[String: AnyObject]] {
                var allphotoModels = [JFInsetPhotoModel]()
                for dict in array {
                    let insetPhotoModel = JFInsetPhotoModel(dict: dict)
                    if let pixel = dict["pixel"] as? [String : CGFloat] {
                        insetPhotoModel.widthPixel = pixel["width"] ?? 0
                        insetPhotoModel.heightPixel = pixel["height"] ?? 0
                    }
                    allphotoModels.append(insetPhotoModel)
                }
                allphoto = allphotoModels
            }
            return
        }
        return super.setValue(value, forKey: key)
    }
    
    /**
     加载资讯数据
     
     - parameter classid:   资讯分类id
     - parameter pageIndex: 加载分页
     - parameter type:      1为资讯列表 2为资讯幻灯片
     - parameter finished:  数据回调
     */
    class func loadNewsDetail(_ classid: Int, id: Int, finished: @escaping (_ articleDetailModel: JFArticleDetailModel?, _ error: NSError?) -> ()) {
        
        JFNewsDALManager.shareManager.loadNewsDetail(classid, id: id) { (result, error) in
            
            // 请求失败
            if error != nil || result == nil {
                finished(nil, error)
                return
            }
            
            // 正文数据
            let dict = result!.dictionaryObject
            finished(JFArticleDetailModel(dict: dict! as [String : AnyObject]), nil)
        }
    }
    
}
/// 正文插图模型
class JFInsetPhotoModel: NSObject {
    
    // 图片占位字符
    var ref: String?
    
    // 图片描述
    var caption: String?
    
    // 图片url
    var url: String?
    
    // 宽度
    var widthPixel: CGFloat = 0
    
    // 高度
    var heightPixel: CGFloat = 0
    
    init(dict: [String : AnyObject]) {
        super.init()
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {}
    
}
/// 相关链接模型
class JFOtherLinkModel: NSObject {
    
    var classid: String?
    
    var id: String?
    
    var titlepic: String?
    
    var onclick: String?
    
    var title: String?
    
    var classname: String?
    
    /// 缓存行高
    var rowHeight: CGFloat = 0
    
    init(dict: [String : AnyObject]) {
        super.init()
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
/// 图库详情模型
class JFPhotoDetailModel: NSObject {
    
    /// 图片标题
    var title: String?
    
    /// 图片描述
    var caption: String?
    
    /// 图片url
    var bigpic: String?
    
    /**
     字典转模型构造方法
     */
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {}
    
}
 | 
	apache-2.0 | 
	ddae68307c74f573b27f41b852f14809 | 21.558559 | 148 | 0.514577 | 4.373799 | false | false | false | false | 
| 
	mdiep/Tentacle | 
	Sources/Tentacle/Color.swift | 
	1 | 
	747 | 
	//
//  Color.swift
//  Tentacle
//
//  Created by Romain Pouclet on 2016-07-19.
//  Copyright © 2016 Matt Diephouse. All rights reserved.
//
import Foundation
#if os(iOS) || os(tvOS)
    import UIKit
    public typealias Color = UIColor
#else
    import Cocoa
    public typealias Color = NSColor
#endif
extension Color {
    internal convenience init(hex: String) {
        precondition(hex.count == 6)
        let scanner = Scanner(string: hex)
        var rgb: UInt32 = 0
        scanner.scanHexInt32(&rgb)
        let r = CGFloat((rgb & 0xff0000) >> 16) / 255.0
        let g = CGFloat((rgb & 0x00ff00) >>  8) / 255.0
        let b = CGFloat((rgb & 0x0000ff) >>  0) / 255.0
        self.init(red: r, green: g, blue: b, alpha: 1)
    }
}
 | 
	mit | 
	130e82b0f73481e17f23a82ffcf9960e | 22.3125 | 57 | 0.597855 | 3.36036 | false | false | false | false | 
| 
	eurofurence/ef-app_ios | 
	Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/News/Component/CompositionalNewsComponentDefaultWidgetsBuilder.swift | 
	1 | 
	4056 | 
	import EurofurenceApplicationSession
import EurofurenceModel
struct CompositionalNewsComponentDefaultWidgetsBuilder {
    
    private let repositories: Repositories
    private let services: Services
    private let builder: CompositionalNewsComponentBuilder
    
    init(repositories: Repositories, services: Services) {
        self.repositories = repositories
        self.services = services
        self.builder = CompositionalNewsComponentBuilder(refreshService: services.refresh)
    }
    
    func buildNewsComponent() -> any NewsComponentFactory {
        addPersonalisedWidget()
        addCountdownWidget()
        addAnnouncementsWidget()
        addUpcomingEventsWidget()
        addRunningEventsWidget()
        addTodaysFavouriteEventsWidget()
        
        return builder.build()
    }
    
    private func addPersonalisedWidget() {
        let dataSource = YourEurofurenceDataSourceServiceAdapter(
            authenticationService: services.authentication,
            privateMessagesService: services.privateMessages
        )
        
        let viewModelFactory = YourEurofurenceWidgetViewModelFactory(dataSource: dataSource)
        let widget = MVVMWidget(viewModelFactory: viewModelFactory, viewFactory: YourEurofurenceWidgetViewFactory())
        _ = builder.with(widget)
    }
    
    private func addCountdownWidget() {
        let dataSource = ConventionCountdownDataSourceServiceAdapter(countdownService: services.conventionCountdown)
        let viewModelFactory = ConventionCountdownViewModelFactory(dataSource: dataSource)
        let widget = MVVMWidget(viewModelFactory: viewModelFactory, viewFactory: ConventionCountdownViewFactory())
        _ = builder.with(widget)
    }
    
    private func addAnnouncementsWidget() {
        struct LimitToThreeAnnouncements: NewsAnnouncementsConfiguration {
            var maxDisplayedAnnouncements: Int = 3
        }
        
        let dataSource = NewsAnnouncementsDataSourceRepositoryAdapter(repository: repositories.announcements)
        let viewModelFactory = NewsAnnouncementsWidgetViewModelFactory(
            dataSource: dataSource,
            configuration: LimitToThreeAnnouncements()
        )
        
        let widget = MVVMWidget(viewModelFactory: viewModelFactory, viewFactory: AnnouncementsNewsWidgetViewFactory())
        _ = builder.with(widget)
    }
    
    private func addUpcomingEventsWidget() {
        let specification = UpcomingEventSpecification(configuration: RemotelyConfiguredUpcomingEventsConfiguration())
        let upcomingEventsDataSource = makeEventsDataSource(specification)
        
        _ = builder.with(makeEventsWidget(dataSource: upcomingEventsDataSource, title: .upcomingEvents))
    }
    
    private func addRunningEventsWidget() {
        let runningEventsDataSource = makeEventsDataSource(RunningEventSpecification())
        _ = builder.with(makeEventsWidget(dataSource: runningEventsDataSource, title: .runningEvents))
    }
    
    private func addTodaysFavouriteEventsWidget() {
        let todaysFavouritesSpecification = TodaysEventsSpecification() && IsFavouriteEventSpecification()
        let todaysFavouritesDataSource = makeEventsDataSource(todaysFavouritesSpecification)
        
        _ = builder.with(makeEventsWidget(dataSource: todaysFavouritesDataSource, title: .todaysFavouriteEvents))
    }
    
    private func makeEventsDataSource<S: Specification>(
        _ specification: S
    ) -> some EventsWidgetDataSource where S.Element == Event {
        FilteredScheduleWidgetDataSource(
            repository: repositories.events,
            specification: specification
        )
    }
    
    private func makeEventsWidget<DataSource>(
        dataSource: DataSource,
        title: String
    ) -> some NewsWidget where DataSource: EventsWidgetDataSource {
        let viewModelFactory = EventsWidgetViewModelFactory(dataSource: dataSource, description: title)
        return MVVMWidget(viewModelFactory: viewModelFactory, viewFactory: TableViewNewsWidgetViewFactory())
    }
    
}
 | 
	mit | 
	49e91ba0e674eab7db7d32882c240c25 | 41.25 | 118 | 0.722633 | 6.317757 | false | true | false | false | 
| 
	sauravexodus/RxFacebook | 
	Carthage/Checkouts/facebook-ios-sdk/samples/HelloTV/HelloTV/FirstViewController.swift | 
	1 | 
	4160 | 
	// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
import FBSDKShareKit
import FBSDKTVOSKit
class FirstViewController: UIViewController {
  @IBOutlet fileprivate weak var imageView: UIImageView?
  @IBOutlet fileprivate weak var loginButton: FBSDKDeviceLoginButton?
  @IBOutlet fileprivate weak var shareButton: FBSDKDeviceShareButton?
  fileprivate var blankImage: UIImage?
  override func viewDidLoad() {
    super.viewDidLoad()
    loginButton?.delegate = self
    blankImage = imageView?.image
    // Subscribe to FB session changes (in case they logged in or out in the second tab)
    NotificationCenter.default.addObserver(
      forName: .FBSDKAccessTokenDidChange,
      object: nil,
      queue: .main) { (_) -> Void in
        self.updateContent()
    }
    // If the user is already logged in.
    if FBSDKAccessToken.current() != nil {
      updateContent()
    }
    let linkContent = FBSDKShareLinkContent()
    linkContent.contentURL = URL(string: "https://developers.facebook.com/docs/tvos")
    linkContent.contentDescription = "Let's build a tvOS app with Facebook!"
    shareButton?.shareContent = linkContent
  }
  fileprivate func flipImageViewToImage(_ image: UIImage?) {
    guard let imageView = imageView else { return }
    UIView.transition(with: imageView,
                      duration: 1,
                      options:.transitionCrossDissolve,
                      animations: { () -> Void in
                        self.imageView?.image = image
      }, completion: nil)
  }
  fileprivate func updateContent() {
    guard let imageView = imageView else {
      return
    }
    guard FBSDKAccessToken.current() != nil else {
      imageView.image = blankImage
      return
    }
    // Download the user's profile image. Usually Facebook Graph API
    // should be accessed via `FBSDKGraphRequest` except for binary data (like the image).
    let urlString = String(
      format: "https://graph.facebook.com/v2.5/me/picture?type=square&width=%d&height=%d&access_token=%@",
      Int(imageView.bounds.size.width),
      Int(imageView.bounds.size.height),
      FBSDKAccessToken.current().tokenString)
    let url = URL(string: urlString)
    let userImage = UIImage(data: try! Data(contentsOf: url!))
    flipImageViewToImage(userImage!)
  }
}
extension FirstViewController: FBSDKDeviceLoginButtonDelegate {
  func deviceLoginButtonDidCancel(_ button: FBSDKDeviceLoginButton) {
    print("Login cancelled")
  }
  func deviceLoginButtonDidLog(in button: FBSDKDeviceLoginButton) {
    print("Login complete")
    updateContent()
  }
  func deviceLoginButtonDidLogOut(_ button: FBSDKDeviceLoginButton) {
    print("Logout complete")
    flipImageViewToImage(blankImage)
  }
  public func deviceLoginButtonDidFail(_ button: FBSDKDeviceLoginButton, error: Error) {
    print("Login error : ", error)
  }
}
extension FirstViewController: FBSDKDeviceShareViewControllerDelegate {
  public func deviceShareViewControllerDidComplete(_ viewController: FBSDKDeviceShareViewController, error: Error?) {
    print("Device share finished with error?", error)
  }
}
 | 
	mit | 
	b57d679600ad2342c55cbd6d0aecba56 | 35.491228 | 117 | 0.719712 | 4.993998 | false | false | false | false | 
| 
	mcomella/prox | 
	Prox/Prox/Utilities/OpenInHelper.swift | 
	1 | 
	6014 | 
	/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import MapKit
private enum Scheme: String {
    case yelp = "www.yelp.com"
    case tripAdvisor = "www.tripadvisor.co.uk"
    case wikipedia = "en.wikipedia.org"
}
struct OpenInHelper {
    static let gmapsAppSchemeString: String = "comgooglemaps://"
    static let gmapsWebSchemeString: String = "https://www.google.com/maps"
    static let appleMapsSchemeString: String = "http://maps.apple.com/"
    static let yelpAppURLSchemeString: String = "yelp://"
    static let tripAdvisorAppURLSchemeString: String = "tripadvisor://"
    static let wikipediaAppURLSchemeString: String = "wikipedia://"
    static func open(url: URL) -> Bool {
        guard let host = url.host,
            let scheme = Scheme(rawValue: host),
            let schemeURL = schemeURL(forScheme: scheme),
            UIApplication.shared.canOpenURL(schemeURL),
            UIApplication.shared.openURL(url) else {
            return openURLInBrowser(url: url)
        }
        return true
    }
    fileprivate static func schemeURL(forScheme scheme: Scheme) -> URL? {
        switch scheme {
        case .yelp:
            return URL(string: yelpAppURLSchemeString)
        case .tripAdvisor:
            return URL(string: tripAdvisorAppURLSchemeString)
        case .wikipedia:
            return URL(string: wikipediaAppURLSchemeString)
        }
    }
    //MARK: Open URL in Browser
    fileprivate static func openURLInBrowser(url: URL) -> Bool {
        // check to see if Firefox is available
        // Open in Firefox or Safari
        let controller = OpenInFirefoxControllerSwift()
        if !controller.openInFirefox(url) {
            return UIApplication.shared.openURL(url)
        }
        return true
    }
    //MARK: Open route in maps
    static func openRoute(fromLocation: CLLocationCoordinate2D, toPlace place: Place, by transportType: MKDirectionsTransportType) -> Bool {
        // try and open in Google Maps app
        if let schemeURL = URL(string: gmapsAppSchemeString),
            UIApplication.shared.canOpenURL(schemeURL),
            let gmapsRoutingRequestURL = gmapsAppURLForRoute(fromLocation: fromLocation, toLocation: place.latLong, by: transportType),
            UIApplication.shared.openURL(gmapsRoutingRequestURL) {
            return true
        // open in Apple maps app
        } else if  let schemeURL = URL(string: appleMapsSchemeString),
            UIApplication.shared.canOpenURL(schemeURL),
            let address = place.address,
            let appleMapsRoutingRequest = appleMapsURLForRoute(fromLocation: fromLocation, toAddress: address, by: transportType),
            UIApplication.shared.openURL(appleMapsRoutingRequest) {
            return true
        // open google maps in a browser
        } else if let gmapsRoutingRequestURL = gmapsWebURLForRoute(fromLocation: fromLocation, toLocation: place.latLong, by: transportType),
            openURLInBrowser(url: gmapsRoutingRequestURL) {
            return true
        }
        print("Unable to open directions")
        return false
    }
    fileprivate static func gmapsAppURLForRoute(fromLocation: CLLocationCoordinate2D, toLocation: CLLocationCoordinate2D, by transportType: MKDirectionsTransportType) -> URL? {
        guard let directionsMode = transportType.directionsMode() else { return nil }
        let queryParams = ["saddr=\(fromLocation.latitude),\(fromLocation.longitude)", "daddr=\(toLocation.latitude),\(toLocation.longitude)", "directionsMode=\(directionsMode)"]
        let gmapsRoutingRequestURLString = gmapsAppSchemeString + "?" + queryParams.joined(separator: "&")
        return URL(string: gmapsRoutingRequestURLString)
    }
    fileprivate static func gmapsWebURLForRoute(fromLocation: CLLocationCoordinate2D, toLocation: CLLocationCoordinate2D, by transportType: MKDirectionsTransportType) -> URL? {
        guard let dirFlg = transportType.dirFlg() else {
            return nil
        }
        let queryParams = ["saddr=\(fromLocation.latitude),\(fromLocation.longitude)", "daddr=\(toLocation.latitude),\(toLocation.longitude)", "dirflg=\(dirFlg)"]
        let gmapsRoutingRequestURLString = gmapsWebSchemeString + "?" + queryParams.joined(separator: "&")
        return URL(string: gmapsRoutingRequestURLString)
    }
    fileprivate static func appleMapsURLForRoute(fromLocation: CLLocationCoordinate2D, toAddress: String, by transportType: MKDirectionsTransportType) -> URL? {
        guard let dirFlg = transportType.dirFlg() else {
            return nil
        }
        let queryParams = ["daddr=\(encodeByAddingPercentEscapes(toAddress))", "dirflg=\(dirFlg)"]
        let appleMapsRoutingRequestURLString = appleMapsSchemeString + "?" + queryParams.joined(separator: "&")
        return URL(string: appleMapsRoutingRequestURLString)
    }
    //MARK: Helper functions
    fileprivate static func encodeByAddingPercentEscapes(_ input: String) -> String {
        return NSString(string: input).addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[]"))!
    }
}
fileprivate extension MKDirectionsTransportType {
    func dirFlg() -> String? {
        switch self {
        case MKDirectionsTransportType.automobile:
            return "d"
        case MKDirectionsTransportType.transit:
            return "r"
        case MKDirectionsTransportType.walking:
            return "w"
        default:
            return nil
        }
    }
    func directionsMode() -> String? {
        switch self {
        case MKDirectionsTransportType.automobile:
            return "driving"
        case MKDirectionsTransportType.transit:
            return "transit"
        case MKDirectionsTransportType.walking:
            return "walking"
        default:
            return nil
        }
    }
}
 | 
	mpl-2.0 | 
	d9b06e3e6dc59e5ccd35246477b0186a | 39.362416 | 178 | 0.671766 | 5.256993 | false | false | false | false | 
| 
	Ezimetzhan/youtube-parser | 
	youtube-parser/Youtube.swift | 
	1 | 
	6048 | 
	//
//  Youtube.swift
//  youtube-parser
//
//  Created by Toygar Dündaralp on 7/5/15.
//  Copyright (c) 2015 Toygar Dündaralp. All rights reserved.
//
import UIKit
public extension NSURL {
  /**
  Parses a query string of an NSURL
  @return key value dictionary with each parameter as an array
  */
  func dictionaryForQueryString() -> [String: AnyObject]? {
    return self.query?.dictionaryFromQueryStringComponents()
  }
}
public extension NSString {
  /**
  Convenient method for decoding a html encoded string
  */
  func stringByDecodingURLFormat() -> String {
    var result = self.stringByReplacingOccurrencesOfString("+", withString:" ")
    return result.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
  }
  /**
  Parses a query string
  @return key value dictionary with each parameter as an array
  */
  func dictionaryFromQueryStringComponents() -> [String: AnyObject] {
    var parameters = [String: AnyObject]()
    for keyValue in componentsSeparatedByString("&") {
      let keyValueArray = keyValue.componentsSeparatedByString("=")
      if keyValueArray.count < 2 {
        continue
      }
      let key = keyValueArray[0].stringByDecodingURLFormat()
      let value = keyValueArray[1].stringByDecodingURLFormat()
      parameters[key] = value
    }
    return parameters
  }
}
public class Youtube: NSObject {
  static let infoURL = "http://www.youtube.com/get_video_info?video_id="
  static var userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"
  /**
  Method for retrieving the youtube ID from a youtube URL
  @param youtubeURL the the complete youtube video url, either youtu.be or youtube.com
  @return string with desired youtube id
  */
  public static func youtubeIDFromYoutubeURL(youtubeURL: NSURL) -> String? {
    if let
      youtubeHost = youtubeURL.host,
      youtubePathComponents = youtubeURL.pathComponents as? [String] {
        let youtubeAbsoluteString = youtubeURL.absoluteString
        if youtubeHost == "youtu.be" {
          return youtubePathComponents[1]
        } else if youtubeAbsoluteString?.rangeOfString("www.youtube.com/embed") != nil {
          return youtubePathComponents[2]
        } else if youtubeHost == "youtube.googleapis.com" ||
          youtubeURL.pathComponents!.first!.isEqualToString("www.youtube.com") {
            return youtubePathComponents[2]
        } else if let
          queryString = youtubeURL.dictionaryForQueryString(),
          searchParam = queryString["v"] as? String {
            return searchParam
        }
    }
    return nil
  }
  /**
  Method for retreiving a iOS supported video link
  @param youtubeURL the the complete youtube video url
  @return dictionary with the available formats for the selected video
  
  */
  public static func h264videosWithYoutubeID(youtubeID: String) -> [String: AnyObject]? {
    if count(youtubeID) > 0 {
      let urlString = String(format: "%@%@", infoURL, youtubeID) as String
      let url = NSURL(string: urlString)!
      let request = NSMutableURLRequest(URL: url)
      request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
      request.HTTPMethod = "GET"
      var response: NSURLResponse?
      var error: NSError?
      if let
        responseData = NSURLConnection.sendSynchronousRequest(
          request,
          returningResponse: &response,
          error: &error),
        responseString = NSString(
          data: responseData,
          encoding: NSUTF8StringEncoding
        ) {
          let parts = responseString.dictionaryFromQueryStringComponents()
          if parts.count > 0 {
            var videoTitle: String = ""
            var streamImage: String = ""
            if let title = parts["title"] as? String {
              videoTitle = title
            }
            if let image = parts["iurl"] as? String {
              streamImage = image
            }
            if let fmtStreamMap = parts["url_encoded_fmt_stream_map"] as? String {
              // Live Stream
              if let isLivePlayback: AnyObject = parts["live_playback"]{
                if let hlsvp = parts["hlsvp"] as? String {
                  return [
                    "url": "\(hlsvp)",
                    "title": "\(videoTitle)",
                    "image": "\(streamImage)",
                    "isStream": true
                  ]
                }
              } else {
                var videoDictionary = []
                let fmtStreamMapArray = fmtStreamMap.componentsSeparatedByString(",")
                for videoEncodedString in fmtStreamMapArray {
                  var videoComponents = videoEncodedString.dictionaryFromQueryStringComponents()
                  videoComponents["title"] = videoTitle
                  videoComponents["isStream"] = false
                  return videoComponents as [String: AnyObject]
                }
              }
            }
          }
      }
    }
    return nil
  }
  /**
  Block based method for retreiving a iOS supported video link
  @param youtubeURL the the complete youtube video url
  @param completeBlock the block which is called on completion
  */
  public static func h264videosWithYoutubeURL(youtubeURL: NSURL,completion: ((
    videoInfo: [String: AnyObject]?, error: NSError?) -> Void)?) {
      let youtubeID = youtubeIDFromYoutubeURL(youtubeURL)
      let priority = DISPATCH_QUEUE_PRIORITY_BACKGROUND
      dispatch_async(dispatch_get_global_queue(priority, 0)) {
        if let youtubeID = self.youtubeIDFromYoutubeURL(youtubeURL), videoInformation = self.h264videosWithYoutubeID(youtubeID) {
          dispatch_async(dispatch_get_main_queue()) {
            completion?(videoInfo: videoInformation, error: nil)
          }
        }else{
          dispatch_async(dispatch_get_main_queue()) {
            completion?(videoInfo: nil, error: NSError(domain: "com.player.youtube.backgroundqueue", code: 1001, userInfo: ["error": "Invalid YouTube URL"]))
          }
        }
      }
    }
  }
 | 
	mit | 
	efd1eb43fa0a800898a5faed321c03c2 | 35.642424 | 157 | 0.633146 | 5.089226 | false | false | false | false | 
| 
	Wevah/Punycode-Cocoa | 
	icumap2code/main.swift | 
	1 | 
	1991 | 
	//
//  main.swift
//  icumap2code
//
//  Created by Nate Weaver on 2020-03-27.
//
import Foundation
import ArgumentParser
struct ICUMap2Code: ParsableCommand {
	static let configuration = CommandConfiguration(commandName: "icumap2code", abstract: "Convert UTS#46 and joiner type map files to a compact binary format.", version: "1.0 (v10)")
	@Option(name: [.customLong("compress"), .short], help: ArgumentHelp("Output compression mode.", discussion: "Default is uncompressed. Supported values are 'lzfse', 'lz4', 'lzma', and 'zlib'.", valueName: "mode"))
	var compression: UTS46.CompressionAlgorithm = .none
	@Flag(name: .shortAndLong, help: "Verbose output (on STDERR).")
	var verbose: Bool = false
	/// ucs46.txt
	@Option(name: [.customLong("uts46"), .short], help: ArgumentHelp("uts46.txt input file.", valueName: "file"))
	var uts46File: String?
	/// DerivedJoiningType.txt
	@Option(name: [.customLong("joiners"), .short], help: ArgumentHelp("Joiner type input file.", valueName: "file"))
	var joinersFile: String?
	@Option(name: [.customLong("output"), .short], help: ArgumentHelp("The output file.", discussion: "If no file is specified, outputs to stdout.", valueName: "file"))
	var outputFile: String?
	func run() throws {
		if let path = uts46File {
			try UTS46.readCharacterMap(fromTextFile: URL(fileURLWithPath: path))
		}
		if let path = joinersFile {
			try UTS46.readJoinerTypes(fromTextFile: URL(fileURLWithPath: path))
		}
		if let outputFile = outputFile {
			let url = URL.init(fileURLWithPath: outputFile)
			try UTS46.write(to: url, compression: compression)
		} else {
			try UTS46.write(to: FileHandle.standardOutput, compression: compression)
		}
	}
}
extension UTS46.CompressionAlgorithm: ExpressibleByArgument {
	public init?(argument: String) {
		switch argument {
			case "lz4":
				self = .lz4
			case "zlib":
				self = .zlib
			case "lzfse":
				self = .lzfse
			case "lzma":
				self = .lzma
			default:
				return nil
		}
	}
}
ICUMap2Code.main()
 | 
	bsd-3-clause | 
	c0328cc9b72804c66710303478fcabf8 | 29.166667 | 213 | 0.700653 | 3.415094 | false | false | false | false | 
| 
	barabashd/WeatherApp | 
	WeatherApp/WeatherViewController+ChangeMapHandler.swift | 
	1 | 
	7352 | 
	//
//  WeatherViewController+ChangeMapHandler.swift
//  WeatherApp
//
//  Created by Dmytro Barabash on 2/16/18.
//  Copyright © 2018 Dmytro. All rights reserved.
//
import MapKit
extension WeatherViewController {
    
    /// Change map type
    ///
    /// - Parameter index: segment index
    func switchMap(to index: Int) {
        if index == 3 {
            if googleTile == nil || googleTile.urlTemplate != googleMapUrl {
                if googleTile != nil {
                    mapView.remove(googleTile)
                }
                googleTile = MKTileOverlay(urlTemplate: googleMapUrl)
                googleTile.canReplaceMapContent = true
                mapView.insert(googleTile, at: 0)
            }
        } else if googleTile != nil && (index == 0 || index == 1 || index == 2) {
            mapView.remove(googleTile)
            googleTile = nil
        }
        
        switch index {
        case 0:
            mapView.mapType = MKMapType.standard
        case 1:
            mapView.mapType = MKMapType.satellite
        case 2:
            mapView.mapType = MKMapType.hybrid
        default:
            break
        }
    }
    
    
    /// Switch tile on map
    ///
    /// - Parameter sender: recognized button
    func switchTile(_ sender: UIButton) {
        
        var indicatior = false
        var site = ""
        
        if selectedBtn == nil {
            selectedBtn = sender
            selectedLbl = lblTemperature
            selectedTintColor = selectedBtn.tintColor
            selectedTextColor = selectedLbl.textColor
        }
        
        switch sender {
        case btnTemperature:
            site = Strings.URL.temperature
            handleButton(button: btnTemperature, label: lblTemperature, indicatior: &indicatior, type: .temperature)
        case btnPrecipitation:
            site = Strings.URL.precipitation
            handleButton(button: btnPrecipitation, label: lblPrecipitation, indicatior: &indicatior, type: .precipitation)
        case btnPressure:
            site = Strings.URL.pressure
            handleButton(button: btnPressure, label: lblPressure, indicatior: &indicatior, type: .pressure)
        case btnWind:
            site = Strings.URL.wind
            handleButton(button: btnWind, label: lblWind, indicatior: &indicatior, type: .wind)
        case btnClouds:
            site = Strings.URL.clouds
            handleButton(button: btnClouds, label: lblClouds, indicatior: &indicatior, type: .clouds)
        default:
            break
        }
        
        if tile != nil {
            mapView.remove(tile)
        }
        
        if indicatior {
            site.append(Strings.URL.tail)
            tile = MKTileOverlay(urlTemplate: site)
            mapView.add(tile)
            UIView.animate(withDuration: Constants.animationDuration, animations: {
                self.gradientViewOne.alpha = Constants.Gradient.visible
                self.gradientViewOne.transform = CGAffineTransform(translationX: Constants.Gradient.translationX,
                                                                   y: Constants.Gradient.translationY)
                if sender == self.btnPrecipitation {
                    self.gradientViewTwo.alpha = Constants.Gradient.visible
                    self.gradientViewTwo.transform = CGAffineTransform(translationX: Constants.Gradient.translationX,
                                                                       y: Constants.Gradient.translationY)
                }
                if self.selectedBtn == self.btnPrecipitation && sender != self.selectedBtn {
                    self.gradientViewTwo.alpha = Constants.Gradient.hidden
                    self.gradientViewTwo.transform = CGAffineTransform(translationX: -Constants.Gradient.translationX,
                                                                       y: -Constants.Gradient.translationY)
                }
            })
        } else {
            UIView.animate(withDuration: Constants.animationDuration, animations: {
                self.gradientViewOne.alpha = Constants.Gradient.hidden
                self.gradientViewOne.transform = CGAffineTransform(translationX: -Constants.Gradient.translationX,
                                                                   y: -Constants.Gradient.translationY)
                if sender == self.btnPrecipitation {
                    self.gradientViewTwo.alpha = Constants.Gradient.hidden
                    self.gradientViewTwo.transform = CGAffineTransform(translationX: -Constants.Gradient.translationX,
                                                                       y: -Constants.Gradient.translationX)
                }
            })
        }
        selectedBtn = sender
    }
    
    
    /// Handle tile button pressed
    ///
    /// - Parameters:
    ///   - button: pressed button
    ///   - label: pressed label
    ///   - indicatior: simple indicator for gradient
    ///   - type: type of tile
    func handleButton(button: UIButton, label: UILabel, indicatior: inout Bool, type: TileType) {
        if label.textColor == .red {
            label.textColor = selectedTextColor
            button.tintColor = selectedTintColor
            indicatior = false
        } else {
            if selectedBtn.tintColor == .red {
                selectedBtn.tintColor = selectedTintColor
                selectedLbl.textColor = selectedTextColor
                indicatior = false
            }
            label.textColor = .red
            button.tintColor = .red
            indicatior = true
            
            switch type {
            case .temperature:
                nameForGradientOne.text = Strings.Gradient.Temperature.name
                paramOneForGradientOne.text = Strings.Gradient.Temperature.startValue
                paramTwoForGradientOne.text = Strings.Gradient.Temperature.endValue
                gradientUp.colors = Colors.temperatureGradient
            case .precipitation:
                nameForGradientOne.text = Strings.Gradient.Precipitation.name
                paramOneForGradientOne.text = Strings.Gradient.Precipitation.startValue
                paramTwoForGradientOne.text = Strings.Gradient.Precipitation.endValue
                gradientUp.colors = Colors.precipitationGradient
            case .pressure:
                nameForGradientOne.text = Strings.Gradient.Pressure.name
                paramOneForGradientOne.text = Strings.Gradient.Pressure.startValue
                paramTwoForGradientOne.text = Strings.Gradient.Pressure.endValue
                gradientUp.colors = Colors.pressureGradient
            case .wind:
                nameForGradientOne.text = Strings.Gradient.Wind.name
                paramOneForGradientOne.text = Strings.Gradient.Wind.startValue
                paramTwoForGradientOne.text = Strings.Gradient.Wind.endValue
                gradientUp.colors = Colors.windGradient
            case .clouds:
                nameForGradientOne.text = Strings.Gradient.Clouds.name
                paramOneForGradientOne.text = Strings.Gradient.Clouds.startValue
                paramTwoForGradientOne.text = Strings.Gradient.Clouds.endValue
                gradientUp.colors = Colors.cloudsGradient
            }
            
        }
        selectedLbl = label
    }
    
}
 | 
	mit | 
	034d45f4050a7de36ae5970e7ec95de2 | 41.738372 | 122 | 0.572575 | 5.890224 | false | false | false | false | 
| 
	kripple/bti-watson | 
	ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/Carthage/Checkouts/Nimble/Nimble/ObjCExpectation.swift | 
	132 | 
	4081 | 
	internal struct ObjCMatcherWrapper : Matcher {
    let matcher: NMBMatcher
    func matches(actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
        return matcher.matches(
            ({ try! actualExpression.evaluate() }),
            failureMessage: failureMessage,
            location: actualExpression.location)
    }
    func doesNotMatch(actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
        return matcher.doesNotMatch(
            ({ try! actualExpression.evaluate() }),
            failureMessage: failureMessage,
            location: actualExpression.location)
    }
}
// Equivalent to Expectation, but for Nimble's Objective-C interface
public class NMBExpectation : NSObject {
    internal let _actualBlock: () -> NSObject!
    internal var _negative: Bool
    internal let _file: String
    internal let _line: UInt
    internal var _timeout: NSTimeInterval = 1.0
    public init(actualBlock: () -> NSObject!, negative: Bool, file: String, line: UInt) {
        self._actualBlock = actualBlock
        self._negative = negative
        self._file = file
        self._line = line
    }
    private var expectValue: Expectation<NSObject> {
        return expect(_file, line: _line){
            self._actualBlock() as NSObject?
        }
    }
    public var withTimeout: (NSTimeInterval) -> NMBExpectation {
        return ({ timeout in self._timeout = timeout
            return self
        })
    }
    public var to: (NMBMatcher) -> Void {
        return ({ matcher in
            self.expectValue.to(ObjCMatcherWrapper(matcher: matcher))
        })
    }
    public var toWithDescription: (NMBMatcher, String) -> Void {
        return ({ matcher, description in
            self.expectValue.to(ObjCMatcherWrapper(matcher: matcher), description: description)
        })
    }
    public var toNot: (NMBMatcher) -> Void {
        return ({ matcher in
            self.expectValue.toNot(
                ObjCMatcherWrapper(matcher: matcher)
            )
        })
    }
    public var toNotWithDescription: (NMBMatcher, String) -> Void {
        return ({ matcher, description in
            self.expectValue.toNot(
                ObjCMatcherWrapper(matcher: matcher), description: description
            )
        })
    }
    public var notTo: (NMBMatcher) -> Void { return toNot }
    public var notToWithDescription: (NMBMatcher, String) -> Void { return toNotWithDescription }
    public var toEventually: (NMBMatcher) -> Void {
        return ({ matcher in
            self.expectValue.toEventually(
                ObjCMatcherWrapper(matcher: matcher),
                timeout: self._timeout,
                description: nil
            )
        })
    }
    public var toEventuallyWithDescription: (NMBMatcher, String) -> Void {
        return ({ matcher, description in
            self.expectValue.toEventually(
                ObjCMatcherWrapper(matcher: matcher),
                timeout: self._timeout,
                description: description
            )
        })
    }
    public var toEventuallyNot: (NMBMatcher) -> Void {
        return ({ matcher in
            self.expectValue.toEventuallyNot(
                ObjCMatcherWrapper(matcher: matcher),
                timeout: self._timeout,
                description: nil
            )
        })
    }
    public var toEventuallyNotWithDescription: (NMBMatcher, String) -> Void {
        return ({ matcher, description in
            self.expectValue.toEventuallyNot(
                ObjCMatcherWrapper(matcher: matcher),
                timeout: self._timeout,
                description: description
            )
        })
    }
    public var toNotEventually: (NMBMatcher) -> Void { return toEventuallyNot }
    public var toNotEventuallyWithDescription: (NMBMatcher, String) -> Void { return toEventuallyNotWithDescription }
    public class func failWithMessage(message: String, file: String, line: UInt) {
        fail(message, location: SourceLocation(file: file, line: line))
    }
}
 | 
	mit | 
	41128eda6e0a06233279c059e94cacb9 | 31.648 | 117 | 0.605489 | 5.463186 | false | false | false | false | 
| 
	regwez/Bezr | 
	Tests/BezrTests/SearchTests.swift | 
	1 | 
	10179 | 
	/*
 This source file is part of the Bezr open source project
 Copyright (c) 2014 - 2017 Regwez, Inc.
 Licensed under Apache License v2.0 with Runtime Library Exception
 Created by Ragy Eleish on 8/7/14.
*/
import XCTest
@testable
import Bezr
protocol ValueStruct:Comparable{
    var value:UInt16 {get}
}
struct TestValueStruct:ValueStruct{
    let value:UInt16
    let carriedValue:String
    init(value:UInt16,carriedValue: String){
        self.value = value
        self.carriedValue = carriedValue
    }
    init(value:UInt16){
        self.value = value
        self.carriedValue = ""
    }
}
func ==<T:ValueStruct>(lhs: T, rhs: T) -> Bool{
    return lhs.value == rhs.value
}
func <=<T:ValueStruct>(lhs: T, rhs: T) -> Bool{
    return lhs.value <= rhs.value
}
func >=<T:ValueStruct>(lhs: T, rhs: T) -> Bool{
    return lhs.value >= rhs.value
}
func ><T:ValueStruct>(lhs: T, rhs: T) -> Bool{
    return lhs.value > rhs.value
}
func <<T:ValueStruct>(lhs: T, rhs: T) -> Bool{
    return lhs.value < rhs.value
}
struct TestStruct:Comparable{
    let value:UInt16
    let carriedValue:String
    init(value:UInt16,carriedValue: String){
        self.value = value
        self.carriedValue = carriedValue
    }
    init(value:UInt16){
        self.value = value
        self.carriedValue = ""
    }
}
func ==(lhs: TestStruct, rhs: TestStruct) -> Bool{
    return lhs.value == rhs.value
}
func <=(lhs: TestStruct, rhs: TestStruct) -> Bool{
    return lhs.value <= rhs.value
}
func >=(lhs: TestStruct, rhs: TestStruct) -> Bool{
    return lhs.value >= rhs.value
}
func >(lhs: TestStruct, rhs: TestStruct) -> Bool{
    return lhs.value > rhs.value
}
func <(lhs: TestStruct, rhs: TestStruct) -> Bool{
    return lhs.value < rhs.value
}
class SearchTests: XCTestCase {
     let _sortedData:[UInt16] = [12, 16, 18, 25, 29, 30, 30, 44, 75, 86, 88, 90, 92, 97, 97, 101, 113, 122, 136, 164, 185, 191, 213, 228, 235, 239, 248, 248, 260, 265, 270, 284, 300, 300, 333, 344, 358, 369, 381, 391, 418, 446, 455, 457, 470, 470, 471, 478, 481, 491, 521, 541, 570, 575, 585, 595, 602, 602, 611, 629, 639, 644, 646, 663, 672, 678, 703, 703, 705, 707, 709, 733, 743, 745, 750, 765, 771, 771, 779, 798, 838, 846, 882, 883, 889, 895, 902, 909, 925, 932, 933, 941, 945, 952, 956, 965, 975, 976, 984, 993]
    let _sortedTestStructData:[TestStruct] = [
        TestStruct(value: 12, carriedValue: "12"), TestStruct(value: 16, carriedValue: "16") ,
        TestStruct(value:18 , carriedValue: "18"),TestStruct(value:25 , carriedValue: "25") ,
        TestStruct(value:29 , carriedValue: "29"),TestStruct(value:30 , carriedValue: "30") ,
        TestStruct(value:30 , carriedValue: "30"),TestStruct(value:44 , carriedValue: "44") ,
        TestStruct(value:75 , carriedValue: "75"),TestStruct(value: 86, carriedValue: "86") ,
        TestStruct(value:88 , carriedValue: "88"),TestStruct(value: 90, carriedValue: "90") ,
        TestStruct(value:92 , carriedValue: "92") ,TestStruct(value:97 , carriedValue: "97") ,
        TestStruct(value:97 , carriedValue: "97"),TestStruct(value:101 , carriedValue: "101") ,
        TestStruct(value:113 , carriedValue: "113"),TestStruct(value: 122, carriedValue: "122") ,
        TestStruct(value:136 , carriedValue: "136"),TestStruct(value:164 , carriedValue: "164") ,
        TestStruct(value:185 , carriedValue: "185"), TestStruct(value:191 , carriedValue: "191"),
        TestStruct(value:213 , carriedValue: "213"),TestStruct(value:228 , carriedValue: "228") ,
        TestStruct(value:235 , carriedValue: "235"),TestStruct(value:239 , carriedValue: "239") ,
        TestStruct(value:248 , carriedValue: "248"), TestStruct(value:248 , carriedValue: "248") ,
        TestStruct(value:260 , carriedValue: "260"), TestStruct(value:265 , carriedValue: "265"),
        TestStruct(value:270 , carriedValue: "270"), TestStruct(value:284 , carriedValue: "284"),
        TestStruct(value:300 , carriedValue: "300"),TestStruct(value:300 , carriedValue: "300") ,
        TestStruct(value:333 , carriedValue: "333"),TestStruct(value:344 , carriedValue: "344") ,
        TestStruct(value:358 , carriedValue: "358"),TestStruct(value:369 , carriedValue: "369") ,
        TestStruct(value:381 , carriedValue: "381"),TestStruct(value:391 , carriedValue: "391") ,
        TestStruct(value:418 , carriedValue: "418"), TestStruct(value:446 , carriedValue: "446"),
        TestStruct(value:455 , carriedValue: "455"),TestStruct(value:457 , carriedValue: "457") ,
        TestStruct(value:470 , carriedValue: "470"), TestStruct(value:470 , carriedValue: "470"),
        TestStruct(value:471 , carriedValue: "471"), TestStruct(value:478 , carriedValue: "478"),
        TestStruct(value: 481, carriedValue: "481"),TestStruct(value:491 , carriedValue: "491") ,
        TestStruct(value:521 , carriedValue: "521"),TestStruct(value:541 , carriedValue: "541") ,
        TestStruct(value:570 , carriedValue: "570"),TestStruct(value:575 , carriedValue: "575") ,
        TestStruct(value:585 , carriedValue: "585"),TestStruct(value:595 , carriedValue: "595") ,
        TestStruct(value:602 , carriedValue: "602"),TestStruct(value:602 , carriedValue: "602") ,
        TestStruct(value:611 , carriedValue: "611"),TestStruct(value:629 , carriedValue: "629") ,
        TestStruct(value:639 , carriedValue: "639"),TestStruct(value:644 , carriedValue: "644") ,
        TestStruct(value:646 , carriedValue: "646"),TestStruct(value:663 , carriedValue: "663") ,
        TestStruct(value:672 , carriedValue: "672") , TestStruct(value:678 , carriedValue: "678"),
        TestStruct(value:703 , carriedValue: "703"),TestStruct(value:703 , carriedValue: "703") ,
        TestStruct(value:705 , carriedValue: "705"), TestStruct(value: 707, carriedValue: "707"),
        TestStruct(value:709 , carriedValue: "709"), TestStruct(value:733 , carriedValue: "733"),
        TestStruct(value:743 , carriedValue: "743"),TestStruct(value:745 , carriedValue: "745") ,
        TestStruct(value:750 , carriedValue: "750"), TestStruct(value:765 , carriedValue: "765"),
        TestStruct(value:771 , carriedValue: "771"), TestStruct(value:771 , carriedValue: "771"),
        TestStruct(value:779 , carriedValue: "779"),TestStruct(value:798 , carriedValue: "798") ,
        TestStruct(value:838 , carriedValue: "838"),TestStruct(value:846 , carriedValue: "846") ,
        TestStruct(value:882 , carriedValue: "882"), TestStruct(value:883 , carriedValue: "883"),
        TestStruct(value:889 , carriedValue: "889"),TestStruct(value:895 , carriedValue: "895") ,
        TestStruct(value:902 , carriedValue: "902"),TestStruct(value:909 , carriedValue: "909") ,
        TestStruct(value:925 , carriedValue: "925"),TestStruct(value:932 , carriedValue: "932") ,
        TestStruct(value:933 , carriedValue: "933"),TestStruct(value:941 , carriedValue: "941") ,
        TestStruct(value:945 , carriedValue: "945"),TestStruct(value:952 , carriedValue: "952") ,
        TestStruct(value:956 , carriedValue: "956"),TestStruct(value:965 , carriedValue: "965") ,
        TestStruct(value:975 , carriedValue: "975"),TestStruct(value:976 , carriedValue: "976") ,
        TestStruct(value:984 , carriedValue: "984"),TestStruct(value:993 , carriedValue: "993") ]
    var _sortedTestValueStructData:[TestValueStruct]? = nil
    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
        var x = [TestValueStruct]()
        for n in _sortedTestStructData{
            x.append(TestValueStruct(value: n.value, carriedValue: n.carriedValue))
        }
        _sortedTestValueStructData = x
    }
    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }
    func testEqual() {
        var index = findIndexEqualToValue(0, array: _sortedData)
        XCTAssert(index == nil, "Pass")
        index = findIndexEqualToValue(12, array: _sortedData)
        XCTAssert(index! == 0, "Pass")
        index = findIndexEqualToValue(993, array: _sortedData)
        XCTAssert(index! == _sortedData.count-1 , "Pass")
    }
    func testStructEqual() {
        var index = findIndexEqualToValue(TestStruct(value:0 ), array: _sortedTestStructData)
        XCTAssert(index == nil, "Pass")
        index = findIndexEqualToValue(TestStruct(value:12), array: _sortedTestStructData)
        XCTAssert(index! == 0, "Pass")
        index = findIndexEqualToValue(TestStruct(value:993 ), array: _sortedTestStructData)
        XCTAssert(index! == _sortedTestStructData.count-1 , "Pass")
    }
    var iterations = 100
    func testUInt16SearchPerformance() {
        let a = _sortedData
        let i = iterations
        self.measure() {
            for _ in 0...i{
                var index = findIndexEqualToValue(0, array: a)
                index = findIndexEqualToValue(12, array: a)
                index = findIndexEqualToValue(707, array: a)
                index = findIndexEqualToValue(993, array: a)
            }
        }
    }
    func testTestStructSearchPerformance() {
        let a = _sortedTestStructData
        let i = iterations
        self.measure() {
            for _ in 0...i{
                var index = findIndexEqualToValue(TestStruct(value:0 ), array: a)
                index = findIndexEqualToValue(TestStruct(value:12 ), array: a)
                index = findIndexEqualToValue(TestStruct(value:707 ), array: a)
                index = findIndexEqualToValue(TestStruct(value:993 ), array: a)
            }
        }
    }
    func testValueTestStructSearchPerformance() {
        let a = _sortedTestValueStructData!
        let i = iterations
        self.measure() {
            for _ in 0...i{
                var index = findIndexEqualToValue(TestValueStruct(value:0 ), array: a)
                index = findIndexEqualToValue(TestValueStruct(value:12 ), array: a)
                index = findIndexEqualToValue(TestValueStruct(value:707 ), array: a)
                index = findIndexEqualToValue(TestValueStruct(value:993 ), array: a)
            }
        }
    }
}
 | 
	apache-2.0 | 
	678ec3978f92b80be2dd0902f2edd0e3 | 43.449782 | 517 | 0.641517 | 4.018555 | false | true | false | false | 
| 
	niunaruto/DeDaoAppSwift | 
	testSwift/Pods/CHIPageControl/CHIPageControl/CHIPageControlAleppo.swift | 
	1 | 
	4090 | 
	//
//  CHIPageControlAleppo.swift
//  CHIPageControl  ( https://github.com/ChiliLabs/CHIPageControl )
//
//  Copyright (c) 2017 Chili ( http://chi.lv )
//
//
// 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
open class CHIPageControlAleppo: CHIBasePageControl {
    fileprivate var diameter: CGFloat {
        return radius * 2
    }
    fileprivate var inactive = [CHILayer]()
    fileprivate var active: CHILayer = CHILayer()
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    public override init(frame: CGRect) {
        super.init(frame: frame)
    }
    override func updateNumberOfPages(_ count: Int) {
        inactive.forEach { $0.removeFromSuperlayer() }
        inactive = [CHILayer]()
        inactive = (0..<count).map {_ in
            let layer = CHILayer()
            self.layer.addSublayer(layer)
            return layer
        }
        self.layer.addSublayer(active)
        setNeedsLayout()
        self.invalidateIntrinsicContentSize()
    }
    override func update(for progress: Double) {
        guard progress >= 0 && progress <= Double(numberOfPages - 1),
            let firstFrame = self.inactive.first?.frame,
            numberOfPages > 1 else { return }
        let normalized = progress * Double(diameter + padding)
        let distance = abs(round(progress) - progress)
        let mult = 1 + distance * 2
        var frame = active.frame
        frame.origin.x = CGFloat(normalized) + firstFrame.origin.x
        frame.size.width = frame.height * CGFloat(mult)
        frame.size.height = self.diameter
        active.frame = frame
    }
    override open func layoutSubviews() {
        super.layoutSubviews()
        
        let floatCount = CGFloat(inactive.count)
        let x = (self.bounds.size.width - self.diameter*floatCount - self.padding*(floatCount-1))*0.5
        let y = (self.bounds.size.height - self.diameter)*0.5
        var frame = CGRect(x: x, y: y, width: self.diameter, height: self.diameter)
        active.cornerRadius = self.radius
        active.backgroundColor = (self.currentPageTintColor ?? self.tintColor)?.cgColor
        active.frame = frame
        inactive.enumerated().forEach() { index, layer in
            layer.backgroundColor = self.tintColor(position: index).withAlphaComponent(self.inactiveTransparency).cgColor
            if self.borderWidth > 0 {
                layer.borderWidth = self.borderWidth
                layer.borderColor = self.tintColor(position: index).cgColor
            }
            layer.cornerRadius = self.radius
            layer.frame = frame
            frame.origin.x += self.diameter + self.padding
        }
        update(for: progress)
    }
    override open var intrinsicContentSize: CGSize {
        return sizeThatFits(CGSize.zero)
    }
    override open func sizeThatFits(_ size: CGSize) -> CGSize {
        return CGSize(width: CGFloat(inactive.count) * self.diameter + CGFloat(inactive.count - 1) * self.padding,
                      height: self.diameter)
    }
}
 | 
	mit | 
	2f2e5650b2f1a9010cc7df73e06fac4a | 35.846847 | 121 | 0.660391 | 4.574944 | false | false | false | false | 
| 
	CocoaheadsSaar/Treffen | 
	Treffen2/Autolayout Teil 2/AutolayoutTests2/AutolayoutTests/MainStackButtonsViewController.swift | 
	1 | 
	1412 | 
	//
//  MainStackButtonsViewController.swift
//  AutolayoutTests
//
//  Created by Markus Schmitt on 13.01.16.
//  Copyright © 2016 My - Markus Schmitt. All rights reserved.
//
import UIKit
import Foundation
class MainStackButtonsViewController: UIViewController {
    var mainStackView: MainStackButtonsView {
        return view as! MainStackButtonsView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        for newButton in mainStackView.buttonArray {
            newButton.addTarget(self, action: Selector("evaluateButton:"), forControlEvents: .TouchDown)
        }
        
    }
    
    override func loadView() {
        
        let contentView = MainStackButtonsView(frame: .zero)
        view = contentView
    }
    
    override func viewWillLayoutSubviews() {
        
        let topLayoutGuide = self.topLayoutGuide
        let bottomLayoutGuide = self.bottomLayoutGuide
        
        let views = ["topLayoutGuide": topLayoutGuide, "buttonStackView" : mainStackView.buttonStackView, "bottomLayoutGuide" : bottomLayoutGuide] as [String:AnyObject]
        NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[topLayoutGuide]-[buttonStackView]-[bottomLayoutGuide]", options: [], metrics: nil, views: views))
        
    }
    
    func evaluateButton(sender: UIButton) {
        print("Button : \(sender.tag)")
    }
    
}
 | 
	gpl-2.0 | 
	f279e16d62658d6c95a306c804c8b617 | 27.22 | 195 | 0.672573 | 5.759184 | false | false | false | false | 
| 
	marcopompei/Gloss | 
	GlossTests/FlowObjectCreationTests.swift | 
	1 | 
	7389 | 
	//
//  FlowObjectCreationTests.swift
//  GlossExample
//
// Copyright (c) 2015 Harlan Kellaway
//
// 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 Gloss
import UIKit
import XCTest
class FlowObjectCreationTests: XCTestCase {
    
    var testJSON: JSON? = [:]
    
    override func setUp() {
        super.setUp()
        
        let testJSONPath: NSString = NSBundle(forClass: self.dynamicType).pathForResource("TestModel", ofType: "json")!
        let testJSONData: NSData = NSData(contentsOfFile: testJSONPath as String)!
        
        do {
            try testJSON = NSJSONSerialization.JSONObjectWithData(testJSONData, options: NSJSONReadingOptions(rawValue: 0)) as? JSON
        } catch {
            print(error)
        }
    }
    
    override func tearDown() {
        testJSON = nil
        
        super.tearDown()
    }
    
    func testObjectDecodedFromJSONHasCorrectProperties() {
        let result = TestModel(json: testJSON!)!
        
        XCTAssertTrue((result.bool == true), "Model created from JSON should have correct property values")
        XCTAssertTrue((result.boolArray! == [true, false, true]), "Model created from JSON should have correct property values")
        XCTAssertTrue((result.integer == 1), "Model created from JSON should have correct property values")
        XCTAssertTrue((result.integerArray! == [1, 2, 3]), "Model created from JSON should have correct property values")
        XCTAssertTrue((result.float == 2.0), "Model created from JSON should have correct property values")
        XCTAssertTrue((result.floatArray! == [1.0, 2.0, 3.0]), "Model created from JSON should have correct property values")
        XCTAssertTrue((result.double == 6.0), "Model created from JSON should have correct property values")
        XCTAssertTrue((result.doubleArray! == [4.0, 5.0, 6.0]), "Model created from JSON should have correct property values")
        XCTAssertTrue(result.dictionary!["otherModel"]!.id! == 789, "Model created from JSON should have correct property values")
        XCTAssertTrue(result.dictionary!["otherModel"]!.name! == "otherModel1", "Model created from JSON should have correct property values")
        XCTAssertTrue(result.dictionaryWithArray!["otherModels"]![0].id! == 123, "Model created from JSON should have correct property values")
        XCTAssertTrue(result.dictionaryWithArray!["otherModels"]![0].name! == "otherModel1", "Model created from JSON should have correct property values")
        XCTAssertTrue(result.dictionaryWithArray!["otherModels"]![1].id! == 456, "Model created from JSON should have correct property values")
        XCTAssertTrue(result.dictionaryWithArray!["otherModels"]![1].name! == "otherModel2", "Model created from JSON should have correct property values")
        XCTAssertTrue((result.string == "abc"), "Model created from JSON should have correct property values")
        XCTAssertTrue((result.stringArray! == ["def", "ghi", "jkl"]), "Model created from JSON should have correct property values")
        XCTAssertTrue((result.enumValue == TestModel.EnumValue.A), "Model created from JSON should have correct property values")
        XCTAssertTrue((result.enumValueArray! == [TestModel.EnumValue.A, TestModel.EnumValue.B, TestModel.EnumValue.C]), "Model created from JSON should have correct property values")
        XCTAssertTrue((TestModel.dateFormatter.stringFromDate(result.date!) == "2015-08-16T20:51:46.600Z"), "Model created from JSON should have correct property values")
        XCTAssertTrue((result.dateArray!.map { date in TestModel.dateFormatter.stringFromDate(date) }) == ["2015-08-16T20:51:46.600Z", "2015-08-16T20:51:46.600Z"], "Model created from JSON should have correct property values")
        XCTAssertTrue((result.dateISO8601 == NSDate(timeIntervalSince1970: 1439071033)), "Model created from JSON should have correct property values")
        XCTAssertTrue((result.int32 == 100000000), "Model created from JSON should have correct property values")
        XCTAssertTrue(result.int32Array! == [100000000, -2147483648, 2147483647], "Model created from JSON should have correct property values")
		XCTAssertTrue((result.uInt32 == 4294967295), "Model created from JSON should have correct property values")
		XCTAssertTrue(result.uInt32Array! == [100000000, 2147483648, 4294967295], "Model created from JSON should have correct property values")
		XCTAssertTrue((result.int64 == 300000000), "Model created from JSON should have correct property values")
        XCTAssertTrue(result.int64Array! == [300000000, -9223372036854775808, 9223372036854775807], "Model created from JSON should have correct property values")
		XCTAssertTrue((result.uInt64 == 18446744073709551615), "Model created from JSON should have correct property values")
		XCTAssertTrue(result.uInt64Array! == [300000000, 9223372036854775808, 18446744073709551615], "Model created from JSON should have correct property values")
		XCTAssertTrue((result.dateISO8601Array!.map { date in date.timeIntervalSince1970 }) == [1439071033, 1439071033], "Model created from JSON should have correct property values")
        XCTAssertTrue((result.url?.absoluteString == "http://github.com"), "Model created from JSON should have correct property values")
        XCTAssertTrue((result.urlArray?.map { url in url.absoluteString })! == ["http://github.com", "http://github.com", "http://github.com"], "Model created from JSON should have correct property values")
        
        XCTAssertTrue((result.nestedModel?.id == 123), "Model created from JSON should have correct property values")
        XCTAssertTrue((result.nestedModel?.name == "nestedModel1"), "Model created from JSON should have correct property values")
        
        let nestedModel2: TestNestedModel = result.nestedModelArray![0]
        let nestedModel3: TestNestedModel = result.nestedModelArray![1]
        XCTAssertTrue((nestedModel2.id == 456), "Model created from JSON should have correct property values")
        XCTAssertTrue((nestedModel2.name == "nestedModel2"), "Model created from JSON should have correct property values")
        XCTAssertTrue((nestedModel3.id == 789), "Model created from JSON should have correct property values")
        XCTAssertTrue((nestedModel3.name == "nestedModel3"), "Model created from JSON should have correct property values")
    }
    
}
 | 
	mit | 
	c362db4279dbfa3e8b0b970ae0885b2a | 72.89 | 226 | 0.72635 | 4.926 | false | true | false | false | 
| 
	imjerrybao/SocketIO-Kit | 
	Source/SocketIOEvent.swift | 
	2 | 
	1062 | 
	//
//  SocketIOEvent.swift
//  Smartime
//
//  Created by Ricardo Pereira on 10/04/2015.
//  Copyright (c) 2015 Ricardo Pereira. All rights reserved.
//
import Foundation
/**
Socket.io system events.
*/
public enum SocketIOEvent: String, Printable {
    
    case Connected = "connected" //Called on a successful connection
    case ConnectedNamespace = "connected_namespace" //Called on a successful namespace connection
    case Disconnected = "disconnected" //Called on a disconnection
    case ConnectError = "connect_error" //Called on a connection error
    case TransportError = "transport_error" //Called on a transport error (WebSocket, ...)
    case ReconnectAttempt = "reconnect_attempt" //Attempt for reconnection
    case EmitError = "emit_error" //Sending errors
    
    /// Event description.
    public var description: String {
        return self.rawValue
    }
    
    /// Protected events.
    static var system: [SocketIOEvent] {
        return [.Connected, .ConnectedNamespace, .Disconnected, .ReconnectAttempt, .EmitError]
    }
    
} | 
	mit | 
	31b12d87931bd2b096cb6b9d82759e23 | 30.264706 | 97 | 0.695857 | 4.538462 | false | false | false | false | 
| 
	nVisium/Swift.nV | 
	Swift.nV/UserHelper.swift | 
	1 | 
	4203 | 
	//
//  UserHelper.swift
//  swift.nV
//
//  Created by Seth Law on 5/1/17.
//  Copyright © 2017 nVisium. All rights reserved.
//
import Foundation
import CoreData
import UIKit
func registerUser(_ email: String,_ password: String,_ firstname: String,_ lastname: String,_ token: String?,_ user_id: Int32?) -> User? {
    let delegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.managedObjectContext!
    
    let user : User = NSEntityDescription.insertNewObject(forEntityName: "User", into: context) as! User
    
    user.email = email
    user.password = password
    user.firstname = firstname
    user.lastname = lastname
    if token != nil {
        user.token = token!
    }
    if user_id != nil {
        user.user_id = user_id!
    }
    
    do {
        try context.save()
    } catch let error as NSError {
        NSLog("Error saving context: %@", error)
        return nil
    }
    
    return user
}
func getUser(_ email:String) -> User? {
    let delegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.managedObjectContext!
    
    //let fr:NSFetchRequest = NSFetchRequest(entityName:"User")
    let fr:NSFetchRequest<NSFetchRequestResult>
    if #available(iOS 10.0, OSX 10.12, *) {
        fr = User.fetchRequest()
    } else {
        fr = NSFetchRequest(entityName: "User")
    }
    //let fr:NSFetchRequest<NSFetchRequestResult = User.FetchRequest(entityName:"User")
    fr.returnsObjectsAsFaults = false
    fr.predicate = NSPredicate(format: "(email LIKE '\(email)')",argumentArray:  nil)
    
    let users : Array<User> = try! context.fetch(fr) as! Array<User>
    if users.count > 0 {
        return users[0]
    } else {
        return nil
    }
}
func getPIN() -> String? {
    return UserDefaults.standard.string(forKey: "PIN")
}
func authenticateUser(_ email:String,_ password:String) -> User? {
    let delegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.managedObjectContext!
    let defaults : UserDefaults = UserDefaults.standard
    
    //let fr:NSFetchRequest = NSFetchRequest(entityName:"User")
    let fr:NSFetchRequest<NSFetchRequestResult>
    if #available(iOS 10.0, OSX 10.12, *) {
        fr = User.fetchRequest()
    } else {
        fr = NSFetchRequest(entityName: "User")
    }
    //let fr:NSFetchRequest<NSFetchRequestResult = User.FetchRequest(entityName:"User")
    fr.returnsObjectsAsFaults = false
    fr.predicate = NSPredicate(format: "(email LIKE '\(email)' AND password LIKE '\(password)')",argumentArray:  nil)
    
    let users : Array<User> = try! context.fetch(fr) as! Array<User>
    if users.count > 0 {
        defaults.set(users[0].email! as NSString, forKey: "email")
        defaults.set(true, forKey: "loggedin")
        defaults.synchronize()
        NSLog("Setting email key in NSUserDefaults to \(String(describing: users[0].email!))")
        
        return users[0]
    } else {
        return nil
    }
}
func deleteUser(_ email: String?) -> Bool {
    let delegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.managedObjectContext!
    let defaults : UserDefaults = UserDefaults.standard
    var success = true
    
    let fr:NSFetchRequest<NSFetchRequestResult>
    if #available(iOS 10.0, OSX 10.12, *) {
        fr = User.fetchRequest()
    } else {
        fr = NSFetchRequest(entityName: "User")
    }
    
    if (email != nil) {
        fr.predicate = NSPredicate(format: "email LIKE '\(email!)'", argumentArray: nil)
    }
    
    let users :Array<User> = try! context.fetch(fr) as! Array<User>
    
    for u: User in users {
        _ = deleteItem(nil, u.email!)
        context.delete(u)
    }
    
    defaults.removeObject(forKey: "email")
    defaults.removeObject(forKey: "loggedin")
    defaults.removeObject(forKey: "networkStorage")
    defaults.removeObject(forKey: "usePin")
    defaults.removeObject(forKey: "PIN")
    
    do {
        try context.save()
    } catch let error as NSError {
        NSLog("Error: %@", error)
        success = false
    } catch {
        fatalError()
    }
    
    return success
}
 | 
	gpl-2.0 | 
	76df1bbd6a3fff24b1fa84e7442236dc | 29.897059 | 138 | 0.639219 | 4.279022 | false | false | false | false | 
| 
	zhouxl/Arithmetic | 
	Arithmetic.playground/Pages/xor.xcplaygroundpage/Contents.swift | 
	1 | 
	717 | 
	//: [Previous](@previous)
import Foundation
/// 给定一组不重复的数,包含0,1,2......n,求出第一个miss的整数,比如[0,1,3]返回2
func missingNum(nums: [Int]) -> Int {
    var result = 0;
    for i in 0..<nums.count {
        result ^= i
        result ^= nums[i]
        if result != 0 { // 当出现result不为0时,说明出了第一个miss的整数,也不需要继续再找了
            result ^= nums[i]
            break
        }
        
    }
    return result
}
let A = [0,1,2,7]
print( missingNum(nums: A))
/// 判断一个数是否是2的n次方
func is2Power(num: Int) -> Bool {
    return (num & (num - 1)) == 0
}
let B = 18
print(is2Power(num: B))
//: [Next](@next)
 | 
	mit | 
	6729e623fd63c847fd3b22d8c96db72f | 17.34375 | 66 | 0.53833 | 2.632287 | false | false | false | false | 
| 
	KrishMunot/swift | 
	test/SILGen/protocol_extensions.swift | 
	5 | 
	34096 | 
	// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -emit-silgen %s | FileCheck %s
public protocol P1 {
  func reqP1a()
  subscript(i: Int) -> Int { get set }
}
struct Box {
  var number: Int
}
extension P1 {
  // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P16extP1a{{.*}} : $@convention(method) <Self where Self : P1> (@in_guaranteed Self) -> () {
  // CHECK: bb0([[SELF:%[0-9]+]] : $*Self):
  final func extP1a() {
    // CHECK: [[WITNESS:%[0-9]+]] = witness_method $Self, #P1.reqP1a!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> ()
    // CHECK-NEXT: apply [[WITNESS]]<Self>([[SELF]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> ()
    reqP1a()
    // CHECK: return
  }
  // CHECK-LABEL: sil @_TFE19protocol_extensionsPS_2P16extP1b{{.*}} : $@convention(method) <Self where Self : P1> (@in_guaranteed Self) -> () {
  // CHECK: bb0([[SELF:%[0-9]+]] : $*Self):
  public final func extP1b() {
    // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P16extP1a{{.*}} : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> ()
    // CHECK-NEXT: apply [[FN]]<Self>([[SELF]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> ()
    extP1a()
    // CHECK: return
  }
  subscript(i: Int) -> Int {
    // materializeForSet can do static dispatch to peer accessors (tested later, in the emission of the concrete conformance)
    get {
      return 0
    }
    set {}
  }
  final func callSubscript() -> Int {
    // But here we have to do a witness method call:
    // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P113callSubscript{{.*}}
    // CHECK: bb0(%0 : $*Self):
    // CHECK: witness_method $Self, #P1.subscript!getter.1
    // CHECK: return
    return self[0]
  }
  static var staticReadOnlyProperty: Int {
    return 0
  }
  static var staticReadWrite1: Int {
    get { return 0 }
    set { }
  }
  static var staticReadWrite2: Box {
    get { return Box(number: 0) }
    set { }
  }
}
// ----------------------------------------------------------------------------
// Using protocol extension members with concrete types
// ----------------------------------------------------------------------------
class C : P1 {
  func reqP1a() { }
}
//   (materializeForSet test from above)
// CHECK-LABEL: sil [transparent] [thunk] @_TTWC19protocol_extensions1CS_2P1S_FS1_m9subscriptFSiSi
// CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $Int, %3 : $*C):
// CHECK: function_ref @_TFE19protocol_extensionsPS_2P1g9subscriptFSiSi
// CHECK: return
class D : C { }
struct S : P1 {
  func reqP1a() { }
}
struct G<T> : P1 {
  func reqP1a() { }
}
struct MetaHolder {
  var d: D.Type = D.self
  var s: S.Type = S.self
}
struct GenericMetaHolder<T> {
  var g: G<T>.Type = G<T>.self
}
func inout_func(_ n: inout Int) {}
// CHECK-LABEL: sil hidden @_TF19protocol_extensions5testDFTVS_10MetaHolder2ddMCS_1D1dS1__T_ : $@convention(thin) (MetaHolder, @thick D.Type, @owned D) -> ()
// CHECK: bb0([[M:%[0-9]+]] : $MetaHolder, [[DD:%[0-9]+]] : $@thick D.Type, [[D:%[0-9]+]] : $D):
func testD(_ m: MetaHolder, dd: D.Type, d: D) {
  // CHECK: [[D2:%[0-9]+]] = alloc_box $D
  // CHECK: [[RESULT:%.*]] = project_box [[D2]]
  // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P111returnsSelf{{.*}}
  // CHECK: [[DCOPY:%[0-9]+]] = alloc_stack $D
  // CHECK: store [[D]] to [[DCOPY]] : $*D
  // CHECK: apply [[FN]]<D>([[RESULT]], [[DCOPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> @out τ_0_0
  var d2: D = d.returnsSelf()
  // CHECK: metatype $@thick D.Type
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi
  let _ = D.staticReadOnlyProperty
  // CHECK: metatype $@thick D.Type
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  D.staticReadWrite1 = 1
  // CHECK: metatype $@thick D.Type
  // CHECK: alloc_stack $Int
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  // CHECK: dealloc_stack
  D.staticReadWrite1 += 1
  // CHECK: metatype $@thick D.Type
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  D.staticReadWrite2 = Box(number: 2)
  // CHECK: metatype $@thick D.Type
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  D.staticReadWrite2.number += 5
  // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_
  // CHECK: metatype $@thick D.Type
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  inout_func(&D.staticReadWrite2.number)
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi
  let _ = dd.staticReadOnlyProperty
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  dd.staticReadWrite1 = 1
  // CHECK: alloc_stack $Int
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  // CHECK: dealloc_stack
  dd.staticReadWrite1 += 1
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  dd.staticReadWrite2 = Box(number: 2)
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  dd.staticReadWrite2.number += 5
  // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  inout_func(&dd.staticReadWrite2.number)
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi
  let _ = m.d.staticReadOnlyProperty
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  m.d.staticReadWrite1 = 1
  // CHECK: alloc_stack $Int
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  // CHECK: dealloc_stack
  m.d.staticReadWrite1 += 1
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  m.d.staticReadWrite2 = Box(number: 2)
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  m.d.staticReadWrite2.number += 5
  // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  inout_func(&m.d.staticReadWrite2.number)
  // CHECK: return
}
// CHECK-LABEL: sil hidden @_TF19protocol_extensions5testSFTVS_10MetaHolder2ssMVS_1S_T_
func testS(_ m: MetaHolder, ss: S.Type) {
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi
  // CHECK: metatype $@thick S.Type
  let _ = S.staticReadOnlyProperty
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  // CHECK: metatype $@thick S.Type
  S.staticReadWrite1 = 1
  // CHECK: alloc_stack $Int
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si
  // CHECK: metatype $@thick S.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  // CHECK: dealloc_stack
  S.staticReadWrite1 += 1
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick S.Type
  S.staticReadWrite2 = Box(number: 2)
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick S.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  S.staticReadWrite2.number += 5
  // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick S.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  inout_func(&S.staticReadWrite2.number)
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi
  // CHECK: metatype $@thick S.Type
  let _ = ss.staticReadOnlyProperty
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  // CHECK: metatype $@thick S.Type
  ss.staticReadWrite1 = 1
  // CHECK: alloc_stack $Int
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si
  // CHECK: metatype $@thick S.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  // CHECK: dealloc_stack
  ss.staticReadWrite1 += 1
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick S.Type
  ss.staticReadWrite2 = Box(number: 2)
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick S.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  ss.staticReadWrite2.number += 5
  // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick S.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  inout_func(&ss.staticReadWrite2.number)
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi
  // CHECK: metatype $@thick S.Type
  let _ = m.s.staticReadOnlyProperty
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  // CHECK: metatype $@thick S.Type
  m.s.staticReadWrite1 = 1
  // CHECK: alloc_stack $Int
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si
  // CHECK: metatype $@thick S.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  // CHECK: dealloc_stack
  m.s.staticReadWrite1 += 1
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick S.Type
  m.s.staticReadWrite2 = Box(number: 2)
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick S.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  m.s.staticReadWrite2.number += 5
  // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick S.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  inout_func(&m.s.staticReadWrite2.number)
  // CHECK: return
}
// CHECK-LABEL: sil hidden @_TF19protocol_extensions5testG
func testG<T>(_ m: GenericMetaHolder<T>, gg: G<T>.Type) {
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi
  // CHECK: metatype $@thick G<T>.Type
  let _ = G<T>.staticReadOnlyProperty
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  // CHECK: metatype $@thick G<T>.Type
  G<T>.staticReadWrite1 = 1
  // CHECK: alloc_stack $Int
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si
  // CHECK: metatype $@thick G<T>.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  // CHECK: dealloc_stack
  G<T>.staticReadWrite1 += 1
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick G<T>.Type
  G<T>.staticReadWrite2 = Box(number: 2)
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick G<T>.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  G<T>.staticReadWrite2.number += 5
  // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick G<T>.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  inout_func(&G<T>.staticReadWrite2.number)
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi
  // CHECK: metatype $@thick G<T>.Type
  let _ = gg.staticReadOnlyProperty
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  // CHECK: metatype $@thick G<T>.Type
  gg.staticReadWrite1 = 1
  // CHECK: alloc_stack $Int
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si
  // CHECK: metatype $@thick G<T>.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  // CHECK: dealloc_stack
  gg.staticReadWrite1 += 1
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick G<T>.Type
  gg.staticReadWrite2 = Box(number: 2)
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick G<T>.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  gg.staticReadWrite2.number += 5
  // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick G<T>.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  inout_func(&gg.staticReadWrite2.number)
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g22staticReadOnlyPropertySi
  // CHECK: metatype $@thick G<T>.Type
  let _ = m.g.staticReadOnlyProperty
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  // CHECK: metatype $@thick G<T>.Type
  m.g.staticReadWrite1 = 1
  // CHECK: alloc_stack $Int
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite1Si
  // CHECK: metatype $@thick G<T>.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite1Si
  // CHECK: dealloc_stack
  m.g.staticReadWrite1 += 1
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick G<T>.Type
  m.g.staticReadWrite2 = Box(number: 2)
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick G<T>.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  m.g.staticReadWrite2.number += 5
  // CHECK: function_ref @_TF19protocol_extensions10inout_funcFRSiT_
  // CHECK: alloc_stack $Box
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1g16staticReadWrite2VS_3Box
  // CHECK: metatype $@thick G<T>.Type
  // CHECK: store
  // CHECK: load
  // CHECK: function_ref @_TZFE19protocol_extensionsPS_2P1s16staticReadWrite2VS_3Box
  // CHECK: dealloc_stack
  inout_func(&m.g.staticReadWrite2.number)
  // CHECK: return
}
// ----------------------------------------------------------------------------
// Using protocol extension members with existentials
// ----------------------------------------------------------------------------
extension P1 {
  final func f1() { }
  final subscript (i: Int64) -> Bool {
    get { return true }
  }
  final var prop: Bool {
    get { return true }
  }
  final func returnsSelf() -> Self { return self }
  final var prop2: Bool {
    get { return true }
    set { }
  }
  final subscript (b: Bool) -> Bool {
    get { return b }
    set { }
  }
}
// CHECK-LABEL: sil hidden @_TF19protocol_extensions17testExistentials1
// CHECK: bb0([[P:%[0-9]+]] : $*P1, [[B:%[0-9]+]] : $Bool, [[I:%[0-9]+]] : $Int64):
func testExistentials1(_ p1: P1, b: Bool, i: Int64) {
  // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]])
  // CHECK: [[F1:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P12f1{{.*}}
  // CHECK: apply [[F1]]<@opened([[UUID]]) P1>([[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> ()
  p1.f1()
  // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1
  // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] :
  // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g9subscriptFVs5Int64Sb
  // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[I]], [[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Int64, @in_guaranteed τ_0_0) -> Bool
  // CHECK: destroy_addr [[POPENED_COPY]]
  // CHECK: store{{.*}} : $*Bool
  // CHECK: dealloc_stack [[POPENED_COPY]]
  var b2 = p1[i]
  // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1
  // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] :
  // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g4propSb
  // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> Bool
  // CHECK: store{{.*}} : $*Bool
  // CHECK: dealloc_stack [[POPENED_COPY]]
  var b3 = p1.prop
}
// CHECK-LABEL: sil hidden @_TF19protocol_extensions17testExistentials2
// CHECK: bb0([[P:%[0-9]+]] : $*P1):
func testExistentials2(_ p1: P1) {
  // CHECK: [[P1A:%[0-9]+]] = alloc_box $P1
  // CHECK: [[PB:%.*]] = project_box [[P1A]]
  // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1
  // CHECK: [[P1AINIT:%[0-9]+]] = init_existential_addr [[PB]] : $*P1, $@opened([[UUID2:".*"]]) P1
  // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P111returnsSelf{{.*}}
  // CHECK: apply [[FN]]<@opened([[UUID]]) P1>([[P1AINIT]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> @out τ_0_0
  var p1a: P1 = p1.returnsSelf()
}
// CHECK-LABEL: sil hidden @_TF19protocol_extensions23testExistentialsGetters
// CHECK: bb0([[P:%[0-9]+]] : $*P1):
func testExistentialsGetters(_ p1: P1) {
  // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1
  // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] :
  // CHECK: [[FN:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g5prop2Sb
  // CHECK: [[B:%[0-9]+]] = apply [[FN]]<@opened([[UUID]]) P1>([[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> Bool
  let b: Bool = p1.prop2
  // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1
  // CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] :
  // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1g9subscriptFSbSb
  // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[B]], [[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @in_guaranteed τ_0_0) -> Bool
  let b2: Bool = p1[b]
}
// CHECK-LABEL: sil hidden @_TF19protocol_extensions22testExistentialSetters
// CHECK: bb0([[P:%[0-9]+]] : $*P1, [[B:%[0-9]+]] : $Bool):
func testExistentialSetters(_ p1: P1, b: Bool) {
  var p1 = p1
  // CHECK: [[PBOX:%[0-9]+]] = alloc_box $P1
  // CHECK: [[PBP:%[0-9]+]] = project_box [[PBOX]]
  // CHECK-NEXT: copy_addr [[P]] to [initialization] [[PBP]] : $*P1
  // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[PBP]] : $*P1 to $*@opened([[UUID:".*"]]) P1
  // CHECK: [[GETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1s5prop2Sb
  // CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[B]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> ()
  // CHECK-NOT: deinit_existential_addr
  p1.prop2 = b
  // CHECK: [[POPENED:%[0-9]+]] = open_existential_addr [[PBP]] : $*P1 to $*@opened([[UUID:".*"]]) P1
  // CHECK: [[SUBSETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1s9subscriptFSbSb
  // CHECK: apply [[SUBSETTER]]<@opened([[UUID]]) P1>([[B]], [[B]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, Bool, @inout τ_0_0) -> ()
  // CHECK-NOT: deinit_existential_addr [[PB]] : $*P1
  p1[b] = b
  // CHECK: return
}
struct HasAP1 {
  var p1: P1
  var someP1: P1 {
    get { return p1 }
    set { p1 = newValue }
  }
}
// CHECK-LABEL: sil hidden @_TF19protocol_extensions29testLogicalExistentialSetters
// CHECK: bb0([[HASP1:%[0-9]+]] : $*HasAP1, [[B:%[0-9]+]] : $Bool)
func testLogicalExistentialSetters(_ hasAP1: HasAP1, _ b: Bool) {
  var hasAP1 = hasAP1
  // CHECK: [[HASP1_BOX:%[0-9]+]] = alloc_box $HasAP1
  // CHECK: [[PBHASP1:%[0-9]+]] = project_box [[HASP1_BOX]]
  // CHECK-NEXT: copy_addr [[HASP1]] to [initialization] [[PBHASP1]] : $*HasAP1
  // CHECK: [[P1_COPY:%[0-9]+]] = alloc_stack $P1
  // CHECK-NEXT: [[HASP1_COPY:%[0-9]+]] = alloc_stack $HasAP1
  // CHECK-NEXT: copy_addr [[PBHASP1]] to [initialization] [[HASP1_COPY]] : $*HasAP1
  // CHECK: [[SOMEP1_GETTER:%[0-9]+]] = function_ref @_TFV19protocol_extensions6HasAP1g6someP1PS_2P1_ : $@convention(method) (@in_guaranteed HasAP1) -> @out P1
  // CHECK: [[RESULT:%[0-9]+]] = apply [[SOMEP1_GETTER]]([[P1_COPY]], %8) : $@convention(method) (@in_guaranteed HasAP1) -> @out P1
  // CHECK: [[P1_OPENED:%[0-9]+]] = open_existential_addr [[P1_COPY]] : $*P1 to $*@opened([[UUID:".*"]]) P1
  // CHECK: [[PROP2_SETTER:%[0-9]+]] = function_ref @_TFE19protocol_extensionsPS_2P1s5prop2Sb : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> ()
  // CHECK: apply [[PROP2_SETTER]]<@opened([[UUID]]) P1>([[B]], [[P1_OPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> ()
  // CHECK: [[SOMEP1_SETTER:%[0-9]+]] = function_ref @_TFV19protocol_extensions6HasAP1s6someP1PS_2P1_ : $@convention(method) (@in P1, @inout HasAP1) -> ()
  // CHECK: apply [[SOMEP1_SETTER]]([[P1_COPY]], [[PBHASP1]]) : $@convention(method) (@in P1, @inout HasAP1) -> ()
  // CHECK-NOT: deinit_existential_addr
  hasAP1.someP1.prop2 = b
  // CHECK: return
}
func plusOneP1() -> P1 {}
// CHECK-LABEL: sil hidden @_TF19protocol_extensions38test_open_existential_semantics_opaque
func test_open_existential_semantics_opaque(_ guaranteed: P1,
                                            immediate: P1) {
  var immediate = immediate
  // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box $P1
  // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]]
  // CHECK: [[VALUE:%.*]] = open_existential_addr %0
  // CHECK: [[METHOD:%.*]] = function_ref
  // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
  guaranteed.f1()
  
  // -- Need a guaranteed copy because it's immutable
  // CHECK: copy_addr [[PB]] to [initialization] [[IMMEDIATE:%.*]] :
  // CHECK: [[VALUE:%.*]] = open_existential_addr [[IMMEDIATE]]
  // CHECK: [[METHOD:%.*]] = function_ref
  // -- Can consume the value from our own copy
  // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
  // CHECK: deinit_existential_addr [[IMMEDIATE]]
  // CHECK: dealloc_stack [[IMMEDIATE]]
  immediate.f1()
  // CHECK: [[PLUS_ONE:%.*]] = alloc_stack $P1
  // CHECK: [[VALUE:%.*]] = open_existential_addr [[PLUS_ONE]]
  // CHECK: [[METHOD:%.*]] = function_ref
  // -- Can consume the value from our own copy
  // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
  // CHECK: deinit_existential_addr [[PLUS_ONE]]
  // CHECK: dealloc_stack [[PLUS_ONE]]
  plusOneP1().f1()
}
protocol CP1: class {}
extension CP1 {
  final func f1() { }
}
func plusOneCP1() -> CP1 {}
// CHECK-LABEL: sil hidden @_TF19protocol_extensions37test_open_existential_semantics_class
func test_open_existential_semantics_class(_ guaranteed: CP1,
                                           immediate: CP1) {
  var immediate = immediate
  // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box $CP1
  // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]]
  // CHECK-NOT: strong_retain %0
  // CHECK: [[VALUE:%.*]] = open_existential_ref %0
  // CHECK: [[METHOD:%.*]] = function_ref
  // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
  // CHECK-NOT: strong_release [[VALUE]]
  // CHECK-NOT: strong_release %0
  guaranteed.f1()
  // CHECK: [[IMMEDIATE:%.*]] = load [[PB]]
  // CHECK: strong_retain [[IMMEDIATE]]
  // CHECK: [[VALUE:%.*]] = open_existential_ref [[IMMEDIATE]]
  // CHECK: [[METHOD:%.*]] = function_ref
  // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
  // CHECK: strong_release [[VALUE]]
  // CHECK-NOT: strong_release [[IMMEDIATE]]
  immediate.f1()
  // CHECK: [[F:%.*]] = function_ref {{.*}}plusOneCP1
  // CHECK: [[PLUS_ONE:%.*]] = apply [[F]]()
  // CHECK: [[VALUE:%.*]] = open_existential_ref [[PLUS_ONE]]
  // CHECK: [[METHOD:%.*]] = function_ref
  // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
  // CHECK: strong_release [[VALUE]]
  // CHECK-NOT: strong_release [[PLUS_ONE]]
  plusOneCP1().f1()
}
protocol InitRequirement {
  init(c: C)
}
extension InitRequirement {
  // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_15InitRequirementC{{.*}} : $@convention(method) <Self where Self : InitRequirement> (@owned D, @thick Self.Type) -> @out Self
  // CHECK:       bb0([[OUT:%.*]] : $*Self, [[ARG:%.*]] : $D, [[SELF_TYPE:%.*]] : $@thick Self.Type):
  init(d: D) {
  // CHECK:         [[DELEGATEE:%.*]] = witness_method $Self, #InitRequirement.init!allocator.1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : InitRequirement> (@owned C, @thick τ_0_0.Type) -> @out τ_0_0
  // CHECK:         [[ARG_UP:%.*]] = upcast [[ARG]]
  // CHECK:         apply [[DELEGATEE]]<Self>({{%.*}}, [[ARG_UP]], [[SELF_TYPE]])
    self.init(c: d)
  }
  // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_15InitRequirementC{{.*}}
  // CHECK:         function_ref @_TFE19protocol_extensionsPS_15InitRequirementC{{.*}}
  init(d2: D) {
    self.init(d: d2)
  }
}
protocol ClassInitRequirement: class {
  init(c: C)
}
extension ClassInitRequirement {
  // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_20ClassInitRequirementC{{.*}} : $@convention(method) <Self where Self : ClassInitRequirement> (@owned D, @thick Self.Type) -> @owned Self
  // CHECK:       bb0([[ARG:%.*]] : $D, [[SELF_TYPE:%.*]] : $@thick Self.Type):
  // CHECK:         [[DELEGATEE:%.*]] = witness_method $Self, #ClassInitRequirement.init!allocator.1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : ClassInitRequirement> (@owned C, @thick τ_0_0.Type) -> @owned τ_0_0
  // CHECK:         [[ARG_UP:%.*]] = upcast [[ARG]]
  // CHECK:         apply [[DELEGATEE]]<Self>([[ARG_UP]], [[SELF_TYPE]])
  init(d: D) {
    self.init(c: d)
  }
}
@objc class OC {}
@objc class OD: OC {}
@objc protocol ObjCInitRequirement {
  init(c: OC, d: OC)
}
func foo(_ t: ObjCInitRequirement.Type, c: OC) -> ObjCInitRequirement {
  return t.init(c: OC(), d: OC())
}
extension ObjCInitRequirement {
  // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_19ObjCInitRequirementC{{.*}} : $@convention(method) <Self where Self : ObjCInitRequirement> (@owned OD, @thick Self.Type) -> @owned Self
  // CHECK:       bb0([[ARG:%.*]] : $OD, [[SELF_TYPE:%.*]] : $@thick Self.Type):
  // CHECK:         [[OBJC_SELF_TYPE:%.*]] = thick_to_objc_metatype [[SELF_TYPE]]
  // CHECK:         [[SELF:%.*]] = alloc_ref_dynamic [objc] [[OBJC_SELF_TYPE]] : $@objc_metatype Self.Type, $Self
  // CHECK:         [[WITNESS:%.*]] = witness_method [volatile] $Self, #ObjCInitRequirement.init!initializer.1.foreign : $@convention(objc_method) <τ_0_0 where τ_0_0 : ObjCInitRequirement> (OC, OC, @owned τ_0_0) -> @owned τ_0_0
  // CHECK:         [[UPCAST1:%.*]] = upcast [[ARG]]
  // CHECK:         [[UPCAST2:%.*]] = upcast [[ARG]]
  // CHECK:         apply [[WITNESS]]<Self>([[UPCAST1]], [[UPCAST2]], [[SELF]])
  init(d: OD) {
    self.init(c: d, d: d)
  }
}
// rdar://problem/21370992 - delegation from an initializer in a
// protocol extension to an @objc initializer in a class.
class ObjCInitClass {
  @objc init() { }
}
protocol ProtoDelegatesToObjC { }
extension ProtoDelegatesToObjC where Self : ObjCInitClass {
  // CHECK-LABEL: sil hidden @_TFe19protocol_extensionsRxCS_13ObjCInitClassxS_20ProtoDelegatesToObjCrS1_C{{.*}}
  // CHECK: bb0([[STR:%[0-9]+]] : $String, [[SELF_META:%[0-9]+]] : $@thick Self.Type):
  init(string: String) {
    // CHECK:   [[SELF_BOX:%[0-9]+]] = alloc_box $Self
    // CHECK:   [[PB:%.*]] = project_box [[SELF_BOX]]
    // CHECK:   [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*Self
    // CHECK:   [[SELF_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[SELF_META]] : $@thick Self.Type to $@objc_metatype Self.Type
    // CHECK:   [[SELF_ALLOC:%[0-9]+]] = alloc_ref_dynamic [objc] [[SELF_META_OBJC]] : $@objc_metatype Self.Type, $Self
    // CHECK:   [[SELF_ALLOC_C:%[0-9]+]] = upcast [[SELF_ALLOC]] : $Self to $ObjCInitClass
    // CHECK:   [[OBJC_INIT:%[0-9]+]] = class_method [[SELF_ALLOC_C]] : $ObjCInitClass, #ObjCInitClass.init!initializer.1 : ObjCInitClass.Type -> () -> ObjCInitClass , $@convention(method) (@owned ObjCInitClass) -> @owned ObjCInitClass
    // CHECK:   [[SELF_RESULT:%[0-9]+]] = apply [[OBJC_INIT]]([[SELF_ALLOC_C]]) : $@convention(method) (@owned ObjCInitClass) -> @owned ObjCInitClass
    // CHECK:   [[SELF_RESULT_AS_SELF:%[0-9]+]] = unchecked_ref_cast [[SELF_RESULT]] : $ObjCInitClass to $Self
    // CHECK:   assign [[SELF_RESULT_AS_SELF]] to [[SELF]] : $*Self
    self.init()
  }
}
// Delegating from an initializer in a protocol extension where Self
// has a superclass to a required initializer of that class.
class RequiredInitClass {
  required init() { }
}
protocol ProtoDelegatesToRequired { }
extension ProtoDelegatesToRequired where Self : RequiredInitClass {
  // CHECK-LABEL: sil hidden @_TFe19protocol_extensionsRxCS_17RequiredInitClassxS_24ProtoDelegatesToRequiredrS1_C{{.*}} 
  // CHECK: bb0([[STR:%[0-9]+]] : $String, [[SELF_META:%[0-9]+]] : $@thick Self.Type):
  init(string: String) {
  // CHECK:   [[SELF_BOX:%[0-9]+]] = alloc_box $Self
  // CHECK:   [[PB:%.*]] = project_box [[SELF_BOX]]
  // CHECK:   [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*Self
  // CHECK:   [[SELF_META_AS_CLASS_META:%[0-9]+]] = upcast [[SELF_META]] : $@thick Self.Type to $@thick RequiredInitClass.Type
  // CHECK:   [[INIT:%[0-9]+]] = class_method [[SELF_META_AS_CLASS_META]] : $@thick RequiredInitClass.Type, #RequiredInitClass.init!allocator.1 : RequiredInitClass.Type -> () -> RequiredInitClass , $@convention(method) (@thick RequiredInitClass.Type) -> @owned RequiredInitClass
  // CHECK:   [[SELF_RESULT:%[0-9]+]] = apply [[INIT]]([[SELF_META_AS_CLASS_META]]) : $@convention(method) (@thick RequiredInitClass.Type) -> @owned RequiredInitClass
  // CHECK:   [[SELF_RESULT_AS_SELF:%[0-9]+]] = unchecked_ref_cast [[SELF_RESULT]] : $RequiredInitClass to $Self
  // CHECK:   assign [[SELF_RESULT_AS_SELF]] to [[SELF]] : $*Self
    self.init()
  }
}
// ----------------------------------------------------------------------------
// Default implementations via protocol extensions
// ----------------------------------------------------------------------------
protocol P2 {
  associatedtype A
  func f1(_ a: A)
  func f2(_ a: A)
  var x: A { get }
}
extension P2 {
  // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P22f1{{.*}}
  // CHECK: witness_method $Self, #P2.f2!1
  // CHECK: function_ref @_TFE19protocol_extensionsPS_2P22f3{{.*}}
  // CHECK: return
  func f1(_ a: A) {
    f2(a)
    f3(a)
  }
  // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P22f2{{.*}}
  // CHECK: witness_method $Self, #P2.f1!1
  // CHECK: function_ref @_TFE19protocol_extensionsPS_2P22f3{{.*}}
  // CHECK: return
  func f2(_ a: A) {
    f1(a)
    f3(a)
  }
  func f3(_ a: A) {}
  // CHECK-LABEL: sil hidden @_TFE19protocol_extensionsPS_2P22f4{{.*}}
  // CHECK: witness_method $Self, #P2.f1!1
  // CHECK: witness_method $Self, #P2.f2!1
  // CHECK: return
  func f4() {
    f1(x)
    f2(x)
  }
}
 | 
	apache-2.0 | 
	0034e196a29587872cac402b25403519 | 39.959085 | 278 | 0.648324 | 3.320683 | false | false | false | false | 
| 
	coderZsq/coderZsq.target.swift | 
	StudyNotes/Swift Note/CS193p/iOS11/EmojiArt/EmojiArt.swift | 
	1 | 
	741 | 
	//
//  EmojiArt.swift
//  EmojiArt
//
//  Created by 朱双泉 on 2018/5/16.
//  Copyright © 2018 Castie!. All rights reserved.
//
import Foundation
struct EmojiArt: Codable {
    
    var url: URL
    var emojis = [EmojiInfo]()
    
    struct EmojiInfo: Codable {
        let x: Int
        let y: Int
        let text: String
        let size: Int
    }
    
    init?(json: Data) {
        if let newValue = try? JSONDecoder().decode(EmojiArt.self, from: json) {
            self = newValue
        } else {
            return nil
        }
    }
    
    var json: Data? {
        return try? JSONEncoder().encode(self)
    }
    
    init(url: URL, emojis: [EmojiInfo]) {
        self.url = url
        self.emojis = emojis
    }
}
 | 
	mit | 
	ae2aaa31c448c4d50ea788833f376b1e | 17.820513 | 80 | 0.521798 | 3.967568 | false | false | false | false | 
| 
	Ehrippura/firefox-ios | 
	Storage/SQL/SQLiteRemoteClientsAndTabs.swift | 
	1 | 
	15729 | 
	/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
import Deferred
private let log = Logger.syncLogger
open class SQLiteRemoteClientsAndTabs: RemoteClientsAndTabs {
    let db: BrowserDB
    public init(db: BrowserDB) {
        self.db = db
    }
    
    class func remoteClientFactory(_ row: SDRow) -> RemoteClient {
        let guid = row["guid"] as? String
        let name = row["name"] as! String
        let mod = (row["modified"] as! NSNumber).uint64Value
        let type = row["type"] as? String
        let form = row["formfactor"] as? String
        let os = row["os"] as? String
        let version = row["version"] as? String
        let fxaDeviceId = row["fxaDeviceId"] as? String
        return RemoteClient(guid: guid, name: name, modified: mod, type: type, formfactor: form, os: os, version: version, fxaDeviceId: fxaDeviceId)
    }
    
    class func remoteTabFactory(_ row: SDRow) -> RemoteTab {
        let clientGUID = row["client_guid"] as? String
        let url = URL(string: row["url"] as! String)! // TODO: find a way to make this less dangerous.
        let title = row["title"] as! String
        let history = SQLiteRemoteClientsAndTabs.convertStringToHistory(row["history"] as? String)
        let lastUsed = row.getTimestamp("last_used")!
        return RemoteTab(clientGUID: clientGUID, URL: url, title: title, history: history, lastUsed: lastUsed, icon: nil)
    }
    class func convertStringToHistory(_ history: String?) -> [URL] {
        if let data = history?.data(using: String.Encoding.utf8) {
            if let urlStrings = try! JSONSerialization.jsonObject(with: data, options: [JSONSerialization.ReadingOptions.allowFragments]) as? [String] {
                return optFilter(urlStrings.map { URL(string: $0) })
            }
        }
        return []
    }
    class func convertHistoryToString(_ history: [URL]) -> String? {
        let historyAsStrings = optFilter(history.map { $0.absoluteString })
        
        let data = try! JSONSerialization.data(withJSONObject: historyAsStrings, options: [])
        return String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
    }
    open func wipeClients() -> Success {
        return db.run("DELETE FROM \(TableClients)")
    }
    open func wipeRemoteTabs() -> Success {
        return db.run("DELETE FROM \(TableTabs) WHERE client_guid IS NOT NULL")
    }
    open func wipeTabs() -> Success {
        return db.run("DELETE FROM \(TableTabs)")
    }
    open func insertOrUpdateTabs(_ tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
        return self.insertOrUpdateTabsForClientGUID(nil, tabs: tabs)
    }
    open func insertOrUpdateTabsForClientGUID(_ clientGUID: String?, tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
        let deleteQuery = "DELETE FROM \(TableTabs) WHERE client_guid IS ?"
        let deleteArgs: Args = [clientGUID]
        return db.transaction { connection -> Int in
            // Delete any existing tabs.
            try connection.executeChange(deleteQuery, withArgs: deleteArgs)
            // Insert replacement tabs.
            var inserted = 0
            for tab in tabs {
                let args: Args = [
                    tab.clientGUID,
                    tab.URL.absoluteString,
                    tab.title,
                    SQLiteRemoteClientsAndTabs.convertHistoryToString(tab.history),
                    NSNumber(value: tab.lastUsed)
                ]
                
                let lastInsertedRowID = connection.lastInsertedRowID
                
                // We trust that each tab's clientGUID matches the supplied client!
                // Really tabs shouldn't have a GUID at all. Future cleanup!
                try connection.executeChange("INSERT INTO \(TableTabs) (client_guid, url, title, history, last_used) VALUES (?, ?, ?, ?, ?)", withArgs: args)
                
                if connection.lastInsertedRowID == lastInsertedRowID {
                    log.debug("Unable to INSERT RemoteTab!")
                } else {
                    inserted += 1
                }
            }
            return inserted
        }
    }
    open func insertOrUpdateClients(_ clients: [RemoteClient]) -> Deferred<Maybe<Int>> {
        // TODO: insert multiple clients in a single query.
        // ORM systems are foolish.
        return db.transaction { connection -> Int in
            var succeeded = 0
            // Update or insert client records.
            for client in clients {
                let args: Args = [
                    client.name,
                    NSNumber(value: client.modified),
                    client.type,
                    client.formfactor,
                    client.os,
                    client.version,
                    client.fxaDeviceId,
                    client.guid
                ]
                
                try connection.executeChange("UPDATE \(TableClients) SET name = ?, modified = ?, type = ?, formfactor = ?, os = ?, version = ?, fxaDeviceId = ? WHERE guid = ?", withArgs: args)
                
                if connection.numberOfRowsModified == 0 {
                    let args: Args = [
                        client.guid,
                        client.name,
                        NSNumber(value: client.modified),
                        client.type,
                        client.formfactor,
                        client.os,
                        client.version,
                        client.fxaDeviceId
                    ]
                    
                    let lastInsertedRowID = connection.lastInsertedRowID
                    
                    try connection.executeChange("INSERT INTO \(TableClients) (guid, name, modified, type, formfactor, os, version, fxaDeviceId) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", withArgs: args)
                    
                    if connection.lastInsertedRowID == lastInsertedRowID {
                        log.debug("INSERT did not change last inserted row ID.")
                    }
                }
                
                succeeded += 1
            }
            return succeeded
        }
    }
    open func insertOrUpdateClient(_ client: RemoteClient) -> Deferred<Maybe<Int>> {
        return insertOrUpdateClients([client])
    }
    open func deleteClient(guid: GUID) -> Success {
        let deleteTabsQuery = "DELETE FROM \(TableTabs) WHERE client_guid = ?"
        let deleteClientQuery = "DELETE FROM \(TableClients) WHERE guid = ?"
        let deleteArgs: Args = [guid]
        return db.transaction { connection -> Void in
            try connection.executeChange(deleteClientQuery, withArgs: deleteArgs)
            try connection.executeChange(deleteTabsQuery, withArgs: deleteArgs)
        }
    }
    open func getClient(guid: GUID) -> Deferred<Maybe<RemoteClient?>> {
        let factory = SQLiteRemoteClientsAndTabs.remoteClientFactory
        return self.db.runQuery("SELECT * FROM \(TableClients) WHERE guid = ?", args: [guid], factory: factory) >>== { deferMaybe($0[0]) }
    }
    open func getClient(fxaDeviceId: String) -> Deferred<Maybe<RemoteClient?>> {
        let factory = SQLiteRemoteClientsAndTabs.remoteClientFactory
        return self.db.runQuery("SELECT * FROM \(TableClients) WHERE fxaDeviceId = ?", args: [fxaDeviceId], factory: factory) >>== { deferMaybe($0[0]) }
    }
    open func getClientWithId(_ clientID: GUID) -> Deferred<Maybe<RemoteClient?>> {
        return self.getClient(guid: clientID)
    }
    open func getClients() -> Deferred<Maybe<[RemoteClient]>> {
        return db.withConnection { connection -> [RemoteClient] in
            let cursor = connection.executeQuery("SELECT * FROM \(TableClients) WHERE EXISTS (SELECT 1 FROM \(TableRemoteDevices) rd WHERE rd.guid = fxaDeviceId) ORDER BY modified DESC", factory: SQLiteRemoteClientsAndTabs.remoteClientFactory)
            defer {
                cursor.close()
            }
            return cursor.asArray()
        }
    }
    open func getClientGUIDs() -> Deferred<Maybe<Set<GUID>>> {
        let c = db.runQuery("SELECT guid FROM \(TableClients) WHERE guid IS NOT NULL", args: nil, factory: { $0["guid"] as! String })
        return c >>== { cursor in
            let guids = Set<GUID>(cursor.asArray())
            return deferMaybe(guids)
        }
    }
    open func getTabsForClientWithGUID(_ guid: GUID?) -> Deferred<Maybe<[RemoteTab]>> {
        let tabsSQL: String
        let clientArgs: Args?
        if let _ = guid {
            tabsSQL = "SELECT * FROM \(TableTabs) WHERE client_guid = ?"
            clientArgs = [guid]
        } else {
            tabsSQL = "SELECT * FROM \(TableTabs) WHERE client_guid IS NULL"
            clientArgs = nil
        }
        log.debug("Looking for tabs for client with guid: \(guid ?? "nil")")
        return db.runQuery(tabsSQL, args: clientArgs, factory: SQLiteRemoteClientsAndTabs.remoteTabFactory) >>== {
            let tabs = $0.asArray()
            log.debug("Found \(tabs.count) tabs for client with guid: \(guid ?? "nil")")
            return deferMaybe(tabs)
        }
    }
    open func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
        return db.withConnection { conn -> ([RemoteClient], [RemoteTab]) in
            let clientsCursor = conn.executeQuery("SELECT * FROM \(TableClients) WHERE EXISTS (SELECT 1 FROM \(TableRemoteDevices) rd WHERE rd.guid = fxaDeviceId) ORDER BY modified DESC", factory: SQLiteRemoteClientsAndTabs.remoteClientFactory)
            let tabsCursor = conn.executeQuery("SELECT * FROM \(TableTabs) WHERE client_guid IS NOT NULL ORDER BY client_guid DESC, last_used DESC", factory: SQLiteRemoteClientsAndTabs.remoteTabFactory)
            defer {
                clientsCursor.close()
                tabsCursor.close()
            }
            return (clientsCursor.asArray(), tabsCursor.asArray())
        } >>== { clients, tabs in
            var acc = [String: [RemoteTab]]()
            for tab in tabs {
                if let guid = tab.clientGUID {
                    if acc[guid] == nil {
                        acc[guid] = [tab]
                    } else {
                        acc[guid]!.append(tab)
                    }
                } else {
                    log.error("RemoteTab (\(tab)) has a nil clientGUID")
                }
            }
            // Most recent first.
            let fillTabs: (RemoteClient) -> ClientAndTabs = { client in
                var tabs: [RemoteTab]? = nil
                if let guid: String = client.guid {
                    tabs = acc[guid]
                }
                return ClientAndTabs(client: client, tabs: tabs ?? [])
            }
            return deferMaybe(clients.map(fillTabs))
        }
    }
    open func deleteCommands() -> Success {
        return db.run("DELETE FROM \(TableSyncCommands)")
    }
    open func deleteCommands(_ clientGUID: GUID) -> Success {
        return db.run("DELETE FROM \(TableSyncCommands) WHERE client_guid = ?", withArgs: [clientGUID] as Args)
    }
    open func insertCommand(_ command: SyncCommand, forClients clients: [RemoteClient]) -> Deferred<Maybe<Int>> {
        return insertCommands([command], forClients: clients)
    }
    open func insertCommands(_ commands: [SyncCommand], forClients clients: [RemoteClient]) -> Deferred<Maybe<Int>> {
        return db.transaction { connection -> Int in
            var numberOfInserts = 0
            // Update or insert client records.
            for command in commands {
                for client in clients {
                    do {
                        if let commandID = try self.insert(connection, sql: "INSERT INTO \(TableSyncCommands) (client_guid, value) VALUES (?, ?)", args: [client.guid, command.value] as Args) {
                            log.verbose("Inserted command: \(commandID)")
                            numberOfInserts += 1
                        } else {
                            log.warning("Command not inserted, but no error!")
                        }
                    } catch let err as NSError {
                        log.error("insertCommands(_:, forClients:) failed: \(err.localizedDescription) (numberOfInserts: \(numberOfInserts)")
                        throw err
                    }
                }
            }
            return numberOfInserts
        }
    }
    open func getCommands() -> Deferred<Maybe<[GUID: [SyncCommand]]>> {
        return db.withConnection { connection -> [GUID: [SyncCommand]] in
            let cursor = connection.executeQuery("SELECT * FROM \(TableSyncCommands)", factory: { row -> SyncCommand in
                SyncCommand(
                    id: row["command_id"] as? Int,
                    value: row["value"] as! String,
                    clientGUID: row["client_guid"] as? GUID)
            })
            defer {
                cursor.close()
            }
            return self.clientsFromCommands(cursor.asArray())
        }
    }
    func clientsFromCommands(_ commands: [SyncCommand]) -> [GUID: [SyncCommand]] {
        var syncCommands = [GUID: [SyncCommand]]()
        for command in commands {
            var cmds: [SyncCommand] = syncCommands[command.clientGUID!] ?? [SyncCommand]()
            cmds.append(command)
            syncCommands[command.clientGUID!] = cmds
        }
        return syncCommands
    }
    
    func insert(_ db: SQLiteDBConnection, sql: String, args: Args?) throws -> Int? {
        let lastID = db.lastInsertedRowID
        try db.executeChange(sql, withArgs: args)
        
        let id = db.lastInsertedRowID
        if id == lastID {
            log.debug("INSERT did not change last inserted row ID.")
            return nil
        }
        
        return id
    }
}
extension SQLiteRemoteClientsAndTabs: RemoteDevices {
    open func replaceRemoteDevices(_ remoteDevices: [RemoteDevice]) -> Success {
        // Drop corrupted records and our own record too.
        let remoteDevices = remoteDevices.filter { $0.id != nil && $0.type != nil && !$0.isCurrentDevice }
        return db.transaction { conn -> Void in
            try conn.executeChange("DELETE FROM \(TableRemoteDevices)")
            let now = Date.now()
            for device in remoteDevices {
                let sql =
                    "INSERT INTO \(TableRemoteDevices) (guid, name, type, is_current_device, date_created, date_modified, last_access_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?)"
                let args: Args = [device.id, device.name, device.type, device.isCurrentDevice, now, now, device.lastAccessTime]
                try conn.executeChange(sql, withArgs: args)
            }
        }
    }
}
extension SQLiteRemoteClientsAndTabs: ResettableSyncStorage {
    public func resetClient() -> Success {
        // For this engine, resetting is equivalent to wiping.
        return self.clear()
    }
    public func clear() -> Success {
        return db.transaction { conn -> Void in
            try conn.executeChange("DELETE FROM \(TableTabs) WHERE client_guid IS NOT NULL")
            try conn.executeChange("DELETE FROM \(TableClients)")
        }
    }
}
extension SQLiteRemoteClientsAndTabs: AccountRemovalDelegate {
    public func onRemovedAccount() -> Success {
        log.info("Clearing clients and tabs after account removal.")
        // TODO: Bug 1168690 - delete our client and tabs records from the server.
        return self.resetClient()
    }
}
 | 
	mpl-2.0 | 
	f245c33c0625b30918f80b9b1bc2771e | 40.392105 | 244 | 0.567932 | 5.108477 | false | false | false | false | 
| 
	eofster/Telephone | 
	Telephone/SoundPreferencesViewEventTarget.swift | 
	1 | 
	3649 | 
	//
//  SoundPreferencesViewEventTarget.swift
//  Telephone
//
//  Copyright © 2008-2016 Alexey Kuznetsov
//  Copyright © 2016-2021 64 Characters
//
//  Telephone is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  Telephone is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
import UseCases
final class SoundPreferencesViewEventTarget: NSObject {
    private let useCaseFactory: UseCaseFactory
    private let presenterFactory: PresenterFactory
    private let userAgentSoundIOSelection: UseCase
    private let ringtoneOutputUpdate: ThrowingUseCase
    private let ringtoneSoundPlayback: SoundPlaybackUseCase
    init(useCaseFactory: UseCaseFactory,
         presenterFactory: PresenterFactory,
         userAgentSoundIOSelection: UseCase,
         ringtoneOutputUpdate: ThrowingUseCase,
         ringtoneSoundPlayback: SoundPlaybackUseCase) {
        self.useCaseFactory = useCaseFactory
        self.presenterFactory = presenterFactory
        self.userAgentSoundIOSelection = userAgentSoundIOSelection
        self.ringtoneOutputUpdate = ringtoneOutputUpdate
        self.ringtoneSoundPlayback = ringtoneSoundPlayback
    }
    @objc(viewShouldReloadData:)
    func shouldReloadData(in view: SoundPreferencesView) {
        loadSettingsSoundIOInViewOrLogError(view: view)
    }
    @objc(viewShouldReloadSoundIO:)
    func shouldReloadSoundIO(in view: SoundPreferencesView) {
        loadSettingsSoundIOInViewOrLogError(view: view)
    }
    @objc(viewDidChangeSoundIO:)
    func didChangeSoundIO(_ soundIO: PresentationSoundIO) {
        updateSettings(withSoundIO: soundIO)
        userAgentSoundIOSelection.execute()
        updateRingtoneOutputOrLogError()
    }
    @objc(viewDidChangeRingtoneName:)
    func didChangeRingtoneName(_ name: String) {
        updateSettings(withRingtoneSoundName: name)
        playRingtoneSoundOrLogError()
    }
    @objc(viewWillDisappear:)
    func willDisappear(_ view: SoundPreferencesView) {
        ringtoneSoundPlayback.stop()
    }
}
private extension SoundPreferencesViewEventTarget {
    func loadSettingsSoundIOInViewOrLogError(view: SoundPreferencesView) {
        do {
            try makeSettingsSoundIOLoadUseCase(view: view).execute()
        } catch {
            print("Could not load Sound IO view data")
        }
    }
    func updateSettings(withSoundIO soundIO: PresentationSoundIO) {
        useCaseFactory.makeSettingsSoundIOSaveUseCase(soundIO: SystemDefaultingSoundIO(soundIO)).execute()
    }
    func updateRingtoneOutputOrLogError() {
        do {
            try ringtoneOutputUpdate.execute()
        } catch {
            print("Could not update ringtone output: \(error)")
        }
    }
    func updateSettings(withRingtoneSoundName name: String) {
        useCaseFactory.makeSettingsRingtoneSoundNameSaveUseCase(name: name).execute()
    }
    func playRingtoneSoundOrLogError() {
        do {
            try ringtoneSoundPlayback.play()
        } catch {
            print("Could not play ringtone sound: \(error)")
        }
    }
    func makeSettingsSoundIOLoadUseCase(view: SoundPreferencesView) -> ThrowingUseCase {
        return useCaseFactory.makeSettingsSoundIOLoadUseCase(
            output: presenterFactory.makeSoundIOPresenter(output: view)
        )
    }
}
 | 
	gpl-3.0 | 
	198e87090f26acf3b0860c6abd8943b5 | 33.084112 | 106 | 0.71456 | 5.293179 | false | false | false | false | 
| 
	kstaring/swift | 
	test/Sema/availability.swift | 
	4 | 
	5774 | 
	// RUN: %target-parse-verify-swift
// REQUIRES: OS=macosx
@available(*, unavailable)
func unavailable_foo() {} // expected-note {{'unavailable_foo()' has been explicitly marked unavailable here}}
func test() {
  unavailable_foo() // expected-error {{'unavailable_foo()' is unavailable}}
}
@available(*,unavailable,message: "use 'Int' instead")
struct NSUInteger {} // expected-note 2 {{explicitly marked unavailable here}}
func foo(x : NSUInteger) { // expected-error {{'NSUInteger' is unavailable: use 'Int' instead}}
     let y : NSUInteger = 42 // expected-error {{'NSUInteger' is unavailable: use 'Int' instead}}
}
// Test preventing overrides of unavailable methods.
class ClassWithUnavailable {
  @available(*, unavailable)
  func doNotOverride() {} // expected-note {{'doNotOverride()' has been explicitly marked unavailable here}}
  // FIXME: extraneous diagnostic here
  @available(*, unavailable)
  init(int _: Int) {} // expected-note 2 {{'init(int:)' has been explicitly marked unavailable here}}
  convenience init(otherInt: Int) {
    self.init(int: otherInt) // expected-error {{'init(int:)' is unavailable}}
  }
  @available(*, unavailable)
  subscript (i: Int) -> Int { // expected-note{{'subscript' has been explicitly marked unavailable here}}
    return i
  }
}
class ClassWithOverride : ClassWithUnavailable {
  override func doNotOverride() {} // expected-error {{cannot override 'doNotOverride' which has been marked unavailable}}
}
func testInit() {
  ClassWithUnavailable(int: 0) // expected-error {{'init(int:)' is unavailable}} // expected-warning{{unused}}
}
func testSubscript(cwu: ClassWithUnavailable) {
  _ = cwu[5] // expected-error{{'subscript' is unavailable}}
}
/* FIXME 'nil == a' fails to type-check with a bogus error message
 * <rdar://problem/17540796>
func markUsed<T>(t: T) {}
func testString() {
  let a : String = "Hey"
  if a == nil {
    markUsed("nil")
  } else if nil == a {
    markUsed("nil")
  }
  else {
    markUsed("not nil")
  }
}
 */
// Test preventing protocol witnesses for unavailable requirements
@objc
protocol ProtocolWithRenamedRequirement {
  @available(*, unavailable, renamed: "new(bar:)")
  @objc optional func old(foo: Int) // expected-note{{'old(foo:)' has been explicitly marked unavailable here}}
  func new(bar: Int)
}
class ClassWithGoodWitness : ProtocolWithRenamedRequirement {
  @objc func new(bar: Int) {}
}
class ClassWithBadWitness : ProtocolWithRenamedRequirement {
  @objc func old(foo: Int) {} // expected-error{{'old(foo:)' has been renamed to 'new(bar:)'}}
  @objc func new(bar: Int) {}
}
@available(OSX, unavailable)
let unavailableOnOSX: Int = 0 // expected-note{{explicitly marked unavailable here}}
@available(iOS, unavailable)
let unavailableOniOS: Int = 0
@available(iOS, unavailable) @available(OSX, unavailable)
let unavailableOnBothA: Int = 0 // expected-note{{explicitly marked unavailable here}}
@available(OSX, unavailable) @available(iOS, unavailable)
let unavailableOnBothB: Int = 0 // expected-note{{explicitly marked unavailable here}}
@available(OSX, unavailable)
typealias UnavailableOnOSX = Int // expected-note{{explicitly marked unavailable here}}
@available(iOS, unavailable)
typealias UnavailableOniOS = Int
@available(iOS, unavailable) @available(OSX, unavailable)
typealias UnavailableOnBothA = Int // expected-note{{explicitly marked unavailable here}}
@available(OSX, unavailable) @available(iOS, unavailable)
typealias UnavailableOnBothB = Int // expected-note{{explicitly marked unavailable here}}
@available(macOS, unavailable)
let unavailableOnMacOS: Int = 0 // expected-note{{explicitly marked unavailable here}}
@available(macOS, unavailable)
typealias UnavailableOnMacOS = Int // expected-note{{explicitly marked unavailable here}}
@available(OSXApplicationExtension, unavailable)
let unavailableOnOSXAppExt: Int = 0
@available(macOSApplicationExtension, unavailable)
let unavailableOnMacOSAppExt: Int = 0
@available(OSXApplicationExtension, unavailable)
typealias UnavailableOnOSXAppExt = Int
@available(macOSApplicationExtension, unavailable)
typealias UnavailableOnMacOSAppExt = Int
func testPlatforms() {
  _ = unavailableOnOSX // expected-error{{unavailable}}
  _ = unavailableOniOS
  _ = unavailableOnBothA // expected-error{{unavailable}}
  _ = unavailableOnBothB // expected-error{{unavailable}}
  _ = unavailableOnMacOS // expected-error{{unavailable}}
  _ = unavailableOnOSXAppExt
  _ = unavailableOnMacOSAppExt
  let _: UnavailableOnOSX = 0 // expected-error{{unavailable}}
  let _: UnavailableOniOS = 0
  let _: UnavailableOnBothA = 0 // expected-error{{unavailable}}
  let _: UnavailableOnBothB = 0 // expected-error{{unavailable}}
  let _: UnavailableOnMacOS = 0 // expected-error{{unavailable}}
  let _: UnavailableOnOSXAppExt = 0
  let _: UnavailableOnMacOSAppExt = 0
}
struct VarToFunc {
  @available(*, unavailable, renamed: "function()")
  var variable: Int // expected-note 2 {{explicitly marked unavailable here}}
  @available(*, unavailable, renamed: "function()")
  func oldFunction() -> Int { return 42 } // expected-note 2 {{explicitly marked unavailable here}}
  func function() -> Int {
    _ = variable // expected-error{{'variable' has been renamed to 'function()'}}{{9-17=function()}}
    _ = oldFunction() //expected-error{{'oldFunction()' has been renamed to 'function()'}}{{9-20=function}}
    _ = oldFunction // expected-error{{'oldFunction()' has been renamed to 'function()'}} {{9-20=function}}
    return 42
  }
  mutating func testAssignment() {
    // This is nonsense, but someone shouldn't be using 'renamed' for this
    // anyway. Just make sure we don't crash or anything.
    variable = 2 // expected-error {{'variable' has been renamed to 'function()'}} {{5-13=function()}}
  }
}
 | 
	apache-2.0 | 
	59f068edf24702bb4e3504f02a1f1bd2 | 36.251613 | 122 | 0.721337 | 4.22694 | false | true | false | false | 
| 
	brentsimmons/Evergreen | 
	Account/Sources/Account/NewsBlur/Internals/NewsBlurAccountDelegate+Internal.swift | 
	1 | 
	17185 | 
	//
//  NewsBlurAccountDelegate+Internal.swift
//  Mostly adapted from FeedbinAccountDelegate.swift
//  Account
//
//  Created by Anh Quang Do on 2020-03-14.
//  Copyright (c) 2020 Ranchero Software, LLC. All rights reserved.
//
import Articles
import RSCore
import RSDatabase
import RSParser
import RSWeb
import SyncDatabase
import os.log
extension NewsBlurAccountDelegate {
	
	func refreshFeeds(for account: Account, completion: @escaping (Result<Void, Error>) -> Void) {
		os_log(.debug, log: log, "Refreshing feeds...")
		caller.retrieveFeeds { result in
			switch result {
			case .success((let feeds, let folders)):
				BatchUpdate.shared.perform {
					self.syncFolders(account, folders)
					self.syncFeeds(account, feeds)
					self.syncFeedFolderRelationship(account, folders)
				}
				completion(.success(()))
			case .failure(let error):
				completion(.failure(error))
			}
		}
	}
	func syncFolders(_ account: Account, _ folders: [NewsBlurFolder]?) {
		guard let folders = folders else { return }
		assert(Thread.isMainThread)
		os_log(.debug, log: log, "Syncing folders with %ld folders.", folders.count)
		let folderNames = folders.map { $0.name }
		// Delete any folders not at NewsBlur
		if let folders = account.folders {
			folders.forEach { folder in
				if !folderNames.contains(folder.name ?? "") {
					for feed in folder.topLevelWebFeeds {
						account.addWebFeed(feed)
						clearFolderRelationship(for: feed, withFolderName: folder.name ?? "")
					}
					account.removeFolder(folder)
				}
			}
		}
		let accountFolderNames: [String] =  {
			if let folders = account.folders {
				return folders.map { $0.name ?? "" }
			} else {
				return [String]()
			}
		}()
		// Make any folders NewsBlur has, but we don't
		// Ignore account-level folder
		folderNames.forEach { folderName in
			if !accountFolderNames.contains(folderName) && folderName != " " {
				_ = account.ensureFolder(with: folderName)
			}
		}
	}
	func syncFeeds(_ account: Account, _ feeds: [NewsBlurFeed]?) {
		guard let feeds = feeds else { return }
		assert(Thread.isMainThread)
		os_log(.debug, log: log, "Syncing feeds with %ld feeds.", feeds.count)
		let newsBlurFeedIds = feeds.map { String($0.feedID) }
		// Remove any feeds that are no longer in the subscriptions
		if let folders = account.folders {
			for folder in folders {
				for feed in folder.topLevelWebFeeds {
					if !newsBlurFeedIds.contains(feed.webFeedID) {
						folder.removeWebFeed(feed)
					}
				}
			}
		}
		for feed in account.topLevelWebFeeds {
			if !newsBlurFeedIds.contains(feed.webFeedID) {
				account.removeWebFeed(feed)
			}
		}
		// Add any feeds we don't have and update any we do
		var feedsToAdd = Set<NewsBlurFeed>()
		feeds.forEach { feed in
			let subFeedId = String(feed.feedID)
			if let webFeed = account.existingWebFeed(withWebFeedID: subFeedId) {
				webFeed.name = feed.name
				// If the name has been changed on the server remove the locally edited name
				webFeed.editedName = nil
				webFeed.homePageURL = feed.homePageURL
				webFeed.externalID = String(feed.feedID)
				webFeed.faviconURL = feed.faviconURL
			}
			else {
				feedsToAdd.insert(feed)
			}
		}
		// Actually add feeds all in one go, so we don’t trigger various rebuilding things that Account does.
		feedsToAdd.forEach { feed in
			let webFeed = account.createWebFeed(with: feed.name, url: feed.feedURL, webFeedID: String(feed.feedID), homePageURL: feed.homePageURL)
			webFeed.externalID = String(feed.feedID)
			account.addWebFeed(webFeed)
		}
	}
	func syncFeedFolderRelationship(_ account: Account, _ folders: [NewsBlurFolder]?) {
		guard let folders = folders else { return }
		assert(Thread.isMainThread)
		os_log(.debug, log: log, "Syncing folders with %ld folders.", folders.count)
		// Set up some structures to make syncing easier
		let relationships = folders.map({ $0.asRelationships }).flatMap { $0 }
		let folderDict = nameToFolderDictionary(with: account.folders)
		let newsBlurFolderDict = relationships.reduce([String: [NewsBlurFolderRelationship]]()) { (dict, relationship) in
			var feedInFolders = dict
			if var feedInFolder = feedInFolders[relationship.folderName] {
				feedInFolder.append(relationship)
				feedInFolders[relationship.folderName] = feedInFolder
			} else {
				feedInFolders[relationship.folderName] = [relationship]
			}
			return feedInFolders
		}
		// Sync the folders
		for (folderName, folderRelationships) in newsBlurFolderDict {
			guard folderName != " " else {
				continue
			}
			let newsBlurFolderFeedIDs = folderRelationships.map { String($0.feedID) }
			guard let folder = folderDict[folderName] else { return }
			// Move any feeds not in the folder to the account
			for feed in folder.topLevelWebFeeds {
				if !newsBlurFolderFeedIDs.contains(feed.webFeedID) {
					folder.removeWebFeed(feed)
					clearFolderRelationship(for: feed, withFolderName: folder.name ?? "")
					account.addWebFeed(feed)
				}
			}
			// Add any feeds not in the folder
			let folderFeedIds = folder.topLevelWebFeeds.map { $0.webFeedID }
			for relationship in folderRelationships {
				let folderFeedID = String(relationship.feedID)
				if !folderFeedIds.contains(folderFeedID) {
					guard let feed = account.existingWebFeed(withWebFeedID: folderFeedID) else {
						continue
					}
					saveFolderRelationship(for: feed, withFolderName: folderName, id: relationship.folderName)
					folder.addWebFeed(feed)
				}
			}
		}
		
		// Handle the account level feeds.  If there isn't the special folder, that means all the feeds are
		// in folders and we need to remove them all from the account level.
		if let folderRelationships = newsBlurFolderDict[" "] {
			let newsBlurFolderFeedIDs = folderRelationships.map { String($0.feedID) }
			for feed in account.topLevelWebFeeds {
				if !newsBlurFolderFeedIDs.contains(feed.webFeedID) {
					account.removeWebFeed(feed)
				}
			}
		} else {
			for feed in account.topLevelWebFeeds {
				account.removeWebFeed(feed)
			}
		}
		
	}
	func clearFolderRelationship(for feed: WebFeed, withFolderName folderName: String) {
		if var folderRelationship = feed.folderRelationship {
			folderRelationship[folderName] = nil
			feed.folderRelationship = folderRelationship
		}
	}
	func saveFolderRelationship(for feed: WebFeed, withFolderName folderName: String, id: String) {
		if var folderRelationship = feed.folderRelationship {
			folderRelationship[folderName] = id
			feed.folderRelationship = folderRelationship
		} else {
			feed.folderRelationship = [folderName: id]
		}
	}
	func nameToFolderDictionary(with folders: Set<Folder>?) -> [String: Folder] {
		guard let folders = folders else {
			return [String: Folder]()
		}
		var d = [String: Folder]()
		for folder in folders {
			let name = folder.name ?? ""
			if d[name] == nil {
				d[name] = folder
			}
		}
		return d
	}
	func refreshUnreadStories(for account: Account, hashes: [NewsBlurStoryHash]?, updateFetchDate: Date?, completion: @escaping (Result<Void, Error>) -> Void) {
		guard let hashes = hashes, !hashes.isEmpty else {
			if let lastArticleFetch = updateFetchDate {
				self.accountMetadata?.lastArticleFetchStartTime = lastArticleFetch
				self.accountMetadata?.lastArticleFetchEndTime = Date()
			}
			completion(.success(()))
			return
		}
		let numberOfStories = min(hashes.count, 100) // api limit
		let hashesToFetch = Array(hashes[..<numberOfStories])
		caller.retrieveStories(hashes: hashesToFetch) { result in
			switch result {
			case .success((let stories, let date)):
				self.processStories(account: account, stories: stories) { result in
					self.refreshProgress.completeTask()
					if case .failure(let error) = result {
						completion(.failure(error))
						return
					}
					self.refreshUnreadStories(for: account, hashes: Array(hashes[numberOfStories...]), updateFetchDate: date) { result in
						os_log(.debug, log: self.log, "Done refreshing stories.")
						switch result {
						case .success:
							completion(.success(()))
						case .failure(let error):
							completion(.failure(error))
						}
					}
				}
			case .failure(let error):
				completion(.failure(error))
			}
		}
	}
	func mapStoriesToParsedItems(stories: [NewsBlurStory]?) -> Set<ParsedItem> {
		guard let stories = stories else { return Set<ParsedItem>() }
		let parsedItems: [ParsedItem] = stories.map { story in
			let author = Set([ParsedAuthor(name: story.authorName, url: nil, avatarURL: nil, emailAddress: nil)])
			return ParsedItem(syncServiceID: story.storyID, uniqueID: String(story.storyID), feedURL: String(story.feedID), url: story.url, externalURL: nil, title: story.title, language: nil, contentHTML: story.contentHTML, contentText: nil, summary: nil, imageURL: story.imageURL, bannerImageURL: nil, datePublished: story.datePublished, dateModified: nil, authors: author, tags: Set(story.tags ?? []), attachments: nil)
		}
		return Set(parsedItems)
	}
	func sendStoryStatuses(_ statuses: [SyncStatus],
								   throttle: Bool,
								   apiCall: ([String], @escaping (Result<Void, Error>) -> Void) -> Void,
								   completion: @escaping (Result<Void, Error>) -> Void) {
		guard !statuses.isEmpty else {
			completion(.success(()))
			return
		}
		let group = DispatchGroup()
		var errorOccurred = false
		let storyHashes = statuses.compactMap { $0.articleID }
		let storyHashGroups = storyHashes.chunked(into: throttle ? 1 : 5) // api limit
		for storyHashGroup in storyHashGroups {
			group.enter()
			apiCall(storyHashGroup) { result in
				switch result {
				case .success:
					self.database.deleteSelectedForProcessing(storyHashGroup.map { String($0) } )
					group.leave()
				case .failure(let error):
					errorOccurred = true
					os_log(.error, log: self.log, "Story status sync call failed: %@.", error.localizedDescription)
					self.database.resetSelectedForProcessing(storyHashGroup.map { String($0) } )
					group.leave()
				}
			}
		}
		group.notify(queue: DispatchQueue.main) {
			if errorOccurred {
				completion(.failure(NewsBlurError.unknown))
			} else {
				completion(.success(()))
			}
		}
	}
	func syncStoryReadState(account: Account, hashes: [NewsBlurStoryHash]?, completion: @escaping (() -> Void)) {
		guard let hashes = hashes else {
			completion()
			return
		}
		database.selectPendingReadStatusArticleIDs() { result in
			func process(_ pendingStoryHashes: Set<String>) {
				let newsBlurUnreadStoryHashes = Set(hashes.map { $0.hash } )
				let updatableNewsBlurUnreadStoryHashes = newsBlurUnreadStoryHashes.subtracting(pendingStoryHashes)
				account.fetchUnreadArticleIDs { articleIDsResult in
					guard let currentUnreadArticleIDs = try? articleIDsResult.get() else {
						return
					}
					let group = DispatchGroup()
					
					// Mark articles as unread
					let deltaUnreadArticleIDs = updatableNewsBlurUnreadStoryHashes.subtracting(currentUnreadArticleIDs)
					group.enter()
					account.markAsUnread(deltaUnreadArticleIDs) { _ in
						group.leave()
					}
					// Mark articles as read
					let deltaReadArticleIDs = currentUnreadArticleIDs.subtracting(updatableNewsBlurUnreadStoryHashes)
					group.enter()
					account.markAsRead(deltaReadArticleIDs) { _ in
						group.leave()
					}
					
					group.notify(queue: DispatchQueue.main) {
						completion()
					}
				}
			}
			switch result {
			case .success(let pendingArticleIDs):
				process(pendingArticleIDs)
			case .failure(let error):
				os_log(.error, log: self.log, "Sync Story Read Status failed: %@.", error.localizedDescription)
			}
		}
	}
	func syncStoryStarredState(account: Account, hashes: [NewsBlurStoryHash]?, completion: @escaping (() -> Void)) {
		guard let hashes = hashes else {
			completion()
			return
		}
		database.selectPendingStarredStatusArticleIDs() { result in
			func process(_ pendingStoryHashes: Set<String>) {
				let newsBlurStarredStoryHashes = Set(hashes.map { $0.hash } )
				let updatableNewsBlurUnreadStoryHashes = newsBlurStarredStoryHashes.subtracting(pendingStoryHashes)
				account.fetchStarredArticleIDs { articleIDsResult in
					guard let currentStarredArticleIDs = try? articleIDsResult.get() else {
						return
					}
					let group = DispatchGroup()
					
					// Mark articles as starred
					let deltaStarredArticleIDs = updatableNewsBlurUnreadStoryHashes.subtracting(currentStarredArticleIDs)
					group.enter()
					account.markAsStarred(deltaStarredArticleIDs) { _ in
						group.leave()
					}
					// Mark articles as unstarred
					let deltaUnstarredArticleIDs = currentStarredArticleIDs.subtracting(updatableNewsBlurUnreadStoryHashes)
					group.enter()
					account.markAsUnstarred(deltaUnstarredArticleIDs) { _ in
						group.leave()
					}
					group.notify(queue: DispatchQueue.main) {
						completion()
					}
				}
			}
			switch result {
			case .success(let pendingArticleIDs):
				process(pendingArticleIDs)
			case .failure(let error):
				os_log(.error, log: self.log, "Sync Story Starred Status failed: %@.", error.localizedDescription)
			}
		}
	}
	func createFeed(account: Account, feed: NewsBlurFeed?, name: String?, container: Container, completion: @escaping (Result<WebFeed, Error>) -> Void) {
		guard let feed = feed else {
			completion(.failure(NewsBlurError.invalidParameter))
			return
		}
		DispatchQueue.main.async {
			let webFeed = account.createWebFeed(with: feed.name, url: feed.feedURL, webFeedID: String(feed.feedID), homePageURL: feed.homePageURL)
			webFeed.externalID = String(feed.feedID)
			webFeed.faviconURL = feed.faviconURL
			account.addWebFeed(webFeed, to: container) { result in
				switch result {
				case .success:
					if let name = name {
						account.renameWebFeed(webFeed, to: name) { result in
							switch result {
							case .success:
								self.initialFeedDownload(account: account, feed: webFeed, completion: completion)
							case .failure(let error):
								completion(.failure(error))
							}
						}
					} else {
						self.initialFeedDownload(account: account, feed: webFeed, completion: completion)
					}
				case .failure(let error):
					completion(.failure(error))
				}
			}
		}
	}
	func downloadFeed(account: Account, feed: WebFeed, page: Int, completion: @escaping (Result<Void, Error>) -> Void) {
		refreshProgress.addToNumberOfTasksAndRemaining(1)
		caller.retrieveStories(feedID: feed.webFeedID, page: page) { result in
			switch result {
			case .success((let stories, _)):
				// No more stories
				guard let stories = stories, stories.count > 0 else {
					self.refreshProgress.completeTask()
					completion(.success(()))
					return
				}
				let since: Date? = Calendar.current.date(byAdding: .month, value: -3, to: Date())
				self.processStories(account: account, stories: stories, since: since) { result in
					self.refreshProgress.completeTask()
					if case .failure(let error) = result {
						completion(.failure(error))
						return
					}
					// No more recent stories
					if case .success(let hasStories) = result, !hasStories {
						completion(.success(()))
						return
					}
					
					self.downloadFeed(account: account, feed: feed, page: page + 1, completion: completion)
				}
			case .failure(let error):
				completion(.failure(error))
			}
		}
	}
	func initialFeedDownload(account: Account, feed: WebFeed, completion: @escaping (Result<WebFeed, Error>) -> Void) {
		refreshProgress.addToNumberOfTasksAndRemaining(1)
		// Download the initial articles
		downloadFeed(account: account, feed: feed, page: 1) { result in
			self.refreshArticleStatus(for: account) { result in
				switch result {
				case .success:
					self.refreshMissingStories(for: account) { result in
						switch result {
						case .success:
							self.refreshProgress.completeTask()
							DispatchQueue.main.async {
								completion(.success(feed))
							}
						case .failure(let error):
							completion(.failure(error))
						}
					}
				case .failure(let error):
					completion(.failure(error))
				}
			}
		}
	}
	func deleteFeed(for account: Account, with feed: WebFeed, from container: Container?, completion: @escaping (Result<Void, Error>) -> Void) {
		// This error should never happen
		guard let feedID = feed.externalID else {
			completion(.failure(NewsBlurError.invalidParameter))
			return
		}
		refreshProgress.addToNumberOfTasksAndRemaining(1)
		let folderName = (container as? Folder)?.name
		caller.deleteFeed(feedID: feedID, folder: folderName) { result in
			self.refreshProgress.completeTask()
			switch result {
			case .success:
				DispatchQueue.main.async {
					let feedID = feed.webFeedID
					if folderName == nil {
						account.removeWebFeed(feed)
					}
					if let folders = account.folders {
						for folder in folders where folderName != nil && folder.name == folderName {
							folder.removeWebFeed(feed)
						}
					}
					if account.existingWebFeed(withWebFeedID: feedID) != nil {
						account.clearWebFeedMetadata(feed)
					}
					completion(.success(()))
				}
			case .failure(let error):
				DispatchQueue.main.async {
					let wrappedError = AccountError.wrappedError(error: error, account: account)
					completion(.failure(wrappedError))
				}
			}
		}
	}
}
 | 
	mit | 
	72b176c5a570e40cdfc970f082222017 | 29.738819 | 413 | 0.691847 | 3.889316 | false | false | false | false | 
| 
	larryhou/swift | 
	MRCodes/MRCodes/ReadViewController.swift | 
	1 | 
	7967 | 
	//
//  ViewController.swift
//  MRCodes
//
//  Created by larryhou on 13/12/2015.
//  Copyright © 2015 larryhou. All rights reserved.
//
import UIKit
import AVFoundation
class ReadViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
    private var FocusContext: String?
    private var ExposureContext: String?
    private var LensContext: String?
    @IBOutlet weak var torchSwitcher: UISwitch!
    @IBOutlet weak var previewView: CameraPreviewView!
    @IBOutlet weak var metadataView: CameraMetadataView!
    private var session: AVCaptureSession!
    private var activeCamera: AVCaptureDevice?
    override func viewDidLoad() {
        super.viewDidLoad()
        session = AVCaptureSession()
        session.sessionPreset = .photo
        previewView.session = session
        (previewView.layer as! AVCaptureVideoPreviewLayer).videoGravity = .resizeAspectFill
        AVCaptureDevice.requestAccess(for: .video) { (success: Bool) -> Void in
            let status = AVCaptureDevice.authorizationStatus(for: .video)
            if success {
                self.configSession()
            } else {
                print(status, status.rawValue)
            }
        }
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let resultController = presentedViewController as? ResultViewController {
            resultController.animate(visible: false)
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        torchSwitcher.isHidden = true
        if !session.isRunning {
            session.startRunning()
        }
    }
    func applicationWillEnterForeground() {
        metadataView.setMetadataObjects([])
    }
    func findCamera(position: AVCaptureDevice.Position) -> AVCaptureDevice! {
        let list = AVCaptureDevice.devices()
        for device in list {
            if device.position == position {
                return device
            }
        }
        return nil
    }
    func configSession() {
        session.beginConfiguration()
        guard let camera = findCamera(position: .back) else {return}
        self.activeCamera = camera
        do {
            let cameraInput = try AVCaptureDeviceInput(device: camera)
            if session.canAddInput(cameraInput) {
                session.addInput(cameraInput)
            }
            setupCamera(camera: camera)
        } catch {}
        let metadata = AVCaptureMetadataOutput()
        if session.canAddOutput(metadata) {
            session.addOutput(metadata)
            metadata.setMetadataObjectsDelegate(self, queue: .main)
            var metadataTypes = metadata.availableMetadataObjectTypes
            for i in 0..<metadataTypes.count {
                if metadataTypes[i] == .face {
                    metadataTypes.remove(at: i)
                    break
                }
            }
            metadata.metadataObjectTypes = metadataTypes
            print(metadata.availableMetadataObjectTypes)
        }
        session.commitConfiguration()
        session.startRunning()
    }
    func setupCamera(camera: AVCaptureDevice) {
        do {
            try camera.lockForConfiguration()
        } catch {
            return
        }
        if camera.isFocusModeSupported(.continuousAutoFocus) {
            camera.focusMode = .continuousAutoFocus
        }
        if camera.isAutoFocusRangeRestrictionSupported {
//            camera.autoFocusRangeRestriction = .near
        }
        if camera.isSmoothAutoFocusSupported {
            camera.isSmoothAutoFocusEnabled = true
        }
        camera.unlockForConfiguration()
//        camera.addObserver(self, forKeyPath: "adjustingFocus", options: .new, context: &FocusContext)
//        camera.addObserver(self, forKeyPath: "exposureDuration", options: .new, context: &ExposureContext)
        camera.addObserver(self, forKeyPath: "lensPosition", options: .new, context: &LensContext)
    }
    @IBAction func torchStatusChange(_ sender: UISwitch) {
        guard let camera = self.activeCamera else { return }
        guard camera.isTorchAvailable else {return}
        do { try camera.lockForConfiguration() } catch { return }
        if sender.isOn {
            if camera.isTorchModeSupported(.on) {
                try? camera.setTorchModeOn(level: AVCaptureDevice.maxAvailableTorchLevel)
            }
        } else {
            if camera.isTorchModeSupported(.off) {
                camera.torchMode = .off
            }
            checkTorchSwitcher(for: camera)
        }
        camera.unlockForConfiguration()
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        if context == &FocusContext || context == &ExposureContext || context == &LensContext, let camera = object as? AVCaptureDevice {
//            print(camera.exposureDuration.seconds, camera.activeFormat.minExposureDuration.seconds, camera.activeFormat.maxExposureDuration.seconds,camera.iso, camera.lensPosition)
            checkTorchSwitcher(for: camera)
        }
    }
    func checkTorchSwitcher(`for` camera: AVCaptureDevice) {
        if camera.iso >= 400 {
            torchSwitcher.isHidden = false
        } else {
            torchSwitcher.isHidden = !camera.isTorchActive
        }
    }
    // MARK: metadataObjects processing
    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        var codes: [AVMetadataMachineReadableCodeObject] = []
        var faces: [AVMetadataFaceObject] = []
        let layer = previewView.layer as! AVCaptureVideoPreviewLayer
        for item in metadataObjects {
            guard let mrc = layer.transformedMetadataObject(for: item) else {continue}
            switch mrc {
                case is AVMetadataMachineReadableCodeObject:
                    codes.append(mrc as! AVMetadataMachineReadableCodeObject)
                case is AVMetadataFaceObject:
                    faces.append(mrc as! AVMetadataFaceObject)
                default:
                    print(mrc)
            }
        }
        DispatchQueue.main.async {
            self.metadataView.setMetadataObjects(codes)
            self.showMetadataObjects(self.metadataView.mrcObjects)
        }
    }
    func showMetadataObjects(_ objects: [AVMetadataMachineReadableCodeObject]) {
        if let resultController = self.presentedViewController as? ResultViewController {
            resultController.mrcObjects = objects
            resultController.reload()
            resultController.animate(visible: true)
        } else {
            guard let resultController = storyboard?.instantiateViewController(withIdentifier: "ResultViewController") as? ResultViewController else {
                return
            }
            resultController.mrcObjects = objects
            resultController.view.frame = view.frame
            present(resultController, animated: false, completion: nil)
        }
    }
    // MARK: orientation
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        let orientation = UIDevice.current.orientation
        if orientation.isLandscape || orientation.isPortrait {
            let layer = previewView.layer as! AVCaptureVideoPreviewLayer
            if layer.connection != nil {
                layer.connection?.videoOrientation = AVCaptureVideoOrientation(rawValue: orientation.rawValue)!
            }
        }
    }
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .all }
    override var prefersStatusBarHidden: Bool { return true }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
 | 
	mit | 
	c28db28575173dbb9cad816f05a0bb7e | 33.336207 | 182 | 0.638966 | 5.65767 | false | false | false | false | 
| 
	ello/ello-ios | 
	Sources/Views/PostToolbar.swift | 
	1 | 
	8453 | 
	////
///  PostToolbar.swift
//
class PostToolbar: UIToolbar {
    enum Style {
        case white
        case dark
    }
    enum Item {
        case views
        case loves
        case comments
        case repost
        case share
        case space
    }
    var style: Style = .white { didSet { updateStyle() } }
    var postItems: [Item] = [] { didSet { updateItems() } }
    weak var postToolsDelegate: PostToolbarDelegate?
    class ImageLabelAccess {
        let control: ImageLabelControl
        init(control: ImageLabelControl) {
            self.control = control
        }
        var title: String? {
            get { return control.title }
            set { control.title = newValue }
        }
        var isEnabled: Bool {
            get { return control.isEnabled }
            set { control.isEnabled = newValue }
        }
        var isSelected: Bool {
            get { return control.isSelected }
            set { control.isSelected = newValue }
        }
        var isInteractable: Bool {
            get { return control.isUserInteractionEnabled }
            set { control.isUserInteractionEnabled = newValue }
        }
    }
    private var viewsItem: UIBarButtonItem!
    private var viewsControl: ImageLabelControl {
        return self.viewsItem.customView as! ImageLabelControl
    }
    private var lovesItem: UIBarButtonItem!
    private var lovesControl: ImageLabelControl {
        return self.lovesItem.customView as! ImageLabelControl
    }
    private var commentsItem: UIBarButtonItem!
    private var commentsControl: ImageLabelControl {
        return self.commentsItem.customView as! ImageLabelControl
    }
    private var repostItem: UIBarButtonItem!
    private var repostControl: ImageLabelControl {
        return self.repostItem.customView as! ImageLabelControl
    }
    private var shareItem: UIBarButtonItem!
    private var shareControl: UIControl {
        return self.shareItem.customView as! UIControl
    }
    var views: ImageLabelAccess { return ImageLabelAccess(control: viewsControl) }
    var comments: ImageLabelAccess { return ImageLabelAccess(control: commentsControl) }
    var loves: ImageLabelAccess { return ImageLabelAccess(control: lovesControl) }
    var reposts: ImageLabelAccess { return ImageLabelAccess(control: repostControl) }
    required override init(frame: CGRect) {
        super.init(frame: frame)
        updateStyle()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        updateStyle()
    }
    convenience init() {
        self.init(frame: .zero)
    }
    private func updateStyle() {
        let selectedColor: UIColor
        let isDark: Bool
        switch style {
        case .white:
            backgroundColor = .white
            setBackgroundImage(nil, forToolbarPosition: .any, barMetrics: .default)
            setShadowImage(nil, forToolbarPosition: .any)
            selectedColor = .black
            isDark = false
        case .dark:
            backgroundColor = .clear
            setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default)
            setShadowImage(UIImage(), forToolbarPosition: .any)
            selectedColor = .white
            isDark = true
        }
        let oldViewsControl = viewsItem?.customView as? ImageLabelControl
        viewsItem = ElloPostToolBarOption.views.barButtonItem(isDark: isDark)
        viewsControl.addTarget(self, action: #selector(viewsButtonTapped), for: .touchUpInside)
        if let oldViewsControl = oldViewsControl {
            viewsControl.isEnabled = oldViewsControl.isEnabled
            viewsControl.isSelected = oldViewsControl.isSelected
            viewsControl.isUserInteractionEnabled = oldViewsControl.isUserInteractionEnabled
        }
        let oldLovesControl = lovesItem?.customView as? ImageLabelControl
        lovesItem = ElloPostToolBarOption.loves.barButtonItem(isDark: isDark)
        lovesControl.addTarget(self, action: #selector(lovesButtonTapped), for: .touchUpInside)
        if let oldLovesControl = oldLovesControl {
            lovesControl.isEnabled = oldLovesControl.isEnabled
            lovesControl.isSelected = oldLovesControl.isSelected
            lovesControl.isUserInteractionEnabled = oldLovesControl.isUserInteractionEnabled
        }
        let oldCommentsControl = commentsItem?.customView as? ImageLabelControl
        commentsItem = ElloPostToolBarOption.comments.barButtonItem(isDark: isDark)
        commentsControl.addTarget(
            self,
            action: #selector(commentsButtonTapped),
            for: .touchUpInside
        )
        if let oldCommentsControl = oldCommentsControl {
            commentsControl.isEnabled = oldCommentsControl.isEnabled
            commentsControl.isSelected = oldCommentsControl.isSelected
            commentsControl.isUserInteractionEnabled = oldCommentsControl.isUserInteractionEnabled
        }
        let oldRepostControl = repostItem?.customView as? ImageLabelControl
        repostItem = ElloPostToolBarOption.repost.barButtonItem(isDark: isDark)
        repostControl.addTarget(self, action: #selector(repostButtonTapped), for: .touchUpInside)
        if let oldRepostControl = oldRepostControl {
            repostControl.isEnabled = oldRepostControl.isEnabled
            repostControl.isSelected = oldRepostControl.isSelected
            repostControl.isUserInteractionEnabled = oldRepostControl.isUserInteractionEnabled
        }
        let oldShareControl = shareItem?.customView as? UIControl
        let control = UIButton()
        control.setImage(.share, imageStyle: .normal, for: .normal)
        control.setImage(.share, imageStyle: isDark ? .white : .selected, for: .selected)
        shareItem = UIBarButtonItem(customView: control)
        shareControl.addTarget(self, action: #selector(shareButtonTapped), for: .touchUpInside)
        if let oldShareControl = oldShareControl {
            shareControl.isEnabled = oldShareControl.isEnabled
            shareControl.isSelected = oldShareControl.isSelected
            shareControl.isUserInteractionEnabled = oldShareControl.isUserInteractionEnabled
        }
        let controls = [viewsControl, lovesControl, commentsControl, repostControl]
        for control in controls {
            control.selectedColor = selectedColor
        }
        updateItems()
    }
    private func updateItems() {
        self.items = Array(
            postItems.map { item in
                switch item {
                case .views: return viewsItem
                case .loves: return lovesItem
                case .comments: return commentsItem
                case .repost: return repostItem
                case .share: return shareItem
                case .space: return fixedItem()
                }
            }.flatMap { [flexibleItem(), $0] }.dropFirst()
        )
    }
    private func fixedItem() -> UIBarButtonItem {
        let item = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        item.width = 44
        return item
    }
    private func flexibleItem() -> UIBarButtonItem {
        return UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    }
}
extension PostToolbar {
    func commentsAnimate() {
        commentsControl.animate()
    }
    func commentsFinishAnimation() {
        commentsControl.finishAnimation()
    }
    @objc
    func viewsButtonTapped() {
        postToolsDelegate?.toolbarViewsButtonTapped(viewsControl: viewsControl)
    }
    @objc
    func commentsButtonTapped() {
        postToolsDelegate?.toolbarCommentsButtonTapped(commentsControl: commentsControl)
    }
    @objc
    func lovesButtonTapped() {
        postToolsDelegate?.toolbarLovesButtonTapped(lovesControl: lovesControl)
    }
    @objc
    func repostButtonTapped() {
        postToolsDelegate?.toolbarRepostButtonTapped(repostControl: repostControl)
    }
    @objc
    func shareButtonTapped() {
        postToolsDelegate?.toolbarShareButtonTapped(shareControl: shareControl)
    }
}
protocol PostToolbarDelegate: class {
    func toolbarViewsButtonTapped(viewsControl: ImageLabelControl)
    func toolbarCommentsButtonTapped(commentsControl: ImageLabelControl)
    func toolbarLovesButtonTapped(lovesControl: ImageLabelControl)
    func toolbarRepostButtonTapped(repostControl: ImageLabelControl)
    func toolbarShareButtonTapped(shareControl: UIView)
}
 | 
	mit | 
	da923d616c6895db583c29056c8c8b10 | 34.368201 | 98 | 0.667929 | 5.817619 | false | false | false | false | 
| 
	elslooo/hoverboard | 
	Hoverboard/SessionWindow.swift | 
	1 | 
	4472 | 
	/*
 * Copyright (c) 2017 Tim van Elsloo
 *
 * 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 AppKit
import Foundation
import HoverboardKit
/**
 * The session window is a slightly blurred hud window that appears for a little
 * over a second during which the user can adjust the position and size of the
 * foreground window.
 */
class SessionWindow : NSWindow {
    /**
     * The effect view is the background view of our hud window that gives it a
     * blurry appearance.
     */
    let effectView = NSVisualEffectView()
    /**
     * The image view contains our logo / symbol (⌘). This is shown until the
     * user presses the first key, after which the symbol disappears and the
     * grid is shown.
     */
    let imageView  = NSImageView()
    /**
     * The grid view reflects the current positioning of the window. The window
     * controller accesses this property to update its grid.
     */
    let gridView   = GridView()
    /**
     * This function initializes and configures the session window.
     */
    init(frame: CGRect) {
        super.init(contentRect: frame,
                     styleMask: .borderless,
                       backing: .buffered,
                         defer: false)
        self.level = Int(CGWindowLevelKey.floatingWindow.rawValue)
        self.isOpaque             = false
        self.backgroundColor      = .clear
        self.isReleasedWhenClosed = false
        self.setupEffectView()
        self.setupMaskImage()
        self.setupImageView()
        self.setupGridView()
    }
    /**
     * This function configures the effect view.
     */
    func setupEffectView() {
        guard let contentView = self.contentView else {
            return
        }
        self.effectView.frame    = contentView.bounds
        self.effectView.material = .light
        self.effectView.state    = .active
        contentView.addSubview(self.effectView)
    }
    /**
     * This function configures a mask image for the effect view. This is
     * necessary because by default, the effect view is rectangular and we want
     * it to have round corners (like the rest of macOS).
     */
    func setupMaskImage() {
        let image = NSImage(size: self.effectView.bounds.size, flipped: false) {
            (frame) -> Bool in
            let path = NSBezierPath(roundedRect: frame,
                                        xRadius: 20,
                                        yRadius: 20)
            NSColor.black.setFill()
            path.fill()
            return true
        }
        self.effectView.maskImage = image
    }
    /**
     * This function configures the logo / symbol image view.
     */
    func setupImageView() {
        guard let contentView = self.contentView else { return }
        self.imageView.frame = contentView.bounds
        self.imageView.image = NSImage(named: "Session-window-icon")
        // Make sure that it is templated so that it appears vibrant in the
        // effect view.
        self.imageView.image?.isTemplate = true
        self.effectView.addSubview(self.imageView)
    }
    /**
     * This function configures a new grid view. As long as its grid property is
     * nill, it won't be visible to the user.
     */
    func setupGridView() {
        guard let contentView = self.contentView else { return }
        self.gridView.frame = contentView.bounds
        self.effectView.addSubview(self.gridView)
    }
}
 | 
	mit | 
	225e56cc274b73ec19f8d7071674b2fd | 33.122137 | 80 | 0.643848 | 4.822006 | false | false | false | false | 
| 
	tectijuana/patrones | 
	Bloque1SwiftArchivado/PracticasSwift/AlvarezCorralMiguel/prog7.swift | 
	1 | 
	831 | 
	/*
Nombre del programa: Suma de 1 a n cuadrados
  Autor: Alvarez Corral Miguel Angel 13211384
  Fecha de inicio: 13-02-2017
  Descripción:
Encontrar la suma de los cuadrados de los enteros del 1 al N. Es decir, su programa calculara:
1^2 + 2^2 + 3^2 + ... + N^2
*/
//Importación de librerías
import Foundation
//declaración de constantes
let N = 21  //Se puede modifcar el valor de N para obtener distintos resultados.
//contador
var i = 1
//variable donde se guarda la suma
var suma = 0
//variable donde se guardara la cadena de la suma
var texto = ""
print("Suma de N^2 valores")
print("N = \(N)")
//suma de los N valores
while i<=N
{
	var cuad = i*i
	suma = suma + cuad
	//Concatenacion de la suma
	if i != N
	{texto += "\(cuad)+"}
	else
	{texto += "\(cuad)"}
	//incremento	
	i = i+1
}
print("\(texto)=\(suma)")
 | 
	gpl-3.0 | 
	9f4fa0c2ed5a07b9a860dc1584617786 | 16.978261 | 94 | 0.663845 | 2.756667 | false | false | false | false | 
| 
	smileyborg/PureLayout | 
	PureLayout/Example-iOS/Demos/iOSDemo4ViewController.swift | 
	4 | 
	4013 | 
	//
//  iOSDemo4ViewController.swift
//  PureLayout Example-iOS
//
//  Copyright (c) 2015 Tyler Fox
//  https://github.com/PureLayout/PureLayout
//
import UIKit
import PureLayout
@objc(iOSDemo4ViewController)
class iOSDemo4ViewController: UIViewController {
    
    let blueLabel: UILabel = {
        let label = UILabel.newAutoLayout()
        label.backgroundColor = .blue
        label.numberOfLines = 1
        label.lineBreakMode = .byClipping
        label.textColor = .white
        label.text = NSLocalizedString("Lorem ipsum", comment: "")
        return label
        }()
    let redLabel: UILabel = {
        let label = UILabel.newAutoLayout()
        label.backgroundColor = .red
        label.numberOfLines = 0
        label.textColor = .white
        label.text = NSLocalizedString("Lorem ipsum", comment: "")
        return label
        }()
    let greenView: UIView = {
        let view = UIView.newAutoLayout()
        view.backgroundColor = .green
        return view
        }()
    var didSetupConstraints = false
    
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor(white: 0.1, alpha: 1.0)
        
        view.addSubview(blueLabel)
        view.addSubview(redLabel)
        view.addSubview(greenView)
        
        view.setNeedsUpdateConstraints() // bootstrap Auto Layout
    }
    
    override func updateViewConstraints() {
        /**
        NOTE: To observe the effect of leading & trailing attributes, you need to change the OS language setting from a left-to-right language,
        such as English, to a right-to-left language, such as Arabic.
        
        This demo project includes localized strings for Arabic, so you will see the Lorem Ipsum text in Arabic if the system is set to that language.
        
        See this method of easily forcing the simulator's language from Xcode: http://stackoverflow.com/questions/8596168/xcode-run-project-with-specified-localization
        */
        
        let smallPadding: CGFloat = 20.0
        let largePadding: CGFloat = 50.0
        
        if (!didSetupConstraints) {
            // Prevent the blueLabel from compressing smaller than required to fit its single line of text
            blueLabel.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .vertical)
            
            // Position the single-line blueLabel at the top of the screen spanning the width, with some small insets
            blueLabel.autoPin(toTopLayoutGuideOf: self, withInset: smallPadding)
            blueLabel.autoPinEdge(toSuperviewEdge: .leading, withInset: smallPadding)
            blueLabel.autoPinEdge(toSuperviewEdge: .trailing, withInset: smallPadding)
            
            // Make the redLabel 60% of the width of the blueLabel
            redLabel.autoMatch(.width, to: .width, of: blueLabel, withMultiplier: 0.6)
            
            // The redLabel is positioned below the blueLabel, with its leading edge to its superview, and trailing edge to the greenView
            redLabel.autoPinEdge(.top, to: .bottom, of: blueLabel, withOffset: smallPadding)
            redLabel.autoPinEdge(toSuperviewEdge: .leading, withInset: smallPadding)
            redLabel.autoPinEdge(toSuperviewEdge: .bottom, withInset: largePadding)
            
            // The greenView is positioned below the blueLabel, with its leading edge to the redLabel, and trailing edge to its superview
            greenView.autoPinEdge(.leading, to: .trailing, of: redLabel, withOffset: largePadding)
            greenView.autoPinEdge(.top, to: .bottom, of: blueLabel, withOffset: smallPadding)
            greenView.autoPinEdge(toSuperviewEdge: .trailing, withInset: smallPadding)
            
            // Match the greenView's height to its width (keeping a consistent aspect ratio)
            greenView.autoMatch(.width, to: .height, of: greenView)
            
            didSetupConstraints = true
        }
        
        super.updateViewConstraints()
    }
}
 | 
	mit | 
	13c4b44fd1550ba322e062b8fb752acd | 41.691489 | 167 | 0.651881 | 5.301189 | false | false | false | false | 
| 
	wentingwei/develop | 
	ZombieConga/ZombieConga/GameOverScene.swift | 
	1 | 
	1331 | 
	//
//  GameOverScene.swift
//  ZombieConga
//
//  Created by wentingwei on 14/12/1.
//  Copyright (c) 2014年 wentingwei. All rights reserved.
//
import Foundation
import SpriteKit
class GameOverScene : SKScene {
    let won:Bool
    init(size: CGSize,won:Bool) {
        self.won = won
        super.init(size: size)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func didMoveToView(view: SKView) {
        var background:SKSpriteNode
        if won {
            background = SKSpriteNode(imageNamed: "YouWin")
            
        }else{
            background = SKSpriteNode(imageNamed: "YouLose")
        }
        background.position = CGPoint(x: size.width/2, y: size.height/2)
        
        addChild(background)
    }
 
#if os(iOS)
    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
        let gameScene = GameScene(size: size)
        let reveal = SKTransition.flipHorizontalWithDuration(0.5)
        view?.presentScene(gameScene, transition: reveal)
    }
#else
    override func mouseDown(theEvent: NSEvent) {
        let gameScene = GameScene(size: size)
        let reveal = SKTransition.flipHorizontalWithDuration(0.5)
        view?.presentScene(gameScene, transition: reveal)
    }
#endif
} | 
	lgpl-3.0 | 
	7f10a14ef5a45e04e3abc823248d62fc | 25.078431 | 74 | 0.633559 | 4.259615 | false | false | false | false | 
| 
	mohsinalimat/ActionButton | 
	Source/ActionButton.swift | 
	2 | 
	8108 | 
	// ActionButton.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 ActionButton
//
// 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
typealias ActionButtonAction = (ActionButton) -> Void
public class ActionButton: NSObject {
    
    var active: Bool = false
    var action: ActionButtonAction?
    var items: [ActionButtonItem]?
    var backgroundColor: UIColor? {
        willSet {
            floatButton.backgroundColor = newValue
        }
    }
    
    private var floatButton: UIButton!
    private var contentView: UIView!
    private var parentView: UIView!
    private var blurVisualEffect: UIVisualEffectView!
    private let itemOffset = -55
    private let floatButtonRadius = 50
    
    public init(attachedToView view: UIView, items: [ActionButtonItem]?) {
        super.init()
        
        self.parentView = view
        self.items = items
        let bounds = self.parentView.bounds
        
        self.floatButton = UIButton.buttonWithType(.Custom) as! UIButton
        self.floatButton.layer.cornerRadius = CGFloat(floatButtonRadius / 2)
        self.floatButton.layer.shadowOpacity = 1
        self.floatButton.layer.shadowRadius = 2
        self.floatButton.layer.shadowOffset = CGSize(width: 1, height: 1)
        self.floatButton.layer.shadowColor = UIColor.grayColor().CGColor
        self.floatButton.setTitle("+", forState: .Normal)
        self.floatButton.backgroundColor = UIColor(red: 238.0/255.0, green: 130.0/255.0, blue: 34.0/255.0, alpha:1.0)
        self.floatButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0)
        self.floatButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 35)
        self.floatButton.userInteractionEnabled = true
        self.floatButton.setTranslatesAutoresizingMaskIntoConstraints(false)
        
        self.floatButton.addTarget(self, action: Selector("buttonTapped:"), forControlEvents: .TouchUpInside)
        self.floatButton.addTarget(self, action: Selector("buttonTouchDown:"), forControlEvents: .TouchDown)
        self.parentView.addSubview(self.floatButton)
        self.contentView = UIView(frame: bounds)
        self.blurVisualEffect = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight))
        self.blurVisualEffect.frame = self.contentView.frame
        self.contentView.addSubview(self.blurVisualEffect)
        
        let tap = UITapGestureRecognizer(target: self, action: Selector("backgroundTapped:"))
        self.contentView.addGestureRecognizer(tap)
        
        self.installConstraints()
    }
    
    required public init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Auto Layout Methods
    
    private func installConstraints() {
        let views = ["floatButton":self.floatButton, "parentView":self.parentView]
        let width = NSLayoutConstraint.constraintsWithVisualFormat("H:[floatButton(\(floatButtonRadius))]", options: nil, metrics: nil, views: views)
        let height = NSLayoutConstraint.constraintsWithVisualFormat("V:[floatButton(\(floatButtonRadius))]", options: nil, metrics: nil, views: views)
        self.floatButton.addConstraints(width)
        self.floatButton.addConstraints(height)
        
        let trailingSpacing = NSLayoutConstraint.constraintsWithVisualFormat("V:[floatButton]-15-|", options: nil, metrics: nil, views: views)
        let bottomSpacing = NSLayoutConstraint.constraintsWithVisualFormat("H:[floatButton]-15-|", options: nil, metrics: nil, views: views)
        self.parentView.addConstraints(trailingSpacing)
        self.parentView.addConstraints(bottomSpacing)
    }
    
    // MARK: - Button Actions Methods
    
    func buttonTapped(sender: UIControl) {
        animatePressingWithScale(1.0)
        
        if let unwrappedAction = self.action {
            unwrappedAction(self)
        }
    }
    
    func buttonTouchDown(sender: UIButton) {
        animatePressingWithScale(0.9)
    }
    
    // MARK: - Gesture Recognizer Methods
    
    func backgroundTapped(gesture: UIGestureRecognizer) {
        if self.active {
            self.toggle()
        }
    }
    
    // MARK: - Custom Methods
    func toggleMenu() {
        self.placeButtonItems()
        self.toggle()
    }
    
    // MARK: - Float Button Items Placement
    
    private func placeButtonItems() {
        if let optionalItems = self.items {
            for item in optionalItems {
                item.view.center = CGPoint(x: self.floatButton.center.x - 83, y: self.floatButton.center.y)
                item.view.removeFromSuperview()
                
                self.contentView.addSubview(item.view)
            }
        }
    }
    
    // MARK - Float Menu Methods
    
    private func toggle() {
        self.animateMenu()
        self.showBlur()
        
        self.active = !self.active
    }
    
    private func animateMenu() {
        let rotation = self.active ? 0 : CGFloat(M_PI_4)
        
        UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: nil, animations: {
            self.floatButton.transform = CGAffineTransformMakeRotation(rotation)
    
            if self.active == false {
                self.contentView.alpha = 1.0
                
                if let optionalItems = self.items {
                    for (index, item) in enumerate(optionalItems) {
                        let offset = index + 1
                        let translation = self.itemOffset * offset
                        item.view.transform = CGAffineTransformMakeTranslation(0, CGFloat(translation))
                        item.view.alpha = 1
                    }
                }
            } else {
                self.contentView.alpha = 0.0
                
                if let optionalItems = self.items {
                    for item in optionalItems {
                        item.view.transform = CGAffineTransformMakeTranslation(0, 0)
                        item.view.alpha = 0
                    }
                }
            }
        }, completion: {completed in
            if self.active == false {
                self.hideBlur()
            }
        })
    }
    
    private func animateClick() {
        UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: .Repeat | .Autoreverse, animations: {
            self.floatButton.transform = CGAffineTransformMakeScale(1.2, 1.2)
        }, completion: nil)
    }
    
    private func showBlur() {
        self.parentView.insertSubview(self.contentView, belowSubview: self.floatButton)
    }
    
    private func hideBlur() {
        self.contentView.removeFromSuperview()
    }
    
    private func animatePressingWithScale(scale: CGFloat) {
        UIView.animateWithDuration(0.2, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: nil, animations: {
            self.floatButton.transform = CGAffineTransformMakeScale(scale, scale)
        }, completion: nil)
    }
}
 | 
	mit | 
	fd4a913f5ab3cab384fae679826bbad4 | 38.745098 | 151 | 0.641959 | 5.023544 | false | false | false | false | 
| 
	5calls/ios | 
	FiveCalls/FiveCalls/StreakCounter.swift | 
	3 | 
	3201 | 
	//
//  StreakCounter.swift
//  FiveCalls
//
//  Created by Nikrad Mahdi on 3/10/17.
//  Copyright © 2017 5calls. All rights reserved.
//
import Foundation
struct StreakCounter {
    
    enum IntervalType {
        case Daily
        case Weekly
    }
    
    let dates: [Date]
    let referenceDate: Date
    
    init(dates: [Date], referenceDate: Date) {
        self.dates = dates
        self.referenceDate = referenceDate
    }
    
    var daily: Int {
        return getStreakFor(intervalType: .Daily)
    }
    
    var weekly: Int {
        return getStreakFor(intervalType: .Weekly)
    }
    func getStreakFor(intervalType: IntervalType) -> Int {
        var count = 0
        
        // No events
        if (self.dates.count == 0) {
            return count
        }
        
        var intervalsApart: (Date, Date) -> Int?
        switch intervalType {
        case .Daily:
            intervalsApart = StreakCounter.daysApart
        case .Weekly:
            intervalsApart = StreakCounter.weeksApart
        }
        
        let datesDescending = self.dates.sorted(by: { (d1, d2) -> Bool in
            return d1 > d2
        })
        
        let latestDate = datesDescending[0]
        guard let intervals = intervalsApart(latestDate, self.referenceDate) else {
            return count
        }
        
        // An event hasn't occurred in this interval or the last interval
        if (intervals > 1) {
            return count
        }
        count += 1
        if (dates.count == 1) {
            return count
        }
        
        var prevDate = latestDate
        for nextDate in datesDescending[1...(datesDescending.count - 1)] {
            if let intervals = intervalsApart(nextDate, prevDate), intervals <= 1 {
                if (intervals == 1) {
                    count += 1
                }
                prevDate = nextDate
                continue
            }
            
            break
        }
        
        return count
    }
    
    static func daysApart(from: Date, to: Date) -> Int? {
        let calendar = Calendar.current
        let fromDate = calendar.startOfDay(for: from)
        let toDate = calendar.startOfDay(for: to)
        let dateComponents = calendar.dateComponents([.day], from: fromDate, to: toDate)
        guard let days = dateComponents.day else {
            return nil
        }
        
        return abs(days)
    }
    
    static func weeksApart(from: Date, to: Date) -> Int? {
        var calendar = Calendar.current
        // Start weeks on Mondays
        calendar.firstWeekday = 2
        let calComponents: Set<Calendar.Component> = [.weekOfYear, .yearForWeekOfYear]
        guard let fromDate = calendar.date(from: calendar.dateComponents(calComponents, from: from)) else {
            return nil
        }
        guard let toDate = calendar.date(from: calendar.dateComponents(calComponents, from: to)) else {
            return nil
        }
        
        let dateComponents = calendar.dateComponents([.weekOfYear], from: fromDate, to: toDate)
        guard let weeks = dateComponents.weekOfYear else {
            return nil
        }
        
        return abs(weeks)
    }
}
 | 
	mit | 
	c31f4a833a382f43f9d1474b614a154a | 26.586207 | 107 | 0.54625 | 4.819277 | false | false | false | false | 
| 
	xuech/OMS-WH | 
	OMS-WH/Classes/Home/View/Cell/HomeCollectionViewCell.swift | 
	1 | 
	2508 | 
	//
//  HomeCollectionViewCell.swift
//  OMSOwner
//
//  Created by gwy on 2017/4/26.
//  Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
class HomeCollectionViewCell: UICollectionViewCell {
    
    var index : IndexPath? {
        didSet {
            if let index = index {
                titleLabel.text = titleArr[index.row]
                iconView.image = iconArr[index.row]
            }
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func setupUI()
    {
        contentView.addSubview(iconView)
        contentView.addSubview(titleLabel)
        contentView.addSubview(lineView)
        contentView.addSubview(lineView2)
        
        iconView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.size.equalTo(CGSize(width: 35, height: 35))
            make.top.equalTo(20)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.height.equalTo(1)
            make.bottom.equalTo(self)
            make.left.right.equalTo(self)
        }
        
        lineView2.snp.makeConstraints { (make) in
            make.top.bottom.equalTo(self)
            make.width.equalTo(1)
            make.right.equalTo(self)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(iconView.snp.bottom).offset(5)
            make.centerX.equalTo(self)
            
        }
    }
    
    // MARK: - 懒加载控件
    private lazy var lineView : UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.groupTableViewBackground
        return view
    }()
    private lazy var lineView2 : UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.groupTableViewBackground
        return view
    }()
    private lazy var iconView = UIImageView()
    private lazy var titleLabel : UILabel = {
        let label = UILabel(textString: "订单", color: UIColor.gray, fontSize: 14, bgColor: UIColor.white)
        return label
    }()
    
    lazy var titleArr = ["库存查询","常用联系人","超时未返库","全部订单"]
    lazy var iconArr = [#imageLiteral(resourceName: "h_stockSearch"),#imageLiteral(resourceName: "h_contactPeople"),#imageLiteral(resourceName: "h_notReturn"),#imageLiteral(resourceName: "h_allOrder")]
}
 | 
	mit | 
	5f1ec564c15574958defd993515d92c6 | 28.578313 | 201 | 0.588595 | 4.521179 | false | false | false | false | 
| 
	avito-tech/Marshroute | 
	Marshroute/Sources/Transitions/TransitionAnimationsLaunching/PopoverNavigation/Presentation/PopoverNavigationPresentationAnimationLaunchingContext.swift | 
	1 | 
	2265 | 
	import UIKit
/// Описание параметров запуска анимаций показа UIPopoverController'а, содержащего UINavigationController
public struct PopoverNavigationPresentationAnimationLaunchingContext {
    /// стиль перехода
    public let transitionStyle: PopoverTransitionStyle
    
    /// контроллер, лежащий в поповере, который нужно показать
    public private(set) weak var targetViewController: UIViewController?
    
    /// контроллер, лежащий в поповере, который нужно показать
    public private(set) weak var targetNavigationController: UINavigationController?
    
    // поповер, который нужно показать
    public private(set) weak var popoverController: UIPopoverController?
    
    /// аниматор, выполняющий анимации прямого и обратного перехода
    public let animator: PopoverNavigationTransitionsAnimator
    
    public init(
        transitionStyle: PopoverTransitionStyle,
        targetViewController: UIViewController,
        targetNavigationController: UINavigationController,
        popoverController: UIPopoverController,
        animator: PopoverNavigationTransitionsAnimator)
    {
        self.transitionStyle = transitionStyle
        self.targetViewController = targetViewController
        self.targetNavigationController = targetNavigationController
        self.popoverController = popoverController
        self.animator = animator
    }
    
    /// контроллер, над которым появится поповер
    public weak var sourceViewController: UIViewController?
    
    public var isDescribingScreenThatWasAlreadyDismissedWithoutInvokingMarshroute: Bool
    {
        if targetViewController == nil {
            return true
        }
        
        if popoverController?.isPopoverVisible != true { 
            marshrouteAssertionFailure(
                """
                It looks like \(targetViewController as Any) did not deallocate due to some retain cycle! 
                """
            )
            return true
        }
        
        return false
    }
}
 | 
	mit | 
	72a2612c97fbd12995c7e30664023cf3 | 35.944444 | 106 | 0.701754 | 5.833333 | false | false | false | false | 
| 
	gintsmurans/SwiftExtensions | 
	Sources/Examples/Config.swift | 
	2 | 
	564 | 
	//
//  Config.swift
//
//  Created by Gints Murans on 08.02.2018.
//  Copyright © 2018. g. 4Apps. All rights reserved.
//
struct Config {
    struct vpn {
        static let ip = "11.11.11.11"
        static let secret = "XX"
        static let username = "YY"
        static let password = "ZZ"
        static let description = "Work"
        static let version = 5
    }
    struct api {
        static let domain = "example.com"
        static let username = "AA"
        static let password = "BB"
        static let baseUrl = "https://example.com"
    }
}
 | 
	mit | 
	74cbfce660581758ef49ce6765c18613 | 22.458333 | 52 | 0.561279 | 3.679739 | false | true | false | false | 
| 
	dalu93/SwiftHelpSet | 
	Sources/Utilities/Each.swift | 
	1 | 
	4894 | 
	//
//  Each.swift
//  SwiftHelpSet
//
//  Created by Luca D'Alberti on 9/5/16.
//  Copyright © 2016 dalu93. All rights reserved.
//
import Foundation
// MARK: - Each declaratiom
/// The `Each` class allows the user to easily create a scheduled action
public class Each {
    
    enum SecondsMultiplierType {
        case toMilliseconds
        case toSeconds
        case toMinutes
        case toHours
        
        var value: Double {
            switch self {
            case .toMilliseconds:   return 1/60
            case .toSeconds:        return 1
            case .toMinutes:        return 60
            case .toHours:          return 3600
            }
        }
    }
    
    // MARK: - Private properties
    /// The timer interval in seconds
    private let _value: TimeInterval
    
    /// The multiplier. If nil when using it, the configuration didn't go well,
    /// the app will crash
    fileprivate var _multiplier: Double? = nil
    
    /// The definitive time interval to use for the timer. If nil, the app will crash
    private var _timeInterval: TimeInterval? {
        guard let _multiplier = _multiplier else { return nil }
        return _multiplier * _value
    }
    
    /// The action to perform when the timer is triggered
    fileprivate var _performClosure: VoidBoolClosure?
    
    /// The timer instance
    private weak var _timer: Timer?
    
    
    // MARK: - Public properties
    /// Instance that runs the specific interval in milliseconds
    lazy var milliseconds:  Each = self._makeEachWith(value: self._value, multiplierType: .toMilliseconds)
    
    /// Instance that runs the specific interval in seconds
    lazy var seconds:       Each = self._makeEachWith(value: self._value, multiplierType: .toSeconds)
    
    /// /// Instance that runs the specific interval in minutes
    lazy var minutes:       Each = self._makeEachWith(value: self._value, multiplierType: .toMinutes)
    
    /// Instance that runs the specific interval in hours
    lazy var hours:         Each = self._makeEachWith(value: self._value, multiplierType: .toHours)
    
    /// Timer is stopped or not
    public var isStopped = true
    
    
    // MARK: - Lifecycle
    /**
     Initialize a new `Each` object with an abstract value.
     Remember to use the variables `milliseconds`, `seconds`, `minutes` and
     `hours` to get the exact configuration
     
     - parameter value: The abstract value that describes the interval together
                        with the time unit
     
     - returns: A new `Each` uncompleted instance
     */
    public init(_ value: TimeInterval) {
        self._value = value
    }
    
    deinit {
        _timer?.invalidate()
    }
    
    
    // MARK: - Public methods
    /**
     Starts the timer and performs the action whenever the timer is triggered
     The closure should return a boolean that indicates to stop or not the timer after
     the trigger. Return `false` to continue, return `true` to stop it
     
     - parameter closure: The closure to execute whenever the timer is triggered.
     The closure should return a boolean that indicates to stop or not the timer after
     the trigger. Return `false` to continue, return `true` to stop it
     */
    public func perform(closure: @escaping VoidBoolClosure) -> Each {
        guard _timer == nil else { return self }
        guard let interval = _timeInterval else { fatalError("Please, speficy the time unit by using `milliseconds`, `seconds`, `minutes` abd `hours` properties") }
        
        isStopped = false
        _performClosure = closure
        _timer = Timer.scheduledTimer(
            timeInterval: interval,
            target: self,
            selector: .Triggered,
            userInfo: nil,
            repeats: true
        )
        
        return self
    }
    
    
    /**
     Stops the timer
     */
    public func stop() {
        _timer?.invalidate()
        _timer = nil
        
        isStopped = true
    }
    
    /**
     Restarts the timer
     */
    public func restart() {
        guard let _performClosure = _performClosure else { fatalError("Don't call the method `start()` in this case. The first time the timer is started automatically") }
        
        _ = perform(closure: _performClosure)
    }
}
// MARK: - Actions
fileprivate extension Each {
    @objc func _trigger(timer: Timer) {
        let stopTimer = _performClosure?() ?? false
        
        guard stopTimer else { return }
        stop()
    }
}
// MARK: - Builders
private extension Each {
    func _makeEachWith(value: TimeInterval, multiplierType: SecondsMultiplierType) -> Each {
        let each = Each(value)
        each._multiplier = multiplierType.value
        
        return each
    }
}
// MARK: - Selectors
private extension Selector {
    static let Triggered = #selector(Each._trigger(timer:))
}
 | 
	mit | 
	f2360456999b46e81a3cba91575b46e4 | 29.203704 | 170 | 0.612712 | 4.830207 | false | false | false | false | 
| 
	skerkewitz/SwignalR | 
	SwignalR/Classes/Transports/LongPollingTransport.swift | 
	1 | 
	8392 | 
	//
//  LongPollingTransport.swift
//  SignalR
//
//  Created by Alex Billingsley on 10/17/11.
//  Copyright (c) 2011 DyKnow LLC. (http://dyknow.com/)
//  Created by Stefan Kerkewitz on 03/03/2017.
//
//  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 Alamofire
/**
 * Long polling does not create a persistent connection, but instead polls the server with a request that stays open
 * until the server responds, at which point the connection closes, and a new connection is requested immediately.
 * This may introduce some latency while the connection resets.
 */
final class SRLongPollingTransport: SRHttpBasedTransport {
    /**
     * The time to wait after a connection drops to try reconnecting.
     *
     * By default, this is 5 seconds
     */
    let reconnectDelay: TimeInterval = 5.0
    /**
     * The time to wait after an error happens to continue polling.
     *
     * By default, this is 2 seconds
     */
    let errorDelay: TimeInterval = 2.0
    var pollingOperationQueue: OperationQueue
    init() {
        self.pollingOperationQueue = OperationQueue()
        self.pollingOperationQueue.maxConcurrentOperationCount = 1
        super.init(name: "longPolling", supportsKeepAlive: false)
    }
    override func negotiate(_ connection: SRConnectionInterface, connectionData: String, completionHandler block: @escaping (SRNegotiationResponse?, NSError?) -> ()) {
        SRLogDebug("longPolling will negotiate")
        super.negotiate(connection, connectionData: connectionData, completionHandler: block)
    }
    override func start(_ connection: SRConnectionInterface, connectionData: String, completionHandler block: ((Any?, NSError?) -> ())?) {
        SRLogDebug("longPolling will connect with connectionData \(connectionData)")
        self.poll(connection, connectionData: connectionData, completionHandler: block)
    }
    override func send(_ connection: SRConnectionInterface, data: String, connectionData: String, completionHandler block: ((Any?, NSError?) -> ())?) {
        SRLogDebug("longPolling will send data \(data)")
        super.send(connection, data: data, connectionData: connectionData, completionHandler: block)
    }
    override func abort(_ connection: SRConnectionInterface, timeout: TimeInterval, connectionData: String) {
        SRLogDebug("longPolling will abort");
        super.abort(connection, timeout: timeout, connectionData: connectionData)
    }
    override func lostConnection(_ connection: SRConnectionInterface) {
        SRLogDebug("longPolling  lost connection");
    }
    func poll(_ connection: SRConnectionInterface, connectionData: String, completionHandler block:((Any?, NSError?) -> ())?) {
        let url: String
        if (connection.messageId == nil) {
            url = connection.url + "connect"
        } else if self.isConnectionReconnecting(connection) {
            url = connection.url + "reconnect"
        } else {
            url = connection.url + "poll"
        }
        var canReconnect = true
        self.delayConnectionReconnect(connection, canReconnect:&canReconnect)
        var parameters: [String: String] = [
                "transport": self.name,
                "connectionToken": connection.connectionToken ?? "",
                "messageId": connection.messageId ?? "",
                "groupsToken": connection.groupsToken ?? "",
                "connectionData": connectionData
        ]
        /* Forward query strings. */
        for key in connection.queryString.keys {
            parameters[key] = connection.queryString[key]!
        }
        let dataRequest = Alamofire.request(url, method: .get, parameters: parameters)
        SRLogDebug("longPolling will connect at url: \(dataRequest.request!.url!.absoluteString)")
        dataRequest.responseString { response in
            SRLogDebug("longPolling did receive: \(response.value!)")
            var shouldReconnect = false
            var disconnectedReceived = false
            if let error = response.error as NSError? {
                SRLogError("longPolling did fail with error \(error)")
                canReconnect = false
                // Transition into reconnecting state
                _ = SRConnection.ensureReconnecting(connection)
                if !self.tryCompleteAbort() && !SRExceptionHelper.isRequestAborted(error) {
                    connection.didReceive(error: error)
                    SRLogDebug("will poll again in \(self.errorDelay) seconds")
                    canReconnect = true
                    DispatchQueue.main.asyncAfter(deadline: .now() + self.errorDelay) { [weak self] in
                        self?.poll(connection, connectionData: connectionData, completionHandler: nil)
                    }
                } else {
                    self.completeAbort()
                    block?(nil, error);
                }
                /* Stop here. */
                return
            }
            connection.process(response: response.value!, shouldReconnect:&shouldReconnect, disconnected:&disconnectedReceived)
            block?(nil, nil);
            if self.isConnectionReconnecting(connection) {
                // If the timeout for the reconnect hasn't fired as yet just fire the
                // event here before any incoming messages are processed
                SRLogWarn("reconnecting");
                canReconnect = self.connectionReconnect(connection)
            }
            if (shouldReconnect) {
                // Transition into reconnecting state
                SRLogDebug("longPolling did receive shouldReconnect command from server")
                SRConnection.ensureReconnecting(connection)
            }
            if (disconnectedReceived) {
                SRLogDebug("longPolling did receive disconnect command from server")
                connection.disconnect()
            }
            if !self.tryCompleteAbort() {
                //Abort has not been called so continue polling...
                canReconnect = true
                self.poll(connection, connectionData:connectionData, completionHandler:nil)
            } else {
                SRLogWarn("longPolling has shutdown due to abort")
            }
        }
    }
    func delayConnectionReconnect(_ connection: SRConnectionInterface, canReconnect: inout Bool) {
        if self.isConnectionReconnecting(connection) {
            SRLogWarn("will reconnect in \(self.reconnectDelay)")
            DispatchQueue.main.asyncAfter(deadline: .now() + self.reconnectDelay) { [weak self] in
                SRLogWarn("reconnecting")
                self?.connectionReconnect(connection)
                //canReconnect = self?.connectionReconnect(connection) ?? false
            }
        }
    }
    
    @discardableResult
    func connectionReconnect(_ connection: SRConnectionInterface) -> Bool {
        // Mark the connection as connected
        if connection.changeState(.reconnecting, toState:.connected) {
            connection.didReconnect()
        }
        return false
    }
    func isConnectionReconnecting(_ connection: SRConnectionInterface) -> Bool {
        return connection.state == .reconnecting;
    }
}
class SRExceptionHelper {
    class func isRequestAborted(_ error: NSError) -> Bool {
        return error.code == NSURLErrorCancelled
    }
}
 | 
	mit | 
	86d6e151ece75d76834e9a06017d8820 | 39.737864 | 167 | 0.647164 | 5.400257 | false | false | false | false | 
| 
	gouyz/GYZBaking | 
	baking/Classes/Tool/3rdLib/ZLaunchAd/ZLaunchAdConfig.swift | 
	1 | 
	2366 | 
	//
//  ZLaunchAdVC+Config.swift
//  ZLaunchAdDemo
//
//  Created by mengqingzheng on 2017/8/17.
//  Copyright © 2017年 meng. All rights reserved.
//
import UIKit
public let Z_SCREEN_WIDTH = UIScreen.main.bounds.size.width
public let Z_SCREEN_HEIGHT = UIScreen.main.bounds.size.height
public typealias ZClosure = ()->()
public enum SkipButtonType {
    case none                   /// 无跳过按钮
    case timer                  /// 跳过+倒计时
    case circle                 /// 圆形跳过
    case text                   /// 跳过
}
public enum TransitionType {
    case none
    case rippleEffect           /// 涟漪波纹
    case fade                   /// 交叉淡化
    case flipFromTop            /// 上下翻转
    case filpFromBottom
    case filpFromLeft           /// 左右翻转
    case filpFromRight
}
public protocol SkipBtnConfig {
    var skipBtnType: SkipButtonType { get }         /// 按钮类型
    var backgroundColor: UIColor { get }            /// 背景颜色
    var titleFont: UIFont { get }                   /// 标题字体
    var titleColor: UIColor { get }                 /// 字体颜色
    var cornerRadius: CGFloat { get }               /// 圆角
    var strokeColor: UIColor { get }                /// 圆形按钮进度条颜色
    var lineWidth: CGFloat { get }                  /// 圆形按钮进度条宽度
    var width: CGFloat { get }
    var height: CGFloat { get }
    var centerX: CGFloat { get }
    var centerY: CGFloat { get }
    var borderColor: UIColor { get }
    var borderWidth: CGFloat { get }
}
struct SkipBtnModel: SkipBtnConfig {
    var cornerRadius: CGFloat = 15
    var backgroundColor = UIColor.black.withAlphaComponent(0.4)
    var titleFont = UIFont.systemFont(ofSize: 13)
    var titleColor = UIColor.white
    var skipBtnType: SkipButtonType = .timer
    var strokeColor = UIColor.red
    var lineWidth: CGFloat = 2
    var width: CGFloat = 60
    var centerX: CGFloat = Z_SCREEN_WIDTH - 40
    var height: CGFloat = 30
    var centerY: CGFloat = 45
    var borderColor: UIColor = UIColor.clear
    var borderWidth: CGFloat = 1
}
//MARK: - Log
func printLog<T>( _ message: T, file: String = #file, method: String = #function, line: Int = #line){
    #if DEBUG
        print("\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)")
    #endif
}
 | 
	mit | 
	91cb52b0e9dfafb65575219803b9ef71 | 30.814286 | 101 | 0.596767 | 4.09375 | false | false | false | false | 
| 
	zmeyc/GRDB.swift | 
	Tests/GRDBTests/FetchedRecordsControllerTests.swift | 
	1 | 
	44817 | 
	import XCTest
#if USING_SQLCIPHER
    import GRDBCipher
#elseif USING_CUSTOMSQLITE
    import GRDBCustomSQLite
#else
    import GRDB
#endif
private class ChangesRecorder<Record: RowConvertible> {
    var changes: [(record: Record, change: FetchedRecordChange)] = []
    var recordsBeforeChanges: [Record]!
    var recordsAfterChanges: [Record]!
    var countBeforeChanges: Int?
    var countAfterChanges: Int?
    var recordsOnFirstEvent: [Record]!
    var transactionExpectation: XCTestExpectation? {
        didSet {
            changes = []
            recordsBeforeChanges = nil
            recordsAfterChanges = nil
            countBeforeChanges = nil
            countAfterChanges = nil
            recordsOnFirstEvent = nil
        }
    }
    
    func controllerWillChange(_ controller: FetchedRecordsController<Record>, count: Int? = nil) {
        recordsBeforeChanges = controller.fetchedRecords
        countBeforeChanges = count
    }
    
    /// The default implementation does nothing.
    func controller(_ controller: FetchedRecordsController<Record>, didChangeRecord record: Record, with change: FetchedRecordChange) {
        if recordsOnFirstEvent == nil {
            recordsOnFirstEvent = controller.fetchedRecords
        }
        changes.append((record: record, change: change))
    }
    
    /// The default implementation does nothing.
    func controllerDidChange(_ controller: FetchedRecordsController<Record>, count: Int? = nil) {
        recordsAfterChanges = controller.fetchedRecords
        countAfterChanges = count
        if let transactionExpectation = transactionExpectation {
            transactionExpectation.fulfill()
        }
    }
}
private class Person : Record {
    var id: Int64?
    let name: String
    let email: String?
    let bookCount: Int?
    
    init(id: Int64? = nil, name: String, email: String? = nil) {
        self.id = id
        self.name = name
        self.email = email
        self.bookCount = nil
        super.init()
    }
    
    required init(row: Row) {
        id = row.value(named: "id")
        name = row.value(named: "name")
        email = row.value(named: "email")
        bookCount = row.value(named: "bookCount")
        super.init(row: row)
    }
    
    override class var databaseTableName: String {
        return "persons"
    }
    
    override var persistentDictionary: [String : DatabaseValueConvertible?] {
        return ["id": id, "name": name, "email": email]
    }
    
    override func didInsert(with rowID: Int64, for column: String?) {
        id = rowID
    }
}
private struct Book : RowConvertible {
    var id: Int64
    var authorID: Int64
    var title: String
    
    init(row: Row) {
        id = row.value(named: "id")
        authorID = row.value(named: "authorID")
        title = row.value(named: "title")
    }
}
class FetchedRecordsControllerTests: GRDBTestCase {
    override func setup(_ dbWriter: DatabaseWriter) throws {
        try dbWriter.write { db in
            try db.create(table: "persons") { t in
                t.column("id", .integer).primaryKey()
                t.column("name", .text)
                t.column("email", .text)
            }
            try db.create(table: "books") { t in
                t.column("id", .integer).primaryKey()
                t.column("authorId", .integer).notNull().references("persons", onDelete: .cascade, onUpdate: .cascade)
                t.column("title", .text)
            }
            try db.create(table: "flowers") { t in
                t.column("id", .integer).primaryKey()
                t.column("name", .text)
            }
        }
    }
    
    func testControllerFromSQL() throws {
        let dbQueue = try makeDatabaseQueue()
        let authorId: Int64 = try dbQueue.inDatabase { db in
            let plato = Person(name: "Plato")
            try plato.insert(db)
            try db.execute("INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [plato.id, "Symposium"])
            let cervantes = Person(name: "Cervantes")
            try cervantes.insert(db)
            try db.execute("INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [cervantes.id, "Don Quixote"])
            return cervantes.id!
        }
        
        let controller = try FetchedRecordsController<Book>(dbQueue, sql: "SELECT * FROM books WHERE authorID = ?", arguments: [authorId])
        try controller.performFetch()
        XCTAssertEqual(controller.fetchedRecords.count, 1)
        XCTAssertEqual(controller.fetchedRecords[0].title, "Don Quixote")
    }
    func testControllerFromSQLWithAdapter() throws {
        let dbQueue = try makeDatabaseQueue()
        let authorId: Int64 = try dbQueue.inDatabase { db in
            let plato = Person(name: "Plato")
            try plato.insert(db)
            try db.execute("INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [plato.id, "Symposium"])
            let cervantes = Person(name: "Cervantes")
            try cervantes.insert(db)
            try db.execute("INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [cervantes.id, "Don Quixote"])
            return cervantes.id!
        }
        
        let adapter = ColumnMapping(["id": "_id", "authorId": "_authorId", "title": "_title"])
        let controller = try FetchedRecordsController<Book>(dbQueue, sql: "SELECT id AS _id, authorId AS _authorId, title AS _title FROM books WHERE authorID = ?", arguments: [authorId], adapter: adapter)
        try controller.performFetch()
        XCTAssertEqual(controller.fetchedRecords.count, 1)
        XCTAssertEqual(controller.fetchedRecords[0].title, "Don Quixote")
    }
    func testControllerFromRequest() throws {
        let dbQueue = try makeDatabaseQueue()
        try dbQueue.inDatabase { db in
            try Person(name: "Plato").insert(db)
            try Person(name: "Cervantes").insert(db)
        }
        
        let request = Person.order(Column("name"))
        let controller = try FetchedRecordsController(dbQueue, request: request)
        try controller.performFetch()
        XCTAssertEqual(controller.fetchedRecords.count, 2)
        XCTAssertEqual(controller.fetchedRecords[0].name, "Cervantes")
        XCTAssertEqual(controller.fetchedRecords[1].name, "Plato")
    }
    func testSections() throws {
        let dbQueue = try makeDatabaseQueue()
        let arthur = Person(name: "Arthur")
        try dbQueue.inDatabase { db in
            try arthur.insert(db)
        }
        
        let request = Person.all()
        let controller = try FetchedRecordsController(dbQueue, request: request)
        try controller.performFetch()
        XCTAssertEqual(controller.sections.count, 1)
        XCTAssertEqual(controller.sections[0].numberOfRecords, 1)
        XCTAssertEqual(controller.sections[0].records.count, 1)
        XCTAssertEqual(controller.sections[0].records[0].name, "Arthur")
        XCTAssertEqual(controller.fetchedRecords.count, 1)
        XCTAssertEqual(controller.fetchedRecords[0].name, "Arthur")
        XCTAssertEqual(controller.record(at: IndexPath(indexes: [0, 0])).name, "Arthur")
        XCTAssertEqual(controller.indexPath(for: arthur), IndexPath(indexes: [0, 0]))
    }
    func testEmptyRequestGivesOneSection() throws {
        let dbQueue = try makeDatabaseQueue()
        let request = Person.all()
        let controller = try FetchedRecordsController(dbQueue, request: request)
        try controller.performFetch()
        XCTAssertEqual(controller.fetchedRecords.count, 0)
        
        // Just like NSFetchedResultsController
        XCTAssertEqual(controller.sections.count, 1)
    }
    func testDatabaseChangesAreNotReReflectedUntilPerformFetchAndDelegateIsSet() {
        // TODO: test that controller.fetchedRecords does not eventually change
        // after a database change. The difficulty of this test lies in the
        // "eventually" word.
    }
    func testSimpleInsert() throws {
        let dbQueue = try makeDatabaseQueue()
        let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id")))
        let recorder = ChangesRecorder<Person>()
        controller.trackChanges(
            willChange: { recorder.controllerWillChange($0) },
            onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
            didChange: { recorder.controllerDidChange($0) })
        try controller.performFetch()
        
        // First insert
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [
                Person(id: 1, name: "Arthur")])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 0)
        XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1)
        XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Arthur"])
        XCTAssertEqual(recorder.changes.count, 1)
        XCTAssertEqual(recorder.changes[0].record.id, 1)
        XCTAssertEqual(recorder.changes[0].record.name, "Arthur")
        switch recorder.changes[0].change {
        case .insertion(let indexPath):
            XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
        default:
            XCTFail()
        }
        
        // Second insert
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [
                Person(id: 1, name: "Arthur"),
                Person(id: 2, name: "Barbara")])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 1)
        XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur"])
        XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2)
        XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Arthur", "Barbara"])
        XCTAssertEqual(recorder.changes.count, 1)
        XCTAssertEqual(recorder.changes[0].record.id, 2)
        XCTAssertEqual(recorder.changes[0].record.name, "Barbara")
        switch recorder.changes[0].change {
        case .insertion(let indexPath):
            XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1]))
        default:
            XCTFail()
        }
    }
    func testSimpleUpdate() throws {
        let dbQueue = try makeDatabaseQueue()
        let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id")))
        let recorder = ChangesRecorder<Person>()
        controller.trackChanges(
            willChange: { recorder.controllerWillChange($0) },
            onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
            didChange: { recorder.controllerDidChange($0) })
        try controller.performFetch()
        
        // Insert
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [
                Person(id: 1, name: "Arthur"),
                Person(id: 2, name: "Barbara")])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        // First update
        recorder.transactionExpectation = expectation(description: "expectation")
        // No change should be recorded
        try dbQueue.inTransaction { db in
            try db.execute("UPDATE persons SET name = ? WHERE id = ?", arguments: ["Arthur", 1])
            return .commit
        }
        // One change should be recorded
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [
                Person(id: 1, name: "Craig"),
                Person(id: 2, name: "Barbara")])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
        XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"])
        XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2)
        XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Craig", "Barbara"])
        XCTAssertEqual(recorder.changes.count, 1)
        XCTAssertEqual(recorder.changes[0].record.id, 1)
        XCTAssertEqual(recorder.changes[0].record.name, "Craig")
        switch recorder.changes[0].change {
        case .update(let indexPath, let changes):
            XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
            XCTAssertEqual(changes, ["name": "Arthur".databaseValue])
        default:
            XCTFail()
        }
        
        // Second update
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [
                Person(id: 1, name: "Craig"),
                Person(id: 2, name: "Danielle")])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
        XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Craig", "Barbara"])
        XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2)
        XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Craig", "Danielle"])
        XCTAssertEqual(recorder.changes.count, 1)
        XCTAssertEqual(recorder.changes[0].record.id, 2)
        XCTAssertEqual(recorder.changes[0].record.name, "Danielle")
        switch recorder.changes[0].change {
        case .update(let indexPath, let changes):
            XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1]))
            XCTAssertEqual(changes, ["name": "Barbara".databaseValue])
        default:
            XCTFail()
        }
    }
    func testSimpleDelete() throws {
        let dbQueue = try makeDatabaseQueue()
        let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id")))
        let recorder = ChangesRecorder<Person>()
        controller.trackChanges(
            willChange: { recorder.controllerWillChange($0) },
            onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
            didChange: { recorder.controllerDidChange($0) })
        try controller.performFetch()
        
        // Insert
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [
                Person(id: 1, name: "Arthur"),
                Person(id: 2, name: "Barbara")])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        // First delete
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [
                Person(id: 2, name: "Barbara")])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
        XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"])
        XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1)
        XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Barbara"])
        XCTAssertEqual(recorder.changes.count, 1)
        XCTAssertEqual(recorder.changes[0].record.id, 1)
        XCTAssertEqual(recorder.changes[0].record.name, "Arthur")
        switch recorder.changes[0].change {
        case .deletion(let indexPath):
            XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
        default:
            XCTFail()
        }
        
        // Second delete
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 1)
        XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Barbara"])
        XCTAssertEqual(recorder.recordsOnFirstEvent.count, 0)
        XCTAssertEqual(recorder.changes.count, 1)
        XCTAssertEqual(recorder.changes[0].record.id, 2)
        XCTAssertEqual(recorder.changes[0].record.name, "Barbara")
        switch recorder.changes[0].change {
        case .deletion(let indexPath):
            XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
        default:
            XCTFail()
        }
    }
    func testSimpleMove() throws {
        let dbQueue = try makeDatabaseQueue()
        let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name")))
        let recorder = ChangesRecorder<Person>()
        controller.trackChanges(
            willChange: { recorder.controllerWillChange($0) },
            onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
            didChange: { recorder.controllerDidChange($0) })
        try controller.performFetch()
        
        // Insert
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [
                Person(id: 1, name: "Arthur"),
                Person(id: 2, name: "Barbara")])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        // Move
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [
                Person(id: 1, name: "Craig"),
                Person(id: 2, name: "Barbara")])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
        XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"])
        XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2)
        XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Barbara", "Craig"])
        XCTAssertEqual(recorder.changes.count, 1)
        XCTAssertEqual(recorder.changes[0].record.id, 1)
        XCTAssertEqual(recorder.changes[0].record.name, "Craig")
        switch recorder.changes[0].change {
        case .move(let indexPath, let newIndexPath, let changes):
            XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
            XCTAssertEqual(newIndexPath, IndexPath(indexes: [0, 1]))
            XCTAssertEqual(changes, ["name": "Arthur".databaseValue])
        default:
            XCTFail()
        }
    }
    func testSideTableChange() throws {
        let dbQueue = try makeDatabaseQueue()
        let controller = try FetchedRecordsController<Person>(
            dbQueue,
            sql: ("SELECT persons.*, COUNT(books.id) AS bookCount " +
                "FROM persons " +
                "LEFT JOIN books ON books.authorId = persons.id " +
                "GROUP BY persons.id " +
                "ORDER BY persons.name"))
        let recorder = ChangesRecorder<Person>()
        controller.trackChanges(
            willChange: { recorder.controllerWillChange($0) },
            onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
            didChange: { recorder.controllerDidChange($0) })
        try controller.performFetch()
        
        // Insert
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
            try db.execute("INSERT INTO books (authorId, title) VALUES (?, ?)", arguments: [1, "Moby Dick"])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        // Change books
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try db.execute("DELETE FROM books")
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 1)
        XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur"])
        XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.bookCount! }, [1])
        XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1)
        XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Arthur"])
        XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.bookCount! }, [0])
        XCTAssertEqual(recorder.changes.count, 1)
        XCTAssertEqual(recorder.changes[0].record.id, 1)
        XCTAssertEqual(recorder.changes[0].record.name, "Arthur")
        XCTAssertEqual(recorder.changes[0].record.bookCount, 0)
        switch recorder.changes[0].change {
        case .update(let indexPath, let changes):
            XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
            XCTAssertEqual(changes, ["bookCount": 1.databaseValue])
        default:
            XCTFail()
        }
    }
    func testComplexChanges() throws {
        let dbQueue = try makeDatabaseQueue()
        let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name")))
        let recorder = ChangesRecorder<Person>()
        controller.trackChanges(
            willChange: { recorder.controllerWillChange($0) },
            onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
            didChange: { recorder.controllerDidChange($0) })
        try controller.performFetch()
        
        enum EventTest {
            case I(String, Int) // insert string at index
            case M(String, Int, Int, String) // move string from index to index with changed string
            case D(String, Int) // delete string at index
            case U(String, Int, String) // update string at index with changed string
            
            func match(name: String, event: FetchedRecordChange) -> Bool {
                switch self {
                case .I(let s, let i):
                    switch event {
                    case .insertion(let indexPath):
                        return s == name && i == indexPath[1]
                    default:
                        return false
                    }
                case .M(let s, let i, let j, let c):
                    switch event {
                    case .move(let indexPath, let newIndexPath, let changes):
                        return s == name && i == indexPath[1] && j == newIndexPath[1] && c == String.fromDatabaseValue(changes["name"]!)!
                    default:
                        return false
                    }
                case .D(let s, let i):
                    switch event {
                    case .deletion(let indexPath):
                        return s == name && i == indexPath[1]
                    default:
                        return false
                    }
                case .U(let s, let i, let c):
                    switch event {
                    case .update(let indexPath, let changes):
                        return s == name && i == indexPath[1] && c == String.fromDatabaseValue(changes["name"]!)!
                    default:
                        return false
                    }
                }
            }
        }
        
        // A list of random updates. We hope to cover most cases if not all cases here.
        let steps: [(word: String, events: [EventTest])] = [
            (word: "B", events: [.I("B",0)]),
            (word: "BA", events: [.I("A",0)]),
            (word: "ABF", events: [.M("B",0,1,"A"), .M("A",1,0,"B"), .I("F",2)]),
            (word: "AB", events: [.D("F",2)]),
            (word: "A", events: [.D("B",1)]),
            (word: "C", events: [.U("C",0,"A")]),
            (word: "", events: [.D("C",0)]),
            (word: "C", events: [.I("C",0)]),
            (word: "CD", events: [.I("D",1)]),
            (word: "B", events: [.D("D",1), .U("B",0,"C")]),
            (word: "BCAEFD", events: [.I("A",0), .I("C",2), .I("D",3), .I("E",4), .I("F",5)]),
            (word: "CADBE", events: [.M("A",2,0,"C"), .D("D",3), .M("C",1,2,"B"), .M("B",4,1,"E"), .M("D",0,3,"A"), .M("E",5,4,"F")]),
            (word: "EB", events: [.D("B",1), .D("D",3), .D("E",4), .M("E",2,1,"C"), .U("B",0,"A")]),
            (word: "BEC", events: [.I("C",1), .M("B",1,0,"E"), .M("E",0,2,"B")]),
            (word: "AB", events: [.D("C",1), .M("B",2,1,"E"), .U("A",0,"B")]),
            (word: "ADEFCB", events: [.I("B",1), .I("C",2), .I("E",4), .M("D",1,3,"B"), .I("F",5)]),
            (word: "DA", events: [.D("B",1), .D("C",2), .D("E",4), .M("A",3,0,"D"), .D("F",5), .M("D",0,1,"A")]),
            (word: "BACEF", events: [.I("C",2), .I("E",3), .I("F",4), .U("B",1,"D")]),
            (word: "BACD", events: [.D("F",4), .U("D",3,"E")]),
            (word: "EABDFC", events: [.M("B",2,1,"C"), .I("C",2), .M("E",1,4,"B"), .I("F",5)]),
            (word: "CAB", events: [.D("C",2), .D("D",3), .D("F",5), .M("C",4,2,"E")]),
            (word: "CBAD", events: [.M("A",1,0,"B"), .M("B",0,1,"A"), .I("D",3)]),
            (word: "BAC", events: [.M("A",1,0,"B"), .M("B",2,1,"C"), .D("D",3), .M("C",0,2,"A")]),
            (word: "CBEADF", events: [.I("A",0), .M("B",0,1,"A"), .I("D",3), .M("C",1,2,"B"), .M("E",2,4,"C"), .I("F",5)]),
            (word: "CBA", events: [.D("A",0), .D("D",3), .M("A",4,0,"E"), .D("F",5)]),
            (word: "CBDAF", events: [.I("A",0), .M("D",0,3,"A"), .I("F",4)]),
            (word: "B", events: [.D("A",0), .D("B",1), .D("D",3), .D("F",4), .M("B",2,0,"C")]),
            (word: "BDECAF", events: [.I("A",0), .I("C",2), .I("D",3), .I("E",4), .I("F",5)]),
            (word: "ABCDEF", events: [.M("A",1,0,"B"), .M("B",3,1,"D"), .M("D",2,3,"C"), .M("C",4,2,"E"), .M("E",0,4,"A")]),
            (word: "ADBCF", events: [.M("B",2,1,"C"), .M("C",3,2,"D"), .M("D",1,3,"B"), .D("F",5), .U("F",4,"E")]),
            (word: "A", events: [.D("B",1), .D("C",2), .D("D",3), .D("F",4)]),
            (word: "AEBDCF", events: [.I("B",1), .I("C",2), .I("D",3), .I("E",4), .I("F",5)]),
            (word: "B", events: [.D("B",1), .D("C",2), .D("D",3), .D("E",4), .D("F",5), .U("B",0,"A")]),
            (word: "ABCDF", events: [.I("B",1), .I("C",2), .I("D",3), .I("F",4), .U("A",0,"B")]),
            (word: "CAB", events: [.M("A",1,0,"B"), .D("D",3), .M("B",2,1,"C"), .D("F",4), .M("C",0,2,"A")]),
            (word: "AC", events: [.D("B",1), .M("A",2,0,"C"), .M("C",0,1,"A")]),
            (word: "DABC", events: [.I("B",1), .I("C",2), .M("A",1,0,"C"), .M("D",0,3,"A")]),
            (word: "BACD", events: [.M("C",1,2,"B"), .M("B",3,1,"D"), .M("D",2,3,"C")]),
            (word: "D", events: [.D("A",0), .D("C",2), .D("D",3), .M("D",1,0,"B")]),
            (word: "CABDFE", events: [.I("A",0), .I("B",1), .I("D",3), .I("E",4), .M("C",0,2,"D"), .I("F",5)]),
            (word: "BACDEF", events: [.M("B",2,1,"C"), .M("C",1,2,"B"), .M("E",5,4,"F"), .M("F",4,5,"E")]),
            (word: "AB", events: [.D("C",2), .D("D",3), .D("E",4), .M("A",1,0,"B"), .D("F",5), .M("B",0,1,"A")]),
            (word: "BACDE", events: [.I("C",2), .M("B",0,1,"A"), .I("D",3), .M("A",1,0,"B"), .I("E",4)]),
            (word: "E", events: [.D("A",0), .D("C",2), .D("D",3), .D("E",4), .M("E",1,0,"B")]),
            (word: "A", events: [.U("A",0,"E")]),
            (word: "ABCDE", events: [.I("B",1), .I("C",2), .I("D",3), .I("E",4)]),
            (word: "BA", events: [.D("C",2), .D("D",3), .M("A",1,0,"B"), .D("E",4), .M("B",0,1,"A")]),
            (word: "A", events: [.D("A",0), .M("A",1,0,"B")]),
            (word: "CAB", events: [.I("A",0), .I("B",1), .M("C",0,2,"A")]),
            (word: "EA", events: [.D("B",1), .M("E",2,1,"C")]),
            (word: "B", events: [.D("A",0), .M("B",1,0,"E")]),
            ]
        
        for step in steps {
            recorder.transactionExpectation = expectation(description: "expectation")
            try dbQueue.inTransaction { db in
                try synchronizePersons(db, step.word.characters.enumerated().map { Person(id: Int64($0), name: String($1)) })
                return .commit
            }
            waitForExpectations(timeout: 1, handler: nil)
            
            XCTAssertEqual(recorder.changes.count, step.events.count)
            for (change, event) in zip(recorder.changes, step.events) {
                XCTAssertTrue(event.match(name: change.record.name, event: change.change))
            }
        }
    }
    func testExternalTableChange() {
        // TODO: test that delegate is not notified after a database change in a
        // table not involved in the fetch request. The difficulty of this test
        // lies in the "not" word.
    }
    func testCustomRecordIdentity() {
        // TODO: test record comparison not based on primary key but based on
        // custom function
    }
    func testRequestChange() throws {
        let dbQueue = try makeDatabaseQueue()
        let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name")))
        let recorder = ChangesRecorder<Person>()
        controller.trackChanges(
            willChange: { recorder.controllerWillChange($0) },
            onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
            didChange: { recorder.controllerDidChange($0) })
        try controller.performFetch()
        
        // Insert
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [
                Person(id: 1, name: "Arthur"),
                Person(id: 2, name: "Barbara")])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        // Change request with Request
        recorder.transactionExpectation = expectation(description: "expectation")
        try controller.setRequest(Person.order(Column("name").desc))
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
        XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"])
        XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2)
        XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Barbara", "Arthur"])
        XCTAssertEqual(recorder.changes.count, 1)
        XCTAssertEqual(recorder.changes[0].record.id, 2)
        XCTAssertEqual(recorder.changes[0].record.name, "Barbara")
        switch recorder.changes[0].change {
        case .move(let indexPath, let newIndexPath, let changes):
            XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1]))
            XCTAssertEqual(newIndexPath, IndexPath(indexes: [0, 0]))
            XCTAssertTrue(changes.isEmpty)
        default:
            XCTFail()
        }
        
        // Change request with SQL and arguments
        recorder.transactionExpectation = expectation(description: "expectation")
        try controller.setRequest(sql: "SELECT ? AS id, ? AS name", arguments: [1, "Craig"])
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
        XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Barbara", "Arthur"])
        XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1)
        XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Craig"])
        XCTAssertEqual(recorder.changes.count, 2)
        XCTAssertEqual(recorder.changes[0].record.id, 2)
        XCTAssertEqual(recorder.changes[0].record.name, "Barbara")
        XCTAssertEqual(recorder.changes[1].record.id, 1)
        XCTAssertEqual(recorder.changes[1].record.name, "Craig")
        switch recorder.changes[0].change {
        case .deletion(let indexPath):
            XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
        default:
            XCTFail()
        }
        switch recorder.changes[1].change {
        case .move(let indexPath, let newIndexPath, let changes):
            // TODO: is it really what we should expect? Wouldn't an update fit better?
            // What does UITableView think?
            XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1]))
            XCTAssertEqual(newIndexPath, IndexPath(indexes: [0, 0]))
            XCTAssertEqual(changes, ["name": "Arthur".databaseValue])
        default:
            XCTFail()
        }
        
        // Change request with a different set of tracked columns
        recorder.transactionExpectation = expectation(description: "expectation")
        try controller.setRequest(Person.select(Column("id"), Column("name"), Column("email")).order(Column("name")))
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 1)
        XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Craig"])
        XCTAssertEqual(recorder.recordsAfterChanges.count, 2)
        XCTAssertEqual(recorder.recordsAfterChanges.map { $0.name }, ["Arthur", "Barbara"])
        
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try db.execute("UPDATE persons SET email = ? WHERE name = ?", arguments: ["[email protected]", "Arthur"])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
        XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"])
        XCTAssertEqual(recorder.recordsAfterChanges.count, 2)
        XCTAssertEqual(recorder.recordsAfterChanges.map { $0.name }, ["Arthur", "Barbara"])
        
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try db.execute("UPDATE PERSONS SET EMAIL = ? WHERE NAME = ?", arguments: ["[email protected]", "Barbara"])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
        XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"])
        XCTAssertEqual(recorder.recordsAfterChanges.count, 2)
        XCTAssertEqual(recorder.recordsAfterChanges.map { $0.name }, ["Arthur", "Barbara"])
    }
    func testSetCallbacksAfterUpdate() throws {
        let dbQueue = try makeDatabaseQueue()
        let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name")))
        let recorder = ChangesRecorder<Person>()
        try controller.performFetch()
        
        // Insert
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [
                Person(id: 1, name: "Arthur")])
            return .commit
        }
        
        // Set callbacks
        recorder.transactionExpectation = expectation(description: "expectation")
        controller.trackChanges(
            willChange: { recorder.controllerWillChange($0) },
            onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
            didChange: { recorder.controllerDidChange($0) })
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 0)
        XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1)
        XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Arthur"])
        XCTAssertEqual(recorder.changes.count, 1)
        XCTAssertEqual(recorder.changes[0].record.id, 1)
        XCTAssertEqual(recorder.changes[0].record.name, "Arthur")
        switch recorder.changes[0].change {
        case .insertion(let indexPath):
            XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
        default:
            XCTFail()
        }
    }
    func testTrailingClosureCallback() throws {
        let dbQueue = try makeDatabaseQueue()
        let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name")))
        var persons: [Person] = []
        try controller.performFetch()
        
        let expectation = self.expectation(description: "expectation")
        controller.trackChanges {
            persons = $0.fetchedRecords
            expectation.fulfill()
        }
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [
                Person(id: 1, name: "Arthur")])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        XCTAssertEqual(persons.map { $0.name }, ["Arthur"])
    }
    func testFetchAlongside() throws {
        let dbQueue = try makeDatabaseQueue()
        let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id")))
        let recorder = ChangesRecorder<Person>()
        controller.trackChanges(
            fetchAlongside: { db in try Person.fetchCount(db) },
            willChange: { (controller, count) in recorder.controllerWillChange(controller, count: count) },
            onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
            didChange: { (controller, count) in recorder.controllerDidChange(controller, count: count) })
        try controller.performFetch()
        
        // First insert
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [
                Person(id: 1, name: "Arthur")])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 0)
        XCTAssertEqual(recorder.recordsAfterChanges.count, 1)
        XCTAssertEqual(recorder.recordsAfterChanges.map { $0.name }, ["Arthur"])
        XCTAssertEqual(recorder.countBeforeChanges!, 1)
        XCTAssertEqual(recorder.countAfterChanges!, 1)
        
        // Second insert
        recorder.transactionExpectation = expectation(description: "expectation")
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [
                Person(id: 1, name: "Arthur"),
                Person(id: 2, name: "Barbara")])
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        
        XCTAssertEqual(recorder.recordsBeforeChanges.count, 1)
        XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur"])
        XCTAssertEqual(recorder.recordsAfterChanges.count, 2)
        XCTAssertEqual(recorder.recordsAfterChanges.map { $0.name }, ["Arthur", "Barbara"])
        XCTAssertEqual(recorder.countBeforeChanges!, 2)
        XCTAssertEqual(recorder.countAfterChanges!, 2)
    }
    func testFetchErrors() throws {
        let dbQueue = try makeDatabaseQueue()
        let controller = try FetchedRecordsController(dbQueue, request: Person.all())
        
        let expectation = self.expectation(description: "expectation")
        var error: Error?
        controller.trackErrors {
            error = $1
            expectation.fulfill()
        }
        controller.trackChanges { _ in }
        try controller.performFetch()
        try dbQueue.inTransaction { db in
            try synchronizePersons(db, [
                Person(id: 1, name: "Arthur")])
            try db.drop(table: "persons")
            return .commit
        }
        waitForExpectations(timeout: 1, handler: nil)
        if let error = error as? DatabaseError {
            XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
            XCTAssertEqual(error.message, "no such table: persons")
            XCTAssertEqual(error.sql!, "SELECT * FROM \"persons\"")
            XCTAssertEqual(error.description, "SQLite error 1 with statement `SELECT * FROM \"persons\"`: no such table: persons")
        } else {
            XCTFail("Expected DatabaseError")
        }
    }
}
// Synchronizes the persons table with a JSON payload
private func synchronizePersons(_ db: Database, _ newPersons: [Person]) throws {
    // Sort new persons and database persons by id:
    let newPersons = newPersons.sorted { $0.id! < $1.id! }
    let databasePersons = try Person.fetchAll(db, "SELECT * FROM persons ORDER BY id")
    
    // Now that both lists are sorted by id, we can compare them with
    // the sortedMerge() function.
    //
    // We'll delete, insert or update persons, depending on their presence
    // in either lists.
    for mergeStep in sortedMerge(
        left: databasePersons,
        right: newPersons,
        leftKey: { $0.id! },
        rightKey: { $0.id! })
    {
        switch mergeStep {
        case .left(let databasePerson):
            try databasePerson.delete(db)
        case .right(let newPerson):
            try newPerson.insert(db)
        case .common(_, let newPerson):
            try newPerson.update(db)
        }
    }
}
/// Given two sorted sequences (left and right), this function emits "merge steps"
/// which tell whether elements are only found on the left, on the right, or on
/// both sides.
///
/// Both sequences do not have to share the same element type. Yet elements must
/// share a common comparable *key*.
///
/// Both sequences must be sorted by this key.
///
/// Keys must be unique in both sequences.
///
/// The example below compare two sequences sorted by integer representation,
/// and prints:
///
/// - Left: 1
/// - Common: 2, 2
/// - Common: 3, 3
/// - Right: 4
///
///     for mergeStep in sortedMerge(
///         left: [1,2,3],
///         right: ["2", "3", "4"],
///         leftKey: { $0 },
///         rightKey: { Int($0)! })
///     {
///         switch mergeStep {
///         case .left(let left):
///             print("- Left: \(left)")
///         case .right(let right):
///             print("- Right: \(right)")
///         case .common(let left, let right):
///             print("- Common: \(left), \(right)")
///         }
///     }
///
/// - parameters:
///     - left: The left sequence.
///     - right: The right sequence.
///     - leftKey: A function that returns the key of a left element.
///     - rightKey: A function that returns the key of a right element.
/// - returns: A sequence of MergeStep
private func sortedMerge<LeftSequence: Sequence, RightSequence: Sequence, Key: Comparable>(
    left lSeq: LeftSequence,
    right rSeq: RightSequence,
    leftKey: @escaping (LeftSequence.Iterator.Element) -> Key,
    rightKey: @escaping (RightSequence.Iterator.Element) -> Key) -> AnySequence<MergeStep<LeftSequence.Iterator.Element, RightSequence.Iterator.Element>>
{
    return AnySequence { () -> AnyIterator<MergeStep<LeftSequence.Iterator.Element, RightSequence.Iterator.Element>> in
        var (lGen, rGen) = (lSeq.makeIterator(), rSeq.makeIterator())
        var (lOpt, rOpt) = (lGen.next(), rGen.next())
        return AnyIterator {
            switch (lOpt, rOpt) {
            case (let lElem?, let rElem?):
                let (lKey, rKey) = (leftKey(lElem), rightKey(rElem))
                if lKey > rKey {
                    rOpt = rGen.next()
                    return .right(rElem)
                } else if lKey == rKey {
                    (lOpt, rOpt) = (lGen.next(), rGen.next())
                    return .common(lElem, rElem)
                } else {
                    lOpt = lGen.next()
                    return .left(lElem)
                }
            case (nil, let rElem?):
                rOpt = rGen.next()
                return .right(rElem)
            case (let lElem?, nil):
                lOpt = lGen.next()
                return .left(lElem)
            case (nil, nil):
                return nil
            }
        }
    }
}
/**
 Support for sortedMerge()
 */
private enum MergeStep<LeftElement, RightElement> {
    /// An element only found in the left sequence:
    case left(LeftElement)
    /// An element only found in the right sequence:
    case right(RightElement)
    /// Left and right elements share a common key:
    case common(LeftElement, RightElement)
}
 | 
	mit | 
	03a07ba56c46aae3a491b4ee91866ddc | 44.269697 | 204 | 0.581766 | 4.383081 | false | false | false | false | 
| 
	tjw/swift | 
	stdlib/public/core/SwiftNativeNSArray.swift | 
	2 | 
	10509 | 
	//===--- SwiftNativeNSArray.swift -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  _ContiguousArrayStorageBase supplies the implementation of the
//  _NSArrayCore API (and thus, NSArray the API) for our
//  _ContiguousArrayStorage<T>.  We can't put this implementation
//  directly on _ContiguousArrayStorage because generic classes can't
//  override Objective-C selectors.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
/// Returns `true` iff the given `index` is valid as a position, i.e. `0
/// ≤ index ≤ count`.
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal func _isValidArrayIndex(_ index: Int, count: Int) -> Bool {
  return (index >= 0) && (index <= count)
}
/// Returns `true` iff the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal func _isValidArraySubscript(_ index: Int, count: Int) -> Bool {
  return (index >= 0) && (index < count)
}
/// An `NSArray` with Swift-native reference counting and contiguous
/// storage.
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline
internal class _SwiftNativeNSArrayWithContiguousStorage
  : _SwiftNativeNSArray { // Provides NSArray inheritance and native refcounting
  @inlinable // FIXME(sil-serialize-all)
  @nonobjc internal override init() {}
  @inlinable // FIXME(sil-serialize-all)
  deinit {}
  // Operate on our contiguous storage
  @inlinable
  internal func withUnsafeBufferOfObjects<R>(
    _ body: (UnsafeBufferPointer<AnyObject>) throws -> R
  ) rethrows -> R {
    _sanityCheckFailure(
      "Must override withUnsafeBufferOfObjects in derived classes")
  }
}
// Implement the APIs required by NSArray 
extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore {
  @objc internal var count: Int {
    return withUnsafeBufferOfObjects { $0.count }
  }
  @objc(objectAtIndex:)
  internal func objectAt(_ index: Int) -> AnyObject {
    return withUnsafeBufferOfObjects {
      objects in
      _precondition(
        _isValidArraySubscript(index, count: objects.count),
        "Array index out of range")
      return objects[index]
    }
  }
  @objc internal func getObjects(
    _ aBuffer: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange
  ) {
    return withUnsafeBufferOfObjects {
      objects in
      _precondition(
        _isValidArrayIndex(range.location, count: objects.count),
        "Array index out of range")
      _precondition(
        _isValidArrayIndex(
          range.location + range.length, count: objects.count),
        "Array index out of range")
      if objects.isEmpty { return }
      // These objects are "returned" at +0, so treat them as pointer values to
      // avoid retains. Copy bytes via a raw pointer to circumvent reference
      // counting while correctly aliasing with all other pointer types.
      UnsafeMutableRawPointer(aBuffer).copyMemory(
        from: objects.baseAddress! + range.location,
        byteCount: range.length * MemoryLayout<AnyObject>.stride)
    }
  }
  @objc(countByEnumeratingWithState:objects:count:)
  internal func countByEnumerating(
    with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
    objects: UnsafeMutablePointer<AnyObject>?, count: Int
  ) -> Int {
    var enumerationState = state.pointee
    if enumerationState.state != 0 {
      return 0
    }
    return withUnsafeBufferOfObjects {
      objects in
      enumerationState.mutationsPtr = _fastEnumerationStorageMutationsPtr
      enumerationState.itemsPtr =
        AutoreleasingUnsafeMutablePointer(objects.baseAddress)
      enumerationState.state = 1
      state.pointee = enumerationState
      return objects.count
    }
  }
  @objc(copyWithZone:)
  internal func copy(with _: _SwiftNSZone?) -> AnyObject {
    return self
  }
}
/// An `NSArray` whose contiguous storage is created and filled, upon
/// first access, by bridging the elements of a Swift `Array`.
///
/// Ideally instances of this class would be allocated in-line in the
/// buffers used for Array storage.
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline
@objc internal final class _SwiftDeferredNSArray
  : _SwiftNativeNSArrayWithContiguousStorage {
  // This stored property should be stored at offset zero.  We perform atomic
  // operations on it.
  //
  // Do not access this property directly.
  @usableFromInline
  @nonobjc
  internal var _heapBufferBridged_DoNotUse: AnyObject?
  // When this class is allocated inline, this property can become a
  // computed one.
  @usableFromInline
  @nonobjc
  internal let _nativeStorage: _ContiguousArrayStorageBase
  @inlinable
  @nonobjc
  internal var _heapBufferBridgedPtr: UnsafeMutablePointer<AnyObject?> {
    return _getUnsafePointerToStoredProperties(self).assumingMemoryBound(
      to: Optional<AnyObject>.self)
  }
  internal typealias HeapBufferStorage = _HeapBufferStorage<Int, AnyObject>
  @inlinable
  internal var _heapBufferBridged: HeapBufferStorage? {
    if let ref =
      _stdlib_atomicLoadARCRef(object: _heapBufferBridgedPtr) {
      return unsafeBitCast(ref, to: HeapBufferStorage.self)
    }
    return nil
  }
  @inlinable // FIXME(sil-serialize-all)
  @nonobjc
  internal init(_nativeStorage: _ContiguousArrayStorageBase) {
    self._nativeStorage = _nativeStorage
  }
  @inlinable
  internal func _destroyBridgedStorage(_ hb: HeapBufferStorage?) {
    if let bridgedStorage = hb {
      let heapBuffer = _HeapBuffer(bridgedStorage)
      let count = heapBuffer.value
      heapBuffer.baseAddress.deinitialize(count: count)
    }
  }
  @inlinable // FIXME(sil-serialize-all)
  deinit {
    _destroyBridgedStorage(_heapBufferBridged)
  }
  @inlinable
  internal override func withUnsafeBufferOfObjects<R>(
    _ body: (UnsafeBufferPointer<AnyObject>) throws -> R
  ) rethrows -> R {
    while true {
      var buffer: UnsafeBufferPointer<AnyObject>
      
      // If we've already got a buffer of bridged objects, just use it
      if let bridgedStorage = _heapBufferBridged {
        let heapBuffer = _HeapBuffer(bridgedStorage)
        buffer = UnsafeBufferPointer(
            start: heapBuffer.baseAddress, count: heapBuffer.value)
      }
      // If elements are bridged verbatim, the native buffer is all we
      // need, so return that.
      else if let buf = _nativeStorage._withVerbatimBridgedUnsafeBuffer(
        { $0 }
      ) {
        buffer = buf
      }
      else {
        // Create buffer of bridged objects.
        let objects = _nativeStorage._getNonVerbatimBridgedHeapBuffer()
        
        // Atomically store a reference to that buffer in self.
        if !_stdlib_atomicInitializeARCRef(
          object: _heapBufferBridgedPtr, desired: objects.storage!) {
          // Another thread won the race.  Throw out our buffer.
          _destroyBridgedStorage(
            unsafeDowncast(objects.storage!, to: HeapBufferStorage.self))
        }
        continue // Try again
      }
      
      defer { _fixLifetime(self) }
      return try body(buffer)
    }
  }
  /// Returns the number of elements in the array.
  ///
  /// This override allows the count to be read without triggering
  /// bridging of array elements.
  @objc
  internal override var count: Int {
    if let bridgedStorage = _heapBufferBridged {
      return _HeapBuffer(bridgedStorage).value
    }
    // Check if elements are bridged verbatim.
    return _nativeStorage._withVerbatimBridgedUnsafeBuffer { $0.count }
      ?? _nativeStorage._getNonVerbatimBridgedCount()
  }
}
#else
// Empty shim version for non-objc platforms.
@usableFromInline
@_fixed_layout
internal class _SwiftNativeNSArrayWithContiguousStorage {
  @inlinable
  internal init() {}
  @inlinable
  deinit {}
}
#endif
/// Base class of the heap buffer backing arrays.  
@usableFromInline
@_fixed_layout
internal class _ContiguousArrayStorageBase
  : _SwiftNativeNSArrayWithContiguousStorage {
  @usableFromInline
  final var countAndCapacity: _ArrayBody
  @inlinable // FIXME(sil-serialize-all)
  @nonobjc
  internal init(_doNotCallMeBase: ()) {
    _sanityCheckFailure("creating instance of _ContiguousArrayStorageBase")
  }
  
#if _runtime(_ObjC)
  @inlinable
  internal override func withUnsafeBufferOfObjects<R>(
    _ body: (UnsafeBufferPointer<AnyObject>) throws -> R
  ) rethrows -> R {
    if let result = try _withVerbatimBridgedUnsafeBuffer(body) {
      return result
    }
    _sanityCheckFailure(
      "Can't use a buffer of non-verbatim-bridged elements as an NSArray")
  }
  /// If the stored type is bridged verbatim, invoke `body` on an
  /// `UnsafeBufferPointer` to the elements and return the result.
  /// Otherwise, return `nil`.
  @inlinable // FIXME(sil-serialize-all)
  internal func _withVerbatimBridgedUnsafeBuffer<R>(
    _ body: (UnsafeBufferPointer<AnyObject>) throws -> R
  ) rethrows -> R? {
    _sanityCheckFailure(
      "Concrete subclasses must implement _withVerbatimBridgedUnsafeBuffer")
  }
  @inlinable // FIXME(sil-serialize-all)
  @nonobjc
  internal func _getNonVerbatimBridgedCount() -> Int {
    _sanityCheckFailure(
      "Concrete subclasses must implement _getNonVerbatimBridgedCount")
  }
  @inlinable // FIXME(sil-serialize-all)
  internal func _getNonVerbatimBridgedHeapBuffer() ->
    _HeapBuffer<Int, AnyObject> {
    _sanityCheckFailure(
      "Concrete subclasses must implement _getNonVerbatimBridgedHeapBuffer")
  }
#endif
  @inlinable // FIXME(sil-serialize-all)
  internal func canStoreElements(ofDynamicType _: Any.Type) -> Bool {
    _sanityCheckFailure(
      "Concrete subclasses must implement canStoreElements(ofDynamicType:)")
  }
  /// A type that every element in the array is.
  @inlinable // FIXME(sil-serialize-all)
  internal var staticElementType: Any.Type {
    _sanityCheckFailure(
      "Concrete subclasses must implement staticElementType")
  }
  @inlinable // FIXME(sil-serialize-all)
  deinit {
    _sanityCheck(
      self !== _emptyArrayStorage, "Deallocating empty array storage?!")
  }
}
 | 
	apache-2.0 | 
	b01aa7846080cae11f2049322930c8f5 | 30.352239 | 80 | 0.689232 | 4.982448 | false | false | false | false | 
| 
	lorentey/GlueKit | 
	Sources/SetChange.swift | 
	1 | 
	2268 | 
	//
//  SetChange.swift
//  GlueKit
//
//  Created by Károly Lőrentey on 2016-08-12.
//  Copyright © 2015–2017 Károly Lőrentey.
//
public struct SetChange<Element: Hashable>: ChangeType {
    public typealias Value = Set<Element>
    public private(set) var removed: Set<Element>
    public private(set) var inserted: Set<Element>
    public init(removed: Set<Element> = [], inserted: Set<Element> = []) {
        self.inserted = inserted
        self.removed = removed
    }
    public init(from oldValue: Value, to newValue: Value) {
        self.removed = oldValue.subtracting(newValue)
        self.inserted = newValue.subtracting(oldValue)
    }
    public var isEmpty: Bool {
        return inserted.isEmpty && removed.isEmpty
    }
    public func apply(on value: inout Set<Element>) {
        value.subtract(removed)
        value = inserted.union(value)
    }
    public func apply(on value: Value) -> Value {
        return inserted.union(value.subtracting(removed))
    }
    public mutating func remove(_ element: Element) {
        self.inserted.remove(element)
        self.removed.update(with: element)
    }
    public mutating func insert(_ element: Element) {
        self.inserted.update(with: element)
    }
    public mutating func merge(with next: SetChange) {
        removed = next.removed.union(removed)
        inserted = next.inserted.union(inserted.subtracting(next.removed))
    }
    public func merged(with next: SetChange) -> SetChange {
        return SetChange(removed: next.removed.union(removed),
                         inserted: next.inserted.union(inserted.subtracting(next.removed)))
    }
    public func reversed() -> SetChange {
        return SetChange(removed: inserted, inserted: removed)
    }
    public func removingEqualChanges() -> SetChange {
        let intersection = removed.intersection(inserted)
        if intersection.isEmpty {
            return self
        }
        return SetChange(removed: removed.subtracting(intersection), inserted: inserted.subtracting(intersection))
    }
}
extension Set {
    public mutating func apply(_ change: SetChange<Element>) {
        self.subtract(change.removed)
        for e in change.inserted {
            self.update(with: e)
        }
    }
}
 | 
	mit | 
	37b5ae0e2e787383d920ada170971972 | 28.363636 | 114 | 0.646617 | 4.424658 | false | false | false | false | 
| 
	mzp/firefox-ios | 
	Extensions/ShareTo/ShareViewController.swift | 
	2 | 
	11087 | 
	/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Storage
struct ShareDestination {
    let code: String
    let name: String
    let image: String
}
// TODO: See if we can do this with an Enum instead. Previous attempts failed because for example NSSet does not take (string) enum values.
let ShareDestinationBookmarks: String = "Bookmarks"
let ShareDestinationReadingList: String = "ReadingList"
let ShareDestinations = [
    ShareDestination(code: ShareDestinationReadingList, name: NSLocalizedString("Add to Reading List", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your reading list"), image: "AddToReadingList"),
    ShareDestination(code: ShareDestinationBookmarks, name: NSLocalizedString("Add to Bookmarks", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your bookmarks"), image: "AddToBookmarks")
]
protocol ShareControllerDelegate {
    func shareControllerDidCancel(shareController: ShareDialogController) -> Void
    func shareController(shareController: ShareDialogController, didShareItem item: ShareItem, toDestinations destinations: NSSet) -> Void
}
private struct ShareDialogControllerUX {
    static let CornerRadius: CGFloat = 4                                                            // Corner radius of the dialog
    static let NavigationBarTintColor = UIColor(rgb: 0xf37c00)                                      // Tint color changes the text color in the navigation bar
    static let NavigationBarCancelButtonFont = UIFont.systemFontOfSize(UIFont.buttonFontSize())     // System default
    static let NavigationBarAddButtonFont = UIFont.boldSystemFontOfSize(UIFont.buttonFontSize())    // System default
    static let NavigationBarIconSize = 38                                                           // Width and height of the icon
    static let NavigationBarBottomPadding = 12
    @available(iOSApplicationExtension 8.2, *)
    static let ItemTitleFontMedium = UIFont.systemFontOfSize(15, weight: UIFontWeightMedium)
    static let ItemTitleFont = UIFont.systemFontOfSize(15)
    static let ItemTitleMaxNumberOfLines = 2
    static let ItemTitleLeftPadding = 44
    static let ItemTitleRightPadding = 44
    static let ItemTitleBottomPadding = 12
    static let ItemLinkFont = UIFont.systemFontOfSize(12)
    static let ItemLinkMaxNumberOfLines = 3
    static let ItemLinkLeftPadding = 44
    static let ItemLinkRightPadding = 44
    static let ItemLinkBottomPadding = 14
    static let DividerColor = UIColor.lightGrayColor()                                              // Divider between the item and the table with destinations
    static let DividerHeight = 0.5
    static let TableRowHeight: CGFloat = 44                                                         // System default
    static let TableRowFont = UIFont.systemFontOfSize(UIFont.labelFontSize())
    static let TableRowTintColor = UIColor(red:0.427, green:0.800, blue:0.102, alpha:1.0)           // Green tint for the checkmark
    static let TableRowTextColor = UIColor(rgb: 0x555555)
    static let TableHeight = 88                                                                     // Height of 2 standard 44px cells
}
class ShareDialogController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    var delegate: ShareControllerDelegate!
    var item: ShareItem!
    var initialShareDestinations: NSSet = NSSet(object: ShareDestinationBookmarks)
    var selectedShareDestinations: NSMutableSet = NSMutableSet()
    var navBar: UINavigationBar!
    var navItem: UINavigationItem!
    override func viewDidLoad() {
        super.viewDidLoad()
        selectedShareDestinations = NSMutableSet(set: initialShareDestinations)
        self.view.backgroundColor = UIColor.whiteColor()
        self.view.layer.cornerRadius = ShareDialogControllerUX.CornerRadius
        self.view.clipsToBounds = true
        // Setup the NavigationBar
        navBar = UINavigationBar()
        navBar.translatesAutoresizingMaskIntoConstraints = false
        navBar.tintColor = ShareDialogControllerUX.NavigationBarTintColor
        navBar.translucent = false
        self.view.addSubview(navBar)
        // Setup the NavigationItem
        navItem = UINavigationItem()
        navItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "cancel")
        navItem.leftBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarCancelButtonFont], forState: UIControlState.Normal)
        navItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Add", tableName: "ShareTo", comment: "Add button in the share dialog"), style: UIBarButtonItemStyle.Done, target: self, action: "add")
        navItem.rightBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarAddButtonFont], forState: UIControlState.Normal)
        let logo = UIImageView(frame: CGRect(x: 0, y: 0, width: ShareDialogControllerUX.NavigationBarIconSize, height: ShareDialogControllerUX.NavigationBarIconSize))
        logo.image = UIImage(named: "Icon-Small")
        logo.contentMode = UIViewContentMode.ScaleAspectFit // TODO Can go away if icon is provided in correct size
        navItem.titleView = logo
        navBar.pushNavigationItem(navItem, animated: false)
        // Setup the title view
        let titleView = UILabel()
        titleView.translatesAutoresizingMaskIntoConstraints = false
        titleView.numberOfLines = ShareDialogControllerUX.ItemTitleMaxNumberOfLines
        titleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail
        titleView.text = item.title
        if #available(iOSApplicationExtension 8.2, *) {
            titleView.font = ShareDialogControllerUX.ItemTitleFontMedium
        } else {
            // Fallback on earlier versions
            titleView.font = ShareDialogControllerUX.ItemTitleFont
        }
        view.addSubview(titleView)
        // Setup the link view
        let linkView = UILabel()
        linkView.translatesAutoresizingMaskIntoConstraints = false
        linkView.numberOfLines = ShareDialogControllerUX.ItemLinkMaxNumberOfLines
        linkView.lineBreakMode = NSLineBreakMode.ByTruncatingTail
        linkView.text = item.url
        linkView.font = ShareDialogControllerUX.ItemLinkFont
        view.addSubview(linkView)
        // Setup the icon
        let iconView = UIImageView()
        iconView.translatesAutoresizingMaskIntoConstraints = false
        iconView.image = UIImage(named: "defaultFavicon")
        view.addSubview(iconView)
        // Setup the divider
        let dividerView = UIView()
        dividerView.translatesAutoresizingMaskIntoConstraints = false
        dividerView.backgroundColor = ShareDialogControllerUX.DividerColor
        view.addSubview(dividerView)
        // Setup the table with destinations
        let tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.separatorInset = UIEdgeInsetsZero
        tableView.layoutMargins = UIEdgeInsetsZero
        tableView.userInteractionEnabled = true
        tableView.delegate = self
        tableView.allowsSelection = true
        tableView.dataSource = self
        tableView.scrollEnabled = false
        view.addSubview(tableView)
        // Setup constraints
        let views = [
            "nav": navBar,
            "title": titleView,
            "link": linkView,
            "icon": iconView,
            "divider": dividerView,
            "table": tableView
        ]
        // TODO See Bug 1102516 - Use Snappy to define share extension layout constraints
        let constraints = [
            "H:|[nav]|",
            "V:|[nav]",
            "H:|-\(ShareDialogControllerUX.ItemTitleLeftPadding)-[title]-\(ShareDialogControllerUX.ItemTitleRightPadding)-|",
            "V:[nav]-\(ShareDialogControllerUX.NavigationBarBottomPadding)-[title]",
            "H:|-\(ShareDialogControllerUX.ItemLinkLeftPadding)-[link]-\(ShareDialogControllerUX.ItemLinkLeftPadding)-|",
            "V:[title]-\(ShareDialogControllerUX.ItemTitleBottomPadding)-[link]",
            "H:|[divider]|",
            "V:[divider(\(ShareDialogControllerUX.DividerHeight))]",
            "V:[link]-\(ShareDialogControllerUX.ItemLinkBottomPadding)-[divider]",
            "H:|[table]|",
            "V:[divider][table]",
            "V:[table(\(ShareDialogControllerUX.TableHeight))]|"
        ]
        for constraint in constraints {
            view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(constraint, options: NSLayoutFormatOptions(), metrics: nil, views: views))
        }
    }
    // UITabBarItem Actions that map to our delegate methods
    func cancel() {
        delegate?.shareControllerDidCancel(self)
    }
    func add() {
        delegate?.shareController(self, didShareItem: item, toDestinations: NSSet(set: selectedShareDestinations))
    }
    // UITableView Delegate and DataSource
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return ShareDestinations.count
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return ShareDialogControllerUX.TableRowHeight
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.textColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.darkGrayColor() : ShareDialogControllerUX.TableRowTextColor
        cell.textLabel?.font = ShareDialogControllerUX.TableRowFont
        cell.accessoryType = selectedShareDestinations.containsObject(ShareDestinations[indexPath.row].code) ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None
        cell.tintColor = ShareDialogControllerUX.TableRowTintColor
        cell.layoutMargins = UIEdgeInsetsZero
        cell.textLabel?.text = ShareDestinations[indexPath.row].name
        cell.imageView?.image = UIImage(named: ShareDestinations[indexPath.row].image)
        return cell
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: false)
        let code = ShareDestinations[indexPath.row].code
        if selectedShareDestinations.containsObject(code) {
            selectedShareDestinations.removeObject(code)
        } else {
            selectedShareDestinations.addObject(code)
        }
        tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        
        navItem.rightBarButtonItem?.enabled = (selectedShareDestinations.count != 0)
    }
}
 | 
	mpl-2.0 | 
	d2dce2380da86fd726a01ef69bec4a7d | 44.81405 | 226 | 0.700911 | 6.038671 | false | false | false | false | 
| 
	AfricanSwift/TUIKit | 
	TUIKit/dev-graphic.swift | 
	1 | 
	11948 | 
	//
//          File:   main2.swift
//    Created by:   African Swift
import Darwin
//var t = TUITable(["abc", "mnopqrs", "xdefg 1234567", "hijkl", "a quick movement of the enemy"])
//print(t.value)
//
//
//var u = TUITable([["def", "12345", "a quick movement"],
//                  ["banana bunch", "zebra colony", "675"],
//                  ["apple pear orange", "dictate", "derk"]])
//// text to multi column
//let path = "/Users/VW/Desktop/testtv.txt"
//let tv = try String(contentsOfFile: path, encoding: .utf8)
//let lines = tv.characters
//  .split(separator: "\n", omittingEmptySubsequences: false)
//  .map { String($0) }.sorted()
//
//
//let third = Int(round(Double(lines.count) / 3))
//var array = init2D(d1: third + 1, d2: 3, repeatedValue: "")
//
//var r = 0
//var c = 0
//for line in lines
//{
//  if r == array.count {
//    r = 0
//    c += 1
//  }
//  array[r][c] = line
//  r += 1
//}
//
//
//var t = TUITable(array)
//print(t.value)
//public extension CountableClosedRange where Bound : Comparable
//{
//  public func isRange(within: CountableClosedRange) -> Bool
//  {
//    guard self.lowerBound >= within.lowerBound && self.upperBound <= within.upperBound
//      else { return false }
//    return true
//  }
//}
// --------------------------------------------------------
public extension ClosedRange where Bound : Comparable
{
  public func isRange(within: ClosedRange) -> Bool
  {
    guard self.lowerBound >= within.lowerBound && self.upperBound <= within.upperBound
      else { return false }
    return true
  }
}
private struct EllipseIterator
{
  private let center: TUIVec2
  private let square: TUISize
  private let square4: TUISize
  private var point1: TUIVec2
  private var point2: TUIVec2
  private var sigma1: Int
  private var sigma2: Int
  private let arc: ClosedRange<Int>
  private init(center: TUIVec2, size: TUISize, arc: ClosedRange<Int>)
  {
    self.center = center
    self.arc = arc
    self.square = TUISize(width: size.width * size.width, height: size.height * size.height)
    self.square4 = TUISize(width: square.width * 4, height: square.height * 4)
    self.point1 = TUIVec2(x: 0, y: size.height)
    self.point2 = TUIVec2(x: size.width, y: 0)
    self.sigma1 = 2 * Int(square.height) + Int(square.width) * (1 - 2 * Int(size.height))
    self.sigma2 = 2 * Int(square.width) + Int(square.height) * (1 - 2 * Int(size.width))
  }
  private func calcQuads(at: TUIVec2) -> [(ClosedRange<Int>, ClosedRange<Int>, Int, Int)]
  {
    let c = (x: Int(self.center.x), y: Int(self.center.y))
    let x = Int(at.x)
    let y = Int(at.y)
    return [(0...45, 45...90, c.x + x, c.y - y),
            (135...180, 90...135, c.x + x, c.y + y),
            (180...225, 225...270, c.x - x, c.y + y),
            (315...360, 270...315, c.x - x, c.y - y)]
  }
}
private extension EllipseIterator
{
  mutating func calcResult1(result: inout [TUIVec2])
  {
    result = calcQuads(at: point1).flatMap {
      return $0.0.isRange(within: self.arc) ? TUIVec2(x: $0.2, y: $0.3) : nil
    }
    if self.sigma1 >= 0
    {
      self.sigma1 += Int(self.square4.width) * (1 - Int(self.point1.y))
      self.point1.y -= 1
    }
    self.sigma1 += Int(self.square.height) * ((4 * Int(self.point1.x)) + 6)
    self.point1.x += 1
  }
  mutating func calcResult2(result: inout [TUIVec2], check1: Bool)
  {
    let quads2 = calcQuads(at: point2).flatMap {
      return $0.1.isRange(within: self.arc) ? TUIVec2(x: $0.2, y: $0.3) : nil
    }
    result = check1 ? result + quads2 : quads2
    if self.sigma2 >= 0
    {
      self.sigma2 += Int(square4.height) * (1 - Int(self.point2.x))
      self.point2.x -= 1
    }
    self.sigma2 += Int(square.width) * ((4 * Int(self.point2.y)) + 6)
    self.point2.y += 1
  }
}
extension EllipseIterator: IteratorProtocol
{
  mutating func next() -> [TUIVec2]?
  {
    var result = [TUIVec2()]
    let check1 = Int(self.square.height * self.point1.x) <= Int(self.square.width * self.point1.y)
    let check2 = Int(square.width * self.point2.y) <= Int(self.square.height * self.point2.x)
    // Stop when checks fails
    guard check1 || check2 else { return nil }
    // First call of ellipse quads
    if check1
    {
      calcResult1(result: &result)
    }
    // Second call of ellipse quads
    if check2
    {
      calcResult2(result: &result, check1: check1)
    }
    return result
  }
}
func drawEllipse(center: TUIVec2, size: TUISize, arc: ClosedRange<Int>,
                 view: inout TUIView, fill: Bool = false)
{
  let color = Ansi.Color(red: 0.6, green: 0.2, blue: 0.4, alpha: 1)
  var ellipse = EllipseIterator(center: center, size: size, arc: arc)
  while let point = ellipse.next()
  {
    point.forEach {
      _ = fill ? view.drawLine(from: center, to: $0, color: color) :
        view.drawPixel(at: $0, color: color)
    }
  }
}
func drawCircle(center: TUIVec2, radius: Double, arc: ClosedRange<Int>,
                view: inout TUIView, fill: Bool = false)
{
  let size = TUISize(width: radius, height: radius)
  drawEllipse(center: center, size: size, arc: arc, view: &view, fill: fill)
}
// --------------------------------------------------------
//guard let wSize = TUIWindow.ttysize() else { exit(EXIT_FAILURE) }
//
//Ansi.Set.cursorOff().stdout()
//
//let width = Int(wSize.character.width * 2) - 4
//let height = Int(wSize.character.height * 4) - 8 - 2 - 8
//let radius = min(width / 2, height / 2)
//Ansi.Cursor.column().stdout()
//
//var view = TUIView(x: 0, y: 0, width: width, height: height)
//let center = TUIVec2(x: width / 2, y: height / 2)
//
//var size = TUISize(width: width / 2 - 1, height: height / 2 - 2)
//
//let color = Ansi.Color(red: 0.6, green: 0.2, blue: 0.4, alpha: 1)
//
//
//for i in stride(from: 5, to: width / 2 - 2, by: 15)
//{
//  size = TUISize(width: i, height: height / 2 - 2)
//  drawEllipse(center: center, size: size, arc: 0...180, view: &view)
//}
//
//for i in stride(from: 5, to: height / 2 - 2, by: 15)
//{
//  size = TUISize(width: width / 2 - 2, height: i)
//  drawEllipse(center: center, size: size, arc: 90...270, view: &view)
//}
// --------------------------------------------------------
//let rect = TUIRectangle(x: 0, y: 0, width: 199, height: 99)
//
//view.drawRoundedRectangle(rect: rect, radius: 20)
//
//view.drawRectangle(rect: rect)
//let rect2 = TUIRectangle(x: 1, y: 1, width: 197, height: 97)
//view.drawRectangle(rect: rect2)
//let lines = [
//  (from: TUIVec2(x: 0, y: 0), to: TUIVec2(x: 0, y: 99)),
//  (from: TUIVec2(x: 0, y: 0), to: TUIVec2(x: 199, y: 0)),
//  (from: TUIVec2(x: 199, y: 0), to: TUIVec2(x: 199, y: 99)),
//  (from: TUIVec2(x: 0, y: 99), to: TUIVec2(x: 199, y: 99)),
//  (from: TUIVec2(x: 0, y: 0), to: TUIVec2(x: 199, y: 99)),
//  (from: TUIVec2(x: 0, y: 99), to: TUIVec2(x: 199, y: 0))]
//
//lines.forEach {
//  view.drawLine(from: $0.from, to: $0.to)
//}
//func plotLine(view: inout TUIView, from f: TUIVec2, to t: TUIVec2)
//{
//  let color = Ansi.Color(red: 0.6, green: 0.2, blue: 0.4, alpha: 1.0)
//  var from = (x: Int(f.x), y: Int(f.y))
//  let to = (x: Int(t.x), y: Int(t.y))
//  let distance = (x: abs(to.x - from.x), y: -abs(to.y - from.y))
//  let slope = (x: from.x < to.x ? 1 : -1, y: from.y < to.y ? 1 : -1)
//  var error1 = distance.x + distance.y
//
//  while true
//  {
//    view.drawPixel(x: from.x, y: from.y, color: color)
//    let error2 = 2 * error1
//
//    if error2 >= distance.y
//    {
//      if from.x == to.x
//      {
//        break
//      }
//      error1 += distance.y
//      from.x += slope.x
//    }
//
//    if error2 <= distance.x
//    {
//      if from.y == to.y
//      {
//        break
//      }
//      error1 += distance.x
//      from.y += slope.y
//    }
//  }
//}
//func plotEllipse(view: inout TUIView, center c: TUIVec2, size: TUISize)
//{
//  let radius = (width: Int(size.width), height: Int(size.height))
//  let color = Ansi.Color(red: 0.6, green: 0.2, blue: 0.4, alpha: 1.0)
//  let center = (x: Int(c.x), y: Int(c.y))
//  var x = -radius.width
//  var y = 0
//  var error2 = radius.height * radius.height
//  var error1 = x * (2 * error2 + x) + error2
//
//  repeat
//  {
//    view.drawPixel(x: center.x - x, y: center.y + y, color: color)
//    view.drawPixel(x: center.x + x, y: center.y + y, color: color)
//    view.drawPixel(x: center.x + x, y: center.y - y, color: color)
//    view.drawPixel(x: center.x - x, y: center.y - y, color: color)
//    error2 = 2 * error1
//    if error2 >= (x * 2 + 1) * radius.height * radius.height
//    {
//      x += 1
//      error1 += (x * 2 + 1) * radius.height * radius.height
//    }
//    if error2 <= (y * 2 + 1) * radius.width * radius.width
//    {
//      y += 1
//      error1 += (y * 2 + 1) * radius.width * radius.width
//    }
//  } while x <= 0
//
//  /* -> finish tip of ellipse */
////  while y < radius.height
////  {
////    view.drawPixel(x: center.x, y: center.y + y, color: color)
////    view.drawPixel(x: center.x, y: center.y - y, color: color)
////    y += 1
////  }
//}
func plotCircle(view: inout TUIView, center c: TUIVec2, radius: Int)
{
  let color = Ansi.Color(red: 0.6, green: 0.2, blue: 0.4, alpha: 1.0)
  let center = (x: Int(c.x), y: Int(c.y))
  var radius = radius
  var x = -radius
  var y = 0
  var error1 = 2 - 2 * radius      /* bottom left to top right */
  repeat
  {
    view.drawPixel(x: center.x - x, y: center.y + y, color: color)   /*   I. Quadrant +x +y */
    view.drawPixel(x: center.x - y, y: center.y - x, color: color)   /*  II. Quadrant -x +y */
    view.drawPixel(x: center.x + x, y: center.y - y, color: color)   /* III. Quadrant -x -y */
    view.drawPixel(x: center.x + y, y: center.y + x, color: color)   /*  IV. Quadrant +x -y */
    radius = error1
    if radius <= y
    {
      y += 1
      error1 += y * 2 + 1                             /* e_xy+e_y < 0 */
    }
    if radius > x || error1 > y                  /* e_xy+e_x > 0 or no 2nd y-step */
    {
      x += 1
      error1 += x * 2 + 1                                     /* -> x-step now */
    }
  } while x < 0
}
func alphaCode()
{
  guard let wSize = TUIWindow.ttysize() else { exit(EXIT_FAILURE) }
  Ansi.Set.cursorOff().stdout()
  let width = Int(wSize.character.width * 2) - 4
  let height = Int(wSize.character.height * 4) - 8 - 2 - 8
  let radius = min(width / 2, height / 2)
  Ansi.Cursor.column().stdout()
  
  var view = TUIView(x: 0, y: 0, width: width, height: height)
  let center = TUIVec2(x: width / 2, y: height / 2)
  let center2 = TUIVec2(x: width / 2 + 4, y: height / 2 + 4)
  
  var size = TUISize(width: width / 2 - 1, height: height / 2 - 2)
  
  let color = Ansi.Color(red: 0.6, green: 0.2, blue: 0.4, alpha: 1)
  
  plotCircle(view: &view, center: center, radius: 16)
  plotCircle(view: &view, center: center, radius: 17)
  plotCircle(view: &view, center: center, radius: 18)
  plotCircle(view: &view, center: center, radius: 19)
  plotCircle(view: &view, center: center, radius: 20)
  plotCircle(view: &view, center: center, radius: 21)
  plotCircle(view: &view, center: center, radius: 40)
  plotCircle(view: &view, center: center, radius: 41)
  plotCircle(view: &view, center: center, radius: 42)
  plotCircle(view: &view, center: center, radius: 53)
  plotCircle(view: &view, center: center, radius: 54)
  plotCircle(view: &view, center: center, radius: 58)
  plotCircle(view: &view, center: center, radius: 59)
  plotCircle(view: &view, center: center, radius: 60)
  
//  for i in stride(from: 5, to: width / 2 - 2, by: 15)
//  {
//    size = TUISize(width: i, height: height / 2 - 2)
//    drawEllipse(center: center, size: size, arc: 0...360, view: &view)
//  }
//  
//  for i in stride(from: 5, to: height / 2 - 2, by: 15)
//  {
//    size = TUISize(width: width / 2 - 2, height: i)
//    drawEllipse(center: center, size: size, arc: 0...360, view: &view)
//  }
  
  let param = TUIRenderParameter(colorspace: .foreground256, composite: .first, style: .drawille)
  view.draw(parameters: param)
}
 | 
	mit | 
	800b7c959df6434244d4243cb8a4491e | 30.114583 | 98 | 0.570639 | 2.884597 | false | false | false | false | 
| 
	SoufianeLasri/Sisley | 
	Sisley/ValidateButton.swift | 
	1 | 
	1258 | 
	//
//  ValidateButton.swift
//  Sisley
//
//  Created by Soufiane Lasri on 29/12/2015.
//  Copyright © 2015 Soufiane Lasri. All rights reserved.
//
import UIKit
class ValidateButton: UIButton {
    init( frame: CGRect, color: UIColor ) {
        super.init( frame: frame )
        
        self.backgroundColor = color
        self.layer.cornerRadius = self.frame.width / 2
        
        let validatePath = UIBezierPath()
        validatePath.moveToPoint( CGPoint( x: self.frame.width / 2 - 10, y: self.frame.height / 2 ) )
        validatePath.addLineToPoint( CGPoint( x: self.frame.width / 2 - 2, y: self.frame.height / 2 + 7 ) )
        validatePath.addLineToPoint( CGPoint( x: self.frame.width / 2 + 10, y: self.frame.height / 2 - 7 ) )
        
        let validateLayer         = CAShapeLayer()
        validateLayer.path        = validatePath.CGPath
        validateLayer.lineWidth   = 2.5
        validateLayer.lineCap     = kCALineJoinRound
        validateLayer.fillColor   = UIColor.clearColor().CGColor
        validateLayer.strokeColor = UIColor.whiteColor().CGColor
        self.layer.addSublayer( validateLayer )
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
} | 
	mit | 
	11ce57392808b1bd22eec935fab26a2d | 34.942857 | 108 | 0.632458 | 4.246622 | false | false | false | false | 
| 
	hayasilin/Crack-the-term | 
	ForgotPasswordViewController.swift | 
	1 | 
	2594 | 
	//
//  ForgotPasswordViewController.swift
//  CrackTheTerm_review
//
//  Created by Kuan-Wei Lin on 8/22/15.
//  Copyright (c) 2015 Kuan-Wei Lin. All rights reserved.
//
import UIKit
class ForgotPasswordViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var resentBtn: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        emailTextField.delegate = self
        resentBtn.layer.cornerRadius = 5
    }
    
    @IBAction func resentEmailAction(sender: UIButton) {
        let email = emailTextField.text
        
        PFUser.requestPasswordResetForEmailInBackground(email!, block: {
            (success: Bool, error: NSError?) -> Void in
            if error == nil{
                print("Resent Email successfully")
                let alertController = UIAlertController(title: "寄出成功", message: "已經重新寄出密碼信", preferredStyle: UIAlertControllerStyle.Alert)
                let goLoginAction = UIAlertAction(title: "前往登入頁面", style: UIAlertActionStyle.Default, handler: { (alert: UIAlertAction) -> Void in
                    
                    let logInViewController: UIViewController = self.storyboard?.instantiateViewControllerWithIdentifier("loginVC") as! LogInViewController
                    self.presentViewController(logInViewController, animated: true, completion: nil)
                })
                
                let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Default, handler: nil)
                
                alertController.addAction(goLoginAction)
                alertController.addAction(cancelAction)
                self.presentViewController(alertController, animated: true, completion: nil)
                
            }else{
                print("erro occur")
                let alertController = UIAlertController(title: "查無此人", message: "並無此信箱,是否仍無註冊呢?", preferredStyle: UIAlertControllerStyle.Alert)
                let alertAction = UIAlertAction(title: "我知道了", style: UIAlertActionStyle.Default, handler: nil)
                alertController.addAction(alertAction)
                self.presentViewController(alertController, animated: true, completion: nil)
            }
        })
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        view.endEditing(true)
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        return true
    }
    
    
}
 | 
	mit | 
	ea894ef76c70c429723531d87d984a8a | 40.114754 | 155 | 0.635167 | 5.235908 | false | false | false | false | 
			Subsets and Splits
				
	
				
			
				
No community queries yet
The top public SQL queries from the community will appear here once available.