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
eurofurence/ef-app_ios
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Modules/Principal Content/TabBarController.swift
1
2428
import UIKit class TabBarController: UITabBarController { override func show(_ vc: UIViewController, sender: Any?) { selectedViewController?.show(vc, sender: sender) } override func showDetailViewController(_ vc: UIViewController, sender: Any?) { selectedViewController?.showDetailViewController(vc, sender: sender) } override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { let newlySelectedIndex = tabBar.items?.firstIndex(of: item) ?? -1 let selectingSameTab = selectedIndex == newlySelectedIndex if selectingSameTab { guard let viewController = viewControllers?[newlySelectedIndex] else { return } performHeuristicTapInteraction(viewController: viewController) } } private func performHeuristicTapInteraction(viewController: UIViewController) { switch viewController { case let viewController as UISplitViewController: guard let mainViewcontroller = viewController.viewControllers.first else { return } performHeuristicTapInteraction(viewController: mainViewcontroller) case let viewController as UINavigationController: if viewController.viewControllers.count > 1 { viewController.popToRootViewController(animated: true) } else { guard let topViewController = viewController.topViewController else { return } performHeuristicTapInteraction(viewController: topViewController) } default: guard let tableView = viewController.view.firstDescendant(ofKind: UITableView.self) else { return } guard tableView.numberOfSections > 0 && tableView.numberOfRows(inSection: 0) > 0 else { return } let firstIndexPath = IndexPath(item: 0, section: 0) tableView.scrollToRow(at: firstIndexPath, at: .top, animated: true) } } } private extension UIView { func firstDescendant<ViewType>(ofKind kind: ViewType.Type) -> ViewType? { if let targetType = self as? ViewType { return targetType } else { for subview in subviews { if let targetType = subview as? ViewType { return targetType } } } return nil } }
mit
26c042d8beb3e3c1cd5f5d8bdaeda0bf
36.9375
111
0.634267
5.980296
false
false
false
false
GeoThings/LakestoneGeometry
Tests/LakestoneGeometryTests/TestLine.swift
1
7622
// // TestLine.swift // LakestoneGeometry // // Created by Volodymyr Andriychenko on 24/10/2016. // Copyright © 2016 GeoThings. 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. // #if COOPER import remobjects.elements.eunit import lakestonecore.android #else import XCTest import Foundation import LakestoneCore @testable import LakestoneGeometry #endif public class TestLine: Test { public func testLineOperations() { let origin = Coordinate(x: 0, y: 0) var testCoordinate1: Coordinate var testCoordinate2: Coordinate var testCoordinate3: Coordinate var testCoordinate4: Coordinate var testLine1: Line var testLine2: Line var testLine3: Line //init line1 testCoordinate1 = origin testCoordinate2 = Coordinate(x: 3, y: 4) testLine1 = Line(endpointA: testCoordinate1, endpointB: testCoordinate2) let length1 = testCoordinate2.x * testCoordinate2.x + testCoordinate2.y * testCoordinate2.y // since this line comes from origin (0;0) its squared length should be equal // to sum of squares of coordinates of the second endpoint Assert.AreEqual(length1, testLine1.squaredLength) // length of the midpoint vector should be half of the original (quarter when squared) testCoordinate3 = testLine1.midPoint testLine1 = Line(endpointA: testCoordinate1, endpointB: testCoordinate3) testLine2 = Line(endpointA: testCoordinate3, endpointB: testCoordinate2) Assert.AreEqual(length1, testLine1.squaredLength * 4) Assert.IsTrue(testLine1.squaredLength == testLine2.squaredLength) //MARK: vector funcs //current state: point3 in the middle from origin (point1) and point2 testCoordinate4 = Coordinate(x: 6, y: 2) testLine3 = Line(endpointA: origin, endpointB: testCoordinate4) Assert.AreEqual(testLine3.dotProduct(withPoint: testCoordinate3), testLine2.dotProduct(withLine: testLine3)) Assert.AreEqual(testLine1.crossProduct(withLine: testLine3) * 2, -testLine3.crossProduct(withPoint: testCoordinate2)) Assert.AreEqual(testLine3.dotProduct(withLine: testLine3), testLine3.squaredLength) Assert.AreEqual(testLine3.dotProduct(withPoint: testCoordinate4), testLine3.squaredLength) testLine1 = Line(endpointA: origin, endpointB: Coordinate(x: testCoordinate2.x, y: 0)) testLine2 = Line(endpointA: origin, endpointB: Coordinate(x: 0, y: testCoordinate2.y)) Assert.AreEqual(testLine2.dotProduct(withLine: testLine1), 0) Assert.AreEqual(testLine1.crossProduct(withLine: testLine2), testCoordinate2.x * testCoordinate2.y) // distance check, requires some precision allowance // the values were calculated using http://www.wolframalpha.com, // where the numbers are rounded to fifth digit, which gives the precision up to 0.5e-5 testLine1 = Line(endpointA: Coordinate(x: -2, y: 0), endpointB: Coordinate(x: 1, y: 3)) testCoordinate1 = Coordinate(x: 3, y: 2) // the distance here is 3/sqtr(2), squared should be equal to 4.5 but still differs by some very small margin Assert.AreEqual(testLine1.distance(toPoint: testCoordinate1) * testLine1.distance(toPoint: testCoordinate1), Double(4.5), Double(1e-15)) testLine1 = Line(endpointA: Coordinate(x: -2, y: 0), endpointB: Coordinate(x: -1, y: 1)) testCoordinate1 = Coordinate(x: -0.5, y: -1) Assert.AreEqual(testLine1.distance(toPoint: testCoordinate1), Double(1.76777), Double(0.000005)) testLine1 = Line(endpointA: Coordinate(x: 0.46, y: 0), endpointB: Coordinate(x: 0.23, y: 1.15)) testCoordinate1 = Coordinate(x: 1, y: 1) Assert.AreEqual(testLine1.distance(toPoint: testCoordinate1), Double(0.72563), Double(0.000005)) //MARK: Bool checks // including endpoint Assert.IsFalse(testLine1.hasEndPoint(point: testCoordinate1)) Assert.IsTrue(testLine2.hasEndPoint(point: origin)) Assert.IsFalse(testLine3.hasEndPoint(point: testCoordinate3)) // are parallel //testLine3 is still from origin to point4(6,2) testLine1 = Line(endpointA: Coordinate(x: 0, y: -2), endpointB: Coordinate(x: 6, y: 0)) Assert.IsTrue(testLine1.isParallel(to: testLine3)) testLine1 = Line(endpointA: origin, endpointB: Coordinate(x: 6, y: 1.9)) Assert.IsFalse(testLine1.isParallel(to: testLine3)) // in this case they're on the same line testLine1 = Line(endpointA: Coordinate(x: 0, y: 5), endpointB: Coordinate(x: 0, y: 10)) Assert.IsTrue(testLine2.isParallel(to: testLine1)) //MARK: intersection // the values were calculated using http://www.wolframalpha.com, // which in the case of given lines provides the result as fractions Assert.IsNil(testLine1.intersection(withLine: testLine2)) Assert.AreEqual(testLine2.intersection(withLine: testLine3)!, origin) testLine1 = Line(endpointA: Coordinate(x: -0.1, y: 0.1), endpointB: Coordinate(x: -0.6, y: 0.6)) testLine2 = Line(endpointA: Coordinate(x: -0.5, y: 0), endpointB: Coordinate(x: 0, y: 1)) testCoordinate1 = testLine2.intersection(withLine: testLine1)! testCoordinate2 = Coordinate(x: -1.0/3.0, y: 1.0/3.0) Assert.AreEqual(testCoordinate1.x, testCoordinate2.x, Double(1e-15)) Assert.AreEqual(testCoordinate1.y, testCoordinate2.y, Double(1e-15)) testLine1 = Line(endpointA: Coordinate(x: 10.0/2.2, y: 0), endpointB: Coordinate(x: 0, y: 10)) testCoordinate1 = testLine3.intersection(withLine: testLine1)! testCoordinate2 = Coordinate(x: 75.0/19.0, y: 25.0/19.0) Assert.AreEqual(testCoordinate1.x, testCoordinate2.x, Double(1e-15)) Assert.AreEqual(testCoordinate1.y, testCoordinate2.y, Double(1e-15)) //MARK: point lies on the line Assert.IsTrue(does(point: testCoordinate1, liesOnTheLine: testLine1)) Assert.IsTrue(does(point: testCoordinate1, liesOnTheLine: testLine3)) Assert.IsTrue(does(point: testCoordinate2, liesOnTheLine: testLine3)) testCoordinate1 = Coordinate(x: 4.5, y: 1.5) Assert.IsTrue(does(point: testCoordinate1, liesOnTheLine: testLine3)) testCoordinate1 = Coordinate(x: 5, y: 1.5) Assert.IsFalse(does(point: testCoordinate1, liesOnTheLine: testLine3)) } } #if !COOPER extension TestLine { static var allTests : [(String, (TestLine) -> () throws -> Void)] { return [ ("testLineOperations", testLineOperations) ] } } #endif
apache-2.0
54414ce9bedaf0f86c0e274ccb1a7908
44.622754
117
0.652448
3.907179
false
true
false
false
mightydeveloper/swift
validation-test/compiler_crashers_fixed/1070-void.swift
13
394
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import CoreData if true { struct Q<T where I.c : a { deinit { protocol a { } protocol A { struct S { } } } print() { let f = A(x: String = "A>(b: d = A.b = c() typealias R = F>()
apache-2.0
1e351c409b117406e1ab626dcba50a91
18.7
87
0.667513
3.102362
false
true
false
false
acidstudios/WorldCupSwift
WorldCup/Classes/CountryMatches/ACDCountryTableViewController.swift
1
3267
// // ACDCountryTableViewController.swift // WorldCup // // Created by Acid Studios on 20/06/14. // Copyright (c) 2014 Acid Studios. All rights reserved. // import UIKit class ACDCountryTableViewController: UITableViewController { var country:CountryModel = CountryModel() var matches: MatchModel[] = Array() init(style: UITableViewStyle) { super.init(style: style) // Custom initialization } init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) UIApplication.sharedApplication().networkActivityIndicatorVisible = true self.title = country.country var request = NSURLRequest(URL: NSURL(string: "http://worldcup.sfg.io/matches/country?fifa_code=\(self.country.fifa_code)")) var session = NSURLSession.sharedSession() session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as AnyObject[] if(json.count > 0) { var matches: MatchModel[] = json.map { var model: MatchModel = MatchModel(dict: $0 as NSDictionary) return model } self.matches = matches self.tableView.reloadData() } UIApplication.sharedApplication().networkActivityIndicatorVisible = false }).resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // #pragma mark - Table view data source override func numberOfSectionsInTableView(tableView: UITableView?) -> Int { return 1 } override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { return self.matches.count } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell = tableView.dequeueReusableCellWithIdentifier("CountryMatchCell", forIndexPath: indexPath) as UITableViewCell var match = self.matches[indexPath.row] cell.textLabel.text = "\(match.home_team.country) V.S \(match.away_team.country)" cell.detailTextLabel.text = "Stadium: \(match.location) Score: \(match.home_team.goals) - \(match.away_team.goals)" if(match.status == "completed") { cell.accessoryType = UITableViewCellAccessoryType.Checkmark } return cell } override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if(segue.identifier == "ViewGameDetails") { var matchDetail = segue.destinationViewController as ACDMatchDetailViewController var indexpath = self.tableView.indexPathForSelectedRow() var match = self.matches[indexpath.row] matchDetail.GameDetail = match; } } }
mit
33a37e6ae3af072648c8661a100f82be
35.3
143
0.640955
5.193959
false
false
false
false
linhaosunny/smallGifts
小礼品/小礼品/Classes/Module/Me/Views/MeHeaderView.swift
1
5255
// // MeHeaderView.swift // 小礼品 // // Created by 李莎鑫 on 2017/4/24. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit import SDWebImage fileprivate let buttonPhotoWidth:CGFloat = 65.0 fileprivate let labelGenderManColor:UIColor = UIColor(red: 27.0/255.0, green: 158.0/255.0, blue: 252.0/255.0, alpha: 1.0) class MeHeaderView: UIView { //MARK: 属性 weak var delegate:MeHeaderViewDelegate? { didSet{ optionFooterView.delegate = delegate as! MeHeadFooterViewDelegate? } } var viewModel:MeHeaderViewModel? { didSet{ if !viewModel!.isEmptyModel { headImage.sd_setImage(with: viewModel?.headImageUrl, placeholderImage: #imageLiteral(resourceName: "me_avatar_boy")) nickNameLabel.text = viewModel?.userNameText genderImage.isHidden = false if viewModel!.gender == 1 { genderImage.image = #imageLiteral(resourceName: "boy_ziliao") if let _ = viewModel?.userNameText { nickNameLabel.textColor = labelGenderManColor } } else { genderImage.image = #imageLiteral(resourceName: "girl_ziliao") if let _ = viewModel?.userNameText { nickNameLabel.textColor = SystemNavgationBarTintColor } } } else { headImage.image = #imageLiteral(resourceName: "me_avatar_boy") nickNameLabel.text = "登录" genderImage.isHidden = true nickNameLabel.textColor = UIColor.white } } } //MARK: 懒加载 lazy var optionFooterView:MeHeadFooterView = MeHeadFooterView() lazy var backgroundImageView:UIImageView = { () -> UIImageView in let view = UIImageView(image: #imageLiteral(resourceName: "me_profile")) return view }() lazy var headImage:UIImageView = { () -> UIImageView in let view = UIImageView(image: #imageLiteral(resourceName: "me_avatar_boy")) view.layer.cornerRadius = buttonPhotoWidth * 0.5 view.layer.masksToBounds = true view.isUserInteractionEnabled = true view.addSubview(self.headIconButton) return view }() lazy var genderImage:UIImageView = { () -> UIImageView in let view = UIImageView() view.isHidden = true return view }() lazy var headIconButton:UIButton = { () -> UIButton in let button = UIButton(type: .custom) return button }() lazy var nickNameLabel:UILabel = { () -> UILabel in let label = UILabel() label.text = "登陆" label.textColor = UIColor.white label.font = fontSize14 label.sizeToFit() return label }() //MARK: 构造方法 override init(frame: CGRect) { super.init(frame: frame) setupMeHeaderView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() setupMeHeaderViewSubView() } //MARK: 私有方法 private func setupMeHeaderView() { backgroundColor = UIColor.white addSubview(backgroundImageView) addSubview(headImage) addSubview(genderImage) addSubview(nickNameLabel) addSubview(optionFooterView) headIconButton.addTarget(self, action: #selector(buttonClick(button:)), for: .touchUpInside) } private func setupMeHeaderViewSubView() { backgroundImageView.snp.makeConstraints { (make) in make.left.right.top.equalToSuperview() make.bottom.equalTo(optionFooterView.snp.top) } headImage.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(90.0) make.width.height.equalTo(buttonPhotoWidth) make.centerX.equalToSuperview() } genderImage.snp.makeConstraints { (make) in make.left.equalTo(headImage.snp.right) make.bottom.equalTo(headImage.snp.bottom) make.width.height.equalTo(margin*1.2) } headIconButton.snp.makeConstraints { (make) in make.edges.equalToSuperview().inset(UIEdgeInsets.zero) } nickNameLabel.snp.makeConstraints { (make) in make.top.equalTo(headIconButton.snp.bottom).offset(margin) make.centerX.equalToSuperview() } optionFooterView.snp.makeConstraints { (make) in make.left.right.bottom.equalToSuperview() make.height.equalTo(70.0) } } //MARK: 内部响应 @objc private func buttonClick(button:UIButton) { delegate?.meHeaderViewHeadIconButtonClick(button: button) } } //MARK: 协议 protocol MeHeaderViewDelegate:NSObjectProtocol { func meHeaderViewHeadIconButtonClick(button:UIButton) }
mit
0a222ec3e7200d5f78c37884942f08cd
30.634146
132
0.58616
4.912879
false
false
false
false
atrick/swift
validation-test/compiler_crashers_2_fixed/sr12723.swift
5
3420
// RUN: %target-swift-emit-silgen %s -verify func SR12723_thin(_: (@convention(thin) () -> Void) -> Void) {} func SR12723_block(_: (@convention(block) () -> Void) -> Void) {} func SR12723_c(_: (@convention(c) () -> Void) -> Void) {} func SR12723_function(_: () -> Void) {} func context() { SR12723_c(SR12723_function) SR12723_block(SR12723_function) SR12723_thin(SR12723_function) } struct SR12723_C { let function: (@convention(c) () -> Void) -> Void } struct SR12723_Thin { let function: (@convention(thin) () -> Void) -> Void } struct SR12723_Block { let function: (@convention(block) () -> Void) -> Void } func proxy(_ f: (() -> Void) -> Void) { let a = 1 f { print(a) } } func cContext() { let c = SR12723_C { app in app() } proxy(c.function) // expected-error@-1 {{converting non-escaping value to '@convention(c) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@convention(c) () -> Void) -> Void' to expected argument type '(() -> Void) -> Void'}} let _ : (@convention(block) () -> Void) -> Void = c.function // expected-error@-1 {{converting non-escaping value to '@convention(c) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@convention(c) () -> Void) -> Void' to specified type '(@convention(block) () -> Void) -> Void'}} let _ : (@convention(c) () -> Void) -> Void = c.function // OK let _ : (@convention(thin) () -> Void) -> Void = c.function // OK let _ : (() -> Void) -> Void = c.function // expected-error@-1 {{converting non-escaping value to '@convention(c) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@convention(c) () -> Void) -> Void' to specified type '(() -> Void) -> Void'}} } func thinContext() { let thin = SR12723_Thin { app in app() } proxy(thin.function) // expected-error@-1 {{converting non-escaping value to '@convention(thin) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@escaping @convention(thin) () -> Void) -> Void' to expected argument type '(() -> Void) -> Void'}} let _ : (@convention(block) () -> Void) -> Void = thin.function // expected-error@-1 {{converting non-escaping value to '@convention(thin) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@escaping @convention(thin) () -> Void) -> Void' to specified type '(@convention(block) () -> Void) -> Void'}} let _ : (@convention(c) () -> Void) -> Void = thin.function // OK let _ : (@convention(thin) () -> Void) -> Void = thin.function // OK let _ : (() -> Void) -> Void = thin.function // expected-error@-1 {{converting non-escaping value to '@convention(thin) () -> Void' may allow it to escape}} // expected-error@-2 {{cannot convert value of type '(@escaping @convention(thin) () -> Void) -> Void' to specified type '(() -> Void) -> Void'}} } func blockContext() { let block = SR12723_Block { app in app() } proxy(block.function) let _ : (@convention(block) () -> Void) -> Void = block.function // OK let _ : (@convention(c) () -> Void) -> Void = block.function // OK let _ : (@convention(thin) () -> Void) -> Void = block.function // OK let _ : (() -> Void) -> Void = block.function // OK }
apache-2.0
d5b614826d964a8dd49ea2d41295af8d
38.310345
168
0.587719
3.518519
false
false
false
false
github410117/XHNetworkingTool
XHMoyaNetworkTool/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift
29
4282
// // Observable+Bind.swift // RxCocoa // // Created by Krunoslav Zaher on 8/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift #endif extension ObservableType { /** Creates new subscription and sends elements to observer. In this form it's equivalent to `subscribe` method, but it communicates intent better, and enables writing more consistent binding code. - parameter observer: Observer that receives events. - returns: Disposable object that can be used to unsubscribe the observer. */ public func bindTo<O: ObserverType>(_ observer: O) -> Disposable where O.E == E { return self.subscribe(observer) } /** Creates new subscription and sends elements to observer. In this form it's equivalent to `subscribe` method, but it communicates intent better, and enables writing more consistent binding code. - parameter observer: Observer that receives events. - returns: Disposable object that can be used to unsubscribe the observer. */ public func bindTo<O: ObserverType>(_ observer: O) -> Disposable where O.E == E? { return self.map { $0 }.subscribe(observer) } /** Creates new subscription and sends elements to variable. In case error occurs in debug mode, `fatalError` will be raised. In case error occurs in release mode, `error` will be logged. - parameter variable: Target variable for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer. */ public func bindTo(_ variable: Variable<E>) -> Disposable { return subscribe { e in switch e { case let .next(element): variable.value = element case let .error(error): let error = "Binding error to variable: \(error)" #if DEBUG rxFatalError(error) #else print(error) #endif case .completed: break } } } /** Creates new subscription and sends elements to variable. In case error occurs in debug mode, `fatalError` will be raised. In case error occurs in release mode, `error` will be logged. - parameter variable: Target variable for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer. */ public func bindTo(_ variable: Variable<E?>) -> Disposable { return self.map { $0 as E? }.bindTo(variable) } /** Subscribes to observable sequence using custom binder function. - parameter binder: Function used to bind elements from `self`. - returns: Object representing subscription. */ public func bindTo<R>(_ binder: (Self) -> R) -> R { return binder(self) } /** Subscribes to observable sequence using custom binder function and final parameter passed to binder function after `self` is passed. public func bindTo<R1, R2>(binder: Self -> R1 -> R2, curriedArgument: R1) -> R2 { return binder(self)(curriedArgument) } - parameter binder: Function used to bind elements from `self`. - parameter curriedArgument: Final argument passed to `binder` to finish binding process. - returns: Object representing subscription. */ public func bindTo<R1, R2>(_ binder: (Self) -> (R1) -> R2, curriedArgument: R1) -> R2 { return binder(self)(curriedArgument) } /** Subscribes an element handler to an observable sequence. In case error occurs in debug mode, `fatalError` will be raised. In case error occurs in release mode, `error` will be logged. - parameter onNext: Action to invoke for each element in the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ public func bindNext(_ onNext: @escaping (E) -> Void) -> Disposable { return subscribe(onNext: onNext, onError: { error in let error = "Binding error: \(error)" #if DEBUG rxFatalError(error) #else print(error) #endif }) } }
mit
64847f840aec42118bbcf99d2082928a
32.708661
112
0.632562
4.777902
false
false
false
false
plutoless/fgo-pluto
FgoPluto/FgoPluto/model/ChaldeaManager.swift
1
12908
// // ChaldeaManager.swift // FgoPluto // // Created by Zhang, Qianze on 17/09/2017. // Copyright © 2017 Plutoless Studio. All rights reserved. // import Foundation import JavaScriptCore import RealmSwift import Realm class ChaldeaManager: NSObject { private let USER_CONTEXT = "USER_CONTEXT" private struct UserContext{ static let account = "account" } static var skill_qp:[[Int64]] = [] static var ad_qp:[[Int64]] = [] //chaldea relevant internal var servants:[Servant] = [] internal var materials:[Material] = [] internal var configuration:Realm.Configuration = Realm.Configuration() //context data private var _contexts:[String:AnyObject]? internal var contexts:[String:AnyObject] { get{ if(_contexts == nil){ if let data = UserDefaults.standard.value(forKey: USER_CONTEXT) as? Data{ _contexts = NSKeyedUnarchiver.unarchiveObject(with: data) as? [String: AnyObject] } } return _contexts ?? [:] } set{ _contexts = newValue } } internal var account:String{ get{ return self.contexts[UserContext.account] as? String ?? "default" } set{ self.contexts[UserContext.account] = newValue as AnyObject self.sync_contexts() } } static let sharedInstance: ChaldeaManager = { let instance = ChaldeaManager() return instance }() private func sync_contexts(){ guard let c = _contexts else {return} let data = NSKeyedArchiver.archivedData(withRootObject: c) UserDefaults.standard.setValue(data, forKey: USER_CONTEXT) UserDefaults.standard.synchronize() } override init(){ super.init() //prepare db config let db_url = URL.documentFolderPath().changeDirectory(folder: "db").file(path: "\(self.account).realm") self.configuration.fileURL = db_url self.configuration.schemaVersion = 1 self.configuration.migrationBlock = {migration, oldSchemaVersion in if (oldSchemaVersion < 1) { // Nothing to do! // Realm will automatically detect new properties and removed properties // And will update the schema on disk automatically } } Realm.Configuration.defaultConfiguration = self.configuration //load default db self.prepareDefaultDB(target_url: db_url) self.prepareDataFromJS() } private func prepareDefaultDB(target_url:URL){ if(!FileManager.default.fileExists(atPath: target_url.path)){ if let default_db_url = Bundle.main.url(forResource: "default", withExtension: "realm"){ try? FileManager.default.copyItem(at: default_db_url, to: target_url) } } do { let realm = try Realm() //materials must be written first realm.objects(Material.self).forEach({ material in self.materials.append(material) }) //as servants have dependencies on materials realm.objects(Servant.self).forEach({ servant in self.servants.append(servant) }) self.materials.sort { (m1, m2) -> Bool in return m1.id < m2.id } } catch { print(error) } } private func prepareDataFromJS(){ do { let servants_array:[[String:AnyObject]] = JSONHelper.loadJsonArray(file: "servants", type: "json") as! [[String:AnyObject]] ChaldeaManager.skill_qp = JSONHelper.loadJsonArray(file: "skill_qp", type: "json") as! [[Int64]] ChaldeaManager.ad_qp = JSONHelper.loadJsonArray(file: "ad_qp", type: "json") as! [[Int64]] let realm = try Realm() try realm.write { realm.delete(realm.objects(Servant.self)) self.servants = [] for item:[String:AnyObject] in servants_array{ let servant = Servant() servant.fillvalues(realm: realm, data: item) self.servants.append(servant) realm.add(servant) } } } catch { print(error) } } internal func servantsByClass() -> [Int: [Servant]]{ var results:[Int: [Servant]] = [:] for servant:Servant in self.servants{ let kind:Int = servant.kind if(results[kind] == nil){ results[kind] = [] } results[kind]?.append(servant) } return results; } internal func materialsByClass() -> [Int: [Material]]{ var results:[Int: [Material]] = [:] for material:Material in self.materials{ let kind:Int = material.kind if(results[kind] == nil){ results[kind] = [] } results[kind]?.append(material) } return results; } func materialsById() -> [Int: Material]{ var results:[Int: Material] = [:] for material:Material in self.materials{ let mid:Int = material.id results[mid] = material } return results; } internal func encode_item_data() -> String{ // var d = "*c", e = "*b", c = "*s", b = "*g", a = "" // // do { // let realm = try Realm() // let qp = realm.object(ofType: Material.self, forPrimaryKey: 900) // a = String(qp?.quantity ?? 0, radix:32).padding(toLength: 6, withPad: "0", startingAt: 0) // print() // } catch { // print(error) // } return "" } internal func decode_servant_data(){ var code:String = "#08wxzh13awssf13dexs9p" do { let realm = try Realm() let initial = code.substringWithRange(lowerBound: 0, length: 1) if(initial != "#"){ //improper } else { code = code.substringWithRange(lowerBound: 1, length: code.characters.count - 1) if(code.characters.count % 7 != 0){ //improper } else { for i in 0..<code.characters.count / 7{ let piece = code.substringWithRange(lowerBound: i*7, length: 7) let servant_source = piece.substringWithRange(lowerBound: 0, length: 2) let servant_code:Int = strtol(servant_source, nil, 36) guard let servant:Servant = realm.object(ofType: Servant.self, forPrimaryKey: servant_code) else {print("Servant \(servant_code) not found"); continue} let data_source = piece.substringWithRange(lowerBound: 2, length: 5) let data_code:Int64 = strtoll(data_source, nil, 36) let parsed_data_source = "\(data_code)" if(parsed_data_source.characters.count != 8){ //improper } else { let ad_from = Int(parsed_data_source.substringWithRange(lowerBound: 0, length: 1)) ?? 0 // let ad_to = Int(parsed_data_source.substringWithRange(lowerBound: 1, length: 1)) ?? 4 let skill1_from = Int(parsed_data_source.substringWithRange(lowerBound: 2, length: 1)) ?? 0 // let skill1_to = Int(parsed_data_source.substringWithRange(lowerBound: 3, length: 1)) ?? 10 let skill2_from = Int(parsed_data_source.substringWithRange(lowerBound: 4, length: 1)) ?? 0 // let skill2_to = Int(parsed_data_source.substringWithRange(lowerBound: 5, length: 1)) ?? 10 let skill3_from = Int(parsed_data_source.substringWithRange(lowerBound: 6, length: 1)) ?? 0 // let skill3_to = Int(parsed_data_source.substringWithRange(lowerBound: 7, length: 1)) ?? 10 try realm.write { servant.ad_level = ad_from - 1 servant.skill1_level = skill1_from servant.skill2_level = skill2_from servant.skill3_level = skill3_from } } } } } }catch{ print(error) } } internal func decode_item_data(){ let code:String = "*c03a78j000a000o0008000z001k000e001u000z000b0007000j0018000h001w0012001h001f0016000k00080012000d001q00230014000s001x000n003c000a0001000l0004000s0004001h*b0047001d006i002t000l00000000*s0008000u000m000q001q000r000o001z0009000h0000*g000e000s001y001200180012001500090006000000000000" guard let realm = try? Realm() else {return} let h = 2 + 6 + 4 + 140 + 2 + 28 + 2 + 44 + 2 + 48 let start = code.index(code.startIndex, offsetBy: 0) let end = code.index(code.startIndex, offsetBy: 1) let range = start..<end let initial = code.substring(with: range) if(initial != "*"){ //improper format } else { if(code.characters.count == h){ let e = code.substringWithRange(lowerBound: 2, length: 150) let g = code.substringWithRange(lowerBound: 154, length: 4*7) let d = code.substringWithRange(lowerBound: 184, length: 4*11) let c = code.substringWithRange(lowerBound: 230, length: 4*12) try? realm.write { var obj = realm.object(ofType: Material.self, forPrimaryKey: 900) obj?.quantity = strtoll(e.substringWithRange(lowerBound: 0, length: 6), nil, 36) obj = realm.object(ofType: Material.self, forPrimaryKey: 800) obj?.quantity = strtoll(e.substringWithRange(lowerBound: 6, length: 4), nil, 36) //银棋 for i in 0..<7{ obj = realm.object(ofType: Material.self, forPrimaryKey: 100 + i) obj?.quantity = strtoll(e.substringWithRange(lowerBound: 10+i*4, length: 4), nil, 36) } //金棋 for i in 0..<7{ obj = realm.object(ofType: Material.self, forPrimaryKey: 110 + i) obj?.quantity = strtoll(e.substringWithRange(lowerBound: 38+i*4, length: 4), nil, 36) } for i in 0..<7{ obj = realm.object(ofType: Material.self, forPrimaryKey: 200 + i) obj?.quantity = strtoll(e.substringWithRange(lowerBound: 66+i*4, length: 4), nil, 36) } for i in 0..<7{ obj = realm.object(ofType: Material.self, forPrimaryKey: 210 + i) obj?.quantity = strtoll(e.substringWithRange(lowerBound: 94+i*4, length: 4), nil, 36) } for i in 0..<7{ obj = realm.object(ofType: Material.self, forPrimaryKey: 220 + i) obj?.quantity = strtoll(e.substringWithRange(lowerBound: 122+i*4, length: 4), nil, 36) } for i in 0..<7{ obj = realm.object(ofType: Material.self, forPrimaryKey: 300 + i) obj?.quantity = strtoll(g.substringWithRange(lowerBound: i*4, length: 4), nil, 36) } for i in 0..<11{ obj = realm.object(ofType: Material.self, forPrimaryKey: 400 + i) obj?.quantity = strtoll(d.substringWithRange(lowerBound: i*4, length: 4), nil, 36) } for i in 0..<12{ obj = realm.object(ofType: Material.self, forPrimaryKey: 500 + i) obj?.quantity = strtoll(c.substringWithRange(lowerBound: i*4, length: 4), nil, 36) } } } else { //improper format } } } }
apache-2.0
26ec1673e75bea898ffd2e3b64641c2e
39.309375
306
0.506008
4.593661
false
false
false
false
codwam/NPB
Demos/NPBDemo/NPBDemo/NPB Test/NPBPlayground.playground/Contents.swift
1
2617
//: Playground - noun: a place where people can play import UIKit // TODO: 引用外部文件 // && let a = 1 let b = 2 if a > 3, b > 0 { print("a 和 b 都成立") } else { print("a 或者 b 不成立") } // Protocol default value protocol NPBBarProtocol { var npb_size: CGSize { get set } // func npb_sizeThatFits(size: CGSize) -> CGSize // // func npb_backgroundView() -> UIView? } fileprivate struct AssociatedKeys { static var npb_size = CGSize.zero } extension NPBBarProtocol { var npb_size: CGSize { get { return objc_getAssociatedObject(self, &AssociatedKeys.npb_size) as! CGSize } set { objc_setAssociatedObject(self, &AssociatedKeys.npb_size, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } class Bar: NSObject, NPBBarProtocol { } var bar = Bar() bar.npb_size = CGSize(width: 100, height: 100) bar.npb_size // Test did set class Person: NSObject { var age: Int { get { return self.age } set { self.age = newValue } } } //let peron = Person() //peron.age //peron.age = 18 //peron.age // Wrapper final class ClosureWrapper<T>: NSObject, NSCopying { var closure: T? convenience init(closure: T?) { self.init() self.closure = closure } func copy(with zone: NSZone? = nil) -> Any { let wrapper = ClosureWrapper() wrapper.closure = closure return wrapper } } let xiaoming = Person() var associatedNameKey: String? objc_setAssociatedObject(xiaoming, &associatedNameKey, "xiaoming", .OBJC_ASSOCIATION_COPY_NONATOMIC) associatedNameKey objc_getAssociatedObject(xiaoming, &associatedNameKey) typealias npb_navigation_block_t = (UINavigationController, Bool) -> Void var closer: npb_navigation_block_t = { (_, _) in print("closer exec") } closer(UINavigationController(), true) //var associatedCloserKey: npb_navigation_block_t? var associatedCloserKey = "123" // nil objc_setAssociatedObject(xiaoming, &associatedCloserKey, closer, .OBJC_ASSOCIATION_COPY_NONATOMIC) associatedCloserKey objc_getAssociatedObject(xiaoming, &associatedCloserKey) // objc_setAssociatedObject(xiaoming, &associatedCloserKey, ClosureWrapper(closure: closer), .OBJC_ASSOCIATION_COPY_NONATOMIC) associatedCloserKey let getClosure = objc_getAssociatedObject(xiaoming, &associatedCloserKey) if let closureWrapper = getClosure as? ClosureWrapper<npb_navigation_block_t> { closureWrapper.closure?(UINavigationController(), true) }
mit
3bcc33c0c4ecd200781a12304db3da3a
20.558333
123
0.662543
3.749275
false
false
false
false
ProjectTorch/iOS
Torch-iOS/Views/DialogsTableView.swift
1
2953
import UIKit var currentUsername = "Bob" class DialogsTableView: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource{ var reuseIdentifier = "cell" var nicknamesArray = [String]() var messagesaArray = [String]() @IBOutlet weak var tableView: UITableView! @IBOutlet var connectActivityIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() connectActivityIndicator.startAnimating() nicknamesArray = ["Alice"] /*let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 20)) searchBar.placeholder = "Search Characters" searchBar.delegate = self self.tableView.tableHeaderView = searchBar*/ self.tableView.delegate = self self.tableView.dataSource = self let uuid = UUID().uuidString print(uuid) /*var contentOffset: CGPoint = self.tableView.contentOffset contentOffset.y += (self.tableView.tableHeaderView?.frame)!.height self.tableView.contentOffset = contentOffset*/ } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return nicknamesArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! DialogsTableCell //cell.lastMessageLabel.text = messagesaArray[indexPath.row] cell.usernameLabel.text = nicknamesArray[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! DialogsTableCell //recipientUsername = cell.usernameLabel.text! self.performSegue(withIdentifier: "ChatSegue", sender: self) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { print(searchText) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { print(searchBar.text) searchBar.text = nil } }
mit
9037da8b8912f83f80decf9248bb1e52
30.752688
127
0.65425
5.468519
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/HCILEReadLocalResolvableAddressReturn.swift
1
4114
// // HCILEReadLocalResolvableAddress.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// LE Read Local Resolvable Address Command /// /// The command is used to get the current local Resolvable Private Address being /// used for the corresponding peer Identity Address. The local’s resolvable address /// being used may change after the command is called. func lowEnergyReadLocalResolvableAddress(peerIdentifyAddressType: LowEnergyPeerIdentifyAddressType, peerIdentifyAddress: UInt64, timeout: HCICommandTimeout = .default) async throws -> UInt64 { let parameters = HCILEReadLocalResolvableAddress(peerIdentifyAddressType: peerIdentifyAddressType, peerIdentifyAddress: peerIdentifyAddress) let returnParameters = try await deviceRequest(parameters, HCILEReadLocalResolvableAddressReturn.self, timeout: timeout) return returnParameters.localResolvableAddress } } // MARK: - Command /// LE Read Local Resolvable Address Command /// /// The command is used to get the current local Resolvable Private Address //// being used for the corresponding peer Identity Address. /// The local’s resolvable address being used may change after the command is called. /// /// This command can be used at any time. /// /// When a Controller cannot find a Resolvable Private Address associated /// with the Peer Identity Address, it shall return the error code /// Unknown Connection Identifier (0x02). @frozen public struct HCILEReadLocalResolvableAddress: HCICommandParameter { //HCI_LE_Read_Local_ Resolvable_Address public static let command = HCILowEnergyCommand.readLocalResolvableAddress //0x002C public let peerIdentifyAddressType: LowEnergyPeerIdentifyAddressType //Peer_Identity_Address_Type public let peerIdentifyAddress: UInt64 //Peer_Identity_Address public init(peerIdentifyAddressType: LowEnergyPeerIdentifyAddressType, peerIdentifyAddress: UInt64) { self.peerIdentifyAddressType = peerIdentifyAddressType self.peerIdentifyAddress = peerIdentifyAddress } public var data: Data { let peerIdentifyAddressBytes = peerIdentifyAddress.littleEndian.bytes return Data([ peerIdentifyAddressType.rawValue, peerIdentifyAddressBytes.0, peerIdentifyAddressBytes.1, peerIdentifyAddressBytes.2, peerIdentifyAddressBytes.3, peerIdentifyAddressBytes.4, peerIdentifyAddressBytes.5, peerIdentifyAddressBytes.6, peerIdentifyAddressBytes.7 ]) } } // MARK: - Return parameter /// LE Read Local Resolvable Address Command /// /// The command is used to get the current local Resolvable Private Address //// being used for the corresponding peer Identity Address. /// The local’s resolvable address being used may change after the command is called. /// /// This command can be used at any time. /// /// When a Controller cannot find a Resolvable Private Address associated /// with the Peer Identity Address, it shall return the error code /// Unknown Connection Identifier (0x02). @frozen public struct HCILEReadLocalResolvableAddressReturn: HCICommandReturnParameter { public static let command = HCILowEnergyCommand.readLocalResolvableAddress //0x002C public static let length: Int = 6 /// Resolvable Private Address being used by the local device public let localResolvableAddress: UInt64 //Local_Resolvable_Address public init?(data: Data) { guard data.count == type(of: self).length else { return nil } self.localResolvableAddress = UInt64(littleEndian: UInt64(bytes: ((data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7])))) } }
mit
ccd781c191c0a551b9e206cff7de18ab
37.027778
149
0.70392
4.90681
false
false
false
false
BellAppLab/Keyboard
Sources/Keyboard/UIViewController+Keyboard.swift
1
3874
import ObjectiveC import UIKit internal struct AssociationKeys {} private extension AssociationKeys { static var handlesKeyboard = "com.bellapplab.handlesKeyboard.key" static var keyboardMargin = "com.bellapplab.keyboardMargin.key" } @objc public extension UIViewController { /// Toggles the `Keyboard` framework in this view controller. @IBInspectable var handlesKeyboard: Bool { get { return (objc_getAssociatedObject(self, &AssociationKeys.handlesKeyboard) as? NSNumber)?.boolValue ?? true } set { Keyboard.yo() objc_setAssociatedObject(self, &AssociationKeys.handlesKeyboard, NSNumber(booleanLiteral: newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Sets a margin between the keyboard and the currently active text input. /// /// Defaults to 40.0. @IBInspectable var keyboardMargin: NSNumber { get { return (objc_getAssociatedObject(self, &AssociationKeys.keyboardMargin) as? NSNumber) ?? NSNumber(floatLiteral: 40.0) } set { Keyboard.yo() objc_setAssociatedObject(self, &AssociationKeys.handlesKeyboard, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } private extension AssociationKeys { static var keyboardWasVisible = "com.bellapplab.handlesKeyboard.key" } fileprivate extension UIViewController { var margin: CGFloat { return CGFloat(keyboardMargin.doubleValue) + 20.0 } var keyboardWasVisible: Bool { get { return (objc_getAssociatedObject(self, &AssociationKeys.keyboardWasVisible) as? NSNumber)?.boolValue ?? false } set { objc_setAssociatedObject(self, &AssociationKeys.keyboardWasVisible, NSNumber(booleanLiteral: newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } public extension KeyboardChangeHandler where Self: UIViewController { func handleKeyboardChange(_ change: Keyboard.Change) { // Validating the View Controller's setup guard hasKeyboardConstraints || hasKeyboardViews else { assertionFailure("Keyboard says: \n\tTo correctly handle the keyboard, View Controllers must either set 'keyboardConstraints' or 'keyboardViews' in: \(self.classForCoder)") return } setKeyboardConstraintsToOriginal() let keyboardIsVisible = Keyboard.default.isVisible if keyboardWasVisible == false && keyboardIsVisible { makeOriginalFrames() } setKeyboardViewsToOriginal() let intersection = change.intersectionOfFinalRect(with: view.currentFirstResponder, andMargin: margin, in: view) setKeyboardConstraints(intersection: intersection) let animations: () -> Void = { [weak self] in if self?.hasKeyboardConstraints ?? false { self?.view.layoutIfNeeded() } self?.setKeyboardFrames(intersection: intersection) } UIView.animate(withDuration: change.transitionDuration, delay: 0.0, options: change.transitionAnimationOptions, animations: animations) { [weak self] finished in guard finished else { return } self?.keyboardWasVisible = keyboardIsVisible } } }
mit
a1a5295e1e1fc3870213ad1dba102e8a
33.589286
184
0.590346
5.697059
false
false
false
false
joshpc/ElasticPullToRefresh
SampleProject/ElasticPullToRefreshDemo/ViewController.swift
1
1297
// // ViewController.swift // ElasticPullToRefresh // // Created by Joshua Tessier on 2015-12-20. // Copyright © 2015-2018. All rights reserved. // import UIKit class ViewController: UIViewController { override func loadView() { let tableView = UITableView() let wrapper = ElasticPullToRefresh(scrollView: tableView) wrapper.didPullToRefresh = { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.seconds(2)) { wrapper.didFinishRefreshing() } } view = wrapper } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationItem.title = "Bananas" self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedStringKey.foregroundColor : UIColor.white, NSAttributedStringKey.font : UIFont.systemFont(ofSize: 18.0, weight: .bold) ]; self.navigationController?.navigationBar.isTranslucent = false self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) self.navigationController?.navigationBar.barTintColor = UIColor.purple } } class NavigationController: UINavigationController { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
mit
a32824e01582e75b99071bc79e2da359
29.857143
98
0.770833
4.423208
false
false
false
false
inaka/ColorPicker
ColorPicker/IkColorPicker.swift
1
8549
// // IkColorPicker.swift // ColorPicker // // Created by Sebastian Cancinos on 8/10/15. // Copyright (c) 2015 Inaka. All rights reserved. // import Foundation import UIKit protocol ColorPickerDelegate { func colorSelectedChanged(color: UIColor); } class IKColorPicker: UIView { private var viewPickerHeight = 0; private let brightnessPickerHeight = 30; private var hueColorsImageView: UIImageView!, brightnessColorsImageView: UIImageView!, fullColorImageView: UIImageView!; var delegate: ColorPickerDelegate?; func colorFor( x: CGFloat, y: CGFloat) -> UIColor { let screenSize: CGRect = UIScreen.mainScreen().bounds return UIColor(hue: (x/screenSize.width), saturation: y/CGFloat(viewPickerHeight), brightness:1, alpha: 1); } func colorWithColor(baseColor: UIColor, brightness: CGFloat) -> UIColor { var hue: CGFloat = 0.0; var saturation: CGFloat = 0.0; baseColor.getHue(&hue, saturation: &saturation, brightness: nil, alpha:nil); return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1); } func createHueColorImage() -> UIImage { let screenSize: CGRect = UIScreen.mainScreen().bounds let imageHeight = CGFloat(viewPickerHeight - brightnessPickerHeight); let imageWidth: CGFloat = screenSize.width; let size: CGSize = CGSize(width: imageWidth, height: CGFloat(imageHeight)); UIGraphicsBeginImageContext(size); let context: CGContextRef = UIGraphicsGetCurrentContext(); let recSize = CGSize(width:ceil(imageWidth/256), height:ceil(imageWidth/256)); for(var y: CGFloat = 0; y < imageHeight; y += imageHeight/256) { for(var x: CGFloat = 0; x < imageWidth; x += imageWidth/256) { let rec = CGRect(x: x, y: y, width: recSize.width , height: recSize.height); let color = self.colorFor(x, y: y); CGContextSetFillColorWithColor(context, color.CGColor); CGContextFillRect(context,rec); } } let hueImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return hueImage; } func createBrightnessImage(baseColor:UIColor) -> UIImage { let imageHeight = CGFloat(brightnessPickerHeight); let screenSize: CGRect = UIScreen.mainScreen().bounds let imageWidth: CGFloat = screenSize.width; let size: CGSize = CGSize(width: imageWidth, height: CGFloat(imageHeight)); UIGraphicsBeginImageContextWithOptions(size, false, 0); let context: CGContextRef = UIGraphicsGetCurrentContext(); let recSize = CGSize(width:ceil(imageWidth/256), height:imageHeight); var hue:CGFloat = 0.0; var saturation:CGFloat = 0.0; baseColor.getHue(&hue, saturation:&saturation, brightness:nil, alpha:nil); for(var x: CGFloat = 0; x < imageWidth; x += imageWidth/256) { let rec = CGRect(x: x, y: 0, width: recSize.width , height: recSize.height); let color = UIColor(hue: hue, saturation: saturation, brightness: (imageWidth-x)/imageWidth, alpha: 1); CGContextSetFillColorWithColor(context, color.CGColor); CGContextFillRect(context,rec); } let hueImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return hueImage; } func createFullColorImage(color :UIColor, size: CGSize, radius: CGFloat) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0); let context: CGContextRef = UIGraphicsGetCurrentContext(); let rec = CGRect(x: 0, y: 0, width: size.width , height: size.height); CGContextSetFillColorWithColor(context, color.CGColor); let roundedRect = UIBezierPath(roundedRect: rec, cornerRadius: radius); roundedRect.fillWithBlendMode(kCGBlendModeNormal, alpha: 1); let fullColorImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return fullColorImage; } func loadView() { let screenSize: CGRect = UIScreen.mainScreen().bounds viewPickerHeight = Int(ceil( screenSize.width / 1.10344)); self.frame = CGRect(x:0,y:0,width:Int(screenSize.width),height:viewPickerHeight); let hueColorImage = self.createHueColorImage(); self.hueColorsImageView = UIImageView(image: hueColorImage); self.addSubview(self.hueColorsImageView); let panRecognizer = UIPanGestureRecognizer(target: self, action:"baseColorPicking:"); self.hueColorsImageView.addGestureRecognizer(panRecognizer); let tapRecognizer = UITapGestureRecognizer(target: self, action: "baseColorPicking:"); self.hueColorsImageView.addGestureRecognizer(tapRecognizer); self.hueColorsImageView.userInteractionEnabled = true; //------ let brightnessColorImage = self.createBrightnessImage(self.selectedBaseColor); self.brightnessColorsImageView = UIImageView(image: brightnessColorImage); self.addSubview(self.brightnessColorsImageView); var brImgRect = self.brightnessColorsImageView.frame; brImgRect.origin.y = self.hueColorsImageView.frame.origin.y + self.hueColorsImageView.frame.size.height; self.brightnessColorsImageView.frame = brImgRect; self.brightnessColorsImageView.userInteractionEnabled = true; let brightSlideGesture = UIPanGestureRecognizer(target: self, action:Selector("colorPicking:")); self.brightnessColorsImageView.addGestureRecognizer(brightSlideGesture); let brightTapGesture = UITapGestureRecognizer(target: self, action: Selector("colorPicking:")); self.brightnessColorsImageView.addGestureRecognizer(brightTapGesture); self.brightnessColorsImageView.userInteractionEnabled = true; } internal var selectedColor: UIColor { didSet{ if((self.fullColorImageView) != nil) { let fullColorImage = self.createFullColorImage(selectedColor, size: CGSize(width: 40, height: 40),radius: CGFloat(6)); fullColorImageView.image = fullColorImage; } self.delegate?.colorSelectedChanged(self.selectedColor); } } var selectedBrightness: CGFloat { get { var brightness: CGFloat=0; self.selectedColor.getHue(nil, saturation: nil, brightness:&brightness, alpha:nil); return brightness; } } func setSelectedBrightness(brightness: CGFloat) { self.selectedColor = self.colorWithColor(self.selectedBaseColor, brightness:brightness); } var selectedBaseColor: UIColor { didSet{ var brightnessColorImage = self.createBrightnessImage(self.selectedBaseColor); self.brightnessColorsImageView.image = brightnessColorImage; } } func setColor(color: UIColor) { selectedBaseColor = color; selectedColor = color; } func baseColorPicking(sender: UIGestureRecognizer) { if(sender.numberOfTouches()==1) { let picked = sender.locationOfTouch(0, inView: sender.view); self.selectedBaseColor = self.colorFor(picked.x, y:picked.y); self.selectedColor = self.colorWithColor(self.selectedBaseColor, brightness:self.selectedBrightness); } } func colorPicking(sender: UIGestureRecognizer) { if(sender.numberOfTouches()==1) { var picked = sender.locationOfTouch(0, inView:sender.view); self.setSelectedBrightness((sender.view!.frame.width-picked.x)/sender.view!.frame.width); } } init(frame:CGRect, color: UIColor) { selectedColor = color; selectedBaseColor = color; super.init(frame: frame); self.loadView(); } required init(coder aDecoder: NSCoder) { selectedColor = UIColor.whiteColor(); selectedBaseColor = UIColor.whiteColor(); super.init(coder: aDecoder); self.loadView(); } }
apache-2.0
9fff49c1c359607cda4e1e9e282e0fc6
34.330579
134
0.640777
5.070581
false
false
false
false
SKrotkih/YTLiveStreaming
YTLiveStreaming/Credentials.swift
1
1551
// // Credentials.swift // YTLiveStreaming // import Foundation final class Credentials: NSObject { private static var _clientID: String? private static var _APIkey: String? private static let plistKeyClientID = "CLIENT_ID" private static let plistKeyAPIkey = "API_KEY" static var clientID: String { if Credentials._clientID == nil { Credentials._clientID = getInfo(plistKeyClientID) } assert(Credentials._clientID != nil, "Please put your Client ID to the Info.plist!") return Credentials._clientID! } static var APIkey: String { if Credentials._APIkey == nil { Credentials._APIkey = getInfo(plistKeyAPIkey) } assert(Credentials._APIkey != nil, "Please put your APY key to the Info.plist!") return Credentials._APIkey! } static private func getInfo(_ key: String) -> String? { if let plist = getPlist("Info"), let info = plist[key] as? String, !info.isEmpty { return info } else if let plist = getPlist("Config"), let info = plist[key] as? String, !info.isEmpty { return info } else { return nil } } static private func getPlist(_ name: String) -> NSDictionary? { var plist: NSDictionary? if let path = Bundle.main.path(forResource: name, ofType: "plist") { if let content = NSDictionary(contentsOfFile: path) as NSDictionary? { plist = content } } return plist } }
mit
d764e46fb06c5eb077573c6b7bacb052
30.653061
99
0.602837
4.40625
false
false
false
false
diegosanchezr/Chatto
ChattoAdditions/Source/Chat Items/TextMessages/Views/TextBubbleView.swift
1
10564
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit public protocol TextBubbleViewStyleProtocol { func bubbleImage(viewModel viewModel: TextMessageViewModelProtocol, isSelected: Bool) -> UIImage func bubbleImageBorder(viewModel viewModel: TextMessageViewModelProtocol, isSelected: Bool) -> UIImage? func textFont(viewModel viewModel: TextMessageViewModelProtocol, isSelected: Bool) -> UIFont func textColor(viewModel viewModel: TextMessageViewModelProtocol, isSelected: Bool) -> UIColor func textInsets(viewModel viewModel: TextMessageViewModelProtocol, isSelected: Bool) -> UIEdgeInsets } public final class TextBubbleView: UIView, MaximumLayoutWidthSpecificable, BackgroundSizingQueryable { public var preferredMaxLayoutWidth: CGFloat = 0 public var animationDuration: CFTimeInterval = 0.33 public var viewContext: ViewContext = .Normal { didSet { if self.viewContext == .Sizing { self.textView.dataDetectorTypes = .None self.textView.selectable = false } else { self.textView.dataDetectorTypes = .All self.textView.selectable = true } } } public var style: TextBubbleViewStyleProtocol! { didSet { self.updateViews() } } public var textMessageViewModel: TextMessageViewModelProtocol! { didSet { self.updateViews() } } public var selected: Bool = false { didSet { self.updateViews() } } override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } private func commonInit() { self.addSubview(self.bubbleImageView) self.addSubview(self.textView) } private lazy var bubbleImageView: UIImageView = { let imageView = UIImageView() imageView.addSubview(self.borderImageView) return imageView }() private var borderImageView: UIImageView = UIImageView() private var textView: UITextView = { let textView = ChatMessageTextView() textView.backgroundColor = UIColor.clearColor() textView.editable = false textView.selectable = true textView.dataDetectorTypes = .All textView.scrollsToTop = false textView.scrollEnabled = false textView.bounces = false textView.bouncesZoom = false textView.showsHorizontalScrollIndicator = false textView.showsVerticalScrollIndicator = false textView.layoutManager.allowsNonContiguousLayout = true textView.exclusiveTouch = true textView.textContainerInset = UIEdgeInsetsZero textView.textContainer.lineFragmentPadding = 0 return textView }() public private(set) var isUpdating: Bool = false public func performBatchUpdates(updateClosure: () -> Void, animated: Bool, completion: (() -> Void)?) { self.isUpdating = true let updateAndRefreshViews = { updateClosure() self.isUpdating = false self.updateViews() if animated { self.layoutIfNeeded() } } if animated { UIView.animateWithDuration(self.animationDuration, animations: updateAndRefreshViews, completion: { (finished) -> Void in completion?() }) } else { updateAndRefreshViews() } } private func updateViews() { if self.viewContext == .Sizing { return } if isUpdating { return } guard let style = self.style, viewModel = self.textMessageViewModel else { return } let font = style.textFont(viewModel: viewModel, isSelected: self.selected) let textColor = style.textColor(viewModel: viewModel, isSelected: self.selected) let bubbleImage = self.style.bubbleImage(viewModel: self.textMessageViewModel, isSelected: self.selected) let borderImage = self.style.bubbleImageBorder(viewModel: self.textMessageViewModel, isSelected: self.selected) if self.textView.font != font { self.textView.font = font} if self.textView.text != viewModel.text {self.textView.text = viewModel.text} if self.textView.textColor != textColor { self.textView.textColor = textColor self.textView.linkTextAttributes = [ NSForegroundColorAttributeName: textColor, NSUnderlineStyleAttributeName : NSUnderlineStyle.StyleSingle.rawValue ] } if self.bubbleImageView.image != bubbleImage { self.bubbleImageView.image = bubbleImage} if self.borderImageView.image != borderImage { self.borderImageView.image = borderImage } } private func bubbleImage() -> UIImage { return self.style.bubbleImage(viewModel: self.textMessageViewModel, isSelected: self.selected) } public override func sizeThatFits(size: CGSize) -> CGSize { return self.calculateTextBubbleLayout(preferredMaxLayoutWidth: size.width).size } // MARK: Layout public override func layoutSubviews() { super.layoutSubviews() let layout = self.calculateTextBubbleLayout(preferredMaxLayoutWidth: self.preferredMaxLayoutWidth) self.textView.bma_rect = layout.textFrame self.bubbleImageView.bma_rect = layout.bubbleFrame self.borderImageView.bma_rect = self.bubbleImageView.bounds } public var layoutCache: NSCache! private func calculateTextBubbleLayout(preferredMaxLayoutWidth preferredMaxLayoutWidth: CGFloat) -> TextBubbleLayoutModel { let layoutContext = TextBubbleLayoutModel.LayoutContext( text: self.textMessageViewModel.text, font: self.style.textFont(viewModel: self.textMessageViewModel, isSelected: self.selected), textInsets: self.style.textInsets(viewModel: self.textMessageViewModel, isSelected: self.selected), preferredMaxLayoutWidth: preferredMaxLayoutWidth ) if let layoutModel = self.layoutCache.objectForKey(layoutContext.hashValue) as? TextBubbleLayoutModel where layoutModel.layoutContext == layoutContext { return layoutModel } let layoutModel = TextBubbleLayoutModel(layoutContext: layoutContext) layoutModel.calculateLayout() self.layoutCache.setObject(layoutModel, forKey: layoutContext.hashValue) return layoutModel } public var canCalculateSizeInBackground: Bool { return true } } private final class TextBubbleLayoutModel { let layoutContext: LayoutContext var textFrame: CGRect = CGRect.zero var bubbleFrame: CGRect = CGRect.zero var size: CGSize = CGSize.zero init(layoutContext: LayoutContext) { self.layoutContext = layoutContext } class LayoutContext: Equatable, Hashable { let text: String let font: UIFont let textInsets: UIEdgeInsets let preferredMaxLayoutWidth: CGFloat init (text: String, font: UIFont, textInsets: UIEdgeInsets, preferredMaxLayoutWidth: CGFloat) { self.font = font self.text = text self.textInsets = textInsets self.preferredMaxLayoutWidth = preferredMaxLayoutWidth } var hashValue: Int { get { return self.text.hashValue ^ self.textInsets.bma_hashValue ^ self.preferredMaxLayoutWidth.hashValue ^ self.font.hashValue } } } func calculateLayout() { let textHorizontalInset = self.layoutContext.textInsets.bma_horziontalInset let maxTextWidth = self.layoutContext.preferredMaxLayoutWidth - textHorizontalInset let textSize = self.textSizeThatFitsWidth(maxTextWidth) let bubbleSize = textSize.bma_outsetBy(dx: textHorizontalInset, dy: self.layoutContext.textInsets.bma_verticalInset) self.bubbleFrame = CGRect(origin: CGPoint.zero, size: bubbleSize) self.textFrame = UIEdgeInsetsInsetRect(self.bubbleFrame, self.layoutContext.textInsets) self.size = bubbleSize } private func textSizeThatFitsWidth(width: CGFloat) -> CGSize { return self.layoutContext.text.boundingRectWithSize( CGSize(width: width, height: CGFloat.max), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: [NSFontAttributeName: self.layoutContext.font], context: nil ).size.bma_round() } } private func == (lhs: TextBubbleLayoutModel.LayoutContext, rhs: TextBubbleLayoutModel.LayoutContext) -> Bool { return lhs.text == rhs.text && lhs.textInsets == rhs.textInsets && lhs.font == rhs.font && lhs.preferredMaxLayoutWidth == rhs.preferredMaxLayoutWidth } /// UITextView with hacks to avoid selection, loupe, define... private final class ChatMessageTextView: UITextView { override func canBecomeFirstResponder() -> Bool { return false } override func addGestureRecognizer(gestureRecognizer: UIGestureRecognizer) { if gestureRecognizer.dynamicType == UILongPressGestureRecognizer.self && gestureRecognizer.delaysTouchesEnded { super.addGestureRecognizer(gestureRecognizer) } } override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { return false } }
mit
a242f770e0b4f8fbb112438e6338bd2a
38.565543
160
0.690363
5.24268
false
false
false
false
appnexus/mobile-sdk-ios
examples/SimpleMediation/SimpleMediation/MediationViewController/Admob/AdMobDFPNativeViewController.swift
1
3755
/* Copyright 2020 APPNEXUS INC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import AppNexusSDK import GoogleMobileAds class AdMobDFPNativeViewController: UIViewController , ANNativeAdRequestDelegate , ANNativeAdDelegate { var gadNativeAdView: GADNativeAdView? var nativeAdRequest: ANNativeAdRequest? var nativeAdResponse: ANNativeAdResponse? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. nativeAdRequest = ANNativeAdRequest() nativeAdRequest!.placementId = "25115874" nativeAdRequest!.shouldLoadIconImage = true nativeAdRequest!.shouldLoadMainImage = true nativeAdRequest!.delegate = self nativeAdRequest!.loadAd() Toast.show(message: "Loading Ad...!! Please wait", controller: self) } // MARK: - ANNativeAdRequestDelegate & ANNativeAdDelegate func adRequest(_ request: ANNativeAdRequest, didReceive response: ANNativeAdResponse) { self.nativeAdResponse = response self.nativeAdResponse?.delegate = self self.nativeAdResponse?.clickThroughAction = ANClickThroughAction.openSDKBrowser createGADNativeAdView() populateGADUnifiedNativeViewWithResponse() Toast.show(message:"Ad did receive ad", controller: self) } func createGADNativeAdView() { let adNib = UINib(nibName: "UnifiedNativeAdView", bundle: Bundle(for: type(of: self))) let array = adNib.instantiate(withOwner: self, options: nil) gadNativeAdView = (array.first as! GADNativeAdView) } func populateGADUnifiedNativeViewWithResponse() { let nativeAdView = gadNativeAdView (nativeAdView?.headlineView as? UILabel)?.text = self.nativeAdResponse?.title (nativeAdView?.bodyView as? UILabel)?.text = self.nativeAdResponse?.body (nativeAdView?.callToActionView as? UIButton)?.setTitle(self.nativeAdResponse?.callToAction, for: .normal) (nativeAdView?.iconView as? UIImageView)?.image = self.nativeAdResponse?.iconImage // Main Image is automatically added by GoogleSDK in the MediaView (nativeAdView?.advertiserView as? UILabel)?.text = self.nativeAdResponse?.sponsoredBy self.view.addSubview(self.gadNativeAdView!) do { let rvc = (UIApplication.shared.keyWindow?.rootViewController)! try nativeAdResponse!.registerView(forTracking: self.gadNativeAdView!, withRootViewController: rvc, clickableViews: [(nativeAdView?.callToActionView) as Any]) } catch { Toast.show(message: "Failed to registerView for Tracking", controller: self) } } func adRequest(_ request: ANNativeAdRequest, didFailToLoadWithError error: Error, with adResponseInfo: ANAdResponseInfo?) { Toast.show(message: "ad requestFailedWithError \(error)", controller: self) } func adDidLogImpression(_ ad: Any) { // Toast.show(message: "adDidLogImpression", controller: self) print("adDidLogImpression===?") } func adWillClose(_ ad: Any) { print("adWillClose===?") } }
apache-2.0
046522e599fb859b5138b2fe4894b35d
37.316327
170
0.691079
4.86399
false
false
false
false
pauljohanneskraft/Math
CoreMath/Classes/Linear Algebra/Matrix.swift
1
472
// // Matrix.swift // Math // // Created by Paul Kraft on 19.12.17. // Copyright © 2017 pauljohanneskraft. All rights reserved. // import Foundation public protocol Matrix: LinearAlgebraic { static func *= <L: LinearAlgebraic>(lhs: inout Self, rhs: L) where L.Number == Number } extension Matrix where Self: All { public static func * <L: LinearAlgebraic>(lhs: Self, rhs: L) -> Self where L.Number == Number { return lhs.copy { $0 *= rhs } } }
mit
9c2734bc1e120667e459a07af9a934f2
23.789474
99
0.653928
3.437956
false
false
false
false
madcato/OSFramework
Sources/OSFramework/UrlHelper.swift
1
996
// // AppleUrlHelper.swift // OSFramework // // Created by Daniel Vela on 30/04/2017. // Copyright © 2017 Daniel Vela. All rights reserved. // class UrlHelper { func launch(_ urlStr: String) { if let url = URL(string: urlStr) { UIApplication.shared.openURL(url) } else { assertionFailure() } } } class MapUrlHelper: UrlHelper { func directionsTo(address: String) { if let scapedAddress = address.addingPercentEncoding( withAllowedCharacters: CharacterSet.urlQueryAllowed) { let url = "http://maps.apple.com/?daddr=\(scapedAddress)&dirflg=w&t=m" super.launch(url) } } func directionsTo(location: String) { if let scapedLocation = location.addingPercentEncoding( withAllowedCharacters: CharacterSet.urlQueryAllowed) { let url = "http://maps.apple.com/?daddr=\(scapedLocation)&dirflg=w&t=m" super.launch(url) } } }
mit
fe0452b0ef96db33808a95a7b26849f5
27.428571
83
0.61206
4.128631
false
false
false
false
tjw/swift
test/SILGen/opaque_values_silgen_lib.swift
1
4333
// RUN: %target-swift-frontend -enable-sil-ownership -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -emit-silgen -module-name Swift %s | %FileCheck %s precedencegroup AssignmentPrecedence { assignment: true } enum Optional<Wrapped> { case none case some(Wrapped) } protocol EmptyP {} struct String { var ptr: Builtin.NativeObject } // Tests Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value) // --- // CHECK-LABEL: sil hidden @$Ss21s010______PAndS_casesyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[MTYPE:%.*]] = metatype $@thin PAndSEnum.Type // CHECK: [[EAPPLY:%.*]] = apply {{.*}}([[MTYPE]]) : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum // CHECK: destroy_value [[EAPPLY]] // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '$Ss21s010______PAndS_casesyyF' func s010______PAndS_cases() { _ = PAndSEnum.A } // Test emitBuiltinReinterpretCast. // --- // CHECK-LABEL: sil hidden @$Ss21s020__________bitCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U { // CHECK: bb0([[ARG:%.*]] : @guaranteed $T, // CHECK: [[CAST:%.*]] = unchecked_bitwise_cast [[ARG]] : $T to $U // CHECK: [[RET:%.*]] = copy_value [[CAST]] : $U // CHECK-NOT: destroy_value [[COPY]] : $T // CHECK: return [[RET]] : $U // CHECK-LABEL: } // end sil function '$Ss21s020__________bitCast_2toq_x_q_mtr0_lF' func s020__________bitCast<T, U>(_ x: T, to type: U.Type) -> U { return Builtin.reinterpretCast(x) } // Test emitBuiltinCastReference // --- // CHECK-LABEL: sil hidden @$Ss21s030__________refCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U { // CHECK: bb0([[ARG:%.*]] : @guaranteed $T, %1 : @trivial $@thick U.Type): // CHECK: [[COPY:%.*]] = copy_value [[ARG]] : $T // CHECK: [[SRC:%.*]] = alloc_stack $T // CHECK: store [[COPY]] to [init] [[SRC]] : $*T // CHECK: [[DEST:%.*]] = alloc_stack $U // CHECK: unchecked_ref_cast_addr T in [[SRC]] : $*T to U in [[DEST]] : $*U // CHECK: [[LOAD:%.*]] = load [take] [[DEST]] : $*U // CHECK: dealloc_stack [[DEST]] : $*U // CHECK: dealloc_stack [[SRC]] : $*T // CHECK-NOT: destroy_value [[ARG]] : $T // CHECK: return [[LOAD]] : $U // CHECK-LABEL: } // end sil function '$Ss21s030__________refCast_2toq_x_q_mtr0_lF' func s030__________refCast<T, U>(_ x: T, to: U.Type) -> U { return Builtin.castReference(x) } // Init of Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value) // --- // CHECK-LABEL: sil shared [transparent] @$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmF : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum { // CHECK: bb0([[ARG0:%.*]] : @owned $EmptyP, [[ARG1:%.*]] : @owned $String, [[ARG2:%.*]] : @trivial $@thin PAndSEnum.Type): // CHECK: [[RTUPLE:%.*]] = tuple ([[ARG0]] : $EmptyP, [[ARG1]] : $String) // CHECK: [[RETVAL:%.*]] = enum $PAndSEnum, #PAndSEnum.A!enumelt.1, [[RTUPLE]] : $(EmptyP, String) // CHECK: return [[RETVAL]] : $PAndSEnum // CHECK-LABEL: } // end sil function '$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmF' // CHECK-LABEL: sil shared [transparent] [thunk] @$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmFTc : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum { // CHECK: bb0([[ARG:%.*]] : @trivial $@thin PAndSEnum.Type): // CHECK: [[RETVAL:%.*]] = partial_apply [callee_guaranteed] {{.*}}([[ARG]]) : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum // CHECK: [[CANONICAL_THUNK_FN:%.*]] = function_ref @$Ss6EmptyP_pSSs9PAndSEnumOIegixr_sAA_pSSACIegngr_TR : $@convention(thin) (@in_guaranteed EmptyP, @guaranteed String, @guaranteed @callee_guaranteed (@in EmptyP, @owned String) -> @out PAndSEnum) -> @out PAndSEnum // CHECK: [[CANONICAL_THUNK:%.*]] = partial_apply [callee_guaranteed] [[CANONICAL_THUNK_FN]]([[RETVAL]]) // CHECK: return [[CANONICAL_THUNK]] : $@callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum // CHECK-LABEL: } // end sil function '$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmFTc' enum PAndSEnum { case A(EmptyP, String) }
apache-2.0
b737fda997c0230186b288c02345a80c
56.013158
267
0.633741
3.233582
false
false
false
false
Zewo/MediaTypeParserCollection
Source/MediaTypeParserCollection.swift
1
3083
// MediaTypeParserCollection.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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. @_exported import MediaType @_exported import InterchangeData public enum MediaTypeParserCollectionError: ErrorProtocol { case NoSuitableParser case MediaTypeNotFound } public final class MediaTypeParserCollection { public var parsers: [(MediaType, InterchangeDataParser)] = [] public var mediaTypes: [MediaType] { return parsers.map({$0.0}) } public init() {} public func setPriority(mediaTypes: MediaType...) throws { for mediaType in mediaTypes.reversed() { try setTopPriority(mediaType) } } public func setTopPriority(mediaType: MediaType) throws { for index in 0 ..< parsers.count { let tuple = parsers[index] if tuple.0 == mediaType { parsers.remove(at: index) parsers.insert(tuple, at: 0) return } } throw MediaTypeParserCollectionError.MediaTypeNotFound } public func add(mediaType: MediaType, parser: InterchangeDataParser) { parsers.append(mediaType, parser) } public func parsersFor(mediaType: MediaType) -> [(MediaType, InterchangeDataParser)] { return parsers.reduce([]) { if $1.0.matches(mediaType) { return $0 + [($1.0, $1.1)] } else { return $0 } } } public func parse(data: Data, mediaType: MediaType) throws -> (MediaType, InterchangeData) { var lastError: ErrorProtocol? for (mediaType, parser) in parsersFor(mediaType) { do { return try (mediaType, parser.parse(data)) } catch { lastError = error continue } } if let lastError = lastError { throw lastError } else { throw MediaTypeParserCollectionError.NoSuitableParser } } }
mit
fddb3ddcfb0768db4b72e2011befeb24
32.150538
96
0.646773
4.772446
false
false
false
false
wess/reddift
reddiftSample/UserContentViewController.swift
1
5404
// // UserContentViewController.swift // reddift // // Created by sonson on 2015/04/27. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation import reddift class UserContentViewController: UITableViewController { var session:Session? var userContent:UserContent = .Comments var source:[Thing] = [] var contents:[CellContent] = [] func updateStrings() { contents.removeAll(keepCapacity:true) contents = source.map{(var obj) -> CellContent in if let comment = obj as? Comment { return CellContent(string:comment.body, width:self.view.frame.size.width) } else if let link = obj as? Link { return CellContent(string:link.title, width:self.view.frame.size.width) } else { return CellContent(string:"Other?", width:self.view.frame.size.width) } } } override func viewDidLoad() { super.viewDidLoad() let nib:UINib = UINib(nibName: "UZTextViewCell", bundle: nil) self.tableView.registerNib(nib, forCellReuseIdentifier: "Cell") if let name = session?.token.name { session?.getUserContent(name, content:userContent, sort:.New, timeFilterWithin:.All, paginator:Paginator(), completion: { (result) -> Void in switch result { case let .Failure: println(result.error) case let .Success: println(result.value) if let listing = result.value as? Listing { for obj in listing.children { if let link = obj as? Link { self.source.append(link) } } // self.paginator = listing.paginator } self.updateStrings() // if let listing = box.value as? Listing { // if let array = listing.children { // self.source += array // } // } // self.updateStrings() dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView.reloadData() }) } }) } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contents.count } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == (contents.count - 1) { } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indices(source) ~= indexPath.row { var obj = source[indexPath.row] if let comment = obj as? Comment { session?.getInfo([comment.linkId], completion: { (result) -> Void in switch result { case let .Failure: println(result.error) case let .Success: if let listing = result.value as? Listing { if listing.children.count == 1 { if let link = listing.children[0] as? Link { if let vc = self.storyboard?.instantiateViewControllerWithIdentifier("CommentViewController") as? CommentViewController{ vc.session = self.session vc.link = link dispatch_async(dispatch_get_main_queue(), { () -> Void in self.navigationController?.pushViewController(vc, animated: true) }) } } } } } }) } else if let link = obj as? Link { if let vc = self.storyboard?.instantiateViewControllerWithIdentifier("CommentViewController") as? CommentViewController{ vc.session = session vc.link = link self.navigationController?.pushViewController(vc, animated: true) } } } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indices(contents) ~= indexPath.row { return contents[indexPath.row].textHeight } return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell if let cell = cell as? UZTextViewCell { if indices(contents) ~= indexPath.row { cell.textView?.attributedString = contents[indexPath.row].attributedString } } return cell } }
mit
2d3aeb345f8c92f986805ae21a4379d7
39.924242
156
0.51592
5.638831
false
false
false
false
lorentey/swift
test/Constraints/trailing_closures_objc.swift
6
1141
// RUN: %target-typecheck-verify-swift // REQUIRES: objc_interop // REQUIRES: OS=macosx import Foundation import AVFoundation import AppKit func foo(options: [AVMediaSelectionOption]) { let menuItems: [NSMenuItem] = options.map { (option: AVMediaSelectionOption) in NSMenuItem(title: option.displayName, action: #selector(NSViewController.respondToMediaOptionSelection(from:)), keyEquivalent: "") // expected-error@-1 {{type 'NSViewController' has no member 'respondToMediaOptionSelection(from:)'}} } } func rdar28004686(a: [IndexPath]) { _ = a.sorted { (lhs: NSIndexPath, rhs: NSIndexPath) -> Bool in true } // expected-error@-1 {{cannot convert value of type '(NSIndexPath, NSIndexPath) -> Bool' to expected argument type '(IndexPath, IndexPath) throws -> Bool'}} } class Test: NSObject { var categories : NSArray? func rdar28012273() { let categories = ["hello", "world"] self.categories = categories.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedDescending } // expected-error@-1 {{cannot assign value of type '[String]' to type 'NSArray'}} {{121-121= as NSArray}} } }
apache-2.0
0bc01ddeb90209456442eff45eff214d
38.344828
158
0.720421
4.179487
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Models/MultiCluster/UserIDQuery.swift
1
1142
// // UserIDQuery.swift // // // Created by Vladislav Fitc on 25/05/2020. // import Foundation /// Query to use with Client.searchUserID. public struct UserIDQuery: Codable { /// Query to search. The search is a prefix search with typoTolerance. Use empty query to retrieve all users. /// - Engine default: "" public var query: String? /// Engine default: null /// If specified only clusters assigned to this cluster can be returned. public var clusterName: ClusterName? /// Engine default: 0 /// Page to fetch. public var page: Int? /// Engine default: 20 /// Number of users to return by page. public var hitsPerPage: Int? public init(query: String? = nil, clusterName: ClusterName? = nil, page: Int? = nil, hitsPerPage: Int? = nil) { self.query = query self.clusterName = clusterName self.clusterName = clusterName self.page = page self.hitsPerPage = hitsPerPage } } extension UserIDQuery: Builder {} extension UserIDQuery: ExpressibleByStringInterpolation { public init(stringLiteral value: String) { self.query = value } }
mit
5db16c1984fc820c0229f59329a609bb
21.84
111
0.66725
4.049645
false
false
false
false
Ryce/stege-ios
Pods/EasyAnimation/EasyAnimation/EasyAnimation.swift
1
20333
// // EasyAnimation.swift // // Created by Marin Todorov on 4/11/15. // Copyright (c) 2015 Underplot ltd. All rights reserved. // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import ObjectiveC // MARK: EA private structures private struct PendingAnimation { let layer: CALayer let keyPath: String let fromValue: AnyObject } private class AnimationContext { var duration: NSTimeInterval = 1.0 var currentTime: NSTimeInterval = {CACurrentMediaTime()}() var delay: NSTimeInterval = 0.0 var options: UIViewAnimationOptions? = nil var pendingAnimations = [PendingAnimation]() //spring additions var springDamping: CGFloat = 0.0 var springVelocity: CGFloat = 0.0 var nrOfUIKitAnimations: Int = 0 } private class CompletionBlock { var context: AnimationContext var completion: ((Bool) -> Void) var nrOfExecutions: Int = 0 init(context c: AnimationContext, completion cb: (Bool) -> Void) { context = c completion = cb } func wrapCompletion(completed: Bool) { if context.nrOfUIKitAnimations > 0 || ++nrOfExecutions % 2 == 0 { //skip every other call if no uikit animations completion(completed) } } } private var didEAInitialize = false private var didEAForLayersInitialize = false private var activeAnimationContexts = [AnimationContext]() // MARK: EA animatable properties private let vanillaLayerKeys = [ "anchorPoint", "backgroundColor", "borderColor", "borderWidth", "bounds", "contentsRect", "cornerRadius", "opacity", "position", "shadowColor", "shadowOffset", "shadowOpacity", "shadowRadius", "sublayerTransform", "transform", "zPosition" ] private let specializedLayerKeys: [String: [String]] = [ CAEmitterLayer.self.description(): ["emitterPosition", "emitterZPosition", "emitterSize", "spin", "velocity", "birthRate", "lifetime"], //TODO: test animating arrays, eg colors & locations CAGradientLayer.self.description(): ["colors", "locations", "endPoint", "startPoint"], CAReplicatorLayer.self.description(): ["instanceDelay", "instanceTransform", "instanceColor", "instanceRedOffset", "instanceGreenOffset", "instanceBlueOffset", "instanceAlphaOffset"], //TODO: test animating paths CAShapeLayer.self.description(): ["path", "fillColor", "lineDashPhase", "lineWidth", "miterLimit", "strokeColor", "strokeStart", "strokeEnd"], CATextLayer.self.description(): ["fontSize", "foregroundColor"] ] public extension UIViewAnimationOptions { //CA Fill modes static let FillModeNone = UIViewAnimationOptions(0) static let FillModeForwards = UIViewAnimationOptions(1024) static let FillModeBackwards = UIViewAnimationOptions(2048) static let FillModeBoth = UIViewAnimationOptions(1024 + 2048) } /** A `UIView` extension that adds super powers to animateWithDuration:animations: and the like. Check the README for code examples of what features this extension adds. */ extension UIView { //TODO: experiment more with path animations //public var animationPath: CGPath? { set {} get {return nil}} // MARK: UIView animation & action methods override public static func initialize() { if !didEAInitialize { replaceAnimationMethods() didEAInitialize = true } } private static func replaceAnimationMethods() { //replace actionForLayer... method_exchangeImplementations( class_getInstanceMethod(self, "actionForLayer:forKey:"), class_getInstanceMethod(self, "EA_actionForLayer:forKey:")) //replace animateWithDuration... method_exchangeImplementations( class_getClassMethod(self, "animateWithDuration:animations:"), class_getClassMethod(self, "EA_animateWithDuration:animations:")) method_exchangeImplementations( class_getClassMethod(self, "animateWithDuration:animations:completion:"), class_getClassMethod(self, "EA_animateWithDuration:animations:completion:")) method_exchangeImplementations( class_getClassMethod(self, "animateWithDuration:delay:options:animations:completion:"), class_getClassMethod(self, "EA_animateWithDuration:delay:options:animations:completion:")) method_exchangeImplementations( class_getClassMethod(self, "animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:"), class_getClassMethod(self, "EA_animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:")) } func EA_actionForLayer(layer: CALayer!, forKey key: String!) -> CAAction! { let result = EA_actionForLayer(layer, forKey: key) if let activeContext = activeAnimationContexts.last { if let result = result as? NSNull { if contains(vanillaLayerKeys, key) || (specializedLayerKeys[layer.classForCoder.description()] != nil && contains(specializedLayerKeys[layer.classForCoder.description()]!, key)) { var currentKeyValue: AnyObject? = layer.valueForKey(key) //exceptions if currentKeyValue == nil && key.hasSuffix("Color") { currentKeyValue = UIColor.clearColor().CGColor } //found an animatable property - add the pending animation if let currentKeyValue: AnyObject = currentKeyValue { activeContext.pendingAnimations.append( PendingAnimation(layer: layer, keyPath: key, fromValue: currentKeyValue) ) } } } else { activeContext.nrOfUIKitAnimations++ } } return result } class func EA_animateWithDuration(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat, options: UIViewAnimationOptions, animations: () -> Void, completion: ((Bool) -> Void)?) { //create context let context = AnimationContext() context.duration = duration context.delay = delay context.options = options context.springDamping = dampingRatio context.springVelocity = velocity //push context activeAnimationContexts.append(context) //enable layer actions CATransaction.begin() CATransaction.setDisableActions(false) var completionBlock: CompletionBlock? = nil //spring animations if let completion = completion { //wrap a completion block completionBlock = CompletionBlock(context: context, completion: completion) EA_animateWithDuration(duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity, options: options, animations: animations, completion: completionBlock!.wrapCompletion) } else { //simply schedule the animation EA_animateWithDuration(duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity, options: options, animations: animations, completion: completion) } //pop context activeAnimationContexts.removeLast() //run pending animations for anim in context.pendingAnimations { anim.layer.addAnimation(EA_animation(anim, context: context), forKey: nil) } CATransaction.commit() } class func EA_animateWithDuration(duration: NSTimeInterval, delay: NSTimeInterval, options: UIViewAnimationOptions, animations: () -> Void, completion: ((Bool) -> Void)?) { //create context let context = AnimationContext() context.duration = duration context.delay = delay context.options = options //push context activeAnimationContexts.append(context) //enable layer actions CATransaction.begin() CATransaction.setDisableActions(false) var completionBlock: CompletionBlock? = nil //animations if let completion = completion { //wrap a completion block completionBlock = CompletionBlock(context: context, completion: completion) EA_animateWithDuration(duration, delay: delay, options: options, animations: animations, completion: completionBlock!.wrapCompletion) } else { //simply schedule the animation EA_animateWithDuration(duration, delay: delay, options: options, animations: animations, completion: nil) } //pop context activeAnimationContexts.removeLast() //run pending animations for anim in context.pendingAnimations { anim.layer.addAnimation(EA_animation(anim, context: context), forKey: nil) } //try a timer now, than see about animation delegate if let completionBlock = completionBlock where context.nrOfUIKitAnimations == 0 && context.pendingAnimations.count > 0 { NSTimer.scheduledTimerWithTimeInterval(context.duration, target: self, selector: "EA_wrappedCompletionHandler:", userInfo: completionBlock, repeats: false) } CATransaction.commit() } class func EA_animateWithDuration(duration: NSTimeInterval, animations: () -> Void, completion: ((Bool) -> Void)?) { animateWithDuration(duration, delay: 0.0, options: nil, animations: animations, completion: completion) } class func EA_animateWithDuration(duration: NSTimeInterval, animations: () -> Void) { animateWithDuration(duration, animations: animations, completion: nil) } class func EA_wrappedCompletionHandler(timer: NSTimer) { if let completionBlock = timer.userInfo as? CompletionBlock { completionBlock.wrapCompletion(true) } } // MARK: create CA animation private class func EA_animation(pending: PendingAnimation, context: AnimationContext) -> CAAnimation { let anim: CAAnimation if (context.springDamping > 0.0) { //create a layer spring animation anim = RBBSpringAnimation(keyPath: pending.keyPath) if let anim = anim as? RBBSpringAnimation { anim.from = pending.fromValue anim.to = pending.layer.valueForKey(pending.keyPath) //TODO: refine the spring animation setup //lotta magic numbers to mimic UIKit springs let epsilon = 0.001 anim.damping = -2.0 * log(epsilon) / context.duration anim.stiffness = Double(pow(anim.damping, 2)) / Double(pow(context.springDamping * 2, 2)) anim.mass = 1.0 anim.velocity = 0.0 //NSLog("mass: %.2f", anim.mass) //NSLog("damping: %.2f", anim.damping) //NSLog("velocity: %.2f", anim.velocity) //NSLog("stiffness: %.2f", anim.stiffness) } } else { //create property animation anim = CABasicAnimation(keyPath: pending.keyPath) (anim as! CABasicAnimation).fromValue = pending.fromValue (anim as! CABasicAnimation).toValue = pending.layer.valueForKey(pending.keyPath) } anim.duration = context.duration if context.delay > 0.0 { anim.beginTime = context.currentTime + context.delay anim.fillMode = kCAFillModeBackwards } //options if let options = context.options?.rawValue { if options & UIViewAnimationOptions.BeginFromCurrentState.rawValue == 0 { //only repeat if not in a chain anim.autoreverses = (options & UIViewAnimationOptions.Autoreverse.rawValue == UIViewAnimationOptions.Autoreverse.rawValue) anim.repeatCount = (options & UIViewAnimationOptions.Repeat.rawValue == UIViewAnimationOptions.Repeat.rawValue) ? Float.infinity : 0 } //easing var timingFunctionName = kCAMediaTimingFunctionEaseInEaseOut if options & UIViewAnimationOptions.CurveLinear.rawValue == UIViewAnimationOptions.CurveLinear.rawValue { //first check for linear (it's this way to take up only 2 bits) timingFunctionName = kCAMediaTimingFunctionLinear } else if options & UIViewAnimationOptions.CurveEaseIn.rawValue == UIViewAnimationOptions.CurveEaseIn.rawValue { timingFunctionName = kCAMediaTimingFunctionEaseIn } else if options & UIViewAnimationOptions.CurveEaseOut.rawValue == UIViewAnimationOptions.CurveEaseOut.rawValue { timingFunctionName = kCAMediaTimingFunctionEaseOut } anim.timingFunction = CAMediaTimingFunction(name: timingFunctionName) //fill mode if options & UIViewAnimationOptions.FillModeBoth.rawValue == UIViewAnimationOptions.FillModeBoth.rawValue { //both anim.fillMode = kCAFillModeBoth } else if options & UIViewAnimationOptions.FillModeForwards.rawValue == UIViewAnimationOptions.FillModeForwards.rawValue { //forward anim.fillMode = (anim.fillMode == kCAFillModeBackwards) ? kCAFillModeBoth : kCAFillModeForwards } else if options & UIViewAnimationOptions.FillModeBackwards.rawValue == UIViewAnimationOptions.FillModeBackwards.rawValue { //backwards anim.fillMode = kCAFillModeBackwards } } return anim } // MARK: chain animations /** Creates and runs an animation which allows other animations to be chained to it and to each other. :param: duration The animation duration in seconds :param: delay The delay before the animation starts :param: options A UIViewAnimationOptions bitmask (check UIView.animationWithDuration:delay:options:animations:completion: for more info) :param: animations Animation closure :param: completion Completion closure of type (Bool)->Void :returns: The created request. */ public class func animateAndChainWithDuration(duration: NSTimeInterval, delay: NSTimeInterval, options: UIViewAnimationOptions, animations: () -> Void, completion: ((Bool) -> Void)?) -> EAAnimationDelayed { let currentAnimation = EAAnimationDelayed() currentAnimation.duration = duration currentAnimation.delay = delay currentAnimation.options = options currentAnimation.animations = animations currentAnimation.completion = completion currentAnimation.nextDelayedAnimation = EAAnimationDelayed() currentAnimation.nextDelayedAnimation!.prevDelayedAnimation = currentAnimation currentAnimation.run() EAAnimationDelayed.animations.append(currentAnimation) return currentAnimation.nextDelayedAnimation! } /** Creates and runs an animation which allows other animations to be chained to it and to each other. :param: duration The animation duration in seconds :param: delay The delay before the animation starts :param: usingSpringWithDamping the spring damping :param: initialSpringVelocity initial velocity of the animation :param: options A UIViewAnimationOptions bitmask (check UIView.animationWithDuration:delay:options:animations:completion: for more info) :param: animations Animation closure :param: completion Completion closure of type (Bool)->Void :returns: The created request. */ public class func animateAndChainWithDuration(duration: NSTimeInterval, delay: NSTimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat, options: UIViewAnimationOptions, animations: () -> Void, completion: ((Bool) -> Void)?) -> EAAnimationDelayed { let currentAnimation = EAAnimationDelayed() currentAnimation.duration = duration currentAnimation.delay = delay currentAnimation.options = options currentAnimation.animations = animations currentAnimation.completion = completion currentAnimation.springDamping = dampingRatio currentAnimation.springVelocity = velocity currentAnimation.nextDelayedAnimation = EAAnimationDelayed() currentAnimation.nextDelayedAnimation!.prevDelayedAnimation = currentAnimation currentAnimation.run() EAAnimationDelayed.animations.append(currentAnimation) return currentAnimation.nextDelayedAnimation! } } extension CALayer { // MARK: CALayer animations override public static func initialize() { super.initialize() if !didEAForLayersInitialize { replaceAnimationMethods() didEAForLayersInitialize = true } } private static func replaceAnimationMethods() { //replace actionForKey method_exchangeImplementations( class_getInstanceMethod(self, "actionForKey:"), class_getInstanceMethod(self, "EA_actionForKey:")) } public func EA_actionForKey(key: String!) -> CAAction! { //check if the layer has a view-delegate if let delegate = delegate as? UIView { return EA_actionForKey(key) // -> this passes the ball to UIView.actionForLayer:forKey: } //create a custom easy animation and add it to the animation stack if let activeContext = activeAnimationContexts.last where contains(vanillaLayerKeys, key) || (specializedLayerKeys[self.classForCoder.description()] != nil && contains(specializedLayerKeys[self.classForCoder.description()]!, key)) { var currentKeyValue: AnyObject? = valueForKey(key) //exceptions if currentKeyValue == nil && key.hasSuffix("Color") { currentKeyValue = UIColor.clearColor().CGColor } //found an animatable property - add the pending animation if let currentKeyValue: AnyObject = currentKeyValue { activeContext.pendingAnimations.append( PendingAnimation(layer: self, keyPath: key, fromValue: currentKeyValue ) ) } } return nil } }
gpl-2.0
537bdfcb324b990dc8aed0d4efdfb611
42.915767
297
0.647568
5.701907
false
false
false
false
iosprogrammingwithswift/iosprogrammingwithswift
04_Swift2015_Final.playground/Pages/09_Classes And Structs.xcplaygroundpage/Contents.swift
1
2783
//: [Previous](@previous) | [Next](@next) //: Definition Syntax struct SomeStructure { // structure definition goes here } class SomeClass { // class definition goes here } struct Resolution { var width = 0 var height = 0 } class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? } //: Class and Structure Instances let someResolution = Resolution() let someVideoMode = VideoMode() //: Memberwise Initializers for Structure Types let vga = Resolution(width: 640, height: 480) let hd = Resolution(width: 1920, height: 1080) var cinema = hd //:Structures and Enumerations Are Value Types /*: A value type is a type whose value is copied when it is assigned to a variable or constant, or when it is passed to a function. You’ve actually been using value types extensively throughout the previous chapters. In fact, all of the basic types in Swift—integers, floating-point numbers, Booleans, strings, arrays and dictionaries—are value types, and are implemented as structures behind the scenes. */ cinema.width = 2048 print("cinema is now \(cinema.width) pixels wide") // prints "cinema is now 2048 pixels wide" //:However, the width property of the original hd instance still has the old value of 1920: print("hd is still \(hd.width) pixels wide") // prints "hd is still 1920 pixels wide //same behavior applies to enumerations enum CompassPoint { case North, South, East, West } var currentDirection = CompassPoint.West let rememberedDirection = currentDirection currentDirection = .East if rememberedDirection == .West { print("The remembered direction is still .West") } // prints "The remembered direction is still .West" //: Classes Are Reference Types let tenEighty = VideoMode() tenEighty.resolution = hd tenEighty.interlaced = true tenEighty.name = "1080i" tenEighty.frameRate = 25.0 let alsoTenEighty = tenEighty alsoTenEighty.frameRate = 30.0 print("The frameRate property of tenEighty is now \(tenEighty.frameRate)") // prints "The frameRate property of tenEighty is now 30.0" //:Identity Operators if tenEighty === alsoTenEighty { print("tenEighty and alsoTenEighty refer to the same VideoMode instance.") } // prints "tenEighty and alsoTenEighty refer to the same VideoMode instance." /*: largely Based of [Apple's Swift Language Guide: Classes And Strucs](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-ID82 ) & [Apple's A Swift Tour](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1 ) */ //: [Previous](@previous) | [Next](@next)
mit
824eea89f0a150743fd3233ecfbfe701
30.91954
414
0.75045
4.1263
false
false
false
false
IngmarStein/swift
test/Interpreter/enum_resilience.swift
1
8664
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-build-swift -emit-library -Xfrontend -enable-resilience -c %S/../Inputs/resilient_struct.swift -o %t/resilient_struct.o // RUN: %target-build-swift -emit-module -Xfrontend -enable-resilience -c %S/../Inputs/resilient_struct.swift -o %t/resilient_struct.o // RUN: %target-build-swift -emit-library -Xfrontend -enable-resilience -c %S/../Inputs/resilient_enum.swift -I %t/ -o %t/resilient_enum.o // RUN: %target-build-swift -emit-module -Xfrontend -enable-resilience -c %S/../Inputs/resilient_enum.swift -I %t/ -o %t/resilient_enum.o // RUN: %target-build-swift %s -Xlinker %t/resilient_struct.o -Xlinker %t/resilient_enum.o -I %t -L %t -o %t/main // RUN: %target-run %t/main // REQUIRES: executable_test import StdlibUnittest import resilient_enum import resilient_struct var ResilientEnumTestSuite = TestSuite("ResilientEnum") ResilientEnumTestSuite.test("ResilientEmptyEnum") { let e = ResilientEmptyEnum.X let n: Int switch e { case .X: n = 0 default: n = -1 } expectEqual(n, 0) } ResilientEnumTestSuite.test("ResilientSingletonEnum") { let o: AnyObject = ArtClass() let e = ResilientSingletonEnum.X(o) let n: Int switch e { case .X(let oo): n = 0 expectTrue(o === oo) default: n = -1 } expectEqual(n, 0) } ResilientEnumTestSuite.test("ResilientSingletonGenericEnum") { let o = ArtClass() let e = ResilientSingletonGenericEnum.X(o) let n: Int switch e { case .X(let oo): n = 0 expectEqual(o === oo, true) default: n = -1 } expectEqual(n, 0) } ResilientEnumTestSuite.test("ResilientNoPayloadEnum") { let a: [ResilientNoPayloadEnum] = [.A, .B, .C] let b: [Int] = a.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 default: return -1 } } expectEqual(b, [0, 1, 2]) } ResilientEnumTestSuite.test("ResilientSinglePayloadEnum") { let o = ArtClass() let a: [ResilientSinglePayloadEnum] = [.A, .B, .C, .X(o)] let b: [Int] = a.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 case .X(let oo): expectTrue(o === oo) return 3 default: return -1 } } expectEqual(b, [0, 1, 2, 3]) } ResilientEnumTestSuite.test("ResilientSinglePayloadGenericEnum") { let o = ArtClass() let a: [ResilientSinglePayloadGenericEnum<ArtClass>] = [.A, .B, .C, .X(o)] let b: [Int] = a.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 case .X(let oo): expectTrue(o === oo) return 3 default: return -1 } } expectEqual(b, [0, 1, 2, 3]) } ResilientEnumTestSuite.test("ResilientMultiPayloadEnum") { let a: [ResilientMultiPayloadEnum] = [.A, .B, .C, .X(1), .Y(2)] let b: [Int] = a.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 case .X(let x): expectEqual(x, 1) return 3 case .Y(let y): expectEqual(y, 2) return 4 default: return -1 } } expectEqual(b, [0, 1, 2, 3, 4]) } ResilientEnumTestSuite.test("ResilientMultiPayloadEnumRoundTrip") { let a = [0, 1, 2, 3, 4] let b = a.map { makeResilientMultiPayloadEnum(1122, i: $0) } let c: [Int] = b.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 case .X(let x): expectEqual(x, 1122) return 3 case .Y(let y): expectEqual(y, 1122) return 4 default: return -1 } } expectEqual(c, a) } ResilientEnumTestSuite.test("ResilientMultiPayloadEnumSpareBits") { let o1 = ArtClass() let o2 = ArtClass() let a: [ResilientMultiPayloadEnumSpareBits] = [.A, .B, .C, .X(o1), .Y(o2)] let b: [Int] = a.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 case .X(let oo1): expectTrue(oo1 === o1) return 3 case .Y(let oo2): expectTrue(oo2 === o2) return 4 default: return -1 } } expectEqual(b, [0, 1, 2, 3, 4]) } ResilientEnumTestSuite.test("ResilientMultiPayloadEnumSpareBitsRoundTrip") { let o = ArtClass() let a = [0, 1, 2, 3, 4] let b = a.map { makeResilientMultiPayloadEnumSpareBits(o, i: $0) } let c: [Int] = b.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 case .X(let oo): expectTrue(oo === o) return 3 case .Y(let oo): expectTrue(oo === o) return 4 default: return -1 } } expectEqual(c, a) } ResilientEnumTestSuite.test("ResilientMultiPayloadEnumSpareBitsAndExtraBits") { let o = ArtClass() let s: SevenSpareBits = (false, 1, 2, 3, 4, 5, 6, 7) let a: [ResilientMultiPayloadEnumSpareBitsAndExtraBits] = [.P1(s), .P2(o), .P3(o), .P4(o), .P5(o), .P6(o), .P7(o), .P8(o)] let b: [Int] = a.map { switch $0 { case .P1(let ss): // FIXME: derive Equatable conformances for arbitrary tuples :-) expectEqual(ss.0, s.0) expectEqual(ss.1, s.1) expectEqual(ss.2, s.2) expectEqual(ss.3, s.3) expectEqual(ss.4, s.4) expectEqual(ss.5, s.5) expectEqual(ss.6, s.6) expectEqual(ss.7, s.7) return 0 case .P2(let oo): expectTrue(oo === o) return 1 case .P3(let oo): expectTrue(oo === o) return 2 case .P4(let oo): expectTrue(oo === o) return 3 case .P5(let oo): expectTrue(oo === o) return 4 case .P6(let oo): expectTrue(oo === o) return 5 case .P7(let oo): expectTrue(oo === o) return 6 case .P8(let oo): expectTrue(oo === o) return 7 default: return -1 } } expectEqual(b, [0, 1, 2, 3, 4, 5, 6, 7]) } ResilientEnumTestSuite.test("ResilientMultiPayloadGenericEnum") { let o1 = ArtClass() let o2 = ArtClass() let a: [ResilientMultiPayloadGenericEnum<ArtClass>] = [.A, .B, .C, .X(o1), .Y(o2)] let b: [Int] = a.map { switch $0 { case .A: return 0 case .B: return 1 case .C: return 2 case .X(let oo1): expectTrue(oo1 === o1) return 3 case .Y(let oo2): expectTrue(oo2 === o2) return 4 default: return -1 } } expectEqual(b, [0, 1, 2, 3, 4]) } public func getMetadata() -> Any.Type { return Shape.self } ResilientEnumTestSuite.test("DynamicLayoutMetatype") { do { var output = "" let expected = "- resilient_enum.Shape #0\n" dump(getMetadata(), to: &output) expectEqual(output, expected) } do { expectEqual(true, getMetadata() == getMetadata()) } } ResilientEnumTestSuite.test("DynamicLayoutSinglePayload") { let s = Size(w: 10, h: 20) let a: [SimpleShape] = [.KleinBottle, .Triangle(s)] let b: [Int] = a.map { switch $0 { case .KleinBottle: return 0 case .Triangle(let s): expectEqual(s.w, 10) expectEqual(s.h, 20) return 1 } } expectEqual(b, [0, 1]) } ResilientEnumTestSuite.test("DynamicLayoutMultiPayload") { let s = Size(w: 10, h: 20) let a: [Shape] = [.Point, .Rect(s), .RoundedRect(s, s)] let b: [Int] = a.map { switch $0 { case .Point: return 0 case .Rect(let s): expectEqual(s.w, 10) expectEqual(s.h, 20) return 1 case .RoundedRect(let s, let ss): expectEqual(s.w, 10) expectEqual(s.h, 20) expectEqual(ss.w, 10) expectEqual(ss.h, 20) return 2 } } expectEqual(b, [0, 1, 2]) } ResilientEnumTestSuite.test("DynamicLayoutMultiPayload2") { let c = Color(r: 1, g: 2, b: 3) let a: [CustomColor] = [.Black, .White, .Custom(c), .Bespoke(c, c)] let b: [Int] = a.map { switch $0 { case .Black: return 0 case .White: return 1 case .Custom(let c): expectEqual(c.r, 1) expectEqual(c.g, 2) expectEqual(c.b, 3) return 2 case .Bespoke(let c, let cc): expectEqual(c.r, 1) expectEqual(c.g, 2) expectEqual(c.b, 3) expectEqual(cc.r, 1) expectEqual(cc.g, 2) expectEqual(cc.b, 3) return 3 } } expectEqual(b, [0, 1, 2, 3]) } // Make sure case numbers round-trip if payload has zero size ResilientEnumTestSuite.test("ResilientEnumWithEmptyCase") { let a: [ResilientEnumWithEmptyCase] = getResilientEnumWithEmptyCase() let b: [Int] = a.map { switch $0 { case .A: return 0 case .B: return 1 case .Empty: return 2 default: return -1 } } expectEqual(b, [0, 1, 2]) } runAllTests()
apache-2.0
8624499f4acf3d3ba4c6a0ceb7f8e994
20.287469
138
0.576408
3.123288
false
true
false
false
brentsimmons/Frontier
BeforeTheRename/FrontierVerbs/FrontierVerbs/VerbTables/SearchVerbs.swift
1
1331
// // SearchVerbs.swift // FrontierVerbs // // Created by Brent Simmons on 4/15/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import Foundation import FrontierData struct SearchVerbs: VerbTable { private enum Verb: String { case reset = "reset" case findNext = "findnext" case replace = "replace" case replaceAll = "replaceall" } static func evaluate(_ lowerVerbName: String, _ params: VerbParams, _ verbAppDelegate: VerbAppDelegate) throws -> Value { guard let verb = Verb(rawValue: lowerVerbName) else { throw LangError(.verbNotFound) } do { switch verb { case .reset: return try reset(params) case .findNext: return try findNext(params) case .replace: return try replace(params) case .replaceAll: return try replaceAll(params) } } catch { throw error } } } private extension SearchVerbs { static func reset(_ params: VerbParams) throws -> Value { throw LangError(.unimplementedVerb) } static func findNext(_ params: VerbParams) throws -> Value { throw LangError(.unimplementedVerb) } static func replace(_ params: VerbParams) throws -> Value { throw LangError(.unimplementedVerb) } static func replaceAll(_ params: VerbParams) throws -> Value { throw LangError(.unimplementedVerb) } }
gpl-2.0
e6fd94d74f1da08045da705d55a52c81
18.850746
122
0.686466
3.746479
false
false
false
false
freshOS/ws
Sources/ws/WS+TypedCalls.swift
2
5395
// // WS+TypedCalls.swift // ws // // Created by Sacha Durand Saint Omer on 06/04/16. // Copyright © 2016 s4cha. All rights reserved. // import Arrow import Foundation import Then extension WS { public func get<T: ArrowParsable>(_ url: String, params: Params = Params(), keypath: String? = nil) -> Promise<[T]> { let keypath = keypath ?? defaultCollectionParsingKeyPath return getRequest(url, params: params).fetch() .registerThen { (json: JSON) -> [T] in WSModelJSONParser<T>().toModels(json, keypath: keypath) }.resolveOnMainThread() } public func get<T: ArrowParsable>(_ url: String, params: Params = Params(), keypath: String? = nil) -> Promise<T> { return resourceCall(.get, url: url, params: params, keypath: keypath) } public func post<T: ArrowParsable>(_ url: String, params: Params = Params(), keypath: String? = nil) -> Promise<T> { return resourceCall(.post, url: url, params: params, keypath: keypath) } public func put<T: ArrowParsable>(_ url: String, params: Params = Params(), keypath: String? = nil) -> Promise<T> { return resourceCall(.put, url: url, params: params, keypath: keypath) } public func delete<T: ArrowParsable>(_ url: String, params: Params = Params(), keypath: String? = nil) -> Promise<T> { return resourceCall(.delete, url: url, params: params, keypath: keypath) } private func resourceCall<T: ArrowParsable>(_ verb: WSHTTPVerb, url: String, params: Params = Params(), keypath: String? = nil) -> Promise<T> { let c = defaultCall() c.httpVerb = verb c.URL = url c.params = params // Apply corresponding JSON mapper return c.fetch().registerThen { (json: JSON) -> T in return WSModelJSONParser<T>().toModel(json, keypath: keypath ?? self.defaultObjectParsingKeyPath) }.resolveOnMainThread() } } extension WS { public func get<T: ArrowInitializable>(_ url: String, params: Params = Params(), keypath: String? = nil) -> Promise<[T]> { let keypath = keypath ?? defaultCollectionParsingKeyPath return getRequest(url, params: params) .fetch() .registerThen { (json: JSON) in Promise<[T]> { (resolve, reject) in if let t: [T] = WSModelJSONParser<T>().toModels(json, keypath: keypath) { resolve(t) } else { reject(WSError.unableToParseResponse) } } } .resolveOnMainThread() } public func get<T: ArrowInitializable>(_ url: String, params: Params = Params(), keypath: String? = nil) -> Promise<T> { return typeCall(.get, url: url, params: params, keypath: keypath) } public func post<T: ArrowInitializable>(_ url: String, params: Params = Params(), keypath: String? = nil) -> Promise<T> { return typeCall(.post, url: url, params: params, keypath: keypath) } public func put<T: ArrowInitializable>(_ url: String, params: Params = Params(), keypath: String? = nil) -> Promise<T> { return typeCall(.put, url: url, params: params, keypath: keypath) } public func delete<T: ArrowInitializable>(_ url: String, params: Params = Params(), keypath: String? = nil) -> Promise<T> { return typeCall(.delete, url: url, params: params, keypath: keypath) } private func typeCall<T: ArrowInitializable>(_ verb: WSHTTPVerb, url: String, params: Params = Params(), keypath: String? = nil) -> Promise<T> { let c = defaultCall() c.httpVerb = verb c.URL = url c.params = params // Apply corresponding JSON mapper return c.fetch() .registerThen { (json: JSON) in Promise<T> { (resolve, reject) in if let t: T = WSModelJSONParser<T>().toModel(json, keypath: keypath ?? self.defaultObjectParsingKeyPath) { resolve(t) } else { reject(WSError.unableToParseResponse) } } } .resolveOnMainThread() } }
mit
672c8d80b726378a023843c02d7c1e71
39.556391
109
0.461253
5.166667
false
false
false
false
soapyigu/LeetCode_Swift
DP/UniquePaths.swift
1
849
/** * Question Link: https://leetcode.com/problems/unique-paths/ * Primary idea: 2D Dynamic Programming, use a 2D array as a cache to store calculated data * Time Complexity: O(mn), Space Complexity: O(mn) * */ class UniquePaths { func uniquePaths(m: Int, _ n: Int) -> Int { var pathNums = Array(count: m, repeatedValue: Array(count: n, repeatedValue: 0)) return _helper(&pathNums, m - 1, n - 1) } private func _helper(inout pathNums: [[Int]], _ m: Int, _ n: Int) -> Int { if m < 0 || n < 0 { return 0 } if m == 0 || n == 0 { return 1 } if pathNums[m][n] != 0 { return pathNums[m][n] } pathNums[m][n] = _helper(&pathNums, m - 1, n) + _helper(&pathNums, m, n - 1) return pathNums[m][n] } }
mit
af28803504270e785dc0d0ab5811dc76
28.310345
91
0.515901
3.396
false
false
false
false
renyufei8023/WeiBo
weibo/Classes/Main/View/VisitorView.swift
1
4130
// // VisitorView.swift // weibo // // Created by 任玉飞 on 16/4/25. // Copyright © 2016年 任玉飞. All rights reserved. // import UIKit import SnapKit protocol VisitorViewDelegate:NSObjectProtocol { func loginBtnWillClick() func registerBtnWillClick() } class VisitorView: UIView { weak var delegate: VisitorViewDelegate? func setupVisitorInfo(isHome:Bool, imageName:String, message:String) { iconView.hidden = !isHome homeIcon.image = UIImage(named: imageName) messageLabel.text = message if isHome { startAnimation() } } private func startAnimation() { let animation = CABasicAnimation(keyPath:"transform.rotation") animation.toValue = 2 * M_PI animation.duration = 20 animation.repeatCount = MAXFLOAT animation.removedOnCompletion = false iconView.layer.addAnimation(animation, forKey: nil) } override init(frame: CGRect) { super.init(frame: frame) addSubview(iconView) addSubview(homeIcon) addSubview(messageLabel) addSubview(loginBtn) addSubview(registerBtn) //MARK:-添加约束 iconView.snp_makeConstraints { (make) -> Void in make.center.equalTo(self) } homeIcon.snp_makeConstraints { (make) in make.center.equalTo(self) } messageLabel.snp_makeConstraints { (make) in make.top.equalTo(iconView.snp_bottom).offset(5) make.centerX.equalTo(self) make.left.equalTo(50) make.right.equalTo(-50) } loginBtn.snp_makeConstraints { (make) in make.top.equalTo(messageLabel.snp_bottom).offset(5) make.width.equalTo(100) make.height.equalTo(40) make.right.equalTo(self.snp_centerX).offset(-20) } registerBtn.snp_makeConstraints { (make) in make.top.equalTo(loginBtn) make.width.equalTo(100) make.height.equalTo(40) make.left.equalTo(self.snp_centerX).offset(20) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var iconView: UIImageView = { let iconView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon")) return iconView }() //MARK:-懒加载 private lazy var homeIcon: UIImageView = { let homeIcon = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house")) return homeIcon }() private lazy var messageLabel: UILabel = { let label = UILabel() label.text = "asdadasday6q7wy8u9idasiufbas'jfhpw9fbewopwajfhwbhd;k" label.numberOfLines = 0 label.textAlignment = NSTextAlignment.Center label.textColor = UIColor.darkGrayColor() return label }() private lazy var loginBtn: UIButton = { let btn = UIButton() btn.setTitle("登陆", forState: UIControlState.Normal) btn.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal) btn.addTarget(self, action: "loginBtnClick", forControlEvents: UIControlEvents.TouchUpInside) return btn }() private lazy var registerBtn: UIButton = { let btn = UIButton() btn.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) btn.setTitle("注册", forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal) btn.addTarget(self, action: "registerBtnClick", forControlEvents: UIControlEvents.TouchUpInside) return btn }() func loginBtnClick() { delegate?.loginBtnWillClick() } func registerBtnClick() { delegate?.registerBtnWillClick() } }
mit
6e285541a38bb58ddf6f6b25cddcb00c
29.774436
110
0.622526
4.614431
false
false
false
false
johnno1962d/swift
test/IDE/print_usrs.swift
3
6254
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify -disable-objc-attr-requires-foundation-module %s // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -print-usrs -source-filename %s | FileCheck %s -strict-whitespace import macros // CHECK: [[@LINE+1]]:8 s:V14swift_ide_test1S{{$}} struct S { // CHECK: [[@LINE+1]]:7 s:vV14swift_ide_test1S1xSi{{$}} var x : Int } // CHECK: [[@LINE+1]]:11 s:14swift_ide_test6MyGInt{{$}} typealias MyGInt = Int // CHECK: [[@LINE+1]]:7 s:C14swift_ide_test5MyCls{{$}} class MyCls { // CHECK: [[@LINE+1]]:13 s:C14swift_ide_test5MyCls2TA{{$}} typealias TA = Int // CHECK: [[@LINE+1]]:7 s:vC14swift_ide_test5MyCls3wwwSi{{$}} var www : Int = 0 // CHECK: [[@LINE+1]]:8 s:FC14swift_ide_test5MyCls3fooFSiT_{{$}} func foo(_ x : Int) {} // CHECK: [[@LINE+1]]:3 s:iC14swift_ide_test5MyCls9subscriptFSiSf{{$}} subscript(i: Int) -> Float { // CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test5MyClsg9subscriptFSiSf{{$}} get { return 0.0 } // CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test5MyClss9subscriptFSiSf{{$}} set {} } } // CHECK: [[@LINE+1]]:7 s:C14swift_ide_test12GenericClass{{$}} class GenericClass { // CHECK: [[@LINE+1]]:13 s:C14swift_ide_test12GenericClass2TA{{$}} typealias TA = Int // CHECK: [[@LINE+1]]:7 s:vC14swift_ide_test12GenericClass11instanceVarSi{{$}} var instanceVar: Int = 0 // CHECK: [[@LINE+1]]:8 s:FC14swift_ide_test12GenericClass12instanceFuncFT_T_{{$}} func instanceFunc() { // CHECK: [[@LINE+2]]:18 s:ZFC14swift_ide_test12GenericClass9classFuncFS0_T_{{$}} // CHECK: [[@LINE+1]]:28 s:vFC14swift_ide_test12GenericClass12instanceFuncFT_T_L_4selfS0_{{$}} GenericClass.classFunc(self) } // CHECK: [[@LINE+2]]:3 s:iC14swift_ide_test12GenericClass9subscriptFSiSf{{$}} // CHECK: [[@LINE+1]]:13 s:vC14swift_ide_test12GenericClassL_1iSi{{$}} subscript(i: Int) -> Float { // CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test12GenericClassg9subscriptFSiSf{{$}} get { return 0.0 } // CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test12GenericClasss9subscriptFSiSf{{$}} set {} } // CHECK: [[@LINE+1]]:3 s:FC14swift_ide_test12GenericClassd{{$}} deinit { // CHECK: [[@LINE+2]]:18 s:ZFC14swift_ide_test12GenericClass9classFuncFS0_T_{{$}} // CHECK: [[@LINE+1]]:28 ERROR:no-usr{{$}} GenericClass.classFunc(self) } // CHECK: [[@LINE+2]]:14 s:ZFC14swift_ide_test12GenericClass9classFuncFS0_T_{{$}} // CHECK: [[@LINE+1]]:26 s:vZFC14swift_ide_test12GenericClass9classFuncFS0_T_L_1aS0_{{$}} class func classFunc(_ a: GenericClass) {} } // CHECK: [[@LINE+1]]:10 s:P14swift_ide_test4Prot{{$}} protocol Prot { // CHECK: [[@LINE+1]]:18 s:P14swift_ide_test4Prot5Blarg{{$}} associatedtype Blarg // CHECK: [[@LINE+1]]:8 s:FP14swift_ide_test4Prot8protMethFwx5BlargwxS1_{{$}} func protMeth(_ x: Blarg) -> Blarg // CHECK: [[@LINE+2]]:7 s:vP14swift_ide_test4Prot17protocolProperty1Si{{$}} // CHECK: [[@LINE+1]]:32 s:FP14swift_ide_test4Protg17protocolProperty1Si{{$}} var protocolProperty1: Int { get } } protocol Prot2 {} class SubCls : MyCls, Prot { // CHECK: [[@LINE+1]]:13 s:C14swift_ide_test6SubCls5Blarg{{$}} typealias Blarg = Prot2 // CHECK: [[@LINE+1]]:8 s:FC14swift_ide_test6SubCls8protMethFPS_5Prot2_PS1__{{$}} func protMeth(_ x: Blarg) -> Blarg {} // CHECK: [[@LINE+1]]:7 s:vC14swift_ide_test6SubCls17protocolProperty1Si{{$}} var protocolProperty1 = 0 } // CHECK: [[@LINE+1]]:6 s:F14swift_ide_test5genFnuRxS_4Protwx5BlargS_5Prot2rFxSi{{$}} func genFn<T : Prot where T.Blarg : Prot2>(_ p : T) -> Int {} // CHECK: [[@LINE+1]]:6 s:F14swift_ide_test3barFSiTSiSf_{{$}} func bar(_ x: Int) -> (Int, Float) {} // CHECK: [[@LINE+1]]:7 s:C14swift_ide_test6GenCls{{$}} class GenCls<T> { // CHECK: [[@LINE+1]]:3 s:FC14swift_ide_test6GenClscFT_GS0_x_{{$}} init() {} // CHECK: [[@LINE+1]]:3 s:FC14swift_ide_test6GenClsd{{$}} deinit {} // CHECK: [[@LINE+1]]:14 s:ZFC14swift_ide_test6GenCls4cfooFT_T_{{$}} class func cfoo() {} // CHECK: [[@LINE+1]]:3 s:iC14swift_ide_test6GenCls9subscriptFTSiSi_Si{{$}} subscript (i : Int, j : Int) -> Int { // CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test6GenClsg9subscriptFTSiSi_Si{{$}} get { return i + j } // CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test6GenClss9subscriptFTSiSi_Si{{$}} set(v) { v + i - j } } } class C4 { // CHECK: [[@LINE+1]]:9 s:CC14swift_ide_test2C42In{{$}} class In { // CHECK: [[@LINE+1]]:16 s:ZFCC14swift_ide_test2C42In3gooFT_T_{{$}} class func goo() {} } } class C5 {} extension C5 { // CHECK: [[@LINE+1]]:8 s:FC14swift_ide_test2C55extFnFT_T_{{$}} func extFn() {} } class Observers { func doit() {} // CHECK: [[@LINE+1]]:7 s:vC14swift_ide_test9Observers2p1Si{{$}} var p1 : Int = 0 { // CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test9Observersw2p1Si{{$}} willSet(newValue) { doit() } // CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test9ObserversW2p1Si{{$}} didSet { doit() } } // CHECK: [[@LINE+1]]:7 s:vC14swift_ide_test9Observers2p2Si{{$}} var p2 = 42 { // CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test9Observersw2p2Si{{$}} willSet(newValue) { doit() } // CHECK: [[@LINE+1]]:5 s:FC14swift_ide_test9ObserversW2p2Si{{$}} didSet { doit() } } } // CHECK: [[@LINE+2]]:7 s:C14swift_ide_test10ObjCClass1{{$}} @objc class ObjCClass1 { // CHECK: [[@LINE+1]]:8 s:FC14swift_ide_test10ObjCClass113instanceFunc1FSiT_{{$}} func instanceFunc1(_ a: Int) {} // CHECK: [[@LINE+1]]:14 s:ZFC14swift_ide_test10ObjCClass111staticFunc1FSiT_{{$}} class func staticFunc1(_ a: Int) {} } // CHECK: [[@LINE+1]]:6 s:O14swift_ide_test5Suits{{$}} enum Suits { // CHECK: [[@LINE+1]]:8 s:FO14swift_ide_test5Suits5ClubsFMS0_S0_{{$}} case Clubs // CHECK: [[@LINE+1]]:8 s:FO14swift_ide_test5Suits8DiamondsFMS0_S0_{{$}} case Diamonds // CHECK: [[@LINE+1]]:8 s:FO14swift_ide_test5Suits5enfooFT_T_{{$}} func enfoo() {} } func importedMacros() { // CHECK: [[@LINE+1]]:12 c:@macro@M_PI{{$}} let m1 = M_PI // CHECK: [[@LINE+1]]:12 c:@macro@MACRO_FROM_IMPL{{$}} let m2 = MACRO_FROM_IMPL // CHECK: [[@LINE+1]]:12 c:@macro@USES_MACRO_FROM_OTHER_MODULE_1{{$}} let m3 = USES_MACRO_FROM_OTHER_MODULE_1 _ = m1; _ = m2; _ = m3 }
apache-2.0
9712e55a6c2dd8c2c3b24d183a4bef8b
33.362637
127
0.629197
2.840145
false
true
false
false
Somnibyte/MLKit
Example/Pods/Upsurge/Source/Complex/ComplexArray.swift
1
6758
// Copyright © 2015 Venture Media Labs. // // 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. open class ComplexArray<T: Real>: MutableLinearType, ExpressibleByArrayLiteral { public typealias Index = Int public typealias Element = Complex<T> public typealias Slice = ComplexArraySlice<T> var elements: ValueArray<Complex<T>> open var count: Int { get { return elements.count } set { elements.count = newValue } } open var capacity: Int { return elements.capacity } open var startIndex: Index { return 0 } open var endIndex: Index { return count } open var step: Index { return 1 } open func index(after i: Index) -> Index { return i + 1 } open func formIndex(after i: inout Index) { i += 1 } open var span: Span { return Span(zeroTo: [endIndex]) } open func withUnsafeBufferPointer<R>(_ body: (UnsafeBufferPointer<Element>) throws -> R) rethrows -> R { return try elements.withUnsafeBufferPointer(body) } open func withUnsafePointer<R>(_ body: (UnsafePointer<Element>) throws -> R) rethrows -> R { return try elements.withUnsafePointer(body) } open func withUnsafeMutableBufferPointer<R>(_ body: (UnsafeMutableBufferPointer<Element>) throws -> R) rethrows -> R { return try elements.withUnsafeMutableBufferPointer(body) } open func withUnsafeMutablePointer<R>(_ body: (UnsafeMutablePointer<Element>) throws -> R) rethrows -> R { return try elements.withUnsafeMutablePointer(body) } open var reals: ComplexArrayRealSlice<T> { get { return ComplexArrayRealSlice<T>(base: self, startIndex: startIndex, endIndex: 2*endIndex - 1, step: 2) } set { precondition(newValue.count == reals.count) for i in 0..<newValue.count { self.reals[i] = newValue[i] } } } open var imags: ComplexArrayRealSlice<T> { get { return ComplexArrayRealSlice<T>(base: self, startIndex: startIndex + 1, endIndex: 2*endIndex, step: 2) } set { precondition(newValue.count == imags.count) for i in 0..<newValue.count { self.imags[i] = newValue[i] } } } /// Construct an uninitialized ComplexArray with the given capacity public required init(capacity: Int) { elements = ValueArray<Complex<T>>(capacity: capacity) } /// Construct an uninitialized ComplexArray with the given size public required init(count: Int) { elements = ValueArray<Complex<T>>(count: count) } /// Construct a ComplexArray from an array literal public required init(arrayLiteral elements: Element...) { self.elements = ValueArray<Complex<T>>(count: elements.count) self.elements.mutablePointer.initialize(from: elements) } /// Construct a ComplexArray from contiguous memory public required init<C: LinearType>(_ values: C) where C.Element == Element { elements = ValueArray<Complex<T>>(values) } /// Construct a ComplexArray of `count` elements, each initialized to `repeatedValue`. public required init(count: Int, repeatedValue: Element) { elements = ValueArray<Complex<T>>(count: count, repeatedValue: repeatedValue) } open subscript(index: Index) -> Element { get { precondition(0 <= index && index < capacity) assert(index < count) return elements[index] } set { precondition(0 <= index && index < capacity) assert(index < count) elements[index] = newValue } } open subscript(indices: [Int]) -> Element { get { assert(indices.count == 1) return self[indices[0]] } set { assert(indices.count == 1) self[indices[0]] = newValue } } open subscript(intervals: [IntervalType]) -> Slice { get { assert(intervals.count == 1) let start = intervals[0].start ?? startIndex let end = intervals[0].end ?? endIndex return Slice(base: self, startIndex: start, endIndex: end, step: step) } set { assert(intervals.count == 1) let start = intervals[0].start ?? startIndex let end = intervals[0].end ?? endIndex assert(startIndex <= start && end <= endIndex) for i in start..<end { self[i] = newValue[newValue.startIndex + i - start] } } } open func copy() -> ComplexArray { return ComplexArray(elements) } open func append(_ value: Element) { elements.append(value) } open func appendContentsOf<C: Collection>(_ values: C) where C.Iterator.Element == Element { elements.appendContentsOf(values) } open func replaceRange<C: Collection>(_ subRange: Range<Index>, with newElements: C) where C.Iterator.Element == Element { elements.replaceRange(subRange, with: newElements) } open func toRowMatrix() -> Matrix<Element> { return Matrix(rows: 1, columns: count, elements: self) } open func toColumnMatrix() -> Matrix<Element> { return Matrix(rows: count, columns: 1, elements: self) } } public func ==<T: Real>(lhs: ComplexArray<T>, rhs: ComplexArray<T>) -> Bool { if lhs.count != rhs.count { return false } for i in 0..<lhs.count { if lhs[i] != rhs[i] { return false } } return true }
mit
66d18d1de096cea305e9e2993992e415
31.330144
126
0.618026
4.534899
false
false
false
false
kyletolle/simple_location
simple_location/ViewController.swift
1
2533
// // ViewController.swift // simple_location // // Created by Kyle Tolle on 1/26/15. // Copyright (c) 2015 Kyle Tolle. All rights reserved. // import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var lblLatitude: UILabel! @IBOutlet weak var lblLongitude: UILabel! @IBOutlet weak var lblCity: UILabel! let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.locationManager.delegate = self self.locationManager.distanceFilter = kCLDistanceFilterNone self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.requestWhenInUseAuthorization() self.locationManager.startUpdatingLocation() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { var dCurrentLatitude : Double = locations[0].coordinate.latitude var dCurrentLongitude : Double = locations[0].coordinate.longitude var latitudeString = NSString(format: "Latitude: %0.4f", dCurrentLatitude) lblLatitude.text = latitudeString var longitudeString = NSString(format: "Longitude: %0.4f", dCurrentLongitude) lblLongitude.text = longitudeString // Followed this tutorial for the next piece: // http://www.veasoftware.com/tutorials/2014/10/18/xcode-6-tutorial-ios-8-current-location-in-swift CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in if error != nil { self.lblCity.text = "Error retrieving city." } if placemarks.count > 0 { let placemark = placemarks[0] as CLPlacemark self.displayCity(placemark) } else { self.lblCity.text = "Error with data." } }) } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { lblLatitude.text = "Can't get your location!" } func displayCity(placemark: CLPlacemark) { lblCity.text = "\(placemark.locality), \(placemark.administrativeArea)" } }
mit
a8dfe2d4360fac6bf0a258547e9e4698
35.710145
113
0.65456
5.086345
false
false
false
false
dclelland/AudioKit
AudioKit/Common/Nodes/Effects/Filters/Equalizer Filter/AKEqualizerFilter.swift
1
5645
// // AKEqualizerFilter.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// A 2nd order tunable equalization filter that provides a peak/notch filter /// for building parametric/graphic equalizers. With gain above 1, there will be /// a peak at the center frequency with a width dependent on bandwidth. If gain /// is less than 1, a notch is formed around the center frequency. /// /// - parameter input: Input node to process /// - parameter centerFrequency: Center frequency. (in Hertz) /// - parameter bandwidth: The peak/notch bandwidth in Hertz /// - parameter gain: The peak/notch gain /// public class AKEqualizerFilter: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKEqualizerFilterAudioUnit? internal var token: AUParameterObserverToken? private var centerFrequencyParameter: AUParameter? private var bandwidthParameter: AUParameter? private var gainParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// Center frequency. (in Hertz) public var centerFrequency: Double = 1000 { willSet { if centerFrequency != newValue { if internalAU!.isSetUp() { centerFrequencyParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.centerFrequency = Float(newValue) } } } } /// The peak/notch bandwidth in Hertz public var bandwidth: Double = 100 { willSet { if bandwidth != newValue { if internalAU!.isSetUp() { bandwidthParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.bandwidth = Float(newValue) } } } } /// The peak/notch gain public var gain: Double = 10 { willSet { if gain != newValue { if internalAU!.isSetUp() { gainParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.gain = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this filter node /// /// - parameter input: Input node to process /// - parameter centerFrequency: Center frequency. (in Hertz) /// - parameter bandwidth: The peak/notch bandwidth in Hertz /// - parameter gain: The peak/notch gain /// public init( _ input: AKNode, centerFrequency: Double = 1000, bandwidth: Double = 100, gain: Double = 10) { self.centerFrequency = centerFrequency self.bandwidth = bandwidth self.gain = gain var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x6571666c /*'eqfl'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKEqualizerFilterAudioUnit.self, asComponentDescription: description, name: "Local AKEqualizerFilter", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKEqualizerFilterAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } guard let tree = internalAU?.parameterTree else { return } centerFrequencyParameter = tree.valueForKey("centerFrequency") as? AUParameter bandwidthParameter = tree.valueForKey("bandwidth") as? AUParameter gainParameter = tree.valueForKey("gain") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.centerFrequencyParameter!.address { self.centerFrequency = Double(value) } else if address == self.bandwidthParameter!.address { self.bandwidth = Double(value) } else if address == self.gainParameter!.address { self.gain = Double(value) } } } internalAU?.centerFrequency = Float(centerFrequency) internalAU?.bandwidth = Float(bandwidth) internalAU?.gain = Float(gain) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
75c667c938a25143500b86037a8cab8a
33.420732
91
0.604074
5.401914
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/DisambiguationPagesViewController.swift
1
2700
import UIKit import WMF @objc(WMFDisambiguationPagesViewController) class DisambiguationPagesViewController: ArticleFetchedResultsViewController { let siteURL: URL let articleURLs: [URL] @objc var resultLimit: Int = 10 @objc(initWithURLs:siteURL:dataStore:theme:) required init(with URLs: [URL], siteURL: URL, dataStore: MWKDataStore, theme: Theme) { self.siteURL = siteURL self.articleURLs = URLs super.init() self.dataStore = dataStore self.theme = theme self.title = WMFLocalizedString("page-similar-titles", value: "Similar pages", comment: "Label for button that shows a list of similar titles (disambiguation) for the current page") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setupFetchedResultsController(with dataStore: MWKDataStore) { let request = WMFArticle.fetchRequest() request.predicate = NSPredicate(format: "key IN %@", articleURLs.compactMap { $0.wmf_databaseKey }) request.sortDescriptors = [NSSortDescriptor(key: "key", ascending: true)] fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: dataStore.viewContext, sectionNameKeyPath: nil, cacheName: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) fetch() } lazy var fakeProgressController: FakeProgressController = { return FakeProgressController(progress: navigationBar, delegate: navigationBar) }() func fetch() { fakeProgressController.start() let articleKeys = articleURLs.compactMap { $0.wmf_inMemoryKey } self.dataStore.articleSummaryController.updateOrCreateArticleSummariesForArticles(withKeys: articleKeys) { (_, error) in self.fakeProgressController.finish() if let error = error { self.wmf_showAlertWithError(error as NSError) return } } } override func configure(cell: ArticleRightAlignedImageCollectionViewCell, forItemAt indexPath: IndexPath, layoutOnly: Bool) { super.configure(cell: cell, forItemAt: indexPath, layoutOnly: layoutOnly) cell.topSeparator.isHidden = indexPath.item != 0 cell.bottomSeparator.isHidden = false } override func canDelete(at indexPath: IndexPath) -> Bool { return false } override var eventLoggingLabel: EventLoggingLabel? { return .similarPage } override var eventLoggingCategory: EventLoggingCategory { return .article } }
mit
ef5c6bcdb54633a2cc51916c75bd3653
37.571429
189
0.684074
5.152672
false
false
false
false
wikimedia/wikipedia-ios
WMF Framework/Remote Notifications/RemoteNotificationsAPIController.swift
1
20846
import CocoaLumberjackSwift public class RemoteNotificationsAPIController: Fetcher { // MARK: Decodable: NotificationsResult struct ResultError: Decodable { let code, info: String? } public struct NotificationsResult: Decodable { struct Query: Decodable { struct Notifications: Decodable { let list: [Notification] let continueId: String? enum CodingKeys: String, CodingKey { case list case continueId = "continue" } } let notifications: Notifications? } let error: ResultError? let query: Query? public struct Notification: Codable, Hashable { struct Timestamp: Codable, Hashable { let utciso8601: String let utcunix: String enum CodingKeys: String, CodingKey { case utciso8601 case utcunix } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) utciso8601 = try values.decode(String.self, forKey: .utciso8601) do { utcunix = String(try values.decode(Int.self, forKey: .utcunix)) } catch { utcunix = try values.decode(String.self, forKey: .utcunix) } } } struct Agent: Codable, Hashable { let id: String? let name: String? enum CodingKeys: String, CodingKey { case id case name } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) name = try values.decode(String.self, forKey: .name) do { id = String(try values.decode(Int.self, forKey: .id)) } catch { id = try values.decode(String.self, forKey: .id) } } } struct Title: Codable, Hashable { let full: String? let namespace: String? let namespaceKey: Int? let text: String? enum CodingKeys: String, CodingKey { case full case namespace case namespaceKey = "namespace-key" case text } } struct Message: Codable, Hashable { let header: String? let body: String? let links: RemoteNotificationLinks? } let wiki: String let id: String let type: String let category: String let section: String let timestamp: Timestamp let title: Title? let agent: Agent? let readString: String? let revisionID: String? let message: Message? let sources: [String: [String: String]]? enum CodingKeys: String, CodingKey { case wiki case id case type case category case section case timestamp case title = "title" case agent case readString = "read" case revisionID = "revid" case message = "*" case sources } public func hash(into hasher: inout Hasher) { hasher.combine(key) } public static func ==(lhs: Notification, rhs: Notification) -> Bool { return lhs.key == rhs.key && lhs.readString == rhs.readString } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) wiki = try values.decode(String.self, forKey: .wiki) do { id = String(try values.decode(Int.self, forKey: .id)) } catch { id = try values.decode(String.self, forKey: .id) } type = try values.decode(String.self, forKey: .type) category = try values.decode(String.self, forKey: .category) section = try values.decode(String.self, forKey: .section) timestamp = try values.decode(Timestamp.self, forKey: .timestamp) title = try? values.decode(Title.self, forKey: .title) agent = try? values.decode(Agent.self, forKey: .agent) readString = try? values.decode(String.self, forKey: .readString) if let intRevID = try? values.decode(Int.self, forKey: .revisionID) { revisionID = String(intRevID) } else { revisionID = (try? values.decode(String.self, forKey: .revisionID)) ?? nil } message = try? values.decode(Message.self, forKey: .message) sources = try? values.decode([String: [String: String]].self, forKey: .sources) } } } // MARK: Decodable: MarkReadResult private struct MarkReadResult: Decodable { let query: Query? let error: ResultError? var succeeded: Bool { return query?.markAsRead?.result == .success } struct Query: Decodable { let markAsRead: MarkedAsRead? enum CodingKeys: String, CodingKey { case markAsRead = "echomarkread" } } struct MarkedAsRead: Decodable { let result: Result? } enum Result: String, Decodable { case success } } enum MarkReadError: LocalizedError { case noResult case unknown case multiple([Error]) var errorDescription: String? { switch self { case .multiple(let errors): if let firstError = errors.first { return (firstError as NSError).alertMessage() } case .noResult, .unknown: return RequestError.unexpectedResponse.errorDescription ?? CommonStrings.genericErrorDescription } return CommonStrings.genericErrorDescription } } // MARK: Decodable: MarkSeenResult struct MarkSeenResult: Decodable { let query: Query? let error: ResultError? var succeeded: Bool { return query?.markAsSeen?.result == .success } struct Query: Decodable { let markAsSeen: MarkAsSeen? enum CodingKeys: String, CodingKey { case markAsSeen = "echomarkseen" } } struct MarkAsSeen: Decodable { let result: Result? } enum Result: String, Decodable { case success } } enum MarkSeenError: LocalizedError { case noResult case unknown var errorDescription: String? { return RequestError.unexpectedResponse.errorDescription ?? CommonStrings.genericErrorDescription } } // MARK: Public public func getUnreadPushNotifications(from project: WikimediaProject, completion: @escaping (Set<NotificationsResult.Notification>, Error?) -> Void) { let completion: (NotificationsResult?, URLResponse?, Error?) -> Void = { result, _, error in guard error == nil else { completion([], error) return } let result = result?.query?.notifications?.list ?? [] completion(Set(result), nil) } request(project: project, queryParameters: Query.notifications(limit: .max, filter: .unread, notifierType: .push, continueId: nil), completion: completion) } func getAllNotifications(from project: WikimediaProject, needsCrossWikiSummary: Bool = false, filter: Query.Filter = .none, continueId: String?, completion: @escaping (NotificationsResult.Query.Notifications?, Error?) -> Void) { let completion: (NotificationsResult?, URLResponse?, Error?) -> Void = { result, _, error in guard error == nil else { completion(nil, error) return } completion(result?.query?.notifications, result?.error) } request(project: project, queryParameters: Query.notifications(from: [project], limit: .max, filter: filter, needsCrossWikiSummary: needsCrossWikiSummary, continueId: continueId), completion: completion) } func markAllAsSeen(project: WikimediaProject, completion: @escaping ((Result<Void, Error>) -> Void)) { request(project: project, queryParameters: Query.markAllAsSeen(project: project), method: .post) { (result: MarkSeenResult?, _, error) in if let error = error { completion(.failure(error)) return } guard let result = result else { assertionFailure("Expected result") completion(.failure(MarkSeenError.noResult)) return } if let error = result.error { completion(.failure(error)) return } if !result.succeeded { completion(.failure(MarkSeenError.unknown)) return } completion(.success(())) } } func markAllAsRead(project: WikimediaProject, completion: @escaping (Error?) -> Void) { request(project: project, queryParameters: Query.markAllAsRead(project: project), method: .post) { (result: MarkReadResult?, _, error) in if let error = error { completion(error) return } guard let result = result else { assertionFailure("Expected result; make sure MarkReadResult maps the expected result correctly") completion(MarkReadError.noResult) return } if let error = result.error { completion(error) return } if !result.succeeded { completion(MarkReadError.unknown) return } completion(nil) } } func markAsReadOrUnread(project: WikimediaProject, identifierGroups: Set<RemoteNotification.IdentifierGroup>, shouldMarkRead: Bool, completion: @escaping (Error?) -> Void) { let maxNumberOfNotificationsPerRequest = 50 let identifierGroups = Array(identifierGroups) let split = identifierGroups.chunked(into: maxNumberOfNotificationsPerRequest) split.asyncCompactMap({ (identifierGroups, completion: @escaping (Error?) -> Void) in request(project: project, queryParameters: Query.markAsReadOrUnread(identifierGroups: identifierGroups, shouldMarkRead: shouldMarkRead), method: .post) { (result: MarkReadResult?, _, error) in if let error = error { completion(error) return } guard let result = result else { assertionFailure("Expected result; make sure MarkReadResult maps the expected result correctly") completion(MarkReadError.noResult) return } if let error = result.error { completion(error) return } if !result.succeeded { completion(MarkReadError.unknown) return } completion(nil) } }) { (errors) in if errors.isEmpty { completion(nil) } else { DDLogError("\(errors.count) of \(split.count) mark as read requests failed") completion(MarkReadError.multiple(errors)) } } } // MARK: Private private func request<T: Decodable>(project: WikimediaProject?, queryParameters: Query.Parameters?, method: Session.Request.Method = .get, completion: @escaping (T?, URLResponse?, Error?) -> Void) { guard let url = project?.mediaWikiAPIURL(configuration: configuration, queryParameters: queryParameters) else { completion(nil, nil, RequestError.invalidParameters) return } if method == .get { session.jsonDecodableTask(with: url, method: .get, completionHandler: completion) } else { requestMediaWikiAPIAuthToken(for:url, type: .csrf) { (result) in switch result { case .failure(let error): completion(nil, nil, error) case .success(let token): self.session.jsonDecodableTask(with: url, method: method, bodyParameters: ["token": token.value], bodyEncoding: .form, completionHandler: completion) } } } } // MARK: Query parameters struct Query { typealias Parameters = [String: Any] enum Limit { case max case numeric(Int) var value: String { switch self { case .max: return "max" case .numeric(let number): return "\(number)" } } } enum Filter: String { case read = "read" case unread = "!read" case none = "read|!read" } enum NotifierType: String { case web case push case email } static func notifications(from projects: [WikimediaProject] = [], limit: Limit = .max, filter: Filter = .none, notifierType: NotifierType? = nil, needsCrossWikiSummary: Bool = false, continueId: String?) -> Parameters { var dictionary: [String: Any] = ["action": "query", "format": "json", "formatversion": "2", "notformat": "model", "meta": "notifications", "notlimit": limit.value, "notfilter": filter.rawValue] if let continueId = continueId { dictionary["notcontinue"] = continueId } if let notifierType = notifierType { dictionary["notnotifiertypes"] = notifierType.rawValue } if needsCrossWikiSummary { dictionary["notcrosswikisummary"] = 1 } let wikis = projects.map { $0.notificationsApiWikiIdentifier } dictionary["notwikis"] = wikis.isEmpty ? "*" : wikis.joined(separator: "|") return dictionary } static func markAsReadOrUnread(identifierGroups: [RemoteNotification.IdentifierGroup], shouldMarkRead: Bool) -> Parameters? { let IDs = identifierGroups.compactMap { $0.id } var dictionary = ["action": "echomarkread", "format": "json"] if shouldMarkRead { dictionary["list"] = IDs.joined(separator: "|") } else { dictionary["unreadlist"] = IDs.joined(separator: "|") } return dictionary } static func markAllAsRead(project: WikimediaProject) -> Parameters? { let dictionary = ["action": "echomarkread", "all": "true", "wikis": project.notificationsApiWikiIdentifier, "format": "json"] return dictionary } static func markAllAsSeen(project: WikimediaProject) -> Parameters? { let dictionary = ["action": "echomarkseen", "wikis": project.notificationsApiWikiIdentifier, "format": "json", "type": "all"] return dictionary } } } extension RemoteNotificationsAPIController.ResultError: LocalizedError { var errorDescription: String? { return info } } // MARK: Public Notification Extensions public extension RemoteNotificationsAPIController.NotificationsResult.Notification { var key: String { return "\(wiki)-\(id)" } var date: Date? { return DateFormatter.wmf_iso8601()?.date(from: timestamp.utciso8601) } var pushContentText: String? { return self.message?.header?.removingHTML } var namespaceKey: Int? { return self.title?.namespaceKey } var titleFull: String? { return self.title?.full } func isNewerThan(timeAgo: TimeInterval) -> Bool { guard let date = date else { return false } return date > Date().addingTimeInterval(-timeAgo) } var namespace: PageNamespace? { return PageNamespace(namespaceValue: title?.namespaceKey) } } // MARK: Test Helpers #if TEST extension RemoteNotificationsAPIController.NotificationsResult.Notification { init?(project: WikimediaProject, titleText: String, titleNamespace: PageNamespace, remoteNotificationType: RemoteNotificationType, date: Date, customID: String? = nil) { switch remoteNotificationType { case .userTalkPageMessage: self.category = "edit-user-talk" self.type = "edit-user-talk" self.section = "alert" case .editReverted: self.category = "reverted" self.type = "reverted" self.section = "alert" default: assertionFailure("Haven't set up test models for this type.") return nil } self.wiki = project.notificationsApiWikiIdentifier let identifier = customID ?? UUID().uuidString self.id = identifier let timestamp = Timestamp(date: date) self.timestamp = timestamp self.title = Title(titleText: titleText, titleNamespace: titleNamespace) self.agent = Agent() self.revisionID = nil self.readString = nil self.message = Message(identifier: identifier) self.sources = nil } } extension RemoteNotificationsAPIController.NotificationsResult.Notification.Timestamp { init(date: Date) { let dateString8601 = DateFormatter.wmf_iso8601().string(from: date) let unixTimeInterval = date.timeIntervalSince1970 self.utciso8601 = dateString8601 self.utcunix = String(unixTimeInterval) } } extension RemoteNotificationsAPIController.NotificationsResult.Notification.Title { init(titleText: String, titleNamespace: PageNamespace) { let namespaceText = titleNamespace.canonicalName self.full = "\(namespaceText):\(titleText)" self.namespace = titleNamespace.canonicalName.denormalizedPageTitle self.namespaceKey = titleNamespace.rawValue self.text = titleText } } extension RemoteNotificationsAPIController.NotificationsResult.Notification.Agent { init() { self.id = String(12345) self.name = "Test Agent Name" } } extension RemoteNotificationsAPIController.NotificationsResult.Notification.Message { init(identifier: String) { self.header = "\(identifier)" self.body = "Test body text for identifier: \(identifier)" let primaryLink = RemoteNotificationLink(type: nil, url: URL(string:"https://en.wikipedia.org/wiki/Cat")!, label: "Label for primary link") self.links = RemoteNotificationLinks(primary: primaryLink, secondary: nil, legacyPrimary: primaryLink) } } #endif
mit
d0aedf90622ef165bfe3e053cd94dca6
34.695205
232
0.52955
5.501715
false
false
false
false
gaurav1981/eidolon
Kiosk/Bid Fulfillment/SwipeCreditCardViewController.swift
1
3600
import UIKit import Artsy_UILabels import ReactiveCocoa import Swift_RAC_Macros import Keys class SwipeCreditCardViewController: UIViewController, RegistrationSubController { @IBOutlet var cardStatusLabel: ARSerifLabel! let finishedSignal = RACSubject() @IBOutlet weak var spinner: Spinner! @IBOutlet weak var processingLabel: UILabel! @IBOutlet weak var illustrationImageView: UIImageView! @IBOutlet weak var titleLabel: ARSerifLabel! class func instantiateFromStoryboard(storyboard: UIStoryboard) -> SwipeCreditCardViewController { return storyboard.viewControllerWithID(.RegisterCreditCard) as! SwipeCreditCardViewController } dynamic var cardName = "" dynamic var cardLastDigits = "" dynamic var cardToken = "" lazy var keys = EidolonKeys() lazy var bidDetails: BidDetails! = { self.navigationController!.fulfillmentNav().bidDetails }() override func viewDidLoad() { super.viewDidLoad() self.setInProgress(false) let cardHandler = CardHandler(apiKey: self.keys.cardflightAPIClientKey(), accountToken: self.keys.cardflightMerchantAccountToken()) cardHandler.cardSwipedSignal.subscribeNext({ (message) -> Void in let message = message as! String self.cardStatusLabel.text = "Card Status: \(message)" if message == "Got Card" { self.setInProgress(true) } if message.hasPrefix("Card Flight Error") { self.processingLabel.text = "ERROR PROCESSING CARD - SEE ADMIN" } }, error: { (error) -> Void in self.cardStatusLabel.text = "Card Status: Errored" self.setInProgress(false) self.titleLabel.text = "Please Swipe a Valid Credit Card" self.titleLabel.textColor = UIColor.artsyRed() }, completed: { self.cardStatusLabel.text = "Card Status: completed" if let card = cardHandler.card { self.cardName = card.name self.cardLastDigits = card.encryptedSwipedCardNumber if AppSetup.sharedState.useStaging { self.cardToken = "/v1/marketplaces/TEST-MP7Fs9XluC54HnVAvBKSI3jQ/cards/CC1AF3Ood4u5GdLz4krD8upG" } else { self.cardToken = card.cardToken } // TODO: RACify this if let newUser = self.navigationController?.fulfillmentNav().bidDetails.newUser { newUser.name = (newUser.name == "" || newUser.name == nil) ? card.name : newUser.name } } cardHandler.end() self.finishedSignal.sendCompleted() }) cardHandler.startSearching() RAC(bidDetails, "newUser.creditCardName") <~ RACObserve(self, "cardName").takeUntil(viewWillDisappearSignal()) RAC(bidDetails, "newUser.creditCardDigit") <~ RACObserve(self, "cardLastDigits").takeUntil(viewWillDisappearSignal()) RAC(bidDetails, "newUser.creditCardToken") <~ RACObserve(self, "cardToken").takeUntil(viewWillDisappearSignal()) } func setInProgress(show: Bool) { illustrationImageView.alpha = show ? 0.1 : 1 processingLabel.hidden = !show spinner.hidden = !show } } private extension SwipeCreditCardViewController { @IBAction func dev_creditCradOKTapped(sender: AnyObject) { self.cardName = "KIOSK SKIPPED CARD CHECK" self.cardLastDigits = "2323" self.cardToken = "3223423423423" self.finishedSignal.sendCompleted() } }
mit
d243d3bcc089a1b320e1824d515fd5cd
36.113402
139
0.649722
4.736842
false
false
false
false
nicadre/SwiftyProtein
SwiftyProtein/Controllers/ProteinViewController.swift
1
6134
// // ProteinViewController.swift // SwiftyProtein // // Created by Nicolas Chevalier on 19/07/16. // Copyright © 2016 Nicolas CHEVALIER. All rights reserved. // import UIKit import SceneKit import SWXMLHash class ProteinViewController: UIViewController, UIPopoverPresentationControllerDelegate { @IBOutlet weak var infoAtomLabel: UILabel! @IBOutlet weak var infoButton: UIButton! @IBOutlet weak var segmentControl: UISegmentedControl! var proteinName: String! var atomList: [Int : Atom]! var connectList: [Connect]! var xml: XMLIndexer? @IBAction func displayInfo(sender: UIButton) { if UIApplication.sharedApplication().networkActivityIndicatorVisible == false { APIRequester.sharedInstance.requestInfoLigand(self.proteinName) { response in dispatch_async(dispatch_get_main_queue()) { if let status = response.response?.statusCode { if case 200..<300 = status { self.xml = SWXMLHash.parse(response.data!) self.performSegueWithIdentifier("popOverInfo", sender: self) } else { let alert = UIAlertController(title: "Load error", message: "Can't get ligand informations. Please retry later.", preferredStyle: .Alert) let action = UIAlertAction(title: "Ok", style: .Default, handler: nil) alert.addAction(action) self.presentViewController(alert, animated: true, completion: nil) } } else { let alert = UIAlertController(title: "Load error", message: "Can't get ligand informations. Please retry later.", preferredStyle: .Alert) let action = UIAlertAction(title: "Ok", style: .Default, handler: nil) alert.addAction(action) self.presentViewController(alert, animated: true, completion: nil) } } } } } @IBAction func shareAction(sender: UIButton) { let scnView = self.view as! SCNView let objects = ["This \(proteinName) is awesome!", scnView.snapshot()] let activityVC = UIActivityViewController(activityItems: objects, applicationActivities: nil) activityVC.popoverPresentationController?.sourceView = sender self.presentViewController(activityVC, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = proteinName infoAtomLabel.text = "" segmentControl.selectedSegmentIndex = 0 let tap = UITapGestureRecognizer(target: self, action: #selector(ProteinViewController.onTap)) let scnView = self.view as! SCNView scnView.addGestureRecognizer(tap) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let scnView = self.view as! SCNView scnView.scene = ProteinScene(atomsList: atomList, connectsList: connectList, representation: true) scnView.backgroundColor = UIColor.fromRGB(0xeeeeee) scnView.autoenablesDefaultLighting = true scnView.allowsCameraControl = true } func onTap(gesture: UITapGestureRecognizer) { let scnView = self.view as! SCNView let p = gesture.locationInView(view) let atoms = scnView.hitTest(p, options: nil) if atoms.count > 0 { let result = atoms[0] if let atom = result.node as? AtomNode { self.infoAtomLabel.text = "Type: \(atom.atom.type) - Id: \(atom.atom.id)" self.infoAtomLabel.sizeToFit() } else { infoAtomLabel.text = "" } } else { infoAtomLabel.text = "" } } @IBAction func changeRepresentation(sender: AnyObject) { let scnView = self.view as! SCNView switch segmentControl.selectedSegmentIndex { case 0: scnView.scene = ProteinScene(atomsList: atomList, connectsList: connectList, representation: true) default: scnView.scene = ProteinScene(atomsList: atomList, connectsList: connectList, representation: false) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "popOverInfo" { if let popoverViewController = segue.destinationViewController as? PopOverViewController { popoverViewController.modalPresentationStyle = UIModalPresentationStyle.Popover popoverViewController.popoverPresentationController!.delegate = self popoverViewController.popoverPresentationController?.sourceRect = CGRectMake(infoButton.frame.width / 2, infoButton.frame.height + 2, 0, 0) let ligand = self.xml!["describeHet"]["ligandInfo"]["ligand"] if let chemicalID = ligand.element?.attributes["chemicalID"] { popoverViewController.chemicalId = chemicalID } if let type = ligand.element?.attributes["type"] { popoverViewController.type = type } if let weight = ligand.element?.attributes["molecularWeight"] { popoverViewController.weight = weight } if let chemicalName = ligand["chemicalName"].element?.text { popoverViewController.chemicalName = chemicalName } if let formula = ligand["formula"].element?.text { popoverViewController.formula = formula } } } } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.None } }
gpl-3.0
42b59a819ce06837d9a9f0bfe4c7b9be
35.505952
165
0.602805
5.337685
false
false
false
false
CoderST/DYZB
DYZB/DYZB/Class/Home/View/SearchHeadRecentlyCell.swift
1
1207
// // SearchHeadCell.swift // DYZB // // Created by xiudou on 2017/6/23. // Copyright © 2017年 xiudo. All rights reserved. // 最近搜索cell import UIKit class SearchHeadRecentlyCell: UICollectionViewCell { fileprivate let titleLabel : UILabel = { let titleLabel = UILabel() titleLabel.font = UIFont.systemFont(ofSize: titleFontSize) titleLabel.textAlignment = .center return titleLabel }() override init(frame: CGRect) { super.init(frame: frame) contentView.backgroundColor = UIColor.lightGray contentView.layer.cornerRadius = 5 contentView.clipsToBounds = true contentView.addSubview(titleLabel) } var searchFrame : SearchModelFrame?{ didSet{ guard let searchFrame = searchFrame else { return } titleLabel.text = searchFrame.searchModel.title titleLabel.frame = CGRect(x: 0, y: 0, width: searchFrame.cellSize.width, height: searchFrame.cellSize.height) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
91687b9ecf0fb2412298c75352c794fe
25.577778
121
0.618729
4.803213
false
false
false
false
mssun/passforios
pass/Services/PasswordDecryptor.swift
1
8890
// // PasswordDecryptor.swift // pass // // Created by Sun, Mingshen on 1/17/21. // Copyright © 2021 Bob Sun. All rights reserved. // import CryptoTokenKit import Gopenpgp import passKit import SVProgressHUD import UIKit import YubiKit func decryptPassword( in controller: UIViewController, with passwordPath: String, using keyID: String? = nil, completion: @escaping ((Password) -> Void) ) { // YubiKey is not supported in extension if Defaults.isYubiKeyEnabled { DispatchQueue.main.async { let alert = UIAlertController(title: "Error", message: "YubiKey is not supported in extension, please use the Pass app instead.", preferredStyle: .alert) alert.addAction(UIAlertAction.ok()) controller.present(alert, animated: true) } return } DispatchQueue.global(qos: .userInteractive).async { do { let requestPGPKeyPassphrase = Utils.createRequestPGPKeyPassphraseHandler(controller: controller) let decryptedPassword = try PasswordStore.shared.decrypt(path: passwordPath, keyID: keyID, requestPGPKeyPassphrase: requestPGPKeyPassphrase) DispatchQueue.main.async { completion(decryptedPassword) } } catch let AppError.pgpPrivateKeyNotFound(keyID: key) { DispatchQueue.main.async { let alert = UIAlertController(title: "CannotShowPassword".localize(), message: AppError.pgpPrivateKeyNotFound(keyID: key).localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction.cancelAndPopView(controller: controller)) let selectKey = UIAlertAction.selectKey(controller: controller) { action in decryptPassword(in: controller, with: passwordPath, using: action.title, completion: completion) } alert.addAction(selectKey) controller.present(alert, animated: true) } } catch { DispatchQueue.main.async { Utils.alert(title: "CannotCopyPassword".localize(), message: error.localizedDescription, controller: controller) } } } } public typealias RequestPINAction = (@escaping (String) -> Void) -> Void let symmetricKeyIDNameDict: [UInt8: String] = [ 2: "3des", 3: "cast5", 7: "aes128", 8: "aes192", 9: "aes256", ] private func isEncryptKeyAlgoRSA(_ applicationRelatedData: Data) -> Bool { if #available(iOS 13.0, *) { let tlv = TKBERTLVRecord.sequenceOfRecords(from: applicationRelatedData)! // 0x73: Discretionary data objects for record in TKBERTLVRecord.sequenceOfRecords(from: tlv.first!.value)! where record.tag == 0x73 { // 0xC2: Algorithm attributes decryption, 0x01: RSA for record2 in TKBERTLVRecord.sequenceOfRecords(from: record.value)! where record2.tag == 0xC2 && record2.value.first! == 0x01 { return true } } return false } else { // We need CryptoTokenKit (iOS 13.0+) to check if data is RSA, so fail open here. return true } } // swiftlint:disable cyclomatic_complexity public func yubiKeyDecrypt( passwordEntity: PasswordEntity, requestPIN: @escaping RequestPINAction, errorHandler: @escaping ((AppError) -> Void), cancellation: @escaping ((_ error: Error) -> Void), completion: @escaping ((Password) -> Void) ) { let encryptedDataPath = PasswordStore.shared.storeURL.appendingPathComponent(passwordEntity.getPath()) guard let encryptedData = try? Data(contentsOf: encryptedDataPath) else { errorHandler(AppError.other(message: "PasswordDoesNotExist".localize())) return } // swiftlint:disable closure_body_length requestPIN { pin in // swiftlint:disable closure_body_length passKit.YubiKeyConnection.shared.connection(cancellation: cancellation) { connection in guard let smartCard = connection.smartCardInterface else { errorHandler(AppError.yubiKey(.connection(message: "Failed to get smart card interface."))) return } // 1. Select OpenPGP application let selectOpenPGPAPDU = YubiKeyAPDU.selectOpenPGPApplication() smartCard.selectApplication(selectOpenPGPAPDU) { _, error in guard error == nil else { errorHandler(AppError.yubiKey(.selectApplication(message: "Failed to select application."))) return } // 2. Verify PIN let verifyApdu = YubiKeyAPDU.verify(password: pin) smartCard.executeCommand(verifyApdu) { _, error in guard error == nil else { errorHandler(AppError.yubiKey(.verify(message: "Failed to verify PIN."))) return } let applicationRelatedDataApdu = YubiKeyAPDU.get_application_related_data() smartCard.executeCommand(applicationRelatedDataApdu) { data, _ in guard let data = data else { errorHandler(AppError.yubiKey(.decipher(message: "Failed to get application related data."))) return } if !isEncryptKeyAlgoRSA(data) { errorHandler(AppError.yubiKey(.decipher(message: "Encryption key algorithm is not supported. Supported algorithm: RSA."))) return } // 3. Decipher let ciphertext = encryptedData var error: NSError? let message = CryptoNewPGPMessage(ciphertext) guard let mpi1 = Gopenpgp.HelperPassGetEncryptedMPI1(message, &error) else { errorHandler(AppError.yubiKey(.decipher(message: "Failed to get encrypted MPI."))) return } let decipherApdu = YubiKeyAPDU.decipher(data: mpi1) smartCard.executeCommand(decipherApdu) { data, error in guard let data = data else { errorHandler(AppError.yubiKey(.decipher(message: "Failed to execute decipher."))) return } if #available(iOS 13.0, *) { YubiKitManager.shared.stopNFCConnection() } guard let algoByte = data.first, let algo = symmetricKeyIDNameDict[algoByte] else { errorHandler(AppError.yubiKey(.decipher(message: "Failed to new session key."))) return } guard let session_key = Gopenpgp.CryptoNewSessionKeyFromToken(data[1 ..< data.count - 2], algo) else { errorHandler(AppError.yubiKey(.decipher(message: "Failed to new session key."))) return } var error: NSError? let message = CryptoNewPGPMessage(ciphertext) guard let plaintext = Gopenpgp.HelperPassDecryptWithSessionKey(message, session_key, &error)?.data else { errorHandler(AppError.yubiKey(.decipher(message: "Failed to decrypt with session key."))) return } guard let plaintext_str = String(data: plaintext, encoding: .utf8) else { errorHandler(AppError.yubiKey(.decipher(message: "Failed to convert plaintext to string."))) return } guard let password = try? Password(name: passwordEntity.getName(), url: passwordEntity.getURL(), plainText: plaintext_str) else { errorHandler(AppError.yubiKey(.decipher(message: "Failed to construct password."))) return } completion(password) } } } } } } } extension Data { struct HexEncodingOptions: OptionSet { let rawValue: Int static let upperCase = HexEncodingOptions(rawValue: 1 << 0) } func hexEncodedString(options: HexEncodingOptions = []) -> String { let format = options.contains(.upperCase) ? "%02hhX" : "%02hhx" return map { String(format: format, $0) }.joined() } }
mit
77e7f931596287106f2af1668ccdeab2
43.00495
183
0.566093
5.064957
false
false
false
false
scootpl/Na4lapyAPI
Sources/Na4LapyCore/AnimalBackend.swift
1
6496
// // AnimalBackend.swift // Na4lapyAPI // // Created by Andrzej Butkiewicz on 24.12.2016. // Copyright © 2016 Stowarzyszenie Na4Łapy. All rights reserved. // import Foundation public class AnimalBackend: Model { let db: DBLayer public init(db: DBLayer) { self.db = db } public func delete(byId id: Int) throws -> String { try db.deleteAnimal(byId: id) return "" } /** Modyfikacja obiektu - Parameter dictionary */ public func edit(withDictionary dictionary: JSONDictionary) throws -> Int { guard let animal = Animal(withJSON: dictionary) else { throw ResultCode.AnimalBackendBadParameters } let id = try db.editAnimal(values: animal.dbRepresentation()) return id } /** Dodawanie obiektu do bazy - Parameter dictionary */ public func add(withDictionary dictionary: JSONDictionary) throws -> Int { guard let animal = Animal(withJSON: dictionary) else { throw ResultCode.AnimalBackendBadParameters } let id = try db.addIntoAnimal(values: animal.dbRepresentation()) return id } /** Pobieranie wszystkich obiektów */ public func getall(shelterid: Int?) throws -> JSONDictionary { var dbresult: [DBEntry] if let shelterid = shelterid { dbresult = try db.fetchAll(shelterid: shelterid) } else { dbresult = try db.fetchAllActiveAnimals(table: Config.animaltable) } if dbresult.count == 0 { throw ResultCode.AnimalBackendNoData } let photo = PhotoBackend(db: db) var animals: [JSONDictionary] = [] // TODO: metody pobierania danych z bazy być może powinny pracować na innym wątku, // TODO: wymaga to zastosowania zabezpieczeń, choćby DispatchGroup for entry in dbresult { guard let animal = Animal(dictionary: entry) else { throw ResultCode.AnimalBackendBadParameters } let photoresult = try photo.get(byId: animal.id) var outputanimal = animal.dictionaryRepresentation() outputanimal[AnimalJSON.photos] = photoresult[AnimalJSON.photos] animals.append(outputanimal) } let metajson: JSONDictionary = [AnimalJSON.data : animals, AnimalJSON.total : "1"] return metajson } /** Pobieranie dokładnie jednego obiektu o zadanym id - Parameter id */ public func get(byId id: Int) throws -> JSONDictionary { let dbresult = try db.fetch(byId: id, table: Config.animaltable, idname: AnimalDBKey.id) if dbresult.count == 0 { throw ResultCode.AnimalBackendNoData } if dbresult.count > 1 { throw ResultCode.AnimalBackendTooManyEntries } guard let animal = Animal(dictionary: dbresult.first!) else { throw ResultCode.AnimalBackendBadParameters } let photo = PhotoBackend(db: db) let photoresult = try photo.get(byId: animal.id) var outputjson: JSONDictionary = animal.dictionaryRepresentation() outputjson[AnimalJSON.photos] = photoresult[AnimalJSON.photos] return outputjson } /** Pobieranie wielu obiektów z uwzględnieniem stronicowania oraz dodatkowych parametrów użytkownika - Parameter page - Parameter size - Parameter params */ public func get(byPage page: Int, size: Int, shelterid: Int?, withParameters params: ParamDictionary) throws -> JSONDictionary { if !params.isEmpty { // TODO // w zapytaniu są dodatkowe parametry } var dbresult: [DBEntry] if let shelterid = shelterid { dbresult = try db.fetch(byPage: page, size: size, shelterid: shelterid, table: Config.animaltable) } else { dbresult = try db.fetchActiveAnimals(byPage: page, size: size, table: Config.animaltable) } if dbresult.count == 0 { throw ResultCode.AnimalBackendNoData } let photo = PhotoBackend(db: db) var animals: [JSONDictionary] = [] var totalPages: Int = 0 // TODO: metody pobierania danych z bazy być może powinny pracować na innym wątku, // TODO: wymaga to zastosowania zabezpieczeń, choćby DispatchGroup for entry in dbresult { guard let animal = Animal(dictionary: entry) else { throw ResultCode.AnimalBackendBadParameters } let photoresult = try photo.get(byId: animal.id) var outputanimal = animal.dictionaryRepresentation() outputanimal[AnimalJSON.photos] = photoresult[AnimalJSON.photos] animals.append(outputanimal) } if let count = dbresult.first?["count"], let intcount = count.int { totalPages = (intcount/size) if intcount % size > 0 { totalPages += 1 } } let metajson: JSONDictionary = [AnimalJSON.data : animals, AnimalJSON.total : totalPages] return metajson } /** Pobieranie wielu obiektów na podstawie tablicy id - Parameter ids */ public func get(byIds ids: [Int]) throws -> JSONDictionary { let dbresult = try db.fetch(byIds: ids, table: Config.animaltable, idname: AnimalJSON.id) if dbresult.count == 0 { throw ResultCode.AnimalBackendNoData } let photo = PhotoBackend(db: db) var animals: [JSONDictionary] = [] // TODO: metody pobierania danych z bazy być może powinny pracować na innym wątku, // TODO: wymaga to zastosowania zabezpieczeń, choćby DispatchGroup for entry in dbresult { guard let animal = Animal(dictionary: entry) else { throw ResultCode.AnimalBackendBadParameters } let photoresult = try photo.get(byId: animal.id) var outputanimal = animal.dictionaryRepresentation() outputanimal[AnimalJSON.photos] = photoresult[AnimalJSON.photos] animals.append(outputanimal) } let metajson: JSONDictionary = [AnimalJSON.data : animals, AnimalJSON.total : 1] return metajson } public func deleteAll(byId id: Int) throws -> [String] { return [] } }
apache-2.0
6c673855126e97a38756cb6db367ca51
33.588235
132
0.614409
4.119745
false
false
false
false
cacawai/Tap2Read
tap2read/tap2read/LanguageBar.swift
1
2870
// // LanguageBar.swift // tap2read // // Created by 徐新元 on 08/12/2016. // Copyright © 2016 Last4 Team. All rights reserved. // import UIKit protocol LanguageBarDelegate: class { func onLanguaeSelected(language: String) } class LanguageBar: UICollectionView,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate { let supportedLanguages:[String] = ConfigMgr.sharedInstance.supportedLanguages var supportedLanguagesCount = 0 var cellPerRow = 1 var cellWidth:CGFloat = ConfigMgr.sharedInstance.screenSize.width var cellHeight:CGFloat = 50.0 var currentLanguage:String = ConfigMgr.sharedInstance.currentLanguage() weak var languageBarDelegate:LanguageBarDelegate? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.dataSource = self self.delegate = self supportedLanguagesCount = supportedLanguages.count cellPerRow = min(supportedLanguagesCount, 5) cellWidth = ConfigMgr.sharedInstance.screenSize.width / CGFloat(cellPerRow) self.register(UINib(nibName: "LanguageBarCell", bundle: nil), forCellWithReuseIdentifier: "LanguageBarCell") } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LanguageBarCell", for: indexPath) as! LanguageBarCell let index = indexPath.row cell.setImageWithLanguage(language: supportedLanguages[index]) cell.setHighlighted(isHighlighted: currentLanguage == supportedLanguages[index]) return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return supportedLanguages.count } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: cellWidth, height: cellHeight) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let index = indexPath.row if index > 1 { return } let language = supportedLanguages[index] currentLanguage = language ConfigMgr.sharedInstance.setCurrentLanguage(language: currentLanguage) languageBarDelegate?.onLanguaeSelected(language: language) let cells = collectionView.visibleCells as! [LanguageBarCell] for cell in cells { cell.setHighlighted(isHighlighted: false) } let currentCell = collectionView.cellForItem(at: indexPath) as! LanguageBarCell currentCell.setHighlighted(isHighlighted: currentLanguage == supportedLanguages[index]) currentCell.doZoomAnimation() } }
mit
1b1244a70a4b6c4203f2e9a5850894ef
38.763889
160
0.733496
5.371482
false
true
false
false
wireapp/wire-ios
Wire-iOS Tests/ConversationMessageCell/ReadReceiptSystemMessage/ReadReceiptViewModelTests.swift
1
2926
// // Wire // Copyright (C) 2018 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 XCTest @testable import Wire final class ReadReceiptViewModelTests: XCTestCase { var sut: ReadReceiptViewModel! var mockMessage: MockMessage! override func setUp() { super.setUp() } override func tearDown() { sut = nil mockMessage = nil super.tearDown() } private func createMockMessage(type: ZMSystemMessageType) { mockMessage = MockMessageFactory.systemMessage(with: type)! } private func createSut(type: ZMSystemMessageType) { sut = ReadReceiptViewModel(icon: .eye, iconColor: UIColor.from(scheme: .textDimmed), systemMessageType: type, sender: mockMessage.senderUser!) } func testThatSelfUserSwitchOffReceiptOption() { // GIVEN & WHEN let type = ZMSystemMessageType.readReceiptsDisabled createMockMessage(type: type) createSut(type: type) // THEN XCTAssertEqual(sut.attributedTitle()?.string, "You turned read receipts off for everyone") } func testThatOneUserSwitchOffReceiptOption() { // GIVEN let type = ZMSystemMessageType.readReceiptsDisabled createMockMessage(type: type) mockMessage.senderUser = SwiftMockLoader.mockUsers().first // WHEN createSut(type: type) // THEN XCTAssertEqual(sut.attributedTitle()?.string, "James Hetfield turned read receipts off for everyone") } func testThatOneUserSwitchOnReceiptOption() { // GIVEN & WHEN let type = ZMSystemMessageType.readReceiptsEnabled createMockMessage(type: type) mockMessage.senderUser = SwiftMockLoader.mockUsers().first createSut(type: type) // THEN XCTAssertEqual(sut.attributedTitle()?.string, "James Hetfield turned read receipts on for everyone") } func testThatReceiptOptionOnMessageIsShown() { // GIVEN & WHEN let type = ZMSystemMessageType.readReceiptsOn createMockMessage(type: type) createSut(type: type) // THEN XCTAssertEqual(sut.attributedTitle()?.string, "Read receipts are on") } }
gpl-3.0
063b6d64e07c0c444485069894fd5c99
29.8
109
0.661312
4.804598
false
true
false
false
wireapp/wire-ios
Wire-iOS/Sources/Authentication/Event Handlers/Registration/RegistrationIncrementalUserDataChangeHandler.swift
1
3340
// // Wire // Copyright (C) 2018 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 import WireDataModel /** * Handles the change of user data during registration. */ class RegistrationIncrementalUserDataChangeHandler: AuthenticationEventHandler { weak var statusProvider: AuthenticationStatusProvider? func handleEvent(currentStep: AuthenticationFlowStep, context: Void) -> [AuthenticationCoordinatorAction]? { // Only handle data change during incremental creation step guard case let .incrementalUserCreation(unregisteredUser, _) = currentStep else { return nil } // Check for missing requirements before allowing the user to register. if unregisteredUser.marketingConsent == nil { return handleMissingMarketingConsent(with: unregisteredUser) } else if unregisteredUser.name == nil { return requestIntermediateStep(.setName, with: unregisteredUser) } else if unregisteredUser.password == nil && unregisteredUser.needsPassword { return requestIntermediateStep(.setPassword, with: unregisteredUser) } else { return handleRegistrationCompletion(with: unregisteredUser) } } // MARK: - Specific Flow Handlers private func requestIntermediateStep(_ step: IntermediateRegistrationStep, with user: UnregisteredUser) -> [AuthenticationCoordinatorAction] { let flowStep = AuthenticationFlowStep.incrementalUserCreation(user, step) return [.hideLoadingView, .transition(flowStep, mode: .reset)] } private func handleMissingMarketingConsent(with user: UnregisteredUser) -> [AuthenticationCoordinatorAction] { // Alert Actions let privacyPolicyAction = AuthenticationCoordinatorAlertAction(title: "news_offers.consent.button.privacy_policy.title".localized, coordinatorActions: [.openURL(URL.wr_privacyPolicy.appendingLocaleParameter)]) let declineAction = AuthenticationCoordinatorAlertAction(title: "general.decline".localized, coordinatorActions: [.setMarketingConsent(false)]) let acceptAction = AuthenticationCoordinatorAlertAction(title: "general.accept".localized, coordinatorActions: [.setMarketingConsent(true)]) // Alert let alert = AuthenticationCoordinatorAlert(title: "news_offers.consent.title".localized, message: "news_offers.consent.message".localized, actions: [privacyPolicyAction, declineAction, acceptAction]) return [.hideLoadingView, .presentAlert(alert)] } private func handleRegistrationCompletion(with user: UnregisteredUser) -> [AuthenticationCoordinatorAction] { return [.showLoadingView, .completeUserRegistration] } }
gpl-3.0
a01c936e9ddd99d1f58ee9c6d587f0d8
43.533333
217
0.742814
5.068285
false
false
false
false
rastogigaurav/mTV
mTV/mTV/Adaptors/Repositories/MoviesRepository.swift
1
9863
// // MovieRepository.swift // mTV // // Created by Gaurav Rastogi on 6/21/17. // Copyright © 2017 Gaurav Rastogi. All rights reserved. // import UIKit protocol MoviesRepositoryProtocol:NSObjectProtocol { func getTopRatedMovies(page:Int, completionHandler:@escaping(_ totalMovies:Int?, _ movies:[Movie]?,_ error:Error?)->Void) -> Void func getUpcomingMovies(page:Int, completionHandler:@escaping(_ totalMovies:Int?, _ movies:[Movie]?,_ error:Error?)->Void) -> Void func getNowPlayingMovies(page:Int, completionHandler:@escaping(_ totalMovies:Int?, _ movies:[Movie]?,_ error:Error?)->Void) -> Void func getPopularMovies(page:Int, completionHandler:@escaping(_ totalMovies:Int?, _ movies:[Movie]?,_ error:Error?)->Void) -> Void func searchMovie(withKeyword keyword:String, page:Int, completionHandler:@escaping(_ totalMovies:Int?, _ movies:[Movie]?,_ error:Error?)->Void) -> Void } class MoviesRepositoryMock: NSObject,MoviesRepositoryProtocol { var getTopRatedMoviesIsCalled:Bool = false var getUpcomingMoviesIsCalled:Bool = false var getNowPlayingMoviesIsCalled:Bool = false var getPopularMoviesIsCalled:Bool = false var searchMovieIsCalled:Bool = false func getTopRatedMovies(page: Int, completionHandler:@escaping (Int?, [Movie]? , Error? ) -> Void) { getTopRatedMoviesIsCalled = true completionHandler(nil,nil,nil) } func getUpcomingMovies(page: Int, completionHandler:@escaping (Int?, [Movie]?, Error?) -> Void) { getUpcomingMoviesIsCalled = true completionHandler(nil,nil,nil) } func getNowPlayingMovies(page: Int, completionHandler:@escaping (Int?, [Movie]?, Error?) -> Void) { getNowPlayingMoviesIsCalled = true completionHandler(nil,nil,nil) } func getPopularMovies(page: Int, completionHandler:@escaping (Int?, [Movie]?, Error?) -> Void) { getPopularMoviesIsCalled = true completionHandler(nil,nil,nil) } func searchMovie(withKeyword keyword: String, page: Int, completionHandler:@escaping(Int?, [Movie]?, Error?) -> Void) { searchMovieIsCalled = true completionHandler(nil,nil,nil) } } class MoviesRepository: NSObject,MoviesRepositoryProtocol { func getTopRatedMovies(page: Int, completionHandler:@escaping (Int?, [Movie]?, Error?) -> Void) { //https://api.themoviedb.org/3/movie/top_rated?api_key=<<api_key>>&language=en-US&page=1 let url : String = baseUrl + "/3/movie/top_rated" let parameters: [String: String] = [ "api_key":apiKey, "language":"en-US", "page":String(describing:page)] NetworkManager.get(url, parameters: parameters as [String : AnyObject], success: {( result: NSDictionary) -> Void in var total = 0 if let count = result.value(forKey: "total_results") as? Int{ total = count } var movieList = [Movie]() if let list = result.value(forKey: "results") as? [AnyObject]{ for item in list{ if let json = item as? Dictionary<String, Any>{ movieList.append(Movie(json:json )) } } } print ("Api Success : top rated movies are:\n \(movieList)") completionHandler(total,movieList,nil) }, failure: {( error: NSDictionary?) -> Void in print ("Api Failure : error is:\n \(String(describing: error))") completionHandler(nil,nil,error as? Error) }) } func getUpcomingMovies(page: Int, completionHandler:@escaping (Int?, [Movie]?, Error?) -> Void) { //https://api.themoviedb.org/3/movie/upcoming?api_key=<<api_key>>&language=en-US&page=1 let url : String = baseUrl + "/3/movie/upcoming" let parameters: [String: String] = [ "api_key":apiKey, "language":"en-US", "page":String(describing:page)] NetworkManager.get(url, parameters: parameters as [String : AnyObject], success: {( result: NSDictionary) -> Void in var total = 0 if let count = result.value(forKey: "total_results") as? Int{ total = count } var movieList = [Movie]() if let list = result.value(forKey: "results") as? [AnyObject]{ for item in list{ if let json = item as? Dictionary<String, Any>{ movieList.append(Movie(json:json )) } } } print ("Api Success : top rated movies are:\n \(movieList)") completionHandler(total,movieList,nil) }, failure: {( error: NSDictionary?) -> Void in print ("Api Failure : error is:\n \(String(describing: error))") completionHandler(nil,nil,error as? Error) }) } func getNowPlayingMovies(page: Int, completionHandler:@escaping (Int?, [Movie]?, Error?) -> Void) { //https://api.themoviedb.org/3/movie/now_playing?api_key=<<api_key>>&language=en-US&page=1 let url : String = baseUrl + "/3/movie/now_playing" let parameters: [String: String] = [ "api_key":apiKey, "language":"en-US", "page":String(describing:page)] NetworkManager.get(url, parameters: parameters as [String : AnyObject], success: {( result: NSDictionary) -> Void in var total = 0 if let count = result.value(forKey: "total_results") as? Int{ total = count } var movieList = [Movie]() if let list = result.value(forKey: "results") as? [AnyObject]{ for item in list{ if let json = item as? Dictionary<String, Any>{ movieList.append(Movie(json:json )) } } } print ("Api Success : top rated movies are:\n \(movieList)") completionHandler(total,movieList,nil) }, failure: {( error: NSDictionary?) -> Void in print ("Api Failure : error is:\n \(String(describing: error))") completionHandler(nil,nil,error as? Error) }) } func getPopularMovies(page: Int, completionHandler:@escaping (Int?, [Movie]?, Error?) -> Void) { //https://api.themoviedb.org/3/movie/popular?api_key=<<api_key>>&language=en-US&page=1 let url : String = baseUrl + "/3/movie/popular" let parameters: [String: String] = [ "api_key":apiKey, "language":"en-US", "page":String(describing:page)] NetworkManager.get(url, parameters: parameters as [String : AnyObject], success: {( result: NSDictionary) -> Void in var total = 0 if let count = result.value(forKey: "total_results") as? Int{ total = count } var movieList = [Movie]() if let list = result.value(forKey: "results") as? [AnyObject]{ for item in list{ if let json = item as? Dictionary<String, Any>{ movieList.append(Movie(json:json )) } } } print ("Api Success : top rated movies are:\n \(movieList)") completionHandler(total,movieList,nil) }, failure: {( error: NSDictionary?) -> Void in print ("Api Failure : error is:\n \(String(describing: error))") completionHandler(nil,nil,error as? Error) }) } func searchMovie(withKeyword keyword: String, page: Int, completionHandler: @escaping (Int?, [Movie]?, Error?) -> Void) { completionHandler(nil,nil,nil) } }
mit
8187a0b20748ea4619d0634d50d616ac
43.624434
155
0.461063
5.49415
false
false
false
false
i-schuetz/SwiftCharts
SwiftCharts/Layers/ChartGroupedBarsLayer.swift
1
15223
// // ChartGroupedBarsLayer.swift // Examples // // Created by ischuetz on 19/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public final class ChartPointsBarGroup<T: ChartBarModel> { public let constant: ChartAxisValue public let bars: [T] public init(constant: ChartAxisValue, bars: [T]) { self.constant = constant self.bars = bars } } open class ChartGroupedBarsLayer<T: ChartBarModel, U: ChartPointViewBar>: ChartCoordsSpaceLayer { fileprivate let groups: [ChartPointsBarGroup<T>] fileprivate let barWidth: CGFloat? fileprivate let barSpacing: CGFloat? fileprivate let groupSpacing: CGFloat? public let horizontal: Bool fileprivate let settings: ChartBarViewSettings open fileprivate(set) var groupViews: [(ChartPointsBarGroup<T>, [ChartPointViewBar])] = [] fileprivate let mode: ChartPointsViewsLayerMode fileprivate let viewGenerator: ChartBarsLayer<U>.ChartBarViewGenerator? convenience init(xAxis: ChartAxis, yAxis: ChartAxis, groups: [ChartPointsBarGroup<T>], horizontal: Bool = false, barSpacing: CGFloat?, groupSpacing: CGFloat?, settings: ChartBarViewSettings, mode: ChartPointsViewsLayerMode = .scaleAndTranslate, viewGenerator: ChartBarsLayer<U>.ChartBarViewGenerator? = nil) { self.init(xAxis: xAxis, yAxis: yAxis, groups: groups, horizontal: horizontal, barWidth: nil, barSpacing: barSpacing, groupSpacing: groupSpacing, settings: settings, mode: mode, viewGenerator: viewGenerator) } init(xAxis: ChartAxis, yAxis: ChartAxis, groups: [ChartPointsBarGroup<T>], horizontal: Bool = false, barWidth: CGFloat?, barSpacing: CGFloat?, groupSpacing: CGFloat?, settings: ChartBarViewSettings, mode: ChartPointsViewsLayerMode = .scaleAndTranslate, viewGenerator: ChartBarsLayer<U>.ChartBarViewGenerator? = nil) { self.groups = groups self.horizontal = horizontal self.barWidth = barWidth self.barSpacing = barSpacing self.groupSpacing = groupSpacing self.settings = settings self.mode = mode self.viewGenerator = viewGenerator super.init(xAxis: xAxis, yAxis: yAxis) } func barsGenerator(barWidth: CGFloat, chart: Chart) -> ChartBarsViewGenerator<T, U> { fatalError("override") } open override func chartInitialized(chart: Chart) { super.chartInitialized(chart: chart) if !settings.delayInit { initBars(chart) } } open func initBars(_ chart: Chart) { calculateDimensions(chart) {maxBarCountInGroup, barWidth in let barsGenerator = self.barsGenerator(barWidth: barWidth, chart: chart) for (groupIndex, group) in self.groups.enumerated() { var groupBars = [ChartPointViewBar]() for (barIndex, bar) in group.bars.enumerated() { let constantScreenLoc = self.calculateConstantScreenLocDir({self.modelLocToScreenLoc(y: $0)}, index: barIndex, group: group, barWidth: barWidth, maxBarCountInGroup: maxBarCountInGroup, horizontal: barsGenerator.horizontal) let barView = barsGenerator.generateView(bar, constantScreenLoc: constantScreenLoc, bgColor: bar.bgColor, settings: self.settings, model: bar, index: barIndex, groupIndex: groupIndex) self.configBarView(group, groupIndex: groupIndex, barIndex: barIndex, bar: bar, barView: barView) groupBars.append(barView) self.addSubview(chart, view: barView) } self.groupViews.append((group, groupBars)) } } } func calculateConstantScreenLoc(_ screenLocCalculator: (Double) -> CGFloat, index: Int, group: ChartPointsBarGroup<T>, barWidth: CGFloat, maxBarCountInGroup: CGFloat) -> CGFloat { let totalWidth = CGFloat(group.bars.count) * barWidth + ((barSpacing ?? 0) * (maxBarCountInGroup - 1)) let groupCenter = screenLocCalculator(group.constant.scalar) let origin = groupCenter - totalWidth / 2 let internalBarOriginScreenLoc = CGFloat(index) * (barWidth + (barSpacing ?? 0)) return origin + internalBarOriginScreenLoc + barWidth / 2 } func mooh(_ screenLocCalculator: (Double) -> CGFloat, index: Int, group: ChartPointsBarGroup<T>, barWidth: CGFloat, maxBarCountInGroup: CGFloat, horizontal: Bool) -> CGFloat { return 1 } func calculateConstantScreenLocDir(_ screenLocCalculator: (Double) -> CGFloat, index: Int, group: ChartPointsBarGroup<T>, barWidth: CGFloat, maxBarCountInGroup: CGFloat, horizontal: Bool) -> CGFloat { if horizontal { return calculateConstantScreenLoc({modelLocToScreenLoc(y: $0)}, index: index, group: group, barWidth: barWidth, maxBarCountInGroup: maxBarCountInGroup) } else { return calculateConstantScreenLoc({modelLocToScreenLoc(x: $0)}, index: index, group: group, barWidth: barWidth, maxBarCountInGroup: maxBarCountInGroup) } } fileprivate func calculateDimensions(_ chart: Chart, onCalculate: (_ maxBarCountInGroup: CGFloat, _ barWidth: CGFloat) -> Void) { let axis = horizontal ? yAxis : xAxis let groupAvailableLength = (axis.screenLength - (groupSpacing ?? 0) * CGFloat(groups.count)) / CGFloat(groups.count + 1) let maxBarCountInGroup = groups.reduce(CGFloat(0)) {maxCount, group in max(maxCount, CGFloat(group.bars.count)) } func calculateBarWidth() -> CGFloat { return (((groupAvailableLength - ((barSpacing ?? 0) * (maxBarCountInGroup - 1))) / CGFloat(maxBarCountInGroup))) } let barWidth = self.barWidth ?? calculateBarWidth() onCalculate(maxBarCountInGroup, barWidth) } func configBarView(_ group: ChartPointsBarGroup<T>, groupIndex: Int, barIndex: Int, bar: T, barView: U) { // barView.selectionViewUpdater = selectionViewUpdater } func addSubview(_ chart: Chart, view: UIView) { mode == .scaleAndTranslate ? chart.addSubview(view) : chart.addSubviewNoTransform(view) } open override func zoom(_ x: CGFloat, y: CGFloat, centerX: CGFloat, centerY: CGFloat) { super.zoom(x, y: y, centerX: centerX, centerY: centerY) updateForTransform() } open override func pan(_ deltaX: CGFloat, deltaY: CGFloat) { super.pan(deltaX, deltaY: deltaY) updateForTransform() } fileprivate func updatePanZoomTranslateMode() { guard let chart = chart else {return} calculateDimensions(chart) {maxBarCountInGroup, barWidth in let barsGenerator = self.barsGenerator(barWidth: barWidth, chart: chart) for (groupIndex, group) in self.groups.enumerated() { for (barIndex, bar) in group.bars.enumerated() { let constantScreenLoc = self.calculateConstantScreenLocDir({self.modelLocToScreenLoc(y: $0)}, index: barIndex, group: group, barWidth: barWidth, maxBarCountInGroup: maxBarCountInGroup, horizontal: barsGenerator.horizontal) if groupIndex < self.groupViews.count { let groupViews = self.groupViews[groupIndex].1 if barIndex < groupViews.count { let barView = groupViews[barIndex] let (p1, p2) = barsGenerator.viewPoints(bar, constantScreenLoc: constantScreenLoc) barView.updateFrame(p1, p2: p2) barView.setNeedsDisplay() } } } } } } func updateForTransform() { switch mode { case .scaleAndTranslate: break case .translate: updatePanZoomTranslateMode() case .custom: fatalError("Not supported") } } open override func modelLocToScreenLoc(x: Double) -> CGFloat { switch mode { case .scaleAndTranslate: return super.modelLocToScreenLoc(x: x) case .translate: return super.modelLocToContainerScreenLoc(x: x) case .custom: fatalError("Not supported") } } open override func modelLocToScreenLoc(y: Double) -> CGFloat { switch mode { case .scaleAndTranslate: return super.modelLocToScreenLoc(y: y) case .translate: return super.modelLocToContainerScreenLoc(y: y) case .custom: fatalError("Not supported") } } } public struct ChartTappedGroupBar { public let tappedBar: ChartTappedBar public let group: ChartPointsBarGroup<ChartBarModel> public let groupIndex: Int public let barIndex: Int // in group public let layer: ChartGroupedBarsLayer<ChartBarModel, ChartPointViewBar> } public typealias ChartGroupedPlainBarsLayer = ChartGroupedPlainBarsLayer_<Any> open class ChartGroupedPlainBarsLayer_<N>: ChartGroupedBarsLayer<ChartBarModel, ChartPointViewBar> { let tapHandler: ((ChartTappedGroupBar) -> Void)? public convenience init(xAxis: ChartAxis, yAxis: ChartAxis, groups: [ChartPointsBarGroup<ChartBarModel>], horizontal: Bool = false, barSpacing: CGFloat?, groupSpacing: CGFloat?, settings: ChartBarViewSettings, mode: ChartPointsViewsLayerMode = .scaleAndTranslate, tapHandler: ((ChartTappedGroupBar) -> Void)? = nil, viewGenerator: ChartBarsLayer<ChartPointViewBar>.ChartBarViewGenerator? = nil) { self.init(xAxis: xAxis, yAxis: yAxis, groups: groups, horizontal: horizontal, barWidth: nil, barSpacing: barSpacing, groupSpacing: groupSpacing, settings: settings, mode: mode, tapHandler: tapHandler, viewGenerator: viewGenerator) } public init(xAxis: ChartAxis, yAxis: ChartAxis, groups: [ChartPointsBarGroup<ChartBarModel>], horizontal: Bool, barWidth: CGFloat?, barSpacing: CGFloat?, groupSpacing: CGFloat?, settings: ChartBarViewSettings, mode: ChartPointsViewsLayerMode = .scaleAndTranslate, tapHandler: ((ChartTappedGroupBar) -> Void)? = nil, viewGenerator: ChartBarsLayer<ChartPointViewBar>.ChartBarViewGenerator? = nil) { self.tapHandler = tapHandler super.init(xAxis: xAxis, yAxis: yAxis, groups: groups, horizontal: horizontal, barWidth: barWidth, barSpacing: barSpacing, groupSpacing: groupSpacing, settings: settings, mode: mode, viewGenerator: viewGenerator) } override func barsGenerator(barWidth: CGFloat, chart: Chart) -> ChartBarsViewGenerator<ChartBarModel, ChartPointViewBar> { return ChartBarsViewGenerator(horizontal: self.horizontal, layer: self, barWidth: barWidth, viewGenerator: viewGenerator) } override func configBarView(_ group: ChartPointsBarGroup<ChartBarModel>, groupIndex: Int, barIndex: Int, bar: ChartBarModel, barView: ChartPointViewBar) { super.configBarView(group, groupIndex: groupIndex, barIndex: barIndex, bar: bar, barView: barView) barView.tapHandler = {[weak self] _ in guard let weakSelf = self else {return} let tappedBar = ChartTappedBar(model: bar, view: barView, layer: weakSelf) let tappedGroupBar = ChartTappedGroupBar(tappedBar: tappedBar, group: group, groupIndex: groupIndex, barIndex: barIndex, layer: weakSelf) weakSelf.tapHandler?(tappedGroupBar) } } } public struct ChartTappedGroupBarStacked { public let tappedBar: ChartTappedBarStacked public let group: ChartPointsBarGroup<ChartStackedBarModel> public let groupIndex: Int public let barIndex: Int // in group } public typealias ChartGroupedStackedBarsLayer = ChartGroupedStackedBarsLayer_<Any> open class ChartGroupedStackedBarsLayer_<N>: ChartGroupedBarsLayer<ChartStackedBarModel, ChartPointViewBarStacked> { fileprivate let stackFrameSelectionViewUpdater: ChartViewSelector? let tapHandler: ((ChartTappedGroupBarStacked) -> Void)? fileprivate let stackedViewGenerator: ChartStackedBarsLayer<ChartPointViewBarStacked>.ChartBarViewGenerator? public convenience init(xAxis: ChartAxis, yAxis: ChartAxis, groups: [ChartPointsBarGroup<ChartStackedBarModel>], horizontal: Bool = false, barSpacing: CGFloat?, groupSpacing: CGFloat?, settings: ChartBarViewSettings, mode: ChartPointsViewsLayerMode = .scaleAndTranslate, stackFrameSelectionViewUpdater: ChartViewSelector? = nil, tapHandler: ((ChartTappedGroupBarStacked) -> Void)? = nil, viewGenerator: ChartStackedBarsLayer<ChartPointViewBarStacked>.ChartBarViewGenerator? = nil) { self.init(xAxis: xAxis, yAxis: yAxis, groups: groups, horizontal: horizontal, barWidth: nil, barSpacing: barSpacing, groupSpacing: groupSpacing, settings: settings, mode: mode, stackFrameSelectionViewUpdater: stackFrameSelectionViewUpdater, tapHandler: tapHandler, viewGenerator: viewGenerator) } public init(xAxis: ChartAxis, yAxis: ChartAxis, groups: [ChartPointsBarGroup<ChartStackedBarModel>], horizontal: Bool, barWidth: CGFloat?, barSpacing: CGFloat?, groupSpacing: CGFloat?, settings: ChartBarViewSettings, mode: ChartPointsViewsLayerMode = .scaleAndTranslate, stackFrameSelectionViewUpdater: ChartViewSelector? = nil, tapHandler: ((ChartTappedGroupBarStacked) -> Void)? = nil, viewGenerator: ChartStackedBarsLayer<ChartPointViewBarStacked>.ChartBarViewGenerator? = nil) { self.stackFrameSelectionViewUpdater = stackFrameSelectionViewUpdater self.tapHandler = tapHandler self.stackedViewGenerator = viewGenerator super.init(xAxis: xAxis, yAxis: yAxis, groups: groups, horizontal: horizontal, barWidth: barWidth, barSpacing: barSpacing, groupSpacing: groupSpacing, settings: settings, mode: mode) } override func barsGenerator(barWidth: CGFloat, chart: Chart) -> ChartBarsViewGenerator<ChartStackedBarModel, ChartPointViewBarStacked> { return ChartStackedBarsViewGenerator(horizontal: horizontal, layer: self, barWidth: barWidth, viewGenerator: stackedViewGenerator) } override func configBarView(_ group: ChartPointsBarGroup<ChartStackedBarModel>, groupIndex: Int, barIndex: Int, bar: ChartStackedBarModel, barView: ChartPointViewBarStacked) { barView.stackedTapHandler = {[weak self, unowned barView] tappedStackedBar in guard let weakSelf = self else {return} let stackFrameData = tappedStackedBar.stackFrame.map{stackFrame in ChartTappedBarStackedFrame(stackedItemModel: bar.items[stackFrame.index], stackedItemView: stackFrame.view, stackedItemViewFrameRelativeToBarParent: stackFrame.viewFrameRelativeToBarSuperview, stackedItemIndex: stackFrame.index) } let tappedStacked = ChartTappedBarStacked(model: bar, barView: barView, stackFrameData: stackFrameData, layer: weakSelf) let tappedGroupBar = ChartTappedGroupBarStacked(tappedBar: tappedStacked, group: group, groupIndex: groupIndex, barIndex: barIndex) weakSelf.tapHandler?(tappedGroupBar) } barView.stackFrameSelectionViewUpdater = stackFrameSelectionViewUpdater } }
apache-2.0
48d7cd79f6e15435098fc7b3fcda86a2
54.155797
486
0.699599
4.910645
false
false
false
false
jhurray/SQLiteModel-Example-Project
tvOS+SQLiteModel/Pods/SQLite.swift/SQLite/Core/Blob.swift
28
1913
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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. // public struct Blob { public let bytes: [UInt8] public init(bytes: [UInt8]) { self.bytes = bytes } public init(bytes: UnsafePointer<Void>, length: Int) { self.init(bytes: [UInt8](UnsafeBufferPointer( start: UnsafePointer(bytes), count: length ))) } public func toHex() -> String { return bytes.map { ($0 < 16 ? "0" : "") + String($0, radix: 16, uppercase: false) }.joinWithSeparator("") } } extension Blob : CustomStringConvertible { public var description: String { return "x'\(toHex())'" } } extension Blob : Equatable { } public func ==(lhs: Blob, rhs: Blob) -> Bool { return lhs.bytes == rhs.bytes }
mit
5b6061d8dd74eeb273fc7633340ac70f
30.344262
80
0.687238
4.258352
false
false
false
false
wtrumler/FluentSwiftAssertions
FluentSwiftAssertions/ArraySliceExtension.swift
1
1544
// // ArraySliceExtension.swift // FluentSwiftAssertions // // Created by Wolfgang Trumler on 13.05.17. // Copyright © 2017 Wolfgang Trumler. All rights reserved. // import Foundation import XCTest extension ArraySlice where Element: Equatable { public var should : ArraySlice { return self } public func beEqualTo( _ expression2: @autoclosure () throws -> ArraySlice<Element>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, assertionFunction : @escaping (_ exp1: @autoclosure () throws -> ArraySlice<Element>, _ exp2: @autoclosure () throws -> ArraySlice<Element>, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertEqual) { assertionFunction(self, expression2, message, file, line) } public func notBeEqualTo( _ expression2: @autoclosure () throws -> ArraySlice<Element>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, assertionFunction : @escaping (_ exp1: @autoclosure () throws -> ArraySlice<Element>, _ exp2: @autoclosure () throws -> ArraySlice<Element>, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertNotEqual) { assertionFunction(self, expression2, message, file, line) } }
mit
c1f49019c5542b517d927d0dfed22d17
43.085714
272
0.582631
4.914013
false
false
false
false
BareFeetWare/BFWDrawView
BFWDrawView/Modules/Draw/Model/UIImage+Drawing.swift
1
1281
// // UIImage+Drawing.swift // BFWDrawView // // Created by Tom Brodhurst-Hill on 6/7/17. // Copyright © 2017 BareFeetWare. All rights reserved. // import Foundation public extension UIImage { class func image(styleKitName: String?, drawingName: String?, size: CGSize? = nil ) -> UIImage? { guard let drawingName = drawingName, !drawingName.isEmpty, let styleKitName = styleKitName, !styleKitName.isEmpty, let drawing = StyleKit(name: styleKitName).drawing(for: drawingName) else { return nil } return image(drawing: drawing, size: size) } class func image(drawing: Drawing?, size: CGSize? = nil, tintColor: UIColor? = nil ) -> UIImage? { guard let drawing = drawing, let size = size ?? drawing.drawnSize else { return nil } let frame = CGRect(origin: .zero, size: size) // TODO: Get image from drawing (for size), without need for DrawingView. let drawingView = DrawingView(frame: frame) drawingView.drawing = drawing drawingView.tintColor = tintColor return drawingView.image } }
mit
ccaf58423afee04d82361ecef82ac7bf
29.47619
81
0.571875
4.587814
false
false
false
false
biohazardlover/ByTrain
ByTrain/Entities/Passenger.swift
1
7025
/// 乘客 public struct Passenger: Equatable { /// 乘客信息中有一些值是从下拉列表里面选出来的,这个结构体就代表这其中的一个选项 public struct Option: Equatable { /// 选项的值 public var value: String? /// 选项显示的内容 public var content: String? public init() {} public init(value: String?, content: String?) { self.value = value self.content = content } } /// 学生信息 public struct StudentInfo: Equatable { /// 学校所在省份的代码 public var province_code: Option? /// 可选的省份 public var optional_province_code_list: [Option]? /// 学校名称 public var school_name: String? /// 学校代码 public var school_code: String? /// 院系 public var department: String? /// 班级 public var school_class: String? /// 学号 public var student_no: String? /// 学制,可选值为“1”~“9” public var school_system: Option? /// 可选的学制 public var optional_school_system_list: [Option]? /// 入学年份 public var enter_year: Option? /// 可选的入学年份 public var optional_enter_year_list: [Option]? /// 优惠卡号 public var preference_card_no: String? /// 优惠起始站的名称 public var preference_from_station_name: String? /// 优惠起始站的代码 public var preference_from_station_code: String? /// 优惠结束站的名称 public var preference_to_station_name: String? /// 优惠结束站的代码 public var preference_to_station_code: String? public init() {} } /// 一种顺序,从“1”开始计算 public var code: String? /// 不明,一般为“0” public var passenger_flag: String? /// 是否是用户自己,“Y”表示是,“N”表示不是 public var isUserSelf: String? /// 乘客的姓名 public var passenger_name: String? /// 之前的姓名 public var old_passenger_name: String? /// 乘客性别的代码,M代表男性,F代表女性 public var sex_code: String? /// 乘客的性别,可选值为“男”,“女” public var sex_name: String? /// 可选的性别列表 public var optional_sex_code_list: [Option]? /// 乘客被添加的日期,格式为yyyy-MM-dd HH:mm:ss public var born_date: String? /// 乘客国籍的代码,CN代表中国 public var country_code: String? /// 可选的国家列表 public var optional_country_code_list: [Option]? /// 乘客证件类型的代码,“1”代表二代身份证,“C”代表港澳通行证,“G"代表台湾通行证,“B”代表护照 public var passenger_id_type_code: String? /// 之前的证件类型的代码 public var old_passenger_id_type_code: String? /// 可选的证件类型列表 public var optional_passenger_id_type_code_list: [Option]? /// 乘客的证件类型,可选值为“二代身份证”,“港澳通行证”,“台湾通行证”,“护照” public var passenger_id_type_name: String? /// 乘客的证件号码 public var passenger_id_no: String? /// 之前的证件号码 public var old_passenger_id_no: String? /// 乘客类型的代码,1代表成人,2代表儿童,3代表学生,4代表残疾军人、伤残人民警察 public var passenger_type: String? /// 乘客的类型,可选值为“成人”,“儿童”,“学生”,“残疾军人、伤残人民警察” public var passenger_type_name: String? /// 可选的乘客类型列表 public var optional_passenger_type_list: [Option]? /// 乘客的手机号码 public var mobile_no: String? /// 乘客的固定电话 public var phone_no: String? /// 乘客的电子邮件 public var email: String? /// 乘客的地址 public var address: String? /// 乘客的邮编 public var postalcode: String? /// 乘客姓名的首字母合集,比如“李俊麟”为“LJL” public var first_letter: String? /// 已添加的乘客的总数 public var recordCount: String? /// 不明 public var total_times: String? /// 一种顺序,从“0”开始计算 public var index_id: String? /// 学生信息 public var studentInfo: StudentInfo? public init() {} } public func ==(lhs: Passenger.Option, rhs: Passenger.Option) -> Bool { return lhs.value == rhs.value && lhs.content == rhs.content } public func ==(lhs: Passenger.StudentInfo, rhs: Passenger.StudentInfo) -> Bool { return lhs.province_code == rhs.province_code && lhs.school_name == rhs.school_name && lhs.school_code == rhs.school_code && lhs.department == rhs.department && lhs.school_class == rhs.school_class && lhs.student_no == rhs.student_no && lhs.school_system == rhs.school_system && lhs.enter_year == rhs.enter_year && lhs.preference_card_no == rhs.preference_card_no && lhs.preference_from_station_name == rhs.preference_from_station_name && lhs.preference_from_station_code == rhs.preference_from_station_code && lhs.preference_to_station_name == rhs.preference_to_station_name && lhs.preference_to_station_code == rhs.preference_to_station_code } public func ==(lhs: Passenger, rhs: Passenger) -> Bool { return lhs.code == rhs.code && lhs.passenger_name == rhs.passenger_name && lhs.sex_code == rhs.sex_code && lhs.sex_name == rhs.sex_name && lhs.born_date == rhs.born_date && lhs.country_code == rhs.country_code && lhs.passenger_id_type_code == rhs.passenger_id_type_code && lhs.passenger_id_type_name == rhs.passenger_id_type_name && lhs.passenger_id_no == rhs.passenger_id_no && lhs.passenger_type == rhs.passenger_type && lhs.passenger_flag == rhs.passenger_flag && lhs.passenger_type_name == rhs.passenger_type_name && lhs.mobile_no == rhs.mobile_no && lhs.phone_no == rhs.phone_no && lhs.email == rhs.email && lhs.address == rhs.address && lhs.postalcode == rhs.postalcode && lhs.first_letter == rhs.first_letter && lhs.recordCount == rhs.recordCount && lhs.total_times == rhs.total_times && lhs.index_id == rhs.index_id && lhs.studentInfo == rhs.studentInfo }
mit
3d26ca57982c2977c7a9e4a25a7fa65c
26.576744
80
0.565019
3.329029
false
false
false
false
LeoMobileDeveloper/MDTable
MDTableExample/AvatarItemView.swift
1
3011
// // AvatarItemView.swift // MDTableExample // // Created by Leo on 2017/7/14. // Copyright © 2017年 Leo Huang. All rights reserved. // import UIKit class HightLightImageView: UIImageView{ lazy var highLightCoverView: UIView = { let view = UIView().added(to: self) view.backgroundColor = UIColor.black.withAlphaComponent(0.5) view.isHidden = true view.frame = self.bounds view.autoresizingMask = [.flexibleHeight,.flexibleWidth] return view }() override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class AvatarItemView: UIView, UIGestureRecognizerDelegate { open var avatarImageView: HightLightImageView! var highLightGesture: UILongPressGestureRecognizer! var tapGesture: UITapGestureRecognizer! var longPresssGesture: UILongPressGestureRecognizer! override init(frame: CGRect) { super.init(frame: frame) avatarImageView = HightLightImageView(frame: CGRect.zero).added(to: self) highLightGesture = UILongPressGestureRecognizer(target: self, action: #selector(AvatarItemView.handleHight(_:))) highLightGesture.delegate = self highLightGesture.minimumPressDuration = 0.1 self.addGestureRecognizer(highLightGesture) tapGesture = UITapGestureRecognizer(target: self, action: #selector(AvatarItemView.handleTap(_:))) tapGesture.delegate = self self.addGestureRecognizer(tapGesture) longPresssGesture = UILongPressGestureRecognizer(target: self, action: #selector(AvatarItemView.handleLongPress(_:))) longPresssGesture.minimumPressDuration = 1.0 longPresssGesture.delegate = self self.addGestureRecognizer(longPresssGesture) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { if otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self){ return false } if gestureRecognizer == longPresssGesture { return false } return true } func handleHight(_ sender: UILongPressGestureRecognizer){ switch sender.state { case .began,.changed: let location = sender.location(in: self) let touchInside = self.bounds.contains(location) avatarImageView.highLightCoverView.isHidden = !touchInside default: avatarImageView.highLightCoverView.isHidden = true } } func handleTap(_ sender: UITapGestureRecognizer){ print("Tap") } func handleLongPress(_ sender: UILongPressGestureRecognizer){ if sender.state == .began{ print("LongPress") } } }
mit
8272546602737242840c4c39b887279f
34.809524
157
0.678524
5.231304
false
false
false
false
nguyenantinhbk77/practice-swift
CoreLocation/Displaying Pins in MapView/Displaying Pins in MapView/ViewController.swift
2
1814
// // ViewController.swift // Displaying Pins in MapView // // Created by Domenico Solazzo on 18/05/15. // License MIT // import UIKit import CoreLocation import MapKit class ViewController: UIViewController, MKMapViewDelegate { var mapView: MKMapView! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) mapView = MKMapView() } /* We have a pin on the map; now zoom into it and make that pin the center of the map */ func setCenterOfMapToLocation(location: CLLocationCoordinate2D){ let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01) let region = MKCoordinateRegion(center: location, span: span) mapView.setRegion(region, animated: true) } func addPinToMapView(){ /* This is just a sample location */ let location = CLLocationCoordinate2D(latitude: 58.592737, longitude: 16.185898) /* Create the annotation using the location */ let annotation = MyAnnotation(coordinate: location, title: "My Title", subtitle: "My Sub Title") /* And eventually add it to the map */ mapView.addAnnotation(annotation) /* And now center the map around the point */ setCenterOfMapToLocation(location) } /* Set up the map and add it to our view */ override func viewDidLoad() { super.viewDidLoad() mapView.mapType = .Standard mapView.frame = view.frame mapView.delegate = self view.addSubview(mapView) } /* Add the pin to the map and center the map around the pin */ override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) addPinToMapView() } }
mit
71e4d89fb696663c2e4bc28aa48fa6fa
27.34375
78
0.625689
4.748691
false
false
false
false
mnin/on_ruby_ios
onruby/Material.swift
1
1057
// // Material.swift // onruby // // Created by Martin Wilhelmi on 25.09.14. // import Foundation class Material { let id: Int let user_id: Int? let name, url: String init(id: Int, user_id: Int?, name: String, url: String) { self.id = id self.user_id = user_id self.name = name self.url = url } func user() -> User? { return User.find(self.user_id!) } class func loadFromJsonArray(materialsFromJson: NSArray) -> [Material] { var materialArray = [Material]() var id: Int var user_id: Int? var name, url: String for dict in materialsFromJson { id = dict["id"] as Int name = dict["name"] as String url = dict["url"] as String user_id = (dict["user_id"] == nil || dict["user_id"] is NSNull) ? nil : (dict["user_id"]! as Int) materialArray.append(Material(id: id, user_id: user_id, name: name, url: url)) } return materialArray } }
gpl-3.0
1240b8d3dce140a2e631a992f0e67324
23.581395
109
0.529801
3.558923
false
false
false
false
ndagrawal/MovieFeed
MovieFeed/CurrentMovie.swift
1
835
// // CurrentMovie.swift // MovieFeed // // Created by Nilesh Agrawal on 9/17/15. // Copyright © 2015 Nilesh Agrawal. All rights reserved. // import UIKit class CurrentMovie: NSObject { var movieImageURL:String! var movieName:String! var movieRating:String! var movieTime:Int! var moviePercentage:Int! var movieCasts:String! var movieSummary:String! init(movieImageUrl:String ,movieName:String, movieRating:String ,movieTime:Int, moviePercentage:Int,movieCasts:String,movieSummary:String){ self.movieImageURL = movieImageUrl self.movieName = movieName self.movieRating = movieRating self.movieTime = movieTime self.moviePercentage = moviePercentage self.movieCasts = movieCasts self.movieSummary = movieSummary } }
mit
d37ba0dc8e513754ae99f1c851752d0b
24.272727
143
0.689448
4.190955
false
false
false
false
RemyDCF/tpg-offline
tpg offline watchOS Extension/Departures/DeparturesInterfaceController.swift
1
4888
// // DeparturesInterfaceController.swift // tpg offline watchOS Extension // // Created by Rémy Da Costa Faro on 08/11/2017. // Copyright © 2018 Rémy Da Costa Faro. All rights reserved. // import WatchKit import Foundation class DeparturesInterfaceController: WKInterfaceController, DeparturesDelegate { var departures: DeparturesGroup? = nil { didSet { loadingImage.setImage(nil) guard let a = self.departures else { if DeparturesManager.shared.status == .loading { loadingImage.setImageNamed("loading-") loadingImage.startAnimatingWithImages(in: NSRange(location: 0, length: 60), duration: 2, repeatCount: -1) } tableView.setNumberOfRows(0, withRowType: "linesRow") return } let departures = a.departures.filter({ $0.line.code == self.line }) tableView.setNumberOfRows(departures.count, withRowType: "departureCell") for (index, departure) in departures.enumerated() { guard let rowController = self.tableView.rowController(at: index) as? DepartureRowController else { continue } rowController.departure = departure } } } var line: String = "" @IBOutlet weak var tableView: WKInterfaceTable! @IBOutlet weak var loadingImage: WKInterfaceImage! override func awake(withContext context: Any?) { super.awake(withContext: context) DeparturesManager.shared.addDeparturesDelegate(delegate: self) guard let option = context as? [Any] else { print("Context is not in a valid format") return } guard let departures = option[0] as? DeparturesGroup else { print("Context is not in a valid format") return } guard let line = option[1] as? String else { print("Context is not in a valid format") return } self.line = line self.departures = departures self.setTitle(Text.line(line)) self.addMenuItem(with: WKMenuItemIcon.resume, title: Text.reload, action: #selector(self.refreshDepartures)) } @objc func refreshDepartures() { DeparturesManager.shared.departures = nil loadingImage.setImageNamed("loading-") loadingImage.startAnimatingWithImages(in: NSRange(location: 0, length: 60), duration: 2, repeatCount: -1) DeparturesManager.shared.refreshDepartures() } deinit { DeparturesManager.shared.removeDeparturesDelegate(delegate: self) } func departuresDidUpdate() { self.departures = DeparturesManager.shared.departures } override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) { guard let rowController = self.tableView.rowController(at: rowIndex) as? DepartureRowController else { return } if rowController.canBeSelected { if rowController.departure.leftTime == "0" { let action = WKAlertAction(title: Text.ok, style: .default, handler: {}) self.presentAlert(withTitle: Text.busIsComming, message: Text.cantSetATimer, preferredStyle: .alert, actions: [action]) } else { presentController(withName: "reminderInterface", context: rowController.departure) } } } } class DepartureRowController: NSObject { @IBOutlet var platformLabel: WKInterfaceLabel! @IBOutlet var destinationLabel: WKInterfaceLabel! @IBOutlet var leftTimeLabel: WKInterfaceLabel! var canBeSelected: Bool = true var departure: Departure! { didSet { self.destinationLabel.setText(departure.line.destination) switch departure.leftTime { case "&gt;1h": let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssz" let time = dateFormatter.date(from: departure.timestamp) if let time = time { self.leftTimeLabel.setText(DateFormatter.localizedString( from: time, dateStyle: DateFormatter.Style.none, timeStyle: DateFormatter.Style.short)) } else { self.leftTimeLabel.setText("?") self.canBeSelected = false } case "no more": self.leftTimeLabel.setText("X") self.canBeSelected = false default: let tilde = departure.reliability == .theoretical ? "~" : "" leftTimeLabel.setText("\(tilde)\(departure.leftTime.time)'") } if let platform = departure.platform { platformLabel.setText(Text.platform(platform)) platformLabel.setHidden(false) } else { platformLabel.setHidden(true) } } } }
mit
ee5fcb537295a726b0e2589359fb8f44
33.160839
80
0.623132
4.84623
false
false
false
false
artursDerkintis/Starfly
Starfly/Models.swift
1
512
// // Models.swift // Starfly // // Created by Arturs Derkintis on 3/16/16. // Copyright © 2016 Starfly. All rights reserved. // import Foundation public struct Item{ var url : String var title : String var favicon : UIImage var screenshot : UIImage? init(url : String, title : String, favicon : UIImage, screenshot : UIImage? = nil){ self.url = url self.title = title self.favicon = favicon self.screenshot = screenshot } }
mit
26d147d5bcaf8642500c29a580facf8e
21.217391
87
0.596869
4.023622
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Models/PXPaymentCongratsTracking.swift
1
1189
import Foundation @objcMembers public class PXPaymentCongratsTracking: NSObject { let campaingId: String? let currencyId: String? let paymentStatusDetail: String let paymentId: Int64 let paymentMethodId: String? let paymentMethodType: String? let totalAmount: NSDecimalNumber let trackListener: PXTrackerListener? let flowName: String? let flowDetails: [String: Any]? let sessionId: String? public init(campaingId: String?, currencyId: String?, paymentStatusDetail: String, totalAmount: NSDecimalNumber, paymentId: Int64, paymentMethodId: String?, paymentMethodType: String?, trackListener: PXTrackerListener, flowName: String?, flowDetails: [String: Any]?, sessionId: String?) { self.campaingId = campaingId self.currencyId = currencyId self.paymentStatusDetail = paymentStatusDetail self.totalAmount = totalAmount self.paymentId = paymentId self.paymentMethodType = paymentMethodType self.paymentMethodId = paymentMethodId self.trackListener = trackListener self.flowName = flowName self.flowDetails = flowDetails self.sessionId = sessionId } }
mit
79bb81491218f5a0e9a45307f6b4d871
38.633333
292
0.724979
4.853061
false
false
false
false
iscriptology/swamp
Swamp/Messages/SwampMessages.swift
1
3159
// // SwampMessages.swift // Defines all swamp messages, and provide basic factory function for each one // // Created by Yossi Abraham on 18/08/2016. // Copyright © 2016 Yossi Abraham. All rights reserved. // enum SwampMessages: Int { // MARK: Basic profile messages case hello = 1 case welcome = 2 case abort = 3 case goodbye = 6 case error = 8 case publish = 16 case published = 17 case subscribe = 32 case subscribed = 33 case unsubscribe = 34 case unsubscribed = 35 case event = 36 case call = 48 case result = 50 case register = 64 case registered = 65 case unregister = 66 case unregistered = 67 case invocation = 68 case yield = 70 // MARK: Advance profile messages case challenge = 4 case authenticate = 5 /// payload consists of all data related to a message, WIHTHOUT the first one - the message identifier typealias WampMessageFactory = (_ payload: [Any]) -> SwampMessage // Split into 2 dictionaries because Swift compiler thinks a single one is too complex // Perhaps find a better solution in the future fileprivate static let mapping1: [SwampMessages: WampMessageFactory] = [ SwampMessages.error: ErrorSwampMessage.init, // Session SwampMessages.hello: HelloSwampMessage.init, SwampMessages.welcome: WelcomeSwampMessage.init, SwampMessages.abort: AbortSwampMessage.init, SwampMessages.goodbye: GoodbyeSwampMessage.init, // Auth SwampMessages.challenge: ChallengeSwampMessage.init, SwampMessages.authenticate: AuthenticateSwampMessage.init ] fileprivate static let mapping2: [SwampMessages: WampMessageFactory] = [ // RPC SwampMessages.call: CallSwampMessage.init, SwampMessages.result: ResultSwampMessage.init, SwampMessages.register: RegisterSwampMessage.init, SwampMessages.registered: RegisteredSwampMessage.init, SwampMessages.invocation: InvocationSwampMessage.init, SwampMessages.yield: YieldSwampMessage.init, SwampMessages.unregister: UnregisterSwampMessage.init, SwampMessages.unregistered: UnregisteredSwampMessage.init, // PubSub SwampMessages.publish: PublishSwampMessage.init, SwampMessages.published: PublishedSwampMessage.init, SwampMessages.event: EventSwampMessage.init, SwampMessages.subscribe: SubscribeSwampMessage.init, SwampMessages.subscribed: SubscribedSwampMessage.init, SwampMessages.unsubscribe: UnsubscribeSwampMessage.init, SwampMessages.unsubscribed: UnsubscribedSwampMessage.init ] static func createMessage(_ payload: [Any]) -> SwampMessage? { if let messageType = SwampMessages(rawValue: payload[0] as! Int) { if let messageFactory = mapping1[messageType] { return messageFactory(Array(payload[1..<payload.count])) } if let messageFactory = mapping2[messageType] { return messageFactory(Array(payload[1..<payload.count])) } } return nil } }
mit
7eaf635ca90afa6eb49431fa0c0eec3c
32.595745
106
0.68556
4.650957
false
false
false
false
cardstream/iOS-SDK
cardstream-ios-sdk/CryptoSwift-0.7.2/Sources/CryptoSwift/Blowfish.swift
5
23965
// // Blowfish.swift // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // https://en.wikipedia.org/wiki/Blowfish_(cipher) // Based on Paul Kocher implementation // public final class Blowfish { public enum Error: Swift.Error { /// Data padding is required case dataPaddingRequired /// Invalid key or IV case invalidKeyOrInitializationVector /// Invalid IV case invalidInitializationVector } public static let blockSize: Int = 8 // 64 bit fileprivate let iv: Array<UInt8> fileprivate let blockMode: BlockMode fileprivate let padding: Padding fileprivate lazy var decryptWorker: BlockModeWorker = { switch self.blockMode { case .CFB, .OFB, .CTR: return self.blockMode.worker(self.iv, cipherOperation: self.encrypt) default: return self.blockMode.worker(self.iv, cipherOperation: self.decrypt) } }() fileprivate lazy var encryptWorker: BlockModeWorker = { self.blockMode.worker(self.iv, cipherOperation: self.encrypt) }() private let N = 16 // rounds private var P: Array<UInt32> private var S: Array<Array<UInt32>> private let origP: Array<UInt32> = [ 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b, ] private let origS: Array<Array<UInt32>> = [ [ 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, ], [ 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, ], [ 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0, ], [ 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6, ], ] public init(key: Array<UInt8>, iv: Array<UInt8>? = nil, blockMode: BlockMode = .CBC, padding: Padding) throws { precondition(key.count >= 8 && key.count <= 56) self.blockMode = blockMode self.padding = padding S = origS P = origP if let iv = iv, !iv.isEmpty { self.iv = iv } else { self.iv = Array<UInt8>(repeating: 0, count: Blowfish.blockSize) } if blockMode.options.contains(.initializationVectorRequired) && self.iv.count != Blowfish.blockSize { assert(false, "Block size and Initialization Vector must be the same length!") throw Error.invalidInitializationVector } expandKey(key: key) } private func reset() { S = origS P = origP // todo expand key } private func expandKey(key: Array<UInt8>) { var j = 0 for i in 0..<(N + 2) { var data: UInt32 = 0x0 for _ in 0..<4 { data = (data << 8) | UInt32(key[j]) j += 1 if j >= key.count { j = 0 } } P[i] ^= data } var datal: UInt32 = 0 var datar: UInt32 = 0 for i in stride(from: 0, to: N + 2, by: 2) { encryptBlowfishBlock(l: &datal, r: &datar) P[i] = datal P[i + 1] = datar } for i in 0..<4 { for j in stride(from: 0, to: 256, by: 2) { encryptBlowfishBlock(l: &datal, r: &datar) S[i][j] = datal S[i][j + 1] = datar } } } fileprivate func encrypt(block: Array<UInt8>) -> Array<UInt8>? { var result = Array<UInt8>() var l = UInt32(bytes: block[0..<4]) var r = UInt32(bytes: block[4..<8]) encryptBlowfishBlock(l: &l, r: &r) // because everything is too complex to be solved in reasonable time o_O result += [ UInt8((l >> 24) & 0xff), UInt8((l >> 16) & 0xff), ] result += [ UInt8((l >> 8) & 0xff), UInt8((l >> 0) & 0xff), ] result += [ UInt8((r >> 24) & 0xff), UInt8((r >> 16) & 0xff), ] result += [ UInt8((r >> 8) & 0xff), UInt8((r >> 0) & 0xff), ] return result } fileprivate func decrypt(block: Array<UInt8>) -> Array<UInt8>? { var result = Array<UInt8>() var l = UInt32(bytes: block[0..<4]) var r = UInt32(bytes: block[4..<8]) decryptBlowfishBlock(l: &l, r: &r) // because everything is too complex to be solved in reasonable time o_O result += [ UInt8((l >> 24) & 0xff), UInt8((l >> 16) & 0xff), ] result += [ UInt8((l >> 8) & 0xff), UInt8((l >> 0) & 0xff), ] result += [ UInt8((r >> 24) & 0xff), UInt8((r >> 16) & 0xff), ] result += [ UInt8((r >> 8) & 0xff), UInt8((r >> 0) & 0xff), ] return result } /// Encrypts the 8-byte padded buffer /// /// - Parameters: /// - l: left half /// - r: right half fileprivate func encryptBlowfishBlock(l: inout UInt32, r: inout UInt32) { var Xl = l var Xr = r for i in 0..<N { Xl = Xl ^ P[i] Xr = F(x: Xl) ^ Xr (Xl, Xr) = (Xr, Xl) } (Xl, Xr) = (Xr, Xl) Xr = Xr ^ P[self.N] Xl = Xl ^ P[self.N + 1] l = Xl r = Xr } /// Decrypts the 8-byte padded buffer /// /// - Parameters: /// - l: left half /// - r: right half fileprivate func decryptBlowfishBlock(l: inout UInt32, r: inout UInt32) { var Xl = l var Xr = r for i in (2...N + 1).reversed() { Xl = Xl ^ P[i] Xr = F(x: Xl) ^ Xr (Xl, Xr) = (Xr, Xl) } (Xl, Xr) = (Xr, Xl) Xr = Xr ^ P[1] Xl = Xl ^ P[0] l = Xl r = Xr } private func F(x: UInt32) -> UInt32 { let f1 = S[0][Int(x >> 24) & 0xff] let f2 = S[1][Int(x >> 16) & 0xff] let f3 = S[2][Int(x >> 8) & 0xff] let f4 = S[3][Int(x & 0xff)] return ((f1 &+ f2) ^ f3) &+ f4 } } extension Blowfish: Cipher { /// Encrypt the 8-byte padded buffer, block by block. Note that for amounts of data larger than a block, it is not safe to just call encrypt() on successive blocks. /// /// - Parameter bytes: Plaintext data /// - Returns: Encrypted data public func encrypt<C: Collection>(_ bytes: C) throws -> Array<UInt8> where C.Element == UInt8, C.IndexDistance == Int, C.Index == Int { let bytes = padding.add(to: Array(bytes), blockSize: Blowfish.blockSize) // FIXME: Array(bytes) copies var out = Array<UInt8>() out.reserveCapacity(bytes.count) for chunk in bytes.batched(by: Blowfish.blockSize) { out += encryptWorker.encrypt(chunk) } if blockMode.options.contains(.paddingRequired) && (out.count % Blowfish.blockSize != 0) { throw Error.dataPaddingRequired } return out } /// Decrypt the 8-byte padded buffer /// /// - Parameter bytes: Ciphertext data /// - Returns: Plaintext data public func decrypt<C: Collection>(_ bytes: C) throws -> Array<UInt8> where C.Element == UInt8, C.IndexDistance == Int, C.Index == Int { if blockMode.options.contains(.paddingRequired) && (bytes.count % Blowfish.blockSize != 0) { throw Error.dataPaddingRequired } var out = Array<UInt8>() out.reserveCapacity(bytes.count) for chunk in Array(bytes).batched(by: Blowfish.blockSize) { out += decryptWorker.decrypt(chunk) // FIXME: copying here is innefective } out = padding.remove(from: out, blockSize: Blowfish.blockSize) return out } }
gpl-3.0
d8e45d7c83d39a995b6c05a4405a2d0f
42.729927
217
0.620931
2.375496
false
false
false
false
jokechat/swift3-novel
swift_novels/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallScaleMultiple.swift
8
2018
// // NVActivityIndicatorAnimationBallScaleMultiple.swift // NVActivityIndicatorViewDemo // // Created by Nguyen Vinh on 7/24/15. // Copyright (c) 2015 Nguyen Vinh. All rights reserved. // import UIKit class NVActivityIndicatorAnimationBallScaleMultiple: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let duration: CFTimeInterval = 1 let beginTime = CACurrentMediaTime() let beginTimes = [0, 0.2, 0.4] // Scale animation let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.duration = duration scaleAnimation.fromValue = 0 scaleAnimation.toValue = 1 // Opacity animation let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.duration = duration opacityAnimation.keyTimes = [0, 0.05, 1] opacityAnimation.values = [0, 1, 0] // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimation] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw balls for i in 0 ..< 3 { let circle = NVActivityIndicatorShape.circle.layerWith(size: size, color: color) let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height) animation.beginTime = beginTime + beginTimes[i] circle.frame = frame circle.opacity = 0 circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } }
apache-2.0
84241c8ff5b2bfc4c1bdac86fed22602
35.035714
92
0.608028
5.439353
false
false
false
false
EdoardoB/MovingHelper
MovingHelper/ModelControllers/TaskSaver.swift
21
1516
// // TaskSaver.swift // MovingHelper // // Created by Ellen Shapiro on 6/15/15. // Copyright (c) 2015 Razeware. All rights reserved. // import Foundation /* Struct to save tasks to JSON. */ public struct TaskSaver { /* Writes a file to the given file name in the documents directory containing JSON storing the given tasks. :param: The tasks to write out. :param: The file name to use when writing out the file. */ static func writeTasksToFile(tasks: [Task], fileName: FileName) { let dictionaries = map(tasks) { task in return task.asJson() } var error: NSError? let fullFilePath = fileName.jsonFileName().pathInDocumentsDirectory() if let jsonData = NSJSONSerialization.dataWithJSONObject(dictionaries, options: .PrettyPrinted, error: &error) { jsonData.writeToFile(fullFilePath, atomically: true) } if let foundError = error { NSLog("Error writing tasks to file: \(foundError.localizedDescription)") } } public static func nukeTaskFile(fileName: FileName) { let fullFilePath = fileName.jsonFileName().pathInDocumentsDirectory() var error: NSError? NSFileManager.defaultManager() .removeItemAtPath(fullFilePath, error: &error) if let foundError = error { if foundError.code != NSFileNoSuchFileError { NSLog("Error deleting file: \(foundError.localizedDescription)") } //Otherwise the file cannot be deleted because it doesn't exist yet. } } }
mit
0252cc753d8a495ec08983ec7057ccf0
26.581818
78
0.682718
4.445748
false
false
false
false
tripleCC/GanHuoCode
GanHuoShareExtension/TPCShareViewController.swift
1
10815
// // TPCShareViewController.swift // 干货 // // Created by tripleCC on 16/4/11. // Copyright © 2016年 tripleCC. All rights reserved. // import UIKit import Social import Alamofire import MobileCoreServices public class TPCShareViewController: UIViewController { var URLString: String? var items = [TPCShareItem]() var actionBeforeDisapear: ((vc: TPCShareViewController) -> Void)? var categories: [String] { get { if let categories = TPCStorageUtil.objectForKey(TPCAllCategoriesKey, suiteName: TPCAppGroupKey) as? [String] { return categories } else { return ["iOS", "Android", "App", "瞎推荐", "前端", "福利", "休息视频", "拓展资源"].filter{ !TPCFilterCategories.contains($0) } } } } @IBOutlet weak var containerView: UIView! @IBOutlet weak var refreshView: TPCRefreshView! { didSet { refreshView.transform = CGAffineTransformMakeScale(0.01, 0.01) } } @IBOutlet weak var titleView: TPCApplicationTitleView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var pickView: TPCShareItemTypePickView! { didSet { // 这里到时候要从userdefault里面取 pickView.typesTitle = categories } } @IBOutlet weak var postButton: UIButton! @IBOutlet weak var cancelButton: UIButton! @IBAction func cancel(sender: AnyObject) { if postButton.titleForState(.Normal) == "发布" { hideSelf({ let error = NSError(domain: "", code: 0, userInfo: nil) self.extensionContext?.cancelRequestWithError(error) }) } else { hidePickView() } } @IBAction func post(sender: AnyObject) { if postButton.titleForState(.Normal) == "发布" { postGanHuo() } else { if let item = items.last { item.content = pickView.selectedTitle tableView.reloadData() } hidePickView() } } override public func viewDidLoad() { initializeItems() fetchURLString() containerView.transform = CGAffineTransformMakeTranslation(0, UIScreen.mainScreen().bounds.height) } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) pickView.transform = CGAffineTransformMakeTranslation(0, pickView.frame.height) } override public func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) doAnimateAction({ self.containerView.transform = CGAffineTransformIdentity }) } deinit { print("释放了") } } extension TPCShareViewController { private func fetchURLString() { if let item = extensionContext?.inputItems.first { let itemp = item.attachments.flatMap{ $0.first } if let itemp = itemp as? NSItemProvider { if itemp.hasItemConformingToTypeIdentifier(String(kUTTypePropertyList)) { itemp.loadItemForTypeIdentifier(String(kUTTypePropertyList), options: nil, completionHandler: { (jsData, error) in if let jsDict = jsData as? NSDictionary { if let jsPreprocessingResults = jsDict[NSExtensionJavaScriptPreprocessingResultsKey] as? NSDictionary { if let title = jsPreprocessingResults["title"] as? String { self.items[1].content = title } if let URLString = jsPreprocessingResults["URL"] as? String { self.URLString = URLString if let URLItem = self.items.first { URLItem.content = self.URLString self.tableView.reloadData() } } } } }) } } } } private func initializeItems() { items.removeAll() let URLItem = TPCShareItem(content: URLString, placeholder: "输入/粘贴分享链接", contentImage: UIImage(named: "se_link")!) let descItem = TPCShareItem(placeholder: "输入分享描述", contentImage: UIImage(named: "se_detail")!) let publisherItem = TPCShareItem(content: getPublsiher(), placeholder: "输入发布人昵称", contentImage: UIImage(named: "se_publisher")!) let typeItem = TPCShareItem(content: categories.first, contentImage: UIImage(named: "se_type")!, type: .Display, clickAction: { [unowned self] content in self.showPickView() }) items.appendContentsOf([URLItem, descItem, publisherItem, typeItem]) } private func startUpload() { refreshView.removeAnimation() refreshView.addAnimation() UIView.animateWithDuration(0.5) { self.refreshView.transform = CGAffineTransformIdentity self.titleView.transform = CGAffineTransformMakeScale(0.01, 0.01) self.titleView.alpha = 0 self.refreshView.alpha = 1 } } private func stopUpload() { UIView.animateWithDuration(0.5) { self.titleView.transform = CGAffineTransformIdentity self.refreshView.transform = CGAffineTransformMakeScale(0.01, 0.01) self.titleView.alpha = 1 self.refreshView.alpha = 0 } } private func postGanHuo() { postButton.userInteractionEnabled = false let keys = ["url", "desc", "who", "type", "debug"] var parameters = [String : AnyObject]() for (idx, key) in keys.enumerate() { if idx < items.count { parameters[key] = items[idx].content } } parameters["debug"] = "false" savePublisher(parameters["who"] as? String ?? "") print(parameters) startUpload() Alamofire.request(.POST, TPCTechnicalType.Add2Gank.path(), parameters: parameters) .response { (request, response, data, error) in self.stopUpload() self.postButton.userInteractionEnabled = true print(data.flatMap{try? NSJSONSerialization.JSONObjectWithData($0, options: .AllowFragments)}) var message: String? var title: String? if let data = data { do { let result = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) if let error = result["error"] as? Bool { title = error ? "上传失败 = =|" : "上传成功!" } message = result["msg"] as? String } catch {} } let ac = UIAlertController(title: title, message: message, preferredStyle: .Alert) self.presentViewController(ac, animated: true, completion: { dispatchSeconds(1) { ac.dismissViewControllerAnimated(true, completion: { finished in if title == "上传成功!" { self.hideSelf { self.extensionContext?.completeRequestReturningItems(nil, completionHandler: nil) } } }) } }) } } private func savePublisher(publisher: String) { let userDefaults = NSUserDefaults(suiteName: TPCAppGroupKey) userDefaults?.setObject(publisher, forKey: "who") } private func getPublsiher() -> String { let userDefaults = NSUserDefaults(suiteName: TPCAppGroupKey) return userDefaults?.objectForKey("who") as? String ?? "" } private func hideSelf(completion: (() -> Void)) { doAnimateAction({ self.containerView.transform = CGAffineTransformMakeTranslation(0, -self.containerView.frame.maxY) self.view.alpha = 0 }, completion: { finished in completion() self.dismissViewControllerAnimated(false, completion: nil) self.actionBeforeDisapear?(vc: self) }) } private func showPickView() { doAnimateAction({ self.pickView.transform = CGAffineTransformIdentity }, completion: { self.postButton.setTitle("确定", forState: .Normal) }) } private func hidePickView() { doAnimateAction({ self.pickView.transform = CGAffineTransformMakeTranslation(0, self.pickView.frame.height) }, completion: { self.postButton.setTitle("发布", forState: .Normal) }) } private func doAnimateAction(action: (() -> Void), completion:(() -> Void)? = nil) { UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 10, initialSpringVelocity: 1.0, options: .CurveEaseInOut, animations: { action() }, completion: { finished in completion?() }) } } extension TPCShareViewController: UITableViewDelegate { public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let item = items[indexPath.row] item.clickAction?(item.content) let cell = tableView.cellForRowAtIndexPath(indexPath) as! TPCShareViewCell cell.beEditing() } } extension TPCShareViewController: UITableViewDataSource { public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("TPCShareViewCell", forIndexPath: indexPath) as! TPCShareViewCell cell.item = items[indexPath.row] cell.editCallBack = { [unowned self] content in self.items[indexPath.row].content = content } return cell } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 50 } }
mit
cad53f5d9635ccb3173b564081cbe48e
38.665428
161
0.566542
5.372608
false
false
false
false
exoplatform/exo-ios
eXo/Sources/Controllers/OnboardingVC/OnboardingViewController.swift
1
8730
// // OnboardingViewController.swift // eXo // // Created by Wajih Benabdessalem on 5/7/2021. // Copyright © 2021 eXo. All rights reserved. // import UIKit final class OnboardingViewController: UIViewController { // MARK: - Outlets . @IBOutlet weak var onboardngCollectionView: UICollectionView! @IBOutlet weak var slideNumberLabel: UILabel! @IBOutlet weak var scanButton: UIButton! @IBOutlet weak var addServerButton: UIButton! @IBOutlet weak var slideTitleLabel: UILabel! @IBOutlet weak var pageControl: UIPageControl! // MARK: - Variables . var onboardingList:[OnboardingItem] = [] var onboardingEnList:[OnboardingItem] = [] var onboardingFrList:[OnboardingItem] = [] var qrCodeServer : Server? var currentPage:Int = 0 var nextScroll:CGFloat = 0 var timer:Timer! override func viewDidLoad() { super.viewDidLoad() initView() } override func viewWillAppear(_ animated: Bool) { navigationController?.navigationBar.isHidden = true AppUtility.lockOrientation(.portrait) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) AppUtility.lockOrientation(.all) if timer != nil { timer.invalidate() timer = nil } } func initView() { DispatchQueue.global().async { CheckStoreUpdate.shared.checkAppStore(callback: { (isNew, appStoreVersion) in if isNew { self.showAlertUpdateVersion(title:"OnBoarding.Title.UpdateVersion".localized,msg: "OnBoarding.Message.UpdateVersion".localized) } }) } onboardingFrList = [ OnboardingItem(title: "OnBoarding.Title.ShowQRCode".localized, image: "slide1_gif-FR"), OnboardingItem(title: "OnBoarding.Title.ScanQRsettings".localized, image: "slide2_gif-FR"), OnboardingItem(title: "OnBoarding.Title.EnterPassword".localized, image: "slide3_gif-FR") ] onboardingEnList = [ OnboardingItem(title: "OnBoarding.Title.ShowQRCode".localized, image: "slide1_gif-EN"), OnboardingItem(title: "OnBoarding.Title.ScanQRsettings".localized, image: "slide2_gif-EN"), OnboardingItem(title: "OnBoarding.Title.EnterPassword".localized, image: "slide3_gif-EN") ] if let lang = Locale.current.languageCode { onboardingList = lang == "en" ? onboardingEnList : onboardingFrList } scanButton.setTitle("OnBoarding.Title.ScanCode".localized, for: .normal) addServerButton.setTitle("OnBoarding.Title.EnterUrleXo".localized, for: .normal) scanButton.addCornerRadiusWith(radius: 5) onboardngCollectionView.delegate = self onboardngCollectionView.dataSource = self onboardngCollectionView.register(OnboardingCell.nib(), forCellWithReuseIdentifier: OnboardingCell.cellId) pageControl.numberOfPages = onboardingList.count slideTitleLabel.text = onboardingList[0].title addObserverWith(selector: #selector(rootToHome(notification:)), name: .rootFromScanURL) addObserverWith(selector: #selector(openServer(notification:)), name: .addDomainKey) startTimer() } @objc func openServer(notification:Notification){ guard let addedServer = notification.userInfo?["addedServer"] as? Server else { return } // Open the selected server in the WebView let sb = UIStoryboard(name: "Main", bundle: nil) let homepageVC = sb.instantiateViewController(withIdentifier: "HomePageViewController") as? HomePageViewController if let homepageVC = homepageVC { homepageVC.serverURL = addedServer.serverURL ServerManager.sharedInstance.addEditServer(addedServer) self.navigationController?.pushViewController(homepageVC, animated: true) } } @objc func rootToHome(notification:Notification){ guard let rootURL = notification.userInfo?["rootURL"] as? String else { return } // check Internet connection if isInternetConnected(inWeb:false) { Tool.verificationServerURL(rootURL, delegate: self, handleSuccess: { (serverURL) -> Void in self.qrCodeServer = Server(serverURL: serverURL) OperationQueue.main.addOperation({ () -> Void in ServerManager.sharedInstance.addEditServer(self.qrCodeServer!) self.qrCodeServer?.lastConnection = Date().timeIntervalSince1970 let sb = UIStoryboard(name: "Main", bundle: nil) let homepageVC = sb.instantiateViewController(withIdentifier: "HomePageViewController") as? HomePageViewController if let homepageVC = homepageVC { homepageVC.serverURL = rootURL + "&source=qrcode" self.navigationController?.pushViewController(homepageVC, animated: true) } }) }) } } @IBAction func addServerTapped(_ sender: Any) { let addDomainVC = AddDomainViewController() addDomainVC.modalPresentationStyle = .overFullScreen self.present(addDomainVC, animated: true) } @IBAction func scanQRTapped(_ sender: Any) { setRootToScan() } func setRootToScan(){ let signInToeXo = QRCodeScannerViewController(nibName: "QRCodeScannerViewController", bundle: nil) signInToeXo.modalPresentationStyle = .overFullScreen present(signInToeXo, animated: false, completion: nil) } /** Scroll to Next Cell */ @objc func scrollToNextCell(){ //get Collection View Instance //get cell size let cellSize = CGSize(width: self.view.frame.width, height: self.view.frame.height) //get current content Offset of the Collection view let contentOffset = onboardngCollectionView.contentOffset //scroll to next cell nextScroll = contentOffset.x + cellSize.width let count = nextScroll/cellSize.width if nextScroll == cellSize.width*3 { nextScroll = 0 setSlideStatus(count:0) } onboardngCollectionView.scrollRectToVisible(CGRect(x: nextScroll, y: contentOffset.y, width: cellSize.width, height: cellSize.height), animated: true) setSlideStatus(count:Int(count)) } /** Invokes Timer to start Automatic Animation with repeat enabled */ func startTimer() { timer = Timer.scheduledTimer(timeInterval: 7.0, target: self, selector: #selector(scrollToNextCell), userInfo: nil, repeats: true) } func setSlideStatus(count:Int) { switch count { case 0: slideTitleLabel.text = onboardingList[count].title slideNumberLabel.text = "\(count + 1)" pageControl.currentPage = count case 1: slideTitleLabel.text = onboardingList[count].title slideNumberLabel.text = "\(count + 1)" pageControl.currentPage = count case 2: slideTitleLabel.text = onboardingList[count].title slideNumberLabel.text = "\(count + 1)" pageControl.currentPage = count default: print(count) } } } extension OnboardingViewController:UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return onboardingList.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: OnboardingCell.cellId, for: indexPath) as! OnboardingCell cell.setDataWith(slide: onboardingList[indexPath.row]) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let height = collectionView.frame.size.height let width = collectionView.frame.size.width return CGSize(width: width, height: height) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let width = scrollView.frame.width currentPage = Int(scrollView.contentOffset.x / width) slideNumberLabel.text = "\(currentPage + 1)" pageControl.currentPage = currentPage slideTitleLabel.text = onboardingList[currentPage].title } }
lgpl-3.0
e9e0f27f5bbe1cdb8e84aa0553682bbc
40.966346
160
0.659755
4.993707
false
false
false
false
daniel-barros/TV-Calendar
TraktKit/Common/HiddenItem.swift
1
899
// // HiddenItem.swift // TraktKit // // Created by Maximilian Litteral on 9/3/16. // Copyright © 2016 Maximilian Litteral. All rights reserved. // import Foundation public struct HiddenItem: TraktProtocol { public let hiddenAt: Date public let type: String public let movie: TraktMovie? public let show: TraktShow? public let season: TraktSeason? // Initialize public init?(json: RawJSON?) { guard let json = json, let hiddenAt = Date.dateFromString(json["hidden_at"]), let type = json["type"] as? String else { return nil } self.hiddenAt = hiddenAt self.type = type self.movie = TraktMovie(json: json["movie"] as? RawJSON) self.show = TraktShow(json: json["show"] as? RawJSON) self.season = TraktSeason(json: json["season"] as? RawJSON) } }
gpl-3.0
62f86a63770cfac1affe4ebff84dce46
25.411765
67
0.608018
4.045045
false
false
false
false
ykay/twitter-with-menu
Twitter/Tweet.swift
1
1429
// // Tweet.swift // Twitter // // Created by Yuichi Kuroda on 10/3/15. // Copyright © 2015 Yuichi Kuroda. All rights reserved. // import UIKit class Tweet: NSObject { // TODO: User should be User!, not optional!! let user: User? var text: String = "" var id: String = "" let createdAt: NSDate? var favorited = false var favoriteCount = 0 var retweeted = false let rawDictionary: [String:AnyObject]? init(_ data: [String:AnyObject]) { rawDictionary = data user = User(data["user"] as! [String:AnyObject]) if let value = data["text"] as? String { text = value } if let value = data["id_str"] as? String { id = value } if let value = data["created_at"] as? String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "EEE MMM d HH:mm:ss Z y" createdAt = dateFormatter.dateFromString(value) } else { createdAt = nil } if let value = data["favorited"] as? Bool { favorited = value } if let value = data["favorite_count"] as? Int { favoriteCount = value } if let value = data["retweeted"] as? Bool { retweeted = value } } class func tweetsWithArray(data: [AnyObject]) -> [Tweet] { var tweets = [Tweet]() for tweetData in data { tweets.append(Tweet(tweetData as! [String:AnyObject])) } return tweets } }
mit
705a8732bb3dfd02fe3f7cd3fed9602c
20.636364
60
0.592437
3.880435
false
false
false
false
davidbjames/Unilib
Unilib/Sources/Elidable.swift
1
6495
// // Elidable.swift // Unilib // // Created by David James on 2022-01-10. // Copyright © 2022 David B James. All rights reserved. // import Foundation /// Support conditional inline logic in chainable interfaces. /// /// Currently available on arrays, Query, Mutator, AutoLayout, /// all animators, and gesture and list publishers. public/**/ protocol Elidable { func `if`(_ condition:Bool, then closure:(Self)->Self, `else`:((Self)->Self)?) -> Self func `switch`<T>(_ input:T?, _ cases:[T:(Self)->Self], `default`:((Self)->Self)?, finally:((Self)->Self)?) -> Self func ifLet<Thing>(_ thing:Thing?, then closure:(Self,Thing)->Self, `else`:((Self)->Self)?) -> Self func `guard`(_ condition:Bool, `else`:((Self)->Void)?) -> Self? func guardLet<Thing>(_ thing:Thing?, finally closure:(Self,Thing)->Self, `else`:((Self)->Void)?) -> Self? } public/**/ extension Elidable { /// Chainable if/else operator using an external condition. /// /// If the condition evaluates to true then execute /// `then` closure returning new self, otherwise return self as-is. /// Optionally, provide trailing `else` block and return new self. /// /// .if(condition) { wrapper in /// wrapper.doFoo() // returns to outer chain /// } else: { wrapper in /// wrapper.doBar() // returns to outer chain /// } /// .. @discardableResult func `if`(_ condition:Bool, then closure:(Self)->Self, `else`:((Self)->Self)? = nil) -> Self { if condition { return closure(self) } else if let other = `else` { return other(self) } else { return self } } /// Chainable if-let/else operator using external optional. /// /// If the binding/unwrapping succeeds, this executes the /// `then` closure passing the self and the unwrapped thing, /// otherwise returns self as-is. /// Optionally, provide trailing `else` block and return new self. /// /// .ifLet(thing) { wrapper, thing in /// wrapper.doFoo(with:thing) // returns to outer chain /// } else: { wrapper in /// wrapper.doBar() // returns to outer chain /// } /// .. @discardableResult func ifLet<Thing>(_ thing:Thing?, then closure:(Self,Thing)->Self, `else`:((Self)->Self)? = nil) -> Self { if let thing = thing { return closure(self, thing) } else if let other = `else` { return other(self) } else { return self } } /// Chainable "switch" operator with input value and series /// of value/closure tuples with the first input-value match /// causing the closure to be run and resulting self returned. /// /// Optionally, provide a `default` closure if no match. /// Optionally, provide a `finally` closure that is fired /// regardless of a match. It can apply to the match closure, /// default closure or self, potentially modifying the chain. /// /// This isn't really a switch operator (no pattern matching, /// only equality (same type)) but is useful when there are /// multiple possible branches, without breaking the chain. /// Example: /// /// .switch(number, [ /// 1 : { /// $0.foo() /// }, /// 2 : { /// $0.bar() /// } /// ], default: { /// $0.baz() /// }, finally: { /// $0.bop() /// }) /// /// Alternatively, if you need a true Swift `switch` statement, /// wrap the `switch` in `aside` (if you don't need the return type) /// or `elide` (if you need the return type). (`aside` and `elide` /// operators available on conforming types.) @discardableResult func `switch`<T>(_ input:T?, _ cases:[T:(Self)->Self], default defaultClosure:((Self)->Self)? = nil, finally:((Self)->Self)? = nil) -> Self { for (value, predicate) in cases { if value == input { if let finally = finally { return finally(predicate(self)) } return predicate(self) } } if let finally = finally { if let defaultClosure = defaultClosure { return finally(defaultClosure(self)) } else { return finally(self) } } else { if let defaultClosure = defaultClosure { return defaultClosure(self) } else { return self } } } /// Chainable guard/else operator using external condition. /// /// In order to proceed with self chain the condition must /// evaluate to true, otherwise self chain is broken (nil return). /// Optionally, provide trailing `else` block to perform side effects. /// /// .guard(condition) { wrapper in /// wrapper.doFoo() // returns to outer chain /// } else: { wrapper in /// wrapper.doSideEffect() // does not return, chain is broken /// }? /// .. @discardableResult func `guard`(_ condition:Bool, `else`:((Self)->Void)? = nil) -> Self? { if condition { return self } else if let other = `else` { other(self) return nil } else { return nil } } /// Chainable guard-let/else operator using external optional. /// /// In order to proceed with self chain the optional thing /// must exist, else the self chain is broken (nil return). /// If the optional does exist it will be passed to a `finally` /// block to act on and return a new self (or self as-is). /// Optionally, provide trailing `else` block to perform side effects. /// /// .guardLet(thing) { wrapper, thing in /// wrapper.doFoo(with:thing) // returns to outer chain /// } else: { wrapper /// wrapper.doSideEffect() // does not return, chain is broken /// }? /// .. @discardableResult func guardLet<Thing>(_ thing:Thing?, finally closure:(Self,Thing)->Self, `else`:((Self)->Void)? = nil) -> Self? { if let thing = thing { return closure(self, thing) } else if let other = `else` { other(self) return nil } else { return nil } } }
mit
d03856fa4ae1da1bfcb9cc79690ed30a
36.537572
145
0.54866
4.286469
false
false
false
false
saragiotto/TMDbFramework
Example/Pods/Nimble/Sources/Nimble/Matchers/BeAnInstanceOf.swift
2
2286
import Foundation /// A Nimble matcher that succeeds when the actual value is an _exact_ instance of the given class. public func beAnInstanceOf<T>(_ expectedType: T.Type) -> Predicate<Any> { let errorMessage = "be an instance of \(String(describing: expectedType))" return Predicate.define { actualExpression in let instance = try actualExpression.evaluate() guard let validInstance = instance else { return PredicateResult( status: .doesNotMatch, message: .expectedActualValueTo(errorMessage) ) } let actualString = "<\(String(describing: type(of: validInstance))) instance>" return PredicateResult( status: PredicateStatus(bool: type(of: validInstance) == expectedType), message: .expectedCustomValueTo(errorMessage, actualString) ) } } /// A Nimble matcher that succeeds when the actual value is an instance of the given class. /// @see beAKindOf if you want to match against subclasses public func beAnInstanceOf(_ expectedClass: AnyClass) -> Predicate<NSObject> { let errorMessage = "be an instance of \(String(describing: expectedClass))" return Predicate.define { actualExpression in let instance = try actualExpression.evaluate() let actualString: String if let validInstance = instance { actualString = "<\(String(describing: type(of: validInstance))) instance>" } else { actualString = "<nil>" } #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) let matches = instance != nil && instance!.isMember(of: expectedClass) #else let matches = instance != nil && type(of: instance!) == expectedClass #endif return PredicateResult( status: PredicateStatus(bool: matches), message: .expectedCustomValueTo(errorMessage, actualString) ) } } #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) extension NMBObjCMatcher { @objc public class func beAnInstanceOfMatcher(_ expected: AnyClass) -> NMBMatcher { return NMBPredicate { actualExpression in return try! beAnInstanceOf(expected).satisfies(actualExpression).toObjectiveC() } } } #endif
mit
eef400fb6c67ac9cfc1416ae7327ffff
39.821429
99
0.648731
4.991266
false
false
false
false
Ramotion/reel-search
RAMReel/Framework/CollectionViewWrapper.swift
1
10212
// // TableViewWrapper.swift // RAMReel // // Created by Mikhail Stepkin on 4/9/15. // Copyright (c) 2015 Ramotion. All rights reserved. // import UIKit // MARK: - Collection view wrapper /** WrapperProtocol -- Helper protocol for CollectionViewWrapper. */ protocol WrapperProtocol : class { /// Number of cells in collection var numberOfCells: Int { get } /** Cell constructor, replaces standard Apple way of doing it. - parameters: - collectionView `UICollectionView` instance in which cell should be created. - indexPath `NSIndexPath` where to put cell to. - returns: Fresh (or reused) cell. */ func createCell(_ collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell /** Attributes of cells in some rect. - parameter rect Area in which you want to probe for attributes. */ func cellAttributes(_ rect: CGRect) -> [UICollectionViewLayoutAttributes] } /** CollectionViewWrapper -- Wraps collection view and set's collection view data source. */ open class CollectionViewWrapper < DataType, CellClass: UICollectionViewCell>: FlowDataDestination, WrapperProtocol where CellClass: ConfigurableCell, DataType == CellClass.DataType { private var lock : NSLock = NSLock() var data: [DataType] = [] { didSet { self.scrollDelegate.itemIndex = nil self.collectionView.reloadData() self.updateOffset() self.scrollDelegate.adjustScroll(self.collectionView) } } /** FlowDataDestination protocol implementation method. - seealso: FlowDataDestination This method processes data from data flow. - parameter data: Data array to process. */ open func processData(_ data: [DataType]) { self.data = data } let collectionView: UICollectionView let cellId: String = "ReelCell" let dataSource = CollectionViewDataSource() let collectionLayout = RAMCollectionViewLayout() let scrollDelegate: ScrollViewDelegate let rotationWrapper = NotificationCallbackWrapper(name: UIDevice.orientationDidChangeNotification.rawValue, object: UIDevice.current) let keyboardWrapper = NotificationCallbackWrapper(name: UIResponder.keyboardDidChangeFrameNotification.rawValue) var theme: Theme /** - parameters: - collectionView: Collection view to wrap around. - theme: Visual theme of collection view. */ public init(collectionView: UICollectionView, theme: Theme) { self.collectionView = collectionView self.theme = theme self.scrollDelegate = ScrollViewDelegate(itemHeight: collectionLayout.itemHeight) self.scrollDelegate.itemIndexChangeCallback = { [weak self] idx in guard let `self` = self else { return } guard let index = idx , 0 <= index && index < self.data.count else { self.selectedItem = nil return } let item = self.data[index] self.selectedItem = item // TODO: Update cell appearance maybe? // Toggle selected? let indexPath = IndexPath(item: index, section: 0) let cell = collectionView.cellForItem(at: indexPath) cell?.isSelected = true } collectionView.register(CellClass.self, forCellWithReuseIdentifier: cellId) dataSource.wrapper = self collectionView.dataSource = dataSource collectionView.collectionViewLayout = collectionLayout collectionView.bounces = false let scrollView = collectionView as UIScrollView scrollView.delegate = scrollDelegate rotationWrapper.callback = { [weak self] notification in guard let `self` = self else { return } self.adjustScroll(notification as Notification) } keyboardWrapper.callback = { [weak self] notification in guard let `self` = self else { return } self.adjustScroll(notification as Notification) } } deinit { NotificationCenter.default.removeObserver(self) } var selectedItem: DataType? // MARK Implementation of WrapperProtocol func createCell(_ collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CellClass let row = (indexPath as NSIndexPath).row let dat = self.data[row] cell.configureCell(dat) cell.theme = self.theme return cell as UICollectionViewCell } var numberOfCells:Int { return data.count } func cellAttributes(_ rect: CGRect) -> [UICollectionViewLayoutAttributes] { let layout = collectionView.collectionViewLayout guard let attributes = layout.layoutAttributesForElements(in: rect) else { return [] } return attributes } // MARK: Update & Adjust func updateOffset(_ notification: Notification? = nil) { let durationNumber = (notification as NSNotification?)?.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber let duration = durationNumber?.doubleValue ?? 0.1 UIView.animate(withDuration: duration, animations: { let number = self.collectionView.numberOfItems(inSection: 0) let itemIndex = self.scrollDelegate.itemIndex ?? number/2 guard itemIndex > 0 else { return } let inset = self.collectionView.contentInset.top let itemHeight = self.collectionLayout.itemHeight let offset = CGPoint(x: 0, y: CGFloat(itemIndex) * itemHeight - inset) self.collectionView.contentOffset = offset }) } func adjustScroll(_ notification: Notification? = nil) { collectionView.contentInset = UIEdgeInsets.zero collectionLayout.updateInsets() self.updateOffset(notification) } } class CollectionViewDataSource: NSObject, UICollectionViewDataSource { weak var wrapper: WrapperProtocol! func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let number = self.wrapper.numberOfCells return number } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = self.wrapper.createCell(collectionView, indexPath: indexPath) return cell } } class ScrollViewDelegate: NSObject, UIScrollViewDelegate { typealias ItemIndexChangeCallback = (Int?) -> () var itemIndexChangeCallback: ItemIndexChangeCallback? fileprivate(set) var itemIndex: Int? = nil { willSet (newIndex) { if let callback = itemIndexChangeCallback { callback(newIndex) } } } let itemHeight: CGFloat init (itemHeight: CGFloat) { self.itemHeight = itemHeight super.init() } func adjustScroll(_ scrollView: UIScrollView) { let inset = scrollView.contentInset.top let currentOffsetY = scrollView.contentOffset.y + inset let floatIndex = currentOffsetY/itemHeight let scrollDirection = ScrollDirection.scrolledWhere(scrollFrom, scrollTo) let itemIndex: Int switch scrollDirection { case .noScroll: itemIndex = Int(floatIndex) case .up: itemIndex = Int(floor(floatIndex)) case .down: itemIndex = Int(ceil(floatIndex)) } if itemIndex >= 0 { self.itemIndex = itemIndex } // Perform no animation if no scroll is needed if case .noScroll = scrollDirection { return } let adjestedOffsetY = CGFloat(itemIndex) * itemHeight - inset // Difference between actual and designated position in pixels let Δ = abs(scrollView.contentOffset.y - adjestedOffsetY) // Allowed differenct between actual and designated position in pixels let ε:CGFloat = 0.5 // If difference is larger than allowed, then adjust position animated if Δ > ε { UIView.animate(withDuration: 0.25, delay: 0.0, options: UIView.AnimationOptions.curveEaseOut, animations: { let newOffset = CGPoint(x: 0, y: adjestedOffsetY) scrollView.contentOffset = newOffset }, completion: nil) } } var scrollFrom: CGFloat = 0 var scrollTo: CGFloat = 0 enum ScrollDirection { case up case down case noScroll static func scrolledWhere(_ from: CGFloat, _ to: CGFloat) -> ScrollDirection { if from < to { return .down } else if from > to { return .up } else { return .noScroll } } } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { scrollFrom = scrollView.contentOffset.y } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollTo = scrollView.contentOffset.y adjustScroll(scrollView) } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { scrollTo = scrollView.contentOffset.y adjustScroll(scrollView) } } }
mit
7f79b529bf1e7b00f00c08539b169701
29.290801
137
0.603644
5.658537
false
false
false
false
josve05a/wikipedia-ios
WMF Framework/Remote Notifications/RemoteNotificationsOperationsController.swift
3
6883
class RemoteNotificationsOperationsController: NSObject { private let apiController: RemoteNotificationsAPIController private let modelController: RemoteNotificationsModelController? private let deadlineController: RemoteNotificationsOperationsDeadlineController? private let operationQueue: OperationQueue private var isLocked: Bool = false { didSet { if isLocked { stop() } } } required init(session: Session, configuration: Configuration) { apiController = RemoteNotificationsAPIController(session: session, configuration: configuration) var modelControllerInitializationError: Error? modelController = RemoteNotificationsModelController(&modelControllerInitializationError) deadlineController = RemoteNotificationsOperationsDeadlineController(with: modelController?.managedObjectContext) if let modelControllerInitializationError = modelControllerInitializationError { DDLogError("Failed to initialize RemoteNotificationsModelController and RemoteNotificationsOperationsDeadlineController: \(modelControllerInitializationError)") isLocked = true } operationQueue = OperationQueue() operationQueue.maxConcurrentOperationCount = 1 super.init() NotificationCenter.default.addObserver(self, selector: #selector(didMakeAuthorizedWikidataDescriptionEdit), name: WikidataDescriptionEditingController.DidMakeAuthorizedWikidataDescriptionEditNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(modelControllerDidLoadPersistentStores(_:)), name: RemoteNotificationsModelController.didLoadPersistentStoresNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } public func stop() { operationQueue.cancelAllOperations() } @objc private func sync(_ completion: @escaping () -> Void) { let completeEarly = { self.operationQueue.addOperation(completion) } guard !isLocked else { completeEarly() return } NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(sync), object: nil) guard operationQueue.operationCount == 0 else { completeEarly() return } guard apiController.isAuthenticated else { stop() completeEarly() return } guard deadlineController?.isBeforeDeadline ?? false else { completeEarly() return } guard let modelController = self.modelController else { completeEarly() return } let markAsReadOperation = RemoteNotificationsMarkAsReadOperation(with: apiController, modelController: modelController) let fetchOperation = RemoteNotificationsFetchOperation(with: apiController, modelController: modelController) let completionOperation = BlockOperation(block: completion) fetchOperation.addDependency(markAsReadOperation) completionOperation.addDependency(fetchOperation) operationQueue.addOperation(markAsReadOperation) operationQueue.addOperation(fetchOperation) operationQueue.addOperation(completionOperation) } // MARK: Notifications @objc private func didMakeAuthorizedWikidataDescriptionEdit(_ note: Notification) { deadlineController?.resetDeadline() } @objc private func modelControllerDidLoadPersistentStores(_ note: Notification) { if let object = note.object, let error = object as? Error { DDLogDebug("RemoteNotificationsModelController failed to load persistent stores with error \(error); stopping RemoteNotificationsOperationsController") isLocked = true } else { isLocked = false } } } extension RemoteNotificationsOperationsController: PeriodicWorker { func doPeriodicWork(_ completion: @escaping () -> Void) { sync(completion) } } extension RemoteNotificationsOperationsController: BackgroundFetcher { func performBackgroundFetch(_ completion: @escaping (UIBackgroundFetchResult) -> Void) { doPeriodicWork { completion(.noData) } } } // MARK: RemoteNotificationsOperationsDeadlineController final class RemoteNotificationsOperationsDeadlineController { private let remoteNotificationsContext: NSManagedObjectContext init?(with remoteNotificationsContext: NSManagedObjectContext?) { guard let remoteNotificationsContext = remoteNotificationsContext else { return nil } self.remoteNotificationsContext = remoteNotificationsContext } let startTimeKey = "WMFRemoteNotificationsOperationsStartTime" let deadline: TimeInterval = 86400 // 24 hours private var now: CFAbsoluteTime { return CFAbsoluteTimeGetCurrent() } private func save() { guard remoteNotificationsContext.hasChanges else { return } do { try remoteNotificationsContext.save() } catch let error { DDLogError("Error saving managedObjectContext: \(error)") } } public var isBeforeDeadline: Bool { guard let startTime = startTime else { return false } return now - startTime < deadline } private var startTime: CFAbsoluteTime? { set { let moc = remoteNotificationsContext moc.perform { if let newValue = newValue { moc.wmf_setValue(NSNumber(value: newValue), forKey: self.startTimeKey) } else { moc.wmf_setValue(nil, forKey: self.startTimeKey) } self.save() } } get { let moc = remoteNotificationsContext let value: CFAbsoluteTime? = moc.performWaitAndReturn { let keyValue = remoteNotificationsContext.wmf_keyValue(forKey: startTimeKey) guard let value = keyValue?.value else { return nil } guard let number = value as? NSNumber else { assertionFailure("Expected keyValue \(startTimeKey) to be of type NSNumber") return nil } return number.doubleValue } return value } } public func resetDeadline() { startTime = now } } private extension NSManagedObjectContext { func performWaitAndReturn<T>(_ block: () -> T?) -> T? { var result: T? = nil performAndWait { result = block() } return result } }
mit
e260869a41e5ceb1eada0b4dcd3a652d
34.297436
225
0.657272
6.251589
false
false
false
false
TheDarkCode/Example-Swift-Apps
Exercises and Basic Principles/active-directory-basics/active-directory-basics/AppDelegate.swift
1
6140
// // AppDelegate.swift // active-directory-basics // // Created by Mark Hamilton on 3/27/16. // Copyright © 2016 dryverless. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.dryverless.active_directory_basics" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("active_directory_basics", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
0626ee07ba2f5d16bcf1d94da8d922ef
54.306306
291
0.720801
5.863419
false
false
false
false
thatseeyou/iOSSDKExamples
Pages/[UITableView] Built-In Cell Styles.xcplaygroundpage/Contents.swift
1
2900
/*: # UITableViewCell의 Style * 기본으로 제공하는 style을 확인한다. * Custom style을 사용하는 경우에 contentView에 subview를 추가한다. */ import Foundation import UIKit class TableViewController: UITableViewController { let cellIdentifiers = ["Cell0", "Cell1", "Cell2", "Cell3", "Cell4"] let cellStyles:[UITableViewCellStyle] = [.Default, .Subtitle, .Value1, .Value2, .Default] let sectionHeaders = ["Default", "Subtitle", "Value1", "Value2", "Custom"] let cellImage = [#Image(imageLiteral: "people.user_simple 64.png")#] /*: ## override UIViewController method */ override func viewDidLoad() { print ("viewDidLoad") super.viewDidLoad() } /*: ## UITableViewDelegate protocol */ /*: ## UITableViewDataSource protocol */ override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 5 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 4 ? 2 : 1 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sectionHeaders[section] } /*: UITableViewCell에서 제공하는 기본 스타일에서 사용하는 속성들 * contentView - textLabel - detailTextLabel - imageView * accessoryView - accessoryType : accessoryView = nil 이면 참조 */ override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // for debug tableView.visibleCells let section = indexPath.section var cell : UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(cellIdentifiers[section]) if cell == nil { // section에 따라서 다른 cell cell = UITableViewCell(style:cellStyles[section], reuseIdentifier:cellIdentifiers[section]) if section == 4 { cell.backgroundColor = [#Color(colorLiteralRed: 0, green: 0, blue: 1, alpha: 1)#] let view = UIView(frame: CGRectMake(0, 0, 100, 100)) view.backgroundColor = [#Color(colorLiteralRed: 1, green: 0.5, blue: 0, alpha: 1)#].colorWithAlphaComponent(0.5) cell.contentView.addSubview(view) // 2. accessoryType cell.accessoryType = .DetailButton } else { // 1-3. imageView cell.imageView?.image = cellImage // 2. accessoryType cell.accessoryType = .DetailButton } } if section != 4 { cell.textLabel?.text = "textLabel at \(indexPath.row)" cell.detailTextLabel?.text = "detailTextLabel at \(indexPath.row)" } return cell } } PlaygroundHelper.showViewController(TableViewController(style: .Plain))
mit
4e8c822f43942d4f02f66cebd92b9670
26.564356
128
0.631106
4.663317
false
false
false
false
OfficeDev/O365-iOS-Microsoft-Graph-Connect-Swift
O365-iOS-Microsoft-Graph-Connect-Swift/ConnectViewController.swift
1
3120
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. * See LICENSE in the project root for license information. */ import UIKit /** ConnectViewController is responsible for authenticating the user. Upon success, open SendMailViewController using predefined segue. Otherwise, show an error. In this sample a user-invoked cancellation is considered an error. */ class ConnectViewController: UIViewController { // Outlets @IBOutlet var connectButton: UIButton! @IBOutlet var activityIndicator: UIActivityIndicatorView! } // MARK: Actions private extension ConnectViewController { @IBAction func connect(_ sender: AnyObject) { authenticate() } @IBAction func disconnect(_ sender: AnyObject) { AuthenticationClass.sharedInstance.disconnect() self.navigationController?.popViewController(animated: true) } } // MARK: Authentication private extension ConnectViewController { func authenticate() { loadingUI(show: true) let scopes = ApplicationConstants.kScopes AuthenticationClass.sharedInstance .connectToGraph(scopes: scopes) { result, _ in defer { self.loadingUI(show: false) } if let graphError = result { switch graphError { case .nsErrorType(let nsError): print(NSLocalizedString("ERROR", comment: ""), nsError.userInfo) self.showError(message: NSLocalizedString("CHECK_LOG_ERROR", comment: "")) } } else { // Run on main thread DispatchQueue.main.async { [unowned self] in self.performSegue(withIdentifier: "sendMail", sender: nil) } } } } } // MARK: UI Helper private extension ConnectViewController { func loadingUI(show: Bool) { DispatchQueue.main.async { if show { self.activityIndicator.startAnimating() self.connectButton.setTitle(NSLocalizedString("CONNECTING", comment: ""), for: .normal) self.connectButton.isEnabled = false } else { self.activityIndicator.stopAnimating() self.connectButton.setTitle(NSLocalizedString("CONNECT", comment: ""), for: .normal) self.connectButton.isEnabled = true } } } func showError(message: String) { DispatchQueue.main.async { [unowned self] in let alertControl = UIAlertController(title: NSLocalizedString("ERROR", comment: ""), message: message, preferredStyle: .alert) alertControl.addAction(UIAlertAction(title: NSLocalizedString("CLOSE", comment: ""), style: .default, handler: nil)) self.present(alertControl, animated: true, completion: nil) } } }
mit
c18e4772586aaaf2a87c167a87adbba1
33.666667
103
0.583013
5.581395
false
false
false
false
PD-Jell/Swift_study
SwiftStudy/DaumMap/DaumMapViewController.swift
1
2114
// // DaumMapViewController.swift // SwiftStudy // // Created by YooHG on 2021/04/05. // Copyright © 2021 Jell PD. All rights reserved. // import UIKit class DaumMapViewController: UIViewController, MTMapViewDelegate { var mapView: MTMapView? override func viewDidLoad() { super.viewDidLoad() mapView = MTMapView(frame: self.view.bounds) if let mapView = mapView { mapView.delegate = self mapView.baseMapType = .standard self.view.addSubview(mapView) DispatchQueue.global().async { sleep(3) mapView.setMapCenter(MTMapPoint.init(geoCoord: MTMapPointGeo(latitude: 37.53737528, longitude: 127.00557633)), animated: true) sleep(3) let poiItem1 = MTMapPOIItem.init() poiItem1.itemName = "City on a Hill" poiItem1.mapPoint = MTMapPoint.init(geoCoord: MTMapPointGeo.init(latitude: 37.541889, longitude: 127.095388)) poiItem1.markerType = .redPin poiItem1.showAnimationType = .dropFromHeaven poiItem1.draggable = true poiItem1.tag = 153 mapView.add(poiItem1) mapView.fitAreaToShowAllPOIItems() let circle = MTMapCircle.init() circle.circleCenterPoint = MTMapPoint.init(geoCoord: MTMapPointGeo.init(latitude: 37.541889, longitude: 127.095388)) circle.circleLineColor = UIColor.init(red: 1, green: 0, blue: 0, alpha: 0.5) circle.circleFillColor = UIColor.init(red: 0, green: 1, blue: 0, alpha: 0.5) circle.tag = 1234 circle.circleRadius = 500 mapView.addCircle(circle) mapView.fitArea(toShow: circle) mapView.setMapCenter(MTMapPoint.init(geoCoord: MTMapPointGeo.init(latitude: 37.541889, longitude: 127.095388)), animated: true) // let poiItem2 = MTMapPOIItem.init() } } } }
mit
bc9fddb0e78c0f718c9745ab99c84e38
38.867925
143
0.576905
4.286004
false
false
false
false
michikono/how-tos
swift-using-typealiases-as-generics/swift-using-typealiases-as-generics.playground/Pages/5-1-implementing-patterns.xcplaygroundpage/Contents.swift
1
1512
//: Implementing Patterns //: ===================== //: [Previous](@previous) protocol Material {} class Wood: Material {} class Glass: Material {} class Metal: Material {} class Cotton: Material {} protocol HouseholdThing { } protocol Furniture: HouseholdThing { init() typealias M: Material typealias T: HouseholdThing func mainMaterial() -> M static func factory() -> T } class Chair: Furniture { required init() {} func mainMaterial() -> Wood { return Wood() } static func factory() -> Chair { return Chair() } } class Lamp: Furniture { required init() {} func mainMaterial() -> Glass { return Glass() } static func factory() -> Lamp { return Lamp() } } //: Now this works class FurnitureMaker<C: Furniture> { func make() -> C { return C() } func material(furniture: C) -> C.M { return furniture.mainMaterial() } } //: So does all this let chairMaker = FurnitureMaker<Chair>() let chair1 = chairMaker.make() let chair2 = chairMaker.make() chairMaker.material(chair2) // returns Wood let lampMaker = FurnitureMaker<Lamp>() let lamp = lampMaker.make() lampMaker.material(lamp) // returns Glass //: Optimizing the code a little by creating a BetterChairMaker... class ChairMaker: FurnitureMaker<Chair> {} let betterChairMaker = ChairMaker() let chair3 = betterChairMaker.make() let chair4 = betterChairMaker.make() betterChairMaker.material(chair4) //: [Next](@next)
mit
19589fd31fc137e92b04005c4b9c7b35
19.432432
66
0.642857
3.549296
false
false
false
false
webstersx/DataStructures
DataStructures.playground/Contents.swift
1
1059
//: Playground - noun: a place where people can play import UIKit import DataStructuresKit /* //Link Lists var ll = LinkedNode() ll.size() ll.head ll.tail ll.find(1) ll.contains(1) ll.add(1) ll.size() ll.find(1) ll.contains(1) ll.head ll.tail ll.add(2) ll.size() ll.head ll.tail ll.head?.next ll.tail?.prev */ let i1 = LinkedNodeItem<Int>(object: 1) let i2 = LinkedNodeItem<Int>(object: 2) i1.next = i2 i2.prev = i1 i1.object i2.object i1.next?.prev?.next?.object let ll = LinkedNode<Int>() let first = ll.add(1) let second = ll.add(1) first second first == second first === second first.object == second.object let firstFound = ll.find(1)! first == firstFound first === firstFound second == firstFound second === firstFound ll.head?.object ll.tail?.object ll.find(1)?.object ll.find(2)?.object ll.contains(1) ll.contains(2) ll.size let lll = LinkedNode<Int>() ll == lll ll === lll let a = LinkedNode<Int>() let b = LinkedNode<Int>() a.add(1) b.add(1) a == b a.add(2) a == b b.add(2) a == b let c = LinkedNode<String>() a == c
mit
30153f253ef7eed2e0c8168219dba89d
10.03125
52
0.66289
2.497642
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/View/Common/BFEmptyDataCell.swift
1
1937
// // BFEmptyDataCell.swift // BeeFun // // Created by WengHengcong on 2018/6/2. // Copyright © 2018年 JungleSong. All rights reserved. // import UIKit protocol BFEmptyDataCellDelegate: class { func didClickEmptyAction(cell: BFEmptyDataCell) } class BFEmptyDataCell: UITableViewCell, BFPlaceHolderViewDelegate { // 无数据提醒 var tip: String? // 无数据提醒的图片 var tipImage: String? // 无数据按钮的title var actionTitle: String? var placeEmptyView: BFPlaceHolderView? weak var delegate: BFEmptyDataCellDelegate? private let emptyViewTag: Int = 12353 override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func display(tip: String?, imageName: String?, actionTitle: String?) { self.tip = tip self.tipImage = imageName self.actionTitle = actionTitle if self.tip == nil { self.tip = "Empty now" } if self.tipImage == nil { self.tipImage = "empty_data" } if self.actionTitle == nil { self.actionTitle = "Explore more".localized } setNeedsDisplay() } override func layoutSubviews() { removeEmptyView() placeEmptyView = BFPlaceHolderView(frame: self.contentView.frame, tip: tip!, image: tipImage!, actionTitle: actionTitle!) placeEmptyView?.placeHolderActionDelegate = self contentView.addSubview(placeEmptyView!) } func removeEmptyView() { if let emptyView = placeEmptyView { emptyView.removeFromSuperview() } } func didAction(place: BFPlaceHolderView) { delegate?.didClickEmptyAction(cell: self) } }
mit
e46d1fd178f45164992d9072088ff91e
26.085714
129
0.635021
4.635697
false
false
false
false
geta6/AKImageCropper
AKImageCropper/SwiftExtensions/CGRect.swift
1
3654
// // CGRect.swift // Extension file // // Created by Krachulov Artem // Copyright (c) 2015 The Krachulovs. All rights reserved. // Website: http://www.artemkrachulov.com/ // import UIKit extension CGRect { /// Centers the rectangle inside another rectangle /// /// Usage: /// /// var rect1 = CGRectMake(0, 0, 500, 300) /// var rect2 = CGRectMake(0, 0, 100, 200) /// rect2.centersRectIn(rect1) // {x 200 y 50 w 100 h 200} /// rect2 = CGRectMake(0, 0, 800, 500) /// rect2.centersRectIn(rect1) // {x -150 y -100 w 800 h 500} mutating func centersRectIn(rect: CGRect) { self = CGRectCenters(self, inRect: rect) } } /// Centers the rectangle inside another rectangle /// /// Usage: /// /// var rect1 = CGRectMake(0, 0, 500, 300) /// var rect2 = CGRectMake(0, 0, 100, 200) /// CGRectCenters(rect2, inRect: rect1) // {x 200 y 50 w 100 h 200} /// rect2 = CGRectMake(0, 0, 800, 500) /// CGRectCenters(rect2, inRect: rect1) // {x -150 y -100 w 800 h 500} public func CGRectCenters(rect1: CGRect, inRect rect2: CGRect) -> CGRect { return CGRect(origin: CGPointMake((CGRectGetWidth(rect2) - CGRectGetWidth(rect1)) / 2, (CGRectGetHeight(rect2) - CGRectGetHeight(rect1)) / 2), size: rect1.size) } /// Get scale value to fit rectangle to another rectangle with ratio /// /// Usage: /// /// var rect1 = CGRectMake(0, 0, 500, 300) /// var rect2 = CGRectMake(0, 0, 100, 200) /// CGRectFitScale(rect1, toRect: rect2) // 0.2 public func CGRectFitScale(rect1: CGRect, toRect rect2: CGRect) -> CGFloat { return min(CGRectGetHeight(rect2) / CGRectGetHeight(rect1), CGRectGetWidth(rect2) / CGRectGetWidth(rect1)) } /// Get scale value to fill rectangle to another rectangle with ratio /// /// Usage: /// /// var rect1 = CGRectMake(0, 0, 100, 200) /// var rect2 = CGRectMake(0, 0, 500, 300) /// CGRectFillScale(rect1, toRect: rect2) // 5 public func CGRectFillScale(rect1: CGRect, toRect rect2: CGRect) -> CGFloat { return max(CGRectGetHeight(rect2) / CGRectGetHeight(rect1), CGRectGetWidth(rect2) / CGRectGetWidth(rect1)) } /// Method returns new rectangle origin and size if rectangle `aRect` goes out the rectangle `maxRect` with min rectangle size value `minSize` /// /// Usage: /// /// let aRect = CGRectMake(-20, 150, 100, 200) /// let bRect = CGRectMake(0, 0, 500, 300) /// let minSize = CGSizeMake(150, 150) /// CGRectFit(aRect, toRect: bRect, minSize) // {x 0 y 150 w 150 h 150} public func CGRectFit(aRect: CGRect, toRect bRect: CGRect, minSize: CGSize) -> CGRect { var rect = aRect rect.size.width = max(minSize.width, aRect.size.width) rect.origin.x = max(bRect.origin.x, aRect.origin.x) if CGRectGetMaxX(rect) > CGRectGetMaxX(bRect) { if CGRectGetMaxX(bRect) - minSize.width < rect.origin.x { rect.size.width = minSize.width rect.origin.x = CGRectGetMaxX(bRect) - rect.size.width } else { rect.size.width = CGRectGetMaxX(bRect) - rect.origin.x } } rect.size.height = max(minSize.height, aRect.size.height) rect.origin.y = max(bRect.origin.y, aRect.origin.y) if CGRectGetMaxY(rect) > CGRectGetMaxY(bRect) { if CGRectGetMaxY(bRect) - minSize.height < rect.origin.y { rect.size.height = minSize.height rect.origin.y = CGRectGetMaxY(bRect) - rect.size.height } else { rect.size.height = CGRectGetMaxY(bRect) - rect.origin.y } } return rect }
mit
77bb1798cc79a26f759e16d82a9ed58f
29.974576
164
0.620416
3.523626
false
false
false
false
jum/Charts
ChartsDemo-iOS/Swift/Demos/LineChartTimeViewController.swift
2
5650
// // LineChartTimeViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // import UIKit import Charts class LineChartTimeViewController: DemoBaseViewController { @IBOutlet var chartView: LineChartView! @IBOutlet var sliderX: UISlider! @IBOutlet var sliderTextX: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Time Line Chart" self.options = [.toggleValues, .toggleFilled, .toggleCircles, .toggleCubic, .toggleHorizontalCubic, .toggleStepped, .toggleHighlight, .animateX, .animateY, .animateXY, .saveToGallery, .togglePinchZoom, .toggleAutoScaleMinMax, .toggleData] chartView.delegate = self chartView.chartDescription?.enabled = false chartView.dragEnabled = true chartView.setScaleEnabled(true) chartView.pinchZoomEnabled = false chartView.highlightPerDragEnabled = true chartView.backgroundColor = .white chartView.legend.enabled = false let xAxis = chartView.xAxis xAxis.labelPosition = .topInside xAxis.labelFont = .systemFont(ofSize: 10, weight: .light) xAxis.labelTextColor = UIColor(red: 255/255, green: 192/255, blue: 56/255, alpha: 1) xAxis.drawAxisLineEnabled = false xAxis.drawGridLinesEnabled = true xAxis.centerAxisLabelsEnabled = true xAxis.granularity = 3600 xAxis.valueFormatter = DateValueFormatter() let leftAxis = chartView.leftAxis leftAxis.labelPosition = .insideChart leftAxis.labelFont = .systemFont(ofSize: 12, weight: .light) leftAxis.drawGridLinesEnabled = true leftAxis.granularityEnabled = true leftAxis.axisMinimum = 0 leftAxis.axisMaximum = 170 leftAxis.yOffset = -9 leftAxis.labelTextColor = UIColor(red: 255/255, green: 192/255, blue: 56/255, alpha: 1) chartView.rightAxis.enabled = false chartView.legend.form = .line sliderX.value = 100 slidersValueChanged(nil) chartView.animate(xAxisDuration: 2.5) } override func updateChartData() { if self.shouldHideData { chartView.data = nil return } self.setDataCount(Int(sliderX.value), range: 30) } func setDataCount(_ count: Int, range: UInt32) { let now = Date().timeIntervalSince1970 let hourSeconds: TimeInterval = 3600 let from = now - (Double(count) / 2) * hourSeconds let to = now + (Double(count) / 2) * hourSeconds let values = stride(from: from, to: to, by: hourSeconds).map { (x) -> ChartDataEntry in let y = arc4random_uniform(range) + 50 return ChartDataEntry(x: x, y: Double(y)) } let set1 = LineChartDataSet(entries: values, label: "DataSet 1") set1.axisDependency = .left set1.setColor(UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1)) set1.lineWidth = 1.5 set1.drawCirclesEnabled = false set1.drawValuesEnabled = false set1.fillAlpha = 0.26 set1.fillColor = UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1) set1.highlightColor = UIColor(red: 244/255, green: 117/255, blue: 117/255, alpha: 1) set1.drawCircleHoleEnabled = false let data = LineChartData(dataSet: set1) data.setValueTextColor(.white) data.setValueFont(.systemFont(ofSize: 9, weight: .light)) chartView.data = data } override func optionTapped(_ option: Option) { switch option { case .toggleFilled: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.drawFilledEnabled = !set.drawFilledEnabled } chartView.setNeedsDisplay() case .toggleCircles: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.drawCirclesEnabled = !set.drawCirclesEnabled } chartView.setNeedsDisplay() case .toggleCubic: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.mode = (set.mode == .cubicBezier) ? .linear : .cubicBezier } chartView.setNeedsDisplay() case .toggleStepped: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.mode = (set.mode == .stepped) ? .linear : .stepped } chartView.setNeedsDisplay() case .toggleHorizontalCubic: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.mode = (set.mode == .cubicBezier) ? .horizontalBezier : .cubicBezier } chartView.setNeedsDisplay() default: super.handleOption(option, forChartView: chartView) } } @IBAction func slidersValueChanged(_ sender: Any?) { sliderTextX.text = "\(Int(sliderX.value))" self.updateChartData() } }
apache-2.0
16755e35ae3e3757905e24f461b4f848
34.086957
95
0.56895
5.04375
false
false
false
false
EZ-NET/CodePiece
CodePiece/Codes/WebCaptureController.swift
1
7936
// // WebCaptureController.swift // CodePiece // // Created by Tomohiro Kumagai on H27/07/26. // Copyright © 平成27年 EasyStyle G.K. All rights reserved. // import Cocoa import WebKit import Ocean import Swim private var thread = DispatchQueue(label: "jp.ez-net.CodePiece.CodeCaptureController") final class WebCaptureController { typealias CaptureCompletionHandler = (NSImage?) -> Void private var requests: [Request] init() { requests = [Request]() } func capture(url: String, of sourceFilename: String, captureInfo: CaptureInfo, completion: @escaping CaptureCompletionHandler) { post(Request(url: url, sourceFilename: sourceFilename, owner: self, captureInfo: captureInfo, handler: completion)) } private func post(_ request: Request) { thread.async { [unowned self] in requests.append(request) request.post() } } } extension WebCaptureController { @objcMembers internal class Request : NSObject { weak var owner: WebCaptureController! var captureInfo: CaptureInfo var url: String var sourceFilename: String var completionHandler: WebCaptureController.CaptureCompletionHandler var view: WKWebView init(url: String, sourceFilename: String, owner: WebCaptureController, captureInfo: CaptureInfo, handler: @escaping WebCaptureController.CaptureCompletionHandler) { self.owner = owner self.captureInfo = captureInfo self.url = url self.sourceFilename = sourceFilename self.completionHandler = handler view = WKWebView(frame: NSRect(x: 0, y: 0, width: captureInfo.clientFrameWidth, height: captureInfo.clientFrameHeight)) super.init() view.navigationDelegate = self view.customUserAgent = captureInfo.userAgent } func post() { DispatchQueue.main.async { [unowned self] in let url = URL(string: self.url)! let request = URLRequest(url: url) view.load(request) } } } } extension WebCaptureController.Request : WKNavigationDelegate { private func fulfillRequest(for image: NSImage?) { completionHandler(image) thread.async { [unowned self] in if let index = owner.requests.firstIndex(of: self) { owner.requests.remove(at: index) } } } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { // frame の bounds が更新される前に呼び出される場合があるようなので、 // 応急対応として待ち時間を挿入します。適切な方法に変える必要があります。(WKWebView ではなく WebView 時代の話) Thread.sleep(forTimeInterval: 0.5) DispatchQueue.main.async { [unowned self] in var containerNodeId: String { let targetName = sourceFilename .replacingOccurrences(of: ".", with: "-") .lowercased() return "file-\(targetName)" } let specifyNodesScript = """ const tableNode = document.getElementsByTagName('table')[0]; const containerNode = document.getElementById('\(containerNodeId)'); const searchNodes = containerNode.getElementsByTagName('div'); const headerNode = Array.from(searchNodes).find(node => node.classList.contains('file-header')); const contentNode = Array.from(searchNodes).find(node => node.getAttribute('itemprop') == 'text'); const numNodes = Array.from(contentNode.getElementsByTagName('td')).filter(node => node.classList.contains('blob-num')); if (headerNode) { containerNode.removeChild(headerNode); } for (let numNode of numNodes) { numNode.style.minWidth = '0px'; } const freeNode = document.createElement('div'); freeNode.style.width = '\(captureInfo.clientWidth)px'; freeNode.style.height = '\(captureInfo.clientHeight)px'; freeNode.appendChild(document.createTextNode('')); containerNode.insertBefore(freeNode, contentNode.nextSibling); true; """ let applyingStyleScript = """ tableNode.style.tabSize = '4'; containerNode.style.borderRadius = '0px'; containerNode.style.border = 'thin solid var(--color-bg-canvas)'; contentNode.style.tabSize = '4'; contentNode.style.borderRadius = '0px'; contentNode.style.border = 'thin solid var(--color-bg-canvas)'; contentNode.style.padding = '6px 0px'; contentNode.style.overflow = 'auto'; """ let gettingBoundsScript = """ const containerBounds = containerNode.getBoundingClientRect(); const contentBounds = contentNode.getBoundingClientRect(); const x = containerBounds.left; const y = containerBounds.top; const width = containerBounds.width; const height = containerBounds.height; const contentWidth = contentBounds.width; const contentHeight = contentBounds.height; const bodyWidth = document.body.offsetWidth; const bodyHeight = document.body.offsetHeight; [x, y, width, height, bodyWidth, bodyHeight, contentWidth, contentHeight]; """ func finishEvaluating(with error: Error) { switch error { case let error as WKWebView.InternalError: switch error { case .unexpected(let message): NSLog("Script evaluation error: unexpected error: \(message)") } case let error as NSError: if error.domain == "WKErrorDomain", let message = error.userInfo["WKJavaScriptExceptionMessage"] as? String { NSLog("Script evaluation error: \(message)") } else { NSLog("Script evaluation error: \(error)") } } fulfillRequest(for: nil) } webView.evaluate(javaScript: specifyNodesScript) { result in if case let .failure(error) = result { return finishEvaluating(with: error) } webView.evaluate(javaScript: applyingStyleScript) { result in if case let .failure(error) = result { return finishEvaluating(with: error) } webView.evaluate(javaScript: gettingBoundsScript) { result in do { let object = try result.get() guard let results = object as? Array<NSNumber> else { return fulfillRequest(for: nil) } let x = results[0].intValue let y = results[1].intValue let containerWidth = results[2].intValue let containerHeight = results[3].intValue let bodyWidth = results[4].intValue let bodyHeight = results[5].intValue let contentWidth = results[6].intValue let contentHeight = results[7].intValue let effectiveHeight = max(min(contentHeight, captureInfo.extendedHeight), captureInfo.minHeight) let effectiveWidth = min(max(contentHeight * 16 / 9, captureInfo.minWidth), captureInfo.maxWidth) NSLog("Captured : (\(effectiveWidth), \(effectiveHeight)) { min: (\(captureInfo.minWidth), \(captureInfo.minHeight)), max: (\(captureInfo.maxWidth), \(captureInfo.extendedHeight)), container: (\(containerWidth), \(containerHeight)), content: (\(contentWidth), \(contentHeight)) }") let rect = NSRect(x: x, y: y, width: effectiveWidth, height: effectiveHeight) view.frame = NSRect(x: 0, y: 0, width: bodyWidth, height: bodyHeight) print(rect) let configuration = instanceApplyingExpression(with: WKSnapshotConfiguration()) { settings in settings.rect = rect } webView.takeSnapshot(with: configuration) { image, error in guard let image = image else { fulfillRequest(for: nil) return } fulfillRequest(for: image) } } catch { finishEvaluating(with: error) } } } } } } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { DispatchQueue.main.async { [unowned self] in fulfillRequest(for: nil) } } }
gpl-3.0
fa2bfefcd8e2d1072aa473281d3c2696
26.711744
288
0.663542
3.954799
false
false
false
false
kostiakoval/Swift-TuplesPower
FunctionCallWithTuple.playground/contents.swift
1
2242
// Playground - noun: a place where people can play import Cocoa func sum(x: Int, y: Int) -> Int { return x + y } func sum1(# x: Int, y: Int) -> Int { return x + y } func sum2(# x: Int, #y: Int) -> Int { return x + y } func sum3(one x: Int, two y: Int) -> Int { return x + y } func sum4(x: Int, y: Int, maybe: Int? = nil) -> Int { return x + y + (maybe ?? 0) } func sum5(x: Int, y: Int, maybe: Int?) -> Int { return x + y + (maybe ?? 0) } sum(1, 1) sum1(x: 1, 2) sum2(x: 1, y: 3) sum3(one: 1, two: 4) sum4(1, 5, maybe: 1) sum4(1, 5) sum5(1, 5, 2) sum5(1, 5, nil) //sum((1,1)) let params = (1,1) let params1 = (x:1, 2) let params2 = (x:1, y:3) let params3 = (one:1, two:4) // Optional let params4 = (1, 5, maybe:1) let params41 = (1, 5, maybe:Optional<Int>.None) let params42 = (1, 5, maybe:Optional<Int>.Some(1)) let m: Int? = nil let params5 = (1, 5, m) let params6 = (1, 5, maybe: Optional<Int>.Some(1)) let params7 = (1, 5, 3) let params8 = (1, 5, Optional<Int>.None) let params9 = (1, 5, Optional<Int>.Some(1)) sum(params) sum1(params1) sum2(params2) sum3(params3) //sum4 - always fails :( sum5(params5) sum5(params8) sum5(params9) // //Fails //Fails //sum4(params) //sum4(params4) //sum4(params41) //sum4(params42) //sum4(params5) //sum4(params6) //sum5(params) //sum5(params6) //sum5(params7) // Fails //sum(params2) //sum(params3) //sum(params4) struct C { let c: Int } let cInit = (1) let cInit1 = (c: 11) let cInit2 = (It_Works: 10); C(c: 123) C(c: cInit1) C(c: cInit2) // Fails //C(cInit1) //let cInit2 = (11, 12) //C(c: cInit2) struct S { let x: Int let y: Int let maybe: String? } class SS { let x: Int let y: Int let maybe: String? init (_ x: Int, _ y: Int, _ maybe: String?) { self.x = x self.y = y self.maybe = maybe } } let sInit = (x: 1, y: 1, maybe: "Hello") let sInit1 = (1, 1, "Hello") let sInit2 = (x: 1, 1, "Hello") S(x: 1, y: 0, maybe: nil) SS(10, 11, "Yes") // Fails //SS(sInit) //SS(sInit1) //SS(sInit2) struct A { func sum(x: Int, y: Int) -> Int { return x + y } static func sum1(x: Int, y: Int) -> Int { return x + y } } let aParams = (1, y:4) A() let a = A() a.sum(1, y: 1) a.sum(aParams) A.sum1(aParams) // Part 2
mit
741988d543a1bbad9b3b2c8f73af6f15
13.0125
53
0.569135
2.164093
false
false
false
false
S2dentik/Taylor
TaylorFrameworkTests/TemperTests/NumberOfMethodsInClassRuleTests.swift
4
1786
// // NumberOfMethodsInClassRuleTests.swift // Temper // // Created by Mihai Seremet on 9/10/15. // Copyright © 2015 Yopeso. All rights reserved. // import Nimble import Quick @testable import TaylorFramework class NumberOfMethodsInClassRuleTests: QuickSpec { let rule = NumberOfMethodsInClassRule() override func spec() { describe("Number Of Methods In Class Rule") { it("should not check the non-class components") { let component = Component(type: .for, range: ComponentRange(sl: 0, el: 0), name: "blabla") let result = self.rule.checkComponent(component) expect(result.isOk).to(beTrue()) expect(result.message).to(beNil()) expect(result.value).to(beNil()) } it("should return true and nil when number of methods is smaller than the limit") { let component = TestsHelper().makeClassComponentWithNrOfMethods(2) let result = self.rule.checkComponent(component) expect(result.isOk).to(beTrue()) expect(result.message).to(beNil()) expect(result.value).to(equal(2)) } it("should return false and message when number of methods is bigger than the limit") { let component = TestsHelper().makeClassComponentWithNrOfMethods(12) let result = self.rule.checkComponent(component) expect(result.isOk).to(beFalse()) expect(result.message).toNot(beNil()) expect(result.value).to(equal(12)) } it("should set the priority") { self.rule.priority = 4 expect(self.rule.priority).to(equal(4)) } } } }
mit
717f250fa9f158521bb4554e919d09a1
39.568182
106
0.588796
4.418317
false
true
false
false
alvarozizou/Noticias-Leganes-iOS
NoticiasLeganes/Chat/ViewControllers/AliasVC.swift
1
1545
// // AliasVC.swift // NoticiasLeganes // // Created by Alvaro Informática on 16/1/18. // Copyright © 2018 Alvaro Blazquez Montero. All rights reserved. // import UIKit import Material import Firebase class AliasVC: InputDataViewController { @IBOutlet weak var aliasView: UIView! private var aliasField: ErrorTextField! var viewModel: ChatVM! override func viewDidLoad() { super.viewDidLoad() prepareAliasField() Analytics.watchAliasChat() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func initChatTap(_ sender: Any) { guard let textAlias = aliasField.text else { return } if textAlias == "" || textAlias.count < 5 { aliasField.isErrorRevealed = true return } Auth.auth().signInAnonymously(completion: { (user, error) in if let _error = error { print(_error.localizedDescription) return } UserDF.alias = textAlias self.viewModel.alias = textAlias self.viewModel.uid = Auth.auth().currentUser?.uid self.navigationController?.popViewController(animated: true) }) } } extension AliasVC { private func prepareAliasField() { aliasField = prepareErrorTextField(placeholder: "Alias", error: "Debe tener al menos 5 caracteres", centerInLayout: aliasView) } }
mit
54c0efef5e77aa0fbd87cc5b5c3739d5
25.603448
134
0.624109
4.538235
false
false
false
false
TerryCK/GogoroBatteryMap
GogoroMap/StationsViewCell.swift
1
14605
// // StationsViewCell.swift // GogoroMap // // Created by 陳 冠禎 on 2017/8/11. // Copyright © 2017年 陳 冠禎. All rights reserved. // import UIKit import StoreKit final class StationsViewCell: BaseCollectionViewCell { weak var delegate: MenuController? { didSet { guideButton.addTarget(delegate, action: #selector(MenuController.performBackupPage), for: .touchUpInside) feedBackButton.addTarget(delegate, action: #selector(MenuController.presentMail), for: .touchUpInside) recommandButton.addTarget(delegate, action: #selector(MenuController.recommand), for: .touchUpInside) shareButton.addTarget(delegate, action: #selector(MenuController.shareThisApp), for: .touchUpInside) moreAppsButton.addTarget(delegate, action: #selector(MenuController.moreApp), for: .touchUpInside) dataUpdateButton.addTarget(delegate, action: #selector(MenuController.attempUpdate), for: .touchUpInside) mapOptions.addTarget(delegate, action: #selector(MenuController.changeMapOption), for: .touchUpInside) clusterSwitcher.addTarget(delegate, action: #selector(MenuController.clusterSwitching(sender:)), for: .valueChanged) } } var analytics: StationAnalyticsModel = .init(total: 0, availables: 0, flags: 0, checkins: 0) { didSet { buildingLabel.text = "\("Building:".localize()) \(analytics.buildings)" haveBeenLabel.text = "\("Have been:".localize()) \(analytics.flags)" availableLabel.text = "\("Opening:".localize()) \(analytics.availables)" hasCheckinsLabel.text = "\("Total checkins:".localize()) \(analytics.checkins)" completedRatioLabel.text = "\("Completed ratio:".localize()) \(analytics.completedPercentage) %" } } var product: SKProduct? { didSet { guard let product = product, let price = product.localizedPrice else { return } removeAdsButton.setTitle("\(price) \n\(product.localizedTitle)", for: .normal) restoreButton.addTarget(delegate, action: #selector(MenuController.restorePurchase), for: .touchUpInside) removeAdsButton.addTarget(self, action: #selector(buyButtonTapped), for: .touchUpInside) buyStoreButtonStackView.isHidden = false layoutIfNeeded() } } var purchaseHandler: ((SKProduct) -> ())? @objc func buyButtonTapped() { if let product = product, let purchaseing = purchaseHandler { purchaseing(product) } } private lazy var lastUpdateDateLabel: UILabel = UILabel { $0.text = "\("Last:".localize()) " + Date().string(dateformat: "yyyy.MM.dd") $0.font = .boldSystemFont(ofSize: 11) } private lazy var hasBeenList: UIButton = { let button = UIButton(type: .system) button.setImage(#imageLiteral(resourceName: "refresh"), for: .normal) button.contentMode = .scaleAspectFit button.layer.cornerRadius = 5 return button }() private var clusterSwitcher = UISwitch { $0.isOn = ClusterStatus() == .on } private lazy var clusterDescribingLabel: UILabel = { let label = UILabel(frame: CGRect(x: 20, y: 50, width: frame.width, height: 16)) label.text = "Cluster".localize() label.font = UIFont.systemFont(ofSize: 16) return label }() private let authorLabel = UILabel { $0.text = "Chen, Guan-Jhen \(Date().string(dateformat: "yyyy")) Copyright" $0.font = .systemFont(ofSize: 12) $0.textColor = .gray } private lazy var availableLabel: UILabel = { let label = UILabel(frame: CGRect(x: 20, y: 50, width: frame.width, height: 16)) label.text = "" label.font = .boldSystemFont(ofSize: 14) return label }() private lazy var haveBeenLabel: UILabel = { let label = UILabel(frame: CGRect(x: 20, y: 50, width: frame.width, height: 16)) label.text = NSLocalizedString("Have been:", comment: "") label.font = UIFont.boldSystemFont(ofSize: 18) return label }() private lazy var hasCheckinsLabel: UILabel = { let label = UILabel(frame: CGRect(x: 20, y: 50, width: frame.width, height: 16)) label.text = NSLocalizedString("Total checkins:", comment: "") label.font = UIFont.boldSystemFont(ofSize: 18) return label }() private lazy var completedRatioLabel: UILabel = { let label = UILabel(frame: CGRect(x: 20, y: 50, width: frame.width, height: 16)) label.text = NSLocalizedString("Completed ratio:", comment: "") label.font = UIFont.boldSystemFont(ofSize: 18) return label }() private lazy var totalLabel: UILabel = { let label = UILabel(frame: CGRect(x: 20, y: 50, width: frame.width, height: 16)) label.text = NSLocalizedString("Total:", comment: "") label.font = UIFont.boldSystemFont(ofSize: 12) return label }() private lazy var buildingLabel: UILabel = { let label = UILabel(frame: CGRect(x: 20, y: 50, width: frame.width, height: 16)) label.text = NSLocalizedString("Building:", comment: "") label.font = UIFont.boldSystemFont(ofSize: 14) return label }() private let copyrightLabel: UILabel = { let label = UILabel() label.text = "Data provided by Gogoro, image: CC0 Public Domain".localize() label.font = UIFont.boldSystemFont(ofSize: 11) label.numberOfLines = 0 return label }() private let thanksLabel: UILabel = { let label = UILabel() label.text = "感謝您的贊助,您的贊助將會鼓勵作者開發更多的App,我們非常歡迎有趣的點子來使您生活更美好" label.font = UIFont.boldSystemFont(ofSize: 11) label.numberOfLines = 0 return label }() lazy var dataUpdateButton: UIButton = { let button = UIButton(type: .system) button.setImage(#imageLiteral(resourceName: "refresh"), for: .normal) button.contentMode = .scaleAspectFit button.layer.cornerRadius = 5 return button }() private let feedBackButton: UIButton = { let button = CustomButton(type: .system) button.setTitle(NSLocalizedString("FeedBack", comment: ""), for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) return button }() private let shareButton: UIButton = { let button = CustomButton(type: .system) button.setTitle(NSLocalizedString("Share", comment: ""), for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) return button }() private let recommandButton: UIButton = { let button = CustomButton(type: .system) button.setTitle(NSLocalizedString("Rating", comment: ""), for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) return button }() private let moreAppsButton: UIButton = { let button = CustomButton(type: .system) button.setTitle("\(NSLocalizedString("More", comment: "")) app", for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) return button }() let mapOptions: UIButton = { let button = CustomButton(type: .system) button.setTitle("\(Navigator.option.description)", for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16) return button }() private let guideButton: UIButton = { let button = CustomButton(type: .system) button.setTitle(NSLocalizedString("Backup", comment: ""), for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) return button }() private let removeAdsButton: UIButton = { let button = CustomButton(type: .system) button.setTitle("testing", for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12) button.titleLabel?.numberOfLines = 0 button.titleLabel?.textAlignment = .center return button }() private let restoreButton: UIButton = { let button = CustomButton(type: .system) button.setTitle(NSLocalizedString("Restore", comment: ""), for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16) return button }() private lazy var updateStackView: UIStackView = { let stackView: UIStackView = UIStackView(arrangedSubviews: [lastUpdateDateLabel, dataUpdateButton]) stackView.axis = .horizontal stackView.alignment = .center stackView.spacing = 10 return stackView }() private lazy var pushShareStackView: UIStackView = { let stackView: UIStackView = UIStackView(arrangedSubviews: [shareButton, recommandButton]) stackView.axis = .horizontal stackView.distribution = .fillEqually stackView.spacing = 10 return stackView }() private lazy var feedBackButtonStackView: UIStackView = { let stackView: UIStackView = UIStackView(arrangedSubviews: [guideButton, feedBackButton]) stackView.axis = .horizontal stackView.distribution = .fillEqually stackView.spacing = 10 return stackView }() private lazy var mapOptionStackView: UIStackView = { let stackView: UIStackView = UIStackView(arrangedSubviews: [mapOptions]) stackView.axis = .horizontal stackView.distribution = .fillEqually stackView.spacing = 10 return stackView }() private lazy var clusterIconImageView: UIImageView = { let imageView = UIImageView() imageView.image = #imageLiteral(resourceName: "cluster") imageView.contentMode = .scaleAspectFit return imageView }() lazy var buyStoreButtonStackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [restoreButton, removeAdsButton]) stackView.axis = .horizontal stackView.distribution = .fillEqually stackView.spacing = 10 stackView.isHidden = true return stackView }() private lazy var clusterView: UIView = { let myView = UIView() [clusterIconImageView, clusterDescribingLabel, clusterSwitcher].forEach(myView.addSubview) clusterIconImageView.anchor(top: myView.topAnchor, left: myView.leftAnchor, bottom: myView.bottomAnchor, right: nil, topPadding: 0, leftPadding: 0, bottomPadding: 0, rightPadding: 0, width: 43, height: 43) clusterDescribingLabel.anchor(top: myView.topAnchor, left: clusterIconImageView.rightAnchor, bottom: myView.bottomAnchor, right: nil, topPadding: 0, leftPadding: 5, bottomPadding: 0, rightPadding: 0, width: 0, height: 0) clusterSwitcher.anchor(top: myView.topAnchor, left: nil, bottom: myView.bottomAnchor, right: myView.rightAnchor, topPadding: 0, leftPadding: 0, bottomPadding: 0, rightPadding: 25, width: 0, height: 0) return myView }() private lazy var operationStatusStack: UIStackView = { let stackView = UIStackView(arrangedSubviews: [availableLabel, buildingLabel]) stackView.axis = .horizontal stackView.distribution = .fillEqually stackView.spacing = 10 return stackView }() private lazy var headStackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [updateStackView, completedRatioLabel, haveBeenLabel, hasCheckinsLabel, operationStatusStack, clusterView]) stackView.axis = .vertical stackView.distribution = .fillEqually return stackView }() private lazy var buttonsStackView: UIStackView = { var subviews: [UIView] = [mapOptions, pushShareStackView, feedBackButtonStackView, buyStoreButtonStackView, copyrightLabel,] let stackView = UIStackView(arrangedSubviews: subviews) stackView.distribution = .fillEqually stackView.axis = .vertical stackView.spacing = 10 return stackView }() private lazy var bottomLabelStackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [copyrightLabel, authorLabel]) stackView.distribution = .fillEqually stackView.axis = .vertical stackView.spacing = 10 return stackView }() func setupThanksLabel() { buttonsStackView.insertArrangedSubview(thanksLabel, at: 0) } override func setupViews() { backgroundColor = .clear layer.cornerRadius = 10 layer.masksToBounds = true viewContainer.addSubview(headStackView) headStackView.anchor(top: viewContainer.topAnchor, left: viewContainer.leftAnchor, bottom: nil, right: viewContainer.rightAnchor, topPadding: 10, leftPadding: 20, bottomPadding: 0, rightPadding: 10, width: 0, height: 200) let separatorView = UIView { $0.backgroundColor = .gray } viewContainer.addSubview(separatorView) separatorView.anchor(top: headStackView.bottomAnchor, left: viewContainer.leftAnchor, bottom: nil, right: viewContainer.rightAnchor, topPadding: 10, leftPadding: 10, bottomPadding: 0, rightPadding: 10, width: 0, height: 0.75) viewContainer.addSubview(authorLabel) authorLabel.anchor(top: nil, left: nil, bottom: viewContainer.bottomAnchor, right: nil, topPadding: 0, leftPadding: 0, bottomPadding: 10, rightPadding: 0, width: 0, height: 20) authorLabel.centerXAnchor.constraint(equalTo: viewContainer.centerXAnchor).isActive = true viewContainer.addSubview(buttonsStackView) buttonsStackView.anchor(top: separatorView.bottomAnchor, left: viewContainer.leftAnchor, bottom: authorLabel.topAnchor, right: viewContainer.rightAnchor, topPadding: 16, leftPadding: 20, bottomPadding: 0, rightPadding: 20, width: 0, height: 0) [totalLabel, thanksLabel, authorLabel, buildingLabel, copyrightLabel, availableLabel, hasCheckinsLabel, haveBeenLabel, lastUpdateDateLabel, completedRatioLabel, clusterDescribingLabel].forEach { $0.textColor = .gray } } }
mit
9a34d2622da0c60e2f25d6b5dc98fffa
41.79056
251
0.646009
4.809682
false
false
false
false
TerryCK/GogoroBatteryMap
GogoroMap/BackupPage/Views/BackupTableViewCell.swift
1
3886
// // BackupTableViewCell.swift // GogoroMap // // Created by 陳 冠禎 on 02/11/2017. // Copyright © 2017 陳 冠禎. All rights reserved. // import UIKit import CloudKit final class BackupTableViewCell: UITableViewCell { static let byteCountFormatter = ByteCountFormatter { $0.allowedUnits = [.useAll] $0.countStyle = .file } enum CellType { case switchButton , none, backupButton } let cellType: CellType var stationRecords: [BatteryStationRecord]? private func setupView() { addSubview(titleLabel) var titleHeight: CGFloat = 0 var titleLeftAnchor: NSLayoutXAxisAnchor? = leftAnchor var titleRightAnchor: NSLayoutXAxisAnchor? var titletopAnchor: NSLayoutYAxisAnchor? switch cellType { case .switchButton: titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true setupRightView(with: switchButton) titleRightAnchor = switchButton.rightAnchor titleHeight = 44 titleLabel.textAlignment = .left case .none: titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true titleLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true titleLeftAnchor = nil case .backupButton: setupRightView(with: cloudImageView) addSubview(subtitleLabel) titletopAnchor = topAnchor titleLabel.font = .boldSystemFont(ofSize: 16) subtitleLabel.textColor = .lightGray subtitleLabel.anchor(top: titleLabel.bottomAnchor, left: titleLabel.leftAnchor, bottom: bottomAnchor, right: titleLabel.rightAnchor, topPadding: 0, leftPadding: 0, bottomPadding: 5, rightPadding: 0, width: 0, height: 0) } titleLabel.anchor(top: titletopAnchor, left: titleLeftAnchor, bottom: nil, right: titleRightAnchor, topPadding: 0, leftPadding: 22, bottomPadding: 0, rightPadding: 0, width: 0, height: titleHeight) } private func setupRightView(with myView: UIView) { addSubview(myView) myView.anchor(top: nil, left: nil, bottom: nil, right: rightAnchor, topPadding: 0, leftPadding: 0, bottomPadding: 0, rightPadding: 20, width: 44, height: 0) myView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true } init(type: CellType = .none, title: String = "", subtitle: String = "" , titleColor: UIColor = .red) { cellType = type super.init(style: .default, reuseIdentifier: "") titleLabel.text = title titleLabel.textColor = titleColor subtitleLabel.text = subtitle setupView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var switchButton : UISwitch = { let myswitch = UISwitch() myswitch.isOn = false return myswitch }() let titleLabel = UILabel { $0.font = .systemFont(ofSize: 18) $0.textAlignment = .center } let subtitleLabel = UILabel { $0.font = UIFont.systemFont(ofSize: 13) $0.textAlignment = .left } lazy var cloudImageView = UIImageView { $0.image = #imageLiteral(resourceName: "downloadFromCloud") $0.contentMode = .scaleAspectFill } } extension BackupTableViewCell { convenience init(title: String, subtitle: String, stationRecords: [BatteryStationRecord]) { self.init(type: .backupButton, title: title, subtitle: subtitle) self.stationRecords = stationRecords titleLabel.font = .systemFont(ofSize: 14) titleLabel.textColor = .black subtitleLabel.textAlignment = .center } }
mit
813ac41072b0239ba34f7b3ee7c2381a
33.274336
231
0.634908
4.940051
false
false
false
false
ainame/Swift-WebP
Sources/WebP/WebPImageInspector.swift
1
956
import Foundation import CWebP public struct WebPImageInspector { public static func inspect(_ webPData: Data) throws -> WebPBitstreamFeatures { var cFeature = UnsafeMutablePointer<CWebP.WebPBitstreamFeatures>.allocate(capacity: 1) defer { cFeature.deallocate() } let status = try webPData.withUnsafeBytes { rawPtr -> VP8StatusCode in guard let bindedBasePtr = rawPtr.baseAddress?.assumingMemoryBound(to: UInt8.self) else { throw WebPError.unexpectedPointerError } return WebPGetFeatures(bindedBasePtr, webPData.count, cFeature) } guard status == VP8_STATUS_OK else { throw WebPError.unexpectedError(withMessage: "Error VP8StatusCode=\(status.rawValue)") } guard let feature = WebPBitstreamFeatures(rawValue: cFeature.pointee) else { throw WebPError.unexpectedPointerError } return feature } }
mit
0a125a526b64ae2908df18561b2ad9ca
34.407407
100
0.674686
4.385321
false
false
false
false
gitkong/FLTableViewComponent
FLTableComponent/FLCollectionBaseComponent.swift
2
7852
// // FLCollectionBaseComponent.swift // FLComponentDemo // // Created by gitKong on 2017/5/17. // Copyright © 2017年 gitKong. All rights reserved. // import UIKit class FLCollectionBaseComponent: FLBaseComponent, FLCollectionComponentConfiguration{ private(set) var collectionView : UICollectionView? private(set) var componentIdentifier : String = "" private(set) var isCustomIdentifier = false init(collectionView : UICollectionView){ super.init() self.collectionView = collectionView self.register() isCustomIdentifier = false // self.componentIdentifier = "\(NSStringFromClass(type(of: self))).Component.\(section!))" } convenience init(collectionView : UICollectionView, identifier : String){ self.init(collectionView: collectionView) isCustomIdentifier = true self.componentIdentifier = identifier } final override var section: Int? { didSet { if !isCustomIdentifier { self.componentIdentifier = "\(NSStringFromClass(type(of: self))).Component.\(section!))" } } } final override func reloadSelfComponent() { collectionView?.reloadSections(IndexSet.init(integer: section!)) } } // MARK : base configuration extension FLCollectionBaseComponent { override func register() { collectionView?.registerClass(FLCollectionViewCell.self, withReuseIdentifier: cellIdentifier) collectionView?.registerClass(FLCollectionHeaderFooterView.self, withReuseIdentifier: headerIdentifier) collectionView?.registerClass(FLCollectionHeaderFooterView.self, withReuseIdentifier: footerIdentifier) } func numberOfItems() -> NSInteger { return 0 } func cellForItem(at item: Int) -> UICollectionViewCell { guard let collectionView = collectionView else { return FLCollectionViewCell() } FLCollectionViewCell.component = self return collectionView.dequeueCell(withReuseIdentifier: cellIdentifier, forIndxPath: IndexPath.init(row: item, section: section!))! } func additionalOperationForReuseCell(_ cell : FLCollectionViewCell?) { } /// If you do not override this method, the flow layout uses the values in its itemSize property to set the size of items instead. Your implementation of this method can return a fixed set of sizes or dynamically adjust the sizes based on the cell’s content. /// /// - Parameters: /// - collectionViewLayout: Default is flowLayout /// - indexPath: current indexPath /// - Returns: item size,default is (50.0, 50.0) func sizeForItem(at item: Int) -> CGSize { guard self.collectionView != nil, self.collectionView?.collectionViewLayout is FLCollectionViewFlowLayout else { return .zero } let flowLayout = self.collectionView!.collectionViewLayout as! FLCollectionViewFlowLayout return flowLayout.itemSize } } // MARK : Header and Footer customization extension FLCollectionBaseComponent { func heightForHeader() -> CGFloat { return 0 } func heightForFooter() -> CGFloat { return 0 } func headerView() -> FLCollectionHeaderFooterView { guard let collectionView = collectionView ,let section = section else { return FLCollectionHeaderFooterView(frame: .zero) } FLCollectionHeaderFooterView.component = self FLCollectionHeaderFooterView.type = .Header let headerView = collectionView.dequeueReusableHeaderFooterView(withReuseIdentifier: headerIdentifier, section: section) return headerView! } func footerView() -> FLCollectionHeaderFooterView { guard let collectionView = collectionView, let section = section else { return FLCollectionHeaderFooterView(frame: CGRect.zero) } FLCollectionHeaderFooterView.component = self FLCollectionHeaderFooterView.type = .Footer let footerView = collectionView.dequeueReusableHeaderFooterView(withReuseIdentifier: footerIdentifier, section: section) return footerView! } func additionalOperationForReuseHeaderView(_ headerView : FLCollectionHeaderFooterView?) { } func additionalOperationForReuseFooterView(_ footerView : FLCollectionHeaderFooterView?) { } final func collectionView(viewOfKind kind: String) -> FLCollectionHeaderFooterView { if kind == UICollectionElementKindSectionHeader { return self.headerView() } else if kind == UICollectionElementKindSectionFooter { return self.footerView() } else { return FLCollectionHeaderFooterView() } } } // MARK : Base UI Customization extension FLCollectionBaseComponent { func sectionInset() -> UIEdgeInsets { guard self.collectionView != nil, self.collectionView?.collectionViewLayout is FLCollectionViewFlowLayout else { return .zero } let flowLayout = self.collectionView!.collectionViewLayout as! FLCollectionViewFlowLayout return flowLayout.sectionInset } func minimumLineSpacing() -> CGFloat { guard self.collectionView != nil, self.collectionView?.collectionViewLayout is FLCollectionViewFlowLayout else { return 0 } let flowLayout = self.collectionView!.collectionViewLayout as! FLCollectionViewFlowLayout return flowLayout.minimumLineSpacing } func minimumInteritemSpacing() -> CGFloat { guard self.collectionView != nil, self.collectionView?.collectionViewLayout is FLCollectionViewFlowLayout else { return 0 } let flowLayout = self.collectionView!.collectionViewLayout as! FLCollectionViewFlowLayout return flowLayout.minimumInteritemSpacing } } extension FLCollectionBaseComponent { func collectionView(willDisplayCell cell: UICollectionViewCell, at item: Int) { // do nothing } func collectionView(didEndDisplayCell cell: UICollectionViewCell, at item: Int) { } func collectionView(willDisplayHeaderView view: FLCollectionHeaderFooterView) { } func collectionView(didEndDisplayHeaderView view: FLCollectionHeaderFooterView) { } func collectionView(willDisplayFooterView view: FLCollectionHeaderFooterView) { } func collectionView(didEndDisplayFooterView view: FLCollectionHeaderFooterView) { } final func collectionView(willDisplayView view : FLCollectionHeaderFooterView, viewOfKind kind: String) { if kind == UICollectionElementKindSectionHeader { self.collectionView(willDisplayHeaderView: view) } else if kind == UICollectionElementKindSectionFooter { self.collectionView(willDisplayHeaderView: view) } } final func collectionView(didEndDisplayView view : FLCollectionHeaderFooterView, viewOfKind kind: String) { if kind == UICollectionElementKindSectionHeader { self.collectionView(didEndDisplayHeaderView: view) } else if kind == UICollectionElementKindSectionFooter { self.collectionView(didEndDisplayHeaderView: view) } } } extension FLCollectionBaseComponent { func shouldShowMenu(at item: Int) -> Bool { return false } func canPerform(selector : Selector, forItemAt: Int, withSender: Any?) -> Bool { return false } func perform(selector : Selector, forItemAt: Int, withSender: Any?) { // do nothing } }
mit
dc3c869de10589a239efa7448fb00c0d
31.970588
262
0.677329
5.962766
false
false
false
false
oscarqpe/machine-learning-algorithms
LNN/Param.swift
1
1851
// // Param.swift // LSH Test // // Created by Andre Valdivia on 21/05/16. // Copyright © 2016 Andre Valdivia. All rights reserved. // import Foundation struct Param { static var W:Int = 0 //W =???? Supuestamente un parametro para normalizar el key del HashUnit static var K:Int = 0 //K = Numero de HashUnit en un Hash Table static var L:Int = 0 //L = Numero de HastTables en el Hash Layer static var lenInput:Int = 64 static var hpos = Array<Int>() static var numNeuronasPorCapa = [3,8,11] static var lrate:Double = 0.1 static var lrateLNN:Double = 10 // static var P1 = [1, 2, 5, 11, 17, 23, 31, 41, 47, 59 ] // static var P2:Array<Int> = Param.primos(Param.K) static var P2 = Array<Int>() static func primos(n:Int) -> Array<Int>{ var ret = Array<Int>() ret.append(1) var c = 1 var p = 2 var d = 2 while c <= n{ if(p % d == 0){ if( p == d){ if (c % 2 == 1){ ret.append(p) } c++ } d = 2 p++ }else{ d++ } } return ret } init(W:Int, K:Int, L:Int, lenInput:Int){ Param.W = W Param.K = K Param.L = L Param.lenInput = lenInput Param.P2 = Param.primos(Param.K * 2 - 2) Param.hpos = Array<Int>(count: Param.K, repeatedValue: 0) for i in 0..<Param.K{ if( i % 2 == 0){ Param.hpos[i] = (i + 2) / 2 - 1 }else{ Param.hpos[i] = Param.K - ((i + 1) / 2) } } Param.numNeuronasPorCapa[0] = Param.L + 1 // Param.numNeuronasPorCapa.last! = Param } }
gpl-3.0
b8b59edac3af6f06d7e806011dbfdfbf
27.476923
101
0.46
3.369763
false
false
false
false
pozi119/Valine
Valine/Hop.swift
1
2085
// // Request.swift // Valine // // Created by Valo on 15/12/23. // Copyright © 2015年 Valo. All rights reserved. // import UIKit public enum HopMethod: String { case Push,Pop,Present,Dismiss } public class Hop { //MARK: 公共属性 /// UIViewController 类名,Storyboard ID public var controller: UIViewController? public var aController:String? /// viewController的参数,使用key-value进行设置 public var parameters: [String:AnyObject]? public var completion: (() -> Void)? /// Present模式,源页面是否需要包含在UINavigationController中,默认为true public var sourceInNav: Bool = true /// Present模式,目标页面是否需要包含在UINavigationController中,默认为false public var destInNav: Bool = false /// Present模式,目标页面透明度,默认为1.0 public var alpha: CGFloat = 1.0 /// 页面跳转时是否有动画 public var animated:Bool = true /// Push模式,push完成后要移除的页面 public var removeVCs:[String]? //MARK: 初始化 public init(){ } public init(controller:UIViewController){ self.controller = controller } public convenience init(controller:UIViewController, parameters:[String:AnyObject]?){ self.init(controller:controller) self.parameters = parameters } public init(aController:String, aStoryboard:String?) { self.aController = aController var controller: UIViewController? if aStoryboard != nil { controller = Utils.instantiateViewController(aController, aStoryboard: aStoryboard) } else{ controller = UIViewController(nibName: aController, bundle: nil) } self.controller = controller } public convenience init(aController:String, aStoryboard:String?, parameters:[String:AnyObject]?) { self.init(aController: aController,aStoryboard:aStoryboard) self.parameters = parameters } }
gpl-2.0
ad4f37ea8fdcdacfff138f68e7888c10
25.219178
102
0.647335
4.440835
false
false
false
false
ocrickard/Theodolite
TheodoliteTests/ActionTests.swift
1
1349
// // ActionTests.swift // Theodolite // // Created by Oliver Rickard on 10/10/17. // Copyright © 2017 Oliver Rickard. All rights reserved. // import XCTest @testable import Theodolite class ActionTests: XCTestCase { class TestObject { let action: () -> () func actionMethod(_: Void) { self.action() } init(action: @escaping () -> ()) { self.action = action } } class TestStringObject { let action: (String) -> () func actionMethod(str: String) { self.action(str) } init(action: @escaping (String) -> ()) { self.action = action } } func test_thatDefaultActions_doNotCrash() { let action: Action<Int32> = Action<Int32>() action.send(0) } func test_whenUsingSimpleHandlers_functionIsCalled() { var calledFunction = false let testObj = TestObject(action: { calledFunction = true }) let handler = Handler(testObj, TestObject.actionMethod) handler.send(Void()) XCTAssert(calledFunction) } func test_whenProvidingStringArgumentToAction_handlerReceivesString() { var obj: String? = nil let testObj = TestStringObject(action: { (str: String) in obj = str }) let str = "hello" let handler = Handler(testObj, TestStringObject.actionMethod) handler.send(str) XCTAssert(obj == str) } }
mit
ce1928f37258a6d34bfe769950b3abff
20.741935
73
0.636499
3.840456
false
true
false
false
dduan/swift
stdlib/public/SDK/Foundation/Foundation.swift
1
45154
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import CoreFoundation import CoreGraphics //===----------------------------------------------------------------------===// // Enums //===----------------------------------------------------------------------===// // FIXME: one day this will be bridged from CoreFoundation and we // should drop it here. <rdar://problem/14497260> (need support // for CF bridging) public var kCFStringEncodingASCII: CFStringEncoding { return 0x0600 } // FIXME: <rdar://problem/16074941> NSStringEncoding doesn't work on 32-bit public typealias NSStringEncoding = UInt public var NSASCIIStringEncoding: UInt { return 1 } public var NSNEXTSTEPStringEncoding: UInt { return 2 } public var NSJapaneseEUCStringEncoding: UInt { return 3 } public var NSUTF8StringEncoding: UInt { return 4 } public var NSISOLatin1StringEncoding: UInt { return 5 } public var NSSymbolStringEncoding: UInt { return 6 } public var NSNonLossyASCIIStringEncoding: UInt { return 7 } public var NSShiftJISStringEncoding: UInt { return 8 } public var NSISOLatin2StringEncoding: UInt { return 9 } public var NSUnicodeStringEncoding: UInt { return 10 } public var NSWindowsCP1251StringEncoding: UInt { return 11 } public var NSWindowsCP1252StringEncoding: UInt { return 12 } public var NSWindowsCP1253StringEncoding: UInt { return 13 } public var NSWindowsCP1254StringEncoding: UInt { return 14 } public var NSWindowsCP1250StringEncoding: UInt { return 15 } public var NSISO2022JPStringEncoding: UInt { return 21 } public var NSMacOSRomanStringEncoding: UInt { return 30 } public var NSUTF16StringEncoding: UInt { return NSUnicodeStringEncoding } public var NSUTF16BigEndianStringEncoding: UInt { return 0x90000100 } public var NSUTF16LittleEndianStringEncoding: UInt { return 0x94000100 } public var NSUTF32StringEncoding: UInt { return 0x8c000100 } public var NSUTF32BigEndianStringEncoding: UInt { return 0x98000100 } public var NSUTF32LittleEndianStringEncoding: UInt { return 0x9c000100 } //===----------------------------------------------------------------------===// // NSObject //===----------------------------------------------------------------------===// // These conformances should be located in the `ObjectiveC` module, but they can't // be placed there because string bridging is not available there. extension NSObject : CustomStringConvertible {} extension NSObject : CustomDebugStringConvertible {} //===----------------------------------------------------------------------===// // Strings //===----------------------------------------------------------------------===// @available(*, unavailable, message: "Please use String or NSString") public class NSSimpleCString {} @available(*, unavailable, message: "Please use String or NSString") public class NSConstantString {} @warn_unused_result @_silgen_name("swift_convertStringToNSString") public // COMPILER_INTRINSIC func _convertStringToNSString(string: String) -> NSString { return string._bridgeToObjectiveC() } extension NSString : StringLiteralConvertible { /// Create an instance initialized to `value`. public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init( extendedGraphemeClusterLiteral value: StaticString ) { self.init(stringLiteral: value) } /// Create an instance initialized to `value`. public required convenience init(stringLiteral value: StaticString) { var immutableResult: NSString if value.hasPointerRepresentation { immutableResult = NSString( bytesNoCopy: UnsafeMutablePointer<Void>(value.utf8Start), length: Int(value.utf8CodeUnitCount), encoding: value.isASCII ? NSASCIIStringEncoding : NSUTF8StringEncoding, freeWhenDone: false)! } else { var uintValue = value.unicodeScalar immutableResult = NSString( bytes: &uintValue, length: 4, encoding: NSUTF32StringEncoding)! } self.init(string: immutableResult as String) } } //===----------------------------------------------------------------------===// // New Strings //===----------------------------------------------------------------------===// // // Conversion from NSString to Swift's native representation // extension String { public init(_ cocoaString: NSString) { self = String(_cocoaString: cocoaString) } } extension String : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSString { // This method should not do anything extra except calling into the // implementation inside core. (These two entry points should be // equivalent.) return unsafeBitCast(_bridgeToObjectiveCImpl(), to: NSString.self) } public static func _forceBridgeFromObjectiveC( x: NSString, result: inout String? ) { result = String(x) } public static func _conditionallyBridgeFromObjectiveC( x: NSString, result: inout String? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return result != nil } public static func _unconditionallyBridgeFromObjectiveC( source: NSString? ) -> String { // `nil` has historically been used as a stand-in for an empty // string; map it to an empty string. if _slowPath(source == nil) { return String() } return String(source!) } } //===----------------------------------------------------------------------===// // Numbers //===----------------------------------------------------------------------===// // Conversions between NSNumber and various numeric types. The // conversion to NSNumber is automatic (auto-boxing), while conversion // back to a specific numeric type requires a cast. // FIXME: Incomplete list of types. extension Int : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public init(_ number: NSNumber) { self = number.integerValue } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(integer: self) } public static func _forceBridgeFromObjectiveC( x: NSNumber, result: inout Int? ) { result = x.integerValue } public static func _conditionallyBridgeFromObjectiveC( x: NSNumber, result: inout Int? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } public static func _unconditionallyBridgeFromObjectiveC( source: NSNumber? ) -> Int { return source!.integerValue } } extension UInt : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public init(_ number: NSNumber) { self = number.unsignedIntegerValue } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(unsignedInteger: self) } public static func _forceBridgeFromObjectiveC( x: NSNumber, result: inout UInt? ) { result = x.unsignedIntegerValue } public static func _conditionallyBridgeFromObjectiveC( x: NSNumber, result: inout UInt? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } public static func _unconditionallyBridgeFromObjectiveC( source: NSNumber? ) -> UInt { return source!.unsignedIntegerValue } } extension Float : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public init(_ number: NSNumber) { self = number.floatValue } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(float: self) } public static func _forceBridgeFromObjectiveC( x: NSNumber, result: inout Float? ) { result = x.floatValue } public static func _conditionallyBridgeFromObjectiveC( x: NSNumber, result: inout Float? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } public static func _unconditionallyBridgeFromObjectiveC( source: NSNumber? ) -> Float { return source!.floatValue } } extension Double : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public init(_ number: NSNumber) { self = number.doubleValue } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(double: self) } public static func _forceBridgeFromObjectiveC( x: NSNumber, result: inout Double? ) { result = x.doubleValue } public static func _conditionallyBridgeFromObjectiveC( x: NSNumber, result: inout Double? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } public static func _unconditionallyBridgeFromObjectiveC( source: NSNumber? ) -> Double { return source!.doubleValue } } extension Bool: _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public init(_ number: NSNumber) { self = number.boolValue } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSNumber { return NSNumber(bool: self) } public static func _forceBridgeFromObjectiveC( x: NSNumber, result: inout Bool? ) { result = x.boolValue } public static func _conditionallyBridgeFromObjectiveC( x: NSNumber, result: inout Bool? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } public static func _unconditionallyBridgeFromObjectiveC( source: NSNumber? ) -> Bool { return source!.boolValue } } // CGFloat bridging. extension CGFloat : _ObjectiveCBridgeable { public static func _isBridgedToObjectiveC() -> Bool { return true } public init(_ number: NSNumber) { self.native = CGFloat.NativeType(number) } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSNumber { return self.native._bridgeToObjectiveC() } public static func _forceBridgeFromObjectiveC( x: NSNumber, result: inout CGFloat? ) { var nativeResult: CGFloat.NativeType? = 0.0 CGFloat.NativeType._forceBridgeFromObjectiveC(x, result: &nativeResult) result = CGFloat(nativeResult!) } public static func _conditionallyBridgeFromObjectiveC( x: NSNumber, result: inout CGFloat? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } public static func _unconditionallyBridgeFromObjectiveC( source: NSNumber? ) -> CGFloat { return CGFloat( CGFloat.NativeType._unconditionallyBridgeFromObjectiveC(source)) } } // Literal support for NSNumber extension NSNumber : FloatLiteralConvertible, IntegerLiteralConvertible, BooleanLiteralConvertible { /// Create an instance initialized to `value`. public required convenience init(integerLiteral value: Int) { self.init(integer: value) } /// Create an instance initialized to `value`. public required convenience init(floatLiteral value: Double) { self.init(double: value) } /// Create an instance initialized to `value`. public required convenience init(booleanLiteral value: Bool) { self.init(bool: value) } } public let NSNotFound: Int = .max //===----------------------------------------------------------------------===// // Arrays //===----------------------------------------------------------------------===// extension NSArray : ArrayLiteralConvertible { /// Create an instance initialized with `elements`. public required convenience init(arrayLiteral elements: AnyObject...) { // + (instancetype)arrayWithObjects:(const id [])objects count:(NSUInteger)cnt; let x = _extractOrCopyToNativeArrayBuffer(elements._buffer) self.init( objects: UnsafeMutablePointer(x.firstElementAddress), count: x.count) _fixLifetime(x) } } extension Array : _ObjectiveCBridgeable { /// Private initializer used for bridging. /// /// The provided `NSArray` will be copied to ensure that the copy can /// not be mutated by other code. internal init(_cocoaArray: NSArray) { _sanityCheck(_isBridgedVerbatimToObjectiveC(Element.self), "Array can be backed by NSArray only when the element type can be bridged verbatim to Objective-C") // FIXME: We would like to call CFArrayCreateCopy() to avoid doing an // objc_msgSend() for instances of CoreFoundation types. We can't do that // today because CFArrayCreateCopy() copies array contents unconditionally, // resulting in O(n) copies even for immutable arrays. // // <rdar://problem/19773555> CFArrayCreateCopy() is >10x slower than // -[NSArray copyWithZone:] // // The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS // and watchOS. self = Array( _immutableCocoaArray: unsafeBitCast(_cocoaArray.copy(), to: _NSArrayCore.self)) } public static func _isBridgedToObjectiveC() -> Bool { return Swift._isBridgedToObjectiveC(Element.self) } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSArray { return unsafeBitCast(self._buffer._asCocoaArray(), to: NSArray.self) } public static func _forceBridgeFromObjectiveC( source: NSArray, result: inout Array? ) { _precondition( Swift._isBridgedToObjectiveC(Element.self), "array element type is not bridged to Objective-C") // If we have the appropriate native storage already, just adopt it. if let native = Array._bridgeFromObjectiveCAdoptingNativeStorageOf(source) { result = native return } if _fastPath(_isBridgedVerbatimToObjectiveC(Element.self)) { // Forced down-cast (possible deferred type-checking) result = Array(_cocoaArray: source) return } result = _arrayForceCast([AnyObject](_cocoaArray: source)) } public static func _conditionallyBridgeFromObjectiveC( source: NSArray, result: inout Array? ) -> Bool { // Construct the result array by conditionally bridging each element. let anyObjectArr = [AnyObject](_cocoaArray: source) result = _arrayConditionalCast(anyObjectArr) return result != nil } public static func _unconditionallyBridgeFromObjectiveC( source: NSArray? ) -> Array { _precondition( Swift._isBridgedToObjectiveC(Element.self), "array element type is not bridged to Objective-C") // `nil` has historically been used as a stand-in for an empty // array; map it to an empty array instead of failing. if _slowPath(source == nil) { return Array() } // If we have the appropriate native storage already, just adopt it. if let native = Array._bridgeFromObjectiveCAdoptingNativeStorageOf(source!) { return native } if _fastPath(_isBridgedVerbatimToObjectiveC(Element.self)) { // Forced down-cast (possible deferred type-checking) return Array(_cocoaArray: source!) } return _arrayForceCast([AnyObject](_cocoaArray: source!)) } } //===----------------------------------------------------------------------===// // Dictionaries //===----------------------------------------------------------------------===// extension NSDictionary : DictionaryLiteralConvertible { public required convenience init( dictionaryLiteral elements: (NSCopying, AnyObject)... ) { self.init( objects: elements.map { (AnyObject?)($0.1) }, forKeys: elements.map { (NSCopying?)($0.0) }, count: elements.count) } } extension Dictionary { /// Private initializer used for bridging. /// /// The provided `NSDictionary` will be copied to ensure that the copy can /// not be mutated by other code. public init(_cocoaDictionary: _NSDictionary) { _sanityCheck( _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self), "Dictionary can be backed by NSDictionary storage only when both key and value are bridged verbatim to Objective-C") // FIXME: We would like to call CFDictionaryCreateCopy() to avoid doing an // objc_msgSend() for instances of CoreFoundation types. We can't do that // today because CFDictionaryCreateCopy() copies dictionary contents // unconditionally, resulting in O(n) copies even for immutable dictionaries. // // <rdar://problem/20690755> CFDictionaryCreateCopy() does not call copyWithZone: // // The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS // and watchOS. self = Dictionary( _immutableCocoaDictionary: unsafeBitCast(_cocoaDictionary.copy(with: nil), to: _NSDictionary.self)) } } // Dictionary<Key, Value> is conditionally bridged to NSDictionary extension Dictionary : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSDictionary { return unsafeBitCast(_bridgeToObjectiveCImpl(), to: NSDictionary.self) } public static func _forceBridgeFromObjectiveC( d: NSDictionary, result: inout Dictionary? ) { if let native = [Key : Value]._bridgeFromObjectiveCAdoptingNativeStorageOf( d as AnyObject) { result = native return } if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { result = [Key : Value]( _cocoaDictionary: unsafeBitCast(d, to: _NSDictionary.self)) return } // `Dictionary<Key, Value>` where either `Key` or `Value` is a value type // may not be backed by an NSDictionary. var builder = _DictionaryBuilder<Key, Value>(count: d.count) d.enumerateKeysAndObjects({ (anyObjectKey: AnyObject, anyObjectValue: AnyObject, stop: UnsafeMutablePointer<ObjCBool>) in builder.add( key: Swift._forceBridgeFromObjectiveC(anyObjectKey, Key.self), value: Swift._forceBridgeFromObjectiveC(anyObjectValue, Value.self)) }) result = builder.take() } public static func _conditionallyBridgeFromObjectiveC( x: NSDictionary, result: inout Dictionary? ) -> Bool { let anyDict = x as [NSObject : AnyObject] if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { result = Swift._dictionaryDownCastConditional(anyDict) return result != nil } result = Swift._dictionaryBridgeFromObjectiveCConditional(anyDict) return result != nil } public static func _isBridgedToObjectiveC() -> Bool { return Swift._isBridgedToObjectiveC(Key.self) && Swift._isBridgedToObjectiveC(Value.self) } public static func _unconditionallyBridgeFromObjectiveC( d: NSDictionary? ) -> Dictionary { // `nil` has historically been used as a stand-in for an empty // dictionary; map it to an empty dictionary. if _slowPath(d == nil) { return Dictionary() } if let native = [Key : Value]._bridgeFromObjectiveCAdoptingNativeStorageOf( d! as AnyObject) { return native } if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { return [Key : Value]( _cocoaDictionary: unsafeBitCast(d!, to: _NSDictionary.self)) } // `Dictionary<Key, Value>` where either `Key` or `Value` is a value type // may not be backed by an NSDictionary. var builder = _DictionaryBuilder<Key, Value>(count: d!.count) d!.enumerateKeysAndObjects({ (anyObjectKey: AnyObject, anyObjectValue: AnyObject, stop: UnsafeMutablePointer<ObjCBool>) in builder.add( key: Swift._forceBridgeFromObjectiveC(anyObjectKey, Key.self), value: Swift._forceBridgeFromObjectiveC(anyObjectValue, Value.self)) }) return builder.take() } } //===----------------------------------------------------------------------===// // Fast enumeration //===----------------------------------------------------------------------===// // NB: This is a class because fast enumeration passes around interior pointers // to the enumeration state, so the state cannot be moved in memory. We will // probably need to implement fast enumeration in the compiler as a primitive // to implement it both correctly and efficiently. final public class NSFastEnumerationIterator : IteratorProtocol { var enumerable: NSFastEnumeration var state: [NSFastEnumerationState] var n: Int var count: Int /// Size of ObjectsBuffer, in ids. var STACK_BUF_SIZE: Int { return 4 } // FIXME: Replace with _CocoaFastEnumerationStackBuf. /// Must have enough space for STACK_BUF_SIZE object references. struct ObjectsBuffer { var buf: (OpaquePointer, OpaquePointer, OpaquePointer, OpaquePointer) = (nil, nil, nil, nil) } var objects: [ObjectsBuffer] public func next() -> AnyObject? { if n == count { // FIXME: Is this check necessary before refresh()? if count == 0 { return nil } refresh() if count == 0 { return nil } } let next: AnyObject = state[0].itemsPtr[n]! n += 1 return next } func refresh() { n = 0 count = enumerable.countByEnumerating( with: state._baseAddressIfContiguous, objects: AutoreleasingUnsafeMutablePointer( objects._baseAddressIfContiguous), count: STACK_BUF_SIZE) } public init(_ enumerable: NSFastEnumeration) { self.enumerable = enumerable self.state = [ NSFastEnumerationState( state: 0, itemsPtr: nil, mutationsPtr: _fastEnumerationStorageMutationsPtr, extra: (0, 0, 0, 0, 0)) ] self.objects = [ ObjectsBuffer() ] self.n = -1 self.count = -1 } } extension NSArray : Sequence { /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). final public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } /* TODO: API review extension NSArray : Swift.Collection { final public var startIndex: Int { return 0 } final public var endIndex: Int { return count } } */ extension Set { /// Private initializer used for bridging. /// /// The provided `NSSet` will be copied to ensure that the copy can /// not be mutated by other code. public init(_cocoaSet: _NSSet) { _sanityCheck(_isBridgedVerbatimToObjectiveC(Element.self), "Set can be backed by NSSet _variantStorage only when the member type can be bridged verbatim to Objective-C") // FIXME: We would like to call CFSetCreateCopy() to avoid doing an // objc_msgSend() for instances of CoreFoundation types. We can't do that // today because CFSetCreateCopy() copies dictionary contents // unconditionally, resulting in O(n) copies even for immutable dictionaries. // // <rdar://problem/20697680> CFSetCreateCopy() does not call copyWithZone: // // The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS // and watchOS. self = Set( _immutableCocoaSet: unsafeBitCast(_cocoaSet.copy(with: nil), to: _NSSet.self)) } } extension NSSet : Sequence { /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } extension NSOrderedSet : Sequence { /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } // FIXME: move inside NSIndexSet when the compiler supports this. public struct NSIndexSetIterator : IteratorProtocol { public typealias Element = Int internal let _set: NSIndexSet internal var _first: Bool = true internal var _current: Int? internal init(set: NSIndexSet) { self._set = set self._current = nil } public mutating func next() -> Int? { if _first { _current = _set.firstIndex _first = false } else if let c = _current { _current = _set.indexGreaterThanIndex(c) } else { // current is already nil } if _current == NSNotFound { _current = nil } return _current } } extension NSIndexSet : Sequence { /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). public func makeIterator() -> NSIndexSetIterator { return NSIndexSetIterator(set: self) } } // Set<Element> is conditionally bridged to NSSet extension Set : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSSet { return unsafeBitCast(_bridgeToObjectiveCImpl(), to: NSSet.self) } public static func _forceBridgeFromObjectiveC(s: NSSet, result: inout Set?) { if let native = Set<Element>._bridgeFromObjectiveCAdoptingNativeStorageOf(s as AnyObject) { result = native return } if _isBridgedVerbatimToObjectiveC(Element.self) { result = Set<Element>(_cocoaSet: unsafeBitCast(s, to: _NSSet.self)) return } // `Set<Element>` where `Element` is a value type may not be backed by // an NSSet. var builder = _SetBuilder<Element>(count: s.count) s.enumerateObjects({ (anyObjectMember: AnyObject, stop: UnsafeMutablePointer<ObjCBool>) in builder.add(member: Swift._forceBridgeFromObjectiveC( anyObjectMember, Element.self)) }) result = builder.take() } public static func _conditionallyBridgeFromObjectiveC( x: NSSet, result: inout Set? ) -> Bool { let anySet = x as Set<NSObject> if _isBridgedVerbatimToObjectiveC(Element.self) { result = Swift._setDownCastConditional(anySet) return result != nil } result = Swift._setBridgeFromObjectiveCConditional(anySet) return result != nil } public static func _unconditionallyBridgeFromObjectiveC(s: NSSet?) -> Set { // `nil` has historically been used as a stand-in for an empty // set; map it to an empty set. if _slowPath(s == nil) { return Set() } if let native = Set<Element>._bridgeFromObjectiveCAdoptingNativeStorageOf(s! as AnyObject) { return native } if _isBridgedVerbatimToObjectiveC(Element.self) { return Set<Element>(_cocoaSet: unsafeBitCast(s!, to: _NSSet.self)) } // `Set<Element>` where `Element` is a value type may not be backed by // an NSSet. var builder = _SetBuilder<Element>(count: s!.count) s!.enumerateObjects({ (anyObjectMember: AnyObject, stop: UnsafeMutablePointer<ObjCBool>) in builder.add(member: Swift._forceBridgeFromObjectiveC( anyObjectMember, Element.self)) }) return builder.take() } public static func _isBridgedToObjectiveC() -> Bool { return Swift._isBridgedToObjectiveC(Element.self) } } extension NSDictionary : Sequence { // FIXME: A class because we can't pass a struct with class fields through an // [objc] interface without prematurely destroying the references. final public class Iterator : IteratorProtocol { var _fastIterator: NSFastEnumerationIterator var _dictionary: NSDictionary { return _fastIterator.enumerable as! NSDictionary } public func next() -> (key: AnyObject, value: AnyObject)? { if let key = _fastIterator.next() { // Deliberately avoid the subscript operator in case the dictionary // contains non-copyable keys. This is rare since NSMutableDictionary // requires them, but we don't want to paint ourselves into a corner. return (key: key, value: _dictionary.object(forKey: key)!) } return nil } internal init(_ _dict: NSDictionary) { _fastIterator = NSFastEnumerationIterator(_dict) } } /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). public func makeIterator() -> Iterator { return Iterator(self) } } extension NSEnumerator : Sequence { /// Return an *iterator* over the *enumerator*. /// /// - Complexity: O(1). public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } //===----------------------------------------------------------------------===// // Ranges //===----------------------------------------------------------------------===// extension NSRange { public init(_ x: Range<Int>) { location = x.startIndex length = x.count } @warn_unused_result public func toRange() -> Range<Int>? { if location == NSNotFound { return nil } return location..<(location+length) } } //===----------------------------------------------------------------------===// // NSLocalizedString //===----------------------------------------------------------------------===// /// Returns a localized string, using the main bundle if one is not specified. @warn_unused_result public func NSLocalizedString(key: String, tableName: String? = nil, bundle: NSBundle = NSBundle.main(), value: String = "", comment: String) -> String { return bundle.localizedString(forKey: key, value:value, table:tableName) } //===----------------------------------------------------------------------===// // NSLog //===----------------------------------------------------------------------===// public func NSLog(format: String, _ args: CVarArg...) { withVaList(args) { NSLogv(format, $0) } } #if os(OSX) //===----------------------------------------------------------------------===// // NSRectEdge //===----------------------------------------------------------------------===// // In the SDK, the following NS*Edge constants are defined as macros for the // corresponding CGRectEdge enumerators. Thus, in the SDK, NS*Edge constants // have CGRectEdge type. This is not correct for Swift (as there is no // implicit conversion to NSRectEdge). @available(*, unavailable, renamed: "NSRectEdge.MinX") public var NSMinXEdge: NSRectEdge { fatalError("unavailable property can't be accessed") } @available(*, unavailable, renamed: "NSRectEdge.MinY") public var NSMinYEdge: NSRectEdge { fatalError("unavailable property can't be accessed") } @available(*, unavailable, renamed: "NSRectEdge.MaxX") public var NSMaxXEdge: NSRectEdge { fatalError("unavailable property can't be accessed") } @available(*, unavailable, renamed: "NSRectEdge.MaxY") public var NSMaxYEdge: NSRectEdge { fatalError("unavailable property can't be accessed") } extension NSRectEdge { public init(rectEdge: CGRectEdge) { self = NSRectEdge(rawValue: UInt(rectEdge.rawValue))! } } extension CGRectEdge { public init(rectEdge: NSRectEdge) { self = CGRectEdge(rawValue: UInt32(rectEdge.rawValue))! } } #endif //===----------------------------------------------------------------------===// // NSError (as an out parameter). //===----------------------------------------------------------------------===// public typealias NSErrorPointer = AutoreleasingUnsafeMutablePointer<NSError?> // Note: NSErrorPointer becomes ErrorPointer in Swift 3. public typealias ErrorPointer = NSErrorPointer public // COMPILER_INTRINSIC let _nilObjCError: ErrorProtocol = _GenericObjCError.nilError @warn_unused_result @_silgen_name("swift_convertNSErrorToErrorProtocol") public // COMPILER_INTRINSIC func _convertNSErrorToErrorProtocol(error: NSError?) -> ErrorProtocol { if let error = error { return error } return _nilObjCError } @warn_unused_result @_silgen_name("swift_convertErrorProtocolToNSError") public // COMPILER_INTRINSIC func _convertErrorProtocolToNSError(error: ErrorProtocol) -> NSError { return unsafeDowncast(_bridgeErrorProtocolToNSError(error), to: NSError.self) } //===----------------------------------------------------------------------===// // Variadic initializers and methods //===----------------------------------------------------------------------===// extension NSPredicate { // + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat, ...; public convenience init(format predicateFormat: String, _ args: CVarArg...) { let va_args = getVaList(args) self.init(format: predicateFormat, arguments: va_args) } } extension NSExpression { // + (NSExpression *) expressionWithFormat:(NSString *)expressionFormat, ...; public convenience init(format expressionFormat: String, _ args: CVarArg...) { let va_args = getVaList(args) self.init(format: expressionFormat, arguments: va_args) } } extension NSString { public convenience init(format: NSString, _ args: CVarArg...) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, arguments: va_args) } public convenience init( format: NSString, locale: NSLocale?, _ args: CVarArg... ) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, locale: locale, arguments: va_args) } @warn_unused_result public class func localizedStringWithFormat( format: NSString, _ args: CVarArg... ) -> Self { return withVaList(args) { self.init(format: format as String, locale: NSLocale.current(), arguments: $0) } } @warn_unused_result public func appendingFormat(format: NSString, _ args: CVarArg...) -> NSString { return withVaList(args) { self.appending(NSString(format: format as String, arguments: $0) as String) as NSString } } } extension NSMutableString { public func appendFormat(format: NSString, _ args: CVarArg...) { return withVaList(args) { self.append(NSString(format: format as String, arguments: $0) as String) } } } extension NSArray { // Overlay: - (instancetype)initWithObjects:(id)firstObj, ... public convenience init(objects elements: AnyObject...) { // - (instancetype)initWithObjects:(const id [])objects count:(NSUInteger)cnt; let x = _extractOrCopyToNativeArrayBuffer(elements._buffer) // Use Imported: // @objc(initWithObjects:count:) // init(withObjects objects: UnsafePointer<AnyObject?>, // count cnt: Int) self.init(objects: UnsafeMutablePointer(x.firstElementAddress), count: x.count) _fixLifetime(x) } } extension NSOrderedSet { // - (instancetype)initWithObjects:(id)firstObj, ... public convenience init(objects elements: AnyObject...) { self.init(array: elements) } } extension NSSet { // - (instancetype)initWithObjects:(id)firstObj, ... public convenience init(objects elements: AnyObject...) { self.init(array: elements) } } extension NSSet : ArrayLiteralConvertible { public required convenience init(arrayLiteral elements: AnyObject...) { self.init(array: elements) } } extension NSOrderedSet : ArrayLiteralConvertible { public required convenience init(arrayLiteral elements: AnyObject...) { self.init(array: elements) } } //===--- "Copy constructors" ----------------------------------------------===// // These are needed to make Cocoa feel natural since we eliminated // implicit bridging conversions from Objective-C to Swift //===----------------------------------------------------------------------===// extension NSArray { /// Initializes a newly allocated array by placing in it the objects /// contained in a given array. /// /// - Returns: An array initialized to contain the objects in /// `anArray``. The returned object might be different than the /// original receiver. /// /// Discussion: After an immutable array has been initialized in /// this way, it cannot be modified. @objc(_swiftInitWithArray_NSArray:) public convenience init(array anArray: NSArray) { self.init(array: anArray as Array) } } extension NSString { /// Returns an `NSString` object initialized by copying the characters /// from another given string. /// /// - Returns: An `NSString` object initialized by copying the /// characters from `aString`. The returned object may be different /// from the original receiver. @objc(_swiftInitWithString_NSString:) public convenience init(string aString: NSString) { self.init(string: aString as String) } } extension NSSet { /// Initializes a newly allocated set and adds to it objects from /// another given set. /// /// - Returns: An initialized objects set containing the objects from /// `set`. The returned set might be different than the original /// receiver. @objc(_swiftInitWithSet_NSSet:) public convenience init(set anSet: NSSet) { self.init(set: anSet as Set) } } extension NSDictionary { /// Initializes a newly allocated dictionary and adds to it objects from /// another given dictionary. /// /// - Returns: An initialized dictionary—which might be different /// than the original receiver—containing the keys and values /// found in `otherDictionary`. @objc(_swiftInitWithDictionary_NSDictionary:) public convenience init(dictionary otherDictionary: NSDictionary) { self.init(dictionary: otherDictionary as Dictionary) } } //===----------------------------------------------------------------------===// // NSUndoManager //===----------------------------------------------------------------------===// @_silgen_name("NS_Swift_NSUndoManager_registerUndoWithTargetHandler") internal func NS_Swift_NSUndoManager_registerUndoWithTargetHandler( self_: AnyObject, _ target: AnyObject, _ handler: @convention(block) (AnyObject) -> Void) extension NSUndoManager { @available(OSX 10.11, iOS 9.0, *) public func registerUndoWithTarget<TargetType : AnyObject>( target: TargetType, handler: (TargetType) -> Void ) { // The generic blocks use a different ABI, so we need to wrap the provided // handler in something ObjC compatible. let objcCompatibleHandler: (AnyObject) -> Void = { internalTarget in handler(internalTarget as! TargetType) } NS_Swift_NSUndoManager_registerUndoWithTargetHandler( self as AnyObject, target as AnyObject, objcCompatibleHandler) } } //===----------------------------------------------------------------------===// // NSCoder //===----------------------------------------------------------------------===// @warn_unused_result @_silgen_name("NS_Swift_NSCoder_decodeObject") internal func NS_Swift_NSCoder_decodeObject( self_: AnyObject, _ error: NSErrorPointer) -> AnyObject? @warn_unused_result @_silgen_name("NS_Swift_NSCoder_decodeObjectForKey") internal func NS_Swift_NSCoder_decodeObjectForKey( self_: AnyObject, _ key: AnyObject, _ error: NSErrorPointer) -> AnyObject? @warn_unused_result @_silgen_name("NS_Swift_NSCoder_decodeObjectOfClassForKey") internal func NS_Swift_NSCoder_decodeObjectOfClassForKey( self_: AnyObject, _ cls: AnyObject, _ key: AnyObject, _ error: NSErrorPointer) -> AnyObject? @warn_unused_result @_silgen_name("NS_Swift_NSCoder_decodeObjectOfClassesForKey") internal func NS_Swift_NSCoder_decodeObjectOfClassesForKey( self_: AnyObject, _ classes: NSSet?, _ key: AnyObject, _ error: NSErrorPointer) -> AnyObject? @available(OSX 10.11, iOS 9.0, *) internal func resolveError(error: NSError?) throws { if let error = error where error.code != NSCoderValueNotFoundError { throw error } } extension NSCoder { @warn_unused_result public func decodeObjectOfClass<DecodedObjectType: NSCoding where DecodedObjectType: NSObject>(cls: DecodedObjectType.Type, forKey key: String) -> DecodedObjectType? { let result = NS_Swift_NSCoder_decodeObjectOfClassForKey(self as AnyObject, cls as AnyObject, key as AnyObject, nil) return result as! DecodedObjectType? } @warn_unused_result @nonobjc public func decodeObjectOfClasses(classes: NSSet?, forKey key: String) -> AnyObject? { var classesAsNSObjects: Set<NSObject>? = nil if let theClasses = classes { classesAsNSObjects = Set(IteratorSequence(NSFastEnumerationIterator(theClasses)).map { unsafeBitCast($0, to: NSObject.self) }) } return self.__decodeObject(ofClasses: classesAsNSObjects, forKey: key) } @warn_unused_result @available(OSX 10.11, iOS 9.0, *) public func decodeTopLevelObject() throws -> AnyObject? { var error: NSError? let result = NS_Swift_NSCoder_decodeObject(self as AnyObject, &error) try resolveError(error) return result } @warn_unused_result @available(OSX 10.11, iOS 9.0, *) public func decodeTopLevelObjectForKey(key: String) throws -> AnyObject? { var error: NSError? let result = NS_Swift_NSCoder_decodeObjectForKey(self as AnyObject, key as AnyObject, &error) try resolveError(error) return result } @warn_unused_result @available(OSX 10.11, iOS 9.0, *) public func decodeTopLevelObjectOfClass<DecodedObjectType: NSCoding where DecodedObjectType: NSObject>(cls: DecodedObjectType.Type, forKey key: String) throws -> DecodedObjectType? { var error: NSError? let result = NS_Swift_NSCoder_decodeObjectOfClassForKey(self as AnyObject, cls as AnyObject, key as AnyObject, &error) try resolveError(error) return result as! DecodedObjectType? } @warn_unused_result @available(OSX 10.11, iOS 9.0, *) public func decodeTopLevelObjectOfClasses(classes: NSSet?, forKey key: String) throws -> AnyObject? { var error: NSError? let result = NS_Swift_NSCoder_decodeObjectOfClassesForKey(self as AnyObject, classes, key as AnyObject, &error) try resolveError(error) return result } } //===----------------------------------------------------------------------===// // NSKeyedUnarchiver //===----------------------------------------------------------------------===// @warn_unused_result @_silgen_name("NS_Swift_NSKeyedUnarchiver_unarchiveObjectWithData") internal func NS_Swift_NSKeyedUnarchiver_unarchiveObjectWithData( self_: AnyObject, _ data: AnyObject, _ error: NSErrorPointer) -> AnyObject? extension NSKeyedUnarchiver { @warn_unused_result @available(OSX 10.11, iOS 9.0, *) public class func unarchiveTopLevelObjectWithData(data: NSData) throws -> AnyObject? { var error: NSError? let result = NS_Swift_NSKeyedUnarchiver_unarchiveObjectWithData(self, data as AnyObject, &error) try resolveError(error) return result } } //===----------------------------------------------------------------------===// // NSURL //===----------------------------------------------------------------------===// extension NSURL : _FileReferenceLiteralConvertible { private convenience init(failableFileReferenceLiteral path: String) { let fullPath = NSBundle.main().path(forResource: path, ofType: nil)! self.init(fileURLWithPath: fullPath) } public required convenience init(fileReferenceLiteral path: String) { self.init(failableFileReferenceLiteral: path) } } public typealias _FileReferenceLiteralType = NSURL //===----------------------------------------------------------------------===// // Mirror/Quick Look Conformance //===----------------------------------------------------------------------===// extension NSURL : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .url(absoluteString) } } extension NSRange : CustomReflectable { public var customMirror: Mirror { return Mirror(self, children: ["location": location, "length": length]) } } extension NSRange : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .range(Int64(location), Int64(length)) } } extension NSDate : CustomPlaygroundQuickLookable { var summary: String { let df = NSDateFormatter() df.dateStyle = .mediumStyle df.timeStyle = .shortStyle return df.string(from: self) } public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(summary) } } extension NSSet : CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self as Set<NSObject>) } } extension NSString : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(self as String) } } extension NSArray : CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self as [AnyObject]) } } extension NSDictionary : CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self as [NSObject : AnyObject]) } }
apache-2.0
5bea47f3ca94201b414d140ba5681c59
30.840621
184
0.653909
4.849624
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Unit/Simulation/Controller/UnitAdvanceCalculationController.swift
1
8371
// // UnitAdvanceCalculationController.swift // DereGuide // // Created by zzk on 2017/6/20. // Copyright © 2017年 zzk. All rights reserved. // import UIKit class UnitAdvanceCalculationController: UITableViewController { struct DescriptionRow { var name: String var value: Int } struct CalculationRow { var name: String var variableDescriptions: [String] var result: String? var variables: [String]? } var formulator: LiveFormulator! var result: LSResult! fileprivate lazy var descriptionSection: [DescriptionRow] = { let row1 = DescriptionRow(name: NSLocalizedString("模拟次数", comment: ""), value: self.result.scores.count) let row2 = DescriptionRow(name: NSLocalizedString("最高分数", comment: ""), value: self.result.maxScore) let row3 = DescriptionRow(name: NSLocalizedString("最低分数", comment: ""), value: self.result.minScore) let row4 = DescriptionRow(name: NSLocalizedString("理论最高分数", comment: ""), value: self.formulator.maxScore) let row5 = DescriptionRow(name: NSLocalizedString("理论最低分数", comment: ""), value: self.formulator.minScore) return [row1, row2, row3, row4, row5] }() fileprivate lazy var calculationSection: [CalculationRow] = { let row1 = CalculationRow(name: NSLocalizedString("模拟结果中前x%的最低分数", comment: ""), variableDescriptions: ["x"], result: nil, variables: nil) let row2 = CalculationRow(name: NSLocalizedString("模拟结果中后x%的最高分数", comment: ""), variableDescriptions: ["x"], result: nil, variables: nil) let row3 = CalculationRow(name: NSLocalizedString("模拟结果中分数落入指定区间[a, b]的概率", comment: ""), variableDescriptions: ["a(" + NSLocalizedString("不填表示", comment: "") + "-∞)", "b(" + NSLocalizedString("不填表示", comment: "") + "+∞)"], result: nil, variables: nil) let row4 = CalculationRow(name: NSLocalizedString("根据概率密度曲线估算分数区间[a, b]的概率", comment: ""), variableDescriptions: ["a(" + NSLocalizedString("不填表示", comment: "") + "-∞)", "b(" + NSLocalizedString("不填表示", comment: "") + "+∞)"], result: nil, variables: nil) return [row1, row2, row3, row4] }() convenience init(result: LSResult) { self.init() self.result = result self.navigationItem.title = NSLocalizedString("高级计算", comment: "") } override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 44 tableView.cellLayoutMarginsFollowReadableWidth = false tableView.keyboardDismissMode = .onDrag tableView.separatorInset = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 0) tableView.register(UnitAdvanceCalculationCell.self, forCellReuseIdentifier: UnitAdvanceCalculationCell.description()) tableView.register(UnitAdvanceDescriptionCell.self, forCellReuseIdentifier: UnitAdvanceDescriptionCell.description()) } } extension UnitAdvanceCalculationController { override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return NSLocalizedString("参考值", comment: "") } else { return NSLocalizedString("自定义计算", comment: "") } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return descriptionSection.count } else { return calculationSection.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: UnitAdvanceDescriptionCell.description(), for: indexPath) as! UnitAdvanceDescriptionCell let row = descriptionSection[indexPath.row] cell.setupWith(leftString: row.name, rightString: String(row.value)) return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: UnitAdvanceCalculationCell.description(), for: indexPath) as! UnitAdvanceCalculationCell let row = calculationSection[indexPath.row] cell.setup(row) cell.delegate = self return cell } } } extension UnitAdvanceCalculationController: UnitAdvanceCalculationCellDelegate { private func validateDoublePercentInput(variable: String) -> Bool { if let double = Double(variable), double <= 100, double >= 0 { return true } else { showNotValidAlert() return false } } private func validateDoubleOrNilInput(variable: String) -> Bool { if variable == "" { return true } else if let _ = Double(variable) { return true } else { showNotValidAlert() return false } } private func showNotValidAlert() { UIAlertController.showHintMessage(NSLocalizedString("您输入的变量不合法", comment: ""), in: nil) } func unitAdvanceCalculationCell(_ unitAdvanceCalculationCell: UnitAdvanceCalculationCell, didStartCalculationWith varibles: [String]) { guard let indexPath = tableView.indexPath(for: unitAdvanceCalculationCell) else { return } switch indexPath.row { case 0: if validateDoublePercentInput(variable: varibles[0]) { let x = Double(varibles[0])! calculationSection[indexPath.row].variables = [String(x)] calculationSection[indexPath.row].result = String(result.get(percent: x, true)) unitAdvanceCalculationCell.updateResult(calculationSection[indexPath.row]) } case 1: if validateDoublePercentInput(variable: varibles[0]) { let x = Double(varibles[0])! calculationSection[indexPath.row].variables = [String(x)] calculationSection[indexPath.row].result = String(result.get(percent: x, false)) unitAdvanceCalculationCell.updateResult(calculationSection[indexPath.row]) } case 2: if validateDoubleOrNilInput(variable: varibles[0]) && validateDoubleOrNilInput(variable: varibles[1]) { let a = Double(varibles[0]) ?? 0 let b = Double(varibles[1]) ?? Double.greatestFiniteMagnitude calculationSection[indexPath.row].variables = varibles let value = Double(result.scores.filter { Double($0) <= b && Double($0) >= a }.count) / Double(result.scores.count) calculationSection[indexPath.row].result = String(value) unitAdvanceCalculationCell.updateResult(calculationSection[indexPath.row]) } case 3: if validateDoubleOrNilInput(variable: varibles[0]) && validateDoubleOrNilInput(variable: varibles[1]) { let a = Double(varibles[0]) ?? 0 let b = Double(varibles[1]) ?? Double.greatestFiniteMagnitude calculationSection[indexPath.row].variables = varibles unitAdvanceCalculationCell.startCalculationAnimating() DispatchQueue.global(qos: .userInteractive).async { let value = self.result.estimate(using: LSResult.Kernel.gaussian, range: Range<Double>.init(uncheckedBounds: (a, b)), bound: Range<Double>.init(uncheckedBounds: (Double(self.formulator.minScore), Double(self.formulator.maxScore)))) self.calculationSection[indexPath.row].result = String(value) DispatchQueue.main.async { unitAdvanceCalculationCell.stopCalculationAnimating() unitAdvanceCalculationCell.updateResult(self.calculationSection[indexPath.row]) } } } default: break } } }
mit
b3813228a714875a2576f6cd8322bbff
45.712644
261
0.638656
4.717353
false
false
false
false
maxsokolov/Kee
Sources/KeyValueFileStorageProvider.swift
1
3697
// // Copyright (c) 2017 Max Sokolov https://twitter.com/max_sokolov // // 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 enum KeyValueFileStorageProviderError: Error { case fileStorageFailed(reason: String) } public final class KeyValueFileStorageProvider: KeyValueStorageProvider { private let fileManager: FileManager private let directory: FileManager.SearchPathDirectory private let domainMask: FileManager.SearchPathDomainMask private let fileSuffix = "keefile" public init(directory: FileManager.SearchPathDirectory = .documentDirectory, domainMask: FileManager.SearchPathDomainMask = .userDomainMask) { self.fileManager = FileManager.default self.directory = directory self.domainMask = domainMask } // MARK: - KeyValueStorageProvider public func setData(_ data: Data?, forKey key: String) throws { if let data = data { try data.write(to: try resolveFileUrl(forKey: key)) } else { try removeData(forKey: key) } } public func getData(forKey key: String) throws -> Data { let fileUrl = try resolveFileUrl(forKey: key) if !fileManager.fileExists(atPath: fileUrl.path) { throw KeyValueStorageError.valueNotFoundError } return try Data(contentsOf: fileUrl) } public func removeData(forKey key: String) throws { let fileUrl = try resolveFileUrl(forKey: key) if fileManager.fileExists(atPath: fileUrl.path) { try fileManager.removeItem(atPath: fileUrl.path) } } public func removeAll() throws { let directoryUrl = try resolveDirectoryUrl() try fileManager.contentsOfDirectory(atPath: directoryUrl.path) .filter({ $0.hasSuffix(fileSuffix) }) .forEach({ try fileManager.removeItem(atPath: directoryUrl.path + "/" + $0) }) } // MARK: - Private private func resolveDirectoryUrl() throws -> URL { guard let directoryUrl = fileManager.urls(for: directory, in: domainMask).first else { throw KeyValueFileStorageProviderError.fileStorageFailed(reason: "Unable to resolve path for directory: \(directory)/\(domainMask)") } return directoryUrl } private func resolveFileUrl(forKey key: String) throws -> URL { let directoryUrl = try resolveDirectoryUrl() return directoryUrl.appendingPathComponent("\(key).\(fileSuffix)") } }
mit
3c8760375cfcbb4b9de2b934d20edb18
35.97
146
0.668921
5.043656
false
false
false
false
csound/csound
iOS/Csound iOS Swift Examples/Csound iOS SwiftExamples/Waveview.swift
3
4625
/* Waveview.swift Nikhil Singh, Dr. Richard Boulanger Adapted from the Csound iOS Examples by Steven Yi and Victor Lazzarini This file is part of Csound iOS SwiftExamples. The Csound for iOS Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Csound 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import UIKit class Waveview: UIView { private var lastY: CGFloat = 0 private var displayData = [Float]() fileprivate var table: UnsafeMutablePointer<Float>? fileprivate var tableLength = 0 fileprivate var fTableNumber = 0 fileprivate var csObj = CsoundObj() fileprivate var tableLoaded = false override init(frame: CGRect) { super.init(frame: frame) displayData = [Float](repeatElement(Float(0), count: Int(frame.width))) // Init with 0s } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) displayData = [Float](repeatElement(Float32(0), count: Int(frame.width))) } func displayFTable(_ fTableNum: Int) { fTableNumber = fTableNum tableLoaded = false self.updateValuesFromCsound() } // Take in a pointer to a float and return a Swift array of values stored beginning at that memory location func ptoa(_ ptr: UnsafeMutablePointer<Float>, length: Int) -> [Float] { let bfr = UnsafeBufferPointer(start: ptr, count: length) return [Float](bfr) } // MARK: Drawing Code override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() context?.setFillColor(UIColor.black.cgColor) context?.fill(rect) if tableLoaded { context?.setStrokeColor(UIColor.white.cgColor) context?.setFillColor(UIColor.white.cgColor) let fill_path = CGMutablePath() let x: CGFloat = 0 let y: CGFloat = CGFloat(displayData[0]) fill_path.move(to: CGPoint(x: x, y: y), transform: .identity) for i in 0 ..< displayData.count { fill_path.addLine(to: CGPoint(x: CGFloat(i), y: CGFloat(displayData[i])), transform: .identity) } context?.addPath(fill_path) context?.setAllowsAntialiasing(true) context?.drawPath(using: .stroke) } } // Update values from F-table in displayData array func updateDisplayData() { let scalingFactor: Float32 = 0.9 let width = self.frame.size.width let height = self.frame.size.height let middle: Float32 = Float32(height / 2.0) if table != nil { let valTable = ptoa(table!, length: tableLength) displayData = [Float](repeatElement(Float(0), count: Int(width))) for i in 0 ..< displayData.count { let percent: Float = Float(i)/Float(width) let index: Int = Int(percent * Float(tableLength)) if table != nil { displayData[i] = (-(valTable[index] * middle * scalingFactor) + middle) } } } DispatchQueue.main.async { [unowned self] in self.setNeedsDisplay() } } } extension Waveview: CsoundBinding { func setup(_ csoundObj: CsoundObj!) { tableLoaded = false csObj = csoundObj fTableNumber = 1 } // Update F-table values from Csound func updateValuesFromCsound() { if !tableLoaded { let cs = csObj.getCsound() tableLength = Int(csoundTableLength(cs, Int32(fTableNumber))) if tableLength > 0 { table = UnsafeMutablePointer<Float>.allocate(capacity: tableLength) csoundGetTable(cs, &table, Int32(fTableNumber)) tableLoaded = true } DispatchQueue.global(qos: .background).async { [unowned self] in self.updateDisplayData() } } } }
lgpl-2.1
efa314af092939ecb3a157f094d9fef3
33.007353
111
0.612973
4.485936
false
false
false
false
cocoaswifty/iVoice
iVoice/DataService.swift
1
1723
// // DataService.swift // iVoice // // Created by jianhao on 2016/4/24. // Copyright © 2016年 cocoaSwifty. All rights reserved. // import Foundation import Firebase //DataService 類別是一個專門和 Firebase 打交道的服務類別。 //要讀寫數據,需要利用 Firebase URL 建立 Firebase 參考數據庫。 //稍後我們會把 users 和 jokes 以子節點的形式保存。 class DataService { static let dataService = DataService() private var _BASE_REF = Firebase(url: "\(BASE_URL)") private var _USER_REF = Firebase(url: "\(BASE_URL)/users") private var _JOKE_REF = Firebase(url: "\(BASE_URL)/jokes") var BASE_REF: Firebase {return _BASE_REF} var USER_REF: Firebase {return _USER_REF} var CURRENT_USER_REF: Firebase { let userID = NSUserDefaults.standardUserDefaults().valueForKey("uid") as! String let currentUser = Firebase(url: "\(BASE_REF)").childByAppendingPath("users").childByAppendingPath(userID) return currentUser! } var JOKE_REF: Firebase { return _JOKE_REF } func createNewAccount(uid: String, user: Dictionary<String, String>) { // A User is born. //保存用戶資料 USER_REF.childByAppendingPath(uid).setValue(user) } func createNewJoke(joke: Dictionary<String, AnyObject>) { // Save the Joke // JOKE_REF is the parent of the new Joke: "jokes". // childByAutoId() saves the joke and gives it its own ID. let firebaseNewJoke = JOKE_REF.childByAutoId() // setValue() saves to Firebase. firebaseNewJoke.setValue(joke) } }
apache-2.0
56b6b93c1d4f67aed2bdc906c966dfa9
27.157895
113
0.621571
3.695853
false
false
false
false
apple/swift-driver
Sources/SwiftDriver/Execution/ArgsResolver.swift
1
10326
//===--------------- ArgsResolver.swift - Argument Resolution -------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import class Foundation.NSLock import TSCBasic // <<< import func TSCBasic.withTemporaryDirectory import protocol TSCBasic.FileSystem import struct TSCBasic.AbsolutePath @_implementationOnly import Yams /// How the resolver is to handle usage of response files public enum ResponseFileHandling { case forced case disabled case heuristic } /// Resolver for a job's argument template. public final class ArgsResolver { /// The map of virtual path to the actual path. public var pathMapping: [VirtualPath: String] /// The file system used by the resolver. private let fileSystem: FileSystem /// Path to the directory that will contain the temporary files. // FIXME: We probably need a dedicated type for this... private let temporaryDirectory: VirtualPath private let lock = NSLock() public init(fileSystem: FileSystem, temporaryDirectory: VirtualPath? = nil) throws { self.pathMapping = [:] self.fileSystem = fileSystem if let temporaryDirectory = temporaryDirectory { self.temporaryDirectory = temporaryDirectory } else { // FIXME: withTemporaryDirectory uses FileManager.default, need to create a FileSystem.temporaryDirectory api. let tmpDir: AbsolutePath = try withTemporaryDirectory(removeTreeOnDeinit: false) { path in // FIXME: TSC removes empty directories even when removeTreeOnDeinit is false. This seems like a bug. try fileSystem.writeFileContents(path.appending(component: ".keep-directory")) { $0 <<< "" } return path } self.temporaryDirectory = .absolute(tmpDir) } } public func resolveArgumentList(for job: Job, useResponseFiles: ResponseFileHandling = .heuristic, quotePaths: Bool = false) throws -> [String] { let (arguments, _) = try resolveArgumentList(for: job, useResponseFiles: useResponseFiles, quotePaths: quotePaths) return arguments } public func resolveArgumentList(for job: Job, useResponseFiles: ResponseFileHandling = .heuristic, quotePaths: Bool = false) throws -> ([String], usingResponseFile: Bool) { let tool = try resolve(.path(job.tool), quotePaths: quotePaths) var arguments = [tool] + (try job.commandLine.map { try resolve($0, quotePaths: quotePaths) }) let usingResponseFile = try createResponseFileIfNeeded(for: job, resolvedArguments: &arguments, useResponseFiles: useResponseFiles) return (arguments, usingResponseFile) } @available(*, deprecated, message: "use resolveArgumentList(for:,useResponseFiles:,quotePaths:)") public func resolveArgumentList(for job: Job, forceResponseFiles: Bool, quotePaths: Bool = false) throws -> [String] { let useResponseFiles: ResponseFileHandling = forceResponseFiles ? .forced : .heuristic return try resolveArgumentList(for: job, useResponseFiles: useResponseFiles, quotePaths: quotePaths) } @available(*, deprecated, message: "use resolveArgumentList(for:,useResponseFiles:,quotePaths:)") public func resolveArgumentList(for job: Job, forceResponseFiles: Bool, quotePaths: Bool = false) throws -> ([String], usingResponseFile: Bool) { let useResponseFiles: ResponseFileHandling = forceResponseFiles ? .forced : .heuristic return try resolveArgumentList(for: job, useResponseFiles: useResponseFiles, quotePaths: quotePaths) } /// Resolve the given argument. public func resolve(_ arg: Job.ArgTemplate, quotePaths: Bool = false) throws -> String { switch arg { case .flag(let flag): return flag case .path(let path): return try lock.withLock { return try unsafeResolve(path: path, quotePaths: quotePaths) } case .responseFilePath(let path): return "@\(try resolve(.path(path), quotePaths: quotePaths))" case let .joinedOptionAndPath(option, path): return option + (try resolve(.path(path), quotePaths: quotePaths)) case let .squashedArgumentList(option: option, args: args): return try option + args.map { try resolve($0, quotePaths: quotePaths) }.joined(separator: " ") } } /// Needs to be done inside of `lock`. Marked unsafe to make that more obvious. private func unsafeResolve(path: VirtualPath, quotePaths: Bool) throws -> String { // If there was a path mapping, use it. if let actualPath = pathMapping[path] { return quotePaths ? "'\(actualPath)'" : actualPath } // Return the path from the temporary directory if this is a temporary file. if path.isTemporary { let actualPath = temporaryDirectory.appending(component: path.name) switch path { case .temporary: break // No special behavior required. case let .temporaryWithKnownContents(_, contents): // FIXME: Need a way to support this for distributed build systems... if let absolutePath = actualPath.absolutePath { try fileSystem.writeFileContents(absolutePath, bytes: .init(contents)) } case let .fileList(_, .list(items)): try createFileList(path: actualPath, contents: items) case let .fileList(_, .outputFileMap(map)): try createFileList(path: actualPath, outputFileMap: map) case .relative, .absolute, .standardInput, .standardOutput: fatalError("Not a temporary path.") } let result = actualPath.name pathMapping[path] = result return quotePaths ? "'\(result)'" : result } // Otherwise, return the path. let result = path.name pathMapping[path] = result return quotePaths ? "'\(result)'" : result } private func createFileList(path: VirtualPath, contents: [VirtualPath]) throws { // FIXME: Need a way to support this for distributed build systems... if let absPath = path.absolutePath { try fileSystem.writeFileContents(absPath) { out in for path in contents { try! out <<< unsafeResolve(path: path, quotePaths: false) <<< "\n" } } } } private func createFileList(path: VirtualPath, outputFileMap: OutputFileMap) throws { // FIXME: Need a way to support this for distributed build systems... if let absPath = path.absolutePath { // This uses Yams to escape and quote strings, but not to output the whole yaml file because // it sometimes outputs mappings in explicit block format (https://yaml.org/spec/1.2/spec.html#id2798057) // and the frontend (llvm) only seems to support implicit block format. try fileSystem.writeFileContents(absPath) { out in for (input, map) in outputFileMap.entries { out <<< quoteAndEscape(path: VirtualPath.lookup(input)) <<< ":" if map.isEmpty { out <<< " {}\n" } else { out <<< "\n" for (type, output) in map { out <<< " " <<< type.name <<< ": " <<< quoteAndEscape(path: VirtualPath.lookup(output)) <<< "\n" } } } } } } private func quoteAndEscape(path: VirtualPath) -> String { let inputNode = Node.scalar(Node.Scalar(try! unsafeResolve(path: path, quotePaths: false), Tag(.str), .doubleQuoted)) // Width parameter of -1 sets preferred line-width to unlimited so that no extraneous // line-breaks will be inserted during serialization. let string = try! Yams.serialize(node: inputNode, width: -1) // Remove the newline from the end return string.trimmingCharacters(in: .whitespacesAndNewlines) } private func createResponseFileIfNeeded(for job: Job, resolvedArguments: inout [String], useResponseFiles: ResponseFileHandling) throws -> Bool { func quote(_ string: String) -> String { return "\"\(String(string.flatMap { ["\\", "\""].contains($0) ? "\\\($0)" : "\($0)" }))\"" } guard useResponseFiles != .disabled else { return false } let forceResponseFiles = useResponseFiles == .forced if forceResponseFiles || (job.supportsResponseFiles && !commandLineFitsWithinSystemLimits(path: resolvedArguments[0], args: resolvedArguments)) { assert(!forceResponseFiles || job.supportsResponseFiles, "Platform does not support response files for job: \(job)") // Match the integrated driver's behavior, which uses response file names of the form "arguments-[0-9a-zA-Z].resp". let responseFilePath = temporaryDirectory.appending(component: "arguments-\(abs(job.hashValue)).resp") // FIXME: Need a way to support this for distributed build systems... if let absPath = responseFilePath.absolutePath { // Adopt the same technique as clang - // Wrap all arguments in double quotes to ensure that both Unix and // Windows tools understand the response file. try fileSystem.writeFileContents(absPath) { $0 <<< resolvedArguments[1...].map { quote($0) }.joined(separator: "\n") } resolvedArguments = [resolvedArguments[0], "@\(absPath.pathString)"] } return true } return false } /// Remove the temporary directory from disk. public func removeTemporaryDirectory() throws { // Only try to remove if we have an absolute path. if let absPath = temporaryDirectory.absolutePath { try fileSystem.removeFileTree(absPath) } } } fileprivate extension NSLock { /// NOTE: Keep in sync with SwiftPM's 'Sources/Basics/NSLock+Extensions.swift' /// Execute the given block while holding the lock. func withLock<T> (_ body: () throws -> T) rethrows -> T { lock() defer { unlock() } return try body() } }
apache-2.0
b111625b680b5f1a9153372dd20d5849
41.146939
147
0.658144
4.630493
false
false
false
false
practicalswift/swift
test/PrintAsObjC/accessibility.swift
16
2497
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -parse-as-library %s -typecheck -emit-objc-header-path %t/accessibility.h -disable-objc-attr-requires-foundation-module // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-PUBLIC %s < %t/accessibility.h // RUN: %check-in-clang %t/accessibility.h // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) %s -typecheck -emit-objc-header-path %t/accessibility-internal.h -disable-objc-attr-requires-foundation-module // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-INTERNAL %s < %t/accessibility-internal.h // RUN: %check-in-clang %t/accessibility-internal.h // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %s -typecheck -import-objc-header %S/../Inputs/empty.h -emit-objc-header-path %t/accessibility-imported-header.h -disable-objc-attr-requires-foundation-module // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-INTERNAL %s < %t/accessibility-imported-header.h // RUN: %check-in-clang %t/accessibility-imported-header.h // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %s -typecheck -DMAIN -emit-objc-header-path %t/accessibility-main.h -disable-objc-attr-requires-foundation-module // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-INTERNAL %s < %t/accessibility-main.h // RUN: %check-in-clang %t/accessibility-main.h // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %s -typecheck -application-extension -emit-objc-header-path %t/accessibility-appext.h -disable-objc-attr-requires-foundation-module // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-INTERNAL %s < %t/accessibility-appext.h // RUN: %check-in-clang %t/accessibility-appext.h // REQUIRES: objc_interop // CHECK-LABEL: @interface A_Public{{$}} // CHECK-INTERNAL-NEXT: init // CHECK-NEXT: @end @objc @objcMembers public class A_Public {} // CHECK-PUBLIC-NOT: B_Internal // CHECK-INTERNAL-LABEL: @interface B_Internal{{$}} // CHECK-INTERNAL-NEXT: init // CHECK-INTERNAL-NEXT: @end @objc @objcMembers internal class B_Internal {} // CHECK-NOT: C_Private @objc @objcMembers private class C_Private {} #if MAIN #if os(macOS) import AppKit @NSApplicationMain @objc class AppDelegate : NSApplicationDelegate {} #elseif os(iOS) || os(tvOS) || os(watchOS) import UIKit @UIApplicationMain @objc class AppDelegate : NSObject, UIApplicationDelegate {} #else // Uh oh, this test depends on having an app delegate. #endif #endif
apache-2.0
42c393f2ffa02f3270bcfa739223d12b
44.4
238
0.746896
3.209512
false
false
false
false
PekanMmd/Pokemon-XD-Code
Revolution Tool CL/objects/PBRScriptClass.swift
1
3192
// // PBRScriptClass.swift // Revolution Tool CL // // Created by The Steez on 26/12/2018. // import Foundation enum XGScriptFunction { case operators(String,Int,Int) case unknownOperator(Int) case known(String,Int,Int) case unknown(Int) var name : String { switch self { case .operators(let name,_,_) : return name case .unknownOperator(let val) : return "operator\(val)" case .known(let name,_,_) : return name case .unknown(let val) : return "function\(val)" } } var index : Int { switch self { case .operators(_,let val,_) : return val case .unknownOperator(let val) : return val case .known(_,let val,_) : return val case .unknown(let val) : return val } } var parameters : Int { switch self { case .operators(_,_,let val) : return val case .unknownOperator(_) : return 0 case .known(_,_,let val) : return val case .unknown : return 0 } } } enum XGScriptClass { case operators case classes(Int) var name : String { switch self { case .operators : return "Operator" case .classes(let val) : return ScriptClassNames[val] ?? "Class\(val)" } } var index : Int { switch self { case .operators : return -1 case .classes(let val) : return val } } subscript(id: Int) -> XGScriptFunction { switch self { case .operators : return operatorWithID(id) case .classes : return functionWithID(id) } } func operatorWithID(_ id: Int) -> XGScriptFunction { for (name,index,parameters) in ScriptOperators { if index == id { return .operators(name, index, parameters) } } return .unknownOperator(id) } func functionWithID(_ id: Int) -> XGScriptFunction { let info = ScriptClassFunctions[self.index] if info == nil { return .unknown(id) } for (name,index,parameters) in info! { if index == id { return .known(name, index, parameters) } } return .unknown(id) } func classDotFunction(_ id: Int) -> String { return self.name + "." + self[id].name } func functionWithName(_ name: String) -> XGScriptFunction? { let kMaxNumberOfXDSClassFunctions = 200 // theoretical limit is 0xffff but 200 is probably safe for i in 0 ..< kMaxNumberOfXDSClassFunctions { let info = self[i] if info.name.lowercased() == name.lowercased() { return info } // so old scripts can still refer to renamed functions by "function" + number if XGScriptFunction.unknown(i).name.lowercased() == name.lowercased() { return self[i] } } return nil } static func getClassNamed(_ name: String) -> XGScriptClass? { // so old scripts can still refer to renamed classes by "Class" + number if name.length > 5 { if name.substring(from: 0, to: 5) == "Class" { if let val = name.substring(from: 5, to: name.length).integerValue { if val < 127 { return XGScriptClass.classes(val) } } } } let kNumberOfXDSClasses = 100 // vanilla has max class of 60 but leave room for expansion for i in 0 ... kNumberOfXDSClasses { let info = XGScriptClass.classes(i) if info.name.lowercased() == name.lowercased() { return info } } return nil } }
gpl-2.0
33cca180f774348741c3d9a4345e4cbb
20.422819
97
0.640664
3.179283
false
false
false
false
gautamjain987/Onboard
Swift/OnboardSwift/AppDelegate.swift
6
4384
// // AppDelegate.swift // OnboardSwift // // Created by Mike on 9/11/14. // Copyright (c) 2014 Mike Amaral. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let userHasOnboardedKey = "user_has_onboarded" func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.backgroundColor = UIColor.whiteColor() application.statusBarStyle = .LightContent // Determine if the user has completed onboarding yet or not var userHasOnboardedAlready = NSUserDefaults.standardUserDefaults().boolForKey(userHasOnboardedKey); // If the user has already onboarded, setup the normal root view controller for the application // without animation like you normally would if you weren't doing any onboarding if userHasOnboardedAlready { self.setupNormalRootVC(false); } // Otherwise the user hasn't onboarded yet, so set the root view controller for the application to the // onboarding view controller generated and returned by this method. else { self.window!.rootViewController = self.generateOnboardingViewController() } self.window!.makeKeyAndVisible() return true } func generateOnboardingViewController() -> OnboardingViewController { // Generate the first page... let firstPage: OnboardingContentViewController = OnboardingContentViewController(title: "What A Beautiful Photo", body: "This city background image is so beautiful", image: UIImage(named: "blue"), buttonText: "Enable Location Services") { println("Do something here..."); } // Generate the second page... let secondPage: OnboardingContentViewController = OnboardingContentViewController(title: "I'm So Sorry", body: "I can't get over the nice blurry background photo.", image: UIImage(named: "red"), buttonText: "Connect With Facebook") { println("Do something else here..."); } // Generate the third page, and when the user hits the button we want to handle that the onboarding // process has been completed. let thirdPage: OnboardingContentViewController = OnboardingContentViewController(title: "Seriously Though", body: "Kudos to the photographer.", image: UIImage(named: "yellow"), buttonText: "Let's Get Started") { self.handleOnboardingCompletion() } // Create the onboarding controller with the pages and return it. let onboardingVC: OnboardingViewController = OnboardingViewController(backgroundImage: UIImage(named: "street"), contents: [firstPage, secondPage, thirdPage]) return onboardingVC } func handleOnboardingCompletion() { // Now that we are done onboarding, we can set in our NSUserDefaults that we've onboarded now, so in the // future when we launch the application we won't see the onboarding again. NSUserDefaults.standardUserDefaults().setBool(true, forKey: userHasOnboardedKey) // Setup the normal root view controller of the application, and set that we want to do it animated so that // the transition looks nice from onboarding to normal app. setupNormalRootVC(true) } func setupNormalRootVC(animated : Bool) { // Here I'm just creating a generic view controller to represent the root of my application. var mainVC = UIViewController() mainVC.title = "Main Application" // If we want to animate it, animate the transition - in this case we're fading, but you can do it // however you want. if animated { UIView.transitionWithView(self.window!, duration: 0.5, options:.TransitionCrossDissolve, animations: { () -> Void in self.window!.rootViewController = mainVC }, completion:nil) } // Otherwise we just want to set the root view controller normally. else { self.window?.rootViewController = mainVC; } } }
mit
0081d879aba9fd89854a7080be2c520a
44.195876
195
0.66469
5.346341
false
false
false
false
oarrabi/Guaka-Generator
Sources/guaka-cli/add.swift
1
2997
// // add.swift // Guaka // // Created by Omar Abdelhafith on 05/11/2016. // // import Guaka import FileUtils import GuakaClILib var addCommand = Command( usage: "add CommandName", configuration: configuration, run: execute) private func configuration(command: Command) { command.add(flags: [ Flag(shortName: "p", longName: "parent", value: "root", description: "Adds a new command to the Guaka project") ] ) command.longMessage = [ "Adds a new Guaka command to your Guaka project.", "", "By default the command will be added as a sub command to the root command.", "You can pass a different parent command by using the `--parent name` flag." ].joined(separator: "\n") command.shortMessage = "Add a new Guaka command to the Guaka project" command.aliases = ["command", "append"] command.example = [ " Add a new command to the root command:", " guaka add new-command", "", " Add a new command to a different parent command:", " guaka add new-command --parent other-command", " guaka add new-command -p other-command", "", " Adding a command creates a new swift file under `Sources` folder", " `guaka add sub-command` creates `Sources/sub-command.swift`" ].joined(separator: "\n") } private func execute(flags: Flags, args: [String]) { do { let name = try GeneratorParts.commandName(forPassedArgs: args) let paths = Paths.currentPaths guard paths.isGuakaDirectory else { throw GuakaError.notAGuakaProject } guard paths.isNewCommand(commandName: name) else { throw GuakaError.commandAlreadyExist(name, paths.path(forSwiftFile: name)) } let parent = flags.get(name: "parent", type: String.self) try FileOperations.addCommandOperations(paths: paths, commandName: name, parent: parent) .perform() printAddSuccess( setupFile: paths.setupSwiftFile, commandFile: paths.path(forSwiftFile: name), projectName: paths.projectName, commandName: name ) } catch let error as GuakaError { print(error.error) print("\nCheck the help for more info:") addCommand.fail(statusCode: 1) } catch { print("General error occured".f.red) print("\nCheck the help for more info:") addCommand.fail(statusCode: 1) } } private func printAddSuccess(setupFile: String, commandFile: String, projectName: String, commandName: String) { let message = [ "A new swift file with the Command has been created at:", " \(commandFile)".f.green, "", "Setup swift file has been updated at:", " \(setupFile)".f.green, "", "Next steps:", " - Build the project with `\("swift build".s.italic)`", " The binary built will be placed under `\(".build/[debug|release]/\(projectName)".s.underline)`", "", " - Test the command added, you can run it with:", " .build/debug/\(projectName) \(commandName)".s.italic, ] print(message.joined(separator: "\n")) }
mit
ddecab44677f29d6ec73d75a35692779
28.673267
115
0.660327
3.779319
false
false
false
false