repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
MaddTheSane/WWDC
refs/heads/master
WWDC/Theme.swift
bsd-2-clause
2
// // Theme.swift // WWDC // // Created by Guilherme Rambo on 18/04/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa private let _SharedThemeInstance = Theme() class Theme: NSObject { class var WWDCTheme: Theme { return _SharedThemeInstance } let separatorColor = NSColor.grayColor().colorWithAlphaComponent(0.3) let backgroundColor = NSColor.whiteColor() let fillColor = NSColor(calibratedRed: 0, green: 0.49, blue: 1, alpha: 1) private var cachedImages: [String:CGImage] = [:] private let starImageName = "star" private let starOutlineImageName = "star-outline" var starImage: CGImage { get { return getImage(starImageName) } } var starOutlineImage: CGImage { get { return getImage(starOutlineImageName) } } private func getImage(name: String) -> CGImage { if let image = cachedImages[name] { return image } else { cachedImages[name] = NSImage(named: name)?.CGImage return cachedImages[name]! } } }
e6834a6495b16e0c56a7439fe1750123
22.958333
77
0.607485
false
false
false
false
kimseongrim/KimSampleCode
refs/heads/master
UIStepper/UIStepper/ViewController.swift
gpl-2.0
1
// // ViewController.swift // UIStepper // // Created by 金成林 on 15/1/24. // Copyright (c) 2015年 Kim. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var mUIStepper: UIStepper! @IBOutlet weak var mUILabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //设定stepper的范围与起始值 mUIStepper.minimumValue = 0 mUIStepper.maximumValue = 10 mUIStepper.stepValue = 1 //设定stepper是否循环(到最大值时再增加数值最从最小值开始) mUIStepper.wraps = true //默认true,true时表示当用户按住时会持续发送ValueChange事件,false则是只有等用户交互结束时才发送ValueChange事件 mUIStepper.continuous = true //默认true,true时表示按住加号或减号不松手,数字会持续变化 mUIStepper.autorepeat = true mUIStepper.addTarget(self, action: "stepperValueIschanged", forControlEvents: UIControlEvents.ValueChanged) } func stepperValueIschanged() { // Double 转 String mUILabel.text = "\(mUIStepper.value)" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
a5f676d8af2ff0f5223f8663a18d9884
25.25
115
0.656349
false
false
false
false
zahlz/HidingNavigationBar
refs/heads/develop
HidingNavigationBarSample/HidingNavigationBarSample/HidingNavTabViewController.swift
mit
1
// // TableViewController.swift // HidingNavigationBarSample // // Created by Tristan Himmelman on 2015-05-01. // Copyright (c) 2015 Tristan Himmelman. All rights reserved. // import UIKit class HidingNavTabViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let identifier = "cell" var hidingNavBarManager: HidingNavigationBarManager? var tableView: UITableView! var toolbar: UIToolbar! override func viewDidLoad() { super.viewDidLoad() tableView = UITableView(frame: view.bounds) tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: identifier) view.addSubview(tableView) let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(HidingNavTabViewController.cancelButtonTouched)) navigationItem.leftBarButtonItem = cancelButton hidingNavBarManager = HidingNavigationBarManager(viewController: self, scrollView: tableView) if let tabBar = navigationController?.tabBarController?.tabBar { hidingNavBarManager?.manageBottomBar(tabBar) tabBar.barTintColor = UIColor(white: 230/255, alpha: 1) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) hidingNavBarManager?.viewWillAppear(animated) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() hidingNavBarManager?.viewDidLayoutSubviews() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) hidingNavBarManager?.viewWillDisappear(animated) } func cancelButtonTouched(){ navigationController?.dismiss(animated: true, completion: nil) } // MARK: UITableViewDelegate func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool { hidingNavBarManager?.shouldScrollToTop() return true } // MARK: - Table view data source func numberOfSections(in tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 100 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) // Configure the cell... cell.textLabel?.text = "row \((indexPath as NSIndexPath).row)" cell.selectionStyle = UITableViewCellSelectionStyle.none return cell } }
92c368319cdddc9d282fddfa668dab28
30.149425
149
0.745387
false
false
false
false
jackmc-xx/firefox-ios
refs/heads/master
ClientTests/TestPanels.swift
mpl-2.0
3
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import UIKit import XCTest class TestPanels: AccountTest { func testPanels() { withTestAccount { account -> Void in self.validatePrefs(account, expectOrder: nil, expectEnabled: nil); var panels = Panels(account: account) XCTAssertEqual(panels.count, 5, "Right number of panels found"); // Test moving an item var a = panels[0]; var b = panels[1]; self.expectNotification("Moving an item should notify us") { () -> Void in panels.moveItem(1, to: 0); } self.validatePrefs(account, expectOrder: ["Bookmarks", "Tabs", "History", "Reader", "Settings"], expectEnabled: [true, true, true, true, true]); XCTAssertNotEqual(a!.title, panels[0]!.title, "Original panel is not in place any more") XCTAssertEqual(a!.title, panels[1]!.title, "Original panel was moved") XCTAssertEqual(b!.title, panels[0]!.title, "Second panel was moved") self.expectNotification("Moving an item should notify us") { () -> Void in panels.moveItem(1, to: 0); } self.validatePrefs(account, expectOrder: ["Tabs", "Bookmarks", "History", "Reader", "Settings"], expectEnabled: [true, true, true, true, true]); // Tests enabling/disabling items var enabledPanels = panels.enabledItems; XCTAssertEqual(enabledPanels.count, 5, "Right number of enabled panels found"); self.expectNotification("Disabling a panel should fire a notification") { () -> Void in panels.enablePanelAt(false, position: 0); } self.validatePrefs(account, expectOrder: ["Tabs", "Bookmarks", "History", "Reader", "Settings"], expectEnabled: [false, true, true, true, true]); XCTAssertEqual(enabledPanels.count, 5, "Right number of enabled panels found"); // Still holding a old reference enabledPanels = panels.enabledItems; XCTAssertEqual(enabledPanels.count, 4, "Right number of enabled panels found"); XCTAssertEqual(panels.count, 5, "Total panels shouldn't change"); self.expectNotification("Enabling a panel should fire a notification") { () -> Void in panels.enablePanelAt(true, position: 0); } self.validatePrefs(account, expectOrder: ["Tabs", "Bookmarks", "History", "Reader", "Settings"], expectEnabled: [true, true, true, true, true]); } } private func expectNotification(description: String, method: () -> Void) { var expectation = expectationWithDescription(description) var fulfilled = false var token :AnyObject? token = NSNotificationCenter.defaultCenter().addObserverForName(PanelsNotificationName, object: nil, queue: nil) { notif in if (token != nil) { fulfilled = true NSNotificationCenter.defaultCenter().removeObserver(token!) expectation.fulfill() } else { XCTAssert(false, "notification before observer was even added?") } } method() waitForExpectationsWithTimeout(10.0, handler:nil) XCTAssertTrue(fulfilled, "Received notification of change") } private func validatePrefs<T : AnyObject>(prefs: AccountPrefs, data: [T]?, key: String) { if var data2 = prefs.arrayForKey(key) as? [T] { if (data != nil) { XCTAssertTrue(true, "Should find \(key) prefs"); } else { XCTAssertTrue(false, "Should not find \(key) prefs but did"); } } else { if (data != nil) { XCTAssertTrue(false, "Should find \(key) prefs but didn't"); } else { XCTAssertTrue(true, "Should not find \(key) prefs"); } } } private func validatePrefs(account: Account, expectOrder: [String]?, expectEnabled: [Bool]?) { let prefs = AccountPrefs(account: account)! validatePrefs(prefs, data: expectOrder, key: "PANELS_ORDER"); validatePrefs(prefs, data: expectEnabled, key: "PANELS_ENABLED"); } }
2fec99ba758aab53cfd8de552d5e8dc5
46.873684
131
0.587291
false
true
false
false
acelan/superfour2
refs/heads/master
GameBoard.swift
mit
1
// // Board.swift // SuperFour2 // // Created by AceLan Kao on 2014/6/12. // Copyright (c) 2014年 AceLan Kao. All rights reserved. // import UIKit class GameBoard : UIView { let UPPER_MARGIN: CGFloat = 200 let LEFT_MARGIN:CGFloat = 50 let RIGHT_MARGIN:CGFloat = 50 let BOTTOM_MARGIN:CGFloat = 100 let CHEESE_RADIUS: CGFloat = 25 let row: UInt = 6 let col: UInt = 7 var lastMove: Int = -1 var vcWidth: UInt var vcHeight: UInt var width: CGFloat var height: CGFloat var difficulty: UInt var board = Array<Array<UInt> >() var posBoard: Dictionary<NSIndexPath, CGPoint> init(frame: CGRect, difficulty d: UInt, w: UInt, h: UInt) { vcWidth = w vcHeight = h difficulty = d posBoard = Dictionary() width = CGFloat(vcWidth) - CGFloat(RIGHT_MARGIN) - CGFloat(LEFT_MARGIN) height = CGFloat(vcHeight) - CGFloat(BOTTOM_MARGIN) - CGFloat(UPPER_MARGIN) super.init(frame: frame) restart() } func restart() { NSLog("[%@,%d]", __FUNCTION__, __LINE__) lastMove = -1 for i in 0..col { var columnArray = Array<UInt>() for j in 0..row { columnArray.append(0) } board.append(columnArray) } posBoard.removeAll(keepCapacity: true) } override func drawRect(rect: CGRect) { var context = UIGraphicsGetCurrentContext(); UIGraphicsPushContext(context); drawBoard(rect, inContext: context); UIGraphicsPopContext(); } func drawBoard(rect: CGRect, inContext context: CGContextRef) { NSLog("[%@,%d]", __FUNCTION__, __LINE__) CGContextSetLineWidth(context, 5.0); UIColor.whiteColor().setStroke() var x = 0 var y = 0 var startX: CGFloat = CGFloat(0) + CGFloat(LEFT_MARGIN) var startY: CGFloat = 0 + CGFloat(UPPER_MARGIN) var components: CGFloat[] = [ 0.4, 0.2, 0.3, 0.3] CGContextSetFillColor(context, components) CGContextFillRect(context, rect) CGContextBeginPath(context) CGContextAddRect(context, CGRectMake(startX, startY, width, height)) CGContextStrokePath(context) CGContextSetFillColorWithColor(context, UIColor.lightGrayColor().CGColor) CGContextFillRect(context, CGRectMake(startX, startY, width, height)) CGContextSetShadow(context, CGSizeMake(7, 7), 5.0) for i in 0..col { for j in 0..row { let pt = CGPointMake( startX + CGFloat(2) * CHEESE_RADIUS + CGFloat(i) * (startX + width - CGFloat(3)*CHEESE_RADIUS)/CGFloat(7) , startY + 2 * CHEESE_RADIUS + CGFloat(j) * (startY + height - 3*CHEESE_RADIUS)/7) posBoard[ NSIndexPath(forRow: Int(i), inSection: 5 - Int(j))] = pt drawCircleAtPoint(pt, radius: CHEESE_RADIUS, inContext: context) } } } func drawCircleAtPoint(p: CGPoint, radius: CGFloat, inContext context: CGContextRef) { NSLog("[%@,%d]", __FUNCTION__, __LINE__) CGContextBeginPath(context); CGContextAddArc(context, p.x, p.y, radius, CGFloat(0), CGFloat(CDouble(2)*M_PI), 1); CGContextStrokePath(context); } func convertPositionToInteger(pt: CGPoint) -> NSInteger { NSLog("[%@,%d]", __FUNCTION__, __LINE__) var i: NSInteger = 0 while( i < 7) { let pi: CGPoint = posBoard[NSIndexPath(forRow: i, inSection: 0)]! let p1: CGPoint = posBoard[NSIndexPath(forRow: 1, inSection: 0)]! let p0: CGPoint = posBoard[NSIndexPath(forRow: 0, inSection: 0)]! if(pi.x - (p1.x - p0.x)/2 > pt.x) { break } i++ } return NSInteger(i) - 1 } func addStone(column: NSInteger) -> NSInteger { NSLog("[%@,%d]", __FUNCTION__, __LINE__) var i: NSInteger = 0 while i < 6 { if( board[ column][ i] == 0) { board[ column][ i] = 1; lastMove = column; break; } i++ } if ( i == 6) { lastMove = -1; } lastMove = column; return lastMove; } func lastStonePosition() -> CGPoint { NSLog("[%@,%d]", __FUNCTION__, __LINE__) var i: NSInteger = 0 while( i < 6) { if (board[lastMove][i] == 0) { break; } i++ } return posBoard[NSIndexPath(forRow: lastMove, inSection:i-1)]! } func isAValidPosition(pt: CGPoint) -> Bool { NSLog("[%@,%d]", __FUNCTION__, __LINE__) if (pt.y > UPPER_MARGIN) { return false } if (pt.x < LEFT_MARGIN || pt.x > RIGHT_MARGIN + width) { return false } // the column is not full yet var i: NSInteger = 0 var column = convertPositionToInteger(pt) while( i < 6) { if( board[ column][ i] == 0) { return true } i++ } if ( i == 6 ) { return false } return true; } }
86ebcbf1c4ca133b9adab58a9c8a07a1
30.224852
143
0.528141
false
false
false
false
lexicalparadox/Chirppy
refs/heads/master
Chirppy/TimelineTweetCell.swift
apache-2.0
1
// // TimelineTweetCell.swift // Chirppy // // Created by Alexander Doan on 9/26/17. // Copyright © 2017 Alexander Doan. All rights reserved. // import UIKit import SwiftDate class TimelineTweetCell: UITableViewCell { @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var retweetedByImage: UIImageView! @IBOutlet weak var retweetedByLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var tweetLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var replyButton: UIImageView! @IBOutlet weak var retweetButton: UIImageView! @IBOutlet weak var favoriteButton: UIImageView! @IBOutlet weak var replyCountLabel: UILabel! @IBOutlet weak var retweetCountLabel: UILabel! @IBOutlet weak var favoriteCountLabel: UILabel! let retweet = UIImage(named: "retweet.png") let favorite = UIImage(named: "favorite.png") let heartEmpty = UIImage(named: "heart_empty.png") let heartFilled = UIImage(named: "heart_filled_2.png") let retweetGreen = UIImage(named: "retweet_green.png") let client = TwitterClient.sharedInstance var tweet: Tweet! { didSet { profileImageView.setImageWith(URL(string: (tweet.user?.profileImageUrl)!)!) nameLabel.text = tweet.user?.name ?? "Default name" usernameLabel.text = String(format: "@%@", tweet.user?.screenName ?? "@Default screen name") tweetLabel.text = tweet.text ?? "Default tweet, because I wasn't able to find an actual tweet for this user!" let createdAtDate = tweet.createdAtDate! let formattedDate = createdAtDate.string(custom: "MM/dd/yy h:mm a") dateLabel.text = formattedDate // dateLabel.text = tweet.createdAt ?? "10 Nov 1988" // let now = Date() // let minutesAgo = now.compare(to: tweet.createdAtDate!, in: Region.Local(), granularity: .minute).rawValue // dateLabel.text = String(format: "%d m ago", minutesAgo) //?? "10 Nov 1988" if tweet.wasRetweeted { self.retweetedByImage.isHidden = false self.retweetedByLabel.isHidden = false self.retweetedByLabel.text = String(format: "@%@ retweeted", tweet.retweetedByUser?.screenName ?? "Codepath") self.retweetedByLabel.sizeToFit() } else { self.retweetedByImage.isHidden = true self.retweetedByLabel.isHidden = true self.retweetedByLabel.text = nil } if tweet.favorited ?? false { self.favoriteButton.image = heartFilled } else { self.favoriteButton.image = favorite } if tweet.retweeted ?? false { self.retweetButton.image = retweetGreen } else { self.retweetButton.image = retweet } } } override func awakeFromNib() { super.awakeFromNib() profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2 profileImageView.clipsToBounds = true tweetLabel.sizeToFit() // tapping reply, retweet, favorite images let retweetTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(TimelineTweetCell.retweetImageTapped(tapGestureRecognizer:))) self.retweetButton.isUserInteractionEnabled = true self.retweetButton.addGestureRecognizer(retweetTapRecognizer) let favoriteTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(TimelineTweetCell.favoriteImageTapped(tapGestureRecognizer:))) self.favoriteButton.isUserInteractionEnabled = true self.favoriteButton.addGestureRecognizer(favoriteTapRecognizer) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func retweetImageTapped(tapGestureRecognizer: UITapGestureRecognizer) { self.retweetButton.image = retweetGreen client.postRetweet(tweetId: self.tweet.id!, success: { self.tweet.retweeted = true print("Successfully retweeted for user: \(self.tweet.user?.screenName) and tweetId: \(self.tweet.id)") }) { (error: Error) in print(error) } } func favoriteImageTapped(tapGestureRecognizer: UITapGestureRecognizer) { self.favoriteButton.image = heartFilled var parameters = [String:String]() parameters["id"] = String(format: "%ld", tweet.id!) client.postFavorite(queryParameters: parameters, success: { self.tweet.favorited = true print("Successfully favorited a tweet for user: \(self.tweet.user?.screenName) and tweetId: \(self.tweet.id)") }) { (error: Error) in print(error) } } }
4b3240f0d55673d071722e8bbc7033ab
39.752
153
0.638987
false
false
false
false
FuckBoilerplate/OkDataSources
refs/heads/master
DemoClass/RxSwiftProject/Pods/RxSwift/RxSwift/Traits/Maybe.swift
apache-2.0
6
// // Maybe.swift // RxSwift // // Created by sergdort on 19/08/2017. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // #if DEBUG import Foundation #endif /// Sequence containing 0 or 1 elements public enum MaybeTrait { } /// Represents a push style sequence containing 0 or 1 element. public typealias Maybe<Element> = PrimitiveSequence<MaybeTrait, Element> public enum MaybeEvent<Element> { /// One and only sequence element is produced. (underlying observable sequence emits: `.next(Element)`, `.completed`) case success(Element) /// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`) case error(Swift.Error) /// Sequence completed successfully. case completed } public extension PrimitiveSequenceType where TraitType == MaybeTrait { public typealias MaybeObserver = (MaybeEvent<ElementType>) -> () /** Creates an observable sequence from a specified subscribe method implementation. - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. - returns: The observable sequence with the specified implementation for the `subscribe` method. */ public static func create(subscribe: @escaping (@escaping MaybeObserver) -> Disposable) -> PrimitiveSequence<TraitType, ElementType> { let source = Observable<ElementType>.create { observer in return subscribe { event in switch event { case .success(let element): observer.on(.next(element)) observer.on(.completed) case .error(let error): observer.on(.error(error)) case .completed: observer.on(.completed) } } } return PrimitiveSequence(raw: source) } /** Subscribes `observer` to receive events for this sequence. - returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources. */ public func subscribe(_ observer: @escaping (MaybeEvent<ElementType>) -> ()) -> Disposable { var stopped = false return self.primitiveSequence.asObservable().subscribe { event in if stopped { return } stopped = true switch event { case .next(let element): observer(.success(element)) case .error(let error): observer(.error(error)) case .completed: observer(.completed) } } } /** Subscribes a success handler, an error handler, and a completion handler for this sequence. - parameter onSuccess: Action to invoke for each element in the observable sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ public func subscribe(onSuccess: ((ElementType) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil) -> Disposable { #if DEBUG let callStack = Hooks.recordCallStackOnError ? Thread.callStackSymbols : [] #else let callStack = [String]() #endif return self.primitiveSequence.subscribe { event in switch event { case .success(let element): onSuccess?(element) case .error(let error): if let onError = onError { onError(error) } else { Hooks.defaultErrorHandler(callStack, error) } case .completed: onCompleted?() } } } } public extension PrimitiveSequenceType where TraitType == MaybeTrait { /** Returns an observable sequence that contains a single element. - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) - parameter element: Single element in the resulting observable sequence. - returns: An observable sequence containing the single specified element. */ public static func just(_ element: ElementType) -> Maybe<ElementType> { return Maybe(raw: Observable.just(element)) } /** Returns an observable sequence that contains a single element. - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) - parameter element: Single element in the resulting observable sequence. - parameter scheduler: Scheduler to send the single element on. - returns: An observable sequence containing the single specified element. */ public static func just(_ element: ElementType, scheduler: ImmediateSchedulerType) -> Maybe<ElementType> { return Maybe(raw: Observable.just(element, scheduler: scheduler)) } /** Returns an observable sequence that terminates with an `error`. - seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: The observable sequence that terminates with specified error. */ public static func error(_ error: Swift.Error) -> Maybe<ElementType> { return PrimitiveSequence(raw: Observable.error(error)) } /** Returns a non-terminating observable sequence, which can be used to denote an infinite duration. - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: An observable sequence whose observers will never get called. */ public static func never() -> Maybe<ElementType> { return PrimitiveSequence(raw: Observable.never()) } /** Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. - seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: An observable sequence with no elements. */ public static func empty() -> Maybe<ElementType> { return Maybe(raw: Observable.empty()) } } public extension PrimitiveSequenceType where TraitType == MaybeTrait { /** Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) - parameter onNext: Action to invoke for each element in the observable sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. - returns: The source sequence with the side-effecting behavior applied. */ public func `do`(onNext: ((ElementType) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> ())? = nil, onSubscribed: (() -> ())? = nil, onDispose: (() -> ())? = nil) -> Maybe<ElementType> { return Maybe(raw: primitiveSequence.source.do( onNext: onNext, onError: onError, onCompleted: onCompleted, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose) ) } /** Filters the elements of an observable sequence based on a predicate. - seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html) - parameter predicate: A function to test each source element for a condition. - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. */ public func filter(_ predicate: @escaping (ElementType) throws -> Bool) -> Maybe<ElementType> { return Maybe(raw: primitiveSequence.source.filter(predicate)) } /** Projects each element of an observable sequence into a new form. - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) - parameter transform: A transform function to apply to each source element. - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. */ public func map<R>(_ transform: @escaping (ElementType) throws -> R) -> Maybe<R> { return Maybe(raw: primitiveSequence.source.map(transform)) } /** Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) - parameter selector: A transform function to apply to each element. - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. */ public func flatMap<R>(_ selector: @escaping (ElementType) throws -> Maybe<R>) -> Maybe<R> { return Maybe<R>(raw: primitiveSequence.source.flatMap(selector)) } /** Emits elements from the source observable sequence, or a default element if the source observable sequence is empty. - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) - parameter default: Default element to be sent if the source does not emit any elements - returns: An observable sequence which emits default element end completes in case the original sequence is empty */ public func ifEmpty(default: ElementType) -> Single<ElementType> { return Single(raw: primitiveSequence.source.ifEmpty(default: `default`)) } /** Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty. - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) - parameter switchTo: Observable sequence being returned when source sequence is empty. - returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements. */ public func ifEmpty(switchTo other: Maybe<ElementType>) -> Maybe<ElementType> { return Maybe(raw: primitiveSequence.source.ifEmpty(switchTo: other.primitiveSequence.source)) } /** Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty. - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) - parameter switchTo: Observable sequence being returned when source sequence is empty. - returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements. */ public func ifEmpty(switchTo other: Single<ElementType>) -> Single<ElementType> { return Single(raw: primitiveSequence.source.ifEmpty(switchTo: other.primitiveSequence.source)) } /** Continues an observable sequence that is terminated by an error with a single element. - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) - parameter element: Last element in an observable sequence in case error occurs. - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. */ public func catchErrorJustReturn(_ element: ElementType) -> PrimitiveSequence<TraitType, ElementType> { return PrimitiveSequence(raw: primitiveSequence.source.catchErrorJustReturn(element)) } }
23eb3bb9e3ddb2436fabd544eb7142b1
43.204778
220
0.669704
false
false
false
false
JohnPJenkins/swift-t
refs/heads/master
stc/tests/686-app-soft-target.swift
apache-2.0
4
// Test app location dispatch import assert; import files; import io; import string; import location; app (file o) hostname() { "hostname" @stdout=o; } (string o) extract_hostname(file f) { o = trim(read(f)); } main { foreach i in [1:500] { string host1 = extract_hostname(hostname()); string host2 = extract_hostname(@soft_location=hostmap_one_worker(host1) hostname()); printf("Hostname %i: %s", i, host2); } }
109a0421e31f8340ae008a3f174dcde5
18
89
0.661327
false
false
false
false
BlenderSleuth/Circles
refs/heads/master
Circles/SKTUtils/SKNode+Extensions.swift
gpl-3.0
1
/* * Copyright (c) 2013-2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import SpriteKit public extension SKNode { /** Lets you treat the node's scale as a CGPoint value. */ public var scaleAsPoint: CGPoint { get { return CGPoint(x: xScale, y: yScale) } set { xScale = newValue.x yScale = newValue.y } } /** * Runs an action on the node that performs a closure or function after * a given time. */ public func afterDelay(_ delay: TimeInterval, runBlock block: @escaping () -> ()) { run(SKAction.sequence([SKAction.wait(forDuration: delay), SKAction.run(block)])) } /** * Makes this node the frontmost node in its parent. */ public func bringToFront() { if let parent = self.parent{ removeFromParent() parent.addChild(self) } } /** * Orients the node in the direction that it is moving by tweening its * rotation angle. This assumes that at 0 degrees the node is facing up. * * @param velocity The current speed and direction of the node. You can get * this from node.physicsBody.velocity. * @param rate How fast the node rotates. Must have a value between 0.0 and * 1.0, where smaller means slower; 1.0 is instantaneous. */ public func rotateToVelocity(_ velocity: CGVector, rate: CGFloat) { // Determine what the rotation angle of the node ought to be based on the // current velocity of its physics body. This assumes that at 0 degrees the // node is pointed up, not to the right, so to compensate we subtract π/4 // (90 degrees) from the calculated angle. let newAngle = atan2(velocity.dy, velocity.dx) - π/2 // This always makes the node rotate over the shortest possible distance. // Because the range of atan2() is -180 to 180 degrees, a rotation from, // -170 to -190 would otherwise be from -170 to 170, which makes the node // rotate the wrong way (and the long way) around. We adjust the angle to // go from 190 to 170 instead, which is equivalent to -170 to -190. if newAngle - zRotation > π { zRotation += π * 2.0 } else if zRotation - newAngle > π { zRotation -= π * 2.0 } // Use the "standard exponential slide" to slowly tween zRotation to the // new angle. The greater the value of rate, the faster this goes. zRotation += (newAngle - zRotation) * rate } }
326a1be7e157cb8787ed197c00eb5881
38.609195
85
0.692107
false
false
false
false
aaronraimist/firefox-ios
refs/heads/master
Sync/Synchronizers/LoginsSynchronizer.swift
mpl-2.0
3
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger private let log = Logger.syncLogger let PasswordsStorageVersion = 1 private func makeDeletedLoginRecord(guid: GUID) -> Record<LoginPayload> { // Local modified time is ignored in upload serialization. let modified: Timestamp = 0 // Arbitrary large number: deletions sync down first. let sortindex = 5_000_000 let json: JSON = JSON([ "id": guid, "deleted": true, ]) let payload = LoginPayload(json) return Record<LoginPayload>(id: guid, payload: payload, modified: modified, sortindex: sortindex) } func makeLoginRecord(login: Login) -> Record<LoginPayload> { let id = login.guid let modified: Timestamp = 0 // Ignored in upload serialization. let sortindex = 1 let tLU = NSNumber(unsignedLongLong: login.timeLastUsed / 1000) let tPC = NSNumber(unsignedLongLong: login.timePasswordChanged / 1000) let tC = NSNumber(unsignedLongLong: login.timeCreated / 1000) let dict: [String: AnyObject] = [ "id": id, "hostname": login.hostname, "httpRealm": login.httpRealm ?? JSON.null, "formSubmitURL": login.formSubmitURL ?? JSON.null, "username": login.username ?? "", "password": login.password, "usernameField": login.usernameField ?? "", "passwordField": login.passwordField ?? "", "timesUsed": login.timesUsed, "timeLastUsed": tLU, "timePasswordChanged": tPC, "timeCreated": tC, ] let payload = LoginPayload(JSON(dict)) return Record<LoginPayload>(id: id, payload: payload, modified: modified, sortindex: sortindex) } /** * Our current local terminology ("logins") has diverged from the terminology in * use when Sync was built ("passwords"). I've done my best to draw a reasonable line * between the server collection/record format/etc. and local stuff: local storage * works with logins, server records and collection are passwords. */ public class LoginsSynchronizer: IndependentRecordSynchronizer, Synchronizer { public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs) { super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, collection: "passwords") } override var storageVersion: Int { return PasswordsStorageVersion } func getLogin(record: Record<LoginPayload>) -> ServerLogin { let guid = record.id let payload = record.payload let modified = record.modified let login = ServerLogin(guid: guid, hostname: payload.hostname, username: payload.username, password: payload.password, modified: modified) login.formSubmitURL = payload.formSubmitURL login.httpRealm = payload.httpRealm login.usernameField = payload.usernameField login.passwordField = payload.passwordField // Microseconds locally, milliseconds remotely. We should clean this up. login.timeCreated = 1000 * (payload.timeCreated ?? 0) login.timeLastUsed = 1000 * (payload.timeLastUsed ?? 0) login.timePasswordChanged = 1000 * (payload.timePasswordChanged ?? 0) login.timesUsed = payload.timesUsed ?? 0 return login } func applyIncomingToStorage(storage: SyncableLogins, records: [Record<LoginPayload>], fetched: Timestamp) -> Success { return self.applyIncomingToStorage(records, fetched: fetched) { rec in let guid = rec.id let payload = rec.payload guard payload.isValid() else { log.warning("Login record \(guid) is invalid. Skipping.") return succeed() } // We apply deletions immediately. That might not be exactly what we want -- perhaps you changed // a password locally after deleting it remotely -- but it's expedient. if payload.deleted { return storage.deleteByGUID(guid, deletedAt: rec.modified) } return storage.applyChangedLogin(self.getLogin(rec)) } } private func uploadModifiedLogins(logins: [Login], lastTimestamp: Timestamp, fromStorage storage: SyncableLogins, withServer storageClient: Sync15CollectionClient<LoginPayload>) -> DeferredTimestamp { return self.uploadRecords(logins.map(makeLoginRecord), by: 50, lastTimestamp: lastTimestamp, storageClient: storageClient) { storage.markAsSynchronized($0.success, modified: $0.modified) } } private func uploadDeletedLogins(guids: [GUID], lastTimestamp: Timestamp, fromStorage storage: SyncableLogins, withServer storageClient: Sync15CollectionClient<LoginPayload>) -> DeferredTimestamp { let records = guids.map(makeDeletedLoginRecord) // Deletions are smaller, so upload 100 at a time. return self.uploadRecords(records, by: 100, lastTimestamp: lastTimestamp, storageClient: storageClient) { storage.markAsDeleted($0.success) >>> always($0.modified) } } // Find any records for which a local overlay exists. If we want to be really precise, // we can find the original server modified time for each record and use it as // If-Unmodified-Since on a PUT, or just use the last fetch timestamp, which should // be equivalent. // We will already have reconciled any conflicts on download, so this upload phase should // be as simple as uploading any changed or deleted items. private func uploadOutgoingFromStorage(storage: SyncableLogins, lastTimestamp: Timestamp, withServer storageClient: Sync15CollectionClient<LoginPayload>) -> Success { let uploadDeleted: Timestamp -> DeferredTimestamp = { timestamp in storage.getDeletedLoginsToUpload() >>== { guids in return self.uploadDeletedLogins(guids, lastTimestamp: timestamp, fromStorage: storage, withServer: storageClient) } } let uploadModified: Timestamp -> DeferredTimestamp = { timestamp in storage.getModifiedLoginsToUpload() >>== { logins in return self.uploadModifiedLogins(logins, lastTimestamp: timestamp, fromStorage: storage, withServer: storageClient) } } return deferMaybe(lastTimestamp) >>== uploadDeleted >>== uploadModified >>> effect({ log.debug("Done syncing.") }) >>> succeed } public func synchronizeLocalLogins(logins: SyncableLogins, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult { if let reason = self.reasonToNotSync(storageClient) { return deferMaybe(.NotStarted(reason)) } let encoder = RecordEncoder<LoginPayload>(decode: { LoginPayload($0) }, encode: { $0 }) guard let passwordsClient = self.collectionClient(encoder, storageClient: storageClient) else { log.error("Couldn't make logins factory.") return deferMaybe(FatalError(message: "Couldn't make logins factory.")) } let since: Timestamp = self.lastFetched log.debug("Synchronizing \(self.collection). Last fetched: \(since).") let applyIncomingToStorage: StorageResponse<[Record<LoginPayload>]> -> Success = { response in let ts = response.metadata.timestampMilliseconds let lm = response.metadata.lastModifiedMilliseconds! log.debug("Applying incoming password records from response timestamped \(ts), last modified \(lm).") log.debug("Records header hint: \(response.metadata.records)") return self.applyIncomingToStorage(logins, records: response.value, fetched: lm) >>> effect { NSNotificationCenter.defaultCenter().postNotificationName(NotificationDataRemoteLoginChangesWereApplied, object: nil) } } return passwordsClient.getSince(since) >>== applyIncomingToStorage // TODO: If we fetch sorted by date, we can bump the lastFetched timestamp // to the last successfully applied record timestamp, no matter where we fail. // There's no need to do the upload before bumping -- the storage of local changes is stable. >>> { self.uploadOutgoingFromStorage(logins, lastTimestamp: 0, withServer: passwordsClient) } >>> { return deferMaybe(.Completed) } } }
94ff40a4b38b09a985b0a48834c3564a
45.489247
204
0.67561
false
false
false
false
IvoPaunov/selfie-apocalypse
refs/heads/master
Selfie apocalypse/Selfie apocalypse/Utils.swift
mit
1
// // Utils.swift // Selfie apocalypse // // Created by Ivko on 2/5/16. // Copyright © 2016 Ivo Paounov. All rights reserved. // import Foundation public class Utils { func setTimeout(delay:NSTimeInterval, block:()->Void) -> NSTimer { return NSTimer.scheduledTimerWithTimeInterval(delay, target: NSBlockOperation(block: block), selector: "main", userInfo: nil, repeats: false) } func setInterval(interval:NSTimeInterval, block:()->Void) -> NSTimer { return NSTimer.scheduledTimerWithTimeInterval(interval, target: NSBlockOperation(block: block), selector: "main", userInfo: nil, repeats: true) } func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage { let size = image.size let widthRatio = targetSize.width / image.size.width let heightRatio = targetSize.height / image.size.height // Figure out what our orientation is, and use that to form the rectangle var newSize: CGSize if(widthRatio > heightRatio) { newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio) } else { newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio) } // This is the rect that we've calculated out and this is what is actually used below let rect = CGRectMake(0, 0, newSize.width, newSize.height) // Actually do the resizing to the rect using the ImageContext stuff UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.drawInRect(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } }
04a01038916b27398c4cccbd5906ba32
36.891304
151
0.65729
false
false
false
false
fitpay/fitpay-ios-sdk
refs/heads/develop
FitpaySDK/Rest/Models/Commit/ApduCommand.swift
mit
1
import Foundation open class APDUCommand: NSObject, Serializable, APDUResponseProtocol { open var commandId: String? open var groupId: Int = 0 open var sequence: Int = 0 open var command: String? open var type: String? open var continueOnFailure: Bool = false open var responseData: Data? open var responseDictionary: [String: Any] { var dic: [String: Any] = [:] if let commandId = commandId { dic["commandId"] = commandId } if let responseCode = responseCode { dic["responseCode"] = responseCode.hex } if let responseData = responseData { dic["responseData"] = responseData.hex } return dic } private enum CodingKeys: String, CodingKey { case commandId case groupId case sequence case command case type case continueOnFailure } // MARK: - Lifecycle public override init() { super.init() } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) commandId = try? container.decode(.commandId) groupId = try container.decodeIfPresent(Int.self, forKey: .groupId) ?? 0 sequence = try container.decodeIfPresent(Int.self, forKey: .sequence) ?? 0 command = try? container.decode(.command) type = try? container.decode(.type) continueOnFailure = try container.decodeIfPresent(Bool.self, forKey: .continueOnFailure) ?? false } }
3d3abf0ed10795c68db0766e5db5f0b1
27.275862
105
0.597561
false
false
false
false
mislavjavor/Kandinsky
refs/heads/master
Sources/Canvas.swift
mit
1
// // Canvas.swift // Kandinsky // // Created by Mislav Javor on 26/04/2017. // Copyright © 2017 Mislav Javor. All rights reserved. // import Foundation import UIKit public typealias ControllerInjectedHandler = (ViewHolder) -> () public protocol Canvas: class { var deferToAfterRender: [ControllerInjectedHandler] { get set } associatedtype UIKitRepresentation: UIView var view: UIKitRepresentation { get } var children: [AnyCanvas] { get set } var id: String? { get set } init() } extension Canvas { func eraseType() -> AnyCanvas { return AnyCanvas(self) } func insert<T: Canvas>(into canvas: inout T) { canvas.children.append(AnyCanvas(self)) } public typealias Creator = (inout Self) -> Void public static func make(_ maker: Creator) -> Self { var this = Self() maker(&this) return this } public typealias Maker = (inout Self) -> Void public func add(_ maker: Maker) -> Self { var this = self maker(&this) return this } } //extension Array where Element: Canvas { // public typealias Customizer = (inout Element) -> Void // public mutating func customize(_ customizer: Customizer) { // for i in 0..<self.count { // customizer(&self[i]) // } // } //}
3bc84e57af30673f13084147d6b055dc
20.968254
67
0.595376
false
false
false
false
lpniuniu/bookmark
refs/heads/master
bookmark/bookmark/BookSearchViewController/BookSearchTableView.swift
mit
1
// // BookSearchTableView.swift // bookmark // // Created by familymrfan on 17/1/6. // Copyright © 2017年 niuniu. All rights reserved. // import UIKit import Alamofire import Kingfisher import Bulb import RealmSwift import Toast_Swift import Crashlytics class BookSearchTableView: UITableView, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate { let cellIdentifier:String = "book_search_cellIdentifier" let searchBar:UISearchBar = UISearchBar() var searchData:Array = [NSDictionary]() override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) delegate = self dataSource = self register(BookSearchCell.self, forCellReuseIdentifier: cellIdentifier) searchBar.delegate = self searchBar.placeholder = "输入要检索的书名" tableHeaderView = searchBar weak var weakSelf = self Bulb.bulbGlobal().register(BookSearchCellAddBookButtonClickSignal.signalDefault()) { (cell:Any?, identifier2Signal:[String:BulbSignal]?) -> Bool in guard let index:IndexPath = self.indexPath(for: cell as! BookSearchCell) else { return false } let book = weakSelf?.searchData[index.row] let newbook = BookData() newbook.name = (book?.object(forKey: "title") as? String)! newbook.pageTotal = Int((book?.object(forKey: "pages") as? String)!)! newbook.photoUrl = book?.object(forKey: "image") as? String newbook.serverId = (book?.object(forKey: "id") as? String)! let realm = try! Realm() let result = realm.objects(BookData.self).filter("done == false").filter("serverId == '\(newbook.serverId)'") if result.count == 0 { try! realm.write { realm.add(newbook) } Bulb.bulbGlobal().fire(BookSavedSignal.signalDefault(), data: newbook) } (cell as! BookSearchCell).makeToast("\(newbook.name)已加入阅读列表") return true } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() searchBar.frame = CGRect(x: 0, y: 0, width: frame.width, height: 40) } // MARK: tableview delegate func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchData.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 200 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:BookSearchCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! BookSearchCell let book = searchData[indexPath.row] let url = URL(string: book.object(forKey: "image") as! String) cell.bookImageView.kf.setImage(with: url) cell.nameLabel.text = book.object(forKey: "title") as? String cell.pageLabel.text = book.object(forKey: "pages") as? String cell.addBookButton.bk_(whenTapped: { Bulb.bulbGlobal().fire(BookSearchCellAddBookButtonClickSignal.signalDefault(), data: cell) }) return cell } // MARK: search bar delegate func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { print("\(searchBar.text)") if let text = searchBar.text { Answers.logSearch(withQuery: text, customAttributes: [:]) } if let searchText = searchBar.text?.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { Alamofire.request("https://api.douban.com/v2/book/search?q=\(searchText)").responseJSON { (response:DataResponse<Any>) in guard response.result.isSuccess else { return } guard let json = response.result.value as? NSDictionary else { return } guard let books = json.object(forKey: "books") as? NSArray else { return } self.searchData.removeAll() for book in books { guard let book = book as? NSDictionary else { continue } guard let bookName = book.object(forKey: "title") as! String?, bookName != "" else { continue } guard let bookPage = book.object(forKey: "pages") as! String?, Int(bookPage) != nil else { continue } guard let bookImage = book.object(forKey: "image") as! String?, bookImage != "" else { continue } guard let bookId = book.object(forKey: "id") as! String?, bookId != "" else { continue } self.searchData.append(book) } self.reloadData() self.endEditing(true) } } } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
5d72cbc65bd55ee684f016f277ea18ff
36.753333
155
0.572311
false
false
false
false
amosavian/swift-corelibs-foundation
refs/heads/master
Foundation/NSCFArray.swift
apache-2.0
6
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation internal final class _NSCFArray : NSMutableArray { deinit { _CFDeinit(self) _CFZeroUnsafeIvars(&_storage) } required init(coder: NSCoder) { fatalError() } required init(objects: UnsafePointer<AnyObject>!, count cnt: Int) { fatalError() } required public convenience init(arrayLiteral elements: Any...) { fatalError() } override var count: Int { return CFArrayGetCount(_cfObject) } override func object(at index: Int) -> Any { let value = CFArrayGetValueAtIndex(_cfObject, index) return _SwiftValue.fetch(nonOptional: unsafeBitCast(value, to: AnyObject.self)) } override func insert(_ value: Any, at index: Int) { let anObject = _SwiftValue.store(value) CFArrayInsertValueAtIndex(_cfMutableObject, index, unsafeBitCast(anObject, to: UnsafeRawPointer.self)) } override func removeObject(at index: Int) { CFArrayRemoveValueAtIndex(_cfMutableObject, index) } override var classForCoder: AnyClass { return NSMutableArray.self } } internal func _CFSwiftArrayGetCount(_ array: AnyObject) -> CFIndex { return (array as! NSArray).count } internal func _CFSwiftArrayGetValueAtIndex(_ array: AnyObject, _ index: CFIndex) -> Unmanaged<AnyObject> { let arr = array as! NSArray if type(of: array) === NSArray.self || type(of: array) === NSMutableArray.self { return Unmanaged.passUnretained(arr._storage[index]) } else { let value = _SwiftValue.store(arr.object(at: index)) let container: NSMutableDictionary if arr._storage.isEmpty { container = NSMutableDictionary() arr._storage.append(container) } else { container = arr._storage[0] as! NSMutableDictionary } container[NSNumber(value: index)] = value return Unmanaged.passUnretained(value) } } internal func _CFSwiftArrayGetValues(_ array: AnyObject, _ range: CFRange, _ values: UnsafeMutablePointer<Unmanaged<AnyObject>?>) { let arr = array as! NSArray if type(of: array) === NSArray.self || type(of: array) === NSMutableArray.self { for idx in 0..<range.length { values[idx] = Unmanaged.passUnretained(arr._storage[idx + range.location]) } } else { for idx in 0..<range.length { let index = idx + range.location let value = _SwiftValue.store(arr.object(at: index)) let container: NSMutableDictionary if arr._storage.isEmpty { container = NSMutableDictionary() arr._storage.append(container) } else { container = arr._storage[0] as! NSMutableDictionary } container[NSNumber(value: index)] = value values[idx] = Unmanaged.passUnretained(value) } } } internal func _CFSwiftArrayAppendValue(_ array: AnyObject, _ value: AnyObject) { (array as! NSMutableArray).add(value) } internal func _CFSwiftArraySetValueAtIndex(_ array: AnyObject, _ value: AnyObject, _ idx: CFIndex) { (array as! NSMutableArray).replaceObject(at: idx, with: value) } internal func _CFSwiftArrayReplaceValueAtIndex(_ array: AnyObject, _ idx: CFIndex, _ value: AnyObject) { (array as! NSMutableArray).replaceObject(at: idx, with: value) } internal func _CFSwiftArrayInsertValueAtIndex(_ array: AnyObject, _ idx: CFIndex, _ value: AnyObject) { (array as! NSMutableArray).insert(value, at: idx) } internal func _CFSwiftArrayExchangeValuesAtIndices(_ array: AnyObject, _ idx1: CFIndex, _ idx2: CFIndex) { (array as! NSMutableArray).exchangeObject(at: idx1, withObjectAt: idx2) } internal func _CFSwiftArrayRemoveValueAtIndex(_ array: AnyObject, _ idx: CFIndex) { (array as! NSMutableArray).removeObject(at: idx) } internal func _CFSwiftArrayRemoveAllValues(_ array: AnyObject) { (array as! NSMutableArray).removeAllObjects() } internal func _CFSwiftArrayReplaceValues(_ array: AnyObject, _ range: CFRange, _ newValues: UnsafeMutablePointer<Unmanaged<AnyObject>>, _ newCount: CFIndex) { NSUnimplemented() // (array as! NSMutableArray).replaceObjectsInRange(NSMakeRange(range.location, range.length), withObjectsFromArray: newValues.array(newCount)) }
40abd398f740588feb0124f22b9eaa7d
35.230769
158
0.669002
false
false
false
false
brianjmoore/material-components-ios
refs/heads/develop
components/AppBar/examples/AppBarDelegateForwardingExample.swift
apache-2.0
2
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import MaterialComponents // This example builds upon AppBarTypicalUseExample. class AppBarDelegateForwardingExample: UITableViewController { let appBar = MDCAppBar() convenience init() { self.init(style: .plain) } override init(style: UITableViewStyle) { super.init(style: style) self.appBar.navigationBar.tintColor = UIColor.white appBar.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.white ] self.addChildViewController(appBar.headerViewController) self.title = "Delegate Forwarding" let color = UIColor(white: 0.2, alpha:1) appBar.headerViewController.headerView.backgroundColor = color let mutator = MDCAppBarTextColorAccessibilityMutator() mutator.mutate(appBar) } override func viewDidLoad() { super.viewDidLoad() // UITableViewController's tableView.delegate is self by default. We're setting it here for // emphasis. self.tableView.delegate = self appBar.headerViewController.headerView.trackingScrollView = self.tableView appBar.addSubviewsToParent() self.tableView.layoutMargins = UIEdgeInsets.zero self.tableView.separatorInset = UIEdgeInsets.zero } // The following four methods must be forwarded to the tracking scroll view in order to implement // the Flexible Header's behavior. override func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == self.appBar.headerViewController.headerView.trackingScrollView { self.appBar.headerViewController.headerView.trackingScrollDidScroll() } } override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == self.appBar.headerViewController.headerView.trackingScrollView { self.appBar.headerViewController.headerView.trackingScrollDidEndDecelerating() } } override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { let headerView = self.appBar.headerViewController.headerView if scrollView == headerView.trackingScrollView { headerView.trackingScrollDidEndDraggingWillDecelerate(decelerate) } } override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let headerView = self.appBar.headerViewController.headerView if scrollView == headerView.trackingScrollView { headerView.trackingScrollWillEndDragging(withVelocity: velocity, targetContentOffset: targetContentOffset) } } // MARK: Typical setup override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.title = "Delegate Forwarding (Swift)" self.addChildViewController(appBar.headerViewController) let color = UIColor( red: CGFloat(0x03) / CGFloat(255), green: CGFloat(0xA9) / CGFloat(255), blue: CGFloat(0xF4) / CGFloat(255), alpha: 1) appBar.headerViewController.headerView.backgroundColor = color appBar.navigationBar.tintColor = UIColor.white } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } // MARK: Catalog by convention extension AppBarDelegateForwardingExample { @objc class func catalogBreadcrumbs() -> [String] { return ["App Bar", "Delegate Forwarding (Swift)"] } @objc class func catalogIsPrimaryDemo() -> Bool { return false } func catalogShouldHideNavigation() -> Bool { return true } } extension AppBarDelegateForwardingExample { override var childViewControllerForStatusBarHidden: UIViewController? { return appBar.headerViewController } override var childViewControllerForStatusBarStyle: UIViewController? { return appBar.headerViewController } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: animated) } } // MARK: - Typical application code (not Material-specific) // MARK: UITableViewDataSource extension AppBarDelegateForwardingExample { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 50 } override func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cell") } cell!.layoutMargins = UIEdgeInsets.zero return cell! } }
370ca59287d2a13eccf86439d004fcba
31.136905
99
0.731802
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
EurofurenceTests/Presenter Tests/News/Interactor Tests/NewsViewModelValue+Equatable.swift
mit
1
@testable import Eurofurence extension NewsViewModelValue: Equatable { public static func == (lhs: NewsViewModelValue, rhs: NewsViewModelValue) -> Bool { switch (lhs, rhs) { case (.messages, .messages): return true case (.announcement(let l), .announcement(let r)): return l == r case (.event(let l), .event(let r)): return l.identifier == r.identifier case (.allAnnouncements, .allAnnouncements): return true default: return false } } }
3096a98732a7dbf106ec8b2ad8610892
22.708333
86
0.567663
false
false
false
false
stripysock/SwiftGen
refs/heads/master
swiftgen-cli/images.swift
mit
1
// // SwiftGen // Copyright (c) 2015 Olivier Halligon // MIT Licence // import Commander import PathKit import GenumKit let imagesCommand = command( outputOption, templateOption("images"), templatePathOption, Option<String>("enumName", "Asset", flag: "e", description: "The name of the enum to generate"), Argument<Path>("DIR", description: "Directory to scan for .imageset files.", validator: dirExists) ) { output, templateName, templatePath, enumName, path in let parser = AssetsCatalogParser() parser.parseDirectory(String(path)) do { let templateRealPath = try findTemplate("images", templateShortName: templateName, templateFullPath: templatePath) let template = try GenumTemplate(path: templateRealPath) let context = parser.stencilContext(enumName: enumName) let rendered = try template.render(context) output.write(rendered) } catch { print("Failed to render template \(error)") } }
5fe964a30630e438fecc61f2a81720d2
31.37931
118
0.733759
false
false
false
false
Aishwarya-Ramakrishnan/sparkios
refs/heads/master
Source/Logger/MemoryLogger.swift
mit
1
// Copyright 2016 Cisco Systems Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CocoaLumberjack class MemoryLoggerStorage { // configs private let BlockSize = 10*1024 private let BlockCount = 10 // storage private var blocks: [String] private var blockIndex = 0 init() { blocks = [String](repeating: "", count: BlockCount) } func write(_ message: String) { objc_sync_enter(self) blocks[blockIndex] += message + "\n" if blocks[blockIndex].characters.count > BlockSize { blockIndex = (blockIndex + 1) % BlockCount blocks[blockIndex] = "" } objc_sync_exit(self) } func read() -> String { var output = "" objc_sync_enter(self) for offset in 1...BlockCount { output += blocks[(blockIndex + offset) % BlockCount] } objc_sync_exit(self) return output } } class MemoryLogger : DDAbstractLogger { private let storage = MemoryLoggerStorage() private var internalLogFormatter: DDLogFormatter? // workaround for log formatter. // see: https://github.com/CocoaLumberjack/CocoaLumberjack/issues/643 override internal var logFormatter: DDLogFormatter! { set { super.logFormatter = newValue internalLogFormatter = newValue } get { return super.logFormatter } } override func log(message logMessage: DDLogMessage!) { var message = logMessage.message if let logFormatter = internalLogFormatter { message = logFormatter.format(message: logMessage) } storage.write(message!) } func getLogs() -> String { return storage.read() } }
2b1153c060732e8310ad70f132f58e73
31.352273
80
0.659993
false
false
false
false
arslanbilal/cryptology-project
refs/heads/master
Cryptology Project/Cryptology Project/Classes/Helpers/MidSquareRandomNumberGenerator.swift
mit
1
// // MidSquareRandomNumberGenerator.swift // Cryptology Project // // Created by Bilal Arslan on 08/04/16. // Copyright © 2016 Bilal Arslan. All rights reserved. // import Foundation class MidSquareRandomNumberGenerator: NSObject { private var startValue: Int! override init() { super.init() self.startValue = getTimeInput() } func next() -> Int { startValue = midSqureRandomNumber(startValue) return startValue } private func midSqureRandomNumber(input: Int) -> Int { let squareString = "\(input * input)" let completedString = completeTo8Digit(squareString) let midString = completedString[2...5] return Int(midString)! } private func completeTo8Digit(input: String) -> String { if input.length > 7 { return input } let count = 8 - input.length var returnValue = input for _ in 0 ..< count { returnValue = "0" + returnValue } return returnValue } private func getTimeInput() -> Int { let dateFormater = NSDateFormatter() dateFormater.dateFormat = "ssmm" let dateString = dateFormater.stringFromDate(NSDate()) return Int(dateString)! } }
1975f962fa71a44ad8926cd2622bfd15
22.77193
62
0.577122
false
false
false
false
rwebaz/Simple-Swift-OS
refs/heads/master
iOs8PlayGrounds/LyndaiOs8SwitchStatements.playground/section-1.swift
agpl-3.0
1
// Lynda.com iOS 8 Switch Statements by Simon Allardice import UIKit /* Note: Switch statements will work w either vars or lets (constants) */ // Declare variables and constants var windSpeed = 5; // windSpeed = 2; switch windSpeed { case 0: // If the var windSpeed = 0, then do this function println("The windSpeed variable is now at \(windSpeed) mph and steady"); case 1: // If the var windSpeed = 1, then do this function break; // The program will break out of the curley braces here in the event case '1' is true case 2...4: // If the var windSpeed = to the range given, then do this function println("The windSpeed variable is now at \(windSpeed) mph and choppy"); default: // If the var windSpeed = 'all other values', then perform this function println("The windSpeed variable is now at \(windSpeed) mph"); }
88d7e672a36ab6a66f75892942671908
26.5
96
0.680682
false
false
false
false
Drusy/auvergne-webcams-ios
refs/heads/master
Carthage/Checkouts/SwiftyUserDefaults/Sources/DefaultsObserver.swift
apache-2.0
2
// // SwiftyUserDefaults // // Copyright (c) 2015-present Radosław Pietruszewski, Łukasz Mróz // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation public protocol DefaultsDisposable { func dispose() } #if !os(Linux) public final class DefaultsObserver<T: DefaultsSerializable>: NSObject, DefaultsDisposable { public struct Update { public let kind: NSKeyValueChange public let indexes: IndexSet? public let isPrior: Bool public let newValue: T.T? public let oldValue: T.T? init(dict: [NSKeyValueChangeKey: Any], key: DefaultsKey<T>) { // swiftlint:disable:next force_cast kind = NSKeyValueChange(rawValue: dict[.kindKey] as! UInt)! indexes = dict[.indexesKey] as? IndexSet isPrior = dict[.notificationIsPriorKey] as? Bool ?? false oldValue = Update.deserialize(dict[.oldKey], for: key) ?? key.defaultValue newValue = Update.deserialize(dict[.newKey], for: key) ?? key.defaultValue } private static func deserialize(_ value: Any?, for key: DefaultsKey<T>) -> T.T? { guard let value = value else { return nil } let bridge = T._defaults if bridge.isSerialized() { return bridge.deserialize(value) } else { return value as? T.T } } } private let key: DefaultsKey<T> private let userDefaults: UserDefaults private let handler: ((Update) -> Void) private var didRemoveObserver = false init(key: DefaultsKey<T>, userDefaults: UserDefaults, options: NSKeyValueObservingOptions, handler: @escaping ((Update) -> Void)) { self.key = key self.userDefaults = userDefaults self.handler = handler super.init() userDefaults.addObserver(self, forKeyPath: key._key, options: options, context: nil) } deinit { dispose() } // swiftlint:disable:next block_based_kvo public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard let change = change, object != nil, keyPath == key._key else { return } let update = Update(dict: change, key: key) handler(update) } public func dispose() { // We use this local property because when you use `removeObserver` when you are // not actually observing anymore, you'll receive a runtime error. if didRemoveObserver { return } didRemoveObserver = true userDefaults.removeObserver(self, forKeyPath: key._key, context: nil) } } #endif
36f160aa9b9e6606b403e3ae948d0831
36.767677
157
0.669698
false
false
false
false
thankmelater23/MyFitZ
refs/heads/master
MyFitZ/JSNViewController.swift
mit
1
// // ViewController.swift // JOSNSwiftDemo // // Created by Shinkangsan on 12/5/16. // Copyright © 2016 Sheldon. All rights reserved. // import UIKit class JSNViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { final let urlString = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors" @IBOutlet weak var tableView: UITableView! var nameArray = [String]() var dobArray = [String]() var imgURLArray = [String]() override func viewDidLoad() { super.viewDidLoad() self.downloadJsonWithURL() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func downloadJsonWithURL() { let url = NSURL(string: urlString) URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary { print(jsonObj!.value(forKey: "actors")) if let actorArray = jsonObj!.value(forKey: "actors") as? NSArray { for actor in actorArray{ if let actorDict = actor as? NSDictionary { if let name = actorDict.value(forKey: "name") { self.nameArray.append(name as! String) } if let name = actorDict.value(forKey: "dob") { self.dobArray.append(name as! String) } if let name = actorDict.value(forKey: "image") { self.imgURLArray.append(name as! String) } } } } OperationQueue.main.addOperation({ self.tableView.reloadData() }) } }).resume() } func downloadJsonWithTask() { let url = NSURL(string: urlString) var downloadTask = URLRequest(url: (url as? URL)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20) downloadTask.httpMethod = "GET" URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) print(jsonData) }).resume() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return nameArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell cell.nameLabel.text = nameArray[indexPath.row] cell.dobLabel.text = dobArray[indexPath.row] let imgURL = NSURL(string: imgURLArray[indexPath.row]) if imgURL != nil { let data = NSData(contentsOf: (imgURL as? URL)!) cell.imgView.image = UIImage(data: data as! Data) } return cell } ///for showing next detailed screen with the downloaded info func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController vc.imageString = imgURLArray[indexPath.row] vc.nameString = nameArray[indexPath.row] vc.dobString = dobArray[indexPath.row] self.navigationController?.pushViewController(vc, animated: true) } }
dba7c9406e75d15b1f9da0866031885c
34.608696
140
0.567766
false
false
false
false
OHeroJ/site
refs/heads/master
Sources/App/Controllers/CategoryController.swift
mit
1
// // CategoryController.swift // spider // // Created by laijihua on 21/12/2016. // // import Foundation import HTTP import Vapor // 分类管理 final class CategoryController : BaseController { override func addRouters() { let group = drop.grouped("category") group.get("/", handler:indexView) // 列表 + 创建 group.post("/", handler: createCategory) group.post("/update",Int.self, handler: updateCategory) group.get("/update", Category.self, handler:reUpdateCategory ) group.post(Category.self,"/delete", handler: deleteCategory) } func indexView(request: Request) throws -> ResponseRepresentable { let categorys = try Category.all().makeNode() let parameters = try Node(node:["categorys":categorys]) print(parameters) return try drop.view.make("blog/category", parameters) } func deleteCategory(request: Request, category: Category) throws -> ResponseRepresentable { try category.delete() return Response(redirect: "/category") } func createCategory(request: Request)throws -> ResponseRepresentable { guard let title = request.data["title"]?.string else { throw Abort.badRequest } var category = Category(title: title) try category.save() return Response(redirect: "/category") } func reUpdateCategory(request: Request, category: Category) throws -> ResponseRepresentable { let parmas = try Node(node: ["category": category.makeNode()]) return try drop.view.make("blog/category_create", parmas) } func updateCategory(request: Request, id:Int) throws -> ResponseRepresentable { guard let title = request.data["title"]?.string else{ throw Abort.badRequest } var category = try Category.find(id) category?.title = title try category?.save() return Response(redirect: "/category") } }
ffd51baa79e8e197c86fd6c01299340b
28.909091
97
0.642351
false
false
false
false
arvedviehweger/swift
refs/heads/master
test/Sema/immutability.swift
apache-2.0
6
// RUN: %target-typecheck-verify-swift func markUsed<T>(_ t: T) {} let bad_property_1: Int { // expected-error {{'let' declarations cannot be computed properties}} get { return 42 } } let bad_property_2: Int = 0 { // expected-error {{'let' declarations cannot be computed properties}} expected-error {{variable with getter/setter cannot have an initial value}} get { return 42 } } let no_initializer : Int func foreach_variable() { for i in 0..<42 { i = 11 // expected-error {{cannot assign to value: 'i' is a 'let' constant}} } } func takeClosure(_ fn : (Int) -> Int) {} func passClosure() { takeClosure { a in a = 42 // expected-error {{cannot assign to value: 'a' is a 'let' constant}} return a } takeClosure { $0 = 42 // expected-error{{cannot assign to value: '$0' is immutable}} return 42 } takeClosure { (a : Int) -> Int in a = 42 // expected-error{{cannot assign to value: 'a' is a 'let' constant}} return 42 } } class FooClass { class let type_let = 5 // expected-error {{class stored properties not supported in classes}} init() { self = FooClass() // expected-error {{cannot assign to value: 'self' is immutable}} } func bar() { self = FooClass() // expected-error {{cannot assign to value: 'self' is immutable}} } mutating init(a : Bool) {} // expected-error {{'mutating' may only be used on 'func' declarations}} {{3-12=}} mutating // expected-error {{'mutating' isn't valid on methods in classes or class-bound protocols}} {{3-12=}} func baz() {} var x : Int { get { return 32 } set(value) { value = 42 // expected-error {{cannot assign to value: 'value' is a 'let' constant}} } } subscript(i : Int) -> Int { get { i = 42 // expected-error {{cannot assign to value: 'i' is immutable}} return 1 } } } func let_decls() { // <rdar://problem/16927246> provide a fixit to change "let" to "var" if needing to mutate a variable let a = 42 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} a = 17 // expected-error {{cannot assign to value: 'a' is a 'let' constant}} let (b,c) = (4, "hello") // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} markUsed(b); markUsed(c) b = 17 // expected-error {{cannot assign to value: 'b' is a 'let' constant}} let d = (4, "hello") // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} markUsed(d.0); markUsed(d.1) d.0 = 17 // expected-error {{cannot assign to property: 'd' is a 'let' constant}} let e = 42 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} ++e // expected-error {{cannot pass immutable value to mutating operator: 'e' is a 'let' constant}} // <rdar://problem/16306600> QoI: passing a 'let' value as an inout results in an unfriendly diagnostic let f = 96 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} var v = 1 swap(&f, &v) // expected-error {{cannot pass immutable value as inout argument: 'f' is a 'let' constant}} // <rdar://problem/19711233> QoI: poor diagnostic for operator-assignment involving immutable operand let g = 14 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} g /= 2 // expected-error {{left side of mutating operator isn't mutable: 'g' is a 'let' constant}} } struct SomeStruct { var iv = 32 static let type_let = 5 // expected-note {{change 'let' to 'var' to make it mutable}} {{10-13=var}} mutating static func f() { // expected-error {{static functions may not be declared mutating}} {{3-12=}} } mutating func g() { iv = 42 } mutating func g2() { iv = 42 } func h() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} iv = 12 // expected-error {{cannot assign to property: 'self' is immutable}} } var p: Int { // Getters default to non-mutating. get { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }} iv = 37 // expected-error {{cannot assign to property: 'self' is immutable}} return 42 } // Setters default to mutating. set { iv = newValue } } // Defaults can be changed. var q : Int { mutating get { iv = 37 return 42 } nonmutating set { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }} iv = newValue // expected-error {{cannot assign to property: 'self' is immutable}} } } var r : Int { get { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }} iv = 37 // expected-error {{cannot assign to property: 'self' is immutable}} return 42 } mutating // Redundant but OK. set { iv = newValue } } } markUsed(SomeStruct.type_let) // ok SomeStruct.type_let = 17 // expected-error {{cannot assign to property: 'type_let' is a 'let' constant}} struct TestMutableStruct { mutating func f() {} func g() {} var mutating_property : Int { mutating get {} set {} } var nonmutating_property : Int { get {} nonmutating set {} } // This property has a mutating getter and !mutating setter. var weird_property : Int { mutating get {} nonmutating set {} } @mutating func mutating_attr() {} // expected-error {{'mutating' is a declaration modifier, not an attribute}} {{3-4=}} @nonmutating func nonmutating_attr() {} // expected-error {{'nonmutating' is a declaration modifier, not an attribute}} {{3-4=}} } func test_mutability() { // Non-mutable method on rvalue is ok. TestMutableStruct().g() // Non-mutable method on let is ok. let x = TestMutableStruct() // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} x.g() // Mutable methods on let and rvalue are not ok. x.f() // expected-error {{cannot use mutating member on immutable value: 'x' is a 'let' constant}} TestMutableStruct().f() // expected-error {{cannot use mutating member on immutable value: function call returns immutable value}} _ = TestMutableStruct().weird_property // expected-error {{cannot use mutating getter on immutable value: function call returns immutable value}} let tms = TestMutableStruct() // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} _ = tms.weird_property // expected-error {{cannot use mutating getter on immutable value: 'tms' is a 'let' constant}} } func test_arguments(_ a : Int, b : Int, let c : Int) { // expected-error {{'let' as a parameter attribute is not allowed}} {{21-25=}} var b = b a = 1 // expected-error {{cannot assign to value: 'a' is a 'let' constant}} b = 2 // ok. _ = b } protocol ClassBoundProtocolMutating : class { mutating // expected-error {{'mutating' isn't valid on methods in classes or class-bound protocols}} {{3-12=}} func f() } protocol MutatingTestProto { mutating func mutatingfunc() func nonmutatingfunc() // expected-note {{protocol requires}} } class TestClass : MutatingTestProto { func mutatingfunc() {} // Ok, doesn't need to be mutating. func nonmutatingfunc() {} } struct TestStruct1 : MutatingTestProto { func mutatingfunc() {} // Ok, doesn't need to be mutating. func nonmutatingfunc() {} } struct TestStruct2 : MutatingTestProto { mutating func mutatingfunc() {} // Ok, can be mutating. func nonmutatingfunc() {} } struct TestStruct3 : MutatingTestProto { // expected-error {{type 'TestStruct3' does not conform to protocol 'MutatingTestProto'}} func mutatingfunc() {} // This is not ok, "nonmutatingfunc" doesn't allow mutating functions. mutating func nonmutatingfunc() {} // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} } // <rdar://problem/16722603> invalid conformance of mutating setter protocol NonMutatingSubscriptable { subscript(i: Int) -> Int {get nonmutating set} // expected-note {{protocol requires subscript with type '(Int) -> Int'}} } struct MutatingSubscriptor : NonMutatingSubscriptable { // expected-error {{type 'MutatingSubscriptor' does not conform to protocol 'NonMutatingSubscriptable'}} subscript(i: Int) -> Int { get { return 42 } mutating set {} // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} } } protocol NonMutatingGet { var a: Int { get } // expected-note {{protocol requires property 'a' with type 'Int'}} } struct MutatingGet : NonMutatingGet { // expected-error {{type 'MutatingGet' does not conform to protocol 'NonMutatingGet'}} var a: Int { mutating get { return 0 } } // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} } func test_properties() { let rvalue = TestMutableStruct() // expected-note 4 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} {{3-6=var}} {{3-6=var}} markUsed(rvalue.nonmutating_property) // ok markUsed(rvalue.mutating_property) // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} markUsed(rvalue.weird_property) // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} rvalue.nonmutating_property = 1 // ok rvalue.mutating_property = 1 // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} rvalue.weird_property = 1 // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} var lvalue = TestMutableStruct() markUsed(lvalue.mutating_property) // ok markUsed(lvalue.nonmutating_property) // ok markUsed(lvalue.weird_property) // ok lvalue.mutating_property = 1 // ok lvalue.nonmutating_property = 1 // ok lvalue.weird_property = 1 // ok } protocol OpaqueBase {} extension OpaqueBase { var x: Int { get { return 0 } set { } } // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} } protocol OpaqueRefinement : class, OpaqueBase { var x: Int { get set } // expected-note {{protocol requires property 'x' with type 'Int'}} } class SetterMutatingConflict : OpaqueRefinement {} // expected-error {{type 'SetterMutatingConflict' does not conform to protocol 'OpaqueRefinement'}} struct DuplicateMutating { mutating mutating func f() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} } protocol SubscriptNoGetter { subscript (i: Int) -> Int { get } } func testSubscriptNoGetter(let iis: SubscriptNoGetter) { // expected-error {{'let' as a parameter attribute is not allowed}}{{28-31=}} var _: Int = iis[17] } func testSelectorStyleArguments1(_ x: Int, bar y: Int) { var x = x var y = y x += 1 y += 1 _ = x _ = y } func testSelectorStyleArguments2(let x: Int, // expected-error {{'let' as a parameter attribute is not allowed}}{{34-37=}} let bar y: Int) { // expected-error {{'let' as a parameter attribute is not allowed}}{{34-38=}} } func testSelectorStyleArguments3(_ x: Int, bar y: Int) { ++x // expected-error {{cannot pass immutable value to mutating operator: 'x' is a 'let' constant}} ++y // expected-error {{cannot pass immutable value to mutating operator: 'y' is a 'let' constant}} } func invalid_inout(inout var x : Int) { // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{26-30=}} // expected-error @-1 {{'inout' before a parameter name is not allowed, place it before the parameter type instead}}{{20-25=}}{{34-34=inout }} } func invalid_var(var x: Int) { // expected-error {{parameters may not have the 'var' specifier}}{{18-21=}} {{1-1= var x = x\n}} } func takesClosure(_: (Int) -> Int) { takesClosure { (var d) in d } // expected-error {{parameters may not have the 'var' specifier}} } func updateInt(_ x : inout Int) {} // rdar://15785677 - allow 'let' declarations in structs/classes be initialized in init() class LetClassMembers { let a : Int // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} let b : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(arg : Int) { a = arg // ok, a is mutable in init() updateInt(&a) // ok, a is mutable in init() and has been initialized b = 17 // ok, b is mutable in init() } func f() { a = 42 // expected-error {{cannot assign to property: 'a' is a 'let' constant}} b = 42 // expected-error {{cannot assign to property: 'b' is a 'let' constant}} updateInt(&a) // expected-error {{cannot pass immutable value as inout argument: 'a' is a 'let' constant}} } } struct LetStructMembers { let a : Int // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} let b : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(arg : Int) { a = arg // ok, a is mutable in init() updateInt(&a) // ok, a is mutable in init() and has been initialized b = 17 // ok, b is mutable in init() } func f() { a = 42 // expected-error {{cannot assign to property: 'a' is a 'let' constant}} b = 42 // expected-error {{cannot assign to property: 'b' is a 'let' constant}} updateInt(&a) // expected-error {{cannot pass immutable value as inout argument: 'a' is a 'let' constant}} } } func QoI() { let x = 97 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} x = 17 // expected-error {{cannot assign to value: 'x' is a 'let' constant}} var get_only: Int { get { return 7 } } get_only = 92 // expected-error {{cannot assign to value: 'get_only' is a get-only property}} } // <rdar://problem/17051675> Structure initializers in an extension cannot assign to constant properties struct rdar17051675_S { let x : Int init(newX: Int) { x = 42 } } extension rdar17051675_S { init(newY: Int) { x = 42 } } struct rdar17051675_S2<T> { let x : Int init(newX: Int) { x = 42 } } extension rdar17051675_S2 { init(newY: Int) { x = 42 } } // <rdar://problem/17400366> let properties should not be mutable in convenience initializers class ClassWithConvenienceInit { let x : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(newX: Int) { x = 42 } convenience init(newY: Int) { self.init(newX: 19) x = 67 // expected-error {{cannot assign to property: 'x' is a 'let' constant}} } } struct StructWithDelegatingInit { let x: Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(x: Int) { self.x = x } init() { self.init(x: 0); self.x = 22 } // expected-error {{cannot assign to property: 'x' is a 'let' constant}} } func test_recovery_missing_name_2(let: Int) {} // expected-error {{'let' as a parameter attribute is not allowed}}{{35-38=}} // expected-error @-1 {{expected parameter name followed by ':'}} // <rdar://problem/16792027> compiler infinite loops on a really really mutating function struct F { // expected-note 1 {{in declaration of 'F'}} mutating mutating mutating f() { // expected-error 2 {{duplicate modifier}} expected-note 2 {{modifier already specified here}} expected-error {{expected declaration}} } mutating nonmutating func g() { // expected-error {{method may not be declared both mutating and nonmutating}} {{12-24=}} } } protocol SingleIntProperty { var i: Int { get } } struct SingleIntStruct : SingleIntProperty { let i: Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} } extension SingleIntStruct { init(_ other: SingleIntStruct) { other.i = 999 // expected-error {{cannot assign to property: 'i' is a 'let' constant}} } } // <rdar://problem/19370429> QoI: fixit to add "mutating" when assigning to a member of self in a struct // <rdar://problem/17632908> QoI: Modifying struct member in non-mutating function produces difficult to understand error message struct TestSubscriptMutability { let let_arr = [1,2,3] // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} var var_arr = [1,2,3] func nonmutating1() { let_arr[1] = 1 // expected-error {{cannot assign through subscript: 'let_arr' is a 'let' constant}} } func nonmutating2() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} var_arr[1] = 1 // expected-error {{cannot assign through subscript: 'self' is immutable}} } func nonmutating3() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} self = TestSubscriptMutability() // expected-error {{cannot assign to value: 'self' is immutable}} } subscript(a : Int) -> TestSubscriptMutability { return TestSubscriptMutability() } func test() { self[1] = TestSubscriptMutability() // expected-error {{cannot assign through subscript: subscript is get-only}} self[1].var_arr = [] // expected-error {{cannot assign to property: subscript is get-only}} self[1].let_arr = [] // expected-error {{cannot assign to property: 'let_arr' is a 'let' constant}} } } func f(_ a : TestSubscriptMutability) { a.var_arr = [] // expected-error {{cannot assign to property: 'a' is a 'let' constant}} } struct TestSubscriptMutability2 { subscript(a : Int) -> Int { get { return 42 } set {} } func test() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} self[1] = 2 // expected-error {{cannot assign through subscript: 'self' is immutable}} } } struct TestBangMutability { let let_opt = Optional(1) // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} var var_opt = Optional(1) func nonmutating1() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} let_opt! = 1 // expected-error {{cannot assign through '!': 'let_opt' is a 'let' constant}} var_opt! = 1 // expected-error {{cannot assign through '!': 'self' is immutable}} self[]! = 2 // expected-error {{cannot assign through '!': subscript is get-only}} } mutating func nonmutating2() { let_opt! = 1 // expected-error {{cannot assign through '!': 'let_opt' is a 'let' constant}} var_opt! = 1 // ok self[]! = 2 // expected-error {{cannot assign through '!': subscript is get-only}} } subscript() -> Int? { return nil } } // <rdar://problem/21176945> mutation through ? not considered a mutation func testBindOptional() { var a : TestStruct2? = nil // Mutated through optional chaining. a?.mutatingfunc() } struct HasTestStruct2 { var t = TestStruct2() } func testConditional(b : Bool) { var x = TestStruct2() var y = TestStruct2() var z = HasTestStruct2() (b ? x : y).mutatingfunc() // expected-error {{cannot use mutating member on immutable value: result of conditional operator '? :' is never mutable}} (b ? (b ? x : y) : y).mutatingfunc() // expected-error {{cannot use mutating member on immutable value: result of conditional operator '? :' is never mutable}} (b ? x : (b ? x : y)).mutatingfunc() // expected-error {{cannot use mutating member on immutable value: result of conditional operator '? :' is never mutable}} (b ? x : z.t).mutatingfunc() // expected-error {{cannot use mutating member on immutable value: result of conditional operator '? :' is never mutable}} } // <rdar://problem/27384685> QoI: Poor diagnostic when assigning a value to a method func f(a : FooClass, b : LetStructMembers) { a.baz = 1 // expected-error {{cannot assign to property: 'baz' is a method}} b.f = 42 // expected-error {{cannot assign to property: 'f' is a method}} }
44b9a9250682440c7418902b22cdcd44
34.238261
176
0.636956
false
true
false
false
dusanIntellex/backend-operation-layer
refs/heads/master
Example/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift
mit
2
// // ConcurrentDispatchQueueScheduler.swift // RxSwift // // Created by Krunoslav Zaher on 7/5/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import struct Foundation.Date import struct Foundation.TimeInterval import Dispatch /// Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. You can also pass a serial dispatch queue, it shouldn't cause any problems. /// /// This scheduler is suitable when some work needs to be performed in background. public class ConcurrentDispatchQueueScheduler: SchedulerType { public typealias TimeInterval = Foundation.TimeInterval public typealias Time = Date public var now : Date { return Date() } let configuration: DispatchQueueConfiguration /// Constructs new `ConcurrentDispatchQueueScheduler` that wraps `queue`. /// /// - parameter queue: Target dispatch queue. /// - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. public init(queue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { configuration = DispatchQueueConfiguration(queue: queue, leeway: leeway) } /// Convenience init for scheduler that wraps one of the global concurrent dispatch queues. /// /// - parameter qos: Target global dispatch queue, by quality of service class. /// - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. @available(iOS 8, OSX 10.10, *) public convenience init(qos: DispatchQoS, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { self.init(queue: DispatchQueue( label: "rxswift.queue.\(qos)", qos: qos, attributes: [DispatchQueue.Attributes.concurrent], target: nil), leeway: leeway ) } /** Schedules an action to be executed immediately. - parameter state: State passed to the action to be executed. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public final func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { return self.configuration.schedule(state, action: action) } /** Schedules an action to be executed. - parameter state: State passed to the action to be executed. - parameter dueTime: Relative time after which to execute the action. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public final func scheduleRelative<StateType>(_ state: StateType, dueTime: Foundation.TimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { return self.configuration.scheduleRelative(state, dueTime: dueTime, action: action) } /** Schedules a periodic piece of work. - parameter state: State passed to the action to be executed. - parameter startAfter: Period after which initial work should be run. - parameter period: Period for running the work periodically. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public func schedulePeriodic<StateType>(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { return self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) } }
386ff227981067abaf64d671cf649690
42.583333
171
0.703906
false
true
false
false
onevcat/CotEditor
refs/heads/develop
CotEditor/Sources/PrintTextView.swift
apache-2.0
1
// // PrintTextView.swift // // CotEditor // https://coteditor.com // // Created by nakamuxu on 2005-10-01. // // --------------------------------------------------------------------------- // // © 2004-2007 nakamuxu // © 2014-2022 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Combine import Cocoa final class PrintTextView: NSTextView, Themable, URLDetectable { // MARK: Constants static let verticalPrintMargin: CGFloat = 56.0 // default 90.0 static let horizontalPrintMargin: CGFloat = 24.0 // default 72.0 private let lineFragmentPadding: CGFloat = 18.0 private let lineNumberPadding: CGFloat = 10.0 private let headerFooterFontSize: CGFloat = 9.0 // MARK: Public Properties var filePath: String? var documentName: String? private(set) var theme: Theme? private(set) lazy var syntaxParser = SyntaxParser(textStorage: self.textStorage!) // settings on current window to be set by Document. // These values are used if set option is "Same as document's setting" var documentShowsLineNumber = false var documentShowsInvisibles = false var urlDetectionTask: Task<Void, Error>? // MARK: Private Properties private let tabWidth: Int private let lineHeight: CGFloat private var printsLineNumber = false private var xOffset: CGFloat = 0 private var lastPaperContentSize: NSSize = .zero private lazy var dateFormatter: DateFormatter = .init() private var asyncHighlightObserver: AnyCancellable? // MARK: - // MARK: Lifecycle init() { self.tabWidth = UserDefaults.standard[.tabWidth] self.lineHeight = UserDefaults.standard[.lineHeight] // setup textContainer let textContainer = TextContainer() textContainer.widthTracksTextView = true textContainer.isHangingIndentEnabled = UserDefaults.standard[.enablesHangingIndent] textContainer.hangingIndentWidth = UserDefaults.standard[.hangingIndentWidth] textContainer.lineFragmentPadding = self.lineFragmentPadding // -> If padding is changed while printing, the print area can be cropped due to text wrapping. // setup textView components let textStorage = NSTextStorage() let layoutManager = PrintLayoutManager() textStorage.addLayoutManager(layoutManager) layoutManager.addTextContainer(textContainer) super.init(frame: .zero, textContainer: textContainer) self.maxSize = .infinite self.isHorizontallyResizable = false self.isVerticallyResizable = true self.linkTextAttributes = UserDefaults.standard[.autoLinkDetection] ? [.underlineStyle: NSUnderlineStyle.single.rawValue] : [:] } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { self.layoutManager?.delegate = nil self.urlDetectionTask?.cancel() } // MARK: Text View Methods /// the top/left point of text container override var textContainerOrigin: NSPoint { return NSPoint(x: self.xOffset, y: 0) } /// view's opacity override var isOpaque: Bool { return true } /// job title override var printJobTitle: String { return self.documentName ?? super.printJobTitle } /// return page header attributed string override var pageHeader: NSAttributedString { return self.headerFooter(for: .header) } /// return page footer attributed string override var pageFooter: NSAttributedString { return self.headerFooter(for: .footer) } /// set printing font override var font: NSFont? { didSet { guard let font = font else { return } // setup paragraph style let paragraphStyle = NSParagraphStyle.default.mutable paragraphStyle.tabStops = [] paragraphStyle.defaultTabInterval = CGFloat(self.tabWidth) * font.width(of: " ") paragraphStyle.lineHeightMultiple = self.lineHeight self.defaultParagraphStyle = paragraphStyle self.textStorage?.addAttribute(.paragraphStyle, value: paragraphStyle, range: self.string.nsRange) // set font also to layout manager (self.layoutManager as? LayoutManager)?.textFont = font } } /// return the number of pages available for printing override func knowsPageRange(_ range: NSRangePointer) -> Bool { // apply print settings self.applyPrintSettings() // adjust content size based on print setting if let paperContentSize = NSPrintOperation.current?.printInfo.paperContentSize, self.lastPaperContentSize != paperContentSize { self.lastPaperContentSize = paperContentSize self.frame.size = paperContentSize self.layoutManager?.doForegroundLayout() } return super.knowsPageRange(range) } /// draw override func draw(_ dirtyRect: NSRect) { // store graphics state to keep line number area drawable // -> Otherwise, line numbers can be cropped. (2016-03 by 1024jp) NSGraphicsContext.saveGraphicsState() super.draw(dirtyRect) NSGraphicsContext.restoreGraphicsState() // draw line numbers if needed if self.printsLineNumber { guard let layoutManager = self.layoutManager as? LayoutManager, let textContainer = self.textContainer else { return assertionFailure() } // prepare text attributes for line numbers let numberFontSize = (0.9 * (self.font?.pointSize ?? 12)).rounded() let numberFont = NSFont.lineNumberFont(ofSize: numberFontSize) let attrs: [NSAttributedString.Key: Any] = [.font: numberFont, .foregroundColor: self.textColor ?? .textColor] // calculate character width by treating the font as a mono-space font let numberSize = NSAttributedString(string: "8", attributes: attrs).size() // adjust values for line number drawing let horizontalOrigin = self.baseWritingDirection != .rightToLeft ? self.textContainerOrigin.x + textContainer.lineFragmentPadding - self.lineNumberPadding : self.textContainerOrigin.x + textContainer.size.width let baselineOffset = layoutManager.baselineOffset(for: self.layoutOrientation) let numberAscender = numberFont.ascender // vertical text let isVerticalText = self.layoutOrientation == .vertical if isVerticalText { // rotate axis NSGraphicsContext.saveGraphicsState() NSGraphicsContext.current?.cgContext.rotate(by: -.pi / 2) } let options: NSTextView.LineEnumerationOptions = isVerticalText ? [.bySkippingWrappedLine] : [] let range = ((self.layoutManager as? PrintLayoutManager)?.showsSelectionOnly == true) ? self.selectedRange : nil self.enumerateLineFragments(in: dirtyRect, for: range, options: options.union(.bySkippingExtraLine)) { (lineRect, line, lineNumber) in let numberString: String = { switch line { case .new: if isVerticalText, lineNumber != 1, !lineNumber.isMultiple(of: 5) { return "·" // draw number only every 5 times } return String(lineNumber) case .wrapped: return "-" } }() // adjust position to draw let width = CGFloat(numberString.count) * numberSize.width let point: NSPoint if isVerticalText { point = NSPoint(x: -lineRect.midY - width / 2, y: horizontalOrigin - numberSize.height) } else { point = NSPoint(x: horizontalOrigin - width, // - width to align to right y: lineRect.minY + baselineOffset - numberAscender) } // draw number NSAttributedString(string: numberString, attributes: attrs).draw(at: point) } if isVerticalText { NSGraphicsContext.restoreGraphicsState() } } } // MARK: Private Methods /// parse current print settings in printInfo private func applyPrintSettings() { guard let layoutManager = self.layoutManager as? PrintLayoutManager, let printInfo = NSPrintOperation.current?.printInfo else { return assertionFailure() } // set scope to print layoutManager.showsSelectionOnly = printInfo.isSelectionOnly // check whether print line numbers self.printsLineNumber = { switch PrintVisibilityMode(printInfo[.lineNumber]) { case .no: return false case .sameAsDocument: return self.documentShowsLineNumber case .yes: return true } }() // adjust paddings considering the line numbers let printsAtLeft = (self.printsLineNumber && self.baseWritingDirection != .rightToLeft) self.xOffset = printsAtLeft ? self.lineFragmentPadding : 0 self.textContainerInset.width = printsAtLeft ? self.lineFragmentPadding : 0 // check whether print invisibles layoutManager.showsInvisibles = { switch PrintVisibilityMode(printInfo[.invisibles]) { case .no: return false case .sameAsDocument: return self.documentShowsInvisibles case .yes: return true } }() // set whether draws background self.drawsBackground = printInfo[.printsBackground] ?? true // create theme let themeName = printInfo[.theme] ?? ThemeName.blackAndWhite let theme = ThemeManager.shared.setting(name: themeName) // nil for Black and White guard self.theme?.name != theme?.name else { return } // set theme // -> The following two procedures are important to change .textColor in the preview properly // while printing only the selection (2022-03 macOS 12): // 1. Set .textColor after setting .backgroundColor. // 2. Ensure glyphs. self.theme = theme self.backgroundColor = theme?.background.color ?? .textBackgroundColor // expensive task self.textColor = theme?.text.color ?? .textColor layoutManager.invisiblesColor = theme?.invisibles.color ?? .disabledControlTextColor layoutManager.ensureGlyphs(forCharacterRange: self.string.nsRange) // perform syntax highlight let progress = self.syntaxParser.highlight() // asynchronously trigger preview update if needed if let progress = progress, let controller = NSPrintOperation.current?.printPanel.accessoryControllers.first as? PrintPanelAccessoryController { self.asyncHighlightObserver = progress.publisher(for: \.isFinished) .first { $0 } .receive(on: DispatchQueue.main) .sink { [weak controller] _ in controller?.needsUpdatePreview = true } } } /// return attributed string for header/footer private func headerFooter(for location: HeaderFooterLocation) -> NSAttributedString { let keys = location.keys guard let printInfo = NSPrintOperation.current?.printInfo, printInfo[keys.needsDraw] == true else { return NSAttributedString() } let primaryInfoType = PrintInfoType(printInfo[keys.primaryContent]) let primaryAlignment = AlignmentType(printInfo[keys.primaryAlignment]) let secondaryInfoType = PrintInfoType(printInfo[keys.secondaryContent]) let secondaryAlignment = AlignmentType(printInfo[keys.secondaryAlignment]) let primaryString = self.printInfoString(type: primaryInfoType) let secondaryString = self.printInfoString(type: secondaryInfoType) switch (primaryString, secondaryString) { // case: empty case (.none, .none): return NSAttributedString() // case: single content case let (.some(string), .none): return NSAttributedString(string: string, attributes: self.headerFooterAttributes(for: primaryAlignment)) case let (.none, .some(string)): return NSAttributedString(string: string, attributes: self.headerFooterAttributes(for: secondaryAlignment)) case let (.some(primaryString), .some(secondaryString)): switch (primaryAlignment, secondaryAlignment) { // case: double-sided case (.left, .right): return NSAttributedString(string: primaryString + "\t\t" + secondaryString, attributes: self.headerFooterAttributes(for: .left)) case (.right, .left): return NSAttributedString(string: secondaryString + "\t\t" + primaryString, attributes: self.headerFooterAttributes(for: .left)) // case: two lines default: let primaryAttrString = NSAttributedString(string: primaryString, attributes: self.headerFooterAttributes(for: primaryAlignment)) let secondaryAttrString = NSAttributedString(string: secondaryString, attributes: self.headerFooterAttributes(for: secondaryAlignment)) return [primaryAttrString, secondaryAttrString].joined(separator: "\n") } } } /// return attributes for header/footer string private func headerFooterAttributes(for alignment: AlignmentType) -> [NSAttributedString.Key: Any] { let font = NSFont.userFont(ofSize: self.headerFooterFontSize) let paragraphStyle = NSParagraphStyle.default.mutable paragraphStyle.lineBreakMode = .byTruncatingMiddle paragraphStyle.alignment = alignment.textAlignment // tab stops for double-sided alignment (imitation of super.pageHeader) if let printInfo = NSPrintOperation.current?.printInfo { let xMax = printInfo.paperSize.width - printInfo.topMargin / 2 paragraphStyle.tabStops = [NSTextTab(type: .centerTabStopType, location: xMax / 2), NSTextTab(type: .rightTabStopType, location: xMax)] } return [.font: font, .paragraphStyle: paragraphStyle] .compactMapValues { $0 } } /// create string for header/footer private func printInfoString(type: PrintInfoType) -> String? { switch type { case .documentName: return self.documentName case .syntaxName: return self.syntaxParser.style.name case .filePath: guard let filePath = self.filePath else { // print document name instead if document doesn't have file path yet return self.documentName } if UserDefaults.standard[.headerFooterPathAbbreviatingWithTilde] { return filePath.abbreviatingWithTildeInSandboxedPath } return filePath case .printDate: self.dateFormatter.dateFormat = UserDefaults.standard[.headerFooterDateFormat] return String(format: "Printed on %@".localized, self.dateFormatter.string(from: Date())) case .pageNumber: guard let pageNumber = NSPrintOperation.current?.currentPage else { return nil } return String(pageNumber) case .none: return nil } } } private extension NSLayoutManager { /// This method causes the text to be laid out in the foreground. /// /// - Note: This method is based on `textEditDoForegroundLayoutToCharacterIndex:` in Apple's TextView.app source code. func doForegroundLayout() { guard self.numberOfGlyphs > 0 else { return } // cause layout by asking a question which has to determine where the glyph is self.textContainer(forGlyphAt: self.numberOfGlyphs - 1, effectiveRange: nil) } } // MARK: - private final class PrintLayoutManager: LayoutManager { var showsSelectionOnly = false { didSet { guard showsSelectionOnly != oldValue else { return } let range = self.attributedString().range self.invalidateGlyphs(forCharacterRange: range, changeInLength: 0, actualCharacterRange: nil) self.invalidateLayout(forCharacterRange: range, actualCharacterRange: nil) // important for vertical orientation self.ensureGlyphs(forCharacterRange: range) self.ensureLayout(forCharacterRange: range) } } func layoutManager(_ layoutManager: NSLayoutManager, shouldGenerateGlyphs glyphs: UnsafePointer<CGGlyph>, properties: UnsafePointer<NSLayoutManager.GlyphProperty>, characterIndexes: UnsafePointer<Int>, font: NSFont, forGlyphRange glyphRange: NSRange) -> Int { // hide unselected glyphs if set so guard self.showsSelectionOnly, let selectedRange = layoutManager.firstTextView?.selectedRange, self.attributedString().length != selectedRange.length else { return 0 } // return 0 for the default processing let glyphIndexesToHide = (0..<glyphRange.length).filter { !selectedRange.contains(characterIndexes[$0]) } guard !glyphIndexesToHide.isEmpty else { return 0 } let newProperties = UnsafeMutablePointer(mutating: properties) for index in glyphIndexesToHide { newProperties[index].insert(.null) } layoutManager.setGlyphs(glyphs, properties: newProperties, characterIndexes: characterIndexes, font: font, forGlyphRange: glyphRange) return glyphRange.length } override func layoutManager(_ layoutManager: NSLayoutManager, shouldUse action: NSLayoutManager.ControlCharacterAction, forControlCharacterAt charIndex: Int) -> NSLayoutManager.ControlCharacterAction { // zero width for folded characters if self.showsSelectionOnly, let selectedRange = layoutManager.firstTextView?.selectedRange, !selectedRange.contains(charIndex) { return .zeroAdvancement } return super.layoutManager(layoutManager, shouldUse: action, forControlCharacterAt: charIndex) } } // MARK: - private enum HeaderFooterLocation { case header case footer struct Keys { var needsDraw: NSPrintInfo.AttributeKey var primaryContent: NSPrintInfo.AttributeKey var primaryAlignment: NSPrintInfo.AttributeKey var secondaryContent: NSPrintInfo.AttributeKey var secondaryAlignment: NSPrintInfo.AttributeKey } var keys: Keys { switch self { case .header: return Keys(needsDraw: .printsHeader, primaryContent: .primaryHeaderContent, primaryAlignment: .primaryHeaderAlignment, secondaryContent: .secondaryHeaderContent, secondaryAlignment: .secondaryHeaderAlignment) case .footer: return Keys(needsDraw: .printsFooter, primaryContent: .primaryFooterContent, primaryAlignment: .primaryFooterAlignment, secondaryContent: .secondaryFooterContent, secondaryAlignment: .secondaryFooterAlignment) } } } private extension AlignmentType { var textAlignment: NSTextAlignment { switch self { case .left: return .left case .center: return .center case .right: return .right } } }
3f1b0aad4486d926d8d72dfd1d1b6ecb
36.5
263
0.598095
false
false
false
false
huaf22/zhihuSwiftDemo
refs/heads/master
zhihuSwiftDemo/Views/WLYPullToRefreshView.swift
mit
1
// // WLYPullToRefreshView.swift // zhihuSwiftDemo // // Created by Afluy on 16/8/30. // Copyright © 2016年 helios. All rights reserved. // import Foundation import UIKit open class WLYPullToRefreshView: UIView { enum PullToRefreshState { case pulling case triggered case refreshing case stop } // MARK: Variables let contentOffsetKeyPath = "contentOffset" let contentSizeKeyPath = "contentSize" var kvoContext = "PullToRefreshKVOContext" var refreshAutoStopTime: Double = 10 var refreshStopTime: Double = 0.2 var scrollViewBounces: Bool = true var scrollViewInsets: UIEdgeInsets = UIEdgeInsets.zero var refreshCompletion: ((Void) -> Void)? fileprivate var pull: Bool = true fileprivate var positionY: CGFloat = 0 { didSet { if self.positionY == oldValue { return } var frame = self.frame frame.origin.y = positionY self.frame = frame } } var state: PullToRefreshState = PullToRefreshState.pulling { didSet { if self.state == oldValue { return } guard let scrollView = superview as? UIScrollView else { return } print("WLYPullToRefreshView state: \(state)") switch self.state { case .stop: stopRefreshAction(scrollView) case .refreshing: startRefreshAction(scrollView) case .pulling: startPullAction(scrollView) case .triggered: startPullTriggeredAction(scrollView) } } } // MARK: UIView override convenience init(frame: CGRect) { self.init(frame:frame, refreshCompletion:nil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { self.removeRegister() } init(frame: CGRect, down:Bool=true, refreshCompletion :((Void) -> Void)?) { self.refreshCompletion = refreshCompletion self.pull = down super.init(frame: frame) self.autoresizingMask = .flexibleWidth } open override func willMove(toSuperview superView: UIView!) { //superview NOT superView, DO NEED to call the following method //superview dealloc will call into this when my own dealloc run later!! self.removeRegister() guard let scrollView = superView as? UIScrollView else { return } scrollView.addObserver(self, forKeyPath: contentOffsetKeyPath, options: .initial, context: &kvoContext) if !pull { scrollView.addObserver(self, forKeyPath: contentSizeKeyPath, options: .initial, context: &kvoContext) } } fileprivate func removeRegister() { if let scrollView = superview as? UIScrollView { scrollView.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &kvoContext) if !pull { scrollView.removeObserver(self, forKeyPath: contentSizeKeyPath, context: &kvoContext) } } } // MARK: KVO open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let scrollView = object as? UIScrollView else { return } if keyPath == contentSizeKeyPath { self.positionY = scrollView.contentSize.height return } if !(context == &kvoContext && keyPath == contentOffsetKeyPath) { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } // Pulling State Check let offsetY = scrollView.contentOffset.y if offsetY <= 0 { if !self.pull { return } if offsetY < -self.frame.size.height { // pulling or refreshing if scrollView.isDragging == false && self.state != .refreshing { //release the finger self.state = .refreshing //startAnimating } else if self.state != .refreshing { //reach the threshold self.state = .triggered } } else if self.state == .triggered { //starting point, start from pulling self.state = .pulling } return //return for pull down } //push up let upHeight = offsetY + scrollView.frame.size.height - scrollView.contentSize.height if upHeight > 0 { // pulling or refreshing if self.pull { return } if upHeight > self.frame.size.height { // pulling or refreshing if scrollView.isDragging == false && self.state != .refreshing { //release the finger self.state = .refreshing //startAnimating } else if self.state != .refreshing { //reach the threshold self.state = .triggered } } else if self.state == .triggered { //starting point, start from pulling self.state = .pulling } } } /** 开始下拉 */ func startPullAction(_ scrollView: UIScrollView) { } /** 下拉到临界点 */ func startPullTriggeredAction(_ scrollView: UIScrollView) { } /** 用户松手,开始刷新操作 */ func startRefreshAction(_ scrollView: UIScrollView) { self.scrollViewBounces = scrollView.bounces self.scrollViewInsets = scrollView.contentInset var insets = scrollView.contentInset if self.pull { insets.top += self.frame.size.height } else { insets.bottom += self.frame.size.height } scrollView.bounces = false scrollView.contentInset = self.scrollViewInsets self.refreshCompletion?() } /** 刷新完毕 */ func stopRefreshAction(_ scrollView: UIScrollView) { scrollView.bounces = self.scrollViewBounces scrollView.contentInset = self.scrollViewInsets self.state = .pulling } }
5393c2ce35a8bb028a86d4ea0826b8fd
29.35514
156
0.559267
false
false
false
false
daaavid/TIY-Assignments
refs/heads/master
44--Philosophone/Philosophone/Philosophone/Extensions.swift
cc0-1.0
1
// // Extensions.swift // Philosophone // // Created by david on 12/4/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import Foundation import UIKit extension UIView { func spin() { let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation") rotateAnimation.fromValue = 0.0 rotateAnimation.toValue = CGFloat(M_PI * 2.0) rotateAnimation.duration = 0.3 self.layer.addAnimation(rotateAnimation, forKey: nil) } func appearWithFade(duration: Double) { dispatch_async(dispatch_get_main_queue()) { () -> Void in self.alpha = 0 UIView.animateWithDuration(duration) { () -> Void in self.alpha = 1 } } } func slideVerticallyToOriginAndSpin(duration: Double, fromPointY: CGFloat, spin: Bool) { let originalY = self.frame.origin.y self.frame.origin.y += fromPointY self.alpha = 0 UIView.animateWithDuration(duration, animations: { () -> Void in self.frame.origin.y = originalY self.alpha = 1 }) { (_) -> Void in if spin { self.spin() } } } } extension UILabel { func typeText(quote: String, interval: Double, delegate: TypedCharacterTextDelegate?) { if self.text != "" { self.text = "" } let global_queue = dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0) dispatch_async(global_queue) { () -> Void in for character in quote.characters { if String(character) != " " && shouldPlayTypingSound == true { let sound = TypewriterClack() sound.playSound("soft") } dispatch_async(dispatch_get_main_queue()) { () -> Void in self.text = self.text! + String(character) } NSThread.sleepForTimeInterval(interval) } delegate?.quoteFinishedTyping() } } }
73cad1c7251aa5002f340d51c123be85
25.951807
90
0.508945
false
false
false
false
wijjo/iOS-WeatherReport
refs/heads/master
WeatherReport/ForecastIO.swift
apache-2.0
1
// // ForecastIO.swift // WeatherReport // // Created by Steve Cooper on 12/20/14. // Copyright (c) 2014 Steve Cooper. All rights reserved. // import Foundation import CoreLocation // https://developer.forecast.io/docs/v2 private let baseURL = "https://api.forecast.io/forecast" let useCannedData = false let cannedData: NSDictionary = [ "apparentTemperature": "44.23", "cloudCover": "0.53", "dewPoint": "40.83", "humidity": "0.84", "icon": "partly-cloudy-day", "nearestStormBearing": 345, "nearestStormDistance": 155, "ozone": "285.65", "precipIntensity": 0, "precipProbability": 0, "pressure": "1026.89", "summary": "Partly Cloudy", "temperature": "45.49", "time": 1419783003, "visibility": "8.52", "windBearing": 33, "windSpeed": "2.14", ] class ForecastIO : WeatherSourceBase { override func getWeather(completionHandler: (items: [WeatherItem]) -> ()) { if !useCannedData { let session = NSURLSession.sharedSession() if let url = forecastURL() { self.log(.Debug, "URL: \(url.absoluteString)") var request = NSMutableURLRequest(URL: url) request.HTTPMethod = "GET" let task = session.dataTaskWithRequest(request) { data, response, error in var items: [WeatherItem] = [] if let httpResponse = response as? NSHTTPURLResponse { if let error = error { self.log(.Error, error.localizedDescription) } else if httpResponse.statusCode != 200 { self.log(.Error, "HTTP error \(httpResponse.statusCode)") } else { if let result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary { if let currently = result["currently"] as? NSDictionary { items = self.forecastItems(currently) } else { self.log(.Error, "failed to access current conditions") } } } } completionHandler(items: items) } task.resume() } else { self.log(.Error, "failed to construct URL") } } else { let items = self.forecastItems(cannedData) completionHandler(items: items) } } func forecastItems(dict: NSDictionary) -> [WeatherItem] { var itemBuilder = WeatherItemBuilder(dict) var fieldBuilder = itemBuilder.makeItem("Summary", symbol: dict["icon"] as? String) fieldBuilder.string("summary") fieldBuilder = itemBuilder.makeItem("Time") fieldBuilder.unixDate("time") fieldBuilder = itemBuilder.makeItem("Temperature") fieldBuilder.degrees("temperature") fieldBuilder.parenthesize() fieldBuilder.label("feels like") fieldBuilder.degrees("apparentTemperature") fieldBuilder = itemBuilder.makeItem("Precipitation", symbol: dict["precipType"] as? String) fieldBuilder.string("precipType") fieldBuilder.percent("precipProbability") fieldBuilder = itemBuilder.makeItem("Wind") fieldBuilder.mph("windSpeed") fieldBuilder.parenthesize() fieldBuilder.label("from") fieldBuilder.bearing("windBearing") fieldBuilder = itemBuilder.makeItem("Humidity") fieldBuilder.percent("humidity") fieldBuilder = itemBuilder.makeItem("Pressure") fieldBuilder.millibars("pressure") fieldBuilder = itemBuilder.makeItem("Cloud Cover") fieldBuilder.percent("cloudCover") fieldBuilder = itemBuilder.makeItem("Visibility") fieldBuilder.miles("visibility") fieldBuilder = itemBuilder.makeItem("Dew Point") fieldBuilder.degrees("dewPoint") return itemBuilder.toItems() } func forecastURL() -> NSURL? { if let coord = self.location?.coordinate { let apiKey = forecastIOAPIKey return NSURL(string: "\(baseURL)/\(apiKey)/\(coord.latitude),\(coord.longitude)") } return nil } func forecastURL(date: NSDate) -> NSURL? { if let url = forecastURL() { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" let dateString = formatter.stringFromDate(date) url.URLByAppendingPathComponent(",\(dateString)") return url } return nil } func log(type: SCSCMessageType, _ message: String) { self.logger.log(type, "Forecast.IO: \(message)") } }
b02276efece2e39959333def9b39de4a
33.901408
102
0.570016
false
false
false
false
EstefaniaGilVaquero/OrienteeringQuizIOS
refs/heads/master
OrienteeringQuiz/Pods/SideMenu/Pod/Classes/SideMenuTransition.swift
apache-2.0
1
// // SideMenuTransition.swift // Pods // // Created by Jon Kent on 1/14/16. // // import UIKit open class SideMenuTransition: UIPercentDrivenInteractiveTransition, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { fileprivate var presenting = false fileprivate var interactive = false fileprivate static weak var originalSuperview: UIView? fileprivate static var switchMenus = false internal static let singleton = SideMenuTransition() internal static var presentDirection: UIRectEdge = .left; internal static weak var tapView: UIView? { didSet { guard let tapView = tapView else { return } tapView.autoresizingMask = [.flexibleHeight, .flexibleWidth] let exitPanGesture = UIPanGestureRecognizer() exitPanGesture.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handleHideMenuPan(_:))) let exitTapGesture = UITapGestureRecognizer() exitTapGesture.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handleHideMenuTap(_:))) tapView.addGestureRecognizer(exitPanGesture) tapView.addGestureRecognizer(exitTapGesture) } } internal static weak var statusBarView: UIView? { didSet { guard let statusBarView = statusBarView else { return } if let menuShrinkBackgroundColor = SideMenuManager.menuAnimationBackgroundColor { statusBarView.backgroundColor = menuShrinkBackgroundColor } else { statusBarView.backgroundColor = UIColor.black } statusBarView.isUserInteractionEnabled = false } } // prevent instantiation fileprivate override init() {} fileprivate class var viewControllerForPresentedMenu: UIViewController? { get { return SideMenuManager.menuLeftNavigationController?.presentingViewController != nil ? SideMenuManager.menuLeftNavigationController?.presentingViewController : SideMenuManager.menuRightNavigationController?.presentingViewController } } fileprivate class var visibleViewController: UIViewController? { get { return getVisibleViewControllerFromViewController(UIApplication.shared.keyWindow?.rootViewController) } } fileprivate class func getVisibleViewControllerFromViewController(_ viewController: UIViewController?) -> UIViewController? { if let navigationController = viewController as? UINavigationController { return getVisibleViewControllerFromViewController(navigationController.visibleViewController) } else if let tabBarController = viewController as? UITabBarController { return getVisibleViewControllerFromViewController(tabBarController.selectedViewController) } else if let presentedViewController = viewController?.presentedViewController { return getVisibleViewControllerFromViewController(presentedViewController) } return viewController } internal class func handlePresentMenuLeftScreenEdge(_ edge: UIScreenEdgePanGestureRecognizer) { SideMenuTransition.presentDirection = .left handlePresentMenuPan(edge) } internal class func handlePresentMenuRightScreenEdge(_ edge: UIScreenEdgePanGestureRecognizer) { SideMenuTransition.presentDirection = .right handlePresentMenuPan(edge) } internal class func handlePresentMenuPan(_ pan: UIPanGestureRecognizer) { // how much distance have we panned in reference to the parent view? guard let view = viewControllerForPresentedMenu != nil ? viewControllerForPresentedMenu?.view : pan.view else { return } let transform = view.transform view.transform = CGAffineTransform.identity let translation = pan.translation(in: pan.view!) view.transform = transform // do some math to translate this to a percentage based value if !singleton.interactive { if translation.x == 0 { return // not sure which way the user is swiping yet, so do nothing } if !(pan is UIScreenEdgePanGestureRecognizer) { SideMenuTransition.presentDirection = translation.x > 0 ? .left : .right } if let menuViewController = SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController : SideMenuManager.menuRightNavigationController, let visibleViewController = visibleViewController { singleton.interactive = true visibleViewController.present(menuViewController, animated: true, completion: nil) } } let direction: CGFloat = SideMenuTransition.presentDirection == .left ? 1 : -1 let distance = translation.x / SideMenuManager.menuWidth // now lets deal with different states that the gesture recognizer sends switch (pan.state) { case .began, .changed: if pan is UIScreenEdgePanGestureRecognizer { singleton.update(min(distance * direction, 1)) } else if distance > 0 && SideMenuTransition.presentDirection == .right && SideMenuManager.menuLeftNavigationController != nil { SideMenuTransition.presentDirection = .left switchMenus = true singleton.cancel() } else if distance < 0 && SideMenuTransition.presentDirection == .left && SideMenuManager.menuRightNavigationController != nil { SideMenuTransition.presentDirection = .right switchMenus = true singleton.cancel() } else { singleton.update(min(distance * direction, 1)) } default: singleton.interactive = false view.transform = CGAffineTransform.identity let velocity = pan.velocity(in: pan.view!).x * direction view.transform = transform if velocity >= 100 || velocity >= -50 && abs(distance) >= 0.5 { // bug workaround: animation briefly resets after call to finishInteractiveTransition() but before animateTransition completion is called. if ProcessInfo().operatingSystemVersion.majorVersion == 8 && singleton.percentComplete > 1 - CGFloat(FLT_EPSILON) { singleton.update(0.9999) } singleton.finish() } else { singleton.cancel() } } } internal class func handleHideMenuPan(_ pan: UIPanGestureRecognizer) { let translation = pan.translation(in: pan.view!) let direction:CGFloat = SideMenuTransition.presentDirection == .left ? -1 : 1 let distance = translation.x / SideMenuManager.menuWidth * direction switch (pan.state) { case .began: singleton.interactive = true viewControllerForPresentedMenu?.dismiss(animated: true, completion: nil) case .changed: singleton.update(max(min(distance, 1), 0)) default: singleton.interactive = false let velocity = pan.velocity(in: pan.view!).x * direction if velocity >= 100 || velocity >= -50 && distance >= 0.5 { // bug workaround: animation briefly resets after call to finishInteractiveTransition() but before animateTransition completion is called. if ProcessInfo().operatingSystemVersion.majorVersion == 8 && singleton.percentComplete > 1 - CGFloat(FLT_EPSILON) { singleton.update(0.9999) } singleton.finish() } else { singleton.cancel() } } } internal class func handleHideMenuTap(_ tap: UITapGestureRecognizer) { viewControllerForPresentedMenu?.dismiss(animated: true, completion: nil) } internal class func hideMenuStart() { NotificationCenter.default.removeObserver(SideMenuTransition.singleton) guard let mainViewController = SideMenuTransition.viewControllerForPresentedMenu, let menuView = SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController?.view : SideMenuManager.menuRightNavigationController?.view else { return } menuView.transform = CGAffineTransform.identity mainViewController.view.transform = CGAffineTransform.identity mainViewController.view.alpha = 1 SideMenuTransition.tapView?.frame = CGRect(x: 0, y: 0, width: mainViewController.view.frame.width, height: mainViewController.view.frame.height) menuView.frame.origin.y = 0 menuView.frame.size.width = SideMenuManager.menuWidth menuView.frame.size.height = mainViewController.view.frame.height SideMenuTransition.statusBarView?.frame = UIApplication.shared.statusBarFrame SideMenuTransition.statusBarView?.alpha = 0 switch SideMenuManager.menuPresentMode { case .viewSlideOut: menuView.alpha = 1 - SideMenuManager.menuAnimationFadeStrength menuView.frame.origin.x = SideMenuTransition.presentDirection == .left ? 0 : mainViewController.view.frame.width - SideMenuManager.menuWidth mainViewController.view.frame.origin.x = 0 menuView.transform = CGAffineTransform(scaleX: SideMenuManager.menuAnimationTransformScaleFactor, y: SideMenuManager.menuAnimationTransformScaleFactor) case .viewSlideInOut: menuView.alpha = 1 menuView.frame.origin.x = SideMenuTransition.presentDirection == .left ? -menuView.frame.width : mainViewController.view.frame.width mainViewController.view.frame.origin.x = 0 case .menuSlideIn: menuView.alpha = 1 menuView.frame.origin.x = SideMenuTransition.presentDirection == .left ? -menuView.frame.width : mainViewController.view.frame.width case .menuDissolveIn: menuView.alpha = 0 menuView.frame.origin.x = SideMenuTransition.presentDirection == .left ? 0 : mainViewController.view.frame.width - SideMenuManager.menuWidth mainViewController.view.frame.origin.x = 0 } } internal class func hideMenuComplete() { guard let mainViewController = SideMenuTransition.viewControllerForPresentedMenu, let menuView = SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController?.view : SideMenuManager.menuRightNavigationController?.view else { return } SideMenuTransition.tapView?.removeFromSuperview() SideMenuTransition.statusBarView?.removeFromSuperview() mainViewController.view.motionEffects.removeAll() mainViewController.view.layer.shadowOpacity = 0 menuView.layer.shadowOpacity = 0 if let topNavigationController = mainViewController as? UINavigationController { topNavigationController.interactivePopGestureRecognizer!.isEnabled = true } originalSuperview?.addSubview(mainViewController.view) } internal class func presentMenuStart(forSize size: CGSize = SideMenuManager.appScreenRect.size) { guard let menuView = SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController?.view : SideMenuManager.menuRightNavigationController?.view, let mainViewController = SideMenuTransition.viewControllerForPresentedMenu else { return } menuView.transform = CGAffineTransform.identity mainViewController.view.transform = CGAffineTransform.identity menuView.frame.size.width = SideMenuManager.menuWidth menuView.frame.size.height = size.height menuView.frame.origin.x = SideMenuTransition.presentDirection == .left ? 0 : size.width - SideMenuManager.menuWidth SideMenuTransition.statusBarView?.frame = UIApplication.shared.statusBarFrame SideMenuTransition.statusBarView?.alpha = 1 switch SideMenuManager.menuPresentMode { case .viewSlideOut: menuView.alpha = 1 let direction:CGFloat = SideMenuTransition.presentDirection == .left ? 1 : -1 mainViewController.view.frame.origin.x = direction * (menuView.frame.width) mainViewController.view.layer.shadowColor = SideMenuManager.menuShadowColor.cgColor mainViewController.view.layer.shadowRadius = SideMenuManager.menuShadowRadius mainViewController.view.layer.shadowOpacity = SideMenuManager.menuShadowOpacity mainViewController.view.layer.shadowOffset = CGSize(width: 0, height: 0) case .viewSlideInOut: menuView.alpha = 1 mainViewController.view.layer.shadowColor = SideMenuManager.menuShadowColor.cgColor mainViewController.view.layer.shadowRadius = SideMenuManager.menuShadowRadius mainViewController.view.layer.shadowOpacity = SideMenuManager.menuShadowOpacity mainViewController.view.layer.shadowOffset = CGSize(width: 0, height: 0) let direction:CGFloat = SideMenuTransition.presentDirection == .left ? 1 : -1 mainViewController.view.frame = CGRect(x: direction * (menuView.frame.width), y: 0, width: size.width, height: size.height) mainViewController.view.transform = CGAffineTransform(scaleX: SideMenuManager.menuAnimationTransformScaleFactor, y: SideMenuManager.menuAnimationTransformScaleFactor) mainViewController.view.alpha = 1 - SideMenuManager.menuAnimationFadeStrength case .menuSlideIn, .menuDissolveIn: menuView.alpha = 1 if SideMenuManager.menuBlurEffectStyle == nil { menuView.layer.shadowColor = SideMenuManager.menuShadowColor.cgColor menuView.layer.shadowRadius = SideMenuManager.menuShadowRadius menuView.layer.shadowOpacity = SideMenuManager.menuShadowOpacity menuView.layer.shadowOffset = CGSize(width: 0, height: 0) } mainViewController.view.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) mainViewController.view.transform = CGAffineTransform(scaleX: SideMenuManager.menuAnimationTransformScaleFactor, y: SideMenuManager.menuAnimationTransformScaleFactor) mainViewController.view.alpha = 1 - SideMenuManager.menuAnimationFadeStrength } } internal class func presentMenuComplete() { NotificationCenter.default.addObserver(SideMenuTransition.singleton, selector:#selector(SideMenuTransition.applicationDidEnterBackgroundNotification), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) guard let mainViewController = SideMenuTransition.viewControllerForPresentedMenu else { return } switch SideMenuManager.menuPresentMode { case .menuSlideIn, .menuDissolveIn, .viewSlideInOut: if SideMenuManager.menuParallaxStrength != 0 { let horizontal = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis) horizontal.minimumRelativeValue = -SideMenuManager.menuParallaxStrength horizontal.maximumRelativeValue = SideMenuManager.menuParallaxStrength let vertical = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis) vertical.minimumRelativeValue = -SideMenuManager.menuParallaxStrength vertical.maximumRelativeValue = SideMenuManager.menuParallaxStrength let group = UIMotionEffectGroup() group.motionEffects = [horizontal, vertical] mainViewController.view.addMotionEffect(group) } case .viewSlideOut: break; } if let topNavigationController = mainViewController as? UINavigationController { topNavigationController.interactivePopGestureRecognizer!.isEnabled = false } } // MARK: UIViewControllerAnimatedTransitioning protocol methods // animate a change from one viewcontroller to another open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { // get reference to our fromView, toView and the container view that we should perform the transition in let container = transitionContext.containerView // prevent any other menu gestures from firing container.isUserInteractionEnabled = false if let menuBackgroundColor = SideMenuManager.menuAnimationBackgroundColor { container.backgroundColor = menuBackgroundColor } let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)! let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)! // assign references to our menu view controller and the 'bottom' view controller from the tuple // remember that our menuViewController will alternate between the from and to view controller depending if we're presenting or dismissing let menuViewController = presenting ? toViewController : fromViewController let topViewController = presenting ? fromViewController : toViewController let menuView = menuViewController.view! let topView = topViewController.view! // prepare menu items to slide in if presenting { SideMenuTransition.originalSuperview = topView.superview // add the both views to our view controller switch SideMenuManager.menuPresentMode { case .viewSlideOut, .viewSlideInOut: container.addSubview(menuView) container.addSubview(topView) case .menuSlideIn, .menuDissolveIn: container.addSubview(topView) container.addSubview(menuView) } if SideMenuManager.menuFadeStatusBar { let statusBarView = UIView() SideMenuTransition.statusBarView = statusBarView container.addSubview(statusBarView) } SideMenuTransition.hideMenuStart() } // perform the animation! let duration = transitionDuration(using: transitionContext) let options: UIViewAnimationOptions = interactive ? .curveLinear : UIViewAnimationOptions() UIView.animate(withDuration: duration, delay: 0, options: options, animations: { () -> Void in if self.presenting { SideMenuTransition.presentMenuStart() } else { SideMenuTransition.hideMenuStart() } }) { (finished) -> Void in container.isUserInteractionEnabled = true // tell our transitionContext object that we've finished animating if transitionContext.transitionWasCancelled { let viewControllerForPresentedMenu = SideMenuTransition.viewControllerForPresentedMenu if self.presenting { SideMenuTransition.hideMenuComplete() } else { SideMenuTransition.presentMenuComplete() } transitionContext.completeTransition(false) if SideMenuTransition.switchMenus { SideMenuTransition.switchMenus = false viewControllerForPresentedMenu?.present(SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController! : SideMenuManager.menuRightNavigationController!, animated: true, completion: nil) } return } if self.presenting { SideMenuTransition.presentMenuComplete() if !SideMenuManager.menuPresentingViewControllerUserInteractionEnabled { let tapView = UIView() topView.addSubview(tapView) tapView.frame = topView.bounds SideMenuTransition.tapView = tapView } transitionContext.completeTransition(true) switch SideMenuManager.menuPresentMode { case .viewSlideOut, .viewSlideInOut: container.addSubview(topView) case .menuSlideIn, .menuDissolveIn: container.insertSubview(topView, at: 0) } if let statusBarView = SideMenuTransition.statusBarView { container.bringSubview(toFront: statusBarView) } return } SideMenuTransition.hideMenuComplete() transitionContext.completeTransition(true) menuView.removeFromSuperview() } } // return how many seconds the transiton animation will take open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return presenting ? SideMenuManager.menuAnimationPresentDuration : SideMenuManager.menuAnimationDismissDuration } // MARK: UIViewControllerTransitioningDelegate protocol methods // return the animator when presenting a viewcontroller // rememeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = true SideMenuTransition.presentDirection = presented == SideMenuManager.menuLeftNavigationController ? .left : .right return self } // return the animator used when dismissing from a viewcontroller open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { presenting = false return self } open func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { // if our interactive flag is true, return the transition manager object // otherwise return nil return interactive ? SideMenuTransition.singleton : nil } open func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactive ? SideMenuTransition.singleton : nil } internal func applicationDidEnterBackgroundNotification() { if let menuViewController: UINavigationController = SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController : SideMenuManager.menuRightNavigationController, menuViewController.presentedViewController == nil { SideMenuTransition.hideMenuStart() SideMenuTransition.hideMenuComplete() menuViewController.dismiss(animated: false, completion: nil) } } }
7f951cfae1a2a343f007039fade15beb
50.118026
243
0.671298
false
false
false
false
amraboelela/swift
refs/heads/master
test/Generics/requirement_inference.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift -typecheck -verify // RUN: %target-typecheck-verify-swift -typecheck -debug-generic-signatures > %t.dump 2>&1 // RUN: %FileCheck %s < %t.dump protocol P1 { func p1() } protocol P2 : P1 { } struct X1<T : P1> { func getT() -> T { } } class X2<T : P1> { func getT() -> T { } } class X3 { } struct X4<T : X3> { func getT() -> T { } } struct X5<T : P2> { } // Infer protocol requirements from the parameter type of a generic function. func inferFromParameterType<T>(_ x: X1<T>) { x.getT().p1() } // Infer protocol requirements from the return type of a generic function. func inferFromReturnType<T>(_ x: T) -> X1<T> { x.p1() } // Infer protocol requirements from the superclass of a generic parameter. func inferFromSuperclass<T, U : X2<T>>(_ t: T, u: U) -> T { t.p1() } // Infer protocol requirements from the parameter type of a constructor. struct InferFromConstructor { init<T> (x : X1<T>) { x.getT().p1() } } // Don't infer requirements for outer generic parameters. class Fox : P1 { func p1() {} } class Box<T : Fox, U> { func unpack(_ x: X1<T>) {} func unpackFail(_ X: X1<U>) { } // expected-error{{type 'U' does not conform to protocol 'P1'}} } // ---------------------------------------------------------------------------- // Superclass requirements // ---------------------------------------------------------------------------- // Compute meet of two superclass requirements correctly. class Carnivora {} class Canidae : Carnivora {} struct U<T : Carnivora> {} struct V<T : Canidae> {} // CHECK-LABEL: .inferSuperclassRequirement1@ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Canidae> func inferSuperclassRequirement1<T : Carnivora>( _ v: V<T>) {} // CHECK-LABEL: .inferSuperclassRequirement2@ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Canidae> func inferSuperclassRequirement2<T : Canidae>(_ v: U<T>) {} // ---------------------------------------------------------------------------- // Same-type requirements // ---------------------------------------------------------------------------- protocol P3 { associatedtype P3Assoc : P2 // expected-note{{declared here}} } protocol P4 { associatedtype P4Assoc : P1 } protocol PCommonAssoc1 { associatedtype CommonAssoc } protocol PCommonAssoc2 { associatedtype CommonAssoc } protocol PAssoc { associatedtype Assoc } struct Model_P3_P4_Eq<T : P3, U : P4> where T.P3Assoc == U.P4Assoc {} func inferSameType1<T, U>(_ x: Model_P3_P4_Eq<T, U>) { let u: U.P4Assoc? = nil let _: T.P3Assoc? = u! } func inferSameType2<T : P3, U : P4>(_: T, _: U) where U.P4Assoc : P2, T.P3Assoc == U.P4Assoc {} // expected-warning@-1{{redundant conformance constraint 'T.P3Assoc': 'P2'}} // expected-note@-2{{conformance constraint 'T.P3Assoc': 'P2' implied here}} func inferSameType3<T : PCommonAssoc1>(_: T) where T.CommonAssoc : P1, T : PCommonAssoc2 { } protocol P5 { associatedtype Element } protocol P6 { associatedtype AssocP6 : P5 } protocol P7 : P6 { associatedtype AssocP7: P6 } // CHECK-LABEL: P7@ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P7, τ_0_0.AssocP6.Element : P6, τ_0_0.AssocP6.Element == τ_0_0.AssocP7.AssocP6.Element> extension P7 where AssocP6.Element : P6, // expected-note{{conformance constraint 'Self.AssocP6.Element': 'P6' written here}} AssocP7.AssocP6.Element : P6, // expected-warning{{redundant conformance constraint 'Self.AssocP6.Element': 'P6'}} AssocP6.Element == AssocP7.AssocP6.Element { func nestedSameType1() { } } protocol P8 { associatedtype A associatedtype B } protocol P9 : P8 { associatedtype A associatedtype B } protocol P10 { associatedtype A associatedtype C } // CHECK-LABEL: sameTypeConcrete1@ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P10, τ_0_0 : P9, τ_0_0.A == X3, τ_0_0.B == Int, τ_0_0.C == Int> func sameTypeConcrete1<T : P9 & P10>(_: T) where T.A == X3, T.C == T.B, T.C == Int { } // CHECK-LABEL: sameTypeConcrete2@ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P10, τ_0_0 : P9, τ_0_0.B == X3, τ_0_0.C == X3> func sameTypeConcrete2<T : P9 & P10>(_: T) where T.B : X3, T.C == T.B, T.C == X3 { } // expected-warning@-1{{redundant superclass constraint 'T.B' : 'X3'}} // expected-note@-2{{same-type constraint 'T.C' == 'X3' written here}} // Note: a standard-library-based stress test to make sure we don't inject // any additional requirements. // CHECK-LABEL: RangeReplaceableCollection // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : MutableCollection, τ_0_0 : RangeReplaceableCollection, τ_0_0.SubSequence == Slice<τ_0_0>> extension RangeReplaceableCollection where Self: MutableCollection, Self.SubSequence == Slice<Self> { func f() { } } // CHECK-LABEL: X14.recursiveConcreteSameType // CHECK: Generic signature: <T, V where T == Range<Int>> // CHECK-NEXT: Canonical generic signature: <τ_0_0, τ_1_0 where τ_0_0 == Range<Int>> struct X14<T> where T.Iterator == IndexingIterator<T> { func recursiveConcreteSameType<V>(_: V) where T == Range<Int> { } } // rdar://problem/30478915 protocol P11 { associatedtype A } protocol P12 { associatedtype B: P11 } struct X6 { } struct X7 : P11 { typealias A = X6 } struct X8 : P12 { typealias B = X7 } struct X9<T: P12, U: P12> where T.B == U.B { // CHECK-LABEL: X9.upperSameTypeConstraint // CHECK: Generic signature: <T, U, V where T == X8, U : P12, U.B == X8.B> // CHECK: Canonical generic signature: <τ_0_0, τ_0_1, τ_1_0 where τ_0_0 == X8, τ_0_1 : P12, τ_0_1.B == X7> func upperSameTypeConstraint<V>(_: V) where T == X8 { } } protocol P13 { associatedtype C: P11 } struct X10: P11, P12 { typealias A = X10 typealias B = X10 } struct X11<T: P12, U: P12> where T.B == U.B.A { // CHECK-LABEL: X11.upperSameTypeConstraint // CHECK: Generic signature: <T, U, V where T : P12, U == X10, T.B == X10.A> // CHECK: Canonical generic signature: <τ_0_0, τ_0_1, τ_1_0 where τ_0_0 : P12, τ_0_1 == X10, τ_0_0.B == X10> func upperSameTypeConstraint<V>(_: V) where U == X10 { } } #if _runtime(_ObjC) // rdar://problem/30610428 @objc protocol P14 { } class X12<S: AnyObject> { func bar<V>(v: V) where S == P14 { } } @objc protocol P15: P14 { } class X13<S: P14> { func bar<V>(v: V) where S == P15 { } } #endif protocol P16 { associatedtype A } struct X15 { } struct X16<X, Y> : P16 { typealias A = (X, Y) } // CHECK-LABEL: .X17.bar@ // CHECK: Generic signature: <S, T, U, V where S == X16<X3, X15>, T == X3, U == X15> struct X17<S: P16, T, U> where S.A == (T, U) { func bar<V>(_: V) where S == X16<X3, X15> { } } // Same-type constraints that are self-derived via a parent need to be // suppressed in the resulting signature. protocol P17 { } protocol P18 { associatedtype A: P17 } struct X18: P18, P17 { typealias A = X18 } // CHECK-LABEL: .X19.foo@ // CHECK: Generic signature: <T, U where T == X18> struct X19<T: P18> where T == T.A { func foo<U>(_: U) where T == X18 { } } // rdar://problem/31520386 protocol P20 { } struct X20<T: P20> { } // CHECK-LABEL: .X21.f@ // CHECK: Generic signature: <T, U, V where T : P20, U == X20<T>> // CHECK: Canonical generic signature: <τ_0_0, τ_0_1, τ_1_0 where τ_0_0 : P20, τ_0_1 == X20<τ_0_0>> struct X21<T, U> { func f<V>(_: V) where U == X20<T> { } } struct X22<T, U> { func g<V>(_: V) where T: P20, U == X20<T> { } } // CHECK: Generic signature: <Self where Self : P22> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P22> // CHECK: Protocol requirement signature: // CHECK: .P22@ // CHECK-NEXT: Requirement signature: <Self where Self.A == X20<Self.B>, Self.B : P20> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X20<τ_0_0.B>, τ_0_0.B : P20> protocol P22 { associatedtype A associatedtype B: P20 where A == X20<B> } // CHECK: Generic signature: <Self where Self : P23> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P23> // CHECK: Protocol requirement signature: // CHECK: .P23@ // CHECK-NEXT: Requirement signature: <Self where Self.A == X20<Self.B>, Self.B : P20> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X20<τ_0_0.B>, τ_0_0.B : P20> protocol P23 { associatedtype A associatedtype B: P20 where A == X20<B> } protocol P24 { associatedtype C: P20 } struct X24<T: P20> : P24 { typealias C = T } // CHECK-LABEL: .P25a@ // CHECK-NEXT: Requirement signature: <Self where Self.A == X24<Self.B>, Self.B : P20> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X24<τ_0_0.B>, τ_0_0.B : P20> protocol P25a { associatedtype A: P24 // expected-warning{{redundant conformance constraint 'Self.A': 'P24'}} associatedtype B: P20 where A == X24<B> // expected-note{{conformance constraint 'Self.A': 'P24' implied here}} } // CHECK-LABEL: .P25b@ // CHECK-NEXT: Requirement signature: <Self where Self.A == X24<Self.B>, Self.B : P20> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X24<τ_0_0.B>, τ_0_0.B : P20> protocol P25b { associatedtype A associatedtype B: P20 where A == X24<B> } protocol P25c { associatedtype A: P24 associatedtype B where A == X<B> // expected-error{{use of undeclared type 'X'}} } protocol P25d { associatedtype A associatedtype B where A == X24<B> // expected-error{{type 'Self.B' does not conform to protocol 'P20'}} } // Similar to the above, but with superclass constraints. protocol P26 { associatedtype C: X3 } struct X26<T: X3> : P26 { typealias C = T } // CHECK-LABEL: .P27a@ // CHECK-NEXT: Requirement signature: <Self where Self.A == X26<Self.B>, Self.B : X3> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X26<τ_0_0.B>, τ_0_0.B : X3> protocol P27a { associatedtype A: P26 // expected-warning{{redundant conformance constraint 'Self.A': 'P26'}} associatedtype B: X3 where A == X26<B> // expected-note{{conformance constraint 'Self.A': 'P26' implied here}} } // CHECK-LABEL: .P27b@ // CHECK-NEXT: Requirement signature: <Self where Self.A == X26<Self.B>, Self.B : X3> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.A == X26<τ_0_0.B>, τ_0_0.B : X3> protocol P27b { associatedtype A associatedtype B: X3 where A == X26<B> } // ---------------------------------------------------------------------------- // Inference of associated type relationships within a protocol hierarchy // ---------------------------------------------------------------------------- struct X28 : P2 { func p1() { } } // CHECK-LABEL: .P28@ // CHECK-NEXT: Requirement signature: <Self where Self : P3, Self.P3Assoc == X28> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : P3, τ_0_0.P3Assoc == X28> protocol P28: P3 { typealias P3Assoc = X28 // expected-warning{{typealias overriding associated type}} } // ---------------------------------------------------------------------------- // Inference of associated types by name match // ---------------------------------------------------------------------------- protocol P29 { associatedtype X } protocol P30 { associatedtype X } protocol P31 { } // CHECK-LABEL: .sameTypeNameMatch1@ // CHECK: Generic signature: <T where T : P29, T : P30, T.X : P31> func sameTypeNameMatch1<T: P29 & P30>(_: T) where T.X: P31 { } // ---------------------------------------------------------------------------- // Infer requirements from conditional conformances // ---------------------------------------------------------------------------- protocol P32 {} protocol P33 { associatedtype A: P32 } protocol P34 {} struct Foo<T> {} extension Foo: P32 where T: P34 {} // Inference chain: U.A: P32 => Foo<V>: P32 => V: P34 // CHECK-LABEL: conditionalConformance1@ // CHECK: Generic signature: <U, V where U : P33, V : P34, U.A == Foo<V>> // CHECK: Canonical generic signature: <τ_0_0, τ_0_1 where τ_0_0 : P33, τ_0_1 : P34, τ_0_0.A == Foo<τ_0_1>> func conditionalConformance1<U: P33, V>(_: U) where U.A == Foo<V> {} struct Bar<U: P32> {} // CHECK-LABEL: conditionalConformance2@ // CHECK: Generic signature: <V where V : P34> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P34> func conditionalConformance2<V>(_: Bar<Foo<V>>) {} // Mentioning a nested type that is conditional should infer that requirement (SR 6850) protocol P35 {} protocol P36 { func foo() } struct ConditionalNested<T> {} extension ConditionalNested where T: P35 { struct Inner {} } // CHECK: Generic signature: <T where T : P35, T : P36> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P35, τ_0_0 : P36> extension ConditionalNested.Inner: P36 where T: P36 { func foo() {} struct Inner2 {} } // CHECK-LABEL: conditionalNested1@ // CHECK: Generic signature: <U where U : P35> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P35> func conditionalNested1<U>(_: [ConditionalNested<U>.Inner?]) {} // CHECK-LABEL: conditionalNested2@ // CHECK: Generic signature: <U where U : P35, U : P36> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P35, τ_0_0 : P36> func conditionalNested2<U>(_: [ConditionalNested<U>.Inner.Inner2?]) {} // // Generate typalias adds requirements that can be inferred // typealias X1WithP2<T: P2> = X1<T> // Inferred requirement T: P2 from the typealias func testX1WithP2<T>(_: X1WithP2<T>) { _ = X5<T>() // requires P2 } // Overload based on the inferred requirement. func testX1WithP2Overloading<T>(_: X1<T>) { _ = X5<T>() // expected-error{{type 'T' does not conform to protocol 'P2'}} } func testX1WithP2Overloading<T>(_: X1WithP2<T>) { _ = X5<T>() // requires P2 } // Extend using the inferred requirement. extension X1WithP2 { func f() { _ = X5<T>() // okay: inferred T: P2 from generic typealias } } extension X1: P1 { func p1() { } } typealias X1WithP2Changed<T: P2> = X1<X1<T>> typealias X1WithP2MoreArgs<T: P2, U> = X1<T> extension X1WithP2Changed { func bad1() { _ = X5<T>() // expected-error{{type 'T' does not conform to protocol 'P2'}} } } extension X1WithP2MoreArgs { func bad2() { _ = X5<T>() // expected-error{{type 'T' does not conform to protocol 'P2'}} } } // Inference from protocol inheritance clauses. typealias ExistentialP4WithP2Assoc<T: P4> = P4 where T.P4Assoc : P2 protocol P37 : ExistentialP4WithP2Assoc<Self> { } extension P37 { func f() { _ = X5<P4Assoc>() // requires P2 } }
54282969fca6c2fdaaa9fbe7d25c4d14
26.870406
149
0.621348
false
false
false
false
mitolog/slidenews
refs/heads/master
SlideNews/Pages/Controllers/SlideViewController.swift
mit
1
// // SlideViewController.swift // SlideView // // Created by mito on 10/2/14. // Copyright (c) 2014 mito. All rights reserved. // import UIKit class SlideViewController: UIViewController, CategorieClipViewDelegate, UIScrollViewDelegate { // objcでいう@propertyのつもり var vcs: Array<TabBaseViewController>? = [] var catClipView: CategoryClipView! var contentScrlViewControl: UIPageControl! var contentScrlView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBarHidden = true; /***************** カテゴリー名(画面上部)の横スクロールビュー *****************/ let categories: Array<Dictionary<String,String>> = [ [ "name":"カラパイア","className":"Tab1ViewController", "nibName":"Tab1ViewController", "cellName":"BaseCell", "rssUrl":"http://karapaia.livedoor.biz/index.rdf" ], [ "name":"ガジェット通信","className":"Tab1ViewController", "nibName":"Tab1ViewController", "cellName":"BaseCell", "rssUrl":"http://getnews.jp/feed/ext/orig" ], [ "name":"tidaブログ","className":"Tab1ViewController", "nibName":"Tab1ViewController", "cellName":"BaseCell", "rssUrl":"http://tidanews.ti-da.net/index.rdf" ] ] let catScrlRect = CGRectMake(0, 0,CGRectGetWidth(self.view.frame),CGFloat(CATEGORYVIEW_HEIGHT)+20) self.catClipView = CategoryClipView(frame: catScrlRect, categories: categories) self.catClipView.delegate = self self.catClipView.backgroundColor = UIColor.catClipViewBgColor() self.view.addSubview(self.catClipView) /***************** コンテンツ(画面下部)の横スクロールビュー *****************/ var contentScrlViewRect: CGRect = CGRectMake(0, CGRectGetMaxY(catScrlRect), CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-CGRectGetHeight(catScrlRect)) self.contentScrlView = UIScrollView(frame: contentScrlViewRect) self.contentScrlView.bounds = contentScrlViewRect self.contentScrlView.clipsToBounds = false self.contentScrlView.pagingEnabled = true self.contentScrlView.showsHorizontalScrollIndicator = false self.contentScrlView.delegate = self self.contentScrlView.backgroundColor = UIColor.whiteColor() self.view.addSubview(self.contentScrlView) var totalWidth: CGFloat = CGRectGetWidth(contentScrlViewRect) * CGFloat(categories.count) self.contentScrlView.contentSize = CGSizeMake(totalWidth, CGRectGetHeight(contentScrlViewRect)) self.contentScrlViewControl = UIPageControl(frame: CGRectZero) self.contentScrlViewControl.backgroundColor = UIColor.clearColor() self.contentScrlViewControl.numberOfPages = categories.count // カテゴリごとのviewを張り付けていく var cnt: CGFloat = 0.0 for aDic : Dictionary<String,String> in categories { var vcFrame: CGRect = CGRectMake(cnt*CGRectGetWidth(contentScrlViewRect), 0.0, CGRectGetWidth(contentScrlViewRect), CGRectGetHeight(contentScrlViewRect)) let vcClass = NSClassFromString(aDic["className"]) as TabBaseViewController.Type let vc: TabBaseViewController = vcClass(frame: vcFrame, info: aDic) self.vcs?.append(vc) self.contentScrlView.addSubview(vc.view) cnt++ } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func categoryScrollViewDidScroll(sender: CategoryClipView) { //[self changeContent]; } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
ac892551677563b10232f1afd5994fe6
37.097345
107
0.632288
false
false
false
false
sdhzwm/WMMatchbox
refs/heads/master
WMMatchbox/WMMatchbox/Classes/Messages(消息)/Controller/WMMessageController.swift
apache-2.0
1
// // WMMessageController.swift // WMMatchbox // // Created by 王蒙 on 15/7/21. // Copyright © 2015年 wm. All rights reserved. // import UIKit class WMMessageController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
9d4b50345a4d2698c01a8165708ae74e
32.863158
157
0.685732
false
false
false
false
authme-org/authme
refs/heads/master
authme-iphone/AuthMe/Src/Service/AuthMeServiceInitialiser.swift
apache-2.0
1
/* * * Copyright 2015 Berin Lautenbach * * 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. * */ // // AuthMeServiceInitialiser.swift // AuthMe // // Created by Berin Lautenbach on 8/03/2015. // Copyright (c) 2015 Berin Lautenbach. All rights reserved. // import Foundation class AuthMeServiceInitialiser : NSObject, AuthMeServiceDelegate, AuthMeSignDelegate { var logger = Log() var initialised = false var masterPassword : MasterPassword var appConfiguration : AppConfiguration var authme : AuthMeService var serviceRSAKey : RSAKey? = nil var serviceAESKey : AESKey? = nil var serviceRSAKCV = "" var serviceAESKCV = "" var encryptedServicePrivateKey = "" var encryptedServiceAESKey = "" let _AUTHME_SERVICE_RSA_KEY_TAG = "org.authme.servicekeypair" override init() { masterPassword = MasterPassword.getInstance() authme = AuthMeService() appConfiguration = AppConfiguration.getInstance() } func doInit() { /* Would be wierd... */ if initialised { return } logger.log(.debug, message: "Starting init of authme service") /* First destroy any existing service configuration */ masterPassword.serviceDeactivated() /* Add device is where we kick off from */ _ = authme.addDevice( masterPassword.getUniqueDeviceId(), withName: masterPassword.getDeviceName(), withType: "iPhone", withAPNToken: appConfiguration.getConfigItem("apnToken") as? String, withPublicKey: masterPassword.deviceRSAKey!.getPublicKey(), withDelegate: self) } func getDevice() { let date = Date() let df = DateFormatter() df.dateFormat = "dd/MM/yyyy-hh:mm:ssa" let nonce = df.string(from: date) // Call the getDevice web service. This will encrypt the nonce using the public key _ = authme.getDevice(masterPassword.getUniqueDeviceId(), withNonce: nonce, withOpaqueData: nonce as AnyObject?, withDelegate: self) return; } func checkDevice(_ json: NSDictionary, withNonce nonce: String) { logger.log(.debug, message: "Validating device") if let encryptedData = json.object(forKey: "encryptedData") as? NSString { if let decrypt = masterPassword.deviceRSAKey?.decrypt(encryptedData as String) { if let decryptString = NSString(data: decrypt, encoding: String.Encoding.utf8.rawValue) { if decryptString as String == nonce { logger.log(.debug, message: "Decrypt of nonce OK") _ = authme.getServiceKey(masterPassword.getUniqueDeviceId(), withDelegate: self) return; } } } } logger.log(.debug, message: "device validation failed") } func uploadServiceKey() { logger.log(.debug, message: "Sending service key to service"); /* First have to sign it */ let signature = AuthMeSign() signature.doSign(masterPassword.getUniqueDeviceId() + serviceAESKCV + encryptedServiceAESKey, keyPair: masterPassword.deviceRSAKey!, delegate: self, withOpaqueData: nil) } /* Worker task to create the RSA and AES service keys in the background */ @objc func createServiceKeyWorker() { /* Generate RSA key */ logger.log(.debug, message:"rsaGEnThreadMain now generating keys") serviceRSAKey = RSAKey(identifier: _AUTHME_SERVICE_RSA_KEY_TAG) if !serviceRSAKey!.generate(masterPassword._AUTHME_RSA_KEY_LENGTH * 8) { logger.log(.warn, message: "Error generating RSA key") return } logger.log(.debug, message: "RSA Service key generated") serviceAESKey = AESKey() if !serviceAESKey!.generateKey() { logger.log(.warn, message: "Error generating AES key") } /* Now we encrypt the private key using the newly generated AES key */ let rsaPrivateAsString = serviceRSAKey!.getPKCS8PrivateKey() let rsaPrivateAsData = Data(base64Encoded: rsaPrivateAsString!, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) serviceRSAKey!.calculateKCV(rsaPrivateAsData) serviceRSAKCV = serviceRSAKey!.getKCV() serviceAESKCV = serviceAESKey!.getKCV() encryptedServicePrivateKey = serviceAESKey!.encrypt(rsaPrivateAsData, plainLength: rsaPrivateAsData!.count) /* Then the AES key under the device key */ let aesKeyAsData = serviceAESKey!.getAsData() encryptedServiceAESKey = masterPassword.deviceRSAKey!.encrypt(aesKeyAsData, plainLength: (aesKeyAsData?.count)!) logger.log(.debug, message: "createServiceKeyWorker finalising"); DispatchQueue.main.async(execute: {self.uploadServiceKey()} ) } func loadServiceKey(_ json: NSDictionary) { if let keyStatus = json.object(forKey: "keyStatus") as? NSString { if keyStatus == "Available" { logger.log(.debug, message: "Service Key available") if let encryptedKeyValue = json.object(forKey: "encryptedKeyValue") as? NSString { if let keyKCV = json.object(forKey: "keyKCV") as? NSString { // Decrypt... if let serviceKeyRaw = masterPassword.deviceRSAKey?.decrypt(encryptedKeyValue as String) { let serviceKey = AESKey() if serviceKey.loadKey(serviceKeyRaw) && serviceKey.checkKCV(keyKCV as String) { logger.log(.debug, message: "ServiceKey loaded") masterPassword.serviceKey = serviceKey loadServiceKeyPair(json) return; } } } } } else if keyStatus == "None" { logger.log(.debug, message: "Service key not set - need to create one") /* Start a background threat to generate new keys */ let createServiceWorkerThread = Thread(target: self, selector: #selector(AuthMeServiceInitialiser.createServiceKeyWorker), object: nil) createServiceWorkerThread.start() return } } logger.log(.debug, message: "Load of service key failed") } func loadServiceKeyPair(_ json: NSDictionary) { if let encryptedPrivateKey = json.object(forKey: "encryptedPrivateKey") as? NSString { if let publicKey = json.object(forKey: "publicKey") as? NSString { if let privateKCV = json.object(forKey: "privateKCV") as? NSString { // Decrypt the private key if let decryptedPrivateKey = masterPassword.serviceKey?.decrypt(encryptedPrivateKey as String, cipherLength: 0) { let k = RSAKey(identifier: _AUTHME_SERVICE_RSA_KEY_TAG) if (k?.loadPKCS8PrivateKey(decryptedPrivateKey as Data!))! && (k?.compareKCV(privateKCV as String))! { if (k?.loadPublicKey(publicKey as String))! { masterPassword.serviceKeyPair = k logger.log(.debug, message: "Service Key Pair loaded") masterPassword.serviceActivated() return } } } } } } logger.log(.warn, message: "Failed to load service key pair") } func stateMachine(_ operation: AuthMeServiceOperation) { // This basically works through each of the steps to initialise switch operation.operationType { case .addDevice: logger.log(.debug, message: "Add Device Returned") if operation.statusCode == 200 || operation.statusCode == 201 { // Good to continue getDevice() } case .getDevice: logger.log(.debug, message: "Get Device Returned") if operation.statusCode == 200 { if let readData = operation.returnData { let json = (try! JSONSerialization.jsonObject(with: readData as Data, options: JSONSerialization.ReadingOptions.mutableContainers)) as! NSDictionary checkDevice(json, withNonce: operation.opaqueData as! String) } } case .getServiceKey: logger.log(.debug, message: "Get Service Key Returned") if operation.statusCode == 200 { if let readData = operation.returnData { let json = (try! JSONSerialization.jsonObject(with: readData as Data, options: JSONSerialization.ReadingOptions.mutableContainers)) as! NSDictionary loadServiceKey(json) } } case .setServiceKey: logger.log(.debug, message: "Set service key returned") if operation.statusCode == 201 { logger.log(.debug, message: "Service key created!") masterPassword.serviceKey = serviceAESKey masterPassword.serviceKeyPair = serviceRSAKey masterPassword.serviceActivated() } else { logger.log(.warn, message: "Set Service key failed - error \(operation.statusCode)") } default: logger.log(.error, message: "Unknown service operation returned!") } } func service(_ service: AuthMeService, didCompletOperation operation: AuthMeServiceOperation, withOpaqueData opaqueData: AnyObject?) { logger.log(.debug, message: "Service return") stateMachine(operation) } func signerDidComplete(_ signer: AuthMeSign, didSucceed: Bool, withOpaqueData opaqueData: AnyObject?) { logger.log(.debug, message: "Signer returned") _ = authme.setServiceKey(masterPassword.getUniqueDeviceId(), encryptedKeyValue: encryptedServiceAESKey, keyKCV: serviceAESKCV, encryptedPrivateKey: encryptedServicePrivateKey, privateKVC: serviceRSAKCV, publicKey: serviceRSAKey!.getPublicKey(), signature: signer, delegate: self) } }
7b305ea53c8cac72020a0b149d10c2a8
38.972318
177
0.578774
false
false
false
false
vitkuzmenko/Swiftex
refs/heads/master
Extensions/UIKit/UIColor+Extension.swift
apache-2.0
1
// // UIColor+Extension.swift // WOSDK // // Created by Vitaliy Kuzmenko on 27/05/15. // Copyright (c) 2015. All rights reserved. // #if os(iOS) || os(watchOS) || os(tvOS) import UIKit extension UIColor { public func hexString(prefix: Bool = false) -> String { let components = self.cgColor.components; let r = components?[0]; let g = components?[1]; let b = components?[2]; let hexString = String(format: "%02X%02X%02X", Int(r! * 255), Int(g! * 255), Int(b! * 255)) return hexString } } #endif
4254a89b68791ab052e9391896a9f404
20.923077
99
0.580702
false
false
false
false
salemoh/GoldenQuraniOS
refs/heads/master
GoldenQuranSwift/GoldenQuranSwift/Constants.swift
mit
1
// // Constants.swift // GoldenQuranSwift // // Created by Omar Fraiwan on 2/12/17. // Copyright © 2017 Omar Fraiwan. All rights reserved. // import Foundation import UIKit struct Constants { static let iOS_LANGUAGES_KEY = "AppleLanguages" static let CURRENT_MUSHAF_KEY = "CurrentMushafGUID" struct color { static let GQBrown = UIColor(red:152.0/255.0 , green:111.0/255.0 , blue:65.0/255.0 , alpha:1.0) as UIColor } struct path { static let documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String static let library = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] as String static let tmp = NSTemporaryDirectory() } struct db { static let defaultMus7afList = "Mus7af" static var defaultMus7afListDBPath:String{ get{ return Bundle.main.path(forResource: Constants.db.defaultMus7afList, ofType: "db")!} } static var userMus7afListDBPath:String{ get{ return Constants.path.library.appending("/\(Constants.db.defaultMus7afList).db")} } static func mushafWithDBName(name:String) -> String{ var verifiedName:String = name var dbExtenstion:String = "db" if name.lowercased().hasSuffix(".db") { let range = name.lowercased().range(of: ".db") verifiedName = name.replacingCharacters(in: range!, with: "") dbExtenstion = name.components(separatedBy: ".").last! } return Bundle.main.path(forResource: verifiedName, ofType: dbExtenstion, inDirectory: "GoldenQuranRes/db")! } static var mushafByTopicDBPath:String{ get{ return Bundle.main.path(forResource: "QuranMawdoo3", ofType: "db", inDirectory: "GoldenQuranRes/db/Additions")!} } static var mushafTextDBPath:String{ get{ return Bundle.main.path(forResource: "quran_text_ar", ofType: "db", inDirectory: "GoldenQuranRes/db")!} } static var mushafMo3jamDBPath:String{ get{ return Bundle.main.path(forResource: "QuranMo3jm", ofType: "db", inDirectory: "GoldenQuranRes/db/Additions")!} } static var hadithFortyDBPath:String{ get{ return Bundle.main.path(forResource: "HadithContent", ofType: "db", inDirectory: "GoldenQuranRes/db")!} } static var mushafRecitationAndTafseerDBPath:String{ get{return Bundle.main.path(forResource: "TafseerAndRecitation", ofType: "db")!} } } struct storyboard { static let main = UIStoryboard(name:"main" , bundle:nil) static let mushaf = UIStoryboard(name:"Mushaf" , bundle:nil) } struct notifiers { static let pageColorChanged = "PAGE_COLOR_CHANGED" static let pageHighlightTopicsChanged = "PAGE_HIGHLIGHT_TOPICS_CHANGED" } struct userDefaultsKeys { //Notifications static let notificationsFridayDisabled = "NOTIFICATIONS_FRIDAY_DISABLED" static let notificationsLongTimeReadingDisabled = "NOTIFICATIONS_LONG_TIME_READING_DISABLED" static let notificationsDailyDisabled = "NOTIFICATIONS_DAILY_DISABLED" static let notificationsAthanDisabled = "NOTIFICATIONS_ATHAN_DISABLED" //Notifications Athan (notification by time) static let notificationsAthanFajrDisabled = "NOTIFICATIONS_ATHAN_DISABLED_FAJR" static let notificationsAthanDouhrDisabled = "NOTIFICATIONS_ATHAN_DISABLED_DUHOR" static let notificationsAthanAsrDisabled = "NOTIFICATIONS_ATHAN_DISABLED_ASR" static let notificationsAthanMaghribDisabled = "NOTIFICATIONS_ATHAN_DISABLED_MAGHRIB" static let notificationsAthanIshaDisabled = "NOTIFICATIONS_ATHAN_DISABLED_ISHA" ///Location Manager static let lastKnownLocationLat = "LOCATION_LAST_KNOWN_LAT" static let lastKnownLocationLon = "LOCATION_LAST_KNOWN_LON" //Prayer Times static let prayerTimesAdjustmentFajr = "PrayerTimesAdjustments_fajr" static let prayerTimesAdjustmentSunrise = "PrayerTimesAdjustments_sunrise" static let prayerTimesAdjustmentDhuhr = "PrayerTimesAdjustments_dhuhr" static let prayerTimesAdjustmentAsr = "PrayerTimesAdjustments_asr" static let prayerTimesAdjustmentMagrib = "PrayerTimesAdjustments_maghrib" static let prayerTimesAdjustmentIsha = "PrayerTimesAdjustments_isha" static let prayerTimesSettingsCalculationMethod = "PrayerTimesSettingsCalcultionMethod" static let prayerTimesSettingsCalculationMadhab = "PrayerTimesSettingsCalcultionMadhab" static let prayerTimesSettingsNotificationSound = "PrayerTimesSettingsNotificationSound" //// Features menu static let highlightMushafByTopicsEnabled = "highlightMushafByTopicsEnabled" /////Page color static let preferedPageBackgroundColor = "PreferedPageBackgroundColor" /////Font size static let preferedFontSize = "PreferedFontSize" //Recitations static let favouriteRecitations = "FavoriteRecitations" //Tafseers static let favouriteTafseers = "FavoriteTafseers" static let activeTafseer = "ActiveTafseer" } }
7263b1a3c9f3747b10335877620a30f6
41.527132
129
0.671163
false
false
false
false
wangkai678/WKDouYuZB
refs/heads/master
WKDouYuZB/WKDouYuZB/Classes/Home/Controller/HomeViewController.swift
mit
1
// // HomeViewController.swift // WKDouYuZB // // Created by wangkai on 17/5/9. // Copyright © 2017年 wk. All rights reserved. // import UIKit private let kTitleViewH:CGFloat = 44; class HomeViewController: UIViewController { //MARK:- 懒加载属性 fileprivate lazy var pageTitleView : PageTitleView = {[weak self] in let titleFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW,height: kTitleViewH); let titles = ["推荐","游戏","娱乐","趣玩"]; let titleView = PageTitleView(frame:titleFrame,titles:titles); titleView.delegate = self; return titleView; }(); fileprivate lazy var pageContentView: PageContentView = {[weak self] in let contentH = kScreenH - kStatusBarH - kNavigationBarH - kTitleViewH - kTabBarH; let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewH, width: kScreenW, height: contentH); var childVcs = [UIViewController](); childVcs.append(RecommendViewController()); childVcs.append(GameViewController()); childVcs.append(AmuseViewController()); childVcs.append(FunnyViewController()); let contentView = PageContentView(frame: contentFrame,childVcs:childVcs,parentViewController:self); contentView.delegate = self; return contentView; }(); override func viewDidLoad() { super.viewDidLoad() //不需要调整UIscrollView的内边距 automaticallyAdjustsScrollViewInsets = false; //1.设置UI界面 setupUI(); //2.添加TitleView view.addSubview(pageTitleView); //3.添加contentview view.addSubview(pageContentView); } } //MARK:-设置UI界面 extension HomeViewController{ fileprivate func setupUI(){ setupNavigationBar(); } fileprivate func setupNavigationBar(){ //设置左侧的item let fixedSpaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action:nil);//为了调整leftItem的位置 fixedSpaceItem.width = -10; let leftItem = UIBarButtonItem(imageName: "logo");//用自定义的view原因是会有点击高亮效果 navigationItem.leftBarButtonItems = [fixedSpaceItem,leftItem]; //设置右侧的item let size = CGSize(width:30,height:30); let histyoryItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size); let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size); let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size); navigationItem.rightBarButtonItems = [fixedSpaceItem,histyoryItem,searchItem,qrcodeItem]; } } //MARK:遵守PageTitleViewDelegate协议 extension HomeViewController : PageTitleViewDelegate{ func pageTitleView(titleView: PageTitleView, selectedIndex index: Int) { pageContentView.setCurrentIndex(currentIndex: index); } } //MARK:遵守PageContentViewDelegate协议 extension HomeViewController : PageContentViewDelegate{ func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex); } }
6101c817c33ee55c5d94f94a493b67fc
36.781609
127
0.691816
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/decl/inherit/inherit.swift
apache-2.0
7
// RUN: %target-typecheck-verify-swift class A { } protocol P { } // Duplicate inheritance class B : A, A { } // expected-error{{duplicate inheritance from 'A'}}{{12-15=}} // Duplicate inheritance from protocol class B2 : P, P { } // expected-error{{duplicate inheritance from 'P'}}{{13-16=}} // Multiple inheritance class C : B, A { } // expected-error{{multiple inheritance from classes 'B' and 'A'}} // Superclass in the wrong position class D : P, A { } // expected-error{{superclass 'A' must appear first in the inheritance clause}}{{12-15=}}{{11-11=A, }} // Struct inheriting a class struct S : A { } // expected-error{{non-class type 'S' cannot inherit from class 'A'}} // Protocol inheriting a class protocol Q : A { } // expected-error{{non-class type 'Q' cannot inherit from class 'A'}} // Extension inheriting a class extension C : A { } // expected-error{{extension of type 'C' cannot inherit from class 'A'}} // Keywords in inheritance clauses struct S2 : struct { } // expected-error{{expected type}} // Protocol composition in inheritance clauses struct S3 : P, P & Q { } // expected-error {{redundant conformance of 'S3' to protocol 'P'}} // expected-error @-1 {{'Q' requires that 'S3' inherit from 'A'}} // expected-note @-2 {{requirement specified as 'Self' : 'A' [with Self = S3]}} // expected-note @-3 {{'S3' declares conformance to protocol 'P' here}} struct S4 : P, P { } // expected-error {{duplicate inheritance from 'P'}} struct S6 : P & { } // expected-error {{expected identifier for type name}} struct S7 : protocol<P, Q> { } // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} // expected-error @-1 {{'Q' requires that 'S7' inherit from 'A'}} // expected-note @-2 {{requirement specified as 'Self' : 'A' [with Self = S7]}} class GenericBase<T> {} class GenericSub<T> : GenericBase<T> {} // okay class InheritGenericParam<T> : T {} // expected-error {{inheritance from non-protocol, non-class type 'T'}} class InheritBody : T { // expected-error {{use of undeclared type 'T'}} typealias T = A } class InheritBodyBad : fn { // expected-error {{use of undeclared type 'fn'}} func fn() {} }
904a04c2cb7d69f45172b08ead0dc28e
44.745098
134
0.62709
false
false
false
false
bfortunato/aj-framework
refs/heads/master
platforms/ios/Libs/AJ/AJ/AJTimers.swift
apache-2.0
1
// // AJTimers.swift // AJ // // Created by bruno fortunato on 17/03/16. // Copyright © 2016 Bruno Fortunato. All rights reserved. // import UIKit import JavaScriptCore import ApplicaFramework let asyncQueue = DispatchQueue(label: "ApplicaFramework.timersAsyncQueue") @objc protocol AJTimersProtocol { func setTimeout(_ action: JSValue, _ delay: Int) -> Int func setInterval(_ action: JSValue, _ delay: Int) -> Int func clearTimeout(_ timerId: Int) func clearInterval(_ timerId: Int) } var AJTimerActionCounter = 0 class AJTimerAction { let id: Int var timer: Timer? let action: JSValue let delayTime: Int var loop = false var complete = false var canceled = false init(action: JSValue, delay: Int) { AJTimerActionCounter += 1 id = AJTimerActionCounter self.action = action self.delayTime = delay } deinit { } func execute() { if delayTime > 0 { AJThread.delay(Double(self.delayTime) / 1000.0) { [weak self] () -> Void in if let me = self { if (!me.canceled) { me._run() } me.complete = true; } } } else { self._run() self.complete = true; } } @objc func _run() { self.action.call(withArguments: []) if (!self.loop) { self.complete = true; } } func cancel() { self.canceled = true; } } @objc class AJTimers: NSObject, AJTimersProtocol { var actions = [AJTimerAction]() func setTimeout(_ action: JSValue, _ delay: Int) -> Int { let timerAction = AJTimerAction(action: action, delay: delay) timerAction.loop = false append(action: timerAction) timerAction.execute() return timerAction.id } func setInterval(_ action: JSValue, _ delay: Int) -> Int { let timerAction = AJTimerAction(action: action, delay: delay) timerAction.loop = true actions.append(timerAction) timerAction.execute() return timerAction.id } func append(action: AJTimerAction) { //first of all, clear completed timer actions actions = actions.filter({!$0.complete}) actions.append(action) } func clearTimeout(_ timerId: Int) { if let timerAction = actions.filter({ $0.id == timerId }).first { timerAction.cancel() } } func clearInterval(_ timerId: Int) { clearTimeout(timerId) } }
156ddebfb009e6014940e568e95f4d91
22.228814
87
0.542868
false
false
false
false
YSduang/YSwift
refs/heads/master
anySignPlugin/anySignPlugin/ViewController.swift
mit
1
// // ViewController.swift // anySignPlugin // // Created by BJCA on 16/4/20. // Copyright © 2016年 YSdang. All rights reserved. // import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{ @IBOutlet weak var photoView: UIImageView! @IBOutlet weak var height: NSLayoutConstraint! @IBAction func takePhoto(sender: UIButton) { let junk = UIImagePickerController() let sourceType = UIImagePickerControllerSourceType.Camera if (UIImagePickerController.isSourceTypeAvailable(sourceType)) { junk.sourceType = sourceType } else { // let a = UIAlertController.init(title: "Stop!", message: "NO camera", preferredStyle: ) // a.show } junk.delegate = self self.presentViewController(junk, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() let screenW:CGFloat = UIScreen.mainScreen().bounds.width self.height.constant = screenW * 320 / 240 } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info:[String : AnyObject]) { let image: UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage self.photoView.image = image self.photoView.frame.size = image.size picker.dismissViewControllerAnimated(true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { picker.dismissViewControllerAnimated(true, completion: nil) } }
dad315a9609540435e68b6b2b1640c40
23.959459
122
0.602057
false
false
false
false
nathan/hush
refs/heads/master
Shared/Hasher.swift
unlicense
1
#if os(iOS) import UIKit #else import Cocoa #endif @objc class HashOptions : NSObject, NSCopying, NSCoding { dynamic var length = 16 dynamic var requireDigit = true dynamic var requireSpecial = true dynamic var requireMixed = true dynamic var forbidSpecial = false dynamic var onlyDigits = false required override init() {} required init?(coder aDecoder: NSCoder) { length = aDecoder.decodeInteger(forKey: "length") requireDigit = aDecoder.decodeBool(forKey: "requireDigit") requireSpecial = aDecoder.decodeBool(forKey: "requireSpecial") requireMixed = aDecoder.decodeBool(forKey: "requireMixed") forbidSpecial = aDecoder.decodeBool(forKey: "forbidSpecial") onlyDigits = aDecoder.decodeBool(forKey: "onlyDigits") } func encode(with aCoder: NSCoder) { aCoder.encode(length, forKey: "length") aCoder.encode(requireDigit, forKey: "requireDigit") aCoder.encode(requireSpecial, forKey: "requireSpecial") aCoder.encode(requireMixed, forKey: "requireMixed") aCoder.encode(forbidSpecial, forKey: "forbidSpecial") aCoder.encode(onlyDigits, forKey: "onlyDigits") } required init?(json: Dictionary<String, AnyObject>) { if let x = json["length"] as? Int {length = x} if let x = json["requireDigit"] as? Bool {requireDigit = x} if let x = json["requireSpecial"] as? Bool {requireSpecial = x} if let x = json["requireMixed"] as? Bool {requireMixed = x} if let x = json["forbidSpecial"] as? Bool {forbidSpecial = x} if let x = json["onlyDigits"] as? Bool {onlyDigits = x} } func toJSON() -> Dictionary<String, AnyObject> {return [ "length": length as AnyObject, "requireDigit": requireDigit as AnyObject, "requireSpecial": requireSpecial as AnyObject, "requireMixed": requireMixed as AnyObject, "forbidSpecial": forbidSpecial as AnyObject, "onlyDigits": onlyDigits as AnyObject, ]} func copy(with zone: NSZone?) -> Any { let options = HashOptions() options.setTo(self) return options } func setTo(_ o: HashOptions) { length = o.length requireDigit = o.requireDigit requireSpecial = o.requireSpecial requireMixed = o.requireMixed forbidSpecial = o.forbidSpecial onlyDigits = o.onlyDigits } static func fromDefaults(_ defaults: UserDefaults = UserDefaults.standard) -> HashOptions { let options = HashOptions() options.length = defaults.integer(forKey: "length") options.requireDigit = defaults.bool(forKey: "requireDigit") options.requireSpecial = defaults.bool(forKey: "requireSpecial") options.requireMixed = defaults.bool(forKey: "requireMixed") options.onlyDigits = defaults.bool(forKey: "onlyDigits") options.forbidSpecial = defaults.bool(forKey: "forbidSpecial") return options } func saveDefaults(_ defaults: UserDefaults = UserDefaults.standard) { let defaults = UserDefaults.standard defaults.set(requireDigit, forKey: "requireDigit") defaults.set(requireSpecial, forKey: "requireSpecial") defaults.set(requireMixed, forKey: "requireMixed") defaults.set(onlyDigits, forKey: "onlyDigits") defaults.set(forbidSpecial, forKey: "forbidSpecial") defaults.set(length, forKey: "length") } } class Hasher : NSObject { var options: HashOptions init(options: HashOptions) { self.options = options } func hash(tag: String, pass: String) -> String? { guard pass != "" && tag != "", let passData = pass.data(using: String.Encoding.ascii), let tagData = tag.data(using: String.Encoding.ascii) else {return nil} let outPtr = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(CC_SHA1_DIGEST_LENGTH)) CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), (passData as NSData).bytes, passData.count, (tagData as NSData).bytes, tagData.count, outPtr) let outData = Data(bytes: UnsafePointer<UInt8>(outPtr), count: Int(CC_SHA1_DIGEST_LENGTH)) guard let b64 = NSString(data: outData.base64EncodedData(options: []), encoding: String.Encoding.utf8.rawValue) as String? else {return nil} let seed = b64.utf8.reduce(0) {$0 + Int($1)} - (b64.last == "=" ? Int("=".utf8.first!) : 0) let str = b64[b64.startIndex..<b64.index(b64.startIndex, offsetBy: options.length)] var utf = Array(str.utf8) if options.onlyDigits { convertToDigits(&utf, seed: seed) } else { if options.requireDigit { injectChar(&utf, at: 0, seed: seed, from: 0x30, length: 10) } if options.requireSpecial && !options.forbidSpecial { injectChar(&utf, at: 1, seed: seed, from: 0x21, length: 15) } if options.requireMixed { injectChar(&utf, at: 2, seed: seed, from: 0x41, length: 26) injectChar(&utf, at: 3, seed: seed, from: 0x61, length: 26) } if options.forbidSpecial { stripSpecial(&utf, seed: seed) } } var result = "" for x in utf { result += String(Character(UnicodeScalar(x))) } return result } func convertToDigits(_ utf: inout [UTF8.CodeUnit], seed: Int) { // logic error in original: var index = 0 var digit = false for (i, x) in utf.enumerated() { if 0x30 <= x && x <= 0x39 { if !digit {index = i} digit = true continue } utf[i] = UTF8.CodeUnit(0x30 + (seed + Int(utf[index])) % 10) index = i + 1 digit = false } // correct implementation: // for (i, x) in utf.enumerate() { // if 0x30 <= x && x <= 0x39 {continue} // utf[i] = UTF8.CodeUnit(0x30 + (seed + Int(x)) % 10) // } } var reservedChars: Int {get {return 4}} func injectChar(_ utf: inout [UTF8.CodeUnit], at offset: Int, seed: Int, from start: UTF8.CodeUnit, length: UTF8.CodeUnit) { let pos = (seed + offset) % utf.count for i in 0..<utf.count - reservedChars { let x = utf[(seed + reservedChars + i) % utf.count] if start <= x && x <= start + length {return} } utf[pos] = UTF8.CodeUnit(Int(start) + (seed + Int(utf[pos])) % Int(length)) } func stripSpecial(_ utf: inout [UTF8.CodeUnit], seed: Int) { // TODO: very similar to convertToDigits, but awkwardly different // logic error in original: var index = 0 var special = true for (i, x) in utf.enumerated() { if 0x30 <= x && x <= 0x39 || 0x41 <= x && x <= 0x5a || 0x61 <= x && x <= 0x7a { if special {index = i} special = false continue } utf[i] = UTF8.CodeUnit(0x41 + (seed + index) % 26) index = i + 1 special = true } // correct implementation: // for (i, x) in utf.enumerate() { // if 0x30 <= x && x <= 0x39 || 0x41 <= x && x <= 0x5a || 0x61 <= x && x <= 0x7a {continue} // utf[i] = UTF8.CodeUnit(0x41 + (seed + Int(x)) % 26) // } } static func formatTag(_ base: String) -> String { // just spaces // return base.lowercaseString.stringByReplacingOccurrencesOfString(" ", withString: " ") // kill EVERYTHING (except letters and numbers) let set = CharacterSet.alphanumerics.inverted return base.lowercased().components(separatedBy: set).joined(separator: "") } static func bumpTag(_ tag: String) -> String { var components = tag.components(separatedBy: ":") if components.count > 1 { let last = components.removeLast() if let n = Int(last) { components.append(String(n + 1)) return components.joined(separator: ":") } } return "\(tag):1" } }
6bcd5b2ce5a801ba154a4454d9ab6377
36.235
144
0.646838
false
false
false
false
qixizhu/PHCyclePictureView
refs/heads/master
Example/PHCyclePictureView/ViewController.swift
mit
1
// // ViewController.swift // PHCyclePictureView // // Created by qixizhu on 10/19/2017. // Copyright (c) 2017 qixizhu. All rights reserved. // import UIKit import PHCyclePictureView class ViewController: UIViewController { @IBOutlet weak var cyclePictureView: PHCyclePictureView! override func viewDidLoad() { super.viewDidLoad() let images = ["http://bizhi.zhuoku.com/bizhi2008/0516/3d/3d_desktop_13.jpg", "http://tupian.enterdesk.com/2012/1015/zyz/03/5.jpg", "http://img.web07.cn/UpImg/Desk/201301/12/desk230393121053551.jpg", "http://wallpaper.160.com/Wallpaper/Image/1280_960/1280_960_37227.jpg", "http://imgsrc.baidu.com/forum/w%3D580/sign=4e0ee1bcd2c8a786be2a4a065709c9c7/bc71953eb13533fae99ad268abd3fd1f40345bf5.jpg"] let titles = ["标题一", "标题二", "标题三", "标题四", "标题五"] cyclePictureView.placeholderImage = #imageLiteral(resourceName: "loading") cyclePictureView.pageControlPosition = .left cyclePictureView.imagePaths = images cyclePictureView.imageTitles = titles // 底部容器的背景颜色 // cyclePictureView.anchorBackgroundColor = .clear cyclePictureView.delegate = self view.addSubview(cyclePictureView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: PHCyclePictureViewDelegate { func cyclePictureView(_ cyclePictureView: PHCyclePictureView, didTapItemAt index: Int) { print("点击了第\(index + 1)张图片") } }
efe570bfec766b9a87d78decf6da2ffa
34.680851
145
0.663685
false
false
false
false
laurentVeliscek/AudioKit
refs/heads/master
AudioKit/Common/MIDI/AKMIDINode.swift
mit
2
// // AKMIDINode.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import AVFoundation import CoreAudio /// A version of AKInstrument specifically targeted to instruments that /// should be triggerable via MIDI or sequenced with the sequencer. public class AKMIDINode: AKNode, AKMIDIListener { // MARK: - Properties /// MIDI Input public var midiIn = MIDIEndpointRef() /// Name of the instrument public var name = "AKMIDINode" internal var internalNode: AKPolyphonicNode // MARK: - Initialization /// Initialize the MIDI node /// /// - parameter node: A polyphonic node that will be triggered via MIDI /// public init(node: AKPolyphonicNode) { internalNode = node super.init() avAudioNode = internalNode.avAudioNode } /// Enable MIDI input from a given MIDI client /// This is not in the init function because it must be called AFTER you start audiokit /// /// - Parameters: /// - midiClient: A refernce to the midi client /// - name: Name to connect with /// public func enableMIDI(midiClient: MIDIClientRef, name: String) { var result: OSStatus result = MIDIDestinationCreateWithBlock(midiClient, name, &midiIn, MyMIDIReadBlock) CheckError(result) } // MARK: - Handling MIDI Data // Send MIDI data to the audio unit func handleMIDI(data1 data1: UInt32, data2: UInt32, data3: UInt32) { let status = Int(data1 >> 4) let noteNumber = Int(data2) let velocity = Int(data3) if status == AKMIDIStatus.NoteOn.rawValue && velocity > 0 { internalNode.play(noteNumber: noteNumber, velocity: velocity) } else if status == AKMIDIStatus.NoteOn.rawValue && velocity == 0 { internalNode.stop(noteNumber: noteNumber) } else if status == AKMIDIStatus.NoteOff.rawValue { internalNode.stop(noteNumber: noteNumber) } } /// Handle MIDI commands that come in externally /// /// - Parameters: /// - noteNumber: MIDI Note number /// - velocity: MIDI velocity /// - channel: MIDI channel /// public func receivedMIDINoteOn(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel) { if velocity > 0 { internalNode.play(noteNumber: noteNumber, velocity: velocity) } else { internalNode.stop(noteNumber: noteNumber) } } private func MyMIDIReadBlock( packetList: UnsafePointer<MIDIPacketList>, srcConnRefCon: UnsafeMutablePointer<Void>) -> Void { let packetCount = Int(packetList.memory.numPackets) let packet = packetList.memory.packet as MIDIPacket var packetPointer: UnsafeMutablePointer<MIDIPacket> = UnsafeMutablePointer.alloc(1) packetPointer.initialize(packet) for _ in 0 ..< packetCount { let event = AKMIDIEvent(packet: packetPointer.memory) handleMIDI(data1: UInt32(event.internalData[0]), data2: UInt32(event.internalData[1]), data3: UInt32(event.internalData[2])) packetPointer = MIDIPacketNext(packetPointer) } } }
381366fe3b559fa6e08385767e08eeb4
31.625
91
0.630121
false
false
false
false
TrustWallet/trust-wallet-ios
refs/heads/master
Trust/Core/Network/Transactions/EthereumTransactionsProvider.swift
gpl-3.0
1
// Copyright DApps Platform Inc. All rights reserved. import Foundation import Result import APIKit import JSONRPCKit class EthereumTransactionsProvider: TransactionsNetworkProvider { let server: RPCServer init( server: RPCServer ) { self.server = server } func update(for transaction: Transaction, completion: @escaping (Result<(Transaction, TransactionState), AnyError>) -> Void) { let request = GetTransactionRequest(hash: transaction.id) Session.send(EtherServiceRequest(for: server, batch: BatchFactory().create(request))) { [weak self] result in guard let `self` = self else { return } switch result { case .success(let tx): guard let newTransaction = Transaction.from(initialTransaction: transaction, transaction: tx, coin: self.server.coin) else { return completion(.success((transaction, .pending))) } if newTransaction.blockNumber > 0 { self.getReceipt(for: newTransaction, completion: completion) } case .failure(let error): switch error { case .responseError(let error): guard let error = error as? JSONRPCError else { return } switch error { case .responseError: if transaction.date > Date().addingTimeInterval(TrustNetwork.deleteMissingInternalSeconds) { completion(.success((transaction, .deleted))) } case .resultObjectParseError: if transaction.date > Date().addingTimeInterval(TrustNetwork.deleteMissingInternalSeconds) { completion(.success((transaction, .failed))) } default: break } default: break } } } } private func getReceipt(for transaction: Transaction, completion: @escaping (Result<(Transaction, TransactionState), AnyError>) -> Void) { let request = GetTransactionReceiptRequest(hash: transaction.id) Session.send(EtherServiceRequest(for: server, batch: BatchFactory().create(request))) { result in switch result { case .success(let receipt): let newTransaction = transaction newTransaction.gasUsed = receipt.gasUsed let state: TransactionState = receipt.status ? .completed : .failed completion(.success((newTransaction, state))) case .failure(let error): completion(.failure(AnyError(error))) } } } }
3bbcc2b805d9ed2aa85a4534e194583a
41.507692
142
0.576547
false
false
false
false
IGRSoft/IGRPhotoTweaks
refs/heads/master
IGRPhotoTweaks/IGRPhotoTweakViewController.swift
mit
1
// // IGRPhotoTweakViewController.swift // IGRPhotoTweaks // // Created by Vitalii Parovishnyk on 2/6/17. // Copyright © 2017 IGR Software. All rights reserved. // import UIKit public protocol IGRPhotoTweakViewControllerDelegate : class { /** Called on image cropped. */ func photoTweaksController(_ controller: IGRPhotoTweakViewController, didFinishWithCroppedImage croppedImage: UIImage) /** Called on cropping image canceled */ func photoTweaksControllerDidCancel(_ controller: IGRPhotoTweakViewController) } open class IGRPhotoTweakViewController: UIViewController { //MARK: - Public VARs /* Image to process. */ public var image: UIImage! /* The optional photo tweaks controller delegate. */ public weak var delegate: IGRPhotoTweakViewControllerDelegate? //MARK: - Protected VARs /* Flag indicating whether the image cropped will be saved to photo library automatically. Defaults to YES. */ internal var isAutoSaveToLibray: Bool = false //MARK: - Private VARs public lazy var photoView: IGRPhotoTweakView! = { [unowned self] by in let photoView = IGRPhotoTweakView(frame: self.view.bounds, image: self.image, customizationDelegate: self) photoView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.view.addSubview(photoView) return photoView }(()) // MARK: - Life Cicle override open func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false self.view.clipsToBounds = true self.setupThemes() self.setupSubviews() } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) in self.photoView.applyDeviceRotation() }) } fileprivate func setupSubviews() { self.view.sendSubviewToBack(self.photoView) } open func setupThemes() { IGRPhotoTweakView.appearance().backgroundColor = UIColor.photoTweakCanvasBackground() IGRPhotoContentView.appearance().backgroundColor = UIColor.clear IGRCropView.appearance().backgroundColor = UIColor.clear IGRCropGridLine.appearance().backgroundColor = UIColor.gridLine() IGRCropLine.appearance().backgroundColor = UIColor.cropLine() IGRCropCornerView.appearance().backgroundColor = UIColor.clear IGRCropCornerLine.appearance().backgroundColor = UIColor.cropLine() IGRCropMaskView.appearance().backgroundColor = UIColor.mask() } // MARK: - Public public func resetView() { self.photoView.resetView() self.stopChangeAngle() } public func dismissAction() { self.delegate?.photoTweaksControllerDidCancel(self) } public func cropAction() { var transform = CGAffineTransform.identity // translate let translation: CGPoint = self.photoView.photoTranslation transform = transform.translatedBy(x: translation.x, y: translation.y) // rotate transform = transform.rotated(by: self.photoView.radians) // scale let t: CGAffineTransform = self.photoView.photoContentView.transform let xScale: CGFloat = sqrt(t.a * t.a + t.c * t.c) let yScale: CGFloat = sqrt(t.b * t.b + t.d * t.d) transform = transform.scaledBy(x: xScale, y: yScale) if let fixedImage = self.image.cgImageWithFixedOrientation() { let imageRef = fixedImage.transformedImage(transform, zoomScale: self.photoView.scrollView.zoomScale, sourceSize: self.image.size, cropSize: self.photoView.cropView.frame.size, imageViewSize: self.photoView.photoContentView.bounds.size) let image = UIImage(cgImage: imageRef) if self.isAutoSaveToLibray { self.saveToLibrary(image: image) } self.delegate?.photoTweaksController(self, didFinishWithCroppedImage: image) } } //MARK: - Customization open func customBorderColor() -> UIColor { return UIColor.cropLine() } open func customBorderWidth() -> CGFloat { return 1.0 } open func customCornerBorderWidth() -> CGFloat { return kCropViewCornerWidth } open func customCornerBorderLength() -> CGFloat { return kCropViewCornerLength } open func customCropLinesCount() -> Int { return kCropLinesCount } open func customGridLinesCount() -> Int { return kGridLinesCount } open func customIsHighlightMask() -> Bool { return true } open func customHighlightMaskAlphaValue() -> CGFloat { return 0.3 } open func customCanvasInsets() -> UIEdgeInsets { return UIEdgeInsets(top: kCanvasHeaderHeigth, left: 0, bottom: 0, right: 0) } }
3e370f208e3afb85f0916858d1f0e096
30.955307
122
0.613811
false
false
false
false
cwwise/CWWeChat
refs/heads/master
CWWeChat/MainClass/Mine/Expression/Model/EmoticonPackage.swift
mit
2
// // EmoticonPackage.swift // CWWeChat // // Created by chenwei on 2017/8/23. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit import Kingfisher // 一组有序的表情,构成一个表情包。 // 一组有序的表情包,构成一个分区。 /// 表情分区 public class EmoticonZone: NSObject { var name: String // 表情包 var packageList: [EmoticonPackage] var count: Int { return packageList.count } subscript(index: Int) -> EmoticonPackage { return packageList[index] } init(name: String, packageList: [EmoticonPackage]) { self.name = name self.packageList = packageList } } /// 表情包 public class EmoticonPackage: NSObject { /// 表情作者 class EmoticonAuthor: NSObject { var name: String = "" var avatar: URL? var banner: URL? var userDescription: String = "" } // 标签类型 var type: EmoticonType = .normal // id var id: String // 表情包名称 var name: String // 副标题 var subTitle: String? // 更新时间 var updated_at: String? var cover: URL? // banner url var banner: URL? // 作者 var author: EmoticonAuthor? // 表情数组 var emoticonList: [Emoticon] = [] // MARK: 表情逻辑 var downloadSuccess: Bool = false init(id: String, name: String) { self.id = id self.name = name } } extension EmoticonPackage: Resource { public var downloadURL: URL { return cover! } public var cacheKey: String { return id } }
95bbfc1d513d3b851966dc1b2be91269
16.781609
56
0.568843
false
false
false
false
bradhilton/Table
refs/heads/master
Example/FormViewController.swift
mit
1
// // FormViewController.swift // Table // // Created by Bradley Hilton on 3/16/17. // Copyright © 2017 Brad Hilton. All rights reserved. // import UIKit import Table class FieldCell : UITableViewCell { let textField = UITextField() var editingDidEnd: (String) -> () = { _ in } var primaryActionTriggered: (UITextField) -> () = { _ in } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(textField) textField.translatesAutoresizingMaskIntoConstraints = false textField.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16).isActive = true textField.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true textField.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true textField.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -30).isActive = true textField.addTarget(self, action: #selector(editingDidEnd(textField:)), for: [.editingDidEnd]) textField.addTarget(self, action: #selector(primaryActionTriggered(textField:)), for: [.primaryActionTriggered]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func editingDidEnd(textField: UITextField) { editingDidEnd(textField.text ?? "") } @objc func primaryActionTriggered(textField: UITextField) { primaryActionTriggered(textField) } } struct Field { let placeholder: String var text: String = "" init(placeholder: String) { self.placeholder = placeholder self.text = "" } } class FormViewController : UITableViewController { var fields = [ Field(placeholder: "First Name"), Field(placeholder: "Last Name"), Field(placeholder: "Email Address"), Field(placeholder: "Phone Number"), Field(placeholder: "Street"), Field(placeholder: "Street 2"), Field(placeholder: "City"), Field(placeholder: "State"), Field(placeholder: "Zip Code"), Field(placeholder: "Country") ] { didSet { tableView.sections = sections } } init() { super.init(style: .grouped) title = "Form" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.tableView.sections = sections } var sections: [Section] { return [ Section { (section: inout Section) in section.rows = fields.enumerated().map { (index, field) in return Row { row in row.height = 44 row.key = field.placeholder row.cell = Cell { [unowned self] (cell: FieldCell) in cell.textField.placeholder = field.placeholder cell.textField.enablesReturnKeyAutomatically = true cell.textField.returnKeyType = index + 1 == self.fields.endIndex ? .done : .next cell.textField.text = field.text cell.editingDidEnd = { [unowned self] text in self.fields[index].text = text } cell.primaryActionTriggered = { textField in textField.tabToNextResponder() } } } } } ] } } extension UIView { private var rootView: UIView { return superview?.rootView ?? self } private var descendents: [UIView] { return subviews + subviews.flatMap { $0.descendents } } private var descendentResponders: [UIView] { return descendents.filter { $0.canBecomeFirstResponder } } private var sortedDescendentResponders: [UIView] { return descendentResponders.sorted { lhs, rhs in let lhs = convert(lhs.frame.origin, from: lhs) let rhs = convert(rhs.frame.origin, from: rhs) return lhs.y == rhs.y ? lhs.x < rhs.x : lhs.y < rhs.y } } private var subsequentResponder: UIView? { let sortedResponders = rootView.sortedDescendentResponders guard let index = sortedResponders.index(of: self) else { return nil } return sortedResponders[(index + 1)...].first } func tabToNextResponder() { if let subsequentResponder = subsequentResponder { subsequentResponder.becomeFirstResponder() } else { resignFirstResponder() } } }
4e1722ad0e54bacba2daa84fe63e9f1f
31.807947
120
0.582156
false
false
false
false
KazmaStudio/Feeding
refs/heads/master
CODE/iOS/Feeding/Feeding/CONST.swift
mit
1
// // CONST.swift // Feeding // // Created by zhaochenjun on 2017/5/4. // Copyright © 2017年 com.kazmastudio. All rights reserved. // import Foundation import UIKit // MARK: String const let STRING_EMPTY = "" let STRING_CELL = "CELL" // MARK: Number let INT_0 = 0 let INT_1 = 1 let INT_10 = 10 let INT_12 = 12 let INT_14 = 14 let INT_16 = 16 let INT_18 = 18 let INT_20 = 20 let INT_24 = 24 let INT_32 = 32 let INT_40 = 40 let INT_44 = 44 let INT_64 = 64 let INT_96 = 96 // MARK: View controller name let VC_NAME_ARTICLE_LITS_TABLE = "ArticleListTableViewController" let VC_NAME_ARTICLE = "ArticleViewController" let VC_NAME_TARGET_LIST_TABLE = "TargetListTableViewController" // MARK: Cell name let CELL_ARTICLE_LIST_TYPE_A = "ArticleTypeATableViewCell" let CELL_ARTICLE_LIST_TYPE_B = "ArticleTypeBTableViewCell" let CELL_ARTICLE_LIST_TYPE_C = "ArticleTypeCTableViewCell" // MARK: Image name let IMG_NAME_TARGET = "target-o" let IMG_NAME_TARGET_COLOR = "target-color" let IMG_NAME_RECORD = "record" let IMG_NAME_CHECKED = "checked" let IMG_NAME_AVATAR_DEFAULT_GIRL = "avater-default-girl" let IMG_NAME_PLACEHOLDER = "placeholder" let IMG_NAME_CHAT = "chat" let IMG_NAME_ARTICLE = "article" // MARK: Oberve name let OBSERVE_KEY_ESTIMATED_PROGRESS = "estimatedProgress" // MARK: System size let ONE_PIXEL = 1 / UIScreen.main.scale let SCREEN_WIDTH = UIScreen.main.bounds.width let SCREEN_HEIGHT = UIScreen.main.bounds.height let STATEBAR_HEIGHT = UIApplication.shared.statusBarFrame.height let TAB_BAR_HEIGHT = CGFloat(49) // MARK: Color let COLOR_BOARD_GRAY = UIColor.init(red: 200 / 255, green: 200 / 255, blue: 220 / 255, alpha: 1) let COLOR_TARGET_RED = UIColor.init(red: 226 / 255, green: 87 / 255, blue: 76 / 255, alpha: 1) // MARK: Tag number let TAG_CELL_HIGHLIGHT_VIEW = 99901 let TAG_TIP_VIEW = 99902 // MARK: Text let TEXT_ADD_TARGET_SUCCESS = "🙂 添加Target成功" let TEXT_CANCEL_TARGET_SUCCESS = "🙂 取消Target成功"
5bbe10c739fa14f865145a59c36c5edb
25.805556
96
0.722798
false
false
false
false
TabletopAssistant/DiceKit
refs/heads/master
DiceKit/FrequencyDistribution.swift
apache-2.0
1
// // FrequencyDistribution.swift // DiceKit // // Created by Brentley Jones on 7/24/15. // Copyright © 2015 Brentley Jones. All rights reserved. // import Foundation public protocol FrequencyDistributionOutcomeType: InvertibleMultiplicativeType, Hashable { /// The number that will be used when determining how many times to perform another /// expression when multiplied by `self`. var multiplierEquivalent: Int { get } } extension Int: InvertibleMultiplicativeType, FrequencyDistributionOutcomeType { public static let additiveIdentity: Int = 0 public static let multiplicativeIdentity: Int = 1 public var multiplierEquivalent: Int { return self } } extension Double: InvertibleMultiplicativeType { public static let additiveIdentity: Double = 0.0 public static let multiplicativeIdentity: Double = 1.0 public var multiplierEquivalent: Double { return self } } public struct FrequencyDistribution<OutcomeType: FrequencyDistributionOutcomeType>: Equatable { public typealias Outcome = OutcomeType public typealias Frequency = Double public typealias FrequenciesPerOutcome = [Outcome: Frequency] // TODO: Change to stored properties when allowed by Swift public static var additiveIdentity: FrequencyDistribution { return FrequencyDistribution(FrequenciesPerOutcome()) } public static var multiplicativeIdentity: FrequencyDistribution { return FrequencyDistribution([Outcome.additiveIdentity: Frequency.multiplicativeIdentity]) } public let frequenciesPerOutcome: FrequenciesPerOutcome let orderedOutcomes: [Outcome] internal init(_ frequenciesPerOutcome: FrequenciesPerOutcome, delta: Double) { self.frequenciesPerOutcome = frequenciesPerOutcome.filterValues { abs($0) > delta } self.orderedOutcomes = self.frequenciesPerOutcome.map { $0.0 }.sort() } public init(_ frequenciesPerOutcome: FrequenciesPerOutcome) { self.init(frequenciesPerOutcome, delta: 0.0) } } // MARK: - CustomStringConvertible extension FrequencyDistribution: CustomStringConvertible { public var description: String { let sortedFrequenciesPerOutcome = frequenciesPerOutcome.sort { $0.0 < $1.0 } let stringifiedFrequenciesPerOutcome: [String] = sortedFrequenciesPerOutcome.map { "\($0.0): \($0.1)" } let innerDesc = stringifiedFrequenciesPerOutcome.joinWithSeparator(", ") let desc = "[\(innerDesc)]" return desc } } // MARK: - Equatable public func == <V>(lhs: FrequencyDistribution<V>, rhs: FrequencyDistribution<V>) -> Bool { return lhs.frequenciesPerOutcome == rhs.frequenciesPerOutcome } // MARK: - Indexable extension FrequencyDistribution: Indexable { public typealias Index = FrequencyDistributionIndex<Outcome> public typealias _Element = (Outcome, Frequency) // This is needed to prevent ambigious Indexable conformance... /// Returns the `Index` for the given value, or `nil` if the value is not /// present in the frequency distribution. public func indexForOutcome(outcome: Outcome) -> Index? { guard frequenciesPerOutcome[outcome] != nil else { return nil } let index = orderedOutcomes.indexOf(outcome)! // This won't crash because we already know the value exists. This isn't used in the guard, because checking if it exists is O(1), while this is O(n) return FrequencyDistributionIndex(index: index, orderedOutcomes: orderedOutcomes) } public var startIndex: Index { return FrequencyDistributionIndex.startIndex(orderedOutcomes) } public var endIndex: Index { return FrequencyDistributionIndex.endIndex(orderedOutcomes) } public subscript(index: Index) -> (Outcome, Frequency) { let outcome = index.value! let frequency = frequenciesPerOutcome[outcome]! return (outcome, frequency) } } // MARK: - CollectionType extension FrequencyDistribution: CollectionType { // Protocol defaults cover implmentation after conforming to `Indexable` } // MARK: - Operations extension FrequencyDistribution { // MARK: Foundational Operations public func mapOutcomes(@noescape transform: (Outcome) -> Outcome) -> FrequencyDistribution { let newFrequenciesPerOutcome = frequenciesPerOutcome.mapKeys ({ $1 + $2 }) { (baseOutcome, _) in transform(baseOutcome) } return FrequencyDistribution(newFrequenciesPerOutcome) } public func mapFrequencies(@noescape transform: (Frequency) -> Frequency) -> FrequencyDistribution { let newFrequenciesPerOutcome = frequenciesPerOutcome.mapValues { (_, frequency) in transform(frequency) } return FrequencyDistribution(newFrequenciesPerOutcome) } // MARK: Primitive Operations public subscript(outcome: Outcome) -> Frequency? { get { return frequenciesPerOutcome[outcome] } } public func approximatelyEqual(x: FrequencyDistribution, delta: Frequency) -> Bool { guard frequenciesPerOutcome.count == x.frequenciesPerOutcome.count else { return false } for (outcome, frequency) in frequenciesPerOutcome { guard let otherFrequency = x.frequenciesPerOutcome[outcome] else { return false } let diff = abs(frequency - otherFrequency) if diff > delta { return false } } return true } public func negateOutcomes() -> FrequencyDistribution { return mapOutcomes { -$0 } } public func shiftOutcomes(outcome: Outcome) -> FrequencyDistribution { return mapOutcomes { $0 + outcome } } public func scaleFrequencies(frequency: Frequency) -> FrequencyDistribution { return mapFrequencies { $0 * frequency } } public func normalizeFrequencies() -> FrequencyDistribution { let frequencies: Frequency = frequenciesPerOutcome.reduce(0) { let (_, value) = $1 return $0 + value } return mapFrequencies { $0 / frequencies } } public func minimumOutcome() -> Outcome? { return orderedOutcomes.first } public func maximumOutcome() -> Outcome? { return orderedOutcomes.last } public func filterZeroFrequencies(delta: Frequency) -> FrequencyDistribution { let newFrequenciesPerOutcome = frequenciesPerOutcome return FrequencyDistribution(newFrequenciesPerOutcome, delta: delta) } // MARK: Advanced Operations public func add(x: FrequencyDistribution) -> FrequencyDistribution { var newFrequenciesPerOutcome = frequenciesPerOutcome for (outcome, frequency) in x.frequenciesPerOutcome { let exisitingFrequency = newFrequenciesPerOutcome[outcome] ?? 0 let newFrequency = exisitingFrequency + frequency newFrequenciesPerOutcome[outcome] = newFrequency } return FrequencyDistribution(newFrequenciesPerOutcome) } public func subtract(x: FrequencyDistribution) -> FrequencyDistribution { var newFrequenciesPerOutcome = frequenciesPerOutcome for (outcome, frequency) in x.frequenciesPerOutcome { let exisitingFrequency = newFrequenciesPerOutcome[outcome] ?? 0 let newFrequency = exisitingFrequency - frequency newFrequenciesPerOutcome[outcome] = newFrequency } return FrequencyDistribution(newFrequenciesPerOutcome) } public func multiply(x: FrequencyDistribution) -> FrequencyDistribution { return frequenciesPerOutcome.reduce(.additiveIdentity) { let (outcome, frequency) = $1 let addend = x.shiftOutcomes(outcome).scaleFrequencies(frequency) return $0.add(addend) } } /// This is a special case of `power(x: FrequencyDistribution)`, /// for when `x` is `FrequencyDistribution([x: 1])`. public func power(x: Outcome) -> FrequencyDistribution { let power = x.multiplierEquivalent guard power != 0 else { return .multiplicativeIdentity } // Crappy implementation. Currently O(n). Can be O(log(n)). var freqDist = self for _ in 1..<abs(power) { freqDist = freqDist.multiply(self) } // if (power < 0) { // return FrequencyDistribution.multiplicativeIdentity.divide(freqDist) // } else { return freqDist // } } public func power(x: FrequencyDistribution) -> FrequencyDistribution { return frequenciesPerOutcome.reduce(.additiveIdentity) { let (outcome, frequency) = $1 let addend = x.power(outcome).normalizeFrequencies().scaleFrequencies(frequency) return $0.add(addend) } } } // TODO: Remove the need for ForwardIndexType extension FrequencyDistribution where OutcomeType: ForwardIndexType { public func divide(y: FrequencyDistribution) -> FrequencyDistribution { guard let initialK = orderedOutcomes.first, lastK = orderedOutcomes.last else { return .additiveIdentity } guard let firstY = y.orderedOutcomes.first, lastY = y.orderedOutcomes.last, firstYFrequency = y[firstY] where firstYFrequency != 0.0 else { fatalError("Invalid divide operation. The divisor expression must not be empty, and its first frequency must not be zero.") } var xFrequencies: FrequenciesPerOutcome = [:] for k in initialK...(lastK + lastY) { var p: Frequency = 0.0 for (n, frequency) in xFrequencies { p += frequency * (y[k - n] ?? 0) } xFrequencies[k - firstY] = ((frequenciesPerOutcome[k] ?? 0) - p) / firstYFrequency } let delta = ProbabilityMassConfig.probabilityEqualityDelta return FrequencyDistribution(xFrequencies).filterZeroFrequencies(delta) } }
963a972e85948305ad12b7d94874e011
33.198675
203
0.659179
false
false
false
false
mparrish91/gifRecipes
refs/heads/master
framework/Model/Config.swift
mit
1
// // Config.swift // reddift // // Created by sonson on 2015/04/13. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation /** Class to manage parameters of reddift. This class is used as singleton model */ struct Config { /// Application verison, be updated by Info.plist later. let version: String /// Bundle identifier, be updated by Info.plist later. let bundleIdentifier: String /// Developer's reddit user name let developerName: String /// OAuth redirect URL you register let redirectURI: String /// Application ID let clientID: String /** Singleton model. */ static let sharedInstance = Config() /** Returns User-Agent for API */ var userAgent: String { return "ios:" + bundleIdentifier + ":v" + version + "(by /u/" + developerName + ")" } /** Returns scheme of redirect URI. */ var redirectURIScheme: String { if let scheme = URL(string:redirectURI)?.scheme { let poop = "gifrecipes" return poop } else { return "" } } init() { version = Bundle.infoValueInMainBundle(for: "CFBundleShortVersionString") as? String ?? "1.0" bundleIdentifier = Bundle.infoValueInMainBundle(for: "CFBundleIdentifier") as? String ?? "" var _developerName: String? = nil var _redirectURI: String? = nil var _clientID: String? = nil if let path = Bundle.main.path(forResource: "reddift_config", ofType: "json") { if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) { do { if let json = try JSONSerialization.jsonObject(with: data, options: []) as? JSONDictionary { _developerName = json["DeveloperName"] as? String _redirectURI = json["redirect_uri"] as? String _clientID = json["client_id"] as? String } } catch { } } } developerName = _developerName ?? "" redirectURI = _redirectURI ?? "" clientID = _clientID ?? "" } }
99edf6961f65c5a51f9593085d7916c2
27.842105
112
0.56615
false
true
false
false
CodaFi/swift
refs/heads/master
test/IRGen/Inputs/ObjectiveC.swift
apache-2.0
6
// This is an overlay Swift module. @_exported import ObjectiveC public struct ObjCBool : CustomStringConvertible { #if (os(macOS) && arch(x86_64)) || (os(iOS) && (arch(i386) || arch(arm) || targetEnvironment(macCatalyst))) // On macOS and 32-bit iOS, Objective-C's BOOL type is a "signed char". private var value: Int8 public init(_ value: Bool) { self.value = value ? 1 : 0 } /// Allow use in a Boolean context. public var boolValue: Bool { return value != 0 } #else // Everywhere else it is C/C++'s "Bool" private var value: Bool public init(_ value: Bool) { self.value = value } public var boolValue: Bool { return value } #endif public var description: String { // Dispatch to Bool. return self.boolValue.description } } public struct Selector { private var ptr : OpaquePointer } // Functions used to implicitly bridge ObjCBool types to Swift's Bool type. public func _convertBoolToObjCBool(_ x: Bool) -> ObjCBool { return ObjCBool(x) } public func _convertObjCBoolToBool(_ x: ObjCBool) -> Bool { return x.boolValue } extension NSObject : Hashable { public func hash(into hasher: inout Hasher) {} } public func ==(x: NSObject, y: NSObject) -> Bool { return x === y }
dd79bcdb9e673d73829c26bdc6034333
22.074074
107
0.670947
false
false
false
false
CodaFi/swift
refs/heads/main
validation-test/compiler_crashers_2_fixed/0059-sr3321.swift
apache-2.0
61
// RUN: %target-swift-frontend %s -emit-ir // RUN: %target-swift-frontend %s -emit-ir -O protocol ControllerB { associatedtype T: Controller } protocol Controller { associatedtype T func shouldSelect<S: ControllerB>(_ a: T, b: S) where S.T == Self } struct ControllerAImpl {} struct ControllerImpl : Controller { typealias T = ControllerAImpl func shouldSelect<S : ControllerB>(_ a: ControllerAImpl, b: S) where S.T == ControllerImpl {} } struct ControllerBImpl1 : ControllerB { typealias T = ControllerImpl } struct ControllerBImpl2<C : Controller> : ControllerB { typealias T = C } extension Controller { func didSelect<S: ControllerB>(_ a: T, b: S) where S.T == Self { shouldSelect(a, b: b) } } ControllerImpl().didSelect(ControllerAImpl(), b: ControllerBImpl1()) ControllerImpl().didSelect(ControllerAImpl(), b: ControllerBImpl2<ControllerImpl>())
89e36666647dc1c0dcb46fbab7ea2d74
23.27027
95
0.703786
false
false
false
false
dmitryrybakov/19test
refs/heads/master
19test/ComicDetailsViewController/ComicDetailsViewController.swift
artistic-2.0
1
// // ComicDetailsViewController.swift // 19test // // Created by Dmitry on 13.05.16. // Copyright © 2016 Dmitry Rybakov. All rights reserved. // import Foundation class ComicDetailsViewController: CommonViewController { @IBOutlet weak var comicImage: UIImageView! @IBOutlet weak var comicNameLabel: UILabel! var pageIndex:Int = 0 var imageURL:String? var comicTitle:String? let bgQueue = NSOperationQueue() override func viewDidLoad() { super.viewDidLoad() self.comicImage.image = UIImage(named:"placeholder") if let URLString = imageURL { let targetImageSize = self.comicImage.bounds.size self.showActivity(true) self.networkManager.getImageByURL(URLString, completionBlock: { (image) -> (Void) in if let imageObject = image { self.showActivity(false) self.bgQueue.addOperationWithBlock({ () -> Void in let resizedImage = imageObject.imageWithSizeKeepAspect(targetImageSize, fitToRect: true) NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in self.comicImage.image = resizedImage }) }) } }, failureBlock: { (error) -> (Void) in self.showActivity(false) if let errorObject = error { print("Error: \(errorObject.description)") } }) } if let titleObject = self.comicTitle { self.comicNameLabel.text = titleObject } } }
f99dd2b594a28629a485f8c0ebc69d48
29.31746
112
0.498167
false
false
false
false
quickthyme/PUTcat
refs/heads/master
PUTcat/Presentation/TransactionResponse/TransactionResponseViewController.swift
apache-2.0
1
import UIKit protocol TransactionResponseViewControllerInput : ViewDataItemSettable, ParentViewDataItemSettable, BasicAlertPresentable, ProgressDisplayable, ProjectIDSettable { func displayViewData(_ viewData: TransactionResponseViewData) func refreshView(_ sender: AnyObject?) } protocol TransactionResponseViewControllerDelegate { func getViewData(refID: String, parentRefID: String, viewController: TransactionResponseViewControllerInput) } class TransactionResponseViewController : UITableViewController { var viewData : TransactionResponseViewData = TransactionResponseViewData(section: []) var viewDataItem : ViewDataItem = TransactionResponseViewDataItem() var viewDataParent : ViewDataItem = TransactionResponseViewDataItem() var projectID: String? @IBOutlet weak var delegateObject : AnyObject? var delegate : TransactionResponseViewControllerDelegate? { return delegateObject as? TransactionResponseViewControllerDelegate } var hasAppeared : Bool = false var buttonItemsNorm : [UIBarButtonItem] { return [] } } // MARK: - Lifecycle extension TransactionResponseViewController { override func viewDidLoad() { super.viewDidLoad() self.setupNavigationBar() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.beginObservingKeyboardNotifications() self.handleFirstWillAppear(animated) } private func handleFirstWillAppear(_ animated: Bool) { guard self.hasAppeared == false else { return } self.hasAppeared = true self.refreshView(nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.endObservingKeyboardNotifications() } private func setupNavigationBar() { self.navigationItem.setRightBarButtonItems(buttonItemsNorm, animated: false) } } // MARK: - TransactionResponseViewControllerInput extension TransactionResponseViewController : TransactionResponseViewControllerInput { func set(viewDataItem: ViewDataItem) { self.viewDataItem = viewDataItem self.navigationItem.title = viewDataItem.title } func set(parentViewDataItem: ViewDataItem) { self.viewDataParent = parentViewDataItem } func displayViewData(_ viewData: TransactionResponseViewData) { self.viewData = viewData self.tableView?.reloadData() self.refreshControl?.endRefreshing() } @IBAction func refreshView(_ sender: AnyObject?) { self.delegate?.getViewData(refID: viewDataItem.refID, parentRefID: viewDataParent.refID, viewController: self) } }
0029e27f09f63e0aa5b072b983355bef
31.768293
118
0.743208
false
false
false
false
valleyman86/ReactiveCocoa
refs/heads/swift-development
ReactiveCocoa/Swift/FoundationExtensions.swift
mit
1
// // FoundationExtensions.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2014-10-19. // Copyright (c) 2014 GitHub. All rights reserved. // import Foundation import Result extension NSNotificationCenter { /// Returns a signal of notifications posted that match the given criteria. /// This signal will not terminate naturally, so it must be explicitly /// disposed to avoid leaks. public func rac_notifications(name: String? = nil, object: AnyObject? = nil) -> Signal<NSNotification, NoError> { return Signal { observer in let notificationObserver = self.addObserverForName(name, object: object, queue: nil) { notification in sendNext(observer, notification) } return ActionDisposable { self.removeObserver(notificationObserver) } } } } extension NSURLSession { /// Returns a producer that will execute the given request once for each /// invocation of start(). public func rac_dataWithRequest(request: NSURLRequest) -> SignalProducer<(NSData, NSURLResponse), NSError> { return SignalProducer { observer, disposable in let task = self.dataTaskWithRequest(request) { (data, response, error) in if let data = data, response = response { sendNext(observer, (data, response)) sendCompleted(observer) } else { sendError(observer, error) } } disposable.addDisposable { task.cancel() } task.resume() } } } /// Removes all nil values from the given sequence. internal func ignoreNil<T, S: SequenceType where S.Generator.Element == Optional<T>>(sequence: S) -> [T] { var results: [T] = [] for value in sequence { if let value = value { results.append(value) } } return results }
e063633ea5ddaa4840f6669b54bfb1fc
25.888889
114
0.706021
false
false
false
false
wscqs/FMDemo-
refs/heads/master
FMDemo/Classes/Utils/Extension/String+Extension.swift
apache-2.0
1
// // String+Extension.swift // QSBaoKan // // Created by mba on 16/6/7. // Copyright © 2016年 cqs. All rights reserved. // import UIKit extension String{ // MARK: 缓存目录 /** 将当前字符串拼接到cache目录后面 */ func cacheDir() -> String{ let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString return path.appendingPathComponent((self as NSString).lastPathComponent) } /** 将当前字符串拼接到doc目录后面 */ func docDir() -> String { let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString return path.appendingPathComponent((self as NSString).lastPathComponent) } /** 将当前字符串拼接到doc目录后面 */ func docRecordDir() -> String { let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString let recordPath = path.appendingPathComponent("record") if !FileManager.default.fileExists(atPath: recordPath) { do{ try FileManager.default.createDirectory(atPath: recordPath, withIntermediateDirectories: false, attributes: nil) }catch { } } return (recordPath as NSString).appendingPathComponent((self as NSString).lastPathComponent) } /** 将当前字符串拼接到doc目录后面 */ func docSaveRecordDir() -> String { let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString let recordPath = path.appendingPathComponent("saveRecord") if !FileManager.default.fileExists(atPath: recordPath) { do{ try FileManager.default.createDirectory(atPath: recordPath, withIntermediateDirectories: false, attributes: nil) }catch { } } return (recordPath as NSString).appendingPathComponent((self as NSString).lastPathComponent) } // MARK: 时间处理 /** 时间戳转为时间 - returns: 时间字符串 */ func timeStampToString() -> String { let string = NSString(string: self) let timeSta: TimeInterval = string.doubleValue let dfmatter = DateFormatter() dfmatter.dateFormat = "yyyy年MM月dd日" let date = Date(timeIntervalSince1970: timeSta) return dfmatter.string(from: date) } /** 时间转为时间戳 - returns: 时间戳字符串 */ func stringToTimeStamp()->String { let dfmatter = DateFormatter() dfmatter.dateFormat = "yyyy年MM月dd日" let date = dfmatter.date(from: self) let dateStamp: TimeInterval = date!.timeIntervalSince1970 let dateSt:Int = Int(dateStamp) return String(dateSt) } // MARK: 判断 /** 判断手机号是否合法 - returns: bool */ func isValidMobile() -> Bool { // 判断是否是手机号 let patternString = "^1[3|4|5|7|8][0-9]\\d{8}$" let predicate = NSPredicate(format: "SELF MATCHES %@", patternString) return predicate.evaluate(with: self) } /** 判断密码是否合法 - returns: bool */ func isValidPasswod() -> Bool { // 验证密码是 6 - 16 位字母或数字 let patternString = "^[0-9A-Za-z]{6,16}$" let predicate = NSPredicate(format: "SELF MATCHES %@", patternString) return predicate.evaluate(with: self) } func md5() ->String{ let str = self.cString(using: String.Encoding.utf8) let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0 ..< digestLen { hash.appendFormat("%02x", result[i]) } result.deinitialize() return String(format: hash as String) } }
0bc79aeffbf81ee23f68e427c0ce8eac
31.098485
179
0.632051
false
false
false
false
PedroTrujilloV/TIY-Assignments
refs/heads/master
37--Resurgence/VenueMenu/VenueMenu/APIController.swift
cc0-1.0
1
// // APIController.swift // VenueMenu // // Created by Pedro Trujillo on 11/29/15. // Copyright © 2015 Pedro Trujillo. All rights reserved. // import Foundation class APIController { var delegator: APIControllerProtocol init(delegate:APIControllerProtocol) { self.delegator = delegate } func searchApiFoursquareForData(searchTerm:String = "", byCriteria:String = "", location:String) { let arrayTerm = location.characters.split(" ") print(">>>>>>>>>>>>>>>>>>arrayTerm: \(arrayTerm.count)") let foursquareSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) if let escapedSearchTerm = foursquareSearchTerm.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet()) { //let searchString = cityAndStateArray.joinWithSeparator(", ") let url:NSURL if byCriteria == "ll" { let urlRequestByLatAndLong = "https://api.foursquare.com/v2/venues/search?client_id=OA5RPW0Y4AHZ0EPBIMXRNOSJQGAM0IFCKY11KEBGWIUK4L2A&client_secret=WK3N22CGBLPEM3B5OKELM2JNI4ISXOGAIAAKLVLYZ0QVXP3D&v=20130815&ll="+location+"&query="+escapedSearchTerm url = NSURL(string: urlRequestByLatAndLong)! print("search by ll") } else { let locationWithoutSpaces = location.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) let urlRequestByNamePlus = "https://api.foursquare.com/v2/venues/explore?client_id=OA5RPW0Y4AHZ0EPBIMXRNOSJQGAM0IFCKY11KEBGWIUK4L2A&client_secret=WK3N22CGBLPEM3B5OKELM2JNI4ISXOGAIAAKLVLYZ0QVXP3D&v=20130815&near="+locationWithoutSpaces+"&query="+escapedSearchTerm url = NSURL(string: urlRequestByNamePlus)! print("search by anything") } let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in print("completed Task foursquare ") if error != nil { print(error!.localizedDescription) } else { if let dictionary = self.parseJSON(data!) { if let response:NSDictionary = dictionary["response"] as? NSDictionary { if byCriteria == "ll" { if let venues:NSArray = response["venues"] as? NSArray { self.delegator.didReceiveAPIResults(venues) // print("------------NSArray venues: \(venues)") } } else { if let groups:NSArray = response["groups"] as? NSArray { var venuesArray:Array<NSDictionary> = [] for group in groups { if let items:NSArray = group["items"] as? NSArray { for item in items { if let venue:NSDictionary = item["venue"] as? NSDictionary { venuesArray.append(venue) //print("------------NSDictionary venue: \(venue)") } } //print("------------NSArray items: \(items)") } } //print("------------NSArray groups: \(groups)") self.delegator.didReceiveAPIResults(venuesArray) } } //print("------------NSDictionary response: \(response)") } //print("dictionary parseJSON: \(dictionary)" ) } // print("urlRequestByUser: \(url)") } }) task.resume() } } func parseJSON(data:NSData) -> NSDictionary? { do { let dictionary: NSDictionary! = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary return dictionary } catch let error as NSError { print(error) return nil } } }
98f0cb0350fe4c811623aee1369815d1
38.061224
278
0.416652
false
false
false
false
devcastid/iOS-Tutorials
refs/heads/master
Davcast-iOS/Pods/Material/Sources/MaterialLayer.swift
mit
1
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Material nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(MaterialDelegate) public protocol MaterialDelegate {} @objc(MaterialLayer) public class MaterialLayer : CAShapeLayer { /** A CAShapeLayer used to manage elements that would be affected by the clipToBounds property of the backing layer. For example, this allows the dropshadow effect on the backing layer, while clipping the image to a desired shape within the visualLayer. */ public private(set) lazy var visualLayer: CAShapeLayer = CAShapeLayer() /// A property that accesses the layer.frame.origin.x property. public var x: CGFloat { get { return frame.origin.x } set(value) { frame.origin.x = value } } /// A property that accesses the layer.frame.origin.y property. public var y: CGFloat { get { return frame.origin.y } set(value) { frame.origin.y = value } } /** A property that accesses the layer.frame.origin.width property. When setting this property in conjunction with the shape property having a value that is not .None, the height will be adjusted to maintain the correct shape. */ public var width: CGFloat { get { return frame.size.width } set(value) { frame.size.width = value if .None != shape { frame.size.height = value } } } /** A property that accesses the layer.frame.origin.height property. When setting this property in conjunction with the shape property having a value that is not .None, the width will be adjusted to maintain the correct shape. */ public var height: CGFloat { get { return frame.size.height } set(value) { frame.size.height = value if .None != shape { frame.size.width = value } } } /** A property that manages an image for the visualLayer's contents property. Images should not be set to the backing layer's contents property to avoid conflicts when using clipsToBounds. */ public var image: UIImage? { didSet { visualLayer.contents = image?.CGImage } } /** Allows a relative subrectangle within the range of 0 to 1 to be specified for the visualLayer's contents property. This allows much greater flexibility than the contentsGravity property in terms of how the image is cropped and stretched. */ public override var contentsRect: CGRect { didSet { visualLayer.contentsRect = contentsRect } } /** A CGRect that defines a stretchable region inside the visualLayer with a fixed border around the edge. */ public override var contentsCenter: CGRect { didSet { visualLayer.contentsCenter = contentsCenter } } /** A floating point value that defines a ratio between the pixel dimensions of the visualLayer's contents property and the size of the layer. By default, this value is set to the UIScreen's scale value, UIScreen.mainScreen().scale. */ public override var contentsScale: CGFloat { didSet { visualLayer.contentsScale = contentsScale } } /// Determines how content should be aligned within the visualLayer's bounds. public override var contentsGravity: String { get { return visualLayer.contentsGravity } set(value) { visualLayer.contentsGravity = value } } /** A property that sets the shadowOffset, shadowOpacity, and shadowRadius for the backing layer. This is the preferred method of setting depth in order to maintain consitency across UI objects. */ public var depth: MaterialDepth = .None { didSet { let value: MaterialDepthType = MaterialDepthToValue(depth) shadowOffset = value.offset shadowOpacity = value.opacity shadowRadius = value.radius } } /** A property that sets the cornerRadius of the backing layer. If the shape property has a value of .Circle when the cornerRadius is set, it will become .None, as it no longer maintains its circle shape. */ public var cornerRadiusPreset: MaterialRadius = .None { didSet { if let v: MaterialRadius = cornerRadiusPreset { cornerRadius = MaterialRadiusToValue(v) if .Circle == shape { shape = .None } } } } /** A property that sets the cornerRadius of the backing layer. If the shape property has a value of .Circle when the cornerRadius is set, it will become .None, as it no longer maintains its circle shape. */ public override var cornerRadius: CGFloat { didSet { if .Circle == shape { shape = .None } } } /** A property that manages the overall shape for the object. If either the width or height property is set, the other will be automatically adjusted to maintain the shape of the object. */ public var shape: MaterialShape = .None { didSet { if .None != shape { if width < height { frame.size.width = height } else { frame.size.height = width } } } } /// A preset property to set the borderWidth. public var borderWidthPreset: MaterialBorder = .None { didSet { borderWidth = MaterialBorderToValue(borderWidthPreset) } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareVisualLayer() } /** An initializer the same as init(). The layer parameter is ignored to avoid crashes on certain architectures. - Parameter layer: AnyObject. */ public override init(layer: AnyObject) { super.init() prepareVisualLayer() } /// A convenience initializer. public override init() { super.init() prepareVisualLayer() } /** An initializer that initializes the object with a CGRect object. - Parameter frame: A CGRect instance. */ public convenience init(frame: CGRect) { self.init() self.frame = frame } public override func layoutSublayers() { super.layoutSublayers() layoutShape() layoutVisualLayer() } /** A method that accepts CAAnimation objects and executes. - Parameter animation: A CAAnimation instance. */ public func animate(animation: CAAnimation) { animation.delegate = self if let a: CABasicAnimation = animation as? CABasicAnimation { a.fromValue = (nil == presentationLayer() ? self : presentationLayer() as! CALayer).valueForKeyPath(a.keyPath!) } if let a: CAPropertyAnimation = animation as? CAPropertyAnimation { addAnimation(a, forKey: a.keyPath!) } else if let a: CAAnimationGroup = animation as? CAAnimationGroup { addAnimation(a, forKey: nil) } else if let a: CATransition = animation as? CATransition { addAnimation(a, forKey: kCATransition) } } /** A delegation method that is executed when the layer starts running an animation. - Parameter anim: The currently running CAAnimation instance. */ public override func animationDidStart(anim: CAAnimation) { (delegate as? MaterialAnimationDelegate)?.materialAnimationDidStart?(anim) } /** A delegation method that is executed when the layer stops running an animation. - Parameter anim: The CAAnimation instance that stopped running. - Parameter flag: A boolean that indicates if the animation stopped because it was completed or interrupted. True if completed, false if interrupted. */ public override func animationDidStop(anim: CAAnimation, finished flag: Bool) { if anim is CAPropertyAnimation { (delegate as? MaterialAnimationDelegate)?.materialAnimationDidStop?(anim, finished: flag) } else if let a: CAAnimationGroup = anim as? CAAnimationGroup { for x in a.animations! { animationDidStop(x, finished: true) } } layoutVisualLayer() } /// Prepares the visualLayer property. public func prepareVisualLayer() { // visualLayer visualLayer.zPosition = 0 visualLayer.masksToBounds = true addSublayer(visualLayer) } /// Manages the layout for the visualLayer property. internal func layoutVisualLayer() { visualLayer.frame = bounds visualLayer.position = CGPointMake(width / 2, height / 2) visualLayer.cornerRadius = cornerRadius } /// Manages the layout for the shape of the layer instance. internal func layoutShape() { if .Circle == shape { cornerRadius = width / 2 } } }
9987afc05dec199922b052eb74243c94
27.981873
114
0.731367
false
false
false
false
flodolo/firefox-ios
refs/heads/main
Client/Application/AppDelegate+PushNotifications.swift
mpl-2.0
2
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import UIKit import Shared import Storage import Sync import UserNotifications import Account import MozillaAppServices /** * This exists because the Sync code is extension-safe, and thus doesn't get * direct access to UIApplication.sharedApplication, which it would need to display a notification. * This will also likely be the extension point for wipes, resets, and getting access to data sources during a sync. */ enum SentTabAction: String { case view = "TabSendViewAction" static let TabSendURLKey = "TabSendURL" static let TabSendTitleKey = "TabSendTitle" static let TabSendCategory = "TabSendCategory" static func registerActions() { let viewAction = UNNotificationAction(identifier: SentTabAction.view.rawValue, title: .SentTabViewActionTitle, options: .foreground) // Register ourselves to handle the notification category set by NotificationService for APNS notifications let sentTabCategory = UNNotificationCategory( identifier: "org.mozilla.ios.SentTab.placeholder", actions: [viewAction], intentIdentifiers: [], options: UNNotificationCategoryOptions(rawValue: 0)) UNUserNotificationCenter.current().setNotificationCategories([sentTabCategory]) } } extension AppDelegate { func pushNotificationSetup() { UNUserNotificationCenter.current().delegate = self SentTabAction.registerActions() NotificationCenter.default.addObserver(forName: .RegisterForPushNotifications, object: nil, queue: .main) { _ in UNUserNotificationCenter.current().getNotificationSettings { settings in DispatchQueue.main.async { if settings.authorizationStatus != .denied { UIApplication.shared.registerForRemoteNotifications() } } } } // If we see our local device with a pushEndpointExpired flag, clear the APNS token and re-register. NotificationCenter.default.addObserver(forName: .constellationStateUpdate, object: nil, queue: nil) { notification in if let newState = notification.userInfo?["newState"] as? ConstellationState { if newState.localDevice?.pushEndpointExpired ?? false { MZKeychainWrapper.sharedClientAppContainerKeychain.removeObject(forKey: KeychainKey.apnsToken, withAccessibility: MZKeychainItemAccessibility.afterFirstUnlock) NotificationCenter.default.post(name: .RegisterForPushNotifications, object: nil) } } } // Use sync event as a periodic check for the apnsToken. // The notification service extension can clear this token if there is an error, and the main app can detect this and re-register. NotificationCenter.default.addObserver(forName: .ProfileDidStartSyncing, object: nil, queue: .main) { _ in let kc = MZKeychainWrapper.sharedClientAppContainerKeychain if kc.object(forKey: KeychainKey.apnsToken, withAccessibility: MZKeychainItemAccessibility.afterFirstUnlock) == nil { NotificationCenter.default.post(name: .RegisterForPushNotifications, object: nil) } } } private func openURLsInNewTabs(_ notification: UNNotification) { var receivedUrlsQueue: [URL] = [] guard let urls = notification.request.content.userInfo["sentTabs"] as? [NSDictionary] else { return } for sentURL in urls { if let urlString = sentURL.value(forKey: "url") as? String, let url = URL(string: urlString) { receivedUrlsQueue.append(url) } } // Check if the app is foregrounded, _also_ verify the BVC is initialized. Most BVC functions depend on viewDidLoad() having run –if not, they will crash. if UIApplication.shared.applicationState == .active { let browserViewController = BrowserViewController.foregroundBVC() browserViewController.loadQueuedTabs(receivedURLs: receivedUrlsQueue) } } } extension AppDelegate: UNUserNotificationCenterDelegate { // Called when the user taps on a sent-tab notification from the background. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { openURLsInNewTabs(response.notification) } // Called when the user receives a tab (or any other notification) while in foreground. func userNotificationCenter( _ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void ) { if profile.prefs.boolForKey(PendingAccountDisconnectedKey) ?? false { profile.removeAccount() // show the notification completionHandler([.alert, .sound]) } else { openURLsInNewTabs(notification) } } } extension AppDelegate { func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { RustFirefoxAccounts.shared.pushNotifications.didRegister(withDeviceToken: deviceToken) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("failed to register. \(error)") SentryIntegration.shared.send(message: "Failed to register for APNS") } }
ab18b84dbe6abed51a14bd2495abd352
45.224
179
0.701454
false
false
false
false
taqun/TodoEver
refs/heads/master
TodoEver/Classes/ViewController/TDEIndexViewController.swift
mit
1
// // TDEIndexViewController.swift // TodoEver // // Created by taqun on 2015/05/27. // Copyright (c) 2015年 envoixapp. All rights reserved. // import UIKit class TDEIndexViewController: UITableViewController { /* * Debug */ @IBOutlet var __btnRefresh: UIBarButtonItem! @IBOutlet var __btnDelete: UIBarButtonItem! @objc private func __didBtnRefresh() { TDEEvernoteController.sharedInstance.sync() } @objc private func __didBtnDelete() { TDEModelManager.sharedInstance.truncate() } /* * Initialize */ override func viewDidLoad() { super.viewDidLoad() __btnRefresh.target = self __btnRefresh.action = Selector("__didBtnRefresh") __btnDelete.target = self __btnDelete.action = Selector("__didBtnDelete") } /* * Private Method */ @objc private func noteUpdated() { self.tableView.reloadData() } /* * UIViewController Method */ override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // navigation bar self.navigationController?.navigationBarHidden = false self.navigationItem.setHidesBackButton(true, animated: false) self.title = "TodoEver" // toolbar self.navigationController?.toolbarHidden = false NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("noteUpdated"), name: TDENotification.UPDATE_NOTES, object: nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } /* * UITableViewDataSource */ override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return TDEModelManager.sharedInstance.notes.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("IndexTableCell", forIndexPath: indexPath) as! UITableViewCell let note = TDEModelManager.sharedInstance.notes[indexPath.row] cell.textLabel?.text = note.title return cell } /* * UITableViewDelegate */ override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var note = TDEModelManager.sharedInstance.notes[indexPath.row] let taskListViewController = TDETaskListViewController(noteData: note) self.navigationController?.pushViewController(taskListViewController, animated: true) } }
15920919b901d4a30ed75b916baf05c7
26.320755
146
0.649862
false
false
false
false
xuech/OMS-WH
refs/heads/master
OMS-WH/Classes/OrderDetail/Model/KitDetailModel.swift
mit
1
// // KitDetailModel.swift // OMS // // Created by ___Gwy on 2017/8/29. // Copyright © 2017年 medlog. All rights reserved. // import UIKit @objcMembers class KitDetailModel: NSObject { var hMedKit:HMedKitModel? var prodLns:[KitProdLnsModel]? init(dict:[String:AnyObject]) { super.init() self.setValuesForKeys(dict) } override func setValue(_ value: Any?, forKey key: String) { super.setValue(value, forKey: key) if key == "prodLns" { var childrenCategory = [KitProdLnsModel]() let child = value as! [[String:AnyObject]] for dict in child { childrenCategory.append(KitProdLnsModel(dict: dict)) } prodLns = childrenCategory } if key == "hMedKit"{ let dict = value as! [String:AnyObject] hMedKit = HMedKitModel.init(dict: dict) } } override func setValue(_ value: Any?, forUndefinedKey key: String) { } } class HMedKitModel: CommonPaseModel { var kitCode:String? var kitDesc:String? var kitFullName:String? var kitName:String? var kitType:String? var kitTypeName:String? var medKitInternalNo:String? var medMIWarehouse:String? var oIName:String? var oIOrgCode:String? var relDesc:String? var relRemark:String? var remark:String? var validStatus:String? var validStatusName:String? var wHName:String? var wMSLastestSyncStatus:String? var wMSLastestSyncStatusBy:String? var wMSLastestSyncStatusDate:String? var wMSLastestSyncStatusInternalID:String? var wMSLastestSyncStatusRemark:String? var zoneCode:String? var zoneName:String? } class KitProdLnsModel: CommonPaseModel { var materials:[MedMaterialList]? var medBrandCode:String = "" var medBrandName:String = "" var medProdLnCode:String = "" var medProdLnName:String = "" var remark:String = "" override func setValue(_ value: Any?, forKey key: String) { super.setValue(value, forKey: key) if key == "materials" { var childrenCategory = [MedMaterialList]() let child = value as! [[String:AnyObject]] for dict in child { childrenCategory.append(MedMaterialList(dict: dict)) } materials = childrenCategory } } } class KitMaterialsModel: CommonPaseModel { var categoryByPlatform:String = "" var categoryByPlatformName = "" var medBrandCode:String = "" var medBrandName:String = "" var medMICode = "" var medMIInternalNo:String = "" var medMIName = "" var medMIUnitName:String = "" var medProdLnCode:String = "" var medProdLnName:String = "" var remark:String = "" var reqQty:NSNumber = 0 var specification = "" }
153abe9ebb3f033811de242f1ea8944e
25.831776
72
0.626611
false
false
false
false
CatchChat/Yep
refs/heads/master
Yep/Views/ActionSheet/ActionSheetView.swift
mit
1
// // ActionSheetView.swift // Yep // // Created by NIX on 16/3/2. // Copyright © 2016年 Catch Inc. All rights reserved. // import UIKit import YepKit // MARK: - ActionSheetDefaultCell final private class ActionSheetDefaultCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) makeUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var colorTitleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(18, weight: UIFontWeightLight) return label }() var colorTitleLabelTextColor: UIColor = UIColor.yepTintColor() { willSet { colorTitleLabel.textColor = newValue } } func makeUI() { contentView.addSubview(colorTitleLabel) colorTitleLabel.translatesAutoresizingMaskIntoConstraints = false let centerY = NSLayoutConstraint(item: colorTitleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0) let centerX = NSLayoutConstraint(item: colorTitleLabel, attribute: .CenterX, relatedBy: .Equal, toItem: contentView, attribute: .CenterX, multiplier: 1, constant: 0) NSLayoutConstraint.activateConstraints([centerY, centerX]) } } // MARK: - ActionSheetDetailCell final private class ActionSheetDetailCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) accessoryType = .DisclosureIndicator layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) textLabel?.textColor = UIColor.darkGrayColor() textLabel?.font = UIFont.systemFontOfSize(18, weight: UIFontWeightLight) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - ActionSheetSwitchCell final private class ActionSheetSwitchCell: UITableViewCell { var action: (Bool -> Void)? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) textLabel?.textColor = UIColor.darkGrayColor() textLabel?.font = UIFont.systemFontOfSize(18, weight: UIFontWeightLight) makeUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var checkedSwitch: UISwitch = { let s = UISwitch() s.addTarget(self, action: #selector(ActionSheetSwitchCell.toggleSwitch(_:)), forControlEvents: .ValueChanged) return s }() @objc private func toggleSwitch(sender: UISwitch) { action?(sender.on) } func makeUI() { contentView.addSubview(checkedSwitch) checkedSwitch.translatesAutoresizingMaskIntoConstraints = false let centerY = NSLayoutConstraint(item: checkedSwitch, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0) let trailing = NSLayoutConstraint(item: checkedSwitch, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .Trailing, multiplier: 1, constant: -20) NSLayoutConstraint.activateConstraints([centerY, trailing]) } } // MARK: - ActionSheetSubtitleSwitchCell final private class ActionSheetSubtitleSwitchCell: UITableViewCell { var action: (Bool -> Void)? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) layoutMargins = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) makeUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var titleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(18, weight: UIFontWeightLight) return label }() lazy var subtitleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(10, weight: UIFontWeightLight) label.textColor = UIColor.lightGrayColor() return label }() lazy var checkedSwitch: UISwitch = { let s = UISwitch() s.addTarget(self, action: #selector(ActionSheetSwitchCell.toggleSwitch(_:)), forControlEvents: .ValueChanged) return s }() @objc private func toggleSwitch(sender: UISwitch) { action?(sender.on) } func makeUI() { contentView.addSubview(checkedSwitch) titleLabel.translatesAutoresizingMaskIntoConstraints = false subtitleLabel.translatesAutoresizingMaskIntoConstraints = false checkedSwitch.translatesAutoresizingMaskIntoConstraints = false let titleStackView = UIStackView(arrangedSubviews: [titleLabel, subtitleLabel]) titleStackView.axis = .Vertical titleStackView.distribution = .Fill titleStackView.alignment = .Fill titleStackView.spacing = 2 titleStackView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(titleStackView) do { let centerY = NSLayoutConstraint(item: titleStackView, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0) let leading = NSLayoutConstraint(item: titleStackView, attribute: .Leading, relatedBy: .Equal, toItem: contentView, attribute: .Leading, multiplier: 1, constant: 20) NSLayoutConstraint.activateConstraints([centerY, leading]) } do { let centerY = NSLayoutConstraint(item: checkedSwitch, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0) let trailing = NSLayoutConstraint(item: checkedSwitch, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .Trailing, multiplier: 1, constant: -20) NSLayoutConstraint.activateConstraints([centerY, trailing]) } let gap = NSLayoutConstraint(item: checkedSwitch, attribute: .Leading, relatedBy: .Equal, toItem: titleStackView, attribute: .Trailing, multiplier: 1, constant: 10) NSLayoutConstraint.activateConstraints([gap]) } } final private class ActionSheetCheckCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) makeUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var colorTitleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(18, weight: UIFontWeightLight) return label }() lazy var checkImageView: UIImageView = { let image = UIImage.yep_iconLocationCheckmark let imageView = UIImageView(image: image) return imageView }() var colorTitleLabelTextColor: UIColor = UIColor.yepTintColor() { willSet { colorTitleLabel.textColor = newValue } } func makeUI() { contentView.addSubview(colorTitleLabel) contentView.addSubview(checkImageView) colorTitleLabel.translatesAutoresizingMaskIntoConstraints = false checkImageView.translatesAutoresizingMaskIntoConstraints = false let centerY = NSLayoutConstraint(item: colorTitleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0) let centerX = NSLayoutConstraint(item: colorTitleLabel, attribute: .CenterX, relatedBy: .Equal, toItem: contentView, attribute: .CenterX, multiplier: 1, constant: 0) NSLayoutConstraint.activateConstraints([centerY, centerX]) let checkImageViewCenterY = NSLayoutConstraint(item: checkImageView, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0) let checkImageViewTrailing = NSLayoutConstraint(item: checkImageView, attribute: .Trailing, relatedBy: .Equal, toItem: contentView, attribute: .Trailing, multiplier: 1, constant: -20) NSLayoutConstraint.activateConstraints([checkImageViewCenterY, checkImageViewTrailing]) } } // MARK: - ActionSheetView final class ActionSheetView: UIView { enum Item { case Default(title: String, titleColor: UIColor, action: () -> Bool) case Detail(title: String, titleColor: UIColor, action: () -> Void) case Switch(title: String, titleColor: UIColor, switchOn: Bool, action: (switchOn: Bool) -> Void) case SubtitleSwitch(title: String, titleColor: UIColor, subtitle: String, subtitleColor: UIColor, switchOn: Bool, action: (switchOn: Bool) -> Void) case Check(title: String, titleColor: UIColor, checked: Bool, action: () -> Void) case Cancel } var items: [Item] private let rowHeight: CGFloat = 60 private var totalHeight: CGFloat { return CGFloat(items.count) * rowHeight } init(items: [Item]) { self.items = items super.init(frame: CGRect.zero) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var containerView: UIView = { let view = UIView() view.backgroundColor = UIColor.clearColor() return view }() private lazy var tableView: UITableView = { let view = UITableView() view.dataSource = self view.delegate = self view.rowHeight = self.rowHeight view.scrollEnabled = false view.registerClassOf(ActionSheetDefaultCell) view.registerClassOf(ActionSheetDetailCell) view.registerClassOf(ActionSheetSwitchCell) view.registerClassOf(ActionSheetSubtitleSwitchCell) view.registerClassOf(ActionSheetCheckCell) return view }() private var isFirstTimeBeenAddedAsSubview = true override func didMoveToSuperview() { super.didMoveToSuperview() if isFirstTimeBeenAddedAsSubview { isFirstTimeBeenAddedAsSubview = false makeUI() let tap = UITapGestureRecognizer(target: self, action: #selector(ActionSheetView.hide)) containerView.addGestureRecognizer(tap) tap.cancelsTouchesInView = true tap.delegate = self } } func refreshItems() { dispatch_async(dispatch_get_main_queue()) { [weak self] in self?.tableView.reloadData() } } private var tableViewBottomConstraint: NSLayoutConstraint? private func makeUI() { addSubview(containerView) containerView.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(tableView) tableView.translatesAutoresizingMaskIntoConstraints = false let viewsDictionary: [String: AnyObject] = [ "containerView": containerView, "tableView": tableView, ] // layout for containerView let containerViewConstraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[containerView]|", options: [], metrics: nil, views: viewsDictionary) let containerViewConstraintsV = NSLayoutConstraint.constraintsWithVisualFormat("V:|[containerView]|", options: [], metrics: nil, views: viewsDictionary) NSLayoutConstraint.activateConstraints(containerViewConstraintsH) NSLayoutConstraint.activateConstraints(containerViewConstraintsV) // layout for tableView let tableViewConstraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[tableView]|", options: [], metrics: nil, views: viewsDictionary) let tableViewBottomConstraint = NSLayoutConstraint(item: tableView, attribute: .Bottom, relatedBy: .Equal, toItem: containerView, attribute: .Bottom, multiplier: 1.0, constant: self.totalHeight) self.tableViewBottomConstraint = tableViewBottomConstraint let tableViewHeightConstraint = NSLayoutConstraint(item: tableView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: self.totalHeight) NSLayoutConstraint.activateConstraints(tableViewConstraintsH) NSLayoutConstraint.activateConstraints([tableViewBottomConstraint, tableViewHeightConstraint]) } func showInView(view: UIView) { frame = view.bounds view.addSubview(self) layoutIfNeeded() containerView.alpha = 1 UIView.animateWithDuration(0.2, delay: 0.0, options: .CurveEaseIn, animations: { [weak self] _ in self?.containerView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3) }, completion: nil) UIView.animateWithDuration(0.2, delay: 0.1, options: .CurveEaseOut, animations: { [weak self] _ in self?.tableViewBottomConstraint?.constant = 0 self?.layoutIfNeeded() }, completion: nil) } func hide() { UIView.animateWithDuration(0.2, delay: 0.0, options: .CurveEaseIn, animations: { [weak self] _ in guard let strongSelf = self else { return } strongSelf.tableViewBottomConstraint?.constant = strongSelf.totalHeight strongSelf.layoutIfNeeded() }, completion: nil) UIView.animateWithDuration(0.2, delay: 0.1, options: .CurveEaseOut, animations: { [weak self] _ in self?.containerView.backgroundColor = UIColor.clearColor() }, completion: { [weak self] _ in self?.removeFromSuperview() }) } func hideAndDo(afterHideAction: (() -> Void)?) { UIView.animateWithDuration(0.2, delay: 0.0, options: .CurveLinear, animations: { [weak self] _ in guard let strongSelf = self else { return } strongSelf.containerView.alpha = 0 strongSelf.tableViewBottomConstraint?.constant = strongSelf.totalHeight strongSelf.layoutIfNeeded() }, completion: { [weak self] _ in self?.removeFromSuperview() }) delay(0.1) { afterHideAction?() } } } // MARK: - UIGestureRecognizerDelegate extension ActionSheetView: UIGestureRecognizerDelegate { func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { if touch.view != containerView { return false } return true } } // MARK: - UITableViewDataSource, UITableViewDelegate extension ActionSheetView: UITableViewDataSource, UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let item = items[indexPath.row] switch item { case let .Default(title, titleColor, _): let cell: ActionSheetDefaultCell = tableView.dequeueReusableCell() cell.colorTitleLabel.text = title cell.colorTitleLabelTextColor = titleColor return cell case let .Detail(title, titleColor, _): let cell: ActionSheetDetailCell = tableView.dequeueReusableCell() cell.textLabel?.text = title cell.textLabel?.textColor = titleColor return cell case let .Switch(title, titleColor, switchOn, action): let cell: ActionSheetSwitchCell = tableView.dequeueReusableCell() cell.textLabel?.text = title cell.textLabel?.textColor = titleColor cell.checkedSwitch.on = switchOn cell.action = action return cell case let .SubtitleSwitch(title, titleColor, subtitle, subtitleColor, switchOn, action): let cell: ActionSheetSubtitleSwitchCell = tableView.dequeueReusableCell() cell.titleLabel.text = title cell.titleLabel.textColor = titleColor cell.subtitleLabel.text = subtitle cell.subtitleLabel.textColor = subtitleColor cell.checkedSwitch.on = switchOn cell.action = action return cell case let .Check(title, titleColor, checked, _): let cell: ActionSheetCheckCell = tableView.dequeueReusableCell() cell.colorTitleLabel.text = title cell.colorTitleLabelTextColor = titleColor cell.checkImageView.hidden = !checked return cell case .Cancel: let cell: ActionSheetDefaultCell = tableView.dequeueReusableCell() cell.colorTitleLabel.text = String.trans_cancel cell.colorTitleLabelTextColor = UIColor.yepTintColor() return cell } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { defer { tableView.deselectRowAtIndexPath(indexPath, animated: true) } let item = items[indexPath.row] switch item { case .Default(_, _, let action): if action() { hide() } case .Detail(_, _, let action): hideAndDo { action() } case .Switch: break case .SubtitleSwitch: break case .Check(_, _, _, let action): action() hide() case .Cancel: hide() break } } }
5ba21119d964914887a91df87ec101b1
32.347505
202
0.666759
false
false
false
false
KaiCode2/swift-corelibs-foundation
refs/heads/master
Foundation/NSKeyedArchiver.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation // Archives created using the class method archivedRootDataWithObject used this key for the root object in the hierarchy of encoded objects. The NSKeyedUnarchiver class method unarchiveObjectWithData: will look for this root key as well. You can also use it as the key for the root object in your own archives. public let NSKeyedArchiveRootObjectKey: String = "root" typealias CFKeyedArchiverUID = CFTypeRef internal let NSKeyedArchiveNullObjectReference = NSKeyedArchiver._createObjectRef(0) internal let NSKeyedArchiveNullObjectReferenceName: String = "$null" internal let NSKeyedArchivePlistVersion = 100000 internal let NSKeyedArchiverSystemVersion : UInt32 = 2000 internal func objectRefGetValue(_ objectRef : CFKeyedArchiverUID) -> UInt32 { assert(objectRef.dynamicType == __NSCFType.self) assert(CFGetTypeID(objectRef) == _CFKeyedArchiverUIDGetTypeID()) return _CFKeyedArchiverUIDGetValue(unsafeBitCast(objectRef, to: CFKeyedArchiverUIDRef.self)) } internal func escapeArchiverKey(_ key: String) -> String { if key.hasPrefix("$") { return "$" + key } else { return key } } internal let NSPropertyListClasses : [AnyClass] = [ NSArray.self, NSDictionary.self, NSString.self, NSData.self, NSDate.self, NSNumber.self ] // NSUniqueObject is a wrapper that allows both hashable and non-hashable objects // to be used as keys in a dictionary internal struct NSUniqueObject : Hashable { var _backing : Any var _hashValue : () -> Int var _equality : (Any) -> Bool init<T: Hashable>(hashableObject: T) { self._backing = hashableObject self._hashValue = { hashableObject.hashValue } self._equality = { if let other = $0 as? T { return hashableObject == other } return false } } init(_ object: AnyObject) { // FIXME can't we check for Hashable directly? if let ns = object as? NSObject { self.init(hashableObject: ns) } else { self.init(hashableObject: ObjectIdentifier(object)) } } var hashValue: Int { return _hashValue() } } internal func ==(x : NSUniqueObject, y : NSUniqueObject) -> Bool { return x._equality(y._backing) } public class NSKeyedArchiver : NSCoder { struct ArchiverFlags : OptionSet { let rawValue : UInt init(rawValue : UInt) { self.rawValue = rawValue } static let None = ArchiverFlags(rawValue: 0) static let FinishedEncoding = ArchiverFlags(rawValue : 1) static let RequiresSecureCoding = ArchiverFlags(rawValue: 2) } private class EncodingContext { // the object container that is being encoded var dict = Dictionary<String, Any>() // the index used for non-keyed objects (encodeObject: vs encodeObject:forKey:) var genericKey : UInt = 0 } private static var _classNameMap = Dictionary<String, String>() private static var _classNameMapLock = NSLock() private var _stream : AnyObject private var _flags = ArchiverFlags(rawValue: 0) private var _containers : Array<EncodingContext> = [EncodingContext()] private var _objects : Array<Any> = [NSKeyedArchiveNullObjectReferenceName] private var _objRefMap : Dictionary<NSUniqueObject, UInt32> = [:] private var _replacementMap : Dictionary<NSUniqueObject, AnyObject> = [:] private var _classNameMap : Dictionary<String, String> = [:] private var _classes : Dictionary<String, CFKeyedArchiverUID> = [:] private var _cache : Array<CFKeyedArchiverUID> = [] public weak var delegate: NSKeyedArchiverDelegate? public var outputFormat = NSPropertyListFormat.BinaryFormat_v1_0 { willSet { if outputFormat != NSPropertyListFormat.XMLFormat_v1_0 && outputFormat != NSPropertyListFormat.BinaryFormat_v1_0 { NSUnimplemented() } } } public class func archivedDataWithRootObject(_ rootObject: AnyObject) -> NSData { let data = NSMutableData() let keyedArchiver = NSKeyedArchiver(forWritingWithMutableData: data) keyedArchiver.encodeObject(rootObject, forKey: NSKeyedArchiveRootObjectKey) keyedArchiver.finishEncoding() return data } public class func archiveRootObject(_ rootObject: AnyObject, toFile path: String) -> Bool { var fd : Int32 = -1 var auxFilePath : String var finishedEncoding : Bool = false do { (fd, auxFilePath) = try _NSCreateTemporaryFile(path) } catch _ { return false } defer { do { if finishedEncoding { try _NSCleanupTemporaryFile(auxFilePath, path) } else { try NSFileManager.defaultManager().removeItem(atPath: auxFilePath) } } catch _ { } } let writeStream = _CFWriteStreamCreateFromFileDescriptor(kCFAllocatorSystemDefault, fd)! if !CFWriteStreamOpen(writeStream) { return false } let keyedArchiver = NSKeyedArchiver(output: writeStream) keyedArchiver.encodeObject(rootObject, forKey: NSKeyedArchiveRootObjectKey) keyedArchiver.finishEncoding() finishedEncoding = keyedArchiver._flags.contains(ArchiverFlags.FinishedEncoding) CFWriteStreamClose(writeStream) return finishedEncoding } private init(output: AnyObject) { self._stream = output super.init() } public convenience init(forWritingWithMutableData data: NSMutableData) { self.init(output: data) } private func _writeXMLData(_ plist : NSDictionary) -> Bool { var success = false if let data = self._stream as? NSMutableData { let xml : CFData? xml = _CFPropertyListCreateXMLDataWithExtras(kCFAllocatorSystemDefault, plist) if let unwrappedXml = xml { data.append(unwrappedXml._nsObject) success = true } } else { success = CFPropertyListWrite(plist, self._stream as! CFWriteStream, kCFPropertyListOpenStepFormat, 0, nil) > 0 } return success } private func _writeBinaryData(_ plist : NSDictionary) -> Bool { return __CFBinaryPlistWriteToStream(plist, self._stream) > 0 } public func finishEncoding() { if _flags.contains(ArchiverFlags.FinishedEncoding) { return } var plist = Dictionary<String, Any>() var success : Bool plist["$archiver"] = NSStringFromClass(self.dynamicType) plist["$version"] = NSKeyedArchivePlistVersion plist["$objects"] = self._objects plist["$top"] = self._containers[0].dict if let unwrappedDelegate = self.delegate { unwrappedDelegate.archiverWillFinish(self) } let nsPlist = plist.bridge() if self.outputFormat == NSPropertyListFormat.XMLFormat_v1_0 { success = _writeXMLData(nsPlist) } else { success = _writeBinaryData(nsPlist) } if let unwrappedDelegate = self.delegate { unwrappedDelegate.archiverDidFinish(self) } if success { let _ = self._flags.insert(ArchiverFlags.FinishedEncoding) } } public class func setClassName(_ codedName: String?, forClass cls: AnyClass) { let clsName = String(cls.dynamicType) _classNameMapLock.synchronized { _classNameMap[clsName] = codedName } } public func setClassName(_ codedName: String?, forClass cls: AnyClass) { let clsName = String(cls.dynamicType) _classNameMap[clsName] = codedName } public override var systemVersion: UInt32 { return NSKeyedArchiverSystemVersion } public override var allowsKeyedCoding: Bool { return true } private func _validateStillEncoding() -> Bool { if self._flags.contains(ArchiverFlags.FinishedEncoding) { fatalError("Encoder already finished") } return true } private class func _supportsSecureCoding(_ objv : AnyObject?) -> Bool { var supportsSecureCoding : Bool = false if let secureCodable = objv as? NSSecureCoding { supportsSecureCoding = secureCodable.dynamicType.supportsSecureCoding() } return supportsSecureCoding } private func _validateObjectSupportsSecureCoding(_ objv : AnyObject?) { if objv != nil && self.requiresSecureCoding && !NSKeyedArchiver._supportsSecureCoding(objv) { fatalError("Secure coding required when encoding \(objv)") } } private static func _createObjectRef(_ uid : UInt32) -> CFKeyedArchiverUID { return Unmanaged<CFKeyedArchiverUID>.fromOpaque( UnsafePointer<Void>(_CFKeyedArchiverUIDCreate(kCFAllocatorSystemDefault, uid))).takeUnretainedValue() } private func _createObjectRefCached(_ uid : UInt32) -> CFKeyedArchiverUID { if uid == 0 { return NSKeyedArchiveNullObjectReference } else if Int(uid) <= self._cache.count { return self._cache[Int(uid) - 1] } else { let objectRef = NSKeyedArchiver._createObjectRef(uid) self._cache.insert(objectRef, at: Int(uid) - 1) return objectRef } } /** Return a new object identifier, freshly allocated if need be. A placeholder null object is associated with the reference. */ private func _referenceObject(_ objv: AnyObject?, conditional: Bool = false) -> CFKeyedArchiverUID? { var uid : UInt32? if objv == nil { return NSKeyedArchiveNullObjectReference } let oid = NSUniqueObject(objv!) uid = self._objRefMap[oid] if uid == nil { if conditional { return nil // object has not been unconditionally encoded } uid = UInt32(self._objects.count) self._objRefMap[oid] = uid self._objects.insert(NSKeyedArchiveNullObjectReferenceName, at: Int(uid!)) } return _createObjectRefCached(uid!) } /** Returns true if the object has already been encoded. */ private func _haveVisited(_ objv: AnyObject?) -> Bool { if objv == nil { return true // always have a null reference } else { let oid = NSUniqueObject(objv!) return self._objRefMap[oid] != nil } } /** Get or create an object reference, and associate the object. */ private func _addObject(_ objv: AnyObject?) -> CFKeyedArchiverUID? { let haveVisited = _haveVisited(objv) let objectRef = _referenceObject(objv) if !haveVisited { _setObject(objv!, forReference: objectRef!) } return objectRef } private func _pushEncodingContext(_ encodingContext: EncodingContext) { self._containers.append(encodingContext) } private func _popEncodingContext() { self._containers.removeLast() } private var _currentEncodingContext : EncodingContext { return self._containers.last! } /** Associate an encoded object or reference with a key in the current encoding context */ private func _setObjectInCurrentEncodingContext(_ object : AnyObject?, forKey key: String? = nil, escape: Bool = true) { let encodingContext = self._containers.last! var encodingKey : String if key != nil { if escape { encodingKey = escapeArchiverKey(key!) } else { encodingKey = key! } } else { encodingKey = _nextGenericKey() } if encodingContext.dict[encodingKey] != nil { NSLog("*** NSKeyedArchiver warning: replacing existing value for key '\(encodingKey)'; probable duplication of encoding keys in class hierarchy") } encodingContext.dict[encodingKey] = object } /** The generic key is used for objects that are encoded without a key. It is a per-encoding context monotonically increasing integer prefixed with "$". */ private func _nextGenericKey() -> String { let key = "$" + String(_currentEncodingContext.genericKey) _currentEncodingContext.genericKey += 1 return key } /** Update replacement object mapping */ private func replaceObject(_ object: AnyObject, withObject replacement: AnyObject?) { let oid = NSUniqueObject(object) if let unwrappedDelegate = self.delegate { unwrappedDelegate.archiver(self, willReplaceObject: object, withObject: replacement) } self._replacementMap[oid] = replacement } /** Returns true if the type cannot be encoded directly (i.e. is a container type) */ private func _isContainer(_ objv: AnyObject?) -> Bool { // Note that we check for class equality rather than membership, because // their mutable subclasses are as object references let valueType = (objv == nil || objv is String || objv!.dynamicType === NSString.self || objv!.dynamicType === NSNumber.self || objv!.dynamicType === NSData.self) return !valueType } /** Associates an object with an existing reference */ private func _setObject(_ objv: Any, forReference reference : CFKeyedArchiverUID) { let index = Int(objectRefGetValue(reference)) self._objects[index] = objv } /** Returns a dictionary describing class metadata for a class */ private func _classDictionary(_ clsv: AnyClass) -> Dictionary<String, Any> { func _classNameForClass(_ clsv: AnyClass) -> String? { var className : String? className = classNameForClass(clsv) if className == nil { className = NSKeyedArchiver.classNameForClass(clsv) } return className } var classDict : [String:Any] = [:] let className = NSStringFromClass(clsv) let mappedClassName = _classNameForClass(clsv) if mappedClassName != nil && mappedClassName != className { // If we have a mapped class name, OS X only encodes the mapped name classDict["$classname"] = mappedClassName } else { var classChain : [String] = [] var classIter : AnyClass? = clsv classDict["$classname"] = className repeat { classChain.append(NSStringFromClass(classIter!)) classIter = _getSuperclass(classIter!) } while classIter != nil classDict["$classes"] = classChain if let ns = clsv as? NSObject.Type { let classHints = ns.classFallbacksForKeyedArchiver() if classHints.count > 0 { classDict["$classhints"] = classHints } } } return classDict } /** Return an object reference for a class Because _classDictionary() returns a dictionary by value, and every time we bridge to NSDictionary we get a new object (the hash code is different), we maintain a private mapping between class name and object reference to avoid redundantly encoding class metadata */ private func _classReference(_ clsv: AnyClass) -> CFKeyedArchiverUID? { let className = NSStringFromClass(clsv) var classRef = self._classes[className] // keyed by actual class name if classRef == nil { let classDict = _classDictionary(clsv) classRef = _addObject(classDict.bridge()) if let unwrappedClassRef = classRef { self._classes[className] = unwrappedClassRef } } return classRef } /** Return the object replacing another object (if any) */ private func _replacementObject(_ object: AnyObject?) -> AnyObject? { var objectToEncode : AnyObject? = nil // object to encode after substitution // nil cannot be mapped if object == nil { return nil } // check replacement cache objectToEncode = self._replacementMap[NSUniqueObject(object!)] if objectToEncode != nil { return objectToEncode } // object replaced by NSObject.replacementObjectForKeyedArchiver // if it is replaced with nil, it cannot be further replaced if objectToEncode == nil { let ns = object as? NSObject objectToEncode = ns?.replacementObjectForKeyedArchiver(self) if objectToEncode == nil { replaceObject(object!, withObject: nil) return nil } } if objectToEncode == nil { objectToEncode = object } // object replaced by delegate. If the delegate returns nil, nil is encoded if let unwrappedDelegate = self.delegate { objectToEncode = unwrappedDelegate.archiver(self, willEncodeObject: objectToEncode!) replaceObject(object!, withObject: objectToEncode) } return objectToEncode } /** Internal function to encode an object. Returns the object reference. */ private func _encodeObject(_ objv: AnyObject?, conditional: Bool = false) -> CFKeyedArchiverUID? { var object : AnyObject? = nil // object to encode after substitution var objectRef : CFKeyedArchiverUID? // encoded object reference let haveVisited : Bool let _ = _validateStillEncoding() haveVisited = _haveVisited(objv) object = _replacementObject(objv) objectRef = _referenceObject(object, conditional: conditional) guard let unwrappedObjectRef = objectRef else { // we can return nil if the object is being conditionally encoded return nil } _validateObjectSupportsSecureCoding(object) if !haveVisited { var encodedObject : Any if _isContainer(object) { guard let codable = object as? NSCoding else { fatalError("Object \(object) does not conform to NSCoding") } let innerEncodingContext = EncodingContext() var cls : AnyClass? _pushEncodingContext(innerEncodingContext) codable.encodeWithCoder(self) let ns = object as? NSObject cls = ns?.classForKeyedArchiver if cls == nil { cls = object!.dynamicType } _setObjectInCurrentEncodingContext(_classReference(cls!), forKey: "$class", escape: false) _popEncodingContext() encodedObject = innerEncodingContext.dict } else { encodedObject = object! } _setObject(encodedObject, forReference: unwrappedObjectRef) } if let unwrappedDelegate = self.delegate { unwrappedDelegate.archiver(self, didEncodeObject: object) } return unwrappedObjectRef } /** Encode an object and associate it with a key in the current encoding context. */ private func _encodeObject(_ objv: AnyObject?, forKey key: String?, conditional: Bool = false) { if let objectRef = _encodeObject(objv, conditional: conditional) { _setObjectInCurrentEncodingContext(objectRef, forKey: key, escape: key != nil) } } public override func encodeObject(_ object: AnyObject?) { _encodeObject(object, forKey: nil) } public override func encodeConditionalObject(_ object: AnyObject?) { _encodeObject(object, forKey: nil, conditional: true) } public override func encodeObject(_ objv: AnyObject?, forKey key: String) { _encodeObject(objv, forKey: key, conditional: false) } public override func encodeConditionalObject(_ objv: AnyObject?, forKey key: String) { _encodeObject(objv, forKey: key, conditional: true) } public override func encodePropertyList(_ aPropertyList: AnyObject) { if !NSPropertyListClasses.contains({ $0 == aPropertyList.dynamicType }) { fatalError("Cannot encode non-property list type \(aPropertyList.dynamicType) as property list") } encodeObject(aPropertyList) } public func encodePropertyList(_ aPropertyList: AnyObject, forKey key: String) { if !NSPropertyListClasses.contains({ $0 == aPropertyList.dynamicType }) { fatalError("Cannot encode non-property list type \(aPropertyList.dynamicType) as property list") } encodeObject(aPropertyList, forKey: key) } public func _encodePropertyList(_ aPropertyList: AnyObject, forKey key: String? = nil) { let _ = _validateStillEncoding() _setObjectInCurrentEncodingContext(aPropertyList, forKey: key) } internal func _encodeValue<T: NSObject where T: NSCoding>(_ objv: T, forKey key: String? = nil) { _encodePropertyList(objv, forKey: key) } private func _encodeValueOfObjCType(_ type: _NSSimpleObjCType, at addr: UnsafePointer<Void>) { switch type { case .ID: let objectp = unsafeBitCast(addr, to: UnsafePointer<AnyObject>.self) encodeObject(objectp.pointee) break case .Class: let classp = unsafeBitCast(addr, to: UnsafePointer<AnyClass>.self) encodeObject(NSStringFromClass(classp.pointee).bridge()) break case .Char: let charp = unsafeBitCast(addr, to: UnsafePointer<CChar>.self) _encodeValue(NSNumber(value: charp.pointee)) break case .UChar: let ucharp = unsafeBitCast(addr, to: UnsafePointer<UInt8>.self) _encodeValue(NSNumber(value: ucharp.pointee)) break case .Int, .Long: let intp = unsafeBitCast(addr, to: UnsafePointer<Int32>.self) _encodeValue(NSNumber(value: intp.pointee)) break case .UInt, .ULong: let uintp = unsafeBitCast(addr, to: UnsafePointer<UInt32>.self) _encodeValue(NSNumber(value: uintp.pointee)) break case .LongLong: let longlongp = unsafeBitCast(addr, to: UnsafePointer<Int64>.self) _encodeValue(NSNumber(value: longlongp.pointee)) break case .ULongLong: let ulonglongp = unsafeBitCast(addr, to: UnsafePointer<UInt64>.self) _encodeValue(NSNumber(value: ulonglongp.pointee)) break case .Float: let floatp = unsafeBitCast(addr, to: UnsafePointer<Float>.self) _encodeValue(NSNumber(value: floatp.pointee)) break case .Double: let doublep = unsafeBitCast(addr, to: UnsafePointer<Double>.self) _encodeValue(NSNumber(value: doublep.pointee)) break case .Bool: let boolp = unsafeBitCast(addr, to: UnsafePointer<Bool>.self) _encodeValue(NSNumber(value: boolp.pointee)) break case .CharPtr: let charpp = unsafeBitCast(addr, to: UnsafePointer<UnsafePointer<Int8>>.self) encodeObject(NSString(UTF8String: charpp.pointee)) break default: fatalError("NSKeyedArchiver.encodeValueOfObjCType: unknown type encoding ('\(type.rawValue)')") break } } public override func encodeValueOfObjCType(_ typep: UnsafePointer<Int8>, at addr: UnsafePointer<Void>) { guard let type = _NSSimpleObjCType(UInt8(typep.pointee)) else { let spec = String(typep.pointee) fatalError("NSKeyedArchiver.encodeValueOfObjCType: unsupported type encoding spec '\(spec)'") } if type == .StructBegin { fatalError("NSKeyedArchiver.encodeValueOfObjCType: this archiver cannot encode structs") } else if type == .ArrayBegin { let scanner = NSScanner(string: String(cString: typep)) scanner.scanLocation = 1 // advance past ObJCType var count : Int = 0 guard scanner.scanInteger(&count) && count > 0 else { fatalError("NSKeyedArchiver.encodeValueOfObjCType: array count is missing or zero") } guard let elementType = _NSSimpleObjCType(scanner.scanUpToString(String(_NSSimpleObjCType.ArrayEnd))) else { fatalError("NSKeyedArchiver.encodeValueOfObjCType: array type is missing") } encodeObject(_NSKeyedCoderOldStyleArray(objCType: elementType, count: count, at: addr)) } else { return _encodeValueOfObjCType(type, at: addr) } } public override func encodeBool(_ boolv: Bool, forKey key: String) { _encodeValue(NSNumber(value: boolv), forKey: key) } public override func encodeInt(_ intv: Int32, forKey key: String) { _encodeValue(NSNumber(value: intv), forKey: key) } public override func encodeInt32(_ intv: Int32, forKey key: String) { _encodeValue(NSNumber(value: intv), forKey: key) } public override func encodeInt64(_ intv: Int64, forKey key: String) { _encodeValue(NSNumber(value: intv), forKey: key) } public override func encodeFloat(_ realv: Float, forKey key: String) { _encodeValue(NSNumber(value: realv), forKey: key) } public override func encodeDouble(_ realv: Double, forKey key: String) { _encodeValue(NSNumber(value: realv), forKey: key) } public override func encodeInteger(_ intv: Int, forKey key: String) { _encodeValue(NSNumber(value: intv), forKey: key) } public override func encodeDataObject(_ data: NSData) { // this encodes as a reference to an NSData object rather than encoding inline encodeObject(data) } public override func encodeBytes(_ bytesp: UnsafePointer<UInt8>, length lenv: Int, forKey key: String) { // this encodes the data inline let data = NSData(bytes: bytesp, length: lenv) _encodeValue(data, forKey: key) } /** Helper API for NSArray and NSDictionary that encodes an array of objects, creating references as it goes */ internal func _encodeArrayOfObjects(_ objects : NSArray, forKey key : String) { var objectRefs = [CFKeyedArchiverUID]() objectRefs.reserveCapacity(objects.count) for object in objects { let objectRef = _encodeObject(object)! objectRefs.append(objectRef) } _encodeValue(objectRefs.bridge(), forKey: key) } /** Enables secure coding support on this keyed archiver. You do not need to enable secure coding on the archiver to enable secure coding on the unarchiver. Enabling secure coding on the archiver is a way for you to be sure that all classes that are encoded conform with NSSecureCoding (it will throw an exception if a class which does not NSSecureCoding is archived). Note that the getter is on the superclass, NSCoder. See NSCoder for more information about secure coding. */ public override var requiresSecureCoding: Bool { get { return _flags.contains(ArchiverFlags.RequiresSecureCoding) } set { if newValue { let _ = _flags.insert(ArchiverFlags.RequiresSecureCoding) } else { _flags.remove(ArchiverFlags.RequiresSecureCoding) } } } // During encoding, the coder first checks with the coder's // own table, then if there was no mapping there, the class's. public class func classNameForClass(_ cls: AnyClass) -> String? { let clsName = String(reflecting: cls) var mappedClass : String? _classNameMapLock.synchronized { mappedClass = _classNameMap[clsName] } return mappedClass } public func classNameForClass(_ cls: AnyClass) -> String? { let clsName = String(reflecting: cls) return _classNameMap[clsName] } } extension NSKeyedArchiverDelegate { func archiver(_ archiver: NSKeyedArchiver, willEncodeObject object: AnyObject) -> AnyObject? { // Returning the same object is the same as doing nothing return object } func archiver(_ archiver: NSKeyedArchiver, didEncodeObject object: AnyObject?) { } func archiver(_ archiver: NSKeyedArchiver, willReplaceObject object: AnyObject?, withObject newObject: AnyObject?) { } func archiverWillFinish(_ archiver: NSKeyedArchiver) { } func archiverDidFinish(_ archiver: NSKeyedArchiver) { } } public protocol NSKeyedArchiverDelegate : class { // Informs the delegate that the object is about to be encoded. The delegate // either returns this object or can return a different object to be encoded // instead. The delegate can also fiddle with the coder state. If the delegate // returns nil, nil is encoded. This method is called after the original object // may have replaced itself with replacementObjectForKeyedArchiver:. // This method is not called for an object once a replacement mapping has been // setup for that object (either explicitly, or because the object has previously // been encoded). This is also not called when nil is about to be encoded. // This method is called whether or not the object is being encoded conditionally. func archiver(_ archiver: NSKeyedArchiver, willEncodeObject object: AnyObject) -> AnyObject? // Informs the delegate that the given object has been encoded. The delegate // might restore some state it had fiddled previously, or use this to keep // track of the objects which are encoded. The object may be nil. Not called // for conditional objects until they are really encoded (if ever). func archiver(_ archiver: NSKeyedArchiver, didEncodeObject object: AnyObject?) // Informs the delegate that the newObject is being substituted for the // object. This is also called when the delegate itself is doing/has done // the substitution. The delegate may use this method if it is keeping track // of the encoded or decoded objects. func archiver(_ archiver: NSKeyedArchiver, willReplaceObject object: AnyObject?, withObject newObject: AnyObject?) // Notifies the delegate that encoding is about to finish. func archiverWillFinish(_ archiver: NSKeyedArchiver) // Notifies the delegate that encoding has finished. func archiverDidFinish(_ archiver: NSKeyedArchiver) }
153d96415b7dd7c9c0c2fd9ff330c6e7
35.515837
310
0.618742
false
false
false
false
ncalexan/firefox-ios
refs/heads/master
Client/Frontend/Browser/BrowserTrayAnimators.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared class TrayToBrowserAnimator: NSObject, UIViewControllerAnimatedTransitioning { func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if let bvc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? BrowserViewController, let tabTray = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? TabTrayController { transitionFromTray(tabTray, toBrowser: bvc, usingContext: transitionContext) } } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.4 } } private extension TrayToBrowserAnimator { func transitionFromTray(_ tabTray: TabTrayController, toBrowser bvc: BrowserViewController, usingContext transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView guard let selectedTab = bvc.tabManager.selectedTab else { return } let tabManager = bvc.tabManager let displayedTabs = selectedTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs guard let expandFromIndex = displayedTabs.index(of: selectedTab) else { return } bvc.view.frame = transitionContext.finalFrame(for: bvc) // Hide browser components bvc.toggleSnackBarVisibility(show: false) toggleWebViewVisibility(false, usingTabManager: bvc.tabManager) bvc.homePanelController?.view.isHidden = true bvc.webViewContainerBackdrop.isHidden = true bvc.statusBarOverlay.isHidden = false if let url = selectedTab.url, !url.isReaderModeURL { bvc.hideReaderModeBar(animated: false) } // Take a snapshot of the collection view that we can scale/fade out. We don't need to wait for screen updates since it's already rendered on the screen let tabCollectionViewSnapshot = tabTray.collectionView.snapshotView(afterScreenUpdates: false)! tabTray.collectionView.alpha = 0 tabCollectionViewSnapshot.frame = tabTray.collectionView.frame container.insertSubview(tabCollectionViewSnapshot, at: 0) // Create a fake cell to use for the upscaling animation let startingFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView, atIndex: expandFromIndex) let cell = createTransitionCellFromTab(bvc.tabManager.selectedTab, withFrame: startingFrame) cell.backgroundHolder.layer.cornerRadius = 0 container.insertSubview(bvc.view, aboveSubview: tabCollectionViewSnapshot) container.insertSubview(cell, aboveSubview: bvc.view) // Flush any pending layout/animation code in preperation of the animation call container.layoutIfNeeded() let finalFrame = calculateExpandedCellFrameFromBVC(bvc) bvc.footer.alpha = shouldDisplayFooterForBVC(bvc) ? 1 : 0 bvc.urlBar.isTransitioning = true // Re-calculate the starting transforms for header/footer views in case we switch orientation resetTransformsForViews([bvc.header, bvc.readerModeBar, bvc.footer]) transformHeaderFooterForBVC(bvc, toFrame: startingFrame, container: container) UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: { // Scale up the cell and reset the transforms for the header/footers cell.frame = finalFrame container.layoutIfNeeded() cell.title.transform = CGAffineTransform(translationX: 0, y: -cell.title.frame.height) bvc.tabTrayDidDismiss(tabTray) UIApplication.shared.windows.first?.backgroundColor = UIConstants.AppBackgroundColor tabTray.navigationController?.setNeedsStatusBarAppearanceUpdate() tabTray.toolbar.transform = CGAffineTransform(translationX: 0, y: UIConstants.ToolbarHeight) tabCollectionViewSnapshot.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) tabCollectionViewSnapshot.alpha = 0 }, completion: { finished in // Remove any of the views we used for the animation cell.removeFromSuperview() tabCollectionViewSnapshot.removeFromSuperview() bvc.footer.alpha = 1 bvc.toggleSnackBarVisibility(show: true) toggleWebViewVisibility(true, usingTabManager: bvc.tabManager) bvc.webViewContainerBackdrop.isHidden = false bvc.homePanelController?.view.isHidden = false bvc.urlBar.isTransitioning = false transitionContext.completeTransition(true) }) } } class BrowserToTrayAnimator: NSObject, UIViewControllerAnimatedTransitioning { func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if let bvc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? BrowserViewController, let tabTray = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? TabTrayController { transitionFromBrowser(bvc, toTabTray: tabTray, usingContext: transitionContext) } } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.4 } } private extension BrowserToTrayAnimator { func transitionFromBrowser(_ bvc: BrowserViewController, toTabTray tabTray: TabTrayController, usingContext transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView guard let selectedTab = bvc.tabManager.selectedTab else { return } let tabManager = bvc.tabManager let displayedTabs = selectedTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs guard let scrollToIndex = displayedTabs.index(of: selectedTab) else { return } tabTray.view.frame = transitionContext.finalFrame(for: tabTray) // Insert tab tray below the browser and force a layout so the collection view can get it's frame right container.insertSubview(tabTray.view, belowSubview: bvc.view) // Force subview layout on the collection view so we can calculate the correct end frame for the animation tabTray.view.layoutSubviews() tabTray.collectionView.scrollToItem(at: IndexPath(item: scrollToIndex, section: 0), at: .centeredVertically, animated: false) // Build a tab cell that we will use to animate the scaling of the browser to the tab let expandedFrame = calculateExpandedCellFrameFromBVC(bvc) let cell = createTransitionCellFromTab(bvc.tabManager.selectedTab, withFrame: expandedFrame) cell.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius cell.innerStroke.isHidden = true // Take a snapshot of the collection view to perform the scaling/alpha effect let tabCollectionViewSnapshot = tabTray.collectionView.snapshotView(afterScreenUpdates: true)! tabCollectionViewSnapshot.frame = tabTray.collectionView.frame tabCollectionViewSnapshot.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) tabCollectionViewSnapshot.alpha = 0 tabTray.view.insertSubview(tabCollectionViewSnapshot, belowSubview: tabTray.toolbar) if let toast = bvc.clipboardBarDisplayHandler?.clipboardToast { toast.removeFromSuperview() } container.addSubview(cell) cell.layoutIfNeeded() cell.title.transform = CGAffineTransform(translationX: 0, y: -cell.title.frame.size.height) // Hide views we don't want to show during the animation in the BVC bvc.homePanelController?.view.isHidden = true bvc.statusBarOverlay.isHidden = true bvc.toggleSnackBarVisibility(show: false) toggleWebViewVisibility(false, usingTabManager: bvc.tabManager) bvc.urlBar.isTransitioning = true // Since we are hiding the collection view and the snapshot API takes the snapshot after the next screen update, // the screenshot ends up being blank unless we set the collection view hidden after the screen update happens. // To work around this, we dispatch the setting of collection view to hidden after the screen update is completed. DispatchQueue.main.async { tabTray.collectionView.isHidden = true let finalFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView, atIndex: scrollToIndex) tabTray.toolbar.transform = CGAffineTransform(translationX: 0, y: UIConstants.ToolbarHeight) UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: { cell.frame = finalFrame cell.title.transform = CGAffineTransform.identity cell.layoutIfNeeded() UIApplication.shared.windows.first?.backgroundColor = TabTrayControllerUX.BackgroundColor tabTray.navigationController?.setNeedsStatusBarAppearanceUpdate() transformHeaderFooterForBVC(bvc, toFrame: finalFrame, container: container) bvc.urlBar.updateAlphaForSubviews(0) bvc.footer.alpha = 0 tabCollectionViewSnapshot.alpha = 1 tabTray.toolbar.transform = CGAffineTransform.identity resetTransformsForViews([tabCollectionViewSnapshot]) }, completion: { finished in // Remove any of the views we used for the animation cell.removeFromSuperview() tabCollectionViewSnapshot.removeFromSuperview() tabTray.collectionView.isHidden = false bvc.toggleSnackBarVisibility(show: true) toggleWebViewVisibility(true, usingTabManager: bvc.tabManager) bvc.homePanelController?.view.isHidden = false bvc.urlBar.isTransitioning = false transitionContext.completeTransition(true) }) } } } private func transformHeaderFooterForBVC(_ bvc: BrowserViewController, toFrame finalFrame: CGRect, container: UIView) { let footerForTransform = footerTransform(bvc.footer.frame, toFrame: finalFrame, container: container) let headerForTransform = headerTransform(bvc.header.frame, toFrame: finalFrame, container: container) bvc.footer.transform = footerForTransform bvc.header.transform = headerForTransform bvc.readerModeBar?.transform = headerForTransform } private func footerTransform( _ frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform { let frame = container.convert(frame, to: container) let endY = finalFrame.maxY - (frame.size.height / 2) let endX = finalFrame.midX let translation = CGPoint(x: endX - frame.midX, y: endY - frame.midY) let scaleX = finalFrame.width / frame.width var transform = CGAffineTransform.identity transform = transform.translatedBy(x: translation.x, y: translation.y) transform = transform.scaledBy(x: scaleX, y: scaleX) return transform } private func headerTransform(_ frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform { let frame = container.convert(frame, to: container) let endY = finalFrame.minY + (frame.size.height / 2) let endX = finalFrame.midX let translation = CGPoint(x: endX - frame.midX, y: endY - frame.midY) let scaleX = finalFrame.width / frame.width var transform = CGAffineTransform.identity transform = transform.translatedBy(x: translation.x, y: translation.y) transform = transform.scaledBy(x: scaleX, y: scaleX) return transform } //MARK: Private Helper Methods private func calculateCollapsedCellFrameUsingCollectionView(_ collectionView: UICollectionView, atIndex index: Int) -> CGRect { if let attr = collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: index, section: 0)) { return collectionView.convert(attr.frame, to: collectionView.superview) } else { return CGRect.zero } } private func calculateExpandedCellFrameFromBVC(_ bvc: BrowserViewController) -> CGRect { var frame = bvc.webViewContainer.frame // If we're navigating to a home panel and we were expecting to show the toolbar, add more height to end frame since // there is no toolbar for home panels if !bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) { return frame } else if let url = bvc.tabManager.selectedTab?.url, url.isAboutURL && bvc.toolbar == nil { frame.size.height += UIConstants.ToolbarHeight } return frame } private func shouldDisplayFooterForBVC(_ bvc: BrowserViewController) -> Bool { if bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) { if let url = bvc.tabManager.selectedTab?.url { return !url.isAboutURL } } return false } private func toggleWebViewVisibility(_ show: Bool, usingTabManager tabManager: TabManager) { for i in 0..<tabManager.count { if let tab = tabManager[i] { tab.webView?.isHidden = !show } } } private func resetTransformsForViews(_ views: [UIView?]) { for view in views { // Reset back to origin view?.transform = CGAffineTransform.identity } } private func transformToolbarsToFrame(_ toolbars: [UIView?], toRect endRect: CGRect) { for toolbar in toolbars { // Reset back to origin toolbar?.transform = CGAffineTransform.identity // Transform from origin to where we want them to end up if let toolbarFrame = toolbar?.frame { toolbar?.transform = CGAffineTransformMakeRectToRect(toolbarFrame, toFrame: endRect) } } } private func createTransitionCellFromTab(_ tab: Tab?, withFrame frame: CGRect) -> TabCell { let cell = TabCell(frame: frame) cell.background.image = tab?.screenshot cell.titleText.text = tab?.displayTitle if let tab = tab, tab.isPrivate { cell.style = .dark } if let favIcon = tab?.displayFavicon { cell.favicon.sd_setImage(with: URL(string: favIcon.url)!) } else { var defaultFavicon = UIImage(named: "defaultFavicon") if tab?.isPrivate ?? false { defaultFavicon = defaultFavicon?.withRenderingMode(.alwaysTemplate) cell.favicon.image = defaultFavicon cell.favicon.tintColor = (tab?.isPrivate ?? false) ? UIColor.white : UIColor.darkGray } else { cell.favicon.image = defaultFavicon } } return cell }
6117cde4228232b33c29083e4ac7e53a
46.089506
170
0.707216
false
false
false
false
takeo-asai/math-puzzle
refs/heads/master
problems/array_ex.swift
mit
1
extension Array { // ExSwift // // Created by pNre on 03/06/14. // Copyright (c) 2014 pNre. All rights reserved. // // https://github.com/pNre/ExSwift/blob/master/ExSwift/Array.swift // https://github.com/pNre/ExSwift/blob/master/LICENSE /** - parameter length: The length of each permutation - returns: All permutations of a given length within an array */ func permutation (length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } else if length == 0 { return [[]] } else { var permutations: [[Element]] = [] let combinations = combination(length) for combination in combinations { var endArray: [[Element]] = [] var mutableCombination = combination permutations += self.permutationHelper(length, array: &mutableCombination, endArray: &endArray) } return permutations } } private func permutationHelper(n: Int, inout array: [Element], inout endArray: [[Element]]) -> [[Element]] { if n == 1 { endArray += [array] } for var i = 0; i < n; i++ { permutationHelper(n - 1, array: &array, endArray: &endArray) let j = n % 2 == 0 ? i : 0 let temp: Element = array[j] array[j] = array[n - 1] array[n - 1] = temp } return endArray } /** - parameter length: - returns: Returns all of the combinations in the array of the given length */ func combination (length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } var indexes: [Int] = (0..<length).reduce([]) {$0 + [$1]} var combinations: [[Element]] = [] let offset = self.count - indexes.count while true { var combination: [Element] = [] for index in indexes { combination.append(self[index]) } combinations.append(combination) var i = indexes.count - 1 while i >= 0 && indexes[i] == i + offset { i-- } if i < 0 { break } i++ let start = indexes[i-1] + 1 for j in (i-1)..<indexes.count { indexes[j] = start + j - i + 1 } } return combinations } /** - parameter length: The length of each permutations - returns: All of the permutations of this array of a given length, allowing repeats */ func repeatedPermutation(length: Int) -> [[Element]] { if length < 1 { return [] } var indexes: [[Int]] = [] indexes.repeatedPermutationHelper([], length: length, arrayLength: self.count, indexes: &indexes) return indexes.map({ $0.map({ i in self[i] }) }) } private func repeatedPermutationHelper(seed: [Int], length: Int, arrayLength: Int, inout indexes: [[Int]]) { if seed.count == length { indexes.append(seed) return } for i in (0..<arrayLength) { var newSeed: [Int] = seed newSeed.append(i) self.repeatedPermutationHelper(newSeed, length: length, arrayLength: arrayLength, indexes: &indexes) } } }
3e033aa97151fe8be99c26df9527a318
34.505155
112
0.512485
false
false
false
false
zhaobin19918183/zhaobinCode
refs/heads/master
XWSwiftRefresh-master/Example/XWSwiftRefresh/Classes/ExampleVC/XWDisplayTableViewController.swift
gpl-3.0
1
// // XWDisplayTableViewController.swift // XWSwiftRefresh // // Created by Xiong Wei on 15/10/7. // Copyright © 2015年 Xiong Wei. All rights reserved. // 简书:猫爪 import UIKit class XWDisplayTableViewController: UITableViewController { // var model:exampleModel = exampleModel var data:Array<String> = ["数据-1", "数据-2", "数据-3"] var method:String = "" { didSet{ self.xwExeAction(Selector(method)) } } override func viewDidLoad() { super.viewDidLoad() self.tableView.tableFooterView = UIView() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") } //默认模式 func example001(){ /* 过期方法 //添加上拉刷新 self.tableView.addHeaderWithCallback { [weak self] () -> () in if let selfStrong = self { selfStrong.upPullLoadData() selfStrong.tableView.endHeaderRefreshing() } } //添加下拉刷新 self.tableView.addFooterWithCallback { [weak self] () -> () in if let selfStrong = self { selfStrong.downPlullLoadData() selfStrong.tableView.endFooterRefreshing() } } */ self.tableView.headerView = XWRefreshNormalHeader(target: self, action: #selector(XWDisplayTableViewController.upPullLoadData)) self.tableView.headerView?.beginRefreshing() self.tableView.headerView?.endRefreshing() self.tableView.footerView = XWRefreshAutoNormalFooter(target: self, action: #selector(XWDisplayTableViewController.downPlullLoadData)) } //gif图片模式 func example011(){ var idleImages = [UIImage]() for (var i = 1; i<=20; i += 1) { let image = UIImage(named: String(format: "mono-black-%zd", i)) idleImages.append(image!) } // 设置即将刷新状态的动画图片(一松开就会刷新的状态) var refreshingImages = [UIImage]() for (var i = 1; i<=20; i += 1) { let image = UIImage(named: String(format: "mono-black-%zd", i)) refreshingImages.append(image!) } // 其实headerView是一个View 拿出来,更合理 let headerView = XWRefreshGifHeader(target: self, action: #selector(XWDisplayTableViewController.upPullLoadData)) //这里是 XWRefreshGifHeader 类型,就是gif图片 headerView.setImages(idleImages, duration: 0.8, state: XWRefreshState.Idle) headerView.setImages(refreshingImages, duration: 0.8, state: XWRefreshState.Refreshing) //隐藏状态栏 headerView.refreshingTitleHidden = true //隐藏时间状态 headerView.refreshingTimeHidden = true //根据上拉比例设置透明度 headerView.automaticallyChangeAlpha = true self.tableView.headerView = headerView } //MARK: 加载数据 func upPullLoadData(){ //延迟执行 模拟网络延迟,实际开发中去掉 xwDelay(1) { () -> Void in for i in 0...15 { self.data.append("数据-\(i + self.data.count)") } self.tableView.reloadData() self.tableView.headerView?.endRefreshing() } } func downPlullLoadData(){ xwDelay(1) { () -> Void in for i in 0 ..< 15 { self.data.append("数据-\(i + self.data.count)") } self.tableView.reloadData() self.tableView.footerView?.endRefreshing() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return self.data.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) cell.textLabel?.text = data[indexPath.row] return cell } }
637edfd56fcda885e1d3379b0ab2e61e
26.567901
142
0.558665
false
false
false
false
flathead/Flame
refs/heads/develop
Flame/CubeRenderer.swift
mit
1
// // CubeRenderer.swift // Flame // // Created by Kenny Deriemaeker on 8/04/16. // Copyright © 2016 Kenny Deriemaeker. All rights reserved. // import MetalKit class CubeRenderer : MeshRenderer { private var numVertices = 0 private var numIndices = 0 private var texture: MTLTexture? private var sampler: MTLSamplerState? override func generateBuffers() { let device = Renderer.sharedInstance.device let a = Vertex(position: Vector4(-0.5, 0.5, 0.5, 1), color: Vector4(1, 0, 0, 1), textureCoords: Vector2(0, 0)) let b = Vertex(position: Vector4(-0.5, -0.5, 0.5, 1), color: Vector4(0, 1, 0, 1), textureCoords: Vector2(1, 0)) let c = Vertex(position: Vector4(0.5, -0.5, 0.5, 1), color: Vector4(0, 0, 1, 1), textureCoords: Vector2(1, 1)) let d = Vertex(position: Vector4(0.5, 0.5, 0.5, 1), color: Vector4(1, 1, 0, 1), textureCoords: Vector2(0, 1)) let q = Vertex(position: Vector4(-0.5, 0.5, -0.5, 1), color: Vector4(0, 1, 1, 1), textureCoords: Vector2(1, 0)) let r = Vertex(position: Vector4(0.5, 0.5, -0.5, 1), color: Vector4(1, 0, 1, 1), textureCoords: Vector2(1, 1)) let s = Vertex(position: Vector4(-0.5, -0.5, -0.5, 1), color: Vector4(0, 1, 0, 1), textureCoords: Vector2(0, 1)) let t = Vertex(position: Vector4(0.5, -0.5, -0.5, 1), color: Vector4(1, 0, 0, 1), textureCoords: Vector2(0, 0)) let vertices = [a, b, c, d, q, r, s, t] let indices: [UInt16] = [ 0, 1, 2, 0, 2, 3, 5, 7, 6, 4, 5, 6, 4, 6, 1, 4, 1, 0, 3, 2, 7, 3, 7, 5, 4, 0, 3, 4, 3, 5, 1, 6, 7, 1, 7, 2 ] numVertices = vertices.count numIndices = indices.count vertexBuffer = device.newBufferWithBytes(vertices, length: vertices.count * sizeof(Vertex), options: .CPUCacheModeDefaultCache) indexBuffer = device.newBufferWithBytes(indices, length: indices.count * sizeof(UInt16), options: .CPUCacheModeDefaultCache) generateTexture() } private func generateTexture() { let device = Renderer.sharedInstance.device let descriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat(.RGBA8Unorm, width: 2, height: 2, mipmapped: true) texture = device.newTextureWithDescriptor(descriptor) let bytesPerRow = 4 * 2 let rawData: [UInt8] = [ 0xFF, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF] let rawTexture = NSData(bytes: rawData as [UInt8], length: rawData.count) texture?.replaceRegion(MTLRegionMake2D(0, 0, 2, 2), mipmapLevel: 0, withBytes: UnsafePointer<UInt8>(rawTexture.bytes), bytesPerRow: bytesPerRow) // Texture sampler let samplerDescriptor = MTLSamplerDescriptor() samplerDescriptor.minFilter = .Linear samplerDescriptor.magFilter = .Linear sampler = device.newSamplerStateWithDescriptor(samplerDescriptor) } override func draw(commandEncoder: MTLRenderCommandEncoder) { if let texture = texture, let sampler = sampler { commandEncoder.setFragmentSamplerState(sampler, atIndex: 0) commandEncoder.setFragmentTexture(texture, atIndex: 0) } commandEncoder.setVertexBuffer(vertexBuffer, offset: 0, atIndex: 0) commandEncoder.drawIndexedPrimitives(.Triangle, indexCount: numIndices, indexType: .UInt16, indexBuffer: indexBuffer!, indexBufferOffset: 0) } }
1023d4e29dc48660e5b752a59646fb09
36.038835
120
0.584164
false
false
false
false
michals92/iOS_skautIS
refs/heads/master
skautIS/UnitsVC.swift
bsd-3-clause
1
// // UnitsVC.swift // skautIS // // Copyright (c) 2015, Michal Simik // All rights reserved. // import UIKit import SWXMLHash class UnitsVC: UIViewController { //variables @IBOutlet weak var unitsSetting: UISwitch! @IBOutlet weak var childUnitsSetting: UISwitch! @IBOutlet weak var isNearSetting: UISwitch! var storage = Storage() var isMyUnit:Bool = false var isNear:Bool = false var includeChildUnits:Bool = false /** Initial method. Sets switches off. */ override func viewDidLoad() { super.viewDidLoad() unitsSetting.setOn(false, animated: true) childUnitsSetting.setOn(false, animated: true) isNearSetting.setOn(false, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /** Performs segue to map */ @IBAction func showUnitsOnMap(sender: AnyObject) { self.performSegueWithIdentifier("showMapSegue", sender: self) } /* Prepares atributtes that are passed to map */ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if (segue.identifier == "showMapSegue"){ let vc = segue.destinationViewController as! MapVC vc.unit = storage.loader("unit") vc.includeChildUnits = includeChildUnits vc.isNear = self.isNear vc.isMyUnit = self.isMyUnit } } //three switch methods @IBAction func unitsState(sender: UISwitch) { if sender.on { isMyUnit = true } else { isMyUnit = false } } @IBAction func childUnitsState(sender: UISwitch) { if sender.on { includeChildUnits = true } else { includeChildUnits = false } } @IBAction func isNear(sender: UISwitch) { if sender.on { isNear = true } else { isNear = false } } }
bde847175ba46b6ecf3ed4562f662853
22.483146
81
0.572249
false
false
false
false
onmyway133/Github.swift
refs/heads/master
Carthage/Checkouts/Tailor/Sources/Shared/Tailor.swift
mit
1
import Foundation import Sugar // MARK: - Error public enum MappableError: ErrorType { case TypeError(message: String) } // MARK: - SubscriptKind public enum SubscriptKind { case Index(Int) case Key(String) } extension SubscriptKind: IntegerLiteralConvertible { public init(integerLiteral value: IntegerLiteralType) { self = .Index(value) } } extension SubscriptKind: StringLiteralConvertible { public typealias UnicodeScalarLiteralType = StringLiteralType public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { self = .Key("\(value)") } public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { self = .Key(value) } public init(stringLiteral value: StringLiteralType) { self = .Key(value) } }
49d152e0b8fc22d64b6d83afb3ad33d8
22.216216
89
0.76135
false
false
false
false
Zewo/Epoch
refs/heads/master
Sources/HTTP/Parser/Parser.swift
mit
1
import CHTTPParser import Core import Foundation import Venice public typealias ParserError = http_errno extension ParserError : Error, CustomStringConvertible { public var description: String { return String(cString: http_errno_description(self)) } } internal class Parser { final class BodyStream : Readable { var complete = false var bodyBuffer = UnsafeRawBufferPointer(start: nil, count: 0) private let parser: Parser public init(parser: Parser) { self.parser = parser } func read( _ buffer: UnsafeMutableRawBufferPointer, deadline: Deadline ) throws -> UnsafeRawBufferPointer { guard let baseAddress = buffer.baseAddress else { return UnsafeRawBufferPointer(start: nil, count: 0) } if bodyBuffer.isEmpty { guard !complete else { return UnsafeRawBufferPointer(start: nil, count: 0) } try parser.read(deadline: deadline) } guard let bodyBaseAddress = bodyBuffer.baseAddress else { return UnsafeRawBufferPointer(start: nil, count: 0) } let bytesRead = min(bodyBuffer.count, buffer.count) memcpy(baseAddress, bodyBaseAddress, bytesRead) #if swift(>=3.2) bodyBuffer = UnsafeRawBufferPointer(rebasing: bodyBuffer.suffix(from: bytesRead)) #else bodyBuffer = bodyBuffer.suffix(from: bytesRead) #endif return UnsafeRawBufferPointer(start: baseAddress, count: bytesRead) } } fileprivate enum State: Int { case ready = 1 case messageBegin = 2 case uri = 3 case status = 4 case headerField = 5 case headerValue = 6 case headersComplete = 7 case body = 8 case messageComplete = 9 } internal class Context { var uri: URI? var status: Response.Status? = nil var headers: Headers = [:] var currentHeaderField: Headers.Field? weak var bodyStream: BodyStream? func addValueForCurrentHeaderField(_ value: String) { guard let key = currentHeaderField else { return } if let existing = headers[key] { headers[key] = existing + ", " + value } else { headers[key] = value } } } private let stream: Readable private let bufferSize: Int private let buffer: UnsafeMutableRawBufferPointer internal var parser: http_parser private var parserSettings: http_parser_settings private var state: State = .ready private var context = Context() private var bytes: [UInt8] = [] public init(stream: Readable, bufferSize: Int = 2048, type: http_parser_type) { self.stream = stream self.bufferSize = bufferSize self.buffer = UnsafeMutableRawBufferPointer.allocate(count: bufferSize) var parser = http_parser() http_parser_init(&parser, type) var parserSettings = http_parser_settings() http_parser_settings_init(&parserSettings) parserSettings.on_message_begin = http_parser_on_message_begin parserSettings.on_url = http_parser_on_url parserSettings.on_status = http_parser_on_status parserSettings.on_header_field = http_parser_on_header_field parserSettings.on_header_value = http_parser_on_header_value parserSettings.on_headers_complete = http_parser_on_headers_complete parserSettings.on_body = http_parser_on_body parserSettings.on_message_complete = http_parser_on_message_complete self.parser = parser self.parserSettings = parserSettings self.parser.data = Unmanaged.passUnretained(self).toOpaque() } deinit { buffer.deallocate() } func headersComplete(context: Context, body: BodyStream, method: Int32, http_major: Int16, http_minor: Int16) -> Bool { return false } func read(deadline: Deadline) throws { let read = try stream.read(buffer, deadline: deadline) try parse(read) } private func parse(_ buffer: UnsafeRawBufferPointer) throws { let final = buffer.isEmpty let needsMessage: Bool switch state { case .ready, .messageComplete: needsMessage = false default: needsMessage = final } let processedCount: Int if final { processedCount = http_parser_execute(&parser, &parserSettings, nil, 0) } else { processedCount = http_parser_execute( &parser, &parserSettings, buffer.baseAddress?.assumingMemoryBound(to: Int8.self), buffer.count ) } guard processedCount == buffer.count else { throw ParserError(parser.http_errno) } guard !needsMessage else { throw ParserError(HPE_INVALID_EOF_STATE.rawValue) } } fileprivate func process(state newState: State, data: UnsafeRawBufferPointer? = nil, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16) -> Int32 { if state != newState { switch state { case .ready, .messageBegin, .body, .messageComplete: break case .uri: guard let uri = bytes.withUnsafeBytes({ buffer in return URI(buffer: buffer, isConnect: method == HTTP_CONNECT.rawValue) }) else { return 1 } context.uri = uri case .status: bytes.append(0) let string = bytes.withUnsafeBufferPointer { (pointer: UnsafeBufferPointer<UInt8>) -> String in return String(cString: pointer.baseAddress!) } context.status = Response.Status( statusCode: Int(status_code), reasonPhrase: string ) case .headerField: bytes.append(0) let string = bytes.withUnsafeBufferPointer { (pointer: UnsafeBufferPointer<UInt8>) -> String in return String(cString: pointer.baseAddress!) } context.currentHeaderField = Headers.Field(string) case .headerValue: bytes.append(0) let string = bytes.withUnsafeBufferPointer { (pointer: UnsafeBufferPointer<UInt8>) -> String in return String(cString: pointer.baseAddress!) } context.addValueForCurrentHeaderField(string) case .headersComplete: context.currentHeaderField = nil let body = BodyStream(parser: self) context.bodyStream = body if !headersComplete(context: context, body: body, method: method, http_major: http_major, http_minor: http_minor) { return 1 } } bytes = [] state = newState if state == .messageComplete { context.bodyStream?.complete = true context = Context() } } guard let data = data, !data.isEmpty else { return 0 } switch state { case .body: context.bodyStream?.bodyBuffer = data default: bytes.append(contentsOf: data) } return 0 } } private func http_parser_on_message_begin(pointer: UnsafeMutablePointer<http_parser>?, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16) -> Int32 { let parser = Unmanaged<Parser>.fromOpaque(pointer!.pointee.data).takeUnretainedValue() return parser.process(state: .messageBegin, method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) } private func http_parser_on_url( pointer: UnsafeMutablePointer<http_parser>?, data: UnsafePointer<Int8>?, length: Int, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16 ) -> Int32 { let parser = Unmanaged<Parser>.fromOpaque(pointer!.pointee.data).takeUnretainedValue() return parser.process(state: .uri, data: UnsafeRawBufferPointer(start: data, count: length), method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) } private func http_parser_on_status( pointer: UnsafeMutablePointer<http_parser>?, data: UnsafePointer<Int8>?, length: Int, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16 ) -> Int32 { let parser = Unmanaged<Parser>.fromOpaque(pointer!.pointee.data).takeUnretainedValue() return parser.process(state: .status, data: UnsafeRawBufferPointer(start: data, count: length), method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) } private func http_parser_on_header_field( pointer: UnsafeMutablePointer<http_parser>?, data: UnsafePointer<Int8>?, length: Int, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16 ) -> Int32 { let parser = Unmanaged<Parser>.fromOpaque(pointer!.pointee.data).takeUnretainedValue() return parser.process(state: .headerField, data: UnsafeRawBufferPointer(start: data, count: length), method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) } private func http_parser_on_header_value( pointer: UnsafeMutablePointer<http_parser>?, data: UnsafePointer<Int8>?, length: Int, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16 ) -> Int32 { let parser = Unmanaged<Parser>.fromOpaque(pointer!.pointee.data).takeUnretainedValue() return parser.process(state: .headerValue, data: UnsafeRawBufferPointer(start: data, count: length), method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) } private func http_parser_on_headers_complete(pointer: UnsafeMutablePointer<http_parser>?, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16) -> Int32 { let parser = Unmanaged<Parser>.fromOpaque(pointer!.pointee.data).takeUnretainedValue() return parser.process(state: .headersComplete, method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) } private func http_parser_on_body( pointer: UnsafeMutablePointer<http_parser>?, data: UnsafePointer<Int8>?, length: Int, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16 ) -> Int32 { let parser = Unmanaged<Parser>.fromOpaque(pointer!.pointee.data).takeUnretainedValue() return parser.process(state: .body, data: UnsafeRawBufferPointer(start: data, count: length), method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) } private func http_parser_on_message_complete(pointer: UnsafeMutablePointer<http_parser>?, method: Int32, status_code: Int32, http_major: Int16, http_minor: Int16) -> Int32 { let parser = Unmanaged<Parser>.fromOpaque(pointer!.pointee.data).takeUnretainedValue() return parser.process(state: .messageComplete, method: method, status_code: status_code, http_major: http_major, http_minor: http_minor) }
2825c82fdbef914e86a1f8e3dbc66b1d
37.726384
194
0.605349
false
false
false
false
glwithu06/ReTodo
refs/heads/master
ReTodo/View/TaskDetailViewController.swift
mit
1
// // TaskDetailViewController.swift // ReTodo // // Created by Nate Kim on 13/07/2017. // Copyright © 2017 NateKim. All rights reserved. // import UIKit import ReSwift class TaskDetailViewController: UIViewController { var task: Task? let dateFormatter:DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .short return dateFormatter }() @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var noteLabel: UILabel! @IBOutlet weak var dueDateLabel: UILabel! @IBOutlet weak var completeLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() title = "Detail" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(editTapped)) mainStore.subscribe(self) updateView(task: task) } deinit { mainStore.unsubscribe(self) } func editTapped() { guard let task = task else { return } let vc = EditTaskViewController(nibName: "EditTaskViewController", bundle: nil) vc.task = task let nvc = UINavigationController(rootViewController: vc) present(nvc, animated: true, completion: nil) } fileprivate func updateView(task: Task?) { self.task = task self.titleLabel.text = task?.title ?? "-" self.noteLabel.text = task?.note ?? "-" if let date = task?.dueDate { self.dueDateLabel.text = dateFormatter.string(from: date) } else { self.dueDateLabel.text = "-" } self.completeLabel.text = task?.complete.description ?? "-" } } extension TaskDetailViewController: StoreSubscriber { func newState(state: AppState) { guard let taskID = task?.id else { return } if let task = state.taskState.task(taskID: taskID) { updateView(task: task) } else { self.navigationController?.popViewController(animated: true) } } }
547de9881c9e3a0520866bb7ded13d75
29.115942
132
0.631858
false
false
false
false
SunnyPRO/Taylor
refs/heads/master
TaylorFramework/Taylor/Array+Extensions.swift
mit
1
// // Array+Extensions.swift // Taylor // // Created by Andrei Raifura on 10/2/15. // Copyright © 2015 YOPESO. All rights reserved. // import Cocoa extension Array { /** Return an `Array` containing the results of mapping `transform` over `self`. The `transform` operation is parralelized to take advantage of all the proccessor cores. */ func pmap<T>(_ transform: @escaping ((Element) -> T)) -> [T] { guard !self.isEmpty else { return [] } var result: [(Int, [T])] = [] let group = DispatchGroup() let lock = DispatchQueue(label: "com.queue.swift.extensions.pmap", attributes: []) let step = Swift.max(1, self.count / ProcessInfo.processInfo.activeProcessorCount) // step can never be 0 stride(from: 0, to: self.count, by: 1).forEach { stepIndex in let capturedStepIndex = stepIndex var stepResult: [T] = [] DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async(group: group) { for i in (capturedStepIndex * step)..<((capturedStepIndex + 1) * step) { if i < self.count { let mappedElement = transform(self[i]) stepResult += [mappedElement] } } lock.async(group: group) { result += [(capturedStepIndex, stepResult)] } } } _ = group.wait(timeout: DispatchTime.distantFuture) return result.sorted { $0.0 < $1.0 }.flatMap { $0.1 } } } func +<T>(lhs: [T], rhs: T) -> [T] { return lhs + [rhs] }
526ee56e97197c2f68f7e34422821c2a
31.346154
113
0.535077
false
false
false
false
hikelee/cinema
refs/heads/master
Sources/App/Utilities/Logger.swift
mit
1
import Foundation public func log(_ message: String, file: String = #file, function: String = #function, line: Int = #line) { if let name = file.components(separatedBy:"/").last, let p = name.components(separatedBy:".").first { let date = Date().string() print("\(date) \(p).\(function),\(line),\(message)") } }
27a78014907b9ee206387fdee4a2d77f
38.2
92
0.528061
false
false
false
false
rvald/Wynfood.iOS
refs/heads/main
Wynfood/SignInViewController.swift
apache-2.0
1
// // SignInViewController.swift // Wynfood // // Created by craftman on 6/2/17. // Copyright © 2017 craftman. All rights reserved. // import UIKit class SignInViewController: UIViewController { // MARK: - Properties var logInView: LogInView! var registerView: RegisterView! // MARK: - View Cycle override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(self.dissmisView), name: Notification.Name("WynfoodDismissViewNotification"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.presentAlertView), name: Notification.Name("WynfoodPresentAlertNotification"), object: nil) view.backgroundColor = UIColor(red: 243.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, alpha: 1.0) logInView = LogInView(frame: CGRect.zero) registerView = RegisterView(frame: CGRect.zero) setupView() } // MARK: - Views let closeButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Close", for: .normal) button.addTarget(self, action: #selector(closeButtonTap), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false return button }() let segmentedControl: UISegmentedControl = { let control = UISegmentedControl(items: ["Log In", "Register"]) control.addTarget(self, action: #selector(segementedControlTapped), for: .valueChanged) control.tintColor = UIColor(red: 0.0/255.0, green: 122.0/255.0, blue: 255.0/255.0, alpha: 1.0) control.backgroundColor = UIColor.white control.selectedSegmentIndex = 0 control.translatesAutoresizingMaskIntoConstraints = false return control }() // MARK: - Methods func setupView() { view.addSubview(closeButton) view.addSubview(segmentedControl) view.addSubview(registerView) view.addSubview(logInView) registerView.isHidden = true // close button constraints view.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 40.0)) view.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: -20.0)) // segmented control constraints view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-88-[v0(36)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": segmentedControl])) view.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: -20.0)) view.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 20.0)) // log in view constraints view.addConstraint(NSLayoutConstraint(item: logInView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: -20.0)) view.addConstraint(NSLayoutConstraint(item: logInView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 20.0)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[v1]-13-[v0]-24-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": logInView, "v1": segmentedControl])) // register view constraints view.addConstraint(NSLayoutConstraint(item: registerView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: -20.0)) view.addConstraint(NSLayoutConstraint(item: registerView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 20.0)) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[v1]-13-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": registerView, "v1": segmentedControl])) } func presentAlertView(notification: NSNotification) { let message = notification.userInfo?["message"] as! String let alert = UIAlertController(title: "Wynfood", message: message, preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil) } func dissmisView() { dismiss(animated: true, completion: nil) } // MARK: - Actions func closeButtonTap() { dismiss(animated: true, completion: nil) } func segementedControlTapped(sender: UISegmentedControl) { if sender.selectedSegmentIndex == 1 { UIView.animate(withDuration: 0.5, animations: { self.logInView.isHidden = true }, completion: { (true) in UIView.animate(withDuration: 0.5, animations: { self.registerView.isHidden = false }) }) } else if sender.selectedSegmentIndex == 0 { UIView.animate(withDuration: 0.5, animations: { self.registerView.isHidden = true }, completion: { (true) in UIView.animate(withDuration: 0.5, animations: { self.logInView.isHidden = false }) }) } } }
5b6078122debb91b8f41b1583cb90c47
38.447368
198
0.619913
false
false
false
false
hokuron/QRCodeKit
refs/heads/master
Lib/QRCodeKit/CaptureMetadataOutputObjectType.swift
mit
1
// // CaptureMetadataOutputObjectType.swift // QRCodeKit // // Created by hokuron on 2015/11/14. // Copyright © 2015年 Takuma Shimizu. All rights reserved. // import AVFoundation protocol CaptureMetadataOutputObjectType: Equatable { typealias MetadataObject: AVMetadataObject var metadataObject: MetadataObject { get } } protocol CaptureMetadataQRCodeObjectType: CaptureMetadataOutputObjectType { typealias MetadataObject = AVMetadataMachineReadableCodeObject } public struct CaptureMetadataQRCodeObject: CaptureMetadataQRCodeObjectType { var metadataObject: AVMetadataMachineReadableCodeObject } public func == (lhs: CaptureMetadataQRCodeObject, rhs: CaptureMetadataQRCodeObject) -> Bool { return lhs.metadataObject.stringValue == rhs.metadataObject.stringValue }
0b7b578f38695491fd0a03c33d266db9
28.555556
93
0.802005
false
false
false
false
firemuzzy/slugg
refs/heads/master
mobile/Slug/Slug/views/RideTableViewCell.swift
mit
1
// // RideTableViewCell.swift // Slug // // Created by Andrew Charkin on 3/22/15. // Copyright (c) 2015 Slug. All rights reserved. // import UIKit class RideTableViewCell: UITableViewCell { @IBOutlet weak var seatsLeft: UILabel! @IBOutlet weak var timeLeft: UILabel! @IBOutlet weak var personName: UILabel! @IBOutlet weak var fromCompany: UILabel! func setup(ride: Ride) { self.personName.text = ride.driver?.firstName self.timeLeft.text = ride.prettyMinutesLeft() if let company = ride.driver?.company() { self.fromCompany.text = "from \(company.name)" } if let seatsLeft = ride.seatsLeft() { switch seatsLeft { case let x where x < 0: self.seatsLeft.text = "full" case 1: self.seatsLeft.text = "\(seatsLeft) seat left" default: self.seatsLeft.text = "\(seatsLeft) seats left" } } else { self.seatsLeft.text = "unavailable" } } }
d62c4b9c03fc33ea0add4e022867b34f
24.567568
64
0.643763
false
false
false
false
clwm01/RCTools
refs/heads/master
RCToolsDemo/RCToolsDemo/ParagraphViewController.swift
mit
2
// // ParagraphViewController.swift // RCToolsDemo // // Created by Apple on 10/15/15. // Copyright (c) 2015 rexcao. All rights reserved. // import UIKit class ParagraphViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.buildVertialLabel() self.buildRichLabel() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func buildRichLabel() { // let richLabel = MyUILabel(frame: CGRectMake(140, 100, 120, 500)) // richLabel.verticalAlignment = VerticalAlignment.Bottom let richLabel = UILabel(frame: CGRectMake(140, 100, 120, 500)) richLabel.numberOfLines = 0 let text = "战火\n为何而燃,秋叶为何而落?天性不可夺,吾辈心中亦有惑。怒拳为谁握?护国安邦惩奸恶,道法自然除心魔。战无休而惑不息,吾辈何以为战?" // let text = "This is my code used to build a non-smoking app." let ps = NSMutableParagraphStyle() // ps.baseWritingDirection = NSWritingDirection.RightToLeft // ps.alignment = NSTextAlignment.Left ps.lineBreakMode = NSLineBreakMode.ByWordWrapping // set line height // ps.lineHeightMultiple = 20 // ps.maximumLineHeight = 20 // ps.minimumLineHeight = 20 var attribs: [String: AnyObject] = NSDictionary() as! [String : AnyObject] // attribs[NSParagraphStyleAttributeName] = ps // attribs[NSWritingDirectionAttributeName] = NSArray(object: NSNumber(integer: 3)) attribs[NSVerticalGlyphFormAttributeName] = NSNumber(integer: 1) attribs[NSTextLayoutSectionOrientation] = NSNumber(integer: 0) let attributedText = NSMutableAttributedString(string: text, attributes: attribs as [String: AnyObject]) richLabel.attributedText = attributedText richLabel.layer.borderColor = UIColor.blackColor().CGColor richLabel.layer.borderWidth = 1.0 self.view.addSubview(richLabel) } func buildVertialLabel() { let verticalLabel = UIVerticalLabel(frame: CGRectMake(10, 100, 120, 500)) let text = "战火为何而燃,秋叶为何而落?天性不可夺,吾辈心中亦有惑。怒拳为谁握?护国安邦惩奸恶,道法自然除心魔。战无休而惑不息,吾辈何以为战?" verticalLabel.text = text verticalLabel.font = UIFont.systemFontOfSize(26) verticalLabel.layer.borderColor = UIColor.blackColor().CGColor verticalLabel.layer.borderWidth = 1.0 self.view.addSubview(verticalLabel) } }
8375fc890a08a7b41789c73a7f3859e1
36.086957
112
0.666276
false
false
false
false
Raizlabs/ios-template
refs/heads/master
{{ cookiecutter.project_name | replace(' ', '') }}/app/{{ cookiecutter.project_name | replace(' ', '') }}/Application/AppLifecycle/Analytics/AnalyticsPageNames.swift
mit
1
// // AnalyticsPageNames.swift // {{ cookiecutter.project_name | replace(' ', '') }} // // Created by {{ cookiecutter.lead_dev }} on {% now 'utc', '%D' %}. // Copyright © {% now 'utc', '%Y' %} {{ cookiecutter.company_name }}. All rights reserved. // import UIKit protocol PageNameConfiguration { static var nameOverrides: [ObjectIdentifier: String] { get } static var ignoreList: [ObjectIdentifier] { get } } extension UIViewController { var analyticsPageName: String? { return AnalyticsPageName.for(self) } var isSystemClass: Bool { let classBundle = Bundle(for: type(of: self)) return !classBundle.bundlePath.hasPrefix(Bundle.main.bundlePath) } } private enum AnalyticsPageName { static func `for`(_ className: String) -> String? { var pageName = className if let range = pageName.range(of: "ViewController", options: [.backwards, .anchored], range: nil, locale: nil) { pageName.removeSubrange(range) } return pageName.replacingOccurrences(of: "([a-z])([A-Z])", with: "$1 $2", options: .regularExpression, range: pageName.startIndex..<pageName.endIndex) } static func `for`(_ viewController: UIViewController) -> String? { let identifier = ObjectIdentifier(type(of: viewController)) if let pageName = AnalyticsConfiguration.nameOverrides[identifier] { return pageName } else if !AnalyticsConfiguration.ignoreList.contains(identifier), !viewController.isSystemClass { let className = String(describing: type(of: viewController)) return AnalyticsPageName.for(className) } else { return nil } } }
459d34bd022f9a82be8ce32c2ed21079
31.433962
158
0.644561
false
true
false
false
jaynakus/Signals
refs/heads/master
SwiftSignalKit/Signal_SideEffects.swift
mit
1
import Foundation public func beforeNext<T, E, R>(_ f: @escaping(T) -> R) -> (Signal<T, E>) -> Signal<T, E> { return { signal in return Signal<T, E> { subscriber in return signal.start(next: { next in let _ = f(next) subscriber.putNext(next) }, error: { error in subscriber.putError(error) }, completed: { subscriber.putCompletion() }) } } } public func afterNext<T, E, R>(_ f: @escaping(T) -> R) -> (Signal<T, E>) -> Signal<T, E> { return { signal in return Signal<T, E> { subscriber in return signal.start(next: { next in subscriber.putNext(next) let _ = f(next) }, error: { error in subscriber.putError(error) }, completed: { subscriber.putCompletion() }) } } } public func beforeStarted<T, E>(_ f: @escaping() -> Void) -> (Signal<T, E>) -> Signal<T, E> { return { signal in return Signal<T, E> { subscriber in f() return signal.start(next: { next in subscriber.putNext(next) }, error: { error in subscriber.putError(error) }, completed: { subscriber.putCompletion() }) } } } public func beforeCompleted<T, E>(_ f: @escaping() -> Void) -> (Signal<T, E>) -> Signal<T, E> { return { signal in return Signal<T, E> { subscriber in return signal.start(next: { next in subscriber.putNext(next) }, error: { error in subscriber.putError(error) }, completed: { f() subscriber.putCompletion() }) } } } public func afterCompleted<T, E>(_ f: @escaping() -> Void) -> (Signal<T, E>) -> Signal<T, E> { return { signal in return Signal<T, E> { subscriber in return signal.start(next: { next in subscriber.putNext(next) }, error: { error in subscriber.putError(error) }, completed: { subscriber.putCompletion() f() }) } } } public func afterDisposed<T, E, R>(_ f: @escaping(Void) -> R) -> (Signal<T, E>) -> Signal<T, E> { return { signal in return Signal<T, E> { subscriber in let disposable = DisposableSet() disposable.add(signal.start(next: { next in subscriber.putNext(next) }, error: { error in subscriber.putError(error) }, completed: { subscriber.putCompletion() })) disposable.add(ActionDisposable { let _ = f() }) return disposable } } } public func withState<T, E, S>(_ signal: Signal<T, E>, _ initialState: @escaping() -> S, next: @escaping(T, S) -> Void = { _ in }, error: @escaping(E, S) -> Void = { _ in }, completed: @escaping(S) -> Void = { _ in }, disposed: @escaping(S) -> Void = { _ in }) -> Signal<T, E> { return Signal { subscriber in let state = initialState() let disposable = signal.start(next: { vNext in next(vNext, state) subscriber.putNext(vNext) }, error: { vError in error(vError, state) subscriber.putError(vError) }, completed: { completed(state) subscriber.putCompletion() }) return ActionDisposable { disposable.dispose() disposed(state) } } }
7827d5fe99c0239eafddb9b1cbf17706
30.931034
278
0.482181
false
false
false
false
apple/swift
refs/heads/main
test/Sema/diag_dictionary_keys_duplicated.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift class CustomDict: ExpressibleByDictionaryLiteral { typealias Key = String typealias Value = String required init(dictionaryLiteral elements: (String, String)...) {} } func fDict(_ d: [String: String]) {} func fCustomDict(_ d: CustomDict) {} func fDictGeneric<D>(_ d: D) where D: ExpressibleByDictionaryLiteral {} // Duplicated let _ = [ // expected-note@+1{{duplicate key declared here}} {{3-11=}} {{11-12=}} "A": "A", // expected-warning{{dictionary literal of type '[String : String]' has duplicate entries for string literal key 'A'}} "A": "B" // expected-note{{duplicate key declared here}} {{3-12=}} {{16:11-12=}} ] let _: [String: String] = [ // expected-note@+1{{duplicate key declared here}} {{3-11=}} {{11-12=}} "A": "A", // expected-warning{{dictionary literal of type '[String : String]' has duplicate entries for string literal key 'A'}} "A": "B" // expected-note{{duplicate key declared here}} {{3-12=}} {{22:11-12=}} ] let _: [String: String] = [ // expected-note@+1{{duplicate key declared here}} {{3-15=}}{{15-16=}} (("A")): "A", // expected-warning{{dictionary literal of type '[String : String]' has duplicate entries for string literal key 'A'}} "A": "B" // expected-note{{duplicate key declared here}} {{3-12=}} {{28:15-16=}} ] let _: [String: String] = [ // expected-note@+1{{duplicate key declared here}} {{3-11=}} {{11-12=}} "A": "A", // expected-warning{{dictionary literal of type '[String : String]' has duplicate entries for string literal key 'A'}} "B": "B", "C": "C", "A": "D" // expected-note{{duplicate key declared here}} {{3-12=}} {{36:11-12=}} ] // Number literal key let _: [Int: String] = [ // expected-note@+1{{duplicate key declared here}} {{3-9=}} {{9-10=}} 1: "1", // expected-warning{{dictionary literal of type '[Int : String]' has duplicate entries for integer literal key '1'}} 2: "2", 1: "3" // expected-note{{duplicate key declared here}} {{3-10=}} {{44:9-10=}} ] let _: [Double: String] = [ // expected-note@+1{{duplicate key declared here}} {{3-12=}} {{12-13=}} 1.01: "1", // expected-warning{{dictionary literal of type '[Double : String]' has duplicate entries for floating-point literal key '1.01'}} 2: "2", 1.01: "3" // expected-note{{duplicate key declared here}} {{3-13=}} {{51:9-10=}} ] // Boolean literal let _: [Bool: String] = [ // expected-note@+1{{duplicate key declared here}} {{3-12=}} {{12-13=}} true: "1", // expected-warning{{dictionary literal of type '[Bool : String]' has duplicate entries for boolean literal key 'true'}} false: "2", true: "3" // expected-note{{duplicate key declared here}} {{3-13=}} {{59:13-14=}} ] // nil literal let _: [Int?: String] = [ // expected-note@+1{{duplicate key declared here}} {{3-11=}} {{11-12=}} nil: "1", // expected-warning{{dictionary literal of type '[Int? : String]' has duplicate entries for nil literal key}} 2: "2", nil: "3" // expected-note{{duplicate key declared here}} {{3-12=}} {{67:9-10=}} ] // Nested let _: [String: [String: String]] = [ // expected-note@+1{{duplicate key declared here}} {{3-11=}} {{11-12=}} "A": [:], // expected-warning{{dictionary literal of type '[String : [String : String]]' has duplicate entries for string literal key 'A'}} "B": [:], "C": [:], "A": [:] // expected-note{{duplicate key declared here}} {{3-12=}} {{76:11-12=}} ] let _: [String: [String: String]] = [ // expected-note@+1{{duplicate key declared here}} {{3-11=}} {{11-12=}} "A": [:], // expected-warning{{dictionary literal of type '[String : [String : String]]' has duplicate entries for string literal key 'A'}} "B": [:], "C": [:], "A": ["a": "", "a": ""] // expected-note{{duplicate key declared here}} {{3-27=}} {{84:11-12=}} // expected-warning@-1{{dictionary literal of type '[String : String]' has duplicate entries for string literal key 'a'}} // expected-note@-2{{duplicate key declared here}} {{9-16=}} {{16-17=}} // expected-note@-3{{duplicate key declared here}} {{18-25=}} {{16-17=}} ] // Parent OK, nested duplicated let _: [String: [String: String]] = [ "A": [:], "B": [:], "C": [:], // expected-note@+1{{duplicate key declared here}} {{9-16=}} {{16-17=}} "D": ["a": "", "a": ""] // expected-warning{{dictionary literal of type '[String : String]' has duplicate entries for string literal key 'a'}} // expected-note@-1{{duplicate key declared here}}{{18-25=}} {{18-25=}} {{16-17=}} ] // Ok, because custom implementations of ExpressibleByDictionaryLiteral can allow duplicated keys. let _: CustomDict = [ "A": "A", "A": "B" ] fDict([ // expected-note@+1{{duplicate key declared here}} {{3-11=}} {{11-12=}} "A": "A", // expected-warning{{dictionary literal of type '[String : String]' has duplicate entries for string literal key 'A'}} "A": "B" // expected-note{{duplicate key declared here}} {{3-12=}} {{109:11-12=}} ]) fCustomDict([ "A": "A", "A": "B" ]) fDictGeneric([ // expected-note@+1{{duplicate key declared here}} {{3-11=}} {{11-12=}} "A": "A", // expected-warning{{dictionary literal of type '[String : String]' has duplicate entries for string literal key 'A'}} "A": "B" // expected-note{{duplicate key declared here}} {{3-12=}} {{118:11-12=}} ]) // Magic literals let _: [String: String] = [ // expected-note@+1{{duplicate key declared here}} {{3-13=}} {{13-14=}} #file: "A", // expected-warning{{dictionary literal of type '[String : String]' has duplicate entries for #file literal key}} #file: "B" // expected-note{{duplicate key declared here}} {{3-14=}} {{125:13-14=}} ] // OK let _ = [ "A": "A", "B": "B" ] let _: [String: String] = [ "A": "A", "B": "B" ] let _: CustomDict = [ "A": "A", "B": "B" ] // Number literal key let _: [Int: String] = [ 1: "1", 2: "2", 3: "3" ] let _: [Double: String] = [ 1.01: "1", 2: "2", 1.02: "3" ] // Boolean literal let _: [Bool: String] = [ true: "1", false: "2" ] // nil literal let _: [Int?: String] = [ nil: "1", 2: "2" ] // Key as the same variable is OK, we only diagnose literals let a = "A" let _: [String: String] = [ a: "A", "B": "B", "a": "C", a: "D" ] let _: [String: [String: String]] = [ "A": [:], "B": [:], "C": [:], "D": ["a": "", "b": ""] ] fDict([ "A": "A", "B": "B" ]) fCustomDict([ "A": "A", "B": "B" ]) fDictGeneric([ "A": "A", "B": "B" ]) func magicFn() { let _: [String: String] = [ #file: "A", #function: "B" ] } // Interpolated literals let _: [String: String] = [ "\(a)": "A", "\(a)": "B", "\(1)": "C" ] // https://github.com/apple/swift/issues/60873 let _: [Int: String] = [ #line: "A", #line: "B" ] let _: [Int: String] = [#line: "A", #line: "B"] // expected-warning{{dictionary literal of type '[Int : String]' has duplicate entries for #line literal key}} // expected-note@-1{{duplicate key declared here}} {{25-35=}} {{35-36=}} // expected-note@-2{{duplicate key declared here}} {{37-47=}} {{35-36=}} let _: [Int: String] = [#column: "A", #column: "B"] // OK let _: [Int: String] = [ // expected-note@+1{{duplicate key declared here}} {{3-15=}} {{15-16=}} #column: "A", // expected-warning{{dictionary literal of type '[Int : String]' has duplicate entries for #column literal key}} #column: "B" // expected-note{{duplicate key declared here}} {{3-16=}} {{227:15-16=}} ] // https://github.com/apple/swift/issues/62117 _ = [ -1: "", 1: "", ] _ = [ -1.0: "", 1.0: "", ] _ = [ // expected-note@+1{{duplicate key declared}} {{3-9=}} {{9-10=}} -1: "", // expected-warning{{dictionary literal of type '[Int : String]' has duplicate entries for integer literal key '-1'}} -1: "", // expected-note{{duplicate key declared}} {{3-9=}} {{9-10=}} ]
b29a6a543c12ceea96c2dd00f1256563
30.597561
158
0.582272
false
false
false
false
schibsted/layout
refs/heads/master
UIDesigner/EditViewController.swift
mit
1
// Copyright © 2017 Schibsted. All rights reserved. import Layout import ObjectiveC import UIKit private let validClasses: [String] = { var classCount: UInt32 = 0 let classes = objc_copyClassList(&classCount) var names = [String]() for cls in UnsafeBufferPointer(start: classes, count: Int(classCount)) { if class_getSuperclass(cls) != nil, class_conformsToProtocol(cls, NSObjectProtocol.self), cls.isSubclass(of: UIView.self) || cls.isSubclass(of: UIViewController.self) { let name = "\(cls)" if !name.hasPrefix("_") { names.append(name) } } } names = names.sorted() return names }() protocol EditViewControllerDelegate: class { func didUpdateClass(_ viewOrControllerClass: NSObject.Type, for node: LayoutNode) func didUpdateExpression(_ expression: String, for name: String, in node: LayoutNode) } class EditViewController: UIViewController, UITextFieldDelegate { weak var delegate: EditViewControllerDelegate? var node: LayoutNode! { didSet { guard rootNode != nil else { return } if oldValue.view.classForCoder != node.view.classForCoder || oldValue.viewController?.classForCoder != node.viewController?.classForCoder { updateUI() } else { updateFieldValues() } } } var rootNode: LayoutNode! @objc var classField: UITextField? var expressionFields = [String: UITextField]() override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) preferredContentSize = CGSize(width: 320, height: 400) } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() updateUI() } override func viewDidLayoutSubviews() { rootNode.update() } private func updateFieldValues() { for (name, field) in expressionFields { field.text = node.expressions[name] } } private func updateUI() { let cls: AnyClass = node.viewController?.classForCoder ?? node.view.classForCoder var children = [ LayoutNode( view: UITextField(), outlet: #keyPath(classField), expressions: [ "top": "10", "left": "10", "width": "100% - 20", "height": "auto", "borderStyle": "roundedRect", "autocorrectionType": "no", "autocapitalizationType": "none", "placeholder": "Class", "editingChanged": "didUpdateText", "editingDidEnd": "didUpdateClass", "text": "\(cls)", ] ), ] expressionFields.removeAll() func filterType(_ key: String, _ type: RuntimeType) -> String? { if !type.isAvailable { return nil } switch type.swiftType { case is CGFloat.Type, is Double.Type, is Float.Type, is Int.Type, is NSNumber.Type, is Bool.Type, is String.Type, is NSString.Type, is NSAttributedString.Type, is UIColor.Type, is UIImage.Type, is UIFont.Type, is CGImage.Type, is CGColor.Type, is [String].Type: return key default: return type.values.isEmpty ? nil : key } } var fieldNames = ["top", "left", "width", "height", "bottom", "right"] fieldNames.append(contentsOf: node.viewControllerExpressionTypes.compactMap(filterType).sorted()) fieldNames.append(contentsOf: node.viewExpressionTypes.compactMap(filterType).sorted { switch ($0.hasPrefix("layer."), $1.hasPrefix("layer.")) { case (true, true), (false, false): return $0 < $1 case (true, false): return false case (false, true): return true } }) let start = CACurrentMediaTime() for name in fieldNames { children.append( LayoutNode( view: UILabel(), expressions: [ "top": "previous.bottom + 5", "left": "10", "width": "100% - 20", "height": "auto", "text": name, "font": "10", ] ) ) let field = UITextField() field.borderStyle = .roundedRect field.autocorrectionType = .no field.autocapitalizationType = .none field.text = node.expressions[name] expressionFields[name] = field children.append( LayoutNode( view: field, expressions: [ "top": "previous.bottom", "left": "10", "width": "100% - 20", "height": "auto", "borderStyle": "roundedRect", "placeholder": name, "editingDidEnd": "didUpdateField:", ] ) ) } rootNode = LayoutNode( view: UIScrollView(), expressions: [ "width": "100%", "height": "100%", ], children: [ LayoutNode( view: UIView(), expressions: [ "width": "100%", "height": "auto + 10", ], children: children ), ] ) print("nodes:", children.count) print("creation:", round((CACurrentMediaTime() - start) * 1000)) for view in view.subviews { view.removeFromSuperview() } do { try rootNode.mount(in: self) } catch { print("\nError: \(error)\n") } print("creation + mount:", round((CACurrentMediaTime() - start) * 1000)) } @objc func didUpdateText() { classField?.backgroundColor = .white guard let classField = classField, let textRange = classField.textRange(from: classField.beginningOfDocument, to: classField.selectedTextRange?.start ?? classField.endOfDocument), let text = classField.text(in: textRange) else { return } var match = "" for name in validClasses { if match.isEmpty || name.count < match.count, name.lowercased().hasPrefix(text.lowercased()) { match = name } } if !match.isEmpty { let string = NSMutableAttributedString(string: String(match[...text.endIndex]), attributes: [NSAttributedStringKey.foregroundColor: UIColor.black]) string.append(NSMutableAttributedString(string: String(match[text.endIndex...]), attributes: [NSAttributedStringKey.foregroundColor: UIColor.lightGray])) classField.attributedText = string classField.selectedTextRange = classField.textRange(from: textRange.end, to: textRange.end) return } let string = NSAttributedString(string: text, attributes: [NSAttributedStringKey.foregroundColor: UIColor.black]) classField.attributedText = string classField.selectedTextRange = classField.textRange(from: textRange.end, to: textRange.end) } @objc func didUpdateClass() { guard let text = classField?.text else { classField?.text = "UIView" delegate?.didUpdateClass(UIView.self, for: node) return } classField?.attributedText = NSAttributedString(string: text, attributes: [NSAttributedStringKey.foregroundColor: UIColor.black]) guard let cls = NSClassFromString(text) as? NSObject.Type, cls is UIView.Type || cls is UIViewController.Type else { classField?.backgroundColor = UIColor(red: 1, green: 0.5, blue: 0.5, alpha: 1) return } delegate?.didUpdateClass(cls, for: node) } @objc func didUpdateField(_ textField: UITextField) { for (name, field) in expressionFields where field === textField { if (node.expressions[name] ?? "") != (field.text ?? "") { delegate?.didUpdateExpression(field.text ?? "", for: name, in: node) } } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } }
ed4202b28d6eefcb1f2fc67580ade146
34.988417
156
0.512928
false
false
false
false
Derek316x/iOS8-day-by-day
refs/heads/master
37-autosizing-collectionview/WordTiles/WordTiles/WordList.swift
apache-2.0
22
// // Copyright 2014 Scott Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation class WordList { var words = [String]() convenience init() { self.init(fileName: "words") } init(fileName: String) { words = importWordsFromFile(fileName) } func importWordsFromFile(name: String) -> [String] { var result = [String]() if let path = NSBundle.mainBundle().pathForResource(name, ofType: "txt") { let s = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) if let s = s { result = s.componentsSeparatedByString("\n") } } return result } }
751fc669a8419a2a48e32e00a689af98
26.023256
86
0.684755
false
false
false
false
midoks/Swift-Learning
refs/heads/master
whistle/whistle/MusicListTableView.swift
apache-2.0
1
// // ListTableView.swift // LoadWebData // // Created by midoks on 15/3/11. // Copyright (c) 2015年 midoks. All rights reserved. // import Foundation import UIKit class MusicListTableView:UIView { let num:NSInteger = 4 var delegate: MusicListTableViewDelegate! /* 布局开发 添加view */ func start(){ let width = self.frame.size.width / CGFloat(num) self.frame.size.height = 120.0 for(var hn = 0; hn<1; hn++) { let hnpos = CGFloat(hn) * CGFloat(60.0) for(var i:NSInteger=0; i<self.num; i++) { let Music:UIButton = UIButton(type: UIButtonType.System); let pos = CGFloat(i) * CGFloat(width); Music.frame = CGRectMake(pos, hnpos, width, 60) Music.backgroundColor = UIColor.greenColor() Music.tag = i; let istring = String(i+hn); Music.setTitle(istring, forState: UIControlState.Normal) self.addSubview(Music) Music.addTarget(self, action: Selector("click:"), forControlEvents: UIControlEvents.TouchDown) } } } func click(button: UIButton){ self.delegate?.MusicClick!(self, pos: button.tag) } } @objc protocol MusicListTableViewDelegate: NSObjectProtocol { optional func MusicClick(selfObj:MusicListTableView, pos:NSInteger) }
5cceb67906d31178429e50e292869484
25.759259
110
0.57687
false
false
false
false
bridger/NumberPad
refs/heads/master
NumberPad/VisualFormat.swift
apache-2.0
1
// // VisualFormat.swift // SwiftVisualFormat // // Created by Bridger Maxwell on 8/1/14. // Copyright (c) 2014 Bridger Maxwell. All rights reserved. // #if os(OSX) import AppKit public typealias ALVFView = NSView #elseif os(iOS) import UIKit public typealias ALVFView = UIView #endif extension ALVFView { @discardableResult public func addVerticalConstraints(_ constraintAble: [ConstraintAble]) -> [NSLayoutConstraint] { let constraints = verticalConstraints(constraintAble) self.addConstraints(constraints) return constraints } @discardableResult public func addHorizontalConstraints(_ constraintAble: [ConstraintAble]) -> [NSLayoutConstraint] { let constraints = horizontalConstraints(constraintAble) self.addConstraints(constraints) return constraints } public func addAutoLayoutSubview(subview: ALVFView) { subview.translatesAutoresizingMaskIntoConstraints = false self.addSubview(subview) } } @objc public protocol ConstraintAble { func toConstraints(axis: UILayoutConstraintAxis) -> [NSLayoutConstraint]; } public func constraints(axis: UILayoutConstraintAxis, constraintAble: [ConstraintAble]) -> [NSLayoutConstraint] { return constraintAble[0].toConstraints(axis: axis) } public func horizontalConstraints(_ constraintAble: [ConstraintAble]) -> [NSLayoutConstraint] { return constraints(axis: .horizontal, constraintAble: constraintAble) } public func verticalConstraints(_ constraintAble: [ConstraintAble]) -> [NSLayoutConstraint] { return constraints(axis: .vertical, constraintAble: constraintAble) } @objc public protocol ViewContainingToken : ConstraintAble { var firstView: ALVFView? { get } var lastView: ALVFView? { get } } protocol ConstantToken { var ALConstant: CGFloat { get } } // This is half of a space constraint, [view]-space class ViewAndSpaceToken : NSObject { let view: ViewContainingToken let space: ConstantToken let relation: NSLayoutRelation init(view: ViewContainingToken, space: ConstantToken, relation: NSLayoutRelation) { self.view = view self.space = space self.relation = relation } } // This is half of a space constraint, |-5 class LeadingSuperviewAndSpaceToken : NSObject { let space: ConstantToken let relation: NSLayoutRelation init(space: ConstantToken, relation: NSLayoutRelation) { self.space = space self.relation = relation } } // This is half of a space constraint, 5-| class TrailingSuperviewAndSpaceToken : NSObject { let space: ConstantToken init(space: ConstantToken) { self.space = space } } // [view]-5-[view2] class SpacedViewsConstraintToken: NSObject, ConstraintAble, ViewContainingToken { let leadingView: ViewContainingToken let trailingView: ViewContainingToken let space: ConstantToken init(leadingView: ViewContainingToken, trailingView: ViewContainingToken, space: ConstantToken) { self.leadingView = leadingView self.trailingView = trailingView self.space = space } var firstView: UIView? { get { return self.leadingView.firstView } } var lastView: UIView? { get { return self.trailingView.lastView } } func toConstraints(axis: UILayoutConstraintAxis) -> [NSLayoutConstraint] { if let leadingView = self.leadingView.lastView { if let trailingView = self.trailingView.firstView { let space = self.space.ALConstant var leadingAttribute: NSLayoutAttribute! var trailingAttribute: NSLayoutAttribute! if (axis == .horizontal) { leadingAttribute = .leading trailingAttribute = .trailing } else { leadingAttribute = .top trailingAttribute = .bottom } var constraints = [NSLayoutConstraint( item: trailingView, attribute: leadingAttribute, relatedBy: .equal, toItem: leadingView, attribute: trailingAttribute, multiplier: 1.0, constant: space)] constraints += self.leadingView.toConstraints(axis: axis) constraints += self.trailingView.toConstraints(axis: axis) return constraints } } NSException(name: NSExceptionName.invalidArgumentException, reason: "This space constraint was between two view items that couldn't fit together. Weird?", userInfo: nil).raise() return [] // To appease the compiler, which doesn't realize this branch dies } } // [view == 50] class SizeConstantConstraintToken: NSObject, ConstraintAble, ViewContainingToken { let view: ALVFView let size: ConstantToken let relation: NSLayoutRelation init(view: ALVFView, size: ConstantToken, relation: NSLayoutRelation) { self.view = view self.size = size self.relation = relation } var firstView: ALVFView? { get { return self.view.firstView } } var lastView: ALVFView? { get { return self.view.lastView } } func toConstraints(axis: UILayoutConstraintAxis) -> [NSLayoutConstraint] { let constant = self.size.ALConstant var attribute: NSLayoutAttribute! if (axis == .horizontal) { attribute = .width } else { attribute = .height } let constraint = NSLayoutConstraint( item: self.view, attribute: attribute, relatedBy: self.relation, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: constant) return [constraint] } } // [view == view2] class SizeRelationConstraintToken: NSObject, ConstraintAble, ViewContainingToken { let view: ALVFView let relatedView: ALVFView let relation: NSLayoutRelation init(view: ALVFView, relatedView: ALVFView, relation: NSLayoutRelation) { self.view = view self.relatedView = relatedView self.relation = relation } var firstView: ALVFView? { get { return self.view.firstView } } var lastView: ALVFView? { get { return self.view.lastView } } func toConstraints(axis: UILayoutConstraintAxis) -> [NSLayoutConstraint] { var attribute: NSLayoutAttribute! if (axis == .horizontal) { attribute = .width } else { attribute = .height } return [ NSLayoutConstraint( item: self.view, attribute: attribute, relatedBy: self.relation, toItem: self.relatedView, attribute: attribute, multiplier: 1.0, constant: 0) ] } } // |-5-[view] public class LeadingSuperviewConstraintToken: NSObject, ConstraintAble, ViewContainingToken { let viewContainer: ViewContainingToken let space: ConstantToken init(viewContainer: ViewContainingToken, space: ConstantToken) { self.viewContainer = viewContainer self.space = space } public var firstView: UIView? { get { return nil // No one can bind to our first view, is the superview } } public var lastView: UIView? { get { return self.viewContainer.lastView } } public func toConstraints(axis: UILayoutConstraintAxis) -> [NSLayoutConstraint] { if let view = self.viewContainer.firstView { let constant = self.space.ALConstant if let superview = view.superview { var constraint: NSLayoutConstraint! if (axis == .horizontal) { constraint = NSLayoutConstraint( item: view, attribute: .leading, relatedBy: .equal, toItem: superview, attribute: .leading, multiplier: 1.0, constant: constant) } else { constraint = NSLayoutConstraint( item: view, attribute: .top, relatedBy: .equal, toItem: superview, attribute: .top, multiplier: 1.0, constant: constant) } return viewContainer.toConstraints(axis: axis) + [constraint] } NSException(name: NSExceptionName.invalidArgumentException, reason: "You tried to create a constraint to \(view)'s superview, but it has no superview yet!", userInfo: nil).raise() } NSException(name: NSExceptionName.invalidArgumentException, reason: "This superview bar | was before something that doesn't have a view. Weird?", userInfo: nil).raise() return [] // To appease the compiler, which doesn't realize this branch dies } } // [view]-5-| public class TrailingSuperviewConstraintToken: NSObject, ConstraintAble, ViewContainingToken { let viewContainer: ViewContainingToken let space: ConstantToken init(viewContainer: ViewContainingToken, space: ConstantToken) { self.viewContainer = viewContainer self.space = space } public var firstView: UIView? { get { return self.viewContainer.firstView } } public var lastView: UIView? { get { return nil // No one can bind to our last view, is the superview } } public func toConstraints(axis: UILayoutConstraintAxis) -> [NSLayoutConstraint] { if let view = self.viewContainer.lastView { let constant = self.space.ALConstant if let superview = view.superview { var constraint: NSLayoutConstraint! if (axis == .horizontal) { constraint = NSLayoutConstraint( item: superview, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: constant) } else { constraint = NSLayoutConstraint( item: superview, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: constant) } return viewContainer.toConstraints(axis: axis) + [constraint] } NSException(name: NSExceptionName.invalidArgumentException, reason: "You tried to create a constraint to \(view)'s superview, but it has no superview yet!", userInfo: nil).raise() } NSException(name: NSExceptionName.invalidArgumentException, reason: "This superview bar | was after something that doesn't have a view. Weird?", userInfo: nil).raise() return [] // To appease the compiler, which doesn't realize this branch dies } } let RequiredPriority: Float = 1000 // For some reason, the linker can't find UILayoutPriorityRequired. Not sure what I am doing wrong prefix operator | prefix public func | (tokenArray: [ViewContainingToken]) -> [LeadingSuperviewConstraintToken] { // |[view] return [LeadingSuperviewConstraintToken(viewContainer: tokenArray[0], space: 0)] } postfix operator | postfix public func | (tokenArray: [ViewContainingToken]) -> [TrailingSuperviewConstraintToken] { // [view]| return [TrailingSuperviewConstraintToken(viewContainer: tokenArray[0], space: 0)] } func >= (left: ALVFView, right: ConstantToken) -> SizeConstantConstraintToken { // [view >= 50] return SizeConstantConstraintToken(view: left, size: right, relation: .greaterThanOrEqual) } func >= (left: ALVFView, right: ALVFView) -> SizeRelationConstraintToken { // [view >= view2] return SizeRelationConstraintToken(view: left, relatedView: right, relation: .greaterThanOrEqual) } func <= (left: ALVFView, right: ConstantToken) -> SizeConstantConstraintToken { // [view <= 50] return SizeConstantConstraintToken(view: left, size: right, relation: .lessThanOrEqual) } func <= (left: ALVFView, right: ALVFView) -> SizeRelationConstraintToken { // [view <= view2] return SizeRelationConstraintToken(view: left, relatedView: right, relation: .lessThanOrEqual) } func == (left: ALVFView, right: ConstantToken) -> SizeConstantConstraintToken { // [view == 50] return SizeConstantConstraintToken(view: left, size: right, relation: .equal) } func == (left: ALVFView, right: ALVFView) -> SizeRelationConstraintToken { // [view == view2] return SizeRelationConstraintToken(view: left, relatedView: right, relation: .equal) } func - (left: [ViewContainingToken], right: ConstantToken) -> ViewAndSpaceToken { // [view]-5 return ViewAndSpaceToken(view: left[0], space: right, relation: .equal) } func - (left: ViewAndSpaceToken, right: [ViewContainingToken]) -> [SpacedViewsConstraintToken] { // [view]-5-[view2] return [SpacedViewsConstraintToken(leadingView: left.view, trailingView: right[0], space: left.space)] } func - (left: [ViewContainingToken], right: TrailingSuperviewAndSpaceToken) -> [TrailingSuperviewConstraintToken] { // [view]-5-| return [TrailingSuperviewConstraintToken(viewContainer: left[0], space: right.space)] } func - (left: LeadingSuperviewAndSpaceToken, right: [ViewContainingToken]) -> [LeadingSuperviewConstraintToken] { // |-5-[view] return [LeadingSuperviewConstraintToken(viewContainer: right[0], space: left.space)] } postfix operator -| postfix func -| (constant: ConstantToken) -> TrailingSuperviewAndSpaceToken { // 5-| return TrailingSuperviewAndSpaceToken(space: constant) } prefix operator |- prefix func |- (constant: ConstantToken) -> LeadingSuperviewAndSpaceToken { // |-5 return LeadingSuperviewAndSpaceToken(space: constant, relation: .equal) } extension ALVFView: ViewContainingToken { public var firstView: ALVFView? { get { return self } } public var lastView: ALVFView? { get { return self } } public func toConstraints(axis: UILayoutConstraintAxis) -> [NSLayoutConstraint] { return [] } } extension CGFloat: ConstantToken { var ALConstant: CGFloat { get { return self } } } extension NSInteger: ConstantToken { var ALConstant: CGFloat { get { return CGFloat(self) } } }
b945e9805ba118ff04e52392061f293d
33.4375
191
0.63084
false
false
false
false
Inquisitor0/LSB2
refs/heads/master
DribbbleCollection/Pods/Tabman/Sources/Tabman/TabmanBar/Utilities/PositionalUtils.swift
mit
4
// // PositionalUtils.swift // Tabman // // Created by Merrick Sapsford on 14/03/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import Foundation import Pageboy internal class TabmanPositionalUtil { /// Get the lower & upper tab indexes for a current relative position. /// /// - Parameters: /// - position: The current position. /// - minimum: The minimum possible index. /// - maximum: The maximum possible index. /// - Returns: The lower and upper indexes for the position. static func lowerAndUpperIndex(forPosition position: CGFloat, minimum: Int, maximum: Int) -> (Int, Int) { let lowerIndex = floor(position) let upperIndex = ceil(position) let minimum = CGFloat(minimum) let maximum = CGFloat(maximum) return (Int(max(minimum, min(maximum, lowerIndex))), Int(min(maximum, max(minimum, upperIndex)))) } /// Get the target index that a transition is travelling toward. /// /// - Parameters: /// - position: The current position. /// - direction: The current travel direction. /// - range: The valid range of indexes. /// - Returns: The target index. static func targetIndex(forPosition position: CGFloat, direction: PageboyViewController.NavigationDirection, range: Range<Int>) -> Int { var index: Int! switch direction { case .reverse: index = Int(floor(position)) default: index = Int(ceil(position)) } return max(range.lowerBound, min(range.upperBound - 1, index)) } }
fd508063946c58219c95688541fe66cd
32.84
109
0.605201
false
false
false
false
ApterKingRepo/Verify-SwiftOC3rd
refs/heads/master
Example/Verify-SwiftOC3rd/ViewController.swift
mit
1
// // ViewController.swift // Verify-SwiftOC3rd // // Created by [email protected] on 06/30/2017. // Copyright (c) 2017 [email protected]. All rights reserved. // import UIKit import Verify_SwiftOC3rd class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let kid = Kid() kid.name = "小明" let family = Family() family.kid = kid family.father = Father(name: "Davi", kid: kid) family.mother = Mother(name: "Lily", kid: kid) family.feed("牛肉", mFood: "牛奶") let button = UIButton(frame: CGRect(x: 200, y: 200, width: 100, height: 50)) button.setTitle("跳转", for: .normal) button.setTitleColor(UIColor.blue, for: .normal) button.addTarget(self, action: #selector(jump), for: .touchUpInside) self.view.addSubview(button) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func jump() { let mapVC = MapViewController() self.present(mapVC, animated: true, completion: nil) } }
095e8782a6654828e4fd5b54127c3006
26.086957
84
0.630016
false
false
false
false
jengelsma/cis657-summer2016-class-demos
refs/heads/master
Lecture04-StopWatch-Demo/Lecture04-StopWatch-Demo/ViewController.swift
mit
1
// // ViewController.swift // Lecture04-StopWatch-Demo // // Created by Jonathan Engelsma on 5/19/16. // Copyright © 2016 Jonathan Engelsma. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var displayLabel: UILabel! @IBOutlet weak var modeButton: UIButton! @IBOutlet weak var startButton: UIButton! @IBOutlet weak var clearButton: UIButton! var myModel: MyModel = MyModel() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.myModel.stopWatchTimer = NSTimer(timeInterval: 1.0/10.0, target: self, selector: #selector(ViewController.updateTimer), userInfo: nil, repeats: true) NSRunLoop.currentRunLoop().addTimer(self.myModel.stopWatchTimer, forMode: NSRunLoopCommonModes) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateTimer() { if(self.myModel.timing) { let currentDate: NSDate = NSDate() let timeInterval : NSTimeInterval = currentDate.timeIntervalSinceDate(self.myModel.startTime) let timerDate = NSDate(timeIntervalSince1970: timeInterval) let dateFormatter = NSDateFormatter() dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT") dateFormatter.setLocalizedDateFormatFromTemplate("HH:mm:ss:SSS") let timeString: String = dateFormatter.stringFromDate(timerDate) self.displayLabel.text = timeString } } @IBAction func clearTimer(sender: UIButton) { self.displayLabel.text = "00:00:00:000" } @IBAction func startTimer(sender: UIButton) { if self.myModel.timing { self.myModel.pauseTime = NSDate() self.myModel.timing = false self.startButton.setTitle("Start", forState: UIControlState.Normal) self.clearButton.enabled = true } else { self.myModel.timing = true if displayLabel.text == "00:00:00:000" { self.myModel.startTime = NSDate() } else { let currentDate = NSDate() let timeInterval: NSTimeInterval = currentDate.timeIntervalSinceDate(self.myModel.pauseTime) self.myModel.startTime = self.myModel.startTime.dateByAddingTimeInterval(timeInterval) } self.startButton.setTitle("Pause", forState: UIControlState.Normal) self.clearButton.enabled = false } } @IBAction func toggleNightMode(sender: UIButton) { if self.modeButton.titleLabel!.text == "Night" { self.modeButton.setTitle("Day", forState: UIControlState.Normal) self.view.backgroundColor = UIColor.blackColor() self.displayLabel.textColor = UIColor.whiteColor() } else { self.modeButton.setTitle("Night", forState: UIControlState.Normal) self.view.backgroundColor = UIColor.whiteColor() self.displayLabel.textColor = UIColor.blackColor() } self.setNeedsStatusBarAppearanceUpdate() } override func preferredStatusBarStyle() -> UIStatusBarStyle { if self.modeButton == nil || self.modeButton?.titleLabel!.text == "Day" { return UIStatusBarStyle.Default } else { return UIStatusBarStyle.LightContent } } }
73979ec6d35600a35a9006e58de78fb9
34.086538
162
0.643464
false
false
false
false
naru-jpn/View2ViewTransition
refs/heads/master
Example/View2ViewTransitionExample/View2ViewTransitionExample/MenuViewController.swift
mit
1
// // MenuViewController.swift // View2ViewTransitionExample // // Created by naru on 2016/09/06. // Copyright © 2016年 naru. All rights reserved. // import UIKit public class MenuViewController: UIViewController { override public func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.view.addSubview(self.tableView) } override public func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) guard !self.isViewControllerInitialized else { return } self.isViewControllerInitialized = true self.present(PresentingViewController(), animated: true, completion: nil) } // MARK: Constants private struct Constants { static let Font: UIFont = UIFont.systemFont(ofSize: 15.0) static let ButtonSize: CGSize = CGSize(width: 200.0, height: 44.0) } // MARK: Elements private var isViewControllerInitialized: Bool = false lazy var tableView: UITableView = { let tableView: UITableView = UITableView(frame: self.view.bounds, style: .grouped) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") tableView.register(TableViewSectionHeader.self, forHeaderFooterViewReuseIdentifier: "header") tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView.delegate = self tableView.dataSource = self return tableView }() } extension MenuViewController: UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { return 1 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath) self.configulerCell(cell, at: indexPath as NSIndexPath) return cell } func configulerCell(_ cell: UITableViewCell, at indexPath: NSIndexPath) { cell.accessoryType = .disclosureIndicator cell.textLabel?.font = UIFont.systemFont(ofSize: 14.0) switch indexPath.row { case 0: cell.textLabel?.text = "Present and Dismiss" case 1: cell.textLabel?.text = "Push and Pop" default: break } } } extension MenuViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return TableViewSectionHeader.Constants.Height } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44.0 } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: self.present(PresentingViewController(), animated: true, completion: nil) case 1: self.present(UINavigationController(rootViewController: PresentingViewController()), animated: true, completion: nil) default: break } tableView.deselectRow(at: indexPath as IndexPath, animated: true) } } private class TableViewSectionHeader: UITableViewHeaderFooterView { struct Constants { static let Height: CGFloat = 60.0 static let Width: CGFloat = UIScreen.main.bounds.width static let Font: UIFont = UIFont.boldSystemFont(ofSize: 14.0) } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) self.contentView.addSubview(self.titleLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var titleLabel: UILabel = { let frame: CGRect = CGRect(x: 12.0, y: Constants.Height - ceil(Constants.Font.lineHeight) - 8.0, width: Constants.Width - 24.0, height: ceil(Constants.Font.lineHeight)) let label: UILabel = UILabel(frame: frame) label.font = Constants.Font label.text = "Examples of View2View Transition" label.textColor = UIColor(white: 0.3, alpha: 1.0) return label }() }
81c74bfd78c92796e8e7443488471871
32.955556
176
0.664049
false
false
false
false
marsal-silveira/Tonight
refs/heads/master
Tonight/src/Utils/CLLocationDistance+Tonight.swift
mit
1
// // CLLocationDistance+Tonight.swift // Tonight // // Created by Domsys on 01/03/16. // Copyright © 2016 Marsal Silveira. All rights reserved. // extension CLLocationDistance { // 100 centimeter == 1 meter func toCentimeter() -> CLLocationDistance { return self*1000 } // 1 foot == 0.3048 meter // 1 meter == 3.2808399 feet func toFeet() -> CLLocationDistance { return self*3.280 } // 1 kilometer == 1000 meters func toKilometer() -> CLLocationDistance { return self/1000 } }
3ed4e16490e493e692d06e4a2be75827
18.62069
58
0.598592
false
false
false
false
lyimin/EyepetizerApp
refs/heads/master
EyepetizerApp/EyepetizerApp/Views/DiscoverView/EYEDiscoverCell.swift
mit
1
// // EYEDiscoverCell.swift // EyepetizerApp // // Created by 梁亦明 on 16/3/17. // Copyright © 2016年 xiaoming. All rights reserved. // import Foundation class EYEDiscoverCell : UICollectionViewCell, Reusable { override init(frame: CGRect) { super.init(frame: frame) self.contentView.addSubview(backgroundImageView) self.contentView.addSubview(coverButton) self.contentView.addSubview(titleLabel) backgroundImageView.snp_makeConstraints { [unowned self](make) -> Void in make.edges.equalTo(self.contentView) } coverButton.snp_makeConstraints { [unowned self](make) -> Void in make.edges.equalTo(self.contentView) } titleLabel.snp_makeConstraints { [unowned self](make) -> Void in make.leading.trailing.equalTo(self.contentView) make.height.equalTo(20) make.centerY.equalTo(self.contentView.center).offset(0) } } var model : EYEDiscoverModel! { didSet { self.backgroundImageView.yy_setImageWithURL(NSURL(string: model.bgPicture)!, options: .ProgressiveBlur) self.titleLabel.text = model.name } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: --------------------------- Getter or Setter -------------------------- /// 背景图片 private var backgroundImageView : UIImageView = { var backgroundImageView : UIImageView = UIImageView () return backgroundImageView }() /// 黑色图层 private lazy var coverButton : UIButton = { var coverButton : UIButton = UIButton() coverButton.userInteractionEnabled = false coverButton.backgroundColor = UIColor.blackColor() coverButton.alpha = 0.3 return coverButton }() /// 标题 private var titleLabel : UILabel = { var titleLabel : UILabel = UILabel() titleLabel.textColor = UIColor.whiteColor() titleLabel.textAlignment = .Center titleLabel.font = UIFont.customFont_FZLTZCHJW(fontSize: UIConstant.UI_FONT_16) return titleLabel }() }
09c82549d7f355809ab6206210100ebb
32.348485
115
0.622273
false
false
false
false
anilkumarbp/ringcentral-swift-v2
refs/heads/master
RingCentral/Platform/Platform.swift
mit
1
// // Platform.swift // RingCentral. // // Created by Anil Kumar BP on 2/10/16 // Copyright © 2016 Anil Kumar BP. All rights reserved.. // import Foundation /// Platform used to call HTTP request methods. public class Platform { // platform Constants public let ACCESS_TOKEN_TTL = "3600"; // 60 minutes public let REFRESH_TOKEN_TTL = "604800"; // 1 week public let TOKEN_ENDPOINT = "/restapi/oauth/token"; public let REVOKE_ENDPOINT = "/restapi/oauth/revoke"; public let API_VERSION = "v1.0"; public let URL_PREFIX = "/restapi"; // Platform credentials internal var auth: Auth internal var client: Client internal let server: String internal let appKey: String internal let appSecret: String internal var appName: String internal var appVersion: String internal var USER_AGENT: String // Creating an enum /// Constructor for the platform of the SDK /// /// - parameter appKey: The appKey of your app /// - parameter appSecet: The appSecret of your app /// - parameter server: Choice of PRODUCTION or SANDBOX public init(client: Client, appKey: String, appSecret: String, server: String, appName: String = "", appVersion: String = "") { self.appKey = appKey self.appName = appName != "" ? appName : "Unnamed" self.appVersion = appVersion != "" ? appVersion : "0.0.0" self.appSecret = appSecret self.server = server self.auth = Auth() self.client = client self.USER_AGENT = "Swift :" + "/App Name : " + appName + "/App Version :" + appVersion + "/Current iOS Version :" + "/RCSwiftSDK"; } // Returns the auth object /// public func returnAuth() -> Auth { return self.auth } /// func createUrl /// /// @param: path The username of the RingCentral account /// @param: options The password of the RingCentral account /// @response: ApiResponse The password of the RingCentral account public func createUrl(path: String, options: [String: AnyObject]) -> String { var builtUrl = "" if(options["skipAuthCheck"] === true){ builtUrl = builtUrl + self.server + path return builtUrl } builtUrl = builtUrl + self.server + self.URL_PREFIX + "/" + self.API_VERSION + path return builtUrl } /// Authenticates the user with the correct credentials /// /// - parameter username: The username of the RingCentral account /// - parameter password: The password of the RingCentral account public func login(username: String, ext: String, password: String, completion: (apiresponse: ApiResponse?,apiexception: NSException?) -> Void) { requestToken(self.TOKEN_ENDPOINT,body: [ "grant_type": "password", "username": username, "extension": ext, "password": password, "access_token_ttl": self.ACCESS_TOKEN_TTL, "refresh_token_ttl": self.REFRESH_TOKEN_TTL ]) { (t,e) in self.auth.setData(t!.getDict()) completion(apiresponse: t, apiexception: e) } } /// Refreshes the Auth object so that the accessToken and refreshToken are updated. /// /// **Caution**: Refreshing an accessToken will deplete it's current time, and will /// not be appended to following accessToken. public func refresh(completion: (apiresponse: ApiResponse?,apiexception: NSException?) -> Void) throws { if(!self.auth.refreshTokenValid()){ throw ApiException(apiresponse: nil, error: NSException(name: "Refresh token has expired", reason: "reason", userInfo: nil)) // apiexception // throw ApiException(apiresponse: nil, error: NSException(name: "Refresh token has expired", reason: "reason", userInfo: nil)) } requestToken(self.TOKEN_ENDPOINT,body: [ "refresh_token": self.auth.refreshToken(), "grant_type": "refresh_token", "access_token_ttl": self.ACCESS_TOKEN_TTL, "refresh_token_ttl": self.REFRESH_TOKEN_TTL ]) { (t,e) in self.auth.setData(t!.getDict()) completion(apiresponse: t, apiexception: e) } } /// func inflateRequest () /// /// @param: request NSMutableURLRequest /// @param: options list of options /// @response: NSMutableURLRequest public func inflateRequest(request: NSMutableURLRequest, options: [String: AnyObject], completion: (apiresponse: ApiResponse?,apiexception: NSException?) -> Void) -> NSMutableURLRequest { if options["skipAuthCheck"] == nil { ensureAuthentication() { (t,e) in completion(apiresponse: t, apiexception: e) } let authHeader = self.auth.tokenType() + " " + self.auth.accessToken() request.setValue(authHeader, forHTTPHeaderField: "Authorization") request.setValue(self.USER_AGENT, forHTTPHeaderField: "User-Agent") } return request } /// func sendRequest () /// /// @param: request NSMutableURLRequest /// @param: options list of options /// @response: ApiResponse Callback public func sendRequest(request: NSMutableURLRequest, options: [String: AnyObject]!, completion: (apiresponse: ApiResponse?,apiexception: NSException?) -> Void) { do{ try client.send(inflateRequest(request, options: options){ (t,e) in completion(apiresponse: t, apiexception: e) }) { (t,e) in completion(apiresponse: t, apiexception: e) } } catch { print("error") } } /// func requestToken () /// /// @param: path The token endpoint /// @param: array The body /// @return ApiResponse func requestToken(path: String, body: [String:AnyObject], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) { let authHeader = "Basic" + " " + self.apiKey() var headers: [String: String] = [:] headers["Authorization"] = authHeader headers["Content-type"] = "application/x-www-form-urlencoded;charset=UTF-8" headers["User-Agent"] = self.USER_AGENT var options: [String: AnyObject] = [:] options["skipAuthCheck"] = true let urlCreated = createUrl(path,options: options) sendRequest(self.client.createRequest("POST", url: urlCreated, query: nil, body: body, headers: headers), options: options){ (r,e) in completion(apiresponse: r,exception: e) } } /// Base 64 encoding func apiKey() -> String { let plainData = (self.appKey + ":" + self.appSecret as NSString).dataUsingEncoding(NSUTF8StringEncoding) let base64String = plainData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) return base64String } /// Logs the user out of the current account. /// /// Kills the current accessToken and refreshToken. public func logout(completion: (apiresponse: ApiResponse?,apiexception: NSException?) -> Void) { requestToken(self.TOKEN_ENDPOINT,body: [ "token": self.auth.accessToken() ]) { (t,e) in self.auth.reset() completion(apiresponse: t, apiexception: e) } } /// Check if the accessToken is valid func ensureAuthentication(completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) { if (!self.auth.accessTokenValid()) { do{ try refresh() { (r,e) in completion(apiresponse: r,exception: e) } } catch { print("error") } } } // Generic Method calls ( HTTP ) GET /// /// @param: url token endpoint /// @param: query body /// @return ApiResponse Callback public func get(url: String, query: [String: String]?=["":""], body: [String: AnyObject]?=nil, headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) { let urlCreated = createUrl(url,options: options!) sendRequest(self.client.createRequest("GET", url: urlCreated, query: query, body: body, headers: headers!), options: options) { (r,e) in completion(apiresponse: r,exception: e) } } // Generic Method calls ( HTTP ) POST /// /// @param: url token endpoint /// @param: body body /// @return ApiResponse Callback public func post(url: String, query: [String: String]?=["":""], body: [String: AnyObject] = ["":""], headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) { let urlCreated = createUrl(url,options: options!) sendRequest(self.client.createRequest("POST", url: urlCreated, query: query, body: body, headers: headers!), options: options) { (r,e) in completion(apiresponse: r,exception: e) } } // Generic Method calls ( HTTP ) PUT /// /// @param: url token endpoint /// @param: body body /// @return ApiResponse Callback public func put(url: String, query: [String: String]?=["":""], body: [String: AnyObject] = ["":""], headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) { let urlCreated = createUrl(url,options: options!) sendRequest(self.client.createRequest("PUT", url: urlCreated, query: query, body: body, headers: headers!), options: options) { (r,e) in completion(apiresponse: r,exception: e) } } // Generic Method calls ( HTTP ) DELETE /// /// @param: url token endpoint /// @param: query body /// @return ApiResponse Callback public func delete(url: String, query: [String: String] = ["":""], body: [String: AnyObject]?=nil, headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) { let urlCreated = createUrl(url,options: options!) sendRequest(self.client.createRequest("DELETE", url: urlCreated, query: query, body: body, headers: headers!), options: options) { (r,e) in completion(apiresponse: r,exception: e) } } }
c1b5c62fc22e94cfdda11f0d6e05b066
39.100719
254
0.577323
false
false
false
false
lcdtyph/ClassRob
refs/heads/master
ClassRob/ClassRob/WebViewController.swift
gpl-3.0
1
// // WebViewController.swift // ClassRob // // Created by lcdtyph on 4/23/17. // Copyright © 2017 lcdtyph. All rights reserved. // import UIKit class WebViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var indicator: UIActivityIndicatorView! @IBOutlet weak var webView: UIWebView! var news: News? = nil override func viewDidLoad() { super.viewDidLoad() webView.delegate = self // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { let url = URL(string: (news?.url)!) webView.loadRequest(URLRequest(url: url!)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func webViewDidStartLoad(_ webView: UIWebView) { UIApplication.shared.isNetworkActivityIndicatorVisible = true indicator.startAnimating() } func webViewDidFinishLoad(_ webView: UIWebView) { UIApplication.shared.isNetworkActivityIndicatorVisible = false indicator.stopAnimating() } func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { UIApplication.shared.isNetworkActivityIndicatorVisible = false indicator.stopAnimating() } func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { if navigationType == UIWebViewNavigationType.linkClicked { UIApplication.shared.open(request.url!, options: [:], completionHandler: nil) return false } return true } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
bfffe106796ff611a1a2771fbe73f915
28.768116
130
0.681597
false
false
false
false
wujianguo/ColoredNavigationController
refs/heads/master
ColoredNavigationController/ColoredNavigation/ColoredNavigationController.swift
mit
1
// // ColoredNavigationController.swift // ColoredNavigationController // // Created by wujianguo on 16/5/18. // Copyright © 2016年 wujianguo. All rights reserved. // import UIKit class ColoredBaseViewController: UIViewController { func navigationBarTransparent() -> Bool { return false } func navigationBarBarTintColor() -> UIColor? { return navigationController?.navigationBar.barTintColor } func navigationBarBarStyle() -> UIBarStyle { return navigationController!.navigationBar.barStyle } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) addFakeNavigationBar() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.updateNavigationBarUI(navigationController?.navigationBar) self.removeFakeNavigationBar() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) addFakeNavigationBar() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) removeFakeNavigationBar() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() fakeBar?.frame = CGRectMake(0, 0, CGRectGetWidth(view.bounds), topLayoutGuide.length) } func updateNavigationBarUI(bar: UINavigationBar?) { bar?.barTintColor = navigationBarBarTintColor() bar?.barStyle = navigationBarBarStyle() if navigationBarTransparent() { bar?.shadowImage = UIImage() bar?.setBackgroundImage(UIImage(), forBarMetrics: .Default) } else { bar?.shadowImage = nil; bar?.setBackgroundImage(nil, forBarMetrics: .Default) } } var fakeBar: UINavigationBar? func addFakeNavigationBar() { navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default) fakeBar = UINavigationBar() updateNavigationBarUI(fakeBar!) view.addSubview(fakeBar!) fakeBar?.frame = CGRectMake(0, 0, CGRectGetWidth(view.bounds), topLayoutGuide.length) } func removeFakeNavigationBar() { fakeBar?.removeFromSuperview() fakeBar = nil } }
453ce26d24ec80b95c386982cde0d1f7
29.076923
98
0.678176
false
false
false
false
dusek/firefox-ios
refs/heads/master
Providers/Profile.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation typealias LogoutCallback = (profile: AccountProfile) -> () /** * A Profile manages access to the user's data. */ protocol Profile { var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> { get } var favicons: Favicons { get } var clients: Clients { get } var prefs: ProfilePrefs { get } // Because we can't test for whether this is an AccountProfile. // TODO: probably Profile should own an Account. func logout() // I got really weird EXC_BAD_ACCESS errors on a non-null reference when I made this a getter. // Similar to <http://stackoverflow.com/questions/26029317/exc-bad-access-when-indirectly-accessing-inherited-member-in-swift>. func localName() -> String } protocol AccountProfile: Profile { var accountName: String { get } func basicAuthorizationHeader() -> String func makeAuthRequest(request: String, success: (data: AnyObject?) -> (), error: (error: RequestError) -> ()) } class MockAccountProfile: AccountProfile { private let name: String = "mockaccount" init() { } func localName() -> String { return name } var accountName: String { get { return "[email protected]" } } lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> = { // Eventually this will be a SyncingBookmarksModel or an OfflineBookmarksModel, perhaps. return MockMemoryBookmarksStore() } () lazy var favicons: Favicons = { return BasicFavicons() } () lazy var clients: Clients = { return MockClients(profile: self) } () lazy var prefs: ProfilePrefs = { return MockProfilePrefs() } () func basicAuthorizationHeader() -> String { return "" } func makeAuthRequest(request: String, success: (data: AnyObject?) -> (), error: (error: RequestError) -> ()) { } func logout() { } } public class RESTAccountProfile: AccountProfile { private let name: String let credential: NSURLCredential private let logoutCallback: LogoutCallback init(localName: String, credential: NSURLCredential, logoutCallback: LogoutCallback) { self.name = localName self.credential = credential self.logoutCallback = logoutCallback } func localName() -> String { return name } var accountName: String { get { return credential.user! } } func basicAuthorizationHeader() -> String { let userPasswordString = "\(credential.user!):\(credential.password!)" let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding) let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions(nil) return "Basic \(base64EncodedCredential)" } func makeAuthRequest(request: String, success: (data: AnyObject?) -> (), error: (error: RequestError) -> ()) { RestAPI.sendRequest( credential, request: request, success: success, error: { err in if err == .BadAuth { self.logout() } error(error: err) }) } func logout() { logoutCallback(profile: self) } lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> = { // Stubbed out to populate data from server. // Eventually this will be a SyncingBookmarksModel or an OfflineBookmarksModel, perhaps. return BookmarksRESTModelFactory(profile: self) } () lazy var clients: Clients = { return RESTClients(profile: self) } () // lazy var ReadingList readingList // lazy var History lazy var favicons: Favicons = { return BasicFavicons() }() func makePrefs() -> ProfilePrefs { return NSUserDefaultsProfilePrefs(profile: self) } lazy var prefs: ProfilePrefs = { self.makePrefs() }() }
969308dae278fcf63dd9746cfc47cf25
27.52027
131
0.635868
false
false
false
false
EvsenevDev/SmartReceiptsiOS
refs/heads/master
SmartReceipts/Services/Local/QuickActionService.swift
agpl-3.0
2
// // QuickActionService.swift // SmartReceipts // // Created by Bogdan Evsenev on 26/12/2018. // Copyright © 2018 Will Baumann. All rights reserved. // import RxSwift enum QuickAction: String { case camera case text case `import` } class QuickActionService { private let bag = DisposeBag() private var subscription: Disposable? private weak var view: UIViewController! private let scanService = ScanService() init(view: UIViewController) { self.view = view } func configureQuickActions() { UIApplication.shared.shortcutItems = WBPreferences.lastOpenedTrip == nil ? [] : [.init(action: .camera), .init(action: .text), .init(action: .import)] } func performAction(action: QuickAction) { if WBPreferences.lastOpenedTrip == nil { return } switch action { case .camera: openCreatePhotoReceipt() case .text: openCreateTextReceipt() case .import: openImportReceiptFile() } } private func openCreatePhotoReceipt() { var hud: PendingHUDView? subscription = ImagePicker.shared.presentCamera(on: view) .flatMap({ [unowned self] img -> Single<ScanResult> in hud = PendingHUDView.showFullScreen(text: ScanStatus.uploading.localizedText) hud?.observe(status: self.scanService.status) return self.scanService.scan(image: img) }).subscribe(onSuccess: { [unowned self] scan in hud?.hide() self.openEditModule(with: scan) }) } private func openImportReceiptFile() { var hud: PendingHUDView? ReceiptFilePicker.sharedInstance.openFilePicker(on: view) .do(onError: { [unowned self] error in Logger.error("Import failed with: \(error.localizedDescription)") let alert = UIAlertController(title: nil, message: error.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: LocalizedString("generic_button_title_ok"), style: .cancel, handler: nil)) self.view.present(alert, animated: true, completion: nil) }).subscribe(onNext: { [unowned self] doc in hud = PendingHUDView.showFullScreen(text: ScanStatus.uploading.localizedText) hud?.observe(status: self.scanService.status) self.subscription = self.scanService.scan(document: doc) .subscribe(onSuccess: { [unowned self] scan in hud?.hide() self.openEditModule(with: scan) }) }, onError: { [unowned self] _ in self.openCreateTextReceipt() }).disposed(by: bag) } private func openCreateTextReceipt() { let receipt: WBReceipt? = nil let data = (trip: WBPreferences.lastOpenedTrip, receipt: receipt) openEditModuleWith(data: data) } private func openEditModuleWith(data: Any?) { subscription?.dispose() subscription = nil let module = AppModules.editReceipt.build() module.router.show(from: view, embedInNavController: true, setupData: data) } private func openEditModule(with scan: ScanResult) { let data = (trip: WBPreferences.lastOpenedTrip, scan: scan) openEditModuleWith(data: data) } } fileprivate extension UIApplicationShortcutItem { convenience init(action: QuickAction) { switch action { case .camera: self.init(type: action.rawValue, title: LocalizedString("receipt_action_camera"), icon: "camera") case .text: self.init(type: action.rawValue, title: LocalizedString("receipt_action_text"), icon: "file-text") case .import: self.init(type: action.rawValue, title: LocalizedString("receipt_action_import"), icon: "file-plus") } } convenience init(type: String, title: String, icon: String) { let icon = UIApplicationShortcutIcon(templateImageName: icon) self.init(type: type, localizedTitle: title, localizedSubtitle: nil, icon: icon, userInfo: nil) } }
9ac078d41a00528ffd55db00a8d9a50d
37.623853
127
0.627316
false
false
false
false
marsal-silveira/iStackOS
refs/heads/master
iStackOS/src/Model/Answer.swift
mit
1
// // Answer.swift // iStackOS // // Created by Marsal on 15/03/16. // Copyright © 2016 Marsal Silveira. All rights reserved. // import Foundation import Gloss public struct Answer: Decodable { // ****************************** // // MARK: Properties // ****************************** // private var _id: Int public var id: Int { return _id } private var _questionID: Int public var questionID: Int { return _questionID } private var _isAccepted: Bool public var isAccepted: Bool { return _isAccepted } private var _score: Int var score: Int { return _score } private var _creationDate: NSDate var creationDate: NSDate { return _creationDate } private var _lastActivityDate: NSDate var lastActivityDate: NSDate { return _lastActivityDate } private var _body: String var body: String { return _body } private var _owner: User var owner: User { return _owner } // ****************************** // // MARK: Init // ****************************** // public init?(json: JSON) { guard let id: Int = "answer_id" <~~ json, let questionID: Int = "question_id" <~~ json, let isAccepted: Int = "is_accepted" <~~ json, let score: Int = "score" <~~ json, let creationDateTimeInterval: NSTimeInterval = "creation_date" <~~ json, let lastActivityDateTimeInterval: NSTimeInterval = "last_activity_date" <~~ json, let body: String = "body" <~~ json, let owner: User = "owner" <~~ json else { return nil } _id = id _questionID = questionID _isAccepted = isAccepted.toBoolean()! _score = score _creationDate = NSDate(timeIntervalSince1970: creationDateTimeInterval) _lastActivityDate = NSDate(timeIntervalSince1970: lastActivityDateTimeInterval) _body = body _owner = owner } }
a15b813151b58fb66d0b7b3421c57429
23.776471
93
0.526841
false
false
false
false
djwbrown/swift
refs/heads/master
stdlib/public/core/StringIndex.swift
apache-2.0
1
//===--- StringIndex.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension String { /// A position of a character or code unit in a string. public struct Index { internal var _compoundOffset : UInt64 @_versioned internal var _cache: _Cache internal typealias _UTF8Buffer = _ValidUTF8Buffer<UInt64> @_versioned internal enum _Cache { case utf16 case utf8(buffer: _UTF8Buffer) case character(stride: UInt16) case unicodeScalar(value: Unicode.Scalar) } } } /// Convenience accessors extension String.Index._Cache { var utf16: Void? { if case .utf16 = self { return () } else { return nil } } var utf8: String.Index._UTF8Buffer? { if case .utf8(let r) = self { return r } else { return nil } } var character: UInt16? { if case .character(let r) = self { return r } else { return nil } } var unicodeScalar: UnicodeScalar? { if case .unicodeScalar(let r) = self { return r } else { return nil } } } extension String.Index : Equatable { public static func == (lhs: String.Index, rhs: String.Index) -> Bool { return lhs._compoundOffset == rhs._compoundOffset } } extension String.Index : Comparable { public static func < (lhs: String.Index, rhs: String.Index) -> Bool { return lhs._compoundOffset < rhs._compoundOffset } } extension String.Index { internal typealias _Self = String.Index /// Creates a new index at the specified UTF-16 offset. /// /// - Parameter offset: An offset in UTF-16 code units. public init(encodedOffset offset: Int) { _compoundOffset = UInt64(offset << _Self._strideBits) _cache = .utf16 } @_versioned internal init(encodedOffset o: Int, transcodedOffset: Int = 0, _ c: _Cache) { _compoundOffset = UInt64(o << _Self._strideBits | transcodedOffset) _cache = c } internal static var _strideBits : Int { return 2 } internal static var _mask : UInt64 { return (1 &<< _Self._strideBits) &- 1 } internal mutating func _setEncodedOffset(_ x: Int) { _compoundOffset = UInt64(x << _Self._strideBits) } /// The offset into a string's UTF-16 encoding for this index. public var encodedOffset : Int { return Int(_compoundOffset >> numericCast(_Self._strideBits)) } /// The offset of this index within whatever encoding this is being viewed as @_versioned internal var _transcodedOffset : Int { get { return Int(_compoundOffset & _Self._mask) } set { let extended = UInt64(newValue) _sanityCheck(extended <= _Self._mask) _compoundOffset &= ~_Self._mask _compoundOffset |= extended } } } // SPI for Foundation extension String.Index { @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public // SPI(Foundation) init(_position: Int) { self.init(encodedOffset: _position) } @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public // SPI(Foundation) init(_offset: Int) { self.init(encodedOffset: _offset) } @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public // SPI(Foundation) init(_base: String.Index, in c: String.CharacterView) { self = _base } /// The integer offset of this index in UTF-16 code units. @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public // SPI(Foundation) var _utf16Index: Int { return self.encodedOffset } /// The integer offset of this index in UTF-16 code units. @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public // SPI(Foundation) var _offset: Int { return self.encodedOffset } } // backward compatibility for index interchange. extension Optional where Wrapped == String.Index { @available( swift, obsoleted: 4.0, message: "Any String view index conversion can fail in Swift 4; please unwrap the optional indices") public static func ..<( lhs: String.Index?, rhs: String.Index? ) -> Range<String.Index> { return lhs! ..< rhs! } @available( swift, obsoleted: 4.0, message: "Any String view index conversion can fail in Swift 4; please unwrap the optional indices") public static func ...( lhs: String.Index?, rhs: String.Index? ) -> ClosedRange<String.Index> { return lhs! ... rhs! } }
ceaafc1b96af30b92ded52e36b72ed7e
28.382716
104
0.646639
false
false
false
false
gobetti/Swift
refs/heads/master
Airdrop/Airdrop/URLViewController.swift
mit
1
// // URLViewController.swift // Airdrop // // Created by Carlos Butron on 07/12/14. // Copyright (c) 2014 Carlos Butron. // import UIKit class URLViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var myURL: UITextField! @IBOutlet weak var webView: UIWebView! @IBAction func send(sender: UIButton) { let url:NSURL = NSURL(string: myURL.text!)! let controller = UIActivityViewController(activityItems: [url], applicationActivities: nil) self.presentViewController(controller, animated: true, completion: nil) } @IBAction func load(sender: UIButton) { let request = NSURLRequest(URL: NSURL(string: myURL.text!)!) self.webView.loadRequest(request) } override func viewDidLoad() { super.viewDidLoad() myURL.text = "http://carlosbutron.es/" webView.delegate = self let request = NSURLRequest(URL: NSURL(string: myURL.text!)!) self.webView.loadRequest(request) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
6f0915d00066402b1f733eb62e12d5bf
28.071429
106
0.660934
false
false
false
false
OneBusAway/onebusaway-iphone
refs/heads/develop
Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/ViewControllers/DiffTableViewController.swift
apache-2.0
2
/** Copyright (c) Facebook, Inc. and its affiliates. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import IGListKit import UIKit final class Person: ListDiffable { let pk: Int let name: String init(pk: Int, name: String) { self.pk = pk self.name = name } func diffIdentifier() -> NSObjectProtocol { return pk as NSNumber } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { guard let object = object as? Person else { return false } return self.name == object.name } } final class DiffTableViewController: UITableViewController { let oldPeople = [ Person(pk: 1, name: "Kevin"), Person(pk: 2, name: "Mike"), Person(pk: 3, name: "Ann"), Person(pk: 4, name: "Jane"), Person(pk: 5, name: "Philip"), Person(pk: 6, name: "Mona"), Person(pk: 7, name: "Tami"), Person(pk: 8, name: "Jesse"), Person(pk: 9, name: "Jaed") ] let newPeople = [ Person(pk: 2, name: "Mike"), Person(pk: 10, name: "Marne"), Person(pk: 5, name: "Philip"), Person(pk: 1, name: "Kevin"), Person(pk: 3, name: "Ryan"), Person(pk: 8, name: "Jesse"), Person(pk: 7, name: "Tami"), Person(pk: 4, name: "Jane"), Person(pk: 9, name: "Chen") ] lazy var people: [Person] = { return self.oldPeople }() var usingOldPeople = true override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .play, target: self, action: #selector(DiffTableViewController.onDiff)) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } @objc func onDiff() { let from = people let to = usingOldPeople ? newPeople : oldPeople usingOldPeople = !usingOldPeople people = to let result = ListDiffPaths(fromSection: 0, toSection: 0, oldArray: from, newArray: to, option: .equality).forBatchUpdates() tableView.beginUpdates() tableView.deleteRows(at: result.deletes, with: .fade) tableView.insertRows(at: result.inserts, with: .fade) result.moves.forEach { tableView.moveRow(at: $0.from, to: $0.to) } tableView.endUpdates() } // MARK: UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return people.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = people[indexPath.row].name return cell } }
0a4bd6c11181ec50e462257bd4b2face
32.592233
131
0.622254
false
false
false
false