repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
xmartlabs/Swift-Project-Template
|
refs/heads/master
|
Project-iOS/XLProjectName/XLProjectName/Helpers/Extensions/AppDelegate+XLProjectName.swift
|
mit
|
1
|
//
// AppDelegate+XLProjectName.swift
// XLProjectName
//
// Created by XLAuthorName ( XLAuthorWebsite )
// Copyright © 2016 'XLOrganizationName'. All rights reserved.
//
import Foundation
import Fabric
import Alamofire
import Eureka
import Crashlytics
extension AppDelegate {
func setupCrashlytics() {
Fabric.with([Crashlytics.self])
Fabric.sharedSDK().debug = Constants.Debug.crashlytics
}
// MARK: Alamofire notifications
func setupNetworking() {
NotificationCenter.default.addObserver(
self,
selector: #selector(AppDelegate.requestDidComplete(_:)),
name: Alamofire.Request.didCompleteTaskNotification,
object: nil)
}
@objc func requestDidComplete(_ notification: Notification) {
guard let request = notification.request, let response = request.response else {
DEBUGLog("Request object not a task")
return
}
if Constants.Network.successRange ~= response.statusCode {
if let token = response.allHeaderFields["Set-Cookie"] as? String {
SessionController.sharedInstance.token = token
}
} else if response.statusCode == Constants.Network.Unauthorized && SessionController.sharedInstance.isLoggedIn() {
SessionController.sharedInstance.clearSession()
// here you should implement AutoLogout: Transition to login screen and show an appropiate message
}
}
/**
Set up your Eureka default row customization here
*/
func stylizeEurekaRows() {
let genericHorizontalMargin = CGFloat(50)
BaseRow.estimatedRowHeight = 58
EmailRow.defaultRowInitializer = {
$0.placeholder = NSLocalizedString("E-mail Address", comment: "")
$0.placeholderColor = .gray
}
EmailRow.defaultCellSetup = { cell, _ in
cell.layoutMargins = .zero
cell.contentView.layoutMargins.left = genericHorizontalMargin
cell.height = { 58 }
}
}
}
|
ffa4aac88ebd8b42b5cb08495807e54c
| 30.846154 | 122 | 0.647343 | false | false | false | false |
gregomni/swift
|
refs/heads/main
|
test/Sanitizers/tsan/racy_async_let_fibonacci.swift
|
apache-2.0
|
2
|
// RUN: %target-swiftc_driver %s -Xfrontend -disable-availability-checking -parse-as-library %import-libdispatch -target %sanitizers-target-triple -g -sanitize=thread -o %t
// RUN: %target-codesign %t
// RUN: env %env-TSAN_OPTIONS="abort_on_error=0" not %target-run %t 2>&1 | %swift-demangle --simplified | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// REQUIRES: tsan_runtime
// rdar://76038845
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
// rdar://75365575 (Failing to start atos external symbolizer)
// UNSUPPORTED: OS=watchos
// rdar://86825277
// SR-15805
// UNSUPPORTED: CPU=arm64 || CPU=arm64e
// Disabled because this test is flaky rdar://76542113
// REQUIRES: rdar76542113
func fib(_ n: Int) -> Int {
var first = 0
var second = 1
for _ in 0..<n {
let temp = first
first = second
second = temp + first
}
return first
}
var racyCounter = 0
@available(SwiftStdlib 5.1, *)
func asyncFib(_ n: Int) async -> Int {
racyCounter += 1
if n == 0 || n == 1 {
return n
}
async let first = await asyncFib(n-2)
async let second = await asyncFib(n-1)
// Sleep a random amount of time waiting on the result producing a result.
await Task.sleep(UInt64.random(in: 0..<100) * 1_000_000)
let result = await first + second
// Sleep a random amount of time before producing a result.
await Task.sleep(UInt64.random(in: 0..<100) * 1_000_000)
return result
}
@available(SwiftStdlib 5.1, *)
func runFibonacci(_ n: Int) async {
let result = await asyncFib(n)
print()
print("Async fib = \(result), sequential fib = \(fib(n))")
assert(result == fib(n))
}
@available(SwiftStdlib 5.1, *)
@main struct Main {
static func main() async {
await runFibonacci(10)
}
}
// CHECK: ThreadSanitizer: Swift access race
// CHECK: Location is global 'racyCounter'
|
f5a632d393bffd0fba8ea202e363d18f
| 24.16 | 172 | 0.677266 | false | false | false | false |
terflogag/GBHFacebookImagePicker
|
refs/heads/master
|
GBHFacebookImagePicker/Classes/Utils/UICollectionView+Extensions.swift
|
mit
|
1
|
//
// UICollectionView+Extensions.swift
// Bolts
//
// Created by Florian Gabach on 11/05/2018.
//
import UIKit
extension UICollectionView {
func selectAllCell(toPosition position: UICollectionView.ScrollPosition = []) {
for section in 0..<self.numberOfSections {
for item in 0..<self.numberOfItems(inSection: section) {
let index = IndexPath(row: item, section: section)
self.selectItem(at: index, animated: false, scrollPosition: position)
}
}
}
func register<T: UICollectionViewCell>(cellType: T.Type)
where T: Reusable {
self.register(cellType.self, forCellWithReuseIdentifier: cellType.reuseIdentifier)
}
func dequeueReusableCell<T: UICollectionViewCell>(for indexPath: IndexPath, cellType: T.Type = T.self) -> T
where T: Reusable {
let bareCell = self.dequeueReusableCell(withReuseIdentifier: cellType.reuseIdentifier, for: indexPath)
guard let cell = bareCell as? T else {
fatalError(
"Failed to dequeue a cell with identifier \(cellType.reuseIdentifier) matching type \(cellType.self). "
+ "Check that the reuseIdentifier is set properly in your XIB/Storyboard "
+ "and that you registered the cell beforehand"
)
}
return cell
}
}
|
cdad696e8f8ad907d6e20bd142d96aee
| 36.447368 | 123 | 0.619817 | false | false | false | false |
jeffreybergier/Hipstapaper
|
refs/heads/main
|
Hipstapaper/Packages/V3Errors/Sources/V3Errors/Errors/DeleteError+CodableError.swift
|
mit
|
1
|
//
// Created by Jeffrey Bergier on 2022/06/29.
//
// MIT License
//
// Copyright (c) 2021 Jeffrey Bergier
//
// 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 Umbrella
import V3Model
// MARK: DeleteTagError
extension DeleteTagError {
internal init?(_ error: CodableError, onConfirm: OnConfirmation?) {
guard
error.errorDomain == type(of: self).errorDomain,
error.errorCode == self.errorCode,
let data = error.arbitraryData,
let identifiers = try? PropertyListDecoder().decode(Tag.Selection.self, from: data)
else { return nil }
self.identifiers = identifiers
self.onConfirm = onConfirm
}
public var codableValue: CodableError {
var error = CodableError(self)
error.arbitraryData = try? PropertyListEncoder().encode(self.identifiers)
return error
}
}
// MARK: DeleteWebsiteError
extension DeleteWebsiteError {
internal init?(_ error: CodableError, onConfirm: OnConfirmation?) {
guard
error.errorDomain == type(of: self).errorDomain,
error.errorCode == self.errorCode,
let data = error.arbitraryData,
let identifiers = try? PropertyListDecoder().decode(Website.Selection.self, from: data)
else { return nil }
self.identifiers = identifiers
self.onConfirm = onConfirm
}
public var codableValue: CodableError {
var error = CodableError(self)
error.arbitraryData = try? PropertyListEncoder().encode(self.identifiers)
return error
}
}
|
7b0ccafb73de6a3668ef4039d5b27ba6
| 36.366197 | 99 | 0.692801 | false | false | false | false |
kingka/SwiftWeiBo
|
refs/heads/master
|
SwiftWeiBo/SwiftWeiBo/Classes/Main/BaseViewController.swift
|
mit
|
1
|
//
// BaseViewController.swift
// SwiftWeiBo
//
// Created by Imanol on 16/1/13.
// Copyright © 2016年 imanol. All rights reserved.
//
import UIKit
class BaseViewController: UITableViewController ,VisitViewDelegate{
let isLogin:Bool = UserAccount.userLogin()
var visitView:VisitView?
override func loadView() {
isLogin ? super.loadView() : setupCustomView()
}
func setupCustomView(){
//初始化visitView
visitView = VisitView()
visitView?.delegate = self
view = visitView
// 添加 导航按钮
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "registerDidClick")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: "loginDidClick")
}
func registerDidClick() {
print(__FUNCTION__)
print(UserAccount.loadAccount())
}
func loginDidClick() {
print(__FUNCTION__)
let oauthVC = OAuthViewController()
let nav = UINavigationController(rootViewController: oauthVC)
presentViewController(nav, animated: true) { () -> Void in
}
}
}
|
ec72dc28349f7de0342efa1bd0143767
| 26.282609 | 148 | 0.641434 | false | false | false | false |
JGiola/swift
|
refs/heads/main
|
test/Generics/rdar80503090.swift
|
apache-2.0
|
6
|
// RUN: %target-typecheck-verify-swift
// RUN: %target-swift-frontend -typecheck -debug-generic-signatures %s 2>&1 | %FileCheck %s
// RUN: %target-swift-frontend -typecheck -debug-generic-signatures %s -disable-requirement-machine-concrete-contraction 2>&1 | %FileCheck %s
protocol P {
associatedtype T where T == Self
}
protocol Q : P {}
extension P {
func missing() {}
}
extension P where T : Q {
// CHECK-LABEL: Generic signature: <Self where Self : Q>
func test() {
missing()
}
}
class C : P {}
// expected-warning@-1 {{non-final class 'C' cannot safely conform to protocol 'P', which requires that 'Self.T' is exactly equal to 'Self'; this is an error in Swift 6}}
extension P where T : C {
// CHECK-LABEL: Generic signature: <Self where Self : C>
func test() {
missing()
}
}
struct S : P {}
extension P where T == S {
// CHECK-LABEL: Generic signature: <Self where Self == S>
func test() {
missing()
}
}
|
403b7c9a25a251c955746dbaad9fc463
| 23.410256 | 170 | 0.656151 | false | true | false | false |
filipealva/WWDC15-Scholarship
|
refs/heads/master
|
Filipe Alvarenga/Model/Story.swift
|
mit
|
1
|
//
// Story.swift
// Filipe Alvarenga
//
// Created by Filipe Alvarenga on 19/04/15.
// Copyright (c) 2015 Filipe Alvarenga. All rights reserved.
//
import Foundation
/**
Story model class.
- parameter title: The story title.
- parameter description: The story description.
*/
class Story {
var title: String!
var description: String!
var date: String!
init(dict: [String: AnyObject]) {
self.title = dict["title"] as? String ?? "No title"
self.description = dict["description"] as? String ?? "No description"
if let date = dict["date"] as? String {
self.date = date
} else {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM yyyy"
self.date = dateFormatter.stringFromDate(NSDate()).capitalizedString
}
}
}
|
2c44f764f9aa08c0e991c1927d610910
| 22.891892 | 80 | 0.594564 | false | false | false | false |
materik/iapcontroller
|
refs/heads/master
|
Swift/IAPController.swift
|
mit
|
1
|
//
// IAPController.swift
// XWorkout
//
// Created by materik on 19/07/15.
// Copyright (c) 2015 materik. All rights reserved.
//
import Foundation
import StoreKit
public let IAPControllerFetchedNotification = "IAPControllerFetchedNotification"
public let IAPControllerPurchasedNotification = "IAPControllerPurchasedNotification"
public let IAPControllerFailedNotification = "IAPControllerFailedNotification"
public let IAPControllerRestoredNotification = "IAPControllerRestoredNotification"
open class IAPController: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver {
// MARK: Properties
open var products: [SKProduct]?
var productIds: [String] = []
// MARK: Singleton
open static var sharedInstance: IAPController = {
return IAPController()
}()
// MARK: Init
public override init() {
super.init()
self.retrieveProductIdsFromPlist()
SKPaymentQueue.default().add(self)
}
private func retrieveProductIdsFromPlist() {
let url = Bundle.main.url(forResource: "IAPControllerProductIds", withExtension: "plist")!
self.productIds = NSArray(contentsOf: url) as! [String]
}
// MARK: Action
open func fetchProducts() {
let request = SKProductsRequest(productIdentifiers: Set(self.productIds))
request.delegate = self
request.start()
}
open func restore() {
SKPaymentQueue.default().restoreCompletedTransactions()
}
// MARK: SKPaymentTransactionObserver
open func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
self.products = response.products
NotificationCenter.default.post(name: Notification.Name(rawValue: IAPControllerFetchedNotification), object: nil)
}
open func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch transaction.transactionState {
case .purchased:
self.purchasedTransaction(transaction: transaction)
break
case .failed:
self.failedTransaction(transaction: transaction)
break
case .restored:
self.restoreTransaction(transaction: transaction)
break
default:
break
}
}
}
open func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
self.failedTransaction(transaction: nil, error: error)
}
open func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
NotificationCenter.default.post(name: Notification.Name(rawValue: IAPControllerRestoredNotification), object: nil)
}
// MARK: Transaction
func finishTransaction(transaction: SKPaymentTransaction? = nil) {
if let transaction = transaction {
SKPaymentQueue.default().finishTransaction(transaction)
}
}
func restoreTransaction(transaction: SKPaymentTransaction? = nil) {
self.finishTransaction(transaction: transaction)
NotificationCenter.default.post(name: Notification.Name(rawValue: IAPControllerPurchasedNotification), object: nil)
}
func failedTransaction(transaction: SKPaymentTransaction? = nil, error: Error? = nil) {
self.finishTransaction(transaction: transaction)
if let error = error ?? transaction?.error {
if error._code != SKError.paymentCancelled.rawValue {
NotificationCenter.default.post(name: Notification.Name(rawValue: IAPControllerFailedNotification), object: error)
}
}
}
func purchasedTransaction(transaction: SKPaymentTransaction? = nil) {
self.finishTransaction(transaction: transaction)
NotificationCenter.default.post(name: Notification.Name(rawValue: IAPControllerPurchasedNotification), object: nil)
}
}
|
0a81cee5dfcaa73190b4830f20b90d4c
| 34.258621 | 130 | 0.681174 | false | false | false | false |
Mqhong/IMSingularity_Swift
|
refs/heads/master
|
Example/Pods/SwiftR/SwiftR/SwiftR.swift
|
mit
|
1
|
//
// SwiftR.swift
// SwiftR
//
// Created by Adam Hartford on 4/13/15.
// Copyright (c) 2015 Adam Hartford. All rights reserved.
//
import Foundation
import WebKit
public enum ConnectionType {
case Hub
case Persistent
}
public enum State {
case Connecting
case Connected
case Disconnected
}
public enum Transport {
case Auto
case WebSockets
case ForeverFrame
case ServerSentEvents
case LongPolling
var stringValue: String {
switch self {
case .WebSockets:
return "webSockets"
case .ForeverFrame:
return "foreverFrame"
case .ServerSentEvents:
return "serverSentEvents"
case .LongPolling:
return "longPolling"
default:
return "auto"
}
}
}
public final class SwiftR: NSObject {
static var connections = [SignalR]()
public static var signalRVersion: SignalRVersion = .v2_2_0
public static var useWKWebView = false
public static var transport: Transport = .Auto
public class func connect(url: String, connectionType: ConnectionType = .Hub, readyHandler: SignalR -> ()) -> SignalR? {
let signalR = SignalR(baseUrl: url, connectionType: connectionType, readyHandler: readyHandler)
connections.append(signalR)
return signalR
}
public class func startAll() {
checkConnections()
for connection in connections {
connection.start()
}
}
public class func stopAll() {
checkConnections()
for connection in connections {
connection.stop()
}
}
#if os(iOS)
public class func cleanup() {
let temp = NSURL(fileURLWithPath: NSTemporaryDirectory())
let jqueryTempURL = temp.URLByAppendingPathComponent("jquery-2.1.3.min.js")
let signalRTempURL = temp.URLByAppendingPathComponent("jquery.signalR-\(signalRVersion).min")
let jsTempURL = temp.URLByAppendingPathComponent("SwiftR.js")
let fileManager = NSFileManager.defaultManager()
do {
if let path = jqueryTempURL.path where fileManager.fileExistsAtPath(path) {
try fileManager.removeItemAtURL(jqueryTempURL)
}
if let path = signalRTempURL.path where fileManager.fileExistsAtPath(path) {
try fileManager.removeItemAtURL(signalRTempURL)
}
if let path = jsTempURL.path where fileManager.fileExistsAtPath(path) {
try fileManager.removeItemAtURL(jsTempURL)
}
} catch {
print("Failed to remove temp JavaScript")
}
}
#endif
class func checkConnections() {
if connections.count == 0 {
print("No active SignalR connections. Use SwiftR.connect(...) first.")
}
}
}
public class SignalR: NSObject, SwiftRWebDelegate {
var webView: SwiftRWebView!
var wkWebView: WKWebView!
var baseUrl: String
var connectionType: ConnectionType
var readyHandler: SignalR -> ()
var hubs = [String: Hub]()
public var state: State = .Disconnected
public var connectionID: String?
public var received: (AnyObject? -> ())?
public var starting: (() -> ())?
public var connected: (() -> ())?
public var disconnected: (() -> ())?
public var connectionSlow: (() -> ())?
public var connectionFailed: (() -> ())?
public var reconnecting: (() -> ())?
public var reconnected: (() -> ())?
public var error: (AnyObject? -> ())?
public var queryString: AnyObject? {
didSet {
if let qs: AnyObject = queryString {
if let jsonData = try? NSJSONSerialization.dataWithJSONObject(qs, options: NSJSONWritingOptions()) {
let json = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
runJavaScript("swiftR.connection.qs = \(json)")
}
} else {
runJavaScript("swiftR.connection.qs = {}")
}
}
}
public var headers: [String: String]? {
didSet {
if let h = headers {
if let jsonData = try? NSJSONSerialization.dataWithJSONObject(h, options: NSJSONWritingOptions()) {
let json = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
runJavaScript("swiftR.headers = \(json)")
}
} else {
runJavaScript("swiftR.headers = {}")
}
}
}
init(baseUrl: String, connectionType: ConnectionType = .Hub, readyHandler: SignalR -> ()) {
self.baseUrl = baseUrl
self.readyHandler = readyHandler
self.connectionType = connectionType
super.init()
#if COCOAPODS
let bundle = NSBundle(identifier: "org.cocoapods.SwiftR")!
#elseif SWIFTR_FRAMEWORK
let bundle = NSBundle(identifier: "com.adamhartford.SwiftR")!
#else
let bundle = NSBundle.mainBundle()
#endif
let jqueryURL = bundle.URLForResource("jquery-2.1.3.min", withExtension: "js")!
let signalRURL = bundle.URLForResource("jquery.signalR-\(SwiftR.signalRVersion).min", withExtension: "js")!
let jsURL = bundle.URLForResource("SwiftR", withExtension: "js")!
if SwiftR.useWKWebView {
var jqueryInclude = "<script src='\(jqueryURL.absoluteString)'></script>"
var signalRInclude = "<script src='\(signalRURL.absoluteString)'></script>"
var jsInclude = "<script src='\(jsURL.absoluteString)'></script>"
// Loading file:// URLs from NSTemporaryDirectory() works on iOS, not OS X.
// Workaround on OS X is to include the script directly.
#if os(iOS)
if !NSProcessInfo().isOperatingSystemAtLeastVersion(NSOperatingSystemVersion(majorVersion: 9, minorVersion: 0, patchVersion: 0)) {
let temp = NSURL(fileURLWithPath: NSTemporaryDirectory())
let jqueryTempURL = temp.URLByAppendingPathComponent("jquery-2.1.3.min.js")
let signalRTempURL = temp.URLByAppendingPathComponent("jquery.signalR-\(SwiftR.signalRVersion).min")
let jsTempURL = temp.URLByAppendingPathComponent("SwiftR.js")
let fileManager = NSFileManager.defaultManager()
do {
if fileManager.fileExistsAtPath(jqueryTempURL.path!) {
try fileManager.removeItemAtURL(jqueryTempURL)
}
if fileManager.fileExistsAtPath(signalRTempURL.path!) {
try fileManager.removeItemAtURL(signalRTempURL)
}
if fileManager.fileExistsAtPath(jsTempURL.path!) {
try fileManager.removeItemAtURL(jsTempURL)
}
} catch {
print("Failed to remove existing temp JavaScript")
}
do {
try fileManager.copyItemAtURL(jqueryURL, toURL: jqueryTempURL)
try fileManager.copyItemAtURL(signalRURL, toURL: signalRTempURL)
try fileManager.copyItemAtURL(jsURL, toURL: jsTempURL)
} catch {
print("Failed to copy JavaScript to temp dir")
}
jqueryInclude = "<script src='\(jqueryTempURL.absoluteString)'></script>"
signalRInclude = "<script src='\(signalRTempURL.absoluteString)'></script>"
jsInclude = "<script src='\(jsTempURL.absoluteString)'></script>"
}
#else
let jqueryString = try! NSString(contentsOfURL: jqueryURL, encoding: NSUTF8StringEncoding)
let signalRString = try! NSString(contentsOfURL: signalRURL, encoding: NSUTF8StringEncoding)
let jsString = try! NSString(contentsOfURL: jsURL, encoding: NSUTF8StringEncoding)
jqueryInclude = "<script>\(jqueryString)</script>"
signalRInclude = "<script>\(signalRString)</script>"
jsInclude = "<script>\(jsString)</script>"
#endif
let config = WKWebViewConfiguration()
config.userContentController.addScriptMessageHandler(self, name: "interOp")
#if !os(iOS)
//config.preferences.setValue(true, forKey: "developerExtrasEnabled")
#endif
wkWebView = WKWebView(frame: CGRectZero, configuration: config)
wkWebView.navigationDelegate = self
let html = "<!doctype html><html><head></head><body>"
+ "\(jqueryInclude)\(signalRInclude)\(jsInclude)"
+ "</body></html>"
wkWebView.loadHTMLString(html, baseURL: bundle.bundleURL)
return
} else {
let jqueryInclude = "<script src='\(jqueryURL.absoluteString)'></script>"
let signalRInclude = "<script src='\(signalRURL.absoluteString)'></script>"
let jsInclude = "<script src='\(jsURL.absoluteString)'></script>"
let html = "<!doctype html><html><head></head><body>"
+ "\(jqueryInclude)\(signalRInclude)\(jsInclude)"
+ "</body></html>"
webView = SwiftRWebView()
#if os(iOS)
webView.delegate = self
webView.loadHTMLString(html, baseURL: bundle.bundleURL)
#else
webView.policyDelegate = self
webView.mainFrame.loadHTMLString(html, baseURL: bundle.bundleURL)
#endif
}
}
deinit {
if let view = wkWebView {
view.removeFromSuperview()
}
}
public func createHubProxy(name: String) -> Hub {
let hub = Hub(name: name, connection: self)
hubs[name.lowercaseString] = hub
return hub
}
public func send(data: AnyObject?) {
var json = "null"
if let d: AnyObject = data {
if d is String {
json = "'\(d)'"
} else if d is NSNumber {
json = "\(d)"
} else if let jsonData = try? NSJSONSerialization.dataWithJSONObject(d, options: NSJSONWritingOptions()) {
json = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String
}
}
runJavaScript("swiftR.connection.send(\(json))")
}
public func start() {
runJavaScript("start()")
}
public func stop() {
runJavaScript("swiftR.connection.stop()")
}
func shouldHandleRequest(request: NSURLRequest) -> Bool {
if request.URL!.absoluteString.hasPrefix("swiftr://") {
let id = (request.URL!.absoluteString as NSString).substringFromIndex(9)
let msg = webView.stringByEvaluatingJavaScriptFromString("readMessage('\(id)')")!
let data = msg.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let json: AnyObject = try! NSJSONSerialization.JSONObjectWithData(data, options: [])
processMessage(json)
return false
}
return true
}
func processMessage(json: AnyObject) {
if let message = json["message"] as? String {
switch message {
case "ready":
let isHub = connectionType == .Hub ? "true" : "false"
runJavaScript("swiftR.transport = '\(SwiftR.transport.stringValue)'")
runJavaScript("initialize('\(baseUrl)', \(isHub))")
readyHandler(self)
runJavaScript("start()")
case "starting":
state = .Connecting
starting?()
case "connected":
state = .Connected
connectionID = json["connectionId"] as? String
connected?()
case "disconnected":
state = .Disconnected
disconnected?()
case "connectionSlow":
connectionSlow?()
case "connectionFailed":
connectionFailed?()
case "reconnecting":
state = .Connecting
reconnecting?()
case "reconnected":
state = .Connected
reconnected?()
case "invokeHandler":
let hubName = json["hub"] as! String
if let hub = hubs[hubName] {
let uuid = json["id"] as! String
let result = json["result"]
let error = json["error"]
if let callback = hub.invokeHandlers[uuid] {
callback(result: result, error: error)
hub.invokeHandlers.removeValueForKey(uuid)
}
}
case "error":
if let err: AnyObject = json["error"] {
error?(err)
} else {
error?(nil)
}
default:
break
}
} else if let data: AnyObject = json["data"] {
received?(data)
} else if let hubName = json["hub"] as? String {
let callbackID = json["id"] as? String
let method = json["method"] as? String
let arguments = json["arguments"] as? [AnyObject]
let hub = hubs[hubName]
if let method = method, callbackID = callbackID, handlers = hub?.handlers[method], handler = handlers[callbackID] {
handler(arguments)
}
}
}
func runJavaScript(script: String, callback: (AnyObject! -> ())? = nil) {
if SwiftR.useWKWebView {
wkWebView.evaluateJavaScript(script, completionHandler: { (result, _) in
callback?(result)
})
} else {
let result = webView.stringByEvaluatingJavaScriptFromString(script)
callback?(result)
}
}
// MARK: - WKNavigationDelegate
// http://stackoverflow.com/questions/26514090/wkwebview-does-not-run-javascriptxml-http-request-with-out-adding-a-parent-vie#answer-26575892
public func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
#if os(iOS)
UIApplication.sharedApplication().keyWindow?.addSubview(wkWebView)
#endif
}
// MARK: - WKScriptMessageHandler
public func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let id = message.body as? String {
wkWebView.evaluateJavaScript("readMessage('\(id)')", completionHandler: { [weak self] (msg, _) in
if let m = msg {
self?.processMessage(m)
}
})
}
}
// MARK: - Web delegate methods
#if os(iOS)
public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
return shouldHandleRequest(request)
}
#else
public func webView(webView: WebView!,
decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!,
request: NSURLRequest!,
frame: WebFrame!,
decisionListener listener: WebPolicyDecisionListener!) {
if shouldHandleRequest(request) {
listener.use()
}
}
#endif
}
// MARK: - Hub
public class Hub {
let name: String
var handlers: [String: [String: [AnyObject]? -> ()]] = [:]
var invokeHandlers: [String: (result: AnyObject?, error: AnyObject?) -> ()] = [:]
public let connection: SignalR!
init(name: String, connection: SignalR) {
self.name = name
self.connection = connection
}
public func on(method: String, callback: [AnyObject]? -> ()) {
let callbackID = NSUUID().UUIDString
if handlers[method] == nil {
handlers[method] = [:]
}
handlers[method]?[callbackID] = callback
connection.runJavaScript("addHandler('\(callbackID)', '\(name)', '\(method)')")
}
public func invoke(method: String, arguments: [AnyObject]?, callback: ((result: AnyObject?, error: AnyObject?) -> ())? = nil) {
var jsonArguments = [String]()
if let args = arguments {
for arg in args {
// Using an array to start with a valid top level type for NSJSONSerialization
let arr = [arg]
if let data = try? NSJSONSerialization.dataWithJSONObject(arr, options: NSJSONWritingOptions()) {
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
// Strip the array brackets to be left with the desired value
let range = str.startIndex.advancedBy(1) ..< str.endIndex.advancedBy(-1)
jsonArguments.append(str.substringWithRange(range))
}
}
}
}
let args = jsonArguments.joinWithSeparator(", ")
let uuid = NSUUID().UUIDString
if let handler = callback {
invokeHandlers[uuid] = handler
}
let doneJS = "function() { postMessage({ message: 'invokeHandler', hub: '\(name.lowercaseString)', id: '\(uuid)', result: arguments[0] }); }"
let failJS = "function() { postMessage({ message: 'invokeHandler', hub: '\(name.lowercaseString)', id: '\(uuid)', error: processError(arguments[0]) }); }"
let js = args.isEmpty
? "ensureHub('\(name)').invoke('\(method)').done(\(doneJS)).fail(\(failJS))"
: "ensureHub('\(name)').invoke('\(method)', \(args)).done(\(doneJS)).fail(\(failJS))"
connection.runJavaScript(js)
}
}
public enum SignalRVersion : CustomStringConvertible {
case v2_2_0
case v2_1_2
case v2_1_1
case v2_1_0
case v2_0_3
case v2_0_2
case v2_0_1
case v2_0_0
public var description: String {
switch self {
case .v2_2_0: return "2.2.0"
case .v2_1_2: return "2.1.2"
case .v2_1_1: return "2.1.1"
case .v2_1_0: return "2.1.0"
case .v2_0_3: return "2.0.3"
case .v2_0_2: return "2.0.2"
case .v2_0_1: return "2.0.1"
case .v2_0_0: return "2.0.0"
}
}
}
#if os(iOS)
typealias SwiftRWebView = UIWebView
public protocol SwiftRWebDelegate: WKNavigationDelegate, WKScriptMessageHandler, UIWebViewDelegate {}
#else
typealias SwiftRWebView = WebView
public protocol SwiftRWebDelegate: WKNavigationDelegate, WKScriptMessageHandler, WebPolicyDelegate {}
#endif
|
cc4dfbab9e6809bc01b59e271248ad2c
| 36.890838 | 162 | 0.554378 | false | false | false | false |
Ben21hao/edx-app-ios-new
|
refs/heads/master
|
Source/TDCourseCatalogDetailViewController/Views/TDCourseCatalogDetailView.swift
|
apache-2.0
|
1
|
//
// TDCourseCatalogDetailView.swift
// edX
//
// Created by Ben on 2017/5/3.
// Copyright © 2017年 edX. All rights reserved.
//
import UIKit
class TDCourseCatalogDetailView: UIView,UITableViewDataSource {
typealias Environment = protocol<OEXAnalyticsProvider, DataManagerProvider, NetworkManagerProvider, OEXRouterProvider>
private let environment : Environment
internal let tableView = UITableView()
internal let courseCardView = CourseCardView()
internal let playButton = UIButton()
internal var playButtonHandle : (() -> ())?
internal var submitButtonHandle : (() -> ())?
internal var showAllTextHandle : ((Bool) -> ())?
var showAllText = false
var submitTitle : String?
var courseModel = OEXCourse()
private var _loaded = Sink<()>()
var loaded : Stream<()> {
return _loaded
}
init(frame: CGRect, environment: Environment) {
self.environment = environment
super.init(frame: frame)
self.backgroundColor = OEXStyles.sharedStyles().baseColor5()
setViewConstraint()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: 加载课程详情信息函数
func applyCourse(course : OEXCourse) {
CourseCardViewModel.onCourseCatalog(course).apply(courseCardView, networkManager: self.environment.networkManager,type:1)//头部图片
self.playButton.hidden = course.intro_video_3rd_url!.isEmpty ?? true
self.courseModel = course
self.tableView.reloadData()
}
//MARK: 全文 - 收起
func moreButtonAction(sender: UIButton) {
self.showAllText = !self.showAllText
if (self.showAllTextHandle != nil) {
self.showAllTextHandle?(self.showAllText)
}
}
func submitButtonAction() { //提交
if (self.submitButtonHandle != nil) {
self.submitButtonHandle!()
}
}
func playButtonAction() {
if self.playButtonHandle != nil {
self.playButtonHandle?()
}
}
//MARK: tableview Delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 3
} else {
return 5
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
let cell = TDCourseIntroduceCell.init(style: .Default, reuseIdentifier: "TDCourseIntroduceCell")
cell.selectionStyle = .None
cell.moreButton.tag = 8
if self.showAllText == true {
cell.introduceLabel.text = "\(self.courseModel.short_description!)\n\(self.courseModel.moreDescription!)"
cell.moreButton.setTitle(Strings.stopUp, forState: .Normal)
} else {
cell.introduceLabel.text = self.courseModel.short_description
cell.moreButton.setTitle(Strings.allText, forState: .Normal)
}
cell.moreButton.addTarget(self, action: #selector(moreButtonAction(_:)), forControlEvents: .TouchUpInside)
if self.courseModel.moreDescription?.characters.count == 0 && self.courseModel.short_description?.characters.count == 0 {
cell.moreButton.hidden = true
}
return cell
} else if indexPath.row == 1 {
let cell = TDCourseMessageCell.init(style: .Default, reuseIdentifier: "TDCourseMessageCell")
cell.selectionStyle = .None
cell.timeLabel.text = self.courseModel.effort?.stringByAppendingString(Strings.studyHour)
if ((self.courseModel.effort?.containsString("约")) != nil) {
let timeStr = NSMutableString.init(string: self.courseModel.effort!)
let time = timeStr.stringByReplacingOccurrencesOfString("约", withString:"\(Strings.aboutTime) ")
cell.timeLabel.text = String(time.stringByAppendingString(" \(Strings.studyHour)"))
}
if self.courseModel.listen_count != nil {
let timeStr : String = self.courseModel.listen_count!.stringValue
cell.numberLabel.text = "\(timeStr) \(Strings.numberStudent)"
} else {
cell.numberLabel.text = "0\(Strings.numberStudent)"
}
return cell
} else {
let cell = TDCourseButtonsCell.init(style: .Default, reuseIdentifier: "TDCourseButtonsCell")
cell.selectionStyle = .None
switch self.courseModel.submitType {
case 0:
cell.submitButton.setTitle(Strings.CourseDetail.viewCourse, forState: .Normal)
case 1:
cell.submitButton.setAttributedTitle(setSubmitTitle(), forState: .Normal)
case 2:
cell.submitButton.setTitle(Strings.viewPrepareOrder, forState: .Normal)
default:
cell.submitButton.setTitle(Strings.willBeginCourse, forState: .Normal)
}
cell.submitButton.addTarget(self, action: #selector(submitButtonAction), forControlEvents: .TouchUpInside)
return cell
}
} else {
let cell = TDCourseDataCell.init(style: .Default, reuseIdentifier: "TDCourseDataCell")
cell.selectionStyle = .None
cell.accessoryType = .DisclosureIndicator
switch indexPath.row {
case 0:
cell.leftLabel.text = "\u{f19c}"
cell.titleLabel.text = Strings.mainProfessor
case 1:
cell.leftLabel.text = "\u{f0ca}"
cell.titleLabel.text = Strings.courseOutline
case 2:
cell.leftLabel.text = "\u{f040}"
cell.titleLabel.text = Strings.studentComment
case 3:
cell.leftLabel.text = "\u{f0c0}"
cell.titleLabel.text = Strings.classTitle
default:
cell.leftLabel.text = "\u{f0c0}"
cell.titleLabel.text = "助教"
}
return cell
}
}
func setSubmitTitle() -> NSAttributedString {
let baseTool = TDBaseToolModel.init()
let priceStr = baseTool.setDetailString("\(Strings.CourseDetail.enrollNow)¥\(String(format: "%.2f",(self.courseModel.course_price?.doubleValue)!))", withFont: 16, withColorStr: "#ffffff")
return priceStr //马上加入
}
//MARK: UI
func setViewConstraint() {
let headerView = UIView.init(frame: CGRectMake(0, 0, TDScreenWidth, (TDScreenWidth - 36) / 1.7 + 21))
headerView.addSubview(courseCardView)
courseCardView.snp_makeConstraints { (make) in
make.left.equalTo(headerView.snp_left).offset(18)
make.right.equalTo(headerView.snp_right).offset(-18)
make.top.equalTo(headerView.snp_top).offset(16)
make.height.equalTo((TDScreenWidth - 36) / 1.77)
}
playButton.setImage(Icon.CourseVideoPlay.imageWithFontSize(60), forState: .Normal)
playButton.tintColor = OEXStyles.sharedStyles().neutralWhite()
playButton.layer.shadowOpacity = 0.5
playButton.layer.shadowRadius = 3
playButton.layer.shadowOffset = CGSizeZero
playButton.addTarget(self, action: #selector(playButtonAction), forControlEvents: .TouchUpInside)
courseCardView.addCenteredOverlay(playButton)
tableView.dataSource = self
tableView.separatorStyle = .None
self.addSubview(tableView)
tableView.snp_makeConstraints { (make) in
make.left.right.top.bottom.equalTo(self)
}
tableView.tableFooterView = UIView()
tableView.tableHeaderView = headerView
headerView.backgroundColor = UIColor.whiteColor()
tableView.backgroundColor = OEXStyles.sharedStyles().baseColor5()
}
}
|
6348868aaf367dc36a3dd5e289cd0904
| 37.855204 | 195 | 0.583673 | false | false | false | false |
aulas-lab/ads-mobile
|
refs/heads/master
|
swift/ClasseDemo/ClasseDemo/Aluno.swift
|
mit
|
1
|
//
// Aluno.swift
// ClasseDemo
//
// Created by Mobitec on 26/04/16.
// Copyright (c) 2016 Unopar. All rights reserved.
//
import Foundation
class Aluno {
private let id: Int
private var nome: String
private var cpf: String
private var endereco: String
// private static var idSeed = 0
init() {
id = 0 // ++Aluno.idSeed
nome = "Sem Nome"
cpf = ""
endereco = ""
}
init(id: Int, nome: String, cpf: String) {
self.id = id
self.nome = nome
self.cpf = cpf
endereco = ""
}
var Nome: String {
get { return nome }
set(novoNome) { nome = novoNome }
}
var Endereco: String {
get { return endereco; }
set(novoEndereco) { endereco = novoEndereco; }
}
// Propriedade somente leitura
var Id: Int {
get { return id }
}
var Turma: String = "" {
willSet(novoNome) {
println("A nova turma sera \(novoNome)")
}
didSet {
println("Turma = Anterior: \(oldValue), Atual: \(Turma)")
}
}
func descricao() -> String {
return "Id: \(id), Nome: \(nome), Endereco: \(endereco), Turma: \(Turma)";
}
}
|
0862e8e08ff6491e177e1d8a6553392b
| 19.901639 | 82 | 0.502745 | false | false | false | false |
carambalabs/UnsplashKit
|
refs/heads/master
|
UnsplashKit/Classes/UnsplashAPI/Models/Response.swift
|
mit
|
1
|
import Foundation
/// API response that includes the pagination links.
public struct Response<A> {
// MARK: - Attributes
/// Response object.
public let object: A
/// Pagination first link.
public let firstLink: Link?
/// Pagination previous link.
public let prevLink: Link?
/// Pagination next link.
public let nextLink: Link?
/// Pagination last link.
public let lastLink: Link?
/// Limit of requests.
public let limitRequests: Int?
/// Number of remaining requests.
public let remainingRequests: Int?
// MARK: - Init
/// Initializes the response with the object and the http response.
///
/// - Parameters:
/// - object: object included in the response.
/// - response: http url response.
internal init(object: A, response: HTTPURLResponse) {
self.object = object
self.firstLink = response.findLink(relation: "first")
self.prevLink = response.findLink(relation: "prev")
self.nextLink = response.findLink(relation: "next")
self.lastLink = response.findLink(relation: "last")
self.limitRequests = response.allHeaderFields["X-Ratelimit-Limit"] as? Int
self.remainingRequests = response.allHeaderFields["X-Ratelimit-Remaining"] as? Int
}
}
|
156cd902e951dbe91b8c5ae6ea94faeb
| 27.369565 | 91 | 0.65364 | false | false | false | false |
Reedyuk/Charts
|
refs/heads/Swift-3.0
|
Charts/Classes/Charts/HorizontalBarChartView.swift
|
apache-2.0
|
6
|
//
// HorizontalBarChartView.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
/// BarChart with horizontal bar orientation. In this implementation, x- and y-axis are switched.
open class HorizontalBarChartView: BarChartView
{
internal override func initialize()
{
super.initialize()
_leftAxisTransformer = ChartTransformerHorizontalBarChart(viewPortHandler: _viewPortHandler)
_rightAxisTransformer = ChartTransformerHorizontalBarChart(viewPortHandler: _viewPortHandler)
renderer = HorizontalBarChartRenderer(dataProvider: self, animator: _animator, viewPortHandler: _viewPortHandler)
_leftYAxisRenderer = ChartYAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer)
_rightYAxisRenderer = ChartYAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer)
_xAxisRenderer = ChartXAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer, chart: self)
self.highlighter = HorizontalBarChartHighlighter(chart: self)
}
internal override func calculateOffsets()
{
var offsetLeft: CGFloat = 0.0,
offsetRight: CGFloat = 0.0,
offsetTop: CGFloat = 0.0,
offsetBottom: CGFloat = 0.0
calculateLegendOffsets(offsetLeft: &offsetLeft,
offsetTop: &offsetTop,
offsetRight: &offsetRight,
offsetBottom: &offsetBottom)
// offsets for y-labels
if (_leftAxis.needsOffset)
{
offsetTop += _leftAxis.getRequiredHeightSpace()
}
if (_rightAxis.needsOffset)
{
offsetBottom += _rightAxis.getRequiredHeightSpace()
}
let xlabelwidth = _xAxis.labelRotatedWidth
if (_xAxis.enabled)
{
// offsets for x-labels
if (_xAxis.labelPosition == .bottom)
{
offsetLeft += xlabelwidth
}
else if (_xAxis.labelPosition == .top)
{
offsetRight += xlabelwidth
}
else if (_xAxis.labelPosition == .bothSided)
{
offsetLeft += xlabelwidth
offsetRight += xlabelwidth
}
}
offsetTop += self.extraTopOffset
offsetRight += self.extraRightOffset
offsetBottom += self.extraBottomOffset
offsetLeft += self.extraLeftOffset
_viewPortHandler.restrainViewPort(
offsetLeft: max(self.minOffset, offsetLeft),
offsetTop: max(self.minOffset, offsetTop),
offsetRight: max(self.minOffset, offsetRight),
offsetBottom: max(self.minOffset, offsetBottom))
prepareOffsetMatrix()
prepareValuePxMatrix()
}
internal override func prepareValuePxMatrix()
{
_rightAxisTransformer.prepareMatrixValuePx(chartXMin: _rightAxis._axisMinimum, deltaX: CGFloat(_rightAxis.axisRange), deltaY: CGFloat(_xAxis.axisRange), chartYMin: _xAxis._axisMinimum)
_leftAxisTransformer.prepareMatrixValuePx(chartXMin: _leftAxis._axisMinimum, deltaX: CGFloat(_leftAxis.axisRange), deltaY: CGFloat(_xAxis.axisRange), chartYMin: _xAxis._axisMinimum)
}
internal override func calcModulus()
{
if let data = _data
{
_xAxis.axisLabelModulus = Int(ceil((CGFloat(data.xValCount) * _xAxis.labelRotatedHeight) / (_viewPortHandler.contentHeight * viewPortHandler.touchMatrix.d)))
}
else
{
_xAxis.axisLabelModulus = 1
}
if (_xAxis.axisLabelModulus < 1)
{
_xAxis.axisLabelModulus = 1
}
}
open override func getBarBounds(_ e: BarChartDataEntry) -> CGRect
{
guard let
set = _data?.getDataSetForEntry(e) as? IBarChartDataSet
else { return CGRect.null }
let barspace = set.barSpace
let y = CGFloat(e.value)
let x = CGFloat(e.xIndex)
let spaceHalf = barspace / 2.0
let top = x - 0.5 + spaceHalf
let bottom = x + 0.5 - spaceHalf
let left = y >= 0.0 ? y : 0.0
let right = y <= 0.0 ? y : 0.0
var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top)
getTransformer(set.axisDependency).rectValueToPixel(&bounds)
return bounds
}
open override func getPosition(_ e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var vals = CGPoint(x: CGFloat(e.value), y: CGFloat(e.xIndex))
getTransformer(axis).pointValueToPixel(&vals)
return vals
}
open override func getHighlightByTouchPoint(_ pt: CGPoint) -> ChartHighlight?
{
if _data === nil
{
Swift.print("Can't select by touch. No data set.", terminator: "\n")
return nil
}
return self.highlighter?.getHighlight(x: pt.y, y: pt.x)
}
open override var lowestVisibleXIndex: Int
{
let step = CGFloat(_data?.dataSetCount ?? 0)
let div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace
var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentBottom)
getTransformer(ChartYAxis.AxisDependency.left).pixelToValue(&pt)
return Int(((pt.y <= 0.0) ? 0.0 : pt.y / div) + 1.0)
}
open override var highestVisibleXIndex: Int
{
let step = CGFloat(_data?.dataSetCount ?? 0)
let div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace
var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentTop)
getTransformer(ChartYAxis.AxisDependency.left).pixelToValue(&pt)
return Int((pt.y >= CGFloat(chartXMax)) ? CGFloat(chartXMax) / div : (pt.y / div))
}
}
|
ee2c527b241dac9cfa3e010ace16224c
| 34.125 | 192 | 0.605446 | false | false | false | false |
Steveaxelrod007/UtilitiesInSwift
|
refs/heads/master
|
UtilitiesInSwift/Classes/CancelableClosure.swift
|
mit
|
1
|
// axee.com by Steve Axelrod
import Foundation
public class CancelableClosure
{
public var cancelled = false
public var closure: () -> () = {}
public func run()
{
if cancelled == false
{
cancelled = true // axe in case they also did a runAfterDelayOf
closure()
}
}
public func runAfterDelayOf(delayTime: Double = 0.5)
{
if cancelled == false
{
Queues.delayThenRunMainQueue(delay: delayTime)
{ [weak self] () -> Void in
if self?.cancelled == false
{
self?.run()
}
}
}
}
public init()
{
}
}
|
3fa552138cb2a020f4ccceb5702a2dbc
| 13.341463 | 68 | 0.576531 | false | false | false | false |
VincentPuget/vigenere
|
refs/heads/master
|
vigenere/class/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// Vigenere
//
// Created by Vincent PUGET on 05/08/2015.
// Copyright (c) 2015 Vincent PUGET. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
//qui l'app si la dernière fenetre active est fermée
func applicationShouldTerminateAfterLastWindowClosed(_ theApplication: NSApplication) -> Bool
{
return true;
}
// // MARK: - Core Data stack
//
// lazy var applicationDocumentsDirectory: NSURL = {
// // The directory the application uses to store the Core Data store file. This code uses a directory named "mao.macos.vigenere.test" in the user's Application Support directory.
// let urls = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)
// let appSupportURL = urls[urls.count - 1] as! NSURL
// return appSupportURL.URLByAppendingPathComponent("mao.macos.vigenere.test")
// }()
//
// lazy var managedObjectModel: NSManagedObjectModel = {
// // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
// let modelURL = NSBundle.mainBundle().URLForResource("test", withExtension: "momd")!
// return NSManagedObjectModel(contentsOfURL: modelURL)!
// }()
//
// lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. (The directory for the store is created, if necessary.) This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// let fileManager = NSFileManager.defaultManager()
// var shouldFail = false
// var error: NSError? = nil
// var failureReason = "There was an error creating or loading the application's saved data."
//
// // Make sure the application files directory is there
// let propertiesOpt = self.applicationDocumentsDirectory.resourceValuesForKeys([NSURLIsDirectoryKey], error: &error)
// if let properties = propertiesOpt {
// if !properties[NSURLIsDirectoryKey]!.boolValue {
// failureReason = "Expected a folder to store application data, found a file \(self.applicationDocumentsDirectory.path)."
// shouldFail = true
// }
// } else if error!.code == NSFileReadNoSuchFileError {
// error = nil
// fileManager.createDirectoryAtPath(self.applicationDocumentsDirectory.path!, withIntermediateDirectories: true, attributes: nil, error: &error)
// }
//
// // Create the coordinator and store
// var coordinator: NSPersistentStoreCoordinator?
// if !shouldFail && (error == nil) {
// coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
// let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("test.storedata")
// if coordinator!.addPersistentStoreWithType(NSXMLStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
// coordinator = nil
// }
// }
//
// if shouldFail || (error != nil) {
// // Report any error we got.
// var dict = [String: AnyObject]()
// dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
// dict[NSLocalizedFailureReasonErrorKey] = failureReason
// if error != nil {
// dict[NSUnderlyingErrorKey] = error
// }
// error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// NSApplication.sharedApplication().presentError(error!)
// return nil
// } else {
// return coordinator
// }
// }()
//
// lazy var managedObjectContext: NSManagedObjectContext? = {
// // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
// let coordinator = self.persistentStoreCoordinator
// if coordinator == nil {
// return nil
// }
// var managedObjectContext = NSManagedObjectContext()
// managedObjectContext.persistentStoreCoordinator = coordinator
// return managedObjectContext
// }()
//
// // MARK: - Core Data Saving and Undo support
//
// @IBAction func saveAction(sender: AnyObject!) {
// // Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user.
// if let moc = self.managedObjectContext {
// if !moc.commitEditing() {
// NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing before saving")
// }
// var error: NSError? = nil
// if moc.hasChanges && !moc.save(&error) {
// NSApplication.sharedApplication().presentError(error!)
// }
// }
// }
//
// func windowWillReturnUndoManager(window: NSWindow) -> NSUndoManager? {
// // Returns the NSUndoManager for the application. In this case, the manager returned is that of the managed object context for the application.
// if let moc = self.managedObjectContext {
// return moc.undoManager
// } else {
// return nil
// }
// }
//
// func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply {
// // Save changes in the application's managed object context before the application terminates.
//
// if let moc = managedObjectContext {
// if !moc.commitEditing() {
// NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing to terminate")
// return .TerminateCancel
// }
//
// if !moc.hasChanges {
// return .TerminateNow
// }
//
// var error: NSError? = nil
// if !moc.save(&error) {
// // Customize this code block to include application-specific recovery steps.
// let result = sender.presentError(error!)
// if (result) {
// return .TerminateCancel
// }
//
// let question = NSLocalizedString("Could not save changes while quitting. Quit anyway?", comment: "Quit without saves error question message")
// let info = NSLocalizedString("Quitting now will lose any changes you have made since the last successful save", comment: "Quit without saves error question info");
// let quitButton = NSLocalizedString("Quit anyway", comment: "Quit anyway button title")
// let cancelButton = NSLocalizedString("Cancel", comment: "Cancel button title")
// let alert = NSAlert()
// alert.messageText = question
// alert.informativeText = info
// alert.addButtonWithTitle(quitButton)
// alert.addButtonWithTitle(cancelButton)
//
// let answer = alert.runModal()
// if answer == NSAlertFirstButtonReturn {
// return .TerminateCancel
// }
// }
// }
// // If we got here, it is time to quit.
// return .TerminateNow
// }
}
|
d68fb4ff5f72cf0190b5d213de7f279f
| 48.719512 | 348 | 0.624847 | false | false | false | false |
SlackKit/SlackKit
|
refs/heads/main
|
SKCore/Sources/DoNotDisturbStatus.swift
|
mit
|
2
|
//
// DoNotDisturbStatus.swift
//
// Copyright © 2017 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public struct DoNotDisturbStatus {
fileprivate enum CodingKeys: String {
case enabled = "dnd_enabled"
case nextDoNotDisturbStart = "next_dnd_start_ts"
case nextDoNotDisturbEnd = "next_dnd_end_ts"
case snoozeEnabled = "snooze_enabled"
case snoozeEndtime = "snooze_endtime"
}
public var enabled: Bool?
public var nextDoNotDisturbStart: Int?
public var nextDoNotDisturbEnd: Int?
public var snoozeEnabled: Bool?
public var snoozeEndtime: Int?
public init(status: [String: Any]?) {
enabled = status?[CodingKeys.enabled] as? Bool
nextDoNotDisturbStart = status?[CodingKeys.nextDoNotDisturbStart] as? Int
nextDoNotDisturbEnd = status?[CodingKeys.nextDoNotDisturbEnd] as? Int
snoozeEnabled = status?[CodingKeys.snoozeEnabled] as? Bool
snoozeEndtime = status?[CodingKeys.snoozeEndtime] as? Int
}
}
extension DoNotDisturbStatus: Codable {
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
enabled = try values.decodeIfPresent(Bool.self, forKey: .enabled)
nextDoNotDisturbStart = try values.decodeIfPresent(Int.self, forKey: .nextDoNotDisturbStart)
nextDoNotDisturbEnd = try values.decodeIfPresent(Int.self, forKey: .nextDoNotDisturbEnd)
snoozeEnabled = try values.decodeIfPresent(Bool.self, forKey: .snoozeEnabled)
snoozeEndtime = try values.decodeIfPresent(Int.self, forKey: .snoozeEndtime)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(enabled, forKey: .enabled)
try container.encode(nextDoNotDisturbStart, forKey: .nextDoNotDisturbStart)
try container.encode(nextDoNotDisturbEnd, forKey: .nextDoNotDisturbEnd)
try container.encode(snoozeEnabled, forKey: .snoozeEnabled)
try container.encode(snoozeEndtime, forKey: .snoozeEndtime)
}
}
extension DoNotDisturbStatus.CodingKeys: CodingKey { }
|
013434fcc4b50f6c096373c174bff911
| 46.5 | 100 | 0.733437 | false | false | false | false |
leosimas/ios_KerbalCampaigns
|
refs/heads/master
|
Kerbal Campaigns/Colors.swift
|
apache-2.0
|
1
|
//
// Colors.swift
// Kerbal Campaigns
//
// Created by SoSucesso on 08/10/17.
// Copyright © 2017 Simas Team. All rights reserved.
//
import UIKit
struct Colors {
static let primary = Colors.hexStringToUIColor(hex: "283593")
static let secondary = Colors.hexStringToUIColor(hex: "3f51b5")
static let progressBar = Colors.hexStringToUIColor(hex: "33ff00")
static func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.characters.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
|
808a0f39a3adc11a93390eac5dd62de0
| 27.564103 | 93 | 0.587971 | false | false | false | false |
sgr-ksmt/PullToDismiss
|
refs/heads/master
|
Demo/Demo/SampleTableViewController.swift
|
mit
|
1
|
//
// SampleTableViewController.swift
// PullToDismiss
//
// Created by Suguru Kishimoto on 11/13/16.
// Copyright © 2016 Suguru Kishimoto. All rights reserved.
//
import UIKit
import PullToDismiss
class SampleTableViewController: UITableViewController {
private lazy var dataSource: [String] = { () -> [String] in
return (0..<100).map { "Item : \($0)" }
}()
private var pullToDismiss: PullToDismiss?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell")
let button = UIBarButtonItem(title: "Close", style: .plain, target: self, action: #selector(dismiss(_:)))
navigationItem.rightBarButtonItem = button
navigationItem.title = "Sample Table View"
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.barTintColor = .orange
navigationController?.navigationBar.setValue(UIBarPosition.topAttached.rawValue, forKey: "barPosition")
pullToDismiss = PullToDismiss(scrollView: tableView)
Config.shared.adaptSetting(pullToDismiss: pullToDismiss)
pullToDismiss?.dismissAction = { [weak self] in
self?.dismiss(nil)
}
pullToDismiss?.delegate = self
}
var disissBlock: (() -> Void)?
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = dataSource[indexPath.row]
return cell
}
@objc func dismiss(_: AnyObject?) {
dismiss(animated: true) { [weak self] in
self?.disissBlock?()
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let alert = UIAlertController(title: "test", message: "\(indexPath.section)-\(indexPath.row) touch!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "ok", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("\(scrollView.contentOffset.y)")
}
}
|
086ab7008634f4413e7a2ce3dff40a2a
| 37.984615 | 133 | 0.672849 | false | false | false | false |
GoodMorningCody/EverybodySwift
|
refs/heads/master
|
WeeklyToDo/WeeklyToDo/WeeklyToDoTableViewController.swift
|
mit
|
1
|
//
// WeeklyToDoTableViewController.swift
// WeeklyToDo
//
// Created by Cody on 2015. 1. 22..
// Copyright (c) 2015년 TIEKLE. All rights reserved.
//
import UIKit
class WeeklyToDoTableViewController: UITableViewController, TaskTableViewCellProtocol, TaskViewProtocol {
var taskViewController : UIViewController?
var timer : NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barTintColor = Color.getNavigationBackgroundColor()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:Color.getPointColor(), NSFontAttributeName : Font.getHightlightFont()]
//
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "add"), style: UIBarButtonItemStyle.Plain, target: self, action: "addNewTask")
self.navigationItem.rightBarButtonItem?.tintColor = Color.getPointColor()
WeeklyToDoDB.sharedInstance.needUpdate()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("orientationChanged"), name: UIDeviceOrientationDidChangeNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("willEnterForrground"), name: UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didEnterBackground"), name: UIApplicationDidEnterBackgroundNotification, object: nil)
setUpdateScheduler()
}
func didEnterBackground() {
if timer != nil {
timer?.invalidate()
timer = nil
}
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceOrientationDidChangeNotification, object: nil)
}
func willEnterForrground() {
setUpdateScheduler()
}
func setUpdateScheduler() {
let components = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitSecond, fromDate: NSDate())
if timer != nil {
timer?.invalidate()
timer = nil
}
var afterSeconds = Double(((24-components.hour)*60*60)-(components.minute*60)-(components.second))
timer = NSTimer.scheduledTimerWithTimeInterval(afterSeconds, target: self, selector: Selector("needUpdate"), userInfo: nil, repeats: false)
}
func needUpdate() {
println("needUpdate")
WeeklyToDoDB.sharedInstance.needUpdate()
tableView?.reloadData()
setUpdateScheduler()
}
func orientationChanged() {
if let viewController = taskViewController {
viewController.view.center = CGPointMake(UIScreen.mainScreen().bounds.size.width/2, UIScreen.mainScreen().bounds.size.height/2)
viewController.view.bounds = UIScreen.mainScreen().bounds
}
}
func addNewTask() {
if taskViewController == nil {
taskViewController = self.storyboard?.instantiateViewControllerWithIdentifier("TaskViewIdentifier") as? UIViewController
}
if let rootView = self.navigationController?.view {
if let taskView = taskViewController!.view as? TaskView {
taskView.delegate = self
taskView.show(rootView)
}
}
}
func didAddingToDo() {
tableView.reloadData()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "TaskSegueIdentifier" {
println("Create or Edit Task")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 7
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return WeeklyToDoDB.sharedInstance.countOfTaskInWeekend(section) + 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cellIdentifier : String?
if indexPath.row==0 {
cellIdentifier = "WeekendTableViewCellIdentifier"
}
else {
cellIdentifier = "TaskTableViewCellIdentifier"
}
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier!, forIndexPath: indexPath) as UITableViewCell
if indexPath.row == 0 {
return updateWeekendCell(cell, withIndexPath: indexPath)
}
return updateTaskCell(cell, withIndexPath: indexPath)
}
private func updateTaskCell(cell: UITableViewCell, withIndexPath indexPath : NSIndexPath) -> TaskTableViewCell {
// 업데이트 로직을 cell 객체로 이동
var taskCell = cell as TaskTableViewCell
taskCell.delegate = self
taskCell.tableView = self.tableView
if let task = WeeklyToDoDB.sharedInstance.taskInWeekend(indexPath.section, atIndex: indexPath.row-1) {
taskCell.todo = task.todo
taskCell.done = task.done.boolValue
taskCell.repeat = task.repeat.boolValue
}
return taskCell
}
private func updateWeekendCell(cell: UITableViewCell, withIndexPath indexPath : NSIndexPath) -> WeekendTableViewCell {
// 업데이트 로직을 cell 객체로 이동
var weekendCell = cell as WeekendTableViewCell
if WeeklyToDoDB.sharedInstance.countOfTaskInWeekend(indexPath.section) > 0 {
weekendCell.depthImageView?.hidden = false
}
else {
weekendCell.depthImageView?.hidden = true
}
weekendCell.todayMarkView?.hidden = (indexPath.section != 0)
weekendCell.weekendLabel?.text = Weekly.weekdayFromNow(indexPath.section, useStandardFormat: false)
var countOfTask = WeeklyToDoDB.sharedInstance.countOfTaskInWeekend(indexPath.section)
var countOfDoneTask = WeeklyToDoDB.sharedInstance.countOfDoneTaskInWeekend(indexPath.section)
if countOfTask>0 {
weekendCell.countLabel?.hidden = false
weekendCell.countLabel?.text = String(countOfDoneTask)+"/"+String(countOfTask)
}
else {
weekendCell.countLabel?.hidden = true
}
return weekendCell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row==0 {
return 58.0
}
return 44.0
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row==0 {
return
}
if taskViewController == nil {
taskViewController = self.storyboard?.instantiateViewControllerWithIdentifier("TaskViewIdentifier") as? UIViewController
}
if let rootView = self.navigationController?.view {
if let taskView = taskViewController!.view as? TaskView {
taskView.delegate = self
taskView.show(rootView, weekend: indexPath.section, index: indexPath.row-1)
}
}
}
func taskTableViewCell(#done: Bool, trash: Bool, repeat: Bool, indexPath:NSIndexPath) {
if done==true {
WeeklyToDoDB.sharedInstance.switchDoneTaskInWeekend(indexPath.section, atIndex: indexPath.row-1)
}
else if trash==true {
WeeklyToDoDB.sharedInstance.removeTaskInWeekend(indexPath.section, atIndex: indexPath.row-1)
}
else if repeat==true {
WeeklyToDoDB.sharedInstance.switchRepeatOptionInWeekend(indexPath.section, atIndex: indexPath.row-1)
}
self.tableView.reloadData()
}
}
|
1d3e48d729566aa7bf2011874f4f917e
| 38.275362 | 189 | 0.6631 | false | false | false | false |
BellAppLab/Defines
|
refs/heads/master
|
Sources/Defines/Defines.swift
|
mit
|
1
|
/*
Copyright (c) 2018 Bell App Lab <apps@bellapplab.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
//MARK: - Main
/**
The main point of interaction with `Defines`. All the flags in this module are namespaced under the `Defines` struct to avoid collisions.
Structure:
```
Defines.Device
Defines.Device.Model
Defines.Screen
Defines.OS
Defines.App
Defines.Version
```
## See Also
- [List of iOS Devices](https://en.wikipedia.org/wiki/List_of_iOS_devices)
*/
public struct Defines
{
//MARK: - Device
public struct Device
{
//MARK: - Model
/**
An enumeration of model identifiers for all the relevant Apple products since 2008.
Roughly speaking, these devices have been listed according to their ability to run the minimum OS versions supported by `Defines`.
## See Also
- [Models - The iPhone Wiki](https://www.theiphonewiki.com/wiki/Models)
- [Watch](https://support.apple.com/en-us/HT204507#link2)
- [iPad](https://support.apple.com/en-us/HT201471#ipad)
- [iPhone](https://support.apple.com/en-us/HT201296)
- [iPod Touch](https://support.apple.com/en-us/HT204217#ipodtouch)
- [MacBook air](https://support.apple.com/en-us/HT201862)
- [MacBook](https://support.apple.com/en-us/HT201608)
- [MacBook Pro](https://support.apple.com/en-us/HT201300)
- [Mac mini](https://support.apple.com/en-us/HT201894)
- [iMac](https://support.apple.com/en-us/HT201634)
- [Mac Pro](https://support.apple.com/en-us/HT202888)
- [What does 'MM' mean?](//https://apple.stackexchange.com/a/101066)
*/
public enum Model: String
{
//MARK: Default
/// If `Defines.Device.Model` cannot find the current device's model, this is the enum case it returns.
case unknown = ""
//MARK: AirPods
/// AirPods model identifier.
case airPods = "AirPods1,1"
//MARK: - Apple TV
/// TV (2nd Generation) model identifier.
case appleTV_2ndGeneration = "AppleTV2,1"
/// TV (3rd Generation) model identifier.
case appleTV_3rdGeneration = "AppleTV3,1"
/// TV (3rd Generation - revision 2) model identifier.
case appleTV_3rdGeneration_2 = "AppleTV3,2"
/// TV (4th Generation) model identifier.
case appleTV_4thGeneration = "AppleTV5,3"
/// TV 4K model identifier.
case appleTV_4K = "AppleTV6,2"
//MARK: Apple Watch
/// Watch (1st Generation) 38mm model identifier.
case appleWatch_1stGeneration_38mm = "Watch1,1"
/// Watch (1st Generation) 42mm model identifier.
case appleWatch_1stGeneration_42mm = "Watch1,2"
/// Watch Series 1 38mm model identifier.
case appleWatchSeries1_38mm = "Watch2,6"
/// Watch Series 1 42mm model identifier.
case appleWatchSeries1_42mm = "Watch2,7"
/// Watch Series 2 38mm model identifier.
case appleWatchSeries2_38mm = "Watch2,3"
/// Watch Series 2 42mm model identifier.
case appleWatchSeries2_42mm = "Watch2,4"
/// Watch Series 3 38mm (GPS+Cellular) model identifier.
case appleWatchSeries3_38mm_GPS_Cellular = "Watch3,1"
/// Watch Series 3 42mm (GPS+Cellular) model identifier.
case appleWatchSeries3_42mm_GPS_Cellular = "Watch3,2"
/// Watch Series 3 38mm (GPS) model identifier.
case appleWatchSeries3_38mm_GPS = "Watch3,3"
/// Watch Series 3 42mm (GPS) model identifier.
case appleWatchSeries3_42mm_GPS = "Watch3,4"
/// Watch Series 4 40mm (GPS) model identifier.
case appleWatchSeries4_40mm_GPS = "Watch4,1"
/// Watch Series 4 42mm (GPS) model identifier.
case appleWatchSeries4_44mm_GPS = "Watch4,2"
/// Watch Series 4 40mm (GPS+Cellular) model identifier.
case appleWatchSeries4_40mm_GPS_Cellular = "Watch4,3"
/// Watch Series 4 42mm (GPS+Cellular) model identifier.
case appleWatchSeries4_44mm_GPS_Cellular = "Watch4,4"
//MARK: Home Pod
/// HomePod model identifier.
case homePod_1 = "AudioAccessory1,1"
/// HomePod (`¯\_(ツ)_/¯`) model identifier.
case homePod_2 = "AudioAccessory1,2"
//MARK: iPad
/// iPad 2 WiFi model identifier.
case iPad_2 = "iPad2,1"
/// iPad 2 GSM model identifier.
case iPad_2_GSM = "iPad2,2"
/// iPad 2 CDMA model identifier.
case iPad_2_CDMA = "iPad2,3"
/// iPad 2 WiFi (revision 2) model identifier.
case iPad_2_2 = "iPad2,4"
/// iPad (3rd Generation) WiFi model identifier.
case iPad_3rdGeneration = "iPad3,1"
/// iPad (3rd Generation) Verizon model identifier.
case iPad_3rdGeneration_Verizon = "iPad3,2"
/// iPad (3rd Generation) GSM model identifier.
case iPad_3rdGeneration_GSM = "iPad3,3"
/// iPad (4th Generation) WiFi model identifier.
case iPad_4thGeneration = "iPad3,4"
/// iPad (4th Generation) CDMA model identifier.
case iPad_4thGeneration_CDMA = "iPad3,5"
/// iPad (4th Generation) Multi-Modal model identifier.
case iPad_4thGeneration_MM = "iPad3,6"
/// iPad air WiFi model identifier.
case iPadAir = "iPad4,1"
/// iPad air GSM model identifier.
case iPadAir_GSM = "iPad4,2"
/// iPad air LTE model identifier.
case iPadAir_TD_LTE = "iPad4,3"
/// iPad air 2 WiFi model identifier.
case iPadAir_2 = "iPad5,3"
/// iPad air 2 Cellular model identifier.
case iPadAir_2_Cellular = "iPad5,4"
/// iPad Pro 12.9" WiFi model identifier.
case iPadPro_12_9_Inch = "iPad6,7"
/// iPad Pro 12.9" Cellular model identifier.
case iPadPro_12_9_Inch_Cellular = "iPad6,8"
/// iPad Pro 9.7" WiFi model identifier.
case iPadPro_9_7_Inch = "iPad6,3"
/// iPad Pro 9.7" Cellular model identifier.
case iPadPro_9_7_Inch_Cellular = "iPad6,4"
/// iPad (5th Generation) WiFi model identifier.
case iPad_5thGeneration = "iPad6,11"
/// iPad (5th Generation) Cellular model identifier.
case iPad_5thGeneration_Cellular = "iPad6,12"
/// iPad Pro 12.9" (2nd Generation) WiFi model identifier.
case iPadPro_12_9_Inch_2ndGeneration = "iPad7,1"
/// iPad Pro 12.9" (2nd Generation) Cellular model identifier.
case iPadPro_12_9_Inch_2ndGeneration_Cellular = "iPad7,2"
/// iPad Pro 10.5" WiFi model identifier.
case iPadPro_10_5_Inch = "iPad7,3"
/// iPad Pro 10.5" Cellular model identifier.
case iPadPro_10_5_Inch_Cellular = "iPad7,4"
/// iPad (6th Generation) WiFi model identifier.
case iPad_6thGeneration = "iPad7,5"
/// iPad (6th Generation) Cellular model identifier.
case iPad_6thGeneration_Cellular = "iPad7,6"
/// iPad Pro 11" WiFi model identifier.
case iPadPro_11_Inch = "iPad8,1"
/// iPad Pro 11" WiFi with 1TB model identifier.
case iPadPro_11_Inch_1TB = "iPad8,2"
/// iPad Pro 11" Cellular model identifier.
case iPadPro_11_Inch_Cellular = "iPad8,3"
/// iPad Pro 11" Cellular with 1TB model identifier.
case iPadPro_11_Inch_1TB_Cellular = "iPad8,4"
/// iPad Pro 12.9" (3rd Generation) WiFi model identifier.
case iPadPro_12_9_Inch_3rdGeneration = "iPad8,5"
/// iPad Pro 12.9" (3rd Generation) WiFi with 1TB model identifier.
case iPadPro_12_9_Inch_3rdGeneration_1TB = "iPad8,6"
/// iPad Pro 12.9" (3rd Generation) Cellular model identifier.
case iPadPro_12_9_Inch_3rdGeneration_Cellular = "iPad8,7"
/// iPad Pro 12.9" (3rd Generation) Cellular with 1TB model identifier.
case iPadPro_12_9_Inch_3rdGeneration_1TB_Cellular = "iPad8,8"
/// iPad mini WiFi model identifier.
case iPad_Mini = "iPad2,5"
/// iPad mini CDMA model identifier.
case iPad_Mini_CDMA = "iPad2,6"
/// iPad mini Multi-Modal model identifier.
case iPad_Mini_MM = "iPad2,7"
/// iPad mini 2 WiFi model identifier.
case iPad_Mini_2 = "iPad4,4"
/// iPad mini 2 GSM model identifier.
case iPad_Mini_2_GSM = "iPad4,5"
/// iPad mini 2 LTE model identifier.
case iPad_Mini_2_TD_LTE = "iPad4,6"
/// iPad mini 3 WiFi model identifier.
case iPad_Mini_3 = "iPad4,7"
/// iPad mini 3 GSM model identifier.
case iPad_Mini_3_GSM = "iPad4,8"
/// iPad mini 3 (China) model identifier.
case iPad_Mini_3_China = "iPad4,9"
/// iPad mini 4 WiFi model identifier.
case iPad_Mini_4 = "iPad5,1"
/// iPad mini 4 GSM model identifier.
case iPad_Mini_4_GSM = "iPad5,2"
//MARK: iPhone
/// iPhone 4s model identifier.
case iPhone4s = "iPhone4,1"
/// iPhone 5 model identifier.
case iPhone5 = "iPhone5,1"
/// iPhone 5 (revision 2) model identifier.
case iPhone5_2 = "iPhone5,2"
/// iPhone 5c (North America and Japan) model identifier.
case iPhone5c_NorthAmerica_Japan = "iPhone5,3"
/// iPhone 5c (Europe and Asia) model identifier.
case iPhone5c_Europe_Asia = "iPhone5,4"
/// iPhone 5s (North America and Japan) model identifier.
case iPhone5s_NorthAmerica_Japan = "iPhone6,1"
/// iPhone 5s (Europe and Asia) model identifier.
case iPhone5s_Europe_Asia = "iPhone6,2"
/// iPhone 6 model identifier.
case iPhone6 = "iPhone7,2"
/// iPhone 6 Plus model identifier.
case iPhone6Plus = "iPhone7,1"
/// iPhone 6s model identifier.
case iPhone6s = "iPhone8,1"
/// iPhone 6s Plus model identifier.
case iPhone6sPlus = "iPhone8,2"
/// iPhone SE model identifier.
case iPhoneSE = "iPhone8,4"
/// iPhone 7 CDMA model identifier.
case iPhone7_CDMA = "iPhone9,1"
/// iPhone 7 Global model identifier.
case iPhone7_Global = "iPhone9,3"
/// iPhone 7 Plust CDMA model identifier.
case iPhone7Plus_CDMA = "iPhone9,2"
/// iPhone 7 Plus Global model identifier.
case iPhone7Plus_Global = "iPhone9,4"
/// iPhone 8 model identifier.
case iPhone8 = "iPhone10,1"
/// iPhone 8 (revision 2) model identifier.
case iPhone8_2 = "iPhone10,4"
/// iPhone 8 Plus model identifier.
case iPhone8Plus = "iPhone10,2"
/// iPhone 8 Plus (revision 2) model identifier.
case iPhone8Plus_2 = "iPhone10,5"
/// iPhone X model identifier.
case iPhoneX = "iPhone10,3"
/// iPhone X (revision 2) model identifier.
case iPhoneX_2 = "iPhone10,6"
/// iPhone XR model identifier.
case iPhoneXR = "iPhone11,8"
/// iPhone XR model identifier.
case iPhoneXS = "iPhone11,2"
/// iPhone XS Max model identifier.
case iPhoneXS_Max = "iPhone11,6"
/// iPhone XS Max (China) model identifier.
case iPhoneXS_Max_China = "iPhone11,4"
//MARK: iPod touch
/// iPod touch (5th Generation) model identifier.
case iPodTouch_5thGeneration = "iPod5,1"
/// iPod touch (6th Generation) model identifier.
case iPodTouch_6thGeneration = "iPod7,1"
//MARK: MacBook air
/// MacBook air 2009 model identifier.
case macBookAir_2009 = "MacBookAir2,1"
/// MacBook air 11" 2010 model identifier.
case macBookAir_11_Inch_2010 = "MacBookAir3,1"
/// MacBook air 13" 2010 model identifier.
case macBookAir_13_Inch_2010 = "MacBookAir3,2"
/// MacBook air 11" 2011 model identifier.
case macBookAir_11_Inch_2011 = "MacBookAir4,1"
/// MacBook air 13" 2011 model identifier.
case macBookAir_13_Inch_2011 = "MacBookAir4,2"
/// MacBook air 11" 2012 model identifier.
case macBookAir_11_Inch_2012 = "MacBookAir5,1"
/// MacBook air 13" 2012 model identifier.
case macBookAir_13_Inch_2012 = "MacBookAir5,2"
/// MacBook air 11" 2013 model identifier.
case macBookAir_11_Inch_2013 = "MacBookAir6,1"
/// MacBook air 13" 2013 model identifier.
case macBookAir_13_Inch_2013 = "MacBookAir6,2"
/// MacBook air 11" 2015 model identifier.
case macBookAir_11_Inch_2015 = "MacBookAir7,1"
/// MacBook air 13" 2015 model identifier.
case macBookAir_13_Inch_2015 = "MacBookAir7,2"
//MARK: MacBook
/// MacBook (Early 2009) model identifier.
case macBook_Early_2009 = "MacBook5,2"
/// MacBook (Late 2009) model identifier.
case macBook_Late_2009 = "MacBook6,1"
/// MacBook 2010 model identifier.
case macBook_2010 = "MacBook7,1"
/// MacBook 2015 model identifier.
case macBook_2015 = "MacBook8,1"
/// MacBook 2016 model identifier.
case macBook_2016 = "MacBook9,1"
/// MacBook 2017 model identifier.
case macBook_2017 = "MacBook10,1"
//MARK: MacBook Pro
/// MacBook Pro (Early 2008) model identifier.
case macBookPro_Early_2008 = "MacBookPro4,1"
/// MacBook Pro (Late 2008) model identifier.
case macBookPro_Late_2008 = "MacBookPro5,1"
/// MacBook Pro 13" 2009 model identifier.
case macBookPro_13_Inch_2009 = "MacBookPro5,5"
/// MacBook Pro 15" 2009 model identifier.
case macBookPro_15_Inch_2009 = "MacBookPro5,3"
/// MacBook Pro 17" 2009 model identifier.
case macBookPro_17_Inch_2009 = "MacBookPro5,2"
/// MacBook Pro 13" 2010 model identifier.
case macBookPro_13_Inch_2010 = "MacBookPro7,1"
/// MacBook Pro 15" 2010 model identifier.
case macBookPro_15_Inch_2010 = "MacBookPro6,2"
/// MacBook Pro 17" 2010 model identifier.
case macBookPro_17_Inch_2010 = "MacBookPro6,1"
/// MacBook Pro 13" 2011 model identifier.
case macBookPro_13_Inch_2011 = "MacBookPro8,1"
/// MacBook Pro 15" 2011 model identifier.
case macBookPro_15_Inch_2011 = "MacBookPro8,2"
/// MacBook Pro 17" 2011 model identifier.
case macBookPro_17_Inch_2011 = "MacBookPro8,3"
/// MacBook Pro 13" 2012 model identifier.
case macBookPro_13_Inch_2012 = "MacBookPro9,2"
/// MacBook Pro 13" Retina 2012 model identifier.
case macBookPro_13_Inch_Retina_2012 = "MacBookPro10,2"
/// MacBook Pro 15" 2012 model identifier.
case macBookPro_15_Inch_2012 = "MacBookPro9,1"
/// MacBook Pro 15" Retina 2012 model identifier.
case macBookPro_15_Inch_Retina_2012 = "MacBookPro10,1"
/// MacBook Pro 13" 2013 model identifier.
case macBookPro_13_Inch_2013 = "MacBookPro11,1"
/// MacBook Pro 15" 2013 model identifier.
case macBookPro_15_Inch_2013 = "MacBookPro11,2"
/// MacBook Pro 15" 2013 (revision 2) model identifier.
case macBookPro_15_Inch_2013_2 = "MacBookPro11,3"
/// MacBook Pro 13" 2015 model identifier.
case macBookPro_13_Inch_2015 = "MacBookPro12,1"
/// MacBook Pro 15" 2015 model identifier.
case macBookPro_15_Inch_2015 = "MacBookPro11,4"
/// MacBook Pro 15" 2015 (revision 2) model identifier.
case macBookPro_15_Inch_2015_2 = "MacBookPro11,5"
/// MacBook Pro 13" (Two Thunderbolt ports) 2016 model identifier.
case macBookPro_13_Inch_2_Thunderbolt_2016 = "MacBookPro13,1"
/// MacBook Pro 13" (Four Thunderbolt ports) 2016 model identifier.
case macBookPro_13_Inch_4_Thunderbolt_2016 = "MacBookPro13,2"
/// MacBook Pro 15" 2016 model identifier.
case macBookPro_15_Inch_2016 = "MacBookPro13,3"
/// MacBook Pro 13" (Two Thunderbolt ports) 2017 model identifier.
case macBookPro_13_Inch_2_Thunderbolt_2017 = "MacBookPro14,1"
/// MacBook Pro 13" (Four Thunderbolt ports) 2017 model identifier.
case macBookPro_13_Inch_4_Thunderbolt_2017 = "MacBookPro14,2"
/// MacBook Pro 15" 2017 model identifier.
case macBookPro_15_Inch_2017 = "MacBookPro14,3"
/// MacBook Pro 13" 2018 model identifier.
case macBookPro_13_Inch_2018 = "MacBookPro15,2"
/// MacBook Pro 15" 2018 model identifier.
case macBookPro_15_Inch_2018 = "MacBookPro15,1"
//MARK: Mac mini
/// Mac mini 2009 model identifier.
case macMini_2009 = "Macmini3,1"
/// Mac mini 2010 model identifier.
case macMini_2010 = "Macmini4,1"
/// Mac mini 2011 model identifier.
case macMini_2011 = "Macmini5,1"
/// Mac mini 2011 (revision 2) model identifier.
case macMini_2011_2 = "Macmini5,2"
/// Mac mini 2012 model identifier.
case macMini_2012 = "Macmini6,1"
/// Mac mini 2012 (revision 2) model identifier.
case macMini_2012_2 = "Macmini6,2"
/// Mac mini 2014 model identifier.
case macMini_2014 = "Macmini7,1"
//MARK: iMac
/// iMac (Early 2009) model identifier.
case iMac_Early_2009 = "iMac9,1"
/// iMac (Late 2009) model identifier.
case iMac_Late_2009 = "iMac10,1"
/// iMac 21.5" 2010 model identifier.
case iMac_21_5_Inch_2010 = "iMac11,2"
/// iMac 27" 2010 model identifier.
case iMac_27_Inch_2010 = "iMac11,3"
/// iMac 21.5" 2011 model identifier.
case iMac_21_5_Inch_2011 = "iMac12,1"
/// iMac 27" 2011 model identifier.
case iMac_27_Inch_2011 = "iMac12,2"
/// iMac 21.5" 2012 model identifier.
case iMac_21_5_Inch_2012 = "iMac13,1"
/// iMac 27" 2012 model identifier.
case iMac_27_Inch_2012 = "iMac13,2"
/// iMac 21.5" 2013 model identifier.
case iMac_21_5_Inch_2013 = "iMac14,1"
/// iMac 27" 2013 model identifier.
case iMac_27_Inch_2013 = "iMac14,2"
/// iMac 21.5" 2014 model identifier.
case iMac_21_5_Inch_2014 = "iMac14,4"
/// iMac 27" 5K 2014 model identifier.
case iMac_27_Inch_5K_2014 = "iMac15,1"
/// iMac 21.5" 2015 model identifier.
case iMac_21_5_Inch_2015 = "iMac16,1"
/// iMac 21.5" 4K 2015 model identifier.
case iMac_21_5_4K_Inch_2015 = "iMac16,2"
/// iMac 27" 5K 2015 model identifier.
case iMac_27_Inch_5K_2015 = "iMac17,1"
/// iMac 21.5" 2017 model identifier.
case iMac_21_5_Inch_2017 = "iMac18,1"
/// iMac 21.5" 4K 2017 model identifier.
case iMac_21_5_4K_Inch_2017 = "iMac18,2"
/// iMac 27" 5K 2017 model identifier.
case iMac_27_Inch_5K_2017 = "iMac18,3"
//MARK: Mac Pro
/// Mac Pro 2009 model identifier.
case macPro_2009 = "MacPro4,1"
/// Mac Pro 2010 model identifier.
case macPro_2010 = "MacPro5,1"
/// Mac Pro 2013 model identifier.
case macPro_2013 = "MacPro6,1"
}
}
/**
Contains information about the current screen available to your app.
*/
public struct Screen {}
/**
Contains information about the OS running your app.
*/
public struct OS {}
/**
Meta information about your app, mainly reading from Info.plist.
*/
public struct App {}
/**
The `Version` struct defines a software version in the format **major.minor.patch (build)**.
`Defines` uses it to describe either the OS version or your app's version, according to your Info.plist file.
It is particularly useful to compare versions of your app. For example:
```swift
let currentVersion = Defines.App.version(forClass: AppDelegate.self)
let oldVersion = Defines.Version(versionString: "1.0.0")
if currentVersion == oldVersion {
//your user is still running an old version of the app
//perhaps you want to let them know there's a new one available
//or let them know their version will be deprecated soon
}
```
*/
public struct Version: Equatable, Comparable, CustomStringConvertible {
/// The version's major number: **major**.minor.patch (build)
public let major: Int
/// The version's minor number: major.**minor**.patch (build)
public let minor: Int
/// The version's patch number: major.minor.**patch** (build)
public let patch: Int
/// The version's build string: major.minor.patch (**build**)
public let build: String
/**
Creates a new `Version` from a major, a minor and a patch `Int`s and a build `String`.
Example:
```
let version = Defines.Version(major: 1, minor: 0, patch: 0, build: "3")
print(version) //prints 'Version: 1.0.0 (3)'
```
- parameters:
- major: The version's major number. Must be greater than or equal to 0. Defaults to 0.
- minor: The version's minor number. Must be greater than or equal to 0. Defaults to 0.
- patch: The version's patch number. Must be greater than or equal to 0. Defaults to 0.
- build: The version's build string. Defaults to an empty string.
*/
public init(major: Int = 0,
minor: Int = 0,
patch: Int = 0,
build: String = "")
{
if major < 0 {
self.major = 0
} else {
self.major = major
}
if minor < 0 {
self.minor = 0
} else {
self.minor = minor
}
if patch < 0 {
self.patch = 0
} else {
self.patch = patch
}
self.build = build
}
}
}
|
122ef5c798f95804c5f92ce5044153fe
| 45.779693 | 139 | 0.576314 | false | false | false | false |
ljshj/actor-platform
|
refs/heads/master
|
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Conversation/Cell/AABubbleVideoCell.swift
|
agpl-3.0
|
2
|
//
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import UIKit
import VBFPopFlatButton
import AVFoundation
import YYImage
public class AABubbleVideoCell: AABubbleBaseFileCell {
// Views
let preview = UIImageView()
let progress = AAProgressView(size: CGSizeMake(64, 64))
let timeBg = UIImageView()
let timeLabel = UILabel()
let statusView = UIImageView()
let playView = UIImageView(image: UIImage.bundled("aa_playbutton"))
// Binded data
var bindedLayout: VideoCellLayout!
var thumbLoaded = false
var contentLoaded = false
// Constructors
public init(frame: CGRect) {
super.init(frame: frame, isFullSize: false)
timeBg.image = ActorSDK.sharedActor().style.statusBackgroundImage
timeLabel.font = UIFont.italicSystemFontOfSize(11)
timeLabel.textColor = appStyle.chatMediaDateColor
statusView.contentMode = UIViewContentMode.Center
contentView.addSubview(preview)
contentView.addSubview(progress)
contentView.addSubview(timeBg)
contentView.addSubview(timeLabel)
contentView.addSubview(statusView)
contentView.addSubview(playView)
preview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(AABubbleVideoCell.mediaDidTap)))
preview.userInteractionEnabled = true
playView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(AABubbleVideoCell.mediaDidTap)))
playView.userInteractionEnabled = true
contentInsets = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Binding
public override func bind(message: ACMessage, receiveDate: jlong, readDate: jlong, reuse: Bool, cellLayout: AACellLayout, setting: AACellSetting) {
self.bindedLayout = cellLayout as! VideoCellLayout
bubbleInsets = UIEdgeInsets(
top: setting.clenchTop ? AABubbleCell.bubbleTopCompact : AABubbleCell.bubbleTop,
left: 10 + (AADevice.isiPad ? 16 : 0),
bottom: setting.clenchBottom ? AABubbleCell.bubbleBottomCompact : AABubbleCell.bubbleBottom,
right: 10 + (AADevice.isiPad ? 16 : 0))
if (!reuse) {
// Bind bubble
if (self.isOut) {
bindBubbleType(BubbleType.MediaOut, isCompact: false)
} else {
bindBubbleType(BubbleType.MediaIn, isCompact: false)
}
// Reset content state
self.preview.image = nil
contentLoaded = false
thumbLoaded = false
// Reset progress
self.progress.hideButton()
//UIView.animateWithDuration(0, animations: { () -> Void in
self.progress.hidden = true
self.preview.hidden = true
//})
// Bind file
fileBind(message, autoDownload: bindedLayout.autoDownload)
}
// Update time
timeLabel.text = cellLayout.date
// Update status
if (isOut) {
statusView.hidden = false
switch(message.messageState.toNSEnum()) {
case .SENT:
if message.sortDate <= readDate {
self.statusView.image = appStyle.chatIconCheck2
self.statusView.tintColor = appStyle.chatStatusMediaRead
} else if message.sortDate <= receiveDate {
self.statusView.image = appStyle.chatIconCheck2
self.statusView.tintColor = appStyle.chatStatusMediaReceived
} else {
self.statusView.image = appStyle.chatIconCheck1
self.statusView.tintColor = appStyle.chatStatusMediaSent
}
case .ERROR:
self.statusView.image = appStyle.chatIconError
self.statusView.tintColor = appStyle.chatStatusMediaError
break
default:
self.statusView.image = appStyle.chatIconClock
self.statusView.tintColor = appStyle.chatStatusMediaSending
break
}
} else {
statusView.hidden = true
}
}
// File state binding
public override func fileUploadPaused(reference: String, selfGeneration: Int) {
bgLoadThumb(selfGeneration)
bgLoadReference(reference, selfGeneration: selfGeneration)
runOnUiThread(selfGeneration) { () -> () in
self.progress.showView()
self.playView.hideView()
self.progress.setButtonType(FlatButtonType.buttonUpBasicType, animated: true)
self.progress.hideProgress()
}
}
public override func fileUploading(reference: String, progress: Double, selfGeneration: Int) {
bgLoadThumb(selfGeneration)
bgLoadReference(reference, selfGeneration: selfGeneration)
runOnUiThread(selfGeneration) { () -> () in
self.progress.showView()
self.playView.hideView()
self.progress.setButtonType(FlatButtonType.buttonPausedType, animated: true)
self.progress.setProgress(progress)
}
}
public override func fileDownloadPaused(selfGeneration: Int) {
bgLoadThumb(selfGeneration)
runOnUiThread(selfGeneration) { () -> () in
self.progress.showView()
self.playView.hideView()
self.progress.setButtonType(FlatButtonType.buttonDownloadType, animated: true)
self.progress.hideProgress()
}
}
public override func fileDownloading(progress: Double, selfGeneration: Int) {
bgLoadThumb(selfGeneration)
runOnUiThread(selfGeneration) { () -> () in
self.progress.showView()
self.playView.hideView()
self.progress.setButtonType(FlatButtonType.buttonPausedType, animated: true)
self.progress.setProgress(progress)
}
}
public override func fileReady(reference: String, selfGeneration: Int) {
bgLoadThumb(selfGeneration)
self.bgLoadReference(reference, selfGeneration: selfGeneration)
runOnUiThread(selfGeneration) { () -> () in
self.progress.setProgress(1)
self.progress.hideView()
self.playView.showView()
}
}
public func bgLoadThumb(selfGeneration: Int) {
if (thumbLoaded) {
return
}
thumbLoaded = true
if (bindedLayout.fastThumb != nil) {
let loadedThumb = UIImage(data: bindedLayout.fastThumb!)?
.imageByBlurLight()!
.roundCorners(bindedLayout.screenSize.width,
h: bindedLayout.screenSize.height,
roundSize: 14)
runOnUiThread(selfGeneration,closure: { ()->() in
self.setPreviewImage(loadedThumb!, fast: true)
});
}
}
public func bgLoadReference(reference: String, selfGeneration: Int) {
let movieAsset = AVAsset(URL: NSURL(fileURLWithPath: CocoaFiles.pathFromDescriptor(reference))) // video asset
let imageGenerator = AVAssetImageGenerator(asset: movieAsset)
var thumbnailTime = movieAsset.duration
thumbnailTime.value = 25
do {
let imageRef = try imageGenerator.copyCGImageAtTime(thumbnailTime, actualTime: nil)
var thumbnail = UIImage(CGImage: imageRef)
let orientation = movieAsset.videoOrientation()
if (orientation.orientation.isPortrait) == true {
thumbnail = thumbnail.imageRotatedByDegrees(90, flip: false)
}
let loadedContent = thumbnail.roundCorners(self.bindedLayout.screenSize.width, h: self.bindedLayout.screenSize.height, roundSize: 14)
runOnUiThread(selfGeneration, closure: { () -> () in
self.setPreviewImage(loadedContent, fast: false)
self.contentLoaded = true
})
} catch {
}
}
public func setPreviewImage(img: UIImage, fast: Bool){
if ((fast && self.preview.image == nil) || !fast) {
self.preview.image = img
self.preview.showView()
}
}
// Media Action
public func mediaDidTap() {
let content = bindedMessage!.content as! ACDocumentContent
if let fileSource = content.getSource() as? ACFileRemoteSource {
Actor.requestStateWithFileId(fileSource.getFileReference().getFileId(), withCallback: AAFileCallback(
notDownloaded: { () -> () in
Actor.startDownloadingWithReference(fileSource.getFileReference())
}, onDownloading: { (progress) -> () in
Actor.cancelDownloadingWithFileId(fileSource.getFileReference().getFileId())
}, onDownloaded: { (reference) -> () in
self.controller.playVideoFromPath(CocoaFiles.pathFromDescriptor(reference))
}))
} else if let fileSource = content.getSource() as? ACFileLocalSource {
let rid = bindedMessage!.rid
Actor.requestUploadStateWithRid(rid, withCallback: AAUploadFileCallback(
notUploaded: { () -> () in
Actor.resumeUploadWithRid(rid)
}, onUploading: { (progress) -> () in
Actor.pauseUploadWithRid(rid)
}, onUploadedClosure: { () -> () in
self.controller.playVideoFromPath(CocoaFiles.pathFromDescriptor(CocoaFiles.pathFromDescriptor(fileSource.getFileDescriptor())))
}))
}
}
// Layouting
public override func layoutContent(maxWidth: CGFloat, offsetX: CGFloat) {
let insets = fullContentInsets
let contentWidth = self.contentView.frame.width
_ = self.contentView.frame.height
let bubbleWidth = self.bindedLayout.screenSize.width
let bubbleHeight = self.bindedLayout.screenSize.height
layoutBubble(bubbleWidth, contentHeight: bubbleHeight)
if (isOut) {
preview.frame = CGRectMake(contentWidth - insets.left - bubbleWidth, insets.top, bubbleWidth, bubbleHeight)
} else {
preview.frame = CGRectMake(insets.left, insets.top, bubbleWidth, bubbleHeight)
}
progress.frame = CGRectMake(preview.frame.origin.x + preview.frame.width/2 - 32, preview.frame.origin.y + preview.frame.height/2 - 32, 64, 64)
playView.frame = progress.frame
timeLabel.frame = CGRectMake(0, 0, 1000, 1000)
timeLabel.sizeToFit()
let timeWidth = (isOut ? 23 : 0) + timeLabel.bounds.width
let timeHeight: CGFloat = 20
timeLabel.frame = CGRectMake(preview.frame.maxX - timeWidth - 18, preview.frame.maxY - timeHeight - 6, timeLabel.frame.width, timeHeight)
if (isOut) {
statusView.frame = CGRectMake(timeLabel.frame.maxX, timeLabel.frame.minY, 23, timeHeight)
}
timeBg.frame = CGRectMake(timeLabel.frame.minX - 4, timeLabel.frame.minY - 1, timeWidth + 8, timeHeight + 2)
}
}
public class VideoCellLayout: AACellLayout {
public let fastThumb: NSData?
public let contentSize: CGSize
public let screenSize: CGSize
public let autoDownload: Bool
/**
Creting layout for media bubble
*/
public init(id: Int64, width: CGFloat, height:CGFloat, date: Int64, fastThumb: ACFastThumb?, autoDownload: Bool, layouter: AABubbleLayouter) {
// Saving content size
self.contentSize = CGSizeMake(width, height)
// Saving autodownload flag
self.autoDownload = autoDownload
// Calculating bubble screen size
let scaleW = 240 / width
let scaleH = 240 / height
let scale = min(scaleW, scaleH)
self.screenSize = CGSize(width: scale * width, height: scale * height)
// Prepare fast thumb
print("video thumb === \(fastThumb?.getImage().toNSData())")
self.fastThumb = fastThumb?.getImage().toNSData()
// Creating layout
super.init(height: self.screenSize.height + 2, date: date, key: "media", layouter: layouter)
}
/**
Creating layout for video content
*/
public convenience init(id: Int64, videoContent: ACVideoContent, date: Int64, layouter: AABubbleLayouter) {
self.init(id: id, width: CGFloat(videoContent.getW()), height: CGFloat(videoContent.getH()), date: date, fastThumb: videoContent.getFastThumb(), autoDownload: false, layouter: layouter)
}
/**
Creating layout for message
*/
public convenience init(message: ACMessage, layouter: AABubbleLayouter) {
if let content = message.content as? ACVideoContent {
self.init(id: Int64(message.rid), videoContent: content, date: Int64(message.date), layouter: layouter)
} else {
fatalError("Unsupported content for media cell")
}
}
}
public class AABubbleVideoCellLayouter: AABubbleLayouter {
public func isSuitable(message: ACMessage) -> Bool {
if message.content is ACVideoContent {
return true
}
return false
}
public func buildLayout(peer: ACPeer, message: ACMessage) -> AACellLayout {
return VideoCellLayout(message: message, layouter: self)
}
public func cellClass() -> AnyClass {
return AABubbleVideoCell.self
}
}
|
6c557f07fdd528e8ccb2d2813b90202f
| 35.715762 | 193 | 0.598536 | false | false | false | false |
thelukester92/swift-engine
|
refs/heads/master
|
swift-engine/Engine/Components/LGPhysicsBody.swift
|
mit
|
1
|
//
// LGPhysicsBody.swift
// swift-engine
//
// Created by Luke Godfrey on 6/7/14.
// Copyright (c) 2014 Luke Godfrey. See LICENSE.
//
import SpriteKit
public final class LGPhysicsBody: LGComponent
{
public class func type() -> String
{
return "LGPhysicsBody"
}
public func type() -> String
{
return LGPhysicsBody.type()
}
public var velocity = LGVector()
public var width: Double
public var height: Double
public var dynamic: Bool
public var trigger = false
// TODO: allow other kinds of directional collisions
public var onlyCollidesVertically = false
public var collidedTop = false
public var collidedBottom = false
public var collidedLeft = false
public var collidedRight = false
public var collidedWith = [Int:LGEntity]()
public init(width: Double, height: Double, dynamic: Bool = true)
{
self.width = width
self.height = height
self.dynamic = dynamic
}
public convenience init(size: LGVector, dynamic: Bool = true)
{
self.init(width: size.x, height: size.y, dynamic: dynamic)
}
public convenience init()
{
self.init(width: 0, height: 0)
}
}
extension LGPhysicsBody: LGDeserializable
{
public class var requiredProps: [String]
{
return [ "width", "height" ]
}
public class var optionalProps: [String]
{
return [ "dynamic", "onlyCollidesVertically", "trigger", "velocity" ]
}
public class func instantiate() -> LGDeserializable
{
return LGPhysicsBody()
}
public func setValue(value: LGJSON, forKey key: String) -> Bool
{
switch key
{
case "width":
width = value.doubleValue!
return true
case "height":
height = value.doubleValue!
return true
case "dynamic":
dynamic = value.boolValue!
return true
case "onlyCollidesVertically":
onlyCollidesVertically = value.boolValue!
return true
case "trigger":
trigger = value.boolValue!
return true
case "velocity":
if let x = value["x"]?.doubleValue
{
velocity.x = x
}
if let y = value["y"]?.doubleValue
{
velocity.y = y
}
return true
default:
break
}
return false
}
public func valueForKey(key: String) -> LGJSON
{
return LGJSON(value: nil)
}
}
|
3ab2b13999780e8c8a9620ef77aba662
| 17.203252 | 71 | 0.660116 | false | false | false | false |
adrianomazucato/CoreStore
|
refs/heads/master
|
CoreStore/Convenience Helpers/NSProgress+Convenience.swift
|
mit
|
2
|
//
// NSProgress+Convenience.swift
// CoreStore
//
// Copyright (c) 2015 John Rommel Estropia
//
// 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 GCDKit
// MARK: - NSProgress
public extension NSProgress {
// MARK: Public
/**
Sets a closure that the `NSProgress` calls whenever its `fractionCompleted` changes. You can use this instead of setting up KVO.
- parameter closure: the closure to execute on progress change
*/
public func setProgressHandler(closure: ((progress: NSProgress) -> Void)?) {
self.progressObserver.progressHandler = closure
}
// MARK: Private
private struct PropertyKeys {
static var progressObserver: Void?
}
private var progressObserver: ProgressObserver {
get {
let object: ProgressObserver? = getAssociatedObjectForKey(&PropertyKeys.progressObserver, inObject: self)
if let observer = object {
return observer
}
let observer = ProgressObserver(self)
setAssociatedRetainedObject(
observer,
forKey: &PropertyKeys.progressObserver,
inObject: self
)
return observer
}
}
}
@objc private final class ProgressObserver: NSObject {
private unowned let progress: NSProgress
private var progressHandler: ((progress: NSProgress) -> Void)? {
didSet {
let progressHandler = self.progressHandler
if (progressHandler == nil) == (oldValue == nil) {
return
}
if let _ = progressHandler {
self.progress.addObserver(
self,
forKeyPath: "fractionCompleted",
options: [.Initial, .New],
context: nil
)
}
else {
self.progress.removeObserver(self, forKeyPath: "fractionCompleted")
}
}
}
private init(_ progress: NSProgress) {
self.progress = progress
super.init()
}
deinit {
if let _ = self.progressHandler {
self.progressHandler = nil
self.progress.removeObserver(self, forKeyPath: "fractionCompleted")
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard let progress = object as? NSProgress where progress == self.progress && keyPath == "fractionCompleted" else {
return
}
GCDQueue.Main.async { [weak self] () -> Void in
self?.progressHandler?(progress: progress)
}
}
}
|
baa4e3e64e208050af9d08c2039cb657
| 29.848485 | 157 | 0.589145 | false | false | false | false |
pkrawat1/TravelApp-ios
|
refs/heads/master
|
TravelApp/Helpers/Extensions.swift
|
mit
|
1
|
//
// Extensions .swift
// YoutubeClone
//
// Created by Pankaj Rawat on 20/01/17.
// Copyright © 2017 Pankaj Rawat. All rights reserved.
//
import UIKit
import SwiftDate
extension UIColor {
static func rgb(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat = 1) -> UIColor {
return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: alpha)
}
static func appBaseColor() -> UIColor {
return rgb(red: 44, green: 62, blue: 80)
}
static func appCallToActionColor() -> UIColor {
return rgb(red: 231, green: 76, blue: 60)
}
static func appMainBGColor() -> UIColor {
return rgb(red: 236, green: 240, blue: 241)
}
static func appLightBlue() -> UIColor {
return rgb(red: 52, green: 152, blue: 219)
}
static func appDarkBlue() -> UIColor {
return rgb(red: 41, green: 128, blue: 185)
}
}
extension UIView {
func addConstraintsWithFormat(format: String, views: UIView...){
var viewsDictionary = [String: UIView]()
for(index, view) in views.enumerated() {
let key = "v\(index)"
view.translatesAutoresizingMaskIntoConstraints = false
viewsDictionary[key] = view
}
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
}
func addBackground(imageName: String) {
// screen width and height:
let width = UIScreen.main.bounds.size.width
let height = UIScreen.main.bounds.size.height
let imageViewBackground = UIImageView(frame: CGRect(x: 0, y: 0, width: width, height: height))
imageViewBackground.image = UIImage(named: imageName)
// you can change the content mode:
imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill
self.addSubview(imageViewBackground)
self.sendSubview(toBack: imageViewBackground)
}
}
let imageCache = NSCache<AnyObject, AnyObject>()
class CustomImageView: UIImageView {
var imageUrlString: String?
func loadImageUsingUrlString(urlString: String, width: Float) {
// Change width of image
var urlString = urlString
let regex = try! NSRegularExpression(pattern: "upload", options: NSRegularExpression.Options.caseInsensitive)
let range = NSMakeRange(0, urlString.characters.count)
urlString = regex.stringByReplacingMatches(in: urlString,
options: [],
range: range,
withTemplate: "upload/w_\(Int(width * 1.5))")
imageUrlString = urlString
image = nil
backgroundColor = UIColor.gray
let url = NSURL(string: urlString)
let configuration = URLSessionConfiguration.default
let urlRequest = URLRequest(url: url as! URL)
let session = URLSession(configuration: configuration)
if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = imageFromCache
return
}
session.dataTask(with: urlRequest) { (data, response, error) -> Void in
if (error != nil) {
print(error!)
return
} else {
DispatchQueue.main.async {
let imageToCache = UIImage(data: data!)
if self.imageUrlString == urlString {
self.image = imageToCache
}
if imageToCache != nil {
imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)
}
}
return
}
}.resume()
}
}
//MARK: - UITextView
extension UITextView{
func numberOfLines() -> Int{
if let fontUnwrapped = self.font{
return Int(self.contentSize.height / fontUnwrapped.lineHeight)
}
return 0
}
}
extension String {
func humanizeDate(format: String = "MM-dd-yyyy HH:mm:ss") -> String {
//"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: self)
dateFormatter.dateFormat = format
return dateFormatter.string(from: dateObj!)
}
func relativeDate() -> String {
let date = try! DateInRegion(string: humanizeDate(), format: .custom("MM-dd-yyyy HH:mm:ss"))
let relevantTime = try! date.colloquialSinceNow().colloquial
return relevantTime
}
}
extension CreateTripController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func handleSelectTripImage() {
let picker = UIImagePickerController()
picker.delegate = self
present(picker, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let imagePicked = info["UIImagePickerControllerOriginalImage"] as? UIImage {
self.tripEditForm.thumbnailImageView.image = imagePicked
statusBarBackgroundView.alpha = 0
}
dismiss(animated: true, completion: nil)
}
}
|
4c96149561fb73d18dffa0aecba1640a
| 32.20904 | 152 | 0.585403 | false | false | false | false |
gmilos/swift
|
refs/heads/master
|
test/stdlib/TestIndexPath.swift
|
apache-2.0
|
2
|
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
#if FOUNDATION_XCTEST
import XCTest
class TestIndexPathSuper : XCTestCase { }
#else
import StdlibUnittest
class TestIndexPathSuper { }
#endif
class TestIndexPath : TestIndexPathSuper {
func testBasics() {
let ip = IndexPath(index: 1)
expectEqual(ip.count, 1)
}
func testAppending() {
var ip : IndexPath = [1, 2, 3, 4]
let ip2 = IndexPath(indexes: [5, 6, 7])
ip.append(ip2)
expectEqual(ip.count, 7)
expectEqual(ip[0], 1)
expectEqual(ip[6], 7)
}
func testRanges() {
let ip1 = IndexPath(indexes: [1, 2, 3])
let ip2 = IndexPath(indexes: [6, 7, 8])
// Replace the whole range
var mutateMe = ip1
mutateMe[0..<3] = ip2
expectEqual(mutateMe, ip2)
// Insert at the beginning
mutateMe = ip1
mutateMe[0..<0] = ip2
expectEqual(mutateMe, IndexPath(indexes: [6, 7, 8, 1, 2, 3]))
// Insert at the end
mutateMe = ip1
mutateMe[3..<3] = ip2
expectEqual(mutateMe, IndexPath(indexes: [1, 2, 3, 6, 7, 8]))
// Insert in middle
mutateMe = ip1
mutateMe[2..<2] = ip2
expectEqual(mutateMe, IndexPath(indexes: [1, 2, 6, 7, 8, 3]))
}
func testMoreRanges() {
var ip = IndexPath(indexes: [1, 2, 3])
let ip2 = IndexPath(indexes: [5, 6, 7, 8, 9, 10])
ip[1..<2] = ip2
expectEqual(ip, IndexPath(indexes: [1, 5, 6, 7, 8, 9, 10, 3]))
}
func testIteration() {
let ip = IndexPath(indexes: [1, 2, 3])
var count = 0
for _ in ip {
count += 1
}
expectEqual(3, count)
}
func test_AnyHashableContainingIndexPath() {
let values: [IndexPath] = [
IndexPath(indexes: [1, 2]),
IndexPath(indexes: [1, 2, 3]),
IndexPath(indexes: [1, 2, 3]),
]
let anyHashables = values.map(AnyHashable.init)
expectEqual(IndexPath.self, type(of: anyHashables[0].base))
expectEqual(IndexPath.self, type(of: anyHashables[1].base))
expectEqual(IndexPath.self, type(of: anyHashables[2].base))
expectNotEqual(anyHashables[0], anyHashables[1])
expectEqual(anyHashables[1], anyHashables[2])
}
func test_AnyHashableCreatedFromNSIndexPath() {
let values: [NSIndexPath] = [
NSIndexPath(index: 1),
NSIndexPath(index: 2),
NSIndexPath(index: 2),
]
let anyHashables = values.map(AnyHashable.init)
expectEqual(IndexPath.self, type(of: anyHashables[0].base))
expectEqual(IndexPath.self, type(of: anyHashables[1].base))
expectEqual(IndexPath.self, type(of: anyHashables[2].base))
expectNotEqual(anyHashables[0], anyHashables[1])
expectEqual(anyHashables[1], anyHashables[2])
}
// TODO: Test bridging
}
#if !FOUNDATION_XCTEST
var IndexPathTests = TestSuite("TestIndexPath")
IndexPathTests.test("testBasics") { TestIndexPath().testBasics() }
IndexPathTests.test("testAppending") { TestIndexPath().testAppending() }
IndexPathTests.test("testRanges") { TestIndexPath().testRanges() }
IndexPathTests.test("testMoreRanges") { TestIndexPath().testMoreRanges() }
IndexPathTests.test("testIteration") { TestIndexPath().testIteration() }
IndexPathTests.test("test_AnyHashableContainingIndexPath") { TestIndexPath().test_AnyHashableContainingIndexPath() }
IndexPathTests.test("test_AnyHashableCreatedFromNSIndexPath") { TestIndexPath().test_AnyHashableCreatedFromNSIndexPath() }
runAllTests()
#endif
|
44b184b543bcdedfeca1eefb311bef9d
| 31.453125 | 122 | 0.601348 | false | true | false | false |
icanzilb/Languages
|
refs/heads/master
|
3-Lab/Languages-3/Languages/ViewController.swift
|
mit
|
1
|
/*
* Copyright (c) 2015 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
// MARK: constants
let kDeselectedDetailsText = "Managing to fluently transmit your thoughts and have daily conversations"
let kSelectedDetailsText = "Excercises: 67%\nConversations: 50%\nDaily streak: 4\nCurrent grade: B"
// MARK: - ViewController
class ViewController: UIViewController {
@IBOutlet var speakingTrailing: NSLayoutConstraint!
// MARK: IB outlets
@IBOutlet var speakingDetails: UILabel!
@IBOutlet var understandingImage: UIImageView!
@IBOutlet var readingImage: UIImageView!
@IBOutlet var speakingView: UIView!
@IBOutlet var understandingView: UIView!
@IBOutlet var readingView: UIView!
// MARK: class properties
var views: [UIView]!
var selectedView: UIView?
var deselectCurrentView: (()->())?
// MARK: - view controller methods
override func viewDidLoad() {
super.viewDidLoad()
views = [speakingView, readingView, understandingView]
let speakingTap = UITapGestureRecognizer(target: self, action: Selector("toggleSpeaking:"))
speakingView.addGestureRecognizer(speakingTap)
let readingTap = UITapGestureRecognizer(target: self, action: Selector("toggleReading:"))
readingView.addGestureRecognizer(readingTap)
let understandingTap = UITapGestureRecognizer(target: self, action: Selector("toggleView:"))
understandingView.addGestureRecognizer(understandingTap)
}
// MARK: - auto layout animation
func adjustHeights(viewToSelect: UIView, shouldSelect: Bool) {
println("tapped: \(viewToSelect) select: \(shouldSelect)")
var newConstraints: [NSLayoutConstraint] = []
for constraint in viewToSelect.superview!.constraints() as [NSLayoutConstraint] {
if contains(views, constraint.firstItem as UIView) &&
constraint.firstAttribute == .Height {
println("height constraint found")
NSLayoutConstraint.deactivateConstraints([constraint])
var multiplier: CGFloat = 0.34
if shouldSelect {
multiplier = (viewToSelect == constraint.firstItem as UIView) ? 0.55 : 0.23
}
let con = NSLayoutConstraint(
item: constraint.firstItem,
attribute: .Height,
relatedBy: .Equal,
toItem: (constraint.firstItem as UIView).superview!,
attribute: .Height,
multiplier: multiplier,
constant: 0.0)
newConstraints.append(con)
}
}
NSLayoutConstraint.activateConstraints(newConstraints)
}
// deselects any selected views and selects the tapped view
func toggleView(tap: UITapGestureRecognizer) {
let wasSelected = selectedView==tap.view!
adjustHeights(tap.view!, shouldSelect: !wasSelected)
selectedView = wasSelected ? nil : tap.view!
if !wasSelected {
UIView.animateWithDuration(1.0, delay: 0.00,
usingSpringWithDamping: 0.4, initialSpringVelocity: 1.0,
options: .CurveEaseIn | .AllowUserInteraction | .BeginFromCurrentState,
animations: {
self.deselectCurrentView?()
self.deselectCurrentView = nil
}, completion: nil)
}
UIView.animateWithDuration(1.0, delay: 0.00,
usingSpringWithDamping: 0.4, initialSpringVelocity: 1.0,
options: .CurveEaseIn | .AllowUserInteraction | .BeginFromCurrentState,
animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
//speaking
func updateSpeakingDetails(#selected: Bool) {
speakingDetails.text = selected ? kSelectedDetailsText : kDeselectedDetailsText
for constraint in speakingDetails.superview!.constraints() as [NSLayoutConstraint] {
if constraint.firstItem as UIView == speakingDetails &&
constraint.firstAttribute == .Leading {
constraint.constant = -view.frame.size.width/2
speakingView.layoutIfNeeded()
UIView.animateWithDuration(0.5, delay: 0.1,
options: .CurveEaseOut, animations: {
constraint.constant = 0.0
self.speakingView.layoutIfNeeded()
}, completion: nil)
break
}
}
}
func toggleSpeaking(tap: UITapGestureRecognizer) {
toggleView(tap)
let isSelected = (selectedView==tap.view!)
UIView.animateWithDuration(1.0, delay: 0.00,
usingSpringWithDamping: 0.4, initialSpringVelocity: 1.0,
options: .CurveEaseIn, animations: {
self.speakingTrailing.constant = isSelected ? self.speakingView.frame.size.width/2.0 : 0.0
self.updateSpeakingDetails(selected: isSelected)
}, completion: nil)
deselectCurrentView = {
self.speakingTrailing.constant = 0.0
self.updateSpeakingDetails(selected: false)
}
}
//reading
func toggleReading(tap: UITapGestureRecognizer) {
toggleView(tap)
let isSelected = (selectedView==tap.view!)
toggleReadingImageSize(readingImage, isSelected: isSelected)
UIView.animateWithDuration(0.5, delay: 0.1,
options: .CurveEaseOut, animations: {
self.readingView.layoutIfNeeded()
}, completion: nil)
deselectCurrentView = {
self.toggleReadingImageSize(self.readingImage, isSelected: false)
}
}
func toggleReadingImageSize(imageView: UIImageView, isSelected: Bool) {
for constraint in imageView.superview!.constraints() as [NSLayoutConstraint] {
if constraint.firstItem as UIView == imageView && constraint.firstAttribute == .Height {
NSLayoutConstraint.deactivateConstraints([constraint])
let con = NSLayoutConstraint(
item: constraint.firstItem,
attribute: .Height,
relatedBy: .Equal,
toItem: (constraint.firstItem as UIView).superview!,
attribute: .Height,
multiplier: isSelected ? 0.33 : 0.67,
constant: 0.0)
con.active = true
}
}
}
}
|
e90c806dc9fd27624ce1476b37169302
| 33.066986 | 103 | 0.676404 | false | false | false | false |
cbguder/CBGPromise
|
refs/heads/master
|
Tests/CBGPromiseTests/PromiseTests.swift
|
mit
|
1
|
import Dispatch
import XCTest
import CBGPromise
class PromiseTests: XCTestCase {
var subject: Promise<String>!
override func setUp() {
subject = Promise<String>()
}
func testCallbackBlockRegisteredBeforeResolution() {
var result: String!
subject.future.then { r in
result = r
}
subject.resolve("My Special Value")
XCTAssertEqual(result, "My Special Value")
}
func testCallbackBlockRegisteredAfterResolution() {
var result: String!
subject.resolve("My Special Value")
subject.future.then { r in
result = r
}
XCTAssertEqual(result, "My Special Value")
}
func testValueAccessAfterResolution() {
subject.resolve("My Special Value")
XCTAssertEqual(subject.future.value, "My Special Value")
}
func testWaitingForResolution() {
let queue = DispatchQueue(label: "test")
queue.asyncAfter(deadline: DispatchTime.now() + .milliseconds(100)) {
self.subject.resolve("My Special Value")
}
let receivedValue = subject.future.wait()
XCTAssertEqual(subject.future.value, "My Special Value")
XCTAssertEqual(receivedValue, subject.future.value)
}
func testMultipleCallbacks() {
var valA: String?
var valB: String?
subject.future.then { v in valA = v }
subject.future.then { v in valB = v }
subject.resolve("My Special Value")
XCTAssertEqual(valA, "My Special Value")
XCTAssertEqual(valB, "My Special Value")
}
func testMapReturnsNewFuture() {
var mappedValue: Int?
let mappedFuture = subject.future.map { str -> Int? in
return Int(str)
}
mappedFuture.then { num in
mappedValue = num
}
subject.resolve("123")
XCTAssertEqual(mappedValue, 123)
}
func testMapAllowsChaining() {
var mappedValue: Int?
let mappedPromise = Promise<Int>()
let mappedFuture = subject.future.map { str -> Future<Int> in
return mappedPromise.future
}
mappedFuture.then { num in
mappedValue = num
}
subject.resolve("Irrelevant")
mappedPromise.resolve(123)
XCTAssertEqual(mappedValue, 123)
}
func testWhenWaitsUntilResolution() {
let firstPromise = Promise<String>()
let secondPromise = Promise<String>()
let receivedFuture = Promise<String>.when([firstPromise.future, secondPromise.future])
XCTAssertNil(receivedFuture.value)
firstPromise.resolve("hello")
XCTAssertNil(receivedFuture.value)
secondPromise.resolve("goodbye")
XCTAssertEqual(receivedFuture.value, ["hello", "goodbye"])
}
func testWhenPreservesOrder() {
let firstPromise = Promise<String>()
let secondPromise = Promise<String>()
let receivedFuture = Promise<String>.when([firstPromise.future, secondPromise.future])
secondPromise.resolve("goodbye")
firstPromise.resolve("hello")
XCTAssertEqual(receivedFuture.value, ["hello", "goodbye"])
}
}
|
dc90a2a534b6071009cc64958cbdba91
| 23.906977 | 94 | 0.619048 | false | true | false | false |
ByteriX/BxTextField
|
refs/heads/master
|
BxTextFieldTests/BxTextFieldPlaceholderTests.swift
|
mit
|
1
|
//
// BxTextFieldPlaceholderTests.swift
// BxTextFieldTests
//
// Created by Sergey Balalaev on 16/05/2018.
// Copyright © 2018 Byterix. All rights reserved.
//
import XCTest
@testable import BxTextField
class BxTextFieldPlaceholderTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testPlaceholderWithPatterns() {
let textField = BxTextField(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
textField.leftPatternText = "www."
textField.rightPatternText = ".byterix.com"
textField.placeholderText = "domain"
textField.isPlaceholderPatternShown = true
XCTAssertEqual(textField.placeholder!, "www.domain.byterix.com")
XCTAssertEqual(textField.enteredText, "")
XCTAssertEqual(textField.text!, "")
textField.enteredText = "mail"
XCTAssertEqual(textField.placeholder!, "www.domain.byterix.com")
XCTAssertEqual(textField.enteredText, "mail")
XCTAssertEqual(textField.text!, "www.mail.byterix.com")
}
func testPlaceholderWithoutPatterns() {
let textField = BxTextField(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
textField.leftPatternText = "www."
textField.rightPatternText = ".byterix.com"
textField.placeholderText = "domain"
textField.isPlaceholderPatternShown = false
XCTAssertEqual(textField.placeholder!, "domain")
XCTAssertEqual(textField.enteredText, "")
XCTAssertEqual(textField.text!, "")
textField.enteredText = "mail"
XCTAssertEqual(textField.placeholder!, "domain")
XCTAssertEqual(textField.enteredText, "mail")
XCTAssertEqual(textField.text!, "www.mail.byterix.com")
}
}
|
bdd00925d072a9c096243477a9a2c14d
| 37.415094 | 111 | 0.673379 | false | true | false | false |
Dhimanswadia/TipCalculator
|
refs/heads/master
|
tips/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// tips
//
// Created by Dhiman on 12/14/15.
// Copyright © 2015 Dhiman. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var billField: UITextField!
@IBOutlet var tipControl: UISegmentedControl!
@IBOutlet var totalLabel: UILabel!
@IBOutlet var tipLabel: UILabel!
var DefaultSegments = [20, 22, 25]
var tipPercentagese: [Double] = [0.0, 0.0, 0.0]
var tip: Double = 0.0
var total: Double = 0.0
override func viewDidLoad() {
super.viewDidLoad()
let defaults = NSUserDefaults.standardUserDefaults()
if((defaults.objectForKey("tipPercentageSE")) != nil)
{
tipPercentagese = defaults.objectForKey("tipPercentageSE") as! [Double]
}
else {
for var i = 0; i < DefaultSegments.count; ++i
{
tipPercentagese[i] = Double(DefaultSegments[i])
}
}
let segments = tipPercentagese
for var index = 0; index < tipControl.numberOfSegments; ++index
{
tipControl.setTitle("\(Int(segments[index]))%", forSegmentAtIndex: index)
}
billField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func OnEditingChanged
(sender: AnyObject) {
let tpercentage = tipControl.selectedSegmentIndex
let tipPercentages = Double(tipPercentagese[tpercentage])
let billAmount = billField.text!._bridgeToObjectiveC().doubleValue
let tip = billAmount * (tipPercentages * 0.01)
let total = billAmount + tip
tipLabel.text = "$\(tip)"
totalLabel.text = "$\(total)"
tipLabel.text = String(format: "$%.2f",tip)
totalLabel.text = String(format: "$%.2f",total)
}
@IBAction func OnTap(sender: AnyObject) {
view.endEditing(true)
}
}
|
c427265b702eca8844eaa80988a5fb59
| 26.948718 | 85 | 0.569725 | false | false | false | false |
daisysomus/swift-algorithm-club
|
refs/heads/master
|
Minimum Spanning Tree/MinimumSpanningTree.playground/Sources/Graph.swift
|
mit
|
1
|
// Undirected edge
public struct Edge<T>: CustomStringConvertible {
public let vertex1: T
public let vertex2: T
public let weight: Int
public var description: String {
return "[\(vertex1)-\(vertex2), \(weight)]"
}
}
// Undirected weighted graph
public struct Graph<T: Hashable>: CustomStringConvertible {
public private(set) var edgeList: [Edge<T>]
public private(set) var vertices: Set<T>
public private(set) var adjList: [T: [(vertex: T, weight: Int)]]
public init() {
edgeList = [Edge<T>]()
vertices = Set<T>()
adjList = [T: [(vertex: T, weight: Int)]]()
}
public var description: String {
var description = ""
for edge in edgeList {
description += edge.description + "\n"
}
return description
}
public mutating func addEdge(vertex1 v1: T, vertex2 v2: T, weight w: Int) {
edgeList.append(Edge(vertex1: v1, vertex2: v2, weight: w))
vertices.insert(v1)
vertices.insert(v2)
adjList[v1] = adjList[v1] ?? []
adjList[v1]?.append((vertex: v2, weight: w))
adjList[v2] = adjList[v2] ?? []
adjList[v2]?.append((vertex: v1, weight: w))
}
public mutating func addEdge(_ edge: Edge<T>) {
addEdge(vertex1: edge.vertex1, vertex2: edge.vertex2, weight: edge.weight)
}
}
|
ecd1ef7bf43ec891297a41ba3f57ea65
| 24.4 | 78 | 0.641732 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Tracks+ShareExtension.swift
|
gpl-2.0
|
1
|
import Foundation
/// This extension implements helper tracking methods, meant for Share Extension Usage.
///
extension Tracks {
// MARK: - Public Methods
public func trackExtensionLaunched(_ wpcomAvailable: Bool) {
let properties = ["is_configured_dotcom": wpcomAvailable]
trackExtensionEvent(.launched, properties: properties as [String: AnyObject]?)
}
public func trackExtensionPosted(_ status: String) {
let properties = ["post_status": status]
trackExtensionEvent(.posted, properties: properties as [String: AnyObject]?)
}
public func trackExtensionError(_ error: NSError) {
let properties = ["error_code": String(error.code), "error_domain": error.domain, "error_description": error.description]
trackExtensionEvent(.error, properties: properties as [String: AnyObject]?)
}
public func trackExtensionCancelled() {
trackExtensionEvent(.canceled)
}
public func trackExtensionTagsOpened() {
trackExtensionEvent(.tagsOpened)
}
public func trackExtensionTagsSelected(_ tags: String) {
let properties = ["selected_tags": tags]
trackExtensionEvent(.tagsSelected, properties: properties as [String: AnyObject]?)
}
public func trackExtensionCategoriesOpened() {
trackExtensionEvent(.categoriesOpened)
}
public func trackExtensionCategoriesSelected(_ categories: String) {
let properties = ["categories_tags": categories]
trackExtensionEvent(.categoriesSelected, properties: properties as [String: AnyObject]?)
}
// MARK: - Private Helpers
fileprivate func trackExtensionEvent(_ event: ExtensionEvents, properties: [String: AnyObject]? = nil) {
track(event.rawValue, properties: properties)
}
// MARK: - Private Enums
fileprivate enum ExtensionEvents: String {
case launched = "wpios_share_extension_launched"
case posted = "wpios_share_extension_posted"
case tagsOpened = "wpios_share_extension_tags_opened"
case tagsSelected = "wpios_share_extension_tags_selected"
case canceled = "wpios_share_extension_canceled"
case error = "wpios_share_extension_error"
case categoriesOpened = "wpios_share_extension_categories_opened"
case categoriesSelected = "wpios_share_extension_categories_selected"
}
}
|
767827d64593f8d168444964112e39da
| 36.71875 | 129 | 0.68517 | false | false | false | false |
exponent/exponent
|
refs/heads/master
|
ios/vendored/unversioned/@stripe/stripe-react-native/ios/CardFormView.swift
|
bsd-3-clause
|
2
|
import Foundation
import UIKit
import Stripe
class CardFormView: UIView, STPCardFormViewDelegate {
public var cardForm: STPCardFormView?
public var cardParams: STPPaymentMethodCardParams? = nil
@objc var dangerouslyGetFullCardDetails: Bool = false
@objc var onFormComplete: RCTDirectEventBlock?
@objc var autofocus: Bool = false
@objc var isUserInteractionEnabledValue: Bool = true
override func didSetProps(_ changedProps: [String]!) {
if let cardForm = self.cardForm {
cardForm.removeFromSuperview()
}
let style = self.cardStyle["type"] as? String == "borderless" ? STPCardFormViewStyle.borderless : STPCardFormViewStyle.standard
let _cardForm = STPCardFormView(style: style)
_cardForm.delegate = self
// _cardForm.isUserInteractionEnabled = isUserInteractionEnabledValue
if autofocus == true {
let _ = _cardForm.becomeFirstResponder()
}
self.cardForm = _cardForm
self.addSubview(_cardForm)
setStyles()
}
@objc var cardStyle: NSDictionary = NSDictionary() {
didSet {
setStyles()
}
}
func cardFormView(_ form: STPCardFormView, didChangeToStateComplete complete: Bool) {
if onFormComplete != nil {
let brand = STPCardValidator.brand(forNumber: cardForm?.cardParams?.card?.number ?? "")
var cardData: [String: Any?] = [
"expiryMonth": cardForm?.cardParams?.card?.expMonth ?? NSNull(),
"expiryYear": cardForm?.cardParams?.card?.expYear ?? NSNull(),
"complete": complete,
"brand": Mappers.mapCardBrand(brand) ?? NSNull(),
"last4": cardForm?.cardParams?.card?.last4 ?? "",
"postalCode": cardForm?.cardParams?.billingDetails?.address?.postalCode ?? "",
"country": cardForm?.cardParams?.billingDetails?.address?.country
]
if (dangerouslyGetFullCardDetails) {
cardData["number"] = cardForm?.cardParams?.card?.number ?? ""
}
if (complete) {
self.cardParams = cardForm?.cardParams?.card
} else {
self.cardParams = nil
}
onFormComplete!(cardData as [AnyHashable : Any])
}
}
func focus() {
let _ = cardForm?.becomeFirstResponder()
}
func blur() {
let _ = cardForm?.resignFirstResponder()
}
func setStyles() {
if let backgroundColor = cardStyle["backgroundColor"] as? String {
cardForm?.backgroundColor = UIColor(hexString: backgroundColor)
}
// if let disabledBackgroundColor = cardStyle["disabledBackgroundColor"] as? String {
// cardForm?.disabledBackgroundColor = UIColor(hexString: disabledBackgroundColor)
// }
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func layoutSubviews() {
cardForm?.frame = self.bounds
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
159484caba8d693d9233c7f3f0e4d49b
| 33.55914 | 135 | 0.59552 | false | false | false | false |
february29/Learning
|
refs/heads/master
|
Pods/RxDataSources/Sources/RxDataSources/RxTableViewSectionedAnimatedDataSource.swift
|
cc0-1.0
|
3
|
//
// RxTableViewSectionedAnimatedDataSource.swift
// RxExample
//
// Created by Krunoslav Zaher on 6/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
import Differentiator
open class RxTableViewSectionedAnimatedDataSource<S: AnimatableSectionModelType>
: TableViewSectionedDataSource<S>
, RxTableViewDataSourceType {
public typealias Element = [S]
public typealias DecideViewTransition = (TableViewSectionedDataSource<S>, UITableView, [Changeset<S>]) -> ViewTransition
/// Animation configuration for data source
public var animationConfiguration: AnimationConfiguration
/// Calculates view transition depending on type of changes
public var decideViewTransition: DecideViewTransition
#if os(iOS)
public init(
animationConfiguration: AnimationConfiguration = AnimationConfiguration(),
decideViewTransition: @escaping DecideViewTransition = { _, _, _ in .animated },
configureCell: @escaping ConfigureCell,
titleForHeaderInSection: @escaping TitleForHeaderInSection = { _, _ in nil },
titleForFooterInSection: @escaping TitleForFooterInSection = { _, _ in nil },
canEditRowAtIndexPath: @escaping CanEditRowAtIndexPath = { _, _ in false },
canMoveRowAtIndexPath: @escaping CanMoveRowAtIndexPath = { _, _ in false },
sectionIndexTitles: @escaping SectionIndexTitles = { _ in nil },
sectionForSectionIndexTitle: @escaping SectionForSectionIndexTitle = { _, _, index in index }
) {
self.animationConfiguration = animationConfiguration
self.decideViewTransition = decideViewTransition
super.init(
configureCell: configureCell,
titleForHeaderInSection: titleForHeaderInSection,
titleForFooterInSection: titleForFooterInSection,
canEditRowAtIndexPath: canEditRowAtIndexPath,
canMoveRowAtIndexPath: canMoveRowAtIndexPath,
sectionIndexTitles: sectionIndexTitles,
sectionForSectionIndexTitle: sectionForSectionIndexTitle
)
}
#else
public init(
animationConfiguration: AnimationConfiguration = AnimationConfiguration(),
decideViewTransition: @escaping DecideViewTransition = { _, _, _ in .animated },
configureCell: @escaping ConfigureCell,
titleForHeaderInSection: @escaping TitleForHeaderInSection = { _, _ in nil },
titleForFooterInSection: @escaping TitleForFooterInSection = { _, _ in nil },
canEditRowAtIndexPath: @escaping CanEditRowAtIndexPath = { _, _ in false },
canMoveRowAtIndexPath: @escaping CanMoveRowAtIndexPath = { _, _ in false }
) {
self.animationConfiguration = animationConfiguration
self.decideViewTransition = decideViewTransition
super.init(
configureCell: configureCell,
titleForHeaderInSection: titleForHeaderInSection,
titleForFooterInSection: titleForFooterInSection,
canEditRowAtIndexPath: canEditRowAtIndexPath,
canMoveRowAtIndexPath: canMoveRowAtIndexPath
)
}
#endif
var dataSet = false
open func tableView(_ tableView: UITableView, observedEvent: Event<Element>) {
Binder(self) { dataSource, newSections in
#if DEBUG
self._dataSourceBound = true
#endif
if !self.dataSet {
self.dataSet = true
dataSource.setSections(newSections)
tableView.reloadData()
}
else {
DispatchQueue.main.async {
// if view is not in view hierarchy, performing batch updates will crash the app
if tableView.window == nil {
dataSource.setSections(newSections)
tableView.reloadData()
return
}
let oldSections = dataSource.sectionModels
do {
let differences = try Diff.differencesForSectionedView(initialSections: oldSections, finalSections: newSections)
switch self.decideViewTransition(self, tableView, differences) {
case .animated:
for difference in differences {
dataSource.setSections(difference.finalSections)
tableView.performBatchUpdates(difference, animationConfiguration: self.animationConfiguration)
}
case .reload:
self.setSections(newSections)
tableView.reloadData()
return
}
}
catch let e {
rxDebugFatalError(e)
self.setSections(newSections)
tableView.reloadData()
}
}
}
}.on(observedEvent)
}
}
#endif
|
99481ba1c059dcbb8fa78e34758e06e7
| 42.99187 | 136 | 0.591573 | false | true | false | false |
warren-gavin/OBehave
|
refs/heads/master
|
OBehave/Classes/Tables/EmptyState/OBEmptyStateBehavior.swift
|
mit
|
1
|
//
// OBEmptyStateBehavior.swift
// OBehave
//
// Created by Warren on 18/02/16.
// Copyright © 2016 Apokrupto. All rights reserved.
//
import UIKit
// MARK: - OBEmptyStateBehaviorDataSource
public protocol OBEmptyStateBehaviorDataSource {
func viewToDisplayOnEmpty(for behavior: OBEmptyStateBehavior?) -> UIView?
}
// MARK: - Views that can have empty states
enum DataSetView {
case table(UITableView)
case collection(UICollectionView)
}
// MARK: - Behavior
public final class OBEmptyStateBehavior: OBBehavior {
@IBOutlet public var scrollView: UIScrollView! {
didSet {
switch scrollView {
case let view as UITableView:
view.tableFooterView = UIView()
dataSetView = .table(view)
case let view as UICollectionView:
dataSetView = .collection(view)
default:
dataSetView = nil
}
}
}
private var dataSetView: DataSetView? {
didSet {
guard let displayingView = dataSetView?.view as? DataDisplaying else {
return
}
interceptDataLoading()
displayingView.emptyStateDataSource = getDataSource()
}
}
}
private extension OBEmptyStateBehavior {
func interceptDataLoading() {
guard
let viewClass = dataSetView?.class,
let viewClassType = viewClass as? DataDisplaying.Type,
!viewClassType.isSwizzled
else {
return
}
zip(viewClassType.swizzledMethods, viewClassType.originalMethods).forEach {
guard
let swizzledMethod = class_getInstanceMethod(viewClass, $0),
let originalMethod = class_getInstanceMethod(viewClass, $1)
else {
return
}
method_exchangeImplementations(swizzledMethod, originalMethod)
}
viewClassType.isSwizzled = true
}
}
// MARK: - DataSetView extension
extension DataSetView {
var view: UIView? {
switch self {
case .table(let view):
return view
case .collection(let view):
return view
}
}
var `class`: AnyClass? {
switch self {
case .table(_):
return UITableView.self
case .collection(_):
return UICollectionView.self
}
}
var isEmpty: Bool {
switch self {
case .table(let table):
return table.isEmpty
case .collection(let collection):
return collection.isEmpty
}
}
}
// MARK: - DataDisplaying protocol
protocol DataDisplaying: class {
var numberOfSections: Int { get }
func count(for section: Int) -> Int
static var originalMethods: [Selector] { get }
static var swizzledMethods: [Selector] { get }
}
extension DataDisplaying where Self: UIView {
var showEmptyState: Bool {
get {
return isEmpty
}
set {
guard let emptyStateView = emptyStateView else {
return
}
if newValue {
addSubview(emptyStateView)
emptyStateView.translatesAutoresizingMaskIntoConstraints = false
emptyStateView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
emptyStateView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
emptyStateView.topAnchor.constraint(greaterThanOrEqualTo: topAnchor).isActive = true
emptyStateView.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor).isActive = true
emptyStateView.leadingAnchor.constraint(greaterThanOrEqualTo: leadingAnchor).isActive = true
emptyStateView.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor).isActive = true
layoutIfNeeded()
}
else {
clearEmptyStateView()
}
emptyStateView.alpha = (newValue ? 1.0 : 0.0)
}
}
}
private struct Constants {
static var isSwizzledKey = "com.apokrupto.OBEmptyStateBehavior.isSwizzled"
static var emptyStateViewKey = "com.apokrupto.OBEmptyDateSetBehavior.emptyStateView"
static var emptyStateDataSourceKey = "com.apokrupto.OBEmptyDateSetBehavior.emptyStateDataSource"
}
private extension DataDisplaying {
var isEmpty: Bool {
return 0 == (0 ..< numberOfSections).reduce(0) { $0 + count(for: $1) }
}
var emptyStateView: UIView? {
get {
if let emptyStateView = objc_getAssociatedObject(self, &Constants.emptyStateViewKey) as? UIView {
return emptyStateView
}
let emptyStateView = emptyStateDataSource?.viewToDisplayOnEmpty(for: nil)
objc_setAssociatedObject(self, &Constants.emptyStateViewKey, emptyStateView, .OBJC_ASSOCIATION_ASSIGN)
return emptyStateView
}
set {
objc_setAssociatedObject(self, &Constants.emptyStateViewKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
}
var emptyStateDataSource: OBEmptyStateBehaviorDataSource? {
get {
return objc_getAssociatedObject(self, &Constants.emptyStateDataSourceKey) as? OBEmptyStateBehaviorDataSource
}
set {
objc_setAssociatedObject(self, &Constants.emptyStateDataSourceKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
}
static var isSwizzled: Bool {
get {
return objc_getAssociatedObject(self, &Constants.isSwizzledKey) as? Bool ?? false
}
set {
objc_setAssociatedObject(self, &Constants.isSwizzledKey, newValue, .OBJC_ASSOCIATION_COPY)
}
}
func clearEmptyStateView() {
emptyStateView?.removeFromSuperview()
emptyStateView = nil
}
}
// MARK: - Extending table and collection views to conform to DataDisplaying
extension UITableView: DataDisplaying {
func count(for section: Int) -> Int {
return dataSource?.tableView(self, numberOfRowsInSection: section) ?? 0
}
@objc func ob_reloadData() {
defer {
showEmptyState = isEmpty
}
clearEmptyStateView()
return ob_reloadData()
}
@objc func ob_endUpdates() {
clearEmptyStateView()
showEmptyState = isEmpty
return ob_endUpdates()
}
static let originalMethods = [
#selector(UITableView.reloadData),
#selector(UITableView.endUpdates)
]
static let swizzledMethods = [
#selector(UITableView.ob_reloadData),
#selector(UITableView.ob_endUpdates)
]
}
extension UICollectionView: DataDisplaying {
func count(for section: Int) -> Int {
return dataSource?.collectionView(self, numberOfItemsInSection: section) ?? 0
}
@objc func ob_reloadData() {
defer {
showEmptyState = isEmpty
}
clearEmptyStateView()
return ob_reloadData()
}
@objc func ob_performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)? = nil) {
return ob_performBatchUpdates(updates) { [unowned self] ok in
completion?(ok)
self.clearEmptyStateView()
self.showEmptyState = self.isEmpty
}
}
static let originalMethods = [
#selector(UICollectionView.reloadData),
#selector(UICollectionView.performBatchUpdates(_:completion:))
]
static let swizzledMethods = [
#selector(UICollectionView.ob_reloadData),
#selector(UICollectionView.ob_performBatchUpdates(_:completion:))
]
}
|
5af6a623ee78fcb3652c0d64dd064011
| 28.142857 | 120 | 0.598793 | false | false | false | false |
superk589/CGSSGuide
|
refs/heads/master
|
DereGuide/Model/CGSSSkill.swift
|
mit
|
2
|
//
// CGSSSkill.swift
// CGSSFoundation
//
// Created by zzk on 16/6/14.
// Copyright © 2016 zzk. All rights reserved.
//
import Foundation
import SwiftyJSON
fileprivate let skillDescriptions = [
1: NSLocalizedString("使所有PERFECT音符获得 %d%% 的分数加成", comment: "技能描述"),
2: NSLocalizedString("使所有PERFECT/GREAT音符获得 %d%% 的分数加成", comment: "技能描述"),
3: NSLocalizedString("使所有PERFECT/GREAT/NICE音符获得 %d%% 的分数加成", comment: "技能描述"),
4: NSLocalizedString("获得额外的 %d%% 的COMBO加成", comment: "技能描述"),
5: NSLocalizedString("使所有GREAT音符改判为PERFECT", comment: "技能描述"),
6: NSLocalizedString("使所有GREAT/NICE音符改判为PERFECT", comment: "技能描述"),
7: NSLocalizedString("使所有GREAT/NICE/BAD音符改判为PERFECT", comment: "技能描述"),
8: NSLocalizedString("所有音符改判为PERFECT", comment: "技能描述"),
9: NSLocalizedString("使NICE音符不会中断COMBO", comment: "技能描述"),
10: NSLocalizedString("使BAD/NICE音符不会中断COMBO", comment: "技能描述"),
11: NSLocalizedString("使你的COMBO不会中断", comment: "技能描述"),
12: NSLocalizedString("使你的生命不会减少", comment: "技能描述"),
13: NSLocalizedString("使所有音符恢复你 %d 点生命", comment: "技能描述"),
14: NSLocalizedString("消耗 %2$d 生命,PERFECT音符获得 %1$d%% 的分数加成,并且NICE/BAD音符不会中断COMBO", comment: "技能描述"),
15: NSLocalizedString("使所有PERFECT音符获得 %d%% 的分数加成,且使PERFECT判定区间的时间范围缩小", comment: ""),
16: NSLocalizedString("重复发动上一个其他偶像发动过的技能", comment: ""),
17: NSLocalizedString("使所有PERFECT音符恢复你 %d 点生命", comment: "技能描述"),
18: NSLocalizedString("使所有PERFECT/GREAT音符恢复你 %d 点生命", comment: "技能描述"),
19: NSLocalizedString("使所有PERFECT/GREAT/NICE音符恢复你 %d 点生命", comment: "技能描述"),
20: NSLocalizedString("使当前发动的分数加成和COMBO加成额外提高 %d%%,生命恢复和护盾额外恢复 1 点生命,改判范围增加一档", comment: ""),
21: NSLocalizedString("当仅有Cute偶像存在于队伍时,使所有PERFECT音符获得 %d%% 的分数加成,并获得额外的 %d%% 的COMBO加成", comment: ""),
22: NSLocalizedString("当仅有Cool偶像存在于队伍时,使所有PERFECT音符获得 %d%% 的分数加成,并获得额外的 %d%% 的COMBO加成", comment: ""),
23: NSLocalizedString("当仅有Passion偶像存在于队伍时,使所有PERFECT音符获得 %d%% 的分数加成,并获得额外的 %d%% 的COMBO加成", comment: ""),
24: NSLocalizedString("获得额外的 %d%% 的COMBO加成,并使所有PERFECT音符恢复你 %d 点生命", comment: ""),
25: NSLocalizedString("获得额外的COMBO加成,当前生命值越高加成越高", comment: ""),
26: NSLocalizedString("当Cute、Cool和Passion偶像存在于队伍时,使所有PERFECT音符获得 %1$d%% 的分数加成/恢复你 %3$d 点生命,并获得额外的 %2$d%% 的COMBO加成", comment: ""),
27: NSLocalizedString("使所有PERFECT音符获得 %d%% 的分数加成,并获得额外的 %d%% 的COMBO加成", comment: ""),
28: NSLocalizedString("使所有PERFECT音符获得 %d%% 的分数加成,如果音符类型是长按则改为提高 %d%%", comment: ""),
29: NSLocalizedString("使所有PERFECT音符获得 %d%% 的分数加成,如果音符类型是滑块则改为提高 %d%%", comment: ""),
31: NSLocalizedString("获得额外的 %d%% 的COMBO加成,并使所有GREAT/NICE音符改判为PERFECT", comment: ""),
]
fileprivate let intervalClause = NSLocalizedString("每 %d 秒,", comment: "")
fileprivate let probabilityClause = NSLocalizedString("有 %@%% 的几率", comment: "")
fileprivate let lengthClause = NSLocalizedString(",持续 %@ 秒。", comment: "")
extension CGSSSkill {
private var effectValue: Int {
var effectValue = value!
if [1, 2, 3, 4, 14, 15, 21, 22, 23, 24, 26, 27, 28, 29, 31].contains(skillTypeId) {
effectValue -= 100
} else if [20].contains(skillTypeId) {
// there is only one possibility: 20% up for combo bonus and perfect bonus, using fixed value here instead of reading it from database table skill_boost_type. if more possiblities are added to the game, fix here.
effectValue = 20
}
return effectValue
}
private var effectValue2: Int {
var effectValue2 = value2!
if [21, 22, 23, 26, 27, 28, 29].contains(skillTypeId) {
effectValue2 -= 100
}
return effectValue2
}
private var effectValue3: Int {
return value3
}
private var effectExpalin: String {
if skillTypeId == 14 {
return String.init(format: skillDescriptions[skillTypeId] ?? NSLocalizedString("未知", comment: ""), effectValue, skillTriggerValue)
} else {
return String.init(format: skillDescriptions[skillTypeId] ?? NSLocalizedString("未知", comment: ""), effectValue, effectValue2, effectValue3)
}
}
private var intervalExplain: String {
return String.init(format: intervalClause, condition)
}
@nonobjc func getLocalizedExplainByRange(_ range: CountableClosedRange<Int>) -> String {
let probabilityRangeString = String(format: "%.2f ~ %.2f", Double(procChanceOfLevel(range.lowerBound)) / 100, Double(procChanceOfLevel(range.upperBound)) / 100)
let probabilityExplain = String.init(format: probabilityClause, probabilityRangeString)
let lengthRangeString = String(format: "%.2f ~ %.2f", Double(effectLengthOfLevel(range.lowerBound)) / 100, Double(effectLengthOfLevel(range.upperBound)) / 100)
let lengthExplain = String(format: lengthClause, lengthRangeString)
return intervalExplain + probabilityExplain + effectExpalin + lengthExplain
}
@nonobjc func getLocalizedExplainByLevel(_ level: Int) -> String {
let probabilityRangeString = String(format: "%@", (Decimal(procChanceOfLevel(level)) / 100).description)
let probabilityExplain = String.init(format: probabilityClause, probabilityRangeString)
let lengthRangeString = String(format: "%@", (Decimal(effectLengthOfLevel(level)) / 100).description)
let lengthExplain = String.init(format: lengthClause, lengthRangeString)
return intervalExplain + probabilityExplain + effectExpalin + lengthExplain
}
var skillFilterType: CGSSSkillTypes {
return CGSSSkillTypes(typeID: skillTypeId)
}
var descriptionShort: String {
return "\(condition!)s/\(procTypeShort)/\(skillFilterType.description)"
}
// 在计算触发几率和持续时间时 要在取每等级增量部分进行一次向下取整
func procChanceOfLevel(_ lv: Int) -> Int {
if let p = procChance {
let p1 = Float(p[1])
let p0 = Float(p[0])
return wpcap(x :(p1 - p0) / 9 * Float(lv - 1) + p0)
} else {
return 0
}
}
func wpcap(x: Float) -> Int {
var n = Int(x)
let n10 = Int(x * 10)
if (n10 % 10 != 0) {
n += 1
}
return n
}
func effectLengthOfLevel(_ lv: Int) -> Int {
if let e = effectLength {
let e1 = Float(e[1])
let e0 = Float(e[0])
return wpcap(x: (e1 - e0) / 9 * Float(lv - 1) + e0)
} else {
return 0
}
}
var procTypeShort: String {
switch maxChance {
case 6000:
return NSLocalizedString("高", comment: "技能触发几率的简写")
case 5250:
return NSLocalizedString("中", comment: "技能触发几率的简写")
case 4500:
return NSLocalizedString("低", comment: "技能触发几率的简写")
default:
return NSLocalizedString("其他", comment: "通用, 通常不会出现, 为未知字符预留")
}
}
var procType: CGSSProcTypes {
switch maxChance {
case 6000:
return .high
case 5250:
return .middle
case 4500:
return .low
default:
return .none
}
}
var conditionType: CGSSConditionTypes {
switch condition {
case 4:
return .c4
case 6:
return .c6
case 7:
return .c7
case 9:
return .c9
case 11:
return .c11
case 13:
return .c13
default:
return .other
}
}
}
class CGSSSkill: CGSSBaseModel {
var condition: Int!
var cutinType: Int!
var effectLength: [Int]!
var explain: String!
var explainEn: String!
var id: Int!
var judgeType: Int!
var maxChance: Int!
var maxDuration: Int!
var procChance: [Int]!
var skillName: String!
var skillTriggerType: Int!
var skillTriggerValue: Int!
var skillType: String!
var value: Int!
var skillTypeId: Int!
var value2: Int!
var value3: Int!
/**
* Instantiate the instance using the passed json values to set the properties values
*/
init(fromJson json: JSON!) {
super.init()
if json == JSON.null {
return
}
condition = json["condition"].intValue
cutinType = json["cutin_type"].intValue
effectLength = [Int]()
let effectLengthArray = json["effect_length"].arrayValue
for effectLengthJson in effectLengthArray {
effectLength.append(effectLengthJson.intValue)
}
explain = json["explain"].stringValue
explainEn = json["explain_en"].stringValue
id = json["id"].intValue
judgeType = json["judge_type"].intValue
maxChance = json["max_chance"].intValue
maxDuration = json["max_duration"].intValue
procChance = [Int]()
let procChanceArray = json["proc_chance"].arrayValue
for procChanceJson in procChanceArray {
procChance.append(procChanceJson.intValue)
}
skillName = json["skill_name"].stringValue
skillTriggerType = json["skill_trigger_type"].intValue
skillTriggerValue = json["skill_trigger_value"].intValue
skillType = json["skill_type"].stringValue
if skillType == "" {
skillType = NSLocalizedString("未知", comment: "")
}
value = json["value"].intValue
value2 = json["value_2"].intValue
value3 = json["value_3"].intValue
skillTypeId = json["skill_type_id"].intValue
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
condition = aDecoder.decodeObject(forKey: "condition") as? Int
cutinType = aDecoder.decodeObject(forKey: "cutin_type") as? Int
effectLength = aDecoder.decodeObject(forKey: "effect_length") as? [Int]
explain = aDecoder.decodeObject(forKey: "explain") as? String
explainEn = aDecoder.decodeObject(forKey: "explain_en") as? String
id = aDecoder.decodeObject(forKey: "id") as? Int
judgeType = aDecoder.decodeObject(forKey: "judge_type") as? Int
maxChance = aDecoder.decodeObject(forKey: "max_chance") as? Int
maxDuration = aDecoder.decodeObject(forKey: "max_duration") as? Int
procChance = aDecoder.decodeObject(forKey: "proc_chance") as? [Int]
skillName = aDecoder.decodeObject(forKey: "skill_name") as? String
skillTriggerType = aDecoder.decodeObject(forKey: "skill_trigger_type") as? Int
skillTriggerValue = aDecoder.decodeObject(forKey: "skill_trigger_value") as? Int
skillType = aDecoder.decodeObject(forKey: "skill_type") as? String ?? NSLocalizedString("未知", comment: "")
value = aDecoder.decodeObject(forKey: "value") as? Int
skillTypeId = aDecoder.decodeObject(forKey: "skill_type_id") as? Int
value2 = aDecoder.decodeObject(forKey: "value_2") as? Int
value3 = aDecoder.decodeObject(forKey: "value_3") as? Int
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
override func encode(with aCoder: NSCoder)
{
super.encode(with: aCoder)
if condition != nil {
aCoder.encode(condition, forKey: "condition")
}
if cutinType != nil {
aCoder.encode(cutinType, forKey: "cutin_type")
}
if effectLength != nil {
aCoder.encode(effectLength, forKey: "effect_length")
}
if explain != nil {
aCoder.encode(explain, forKey: "explain")
}
if explainEn != nil {
aCoder.encode(explainEn, forKey: "explain_en")
}
if id != nil {
aCoder.encode(id, forKey: "id")
}
if judgeType != nil {
aCoder.encode(judgeType, forKey: "judge_type")
}
if maxChance != nil {
aCoder.encode(maxChance, forKey: "max_chance")
}
if maxDuration != nil {
aCoder.encode(maxDuration, forKey: "max_duration")
}
if procChance != nil {
aCoder.encode(procChance, forKey: "proc_chance")
}
if skillName != nil {
aCoder.encode(skillName, forKey: "skill_name")
}
if skillTriggerType != nil {
aCoder.encode(skillTriggerType, forKey: "skill_trigger_type")
}
if skillTriggerValue != nil {
aCoder.encode(skillTriggerValue, forKey: "skill_trigger_value")
}
if skillType != nil {
aCoder.encode(skillType, forKey: "skill_type")
}
if value != nil {
aCoder.encode(value, forKey: "value")
}
if skillTypeId != nil {
aCoder.encode(skillTypeId, forKey: "skill_type_id")
}
if value2 != nil {
aCoder.encode(value2, forKey: "value_2")
}
if value3 != nil {
aCoder.encode(value3, forKey: "value_3")
}
}
}
|
cc5476980c4b82be4289332abd7b5a3f
| 36.887931 | 224 | 0.610087 | false | false | false | false |
orta/eidolon
|
refs/heads/master
|
KioskTests/KioskTests.swift
|
mit
|
1
|
class KioskTests {}
import UIKit
var sharedInstances = Dictionary<String, AnyObject>()
public extension UIStoryboard {
public class func fulfillment() -> UIStoryboard {
// This will ensure that a storyboard instance comes out of the testing bundle
// instead of the MainBundle.
return UIStoryboard(name: "Fulfillment", bundle: NSBundle(forClass: KioskTests.self))
}
public func viewControllerWithID(identifier:ViewControllerStoryboardIdentifier) -> UIViewController {
let id = identifier.rawValue
// Uncomment for experimental caching.
//
// if let cached: NSData = sharedInstances[id] as NSData {
// return NSKeyedUnarchiver.unarchiveObjectWithData(cached) as UIViewController
//
// } else {
let vc = self.instantiateViewControllerWithIdentifier(id) as UIViewController
// sharedInstances[id] = NSKeyedArchiver.archivedDataWithRootObject(vc);
return vc;
// }
}
}
|
1e10e84643ab40875b2a34e72b7e9288
| 31.096774 | 105 | 0.687437 | false | true | false | false |
OneBusAway/onebusaway-iphone
|
refs/heads/develop
|
Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobufPluginLibrary/Array+Extensions.swift
|
apache-2.0
|
4
|
// Sources/SwiftProtobufPluginLibrary/Array+Extensions.swift - Additions to Arrays
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
import Foundation
extension Array {
/// Like map, but calls the transform with the index and value.
///
/// NOTE: It would seem like doing:
/// return self.enumerated().map {
/// return try transform($0.index, $0.element)
/// }
/// would seem like a simple thing to avoid extension. However as of Xcode 8.3.2
/// (Swift 3.1), building/running 5000000 interation test (macOS) of the differences
/// are rather large -
/// Release build:
/// Using enumerated: 3.694987967
/// Using enumeratedMap: 0.961241992
/// Debug build:
/// Using enumerated: 20.038512905
/// Using enumeratedMap: 8.521299144
func enumeratedMap<T>(_ transform: (Int, Element) throws -> T) rethrows -> [T] {
var i: Int = -1
return try map {
i += 1
return try transform(i, $0)
}
}
}
#if !swift(>=4.2)
extension Array {
func firstIndex(where predicate: (Element) throws -> Bool) rethrows -> Int? {
var i = self.startIndex
while i < self.endIndex {
if try predicate(self[i]) {
return i
}
self.formIndex(after: &i)
}
return nil
}
}
#endif // !swift(>=4.2)
|
ab08b6c20597f4de973cd6d2b7e402f2
| 29.288462 | 86 | 0.607619 | false | false | false | false |
rastogigaurav/mTV
|
refs/heads/master
|
mTV/mTV/ViewModels/MovieListViewModel.swift
|
mit
|
1
|
//
// MovieListViewModel.swift
// mTV
//
// Created by Gaurav Rastogi on 6/25/17.
// Copyright © 2017 Gaurav Rastogi. All rights reserved.
//
import UIKit
class MovieListViewModel: NSObject {
var movies:[Movie] = []{
willSet{
filteredMovies = newValue
}
}
var section:MovieSections
var filteredMovies:[Movie] = []
var startDateIndex:Int = years_1950_2017.count-18
var endDateIndex:Int = years_1950_2017.count-1
var displayMovies:DisplayMoviesProtocol!
init(with displayList:DisplayMoviesProtocol, selectedSection section:MovieSections){
self.section = section
self.displayMovies = displayList
}
func fetchMovies(withPage page:Int, reload:@escaping (_ totalMovies:Int?)->Void){
self.displayMovies.displayMovies(forSection: self.section, withPage: page) {
[unowned self] (total,movies,section) in
if let list = movies{
self.movies.append(contentsOf: list)
}
reload(total)
}
}
func filter(basedOn startIndex:Int, endIndex:Int, reload:@escaping ()->())->Void{
self.displayMovies.filter(movieList: movies, startYear: years_1950_2017[startIndex], endYear: years_1950_2017[endIndex]) {[unowned self] (filteredMovies) in
self.startDateIndex = startIndex
self.endDateIndex = endIndex
self.filteredMovies = filteredMovies
reload()
}
}
func numberOfItemsInSection(section:Int)->Int{
return self.filteredMovies.count
}
func titleAndReleaseYearForMovie(at indexPath:IndexPath)->String?{
if let mTitle = self.filteredMovies[indexPath.row].title{
return (mTitle + " (" + String(self.filteredMovies[indexPath.row].releaseYear) + ")")
}
return nil
}
func releaseDateForMovie(at indexPath:IndexPath)->String?{
if let releaseDate = self.filteredMovies[indexPath.row].releaseDate{
return releaseDate
}
return nil
}
func posterImageUrlForMovie(at indexPath:IndexPath)->String?{
if let posterImageUrl = self.filteredMovies[indexPath.row].posterPathURL(){
return posterImageUrl
}
return nil
}
func movieId(forMovieAt indexPath:IndexPath)->Int{
return (self.filteredMovies[indexPath.row]).id!
}
func titel()->String?{
switch self.section {
case .topRated:
return "Top Rated"
case .upcoming:
return "Upcoming"
case .nowPlaying:
return "Now Playing"
case .popular:
return "Popular"
default:
return nil
}
}
}
|
bb946dd2a81844ea2e1527dceab82889
| 28.326316 | 164 | 0.609117 | false | false | false | false |
pozi119/Valine
|
refs/heads/master
|
Valine/Valine.swift
|
gpl-2.0
|
1
|
//
// Valine.swift
// Valine
//
// Created by Valo on 15/12/23.
// Copyright © 2015年 Valo. All rights reserved.
//
import UIKit
public func pageHop(hopMethod:HopMethod,hop:Hop)->AnyObject?{
if hop.controller != nil {
Utils.setParameters(hop.parameters, forObject:hop.controller!)
}
switch hopMethod{
case .Push:
Manager.sharedManager.currentNaviController?.pushViewController(hop.controller!, animated:hop.animated)
if(hop.removeVCs?.count > 0){
var existVCs = Manager.sharedManager.currentNaviController?.viewControllers
for var idx = 0; idx < existVCs?.count; ++idx{
let vc = existVCs![idx]
let vcName = NSStringFromClass(vc.classForKeyedArchiver!)
for tmpName in hop.removeVCs!{
if vcName.containsString(tmpName){
existVCs?.removeAtIndex(idx)
}
}
}
Manager.sharedManager.currentNaviController?.viewControllers = existVCs!
}
case .Pop:
if hop.controller == nil{
Manager.sharedManager.currentNaviController?.popViewControllerAnimated(hop.animated)
}
else{
var destVC = hop.controller
let existVCs = Manager.sharedManager.currentNaviController?.viewControllers
for vc in existVCs!{
let vcName = NSStringFromClass(vc.classForKeyedArchiver!)
if vcName.containsString(hop.aController!){
destVC = vc
if hop.parameters != nil{
Utils.setParameters(hop.parameters, forObject:destVC!)
}
break
}
}
Manager.sharedManager.currentNaviController?.popToViewController(destVC!, animated: hop.animated)
}
case .Present:
var sourceVC:UIViewController
if hop.sourceInNav && Manager.sharedManager.currentNaviController != nil{
sourceVC = Manager.sharedManager.currentNaviController!
}
else{
sourceVC = Manager.sharedManager.currentViewController!
}
var destVC = hop.controller
if hop.destInNav{
if destVC!.navigationController != nil{
destVC = destVC!.navigationController!
}
else{
destVC = UINavigationController(rootViewController: destVC!)
}
}
if hop.alpha < 1.0 && hop.alpha > 0.0 {
hop.controller!.view.alpha = hop.alpha
}
sourceVC.presentViewController(destVC!, animated:hop.animated, completion:hop.completion)
case .Dismiss:
Manager.sharedManager.currentViewController?.dismissViewControllerAnimated(hop.animated, completion:hop.completion)
}
return nil
}
|
30a7c49d9194098f6a70910cd5fd0cd1
| 34.313253 | 123 | 0.582054 | false | false | false | false |
yarshure/Surf
|
refs/heads/UIKitForMac
|
Surf-Mac/RequestsBasic.swift
|
bsd-3-clause
|
1
|
//
// RequestsBasic.swift
// XDataService
//
// Created by yarshure on 2018/1/17.
// Copyright © 2018年 A.BIG.T. All rights reserved.
//
import Cocoa
import SwiftyJSON
import NetworkExtension
import SFSocket
import XProxy
open class RequestsBasic: NSViewController,NSTableViewDelegate,NSTableViewDataSource {
public var results:[SFRequestInfo] = []
public var dbURL:URL?
@IBOutlet public weak var tableView:NSTableView!
public override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) {
print("load....")
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
@objc required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
print("load coder....")
}
public func processData(data:Data) {
let oldresults = results
results.removeAll()
let obj = try! JSON.init(data: data)
if obj.error == nil {
let count = obj["count"]
if count.intValue != 0 {
let result = obj["data"]
if result.type == .array {
for item in result {
let json = item.1
let r = SFRequestInfo.init(rID: 0)
r.map(json)
let rr = oldresults.filter({ info -> Bool in
if info.reqID == r.reqID && info.subID == r.subID {
return true
}
return false
})
if rr.isEmpty {
results.append(r)
r.speedtraffice = r.traffice
}else {
let old = rr.first!
if r.traffice.rx > old.traffice.rx {
//sub id reset
r.speedtraffice.rx = r.traffice.rx - old.traffice.rx
}
if r.traffice.tx > old.traffice.tx{
//?
r.speedtraffice.tx = r.traffice.tx - old.traffice.tx
}
results.append(r)
}
}
}
if results.count > 0 {
results.sort(by: { $0.reqID < $1.reqID })
}
}
}
tableView.reloadData()
}
public func numberOfRows(in tableView: NSTableView) -> Int {
return results.count
}
public func tableView(_ tableView: NSTableView
, objectValueFor tableColumn: NSTableColumn?
, row: Int) -> Any? {
let result = results[row]
if (tableColumn?.identifier)!.rawValue == "Icon" {
switch result.rule.policy{
case .Direct:
return NSImage(named:"NSStatusPartiallyAvailable")
case .Proxy:
return NSImage(named:"NSStatusAvailable")
case .Reject:
return NSImage(named:"NSStatusUnavailable")
default:
break
}
}
return nil
}
public func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let iden = tableColumn!.identifier.rawValue
let result = results[row]
let cell:NSTableCellView = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: self) as! NSTableCellView
if iden == "Index" {
cell.textField?.stringValue = "\(result.reqID) \(result.subID)"
}else if iden == "App" {
cell.textField?.attributedStringValue = result.detailString()
}else if iden == "Url" {
if result.mode == .HTTP {
if let u = URL(string: result.url){
if let h = u.host {
cell.textField?.stringValue = h
}else {
cell.textField?.stringValue = u.description
}
}else {
if let req = result.reqHeader{
cell.textField?.stringValue = req.Host
}
}
}else {
cell.textField?.stringValue = result.url
}
}else if iden == "Rule" {
}else if iden == "Date" {
cell.textField?.stringValue = result.dataDesc(result.sTime)
}else if iden == "Status" {
let n = Date()
let a = result.activeTime
let idle = n.timeIntervalSince(a)
if idle > 1 {
cell.textField?.stringValue = "idle \(Int(idle))"
}else {
cell.textField?.stringValue = result.status.description
}
}else if iden == "Policy" {
let rule = result.rule
cell.textField?.stringValue = rule.policy.description + " (" + rule.type.description + ":" + rule.name + ")"
//(\(rule.type.description):\(rule.name) ProxyName:\(rule.proxyName))"
//cell.textField?.stringValue = "Demo"//result.status.description
}else if iden == "Up" {
let tx = result.speedtraffice.tx
cell.textField?.stringValue = self.toString(x: tx,label:"",speed: true)
}else if iden == "Down" {
let rx = result.speedtraffice.rx
cell.textField?.stringValue = self.toString(x: rx,label:"",speed: true)
}else if iden == "Method" {
if result.mode == .TCP{
cell.textField?.stringValue = "TCP"
}else {
if let req = result.reqHeader {
if req.method == .CONNECT {
cell.textField?.stringValue = "HTTPS"
}else {
cell.textField?.stringValue = req.method.rawValue
}
}
}
}else if iden == "Icon" {
switch result.rule.policy{
case .Direct:
cell.imageView?.objectValue = NSImage(named:"NSStatusPartiallyAvailable")
case .Proxy:
cell.imageView?.objectValue = NSImage(named:"NSStatusAvailable")
case .Reject:
cell.imageView?.objectValue = NSImage(named:"NSStatusUnavailable")
default:
break
}
}else if iden == "DNS" {
if !result.rule.ipAddress.isEmpty {
cell.textField?.stringValue = result.rule.ipAddress
}else {
if !result.remoteIPaddress.isEmpty{
let x = result.remoteIPaddress.components(separatedBy: " ")
if x.count > 1 {
cell.textField?.stringValue = x.last!
}else {
cell.textField?.stringValue = x.first!
}
}else {
if !result.rule.name.isEmpty {
cell.textField?.stringValue = result.rule.name
}else {
let x = "NONE"
let s = NSMutableAttributedString(string:x )
let r = NSMakeRange(0, 4);
s.addAttributes([NSAttributedString.Key.foregroundColor:NSColor.red,NSAttributedString.Key.backgroundColor:NSColor.white], range: r)
cell.textField?.attributedStringValue = s
}
}
}
}
if row % 2 == 0 {
cell.backgroundStyle = .dark
}else {
cell.backgroundStyle = .light
}
return cell
}
public func toString(x:UInt,label:String,speed:Bool) ->String {
var s = "/s"
if !speed {
s = ""
}
if x < 1024{
return label + " \(x) B" + s
}else if x >= 1024 && x < 1024*1024 {
return label + String(format: "%0.2f KB", Float(x)/1024.0) + s
}else if x >= 1024*1024 && x < 1024*1024*1024 {
return label + String(format: "%0.2f MB", Float(x)/1024/1024) + s
}else {
return label + String(format: "%0.2f GB", Float(x)/1024/1024/1024) + s
}
}
}
|
2cf343369c6ce3041bf0521fc9278bbf
| 34.419608 | 156 | 0.443756 | false | false | false | false |
BridgeTheGap/KRStackView
|
refs/heads/master
|
Example/KRStackView/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// KRStackView
//
// Created by Joshua Park on 07/13/2016.
// Copyright (c) 2016 Joshua Park. All rights reserved.
//
import UIKit
import KRStackView
private var Screen: UIScreen {
return UIScreen.main
}
private var DEFAULT_FRAME = CGRect(x: 20.0, y: 20.0, width: 148.0, height: 400.0)
class ViewController: UIViewController {
@IBOutlet weak var stackView: KRStackView!
@IBOutlet weak var viewRed: UIView!
@IBOutlet weak var viewYellow: UIView!
@IBOutlet weak var viewBlue: UIView!
@IBOutlet weak var viewControls: UIView!
@IBOutlet weak var switchEnabled: UISwitch!
@IBOutlet weak var controlDirection: UISegmentedControl!
@IBOutlet weak var switchShouldWrap: UISwitch!
@IBOutlet weak var controlAlignment: UISegmentedControl!
@IBOutlet weak var sliderTop: UISlider!
@IBOutlet weak var sliderRight: UISlider!
@IBOutlet weak var sliderBottom: UISlider!
@IBOutlet weak var sliderLeft: UISlider!
@IBOutlet weak var switchIndividual: UISwitch!
@IBOutlet weak var controlView: UISegmentedControl!
@IBOutlet weak var sliderWidth: UISlider!
@IBOutlet weak var sliderHeight: UISlider!
@IBOutlet weak var sliderSpacing: UISlider!
@IBOutlet weak var sliderOffset: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
stackView.enabled = false
viewControls.frame.origin.x = Screen.bounds.width
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backgroundAction(_ sender: AnyObject) {
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 300.0, initialSpringVelocity: 4.0, options: [], animations: {
if self.viewControls.frame.origin.x == Screen.bounds.width {
self.viewControls.frame.origin.x = 401.0
} else {
self.viewControls.frame.origin.x = Screen.bounds.width
}
}, completion: nil)
}
// MARK: - Controls
@IBAction func enabledAction(_ sender: AnyObject) {
let enabled = (sender as! UISwitch).isOn
stackView.enabled = enabled
if !enabled {
switchIndividual.isOn = false
switchIndividual.sendActions(for: .valueChanged)
}
for view in viewControls.subviews {
if [switchEnabled, controlView, sliderWidth, sliderHeight, sliderSpacing, sliderOffset].contains(view) { continue }
if let control = view as? UIControl { control.isEnabled = enabled }
}
stackView.setNeedsLayout()
}
@IBAction func directionAction(_ sender: AnyObject) {
stackView.frame = DEFAULT_FRAME
if stackView.direction == .vertical { stackView.direction = .horizontal }
else { stackView.direction = .vertical }
stackView.setNeedsLayout()
}
@IBAction func wrapAction(_ sender: AnyObject) {
stackView.frame = DEFAULT_FRAME
stackView.shouldWrap = (sender as! UISwitch).isOn
stackView.setNeedsLayout()
}
@IBAction func alignmentAction(_ sender: AnyObject) {
stackView.frame = DEFAULT_FRAME
guard let control = sender as? UISegmentedControl else { return }
switch control.selectedSegmentIndex {
case 0: stackView.alignment = .origin
case 1: stackView.alignment = .center
default: stackView.alignment = .endPoint
}
stackView.setNeedsLayout()
}
@IBAction func topInsetAction(_ sender: AnyObject) {
stackView.frame = DEFAULT_FRAME
stackView.insets.top = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
@IBAction func rightInsetAction(_ sender: AnyObject) {
stackView.frame = DEFAULT_FRAME
stackView.insets.right = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
@IBAction func bottomInsetAction(_ sender: AnyObject) {
stackView.frame = DEFAULT_FRAME
stackView.insets.bottom = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
@IBAction func leftInsetAction(_ sender: AnyObject) {
stackView.frame = DEFAULT_FRAME
stackView.insets.left = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
@IBAction func individualAction(_ sender: AnyObject) {
let enabled = (sender as! UISwitch).isOn
controlView.isEnabled = enabled
sliderWidth.isEnabled = enabled
sliderHeight.isEnabled = enabled
sliderSpacing.isEnabled = enabled && controlView.selectedSegmentIndex != 2
sliderOffset.isEnabled = enabled
stackView.itemSpacing = enabled ? [8.0, 8.0] : nil
stackView.itemOffset = enabled ? [0.0, 0.0, 0.0] : nil
}
@IBAction func viewSelectAction(_ sender: AnyObject) {
let index = (sender as! UISegmentedControl).selectedSegmentIndex
let view = [viewRed, viewYellow, viewBlue][index]!
sliderWidth.value = Float(view.frame.width)
sliderHeight.value = Float(view.frame.height)
sliderSpacing.isEnabled = switchIndividual.isOn && controlView.selectedSegmentIndex != 2
sliderSpacing.value = index != 2 ? Float(stackView.itemSpacing![index]) : sliderSpacing.value
sliderOffset.value = Float(stackView.itemOffset![index])
}
@IBAction func widthAction(_ sender: AnyObject) {
let index = controlView.selectedSegmentIndex
let view = [viewRed, viewYellow, viewBlue][index]!
view.frame.size.width = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
@IBAction func heightAction(_ sender: AnyObject) {
let index = controlView.selectedSegmentIndex
let view = [viewRed, viewYellow, viewBlue][index]
view?.frame.size.height = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
@IBAction func spacingAction(_ sender: AnyObject) {
let index = controlView.selectedSegmentIndex
stackView.itemSpacing![index] = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
@IBAction func offsetAction(_ sender: AnyObject) {
let index = controlView.selectedSegmentIndex
stackView.itemOffset![index] = CGFloat((sender as! UISlider).value)
stackView.setNeedsLayout()
}
}
|
3e9a15efd1abdc783394e297d561cb3d
| 33.739583 | 140 | 0.647826 | false | false | false | false |
wumbo/Wumbofant
|
refs/heads/master
|
Wumbofant/CSVLoader.swift
|
bsd-3-clause
|
1
|
//
// CSVLoader.swift
// Wumbofant
//
// Created by Simon Crequer on 13/07/15.
// Copyright (c) 2015 Simon Crequer. All rights reserved.
//
import Cocoa
import CoreData
class CSVLoader {
var url: NSURL
init(url: NSURL) {
self.url = url
loadEntries()
}
lazy var entries: [LogEntry] = {
let managedObjectContext = (NSApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "LogEntry")
let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as! [LogEntry]
return fetchResults
}()
/**
Loads the CSV file given by url and parses it into an array of LogEntry objects
*/
func loadEntries() {
var error: NSError?
var contents: String? = String(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: &error)
if error != nil {
println("Error fetching file contents: \(error)")
} else if contents != nil {
var lines: [String] = contents!.componentsSeparatedByString("\r\n")
if lines[0] == "Product,Project,Iteration,Story,Task,Comment,User,Date,Spent effort (hours)" {
lines.removeAtIndex(0)
for line in lines {
let items = readLine(line)
let dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm"
let date: NSDate = dateFormatter.dateFromString(items[7])!
// Create a CoreData entity for the LogEntry that can be referenced from
// anywhere in the application
let entry = NSEntityDescription.insertNewObjectForEntityForName("LogEntry", inManagedObjectContext: (NSApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!) as! LogEntry
entry.product = items[0]
entry.project = items[1]
entry.iteration = items[2]
entry.story = items[3]
entry.task = items[4]
entry.comment = items[5]
entry.user = items[6]
entry.date = date
entry.spentEffort = NSNumber(float: NSString(string: items[8]).floatValue)
}
}
}
}
/**
Parses a line from the CSV file into an array of Strings. Rather than treating
every comma as a seperator, it first checks if a comma is inside "quotation
marks" and only treats it as a seperator if it isn't.
:param: line The line of CSV data to be parsed
:returns: An array of 9 Strings containing each part of the LogEntry
*/
private func readLine(line: String) -> [String] {
var values: [String] = ["","","","","","","","",""]
var index: Int = 0
var quoteReached: Bool = false
for c in line {
if c != "," && c != "\"" {
values[index].append(c)
} else if c == "\"" {
if !quoteReached {
quoteReached = true
} else {
quoteReached = false
}
} else if c == "," {
if quoteReached {
values[index].append(c)
} else {
index++
}
}
}
return values
}
}
|
504b7655f7a0b2a321b49325fba4a680
| 33.45283 | 216 | 0.523692 | false | false | false | false |
kyungmin/pigeon
|
refs/heads/master
|
Pigeon/Pigeon/FrontEditViewController.swift
|
mit
|
1
|
//
// FrontEditViewController.swift
// Pigeon
//
// Created by Kyungmin Kim on 3/17/15.
// Copyright (c) 2015 Kyungmin Kim. All rights reserved.
//
import UIKit
class FrontEditViewController: UIViewController, UIViewControllerTransitioningDelegate, UIGestureRecognizerDelegate {
@IBOutlet weak var frontBackground: UIImageView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var buttonGroup: UIView!
var photoScale: CGFloat! = 1
var labelScale: CGFloat! = 1
var translation: CGPoint! = CGPoint(x: 0.0, y: 0.0)
var location: CGPoint! = CGPoint(x: 0.0, y: 0.0)
var originalImageFrame: CGRect!
var originalImageCenter: CGPoint!
var currentSelection: AnyObject!
var imageTransition: ImageTransition!
var textField: UITextField!
var newSticker: UIImageView!
var stickerNames: [String]!
var segues: [String!] = []
var originalImageY: CGFloat!
//create a variable to catch the image passing from the previous view controller
var photoImage:UIImage!
override func viewDidLoad() {
super.viewDidLoad()
originalImageY = scrollView.center.y
//assign selected image to imageView
imageView.image = photoImage
imageView.contentMode = UIViewContentMode.ScaleAspectFill
originalImageFrame = imageView.frame
originalImageCenter = imageView.center
scrollView.contentSize = imageView.frame.size
segues = ["fontSegue", "stickerSegue", "templateSegue"]
stickerNames = ["sticker_heart_highlighted", "sticker_plane_highlighted", "sticker_lips_highlighted"]
buttonGroup.center.y = buttonGroup.center.y + buttonGroup.frame.height
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
override func viewDidAppear(animated: Bool) {
showMenu()
}
func keyboardWillShow(notification: NSNotification!) {
var userInfo = notification.userInfo!
var kbSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue().size
var durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber
var animationDuration = durationValue.doubleValue
var curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as NSNumber
var animationCurve = curveValue.integerValue
UIView.animateWithDuration(animationDuration, delay: 0.0, options: UIViewAnimationOptions(UInt(animationCurve << 16)), animations: {
self.scrollView.center.y = 200
self.frontBackground.center.y -= (self.originalImageY - 200)
}, completion: nil)
}
func keyboardWillHide(notification: NSNotification!) {
var userInfo = notification.userInfo!
// Get the keyboard height and width from the notification
// Size varies depending on OS, language, orientation
var kbSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue().size
var durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber
var animationDuration = durationValue.doubleValue
var curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as NSNumber
var animationCurve = curveValue.integerValue
UIView.animateWithDuration(animationDuration, delay: 0.0, options: UIViewAnimationOptions(UInt(animationCurve << 16)), animations: {
self.scrollView.center.y = self.originalImageY
self.frontBackground.center.y += (self.originalImageY - 200)
}, completion: nil)
}
@IBAction func didPinchImage(sender: UIPinchGestureRecognizer) {
photoScale = sender.scale
var target = sender.view!
if (sender.state == UIGestureRecognizerState.Changed) {
target.transform = CGAffineTransformScale(target.transform, photoScale, photoScale)
} else if (sender.state == UIGestureRecognizerState.Ended) {
if (target.frame.size.width < originalImageFrame.size.width) {
target.transform = CGAffineTransformMakeScale(1, 1)
}
checkImageBoundary()
}
sender.scale = 1
}
@IBAction func didPinchLabel(sender: UIPinchGestureRecognizer) {
imageView.userInteractionEnabled = false
if sender.scale >= 1 {
labelScale = 1
} else {
labelScale = -1
}
var label = sender.view as UILabel
if (sender.state == UIGestureRecognizerState.Changed) {
label.frame.size = CGSize(width: label.frame.width + labelScale, height: label.frame.height + labelScale)
label.font = label.font.fontWithSize(label.font.pointSize + labelScale)
} else if (sender.state == UIGestureRecognizerState.Ended) {
imageView.userInteractionEnabled = true
}
sender.scale = 1
}
@IBAction func didPanImage(sender: UIPanGestureRecognizer) {
translation = sender.translationInView(view)
location = sender.locationInView(view)
//println(sender.view)
if (sender.state == UIGestureRecognizerState.Began) {
originalImageCenter = imageView.center
} else if (sender.state == UIGestureRecognizerState.Changed) {
imageView.transform = CGAffineTransformScale(sender.view!.transform, photoScale, photoScale)
imageView.center = CGPoint(x: originalImageCenter.x + translation.x, y: originalImageCenter.y + translation.y)
} else if (sender.state == UIGestureRecognizerState.Ended) {
checkImageBoundary()
}
}
@IBAction func didPanLabel(sender: UIPanGestureRecognizer) {
translation = sender.translationInView(view)
var label = sender.view as UILabel
if (sender.state == UIGestureRecognizerState.Began) {
originalImageCenter = sender.view!.center
} else if (sender.state == UIGestureRecognizerState.Changed) {
label.textColor = UIColor.grayColor()
label.transform = CGAffineTransformScale(sender.view!.transform, labelScale, labelScale)
label.center = CGPoint(x: originalImageCenter.x + translation.x, y: originalImageCenter.y + translation.y)
} else if (sender.state == UIGestureRecognizerState.Ended) {
label.textColor = UIColor.whiteColor()
imageView.userInteractionEnabled = true
}
}
@IBAction func didTapLabel(sender: UIPanGestureRecognizer) {
var label = sender.view as UILabel
currentSelection = label
textField = UITextField(frame: CGRect(x: 0, y: 0, width: label.frame.width, height: label.frame.height))
label.alpha = 0
textField.center = label.center
textField.textAlignment = .Center
textField.text = label.text
textField.font = label.font
textField.textColor = UIColor.whiteColor()
scrollView.addSubview(textField)
textField.becomeFirstResponder()
textField.selectedTextRange = textField.textRangeFromPosition(textField.beginningOfDocument, toPosition: textField.endOfDocument)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
if textField != nil {
view.endEditing(true)
var label = currentSelection as UILabel
label.text = textField.text
label.alpha = 1
textField.removeFromSuperview()
}
super.touchesBegan(touches, withEvent: event)
}
func addFont(selectedFont: String) {
var newLabel = UILabel(frame: CGRectMake(0, 0, 200, 50))
newLabel.font = UIFont(name: selectedFont, size: CGFloat(20))
newLabel.text = "Your text"
newLabel.textColor = UIColor.whiteColor()
newLabel.textAlignment = .Center
newLabel.center = imageView.center
newLabel.userInteractionEnabled = true
imageView.userInteractionEnabled = false
currentSelection = newLabel
addTapGestureRecognizer(newLabel)
addPanGestureRecognizer(newLabel)
addPinchGestureRecognizer(newLabel)
scrollView.addSubview(newLabel)
}
func addStickers(selectedStickers: [NSDictionary!]) {
imageView.userInteractionEnabled = false
for sticker in selectedStickers {
var imageName = stickerNames[sticker["tag"] as Int]
var image = UIImage(named: imageName)
newSticker = UIImageView(image: image)
newSticker.center = CGPoint(x: sticker["x"] as CGFloat, y: sticker["y"] as CGFloat)
scrollView.addSubview(newSticker)
newSticker.userInteractionEnabled = true
}
}
func setTemplate(selectedWidth: CGFloat) {
UIView.animateKeyframesWithDuration(0.3, delay: 0, options: nil, animations: { () -> Void in
self.scrollView.frame.size = CGSize(width: selectedWidth, height: self.scrollView.frame.height)
}, completion: nil)
}
// scaling text
func addPinchGestureRecognizer(target :AnyObject) {
var pinchGesture = UIPinchGestureRecognizer(target: self, action: "didPinchLabel:")
pinchGesture.delegate = self
target.addGestureRecognizer(pinchGesture)
}
// editing text
func addTapGestureRecognizer(target :AnyObject) {
var tapGesture = UITapGestureRecognizer(target: self, action: "didTapLabel:")
tapGesture.delegate = self
target.addGestureRecognizer(tapGesture)
}
// moving text
func addPanGestureRecognizer(target :AnyObject) {
var panGesture = UIPanGestureRecognizer(target: self, action: "didPanLabel:")
panGesture.delegate = self
target.addGestureRecognizer(panGesture)
}
func checkImageBoundary() {
if (imageView.frame.origin.x >= 0) {
imageView.frame.origin.x = 0
}
if (imageView.frame.origin.y >= 0) {
imageView.frame.origin.y = 0
}
if (imageView.frame.origin.x < 0 && imageView.frame.origin.x + imageView.frame.size.width < scrollView.frame.width) {
imageView.frame.origin.x = imageView.frame.origin.x + (scrollView.frame.width - (imageView.frame.origin.x + imageView.frame.size.width))
}
if (imageView.frame.origin.y < 0 && imageView.frame.origin.y + imageView.frame.size.height < scrollView.frame.height) {
imageView.frame.origin.y = imageView.frame.origin.y + (scrollView.frame.height - (imageView.frame.origin.y + imageView.frame.size.height))
}
}
@IBAction func didPressMenu(sender: AnyObject) {
performSegueWithIdentifier(segues[sender.tag], sender: self)
}
@IBAction func didPressBackButton(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func didPressNextButton(sender: AnyObject) {
performSegueWithIdentifier("saveFontSegue", sender: self)
}
func showMenu() {
UIView.animateWithDuration(0.4, delay: 0.4, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.4, options: nil, animations: { () -> Void in
self.buttonGroup.center = CGPoint(x:self.buttonGroup.center.x, y: self.buttonGroup.center.y - self.buttonGroup.frame.height)
}, completion: nil)
}
func hideMenu() {
UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.4, options: nil, animations: { () -> Void in
self.buttonGroup.center = CGPoint(x:self.buttonGroup.center.x, y: self.buttonGroup.center.y + self.buttonGroup.frame.height)
}, completion: nil)
}
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?) {
imageTransition = ImageTransition()
imageTransition.duration = 0.3
var fromViewController = segue.sourceViewController as FrontEditViewController
if segue.identifier == "fontSegue" {
var toViewController = segue.destinationViewController as FontViewController
toViewController.modalPresentationStyle = UIModalPresentationStyle.Custom
toViewController.transitioningDelegate = imageTransition
} else if segue.identifier == "stickerSegue" {
var toViewController = segue.destinationViewController as StickerViewController
toViewController.modalPresentationStyle = UIModalPresentationStyle.Custom
toViewController.transitioningDelegate = imageTransition
} else if segue.identifier == "templateSegue" {
var toViewController = segue.destinationViewController as TemplateViewController
toViewController.modalPresentationStyle = UIModalPresentationStyle.Custom
toViewController.transitioningDelegate = imageTransition
} else if segue.identifier == "saveFontSegue" {
hideMenu()
var toViewController = segue.destinationViewController as FakeFrontViewController
toViewController.modalPresentationStyle = UIModalPresentationStyle.Custom
toViewController.transitioningDelegate = imageTransition
}
}
}
|
11ad97524b4a069f27f0b5af1576553e
| 41.009009 | 151 | 0.66781 | false | false | false | false |
a2/Gulliver
|
refs/heads/master
|
Gulliver Tests/Source/SocialProfileSpec.swift
|
mit
|
1
|
import AddressBook
import Gulliver
import Nimble
import Quick
class SocialProfileSpec: QuickSpec {
override func spec() {
describe("multiValueRepresentation") {
it("should contain the correct data") {
let profile = SocialProfile(URL: "http://twitter.com/jbgoode", service: SocialProfile.Services.Twitter, username: "@jbgoode", userIdentifier: nil)
let mvr = profile.multiValueRepresentation as! [NSObject : AnyObject]
expect((mvr[kABPersonSocialProfileURLKey as String] as! String)) == "http://twitter.com/jbgoode"
expect((mvr[kABPersonSocialProfileServiceKey as String] as! String)) == kABPersonSocialProfileServiceTwitter as String
expect((mvr[kABPersonSocialProfileUsernameKey as String] as! String)) == "@jbgoode"
expect(mvr[kABPersonSocialProfileUserIdentifierKey as String]).to(beNil())
}
it("is a valid representation") {
let profile = SocialProfile(URL: "http://twitter.com/jbgoode", service: SocialProfile.Services.Twitter, username: "@jbgoode", userIdentifier: nil)
let multiValue: ABMutableMultiValueRef = ABMultiValueCreateMutable(numericCast(kABDictionaryPropertyType)).takeRetainedValue()
if !ABMultiValueAddValueAndLabel(multiValue, profile.multiValueRepresentation, kABWorkLabel, nil) {
fail("Could not add profile to multi value")
}
let record: ABRecordRef = ABPersonCreate().takeRetainedValue()
var error: Unmanaged<CFErrorRef>? = nil
if !ABRecordSetValue(record, kABPersonSocialProfileProperty, multiValue, &error) {
let nsError = (error?.takeUnretainedValue()).map { unsafeBitCast($0, NSError.self) }
fail("Could not set value on record: \(nsError?.localizedDescription)")
}
}
}
describe("init(multiValueRepresentation:)") {
it("creates a valid SocialProfile") {
let representation: [NSObject : AnyObject] = [
kABPersonSocialProfileURLKey as String: "http://twitter.com/jbgoode",
kABPersonSocialProfileServiceKey as String: kABPersonSocialProfileServiceTwitter as String,
kABPersonSocialProfileUsernameKey as String: "@jbgoode",
]
let profile = SocialProfile(multiValueRepresentation: representation)
expect(profile).notTo(beNil())
expect(profile!.URL) == "http://twitter.com/jbgoode"
expect(profile!.service) == SocialProfile.Services.Twitter
expect(profile!.username) == "@jbgoode"
}
it("works with vCard data") {
let fileURL = NSBundle(forClass: PostalAddressSpec.self).URLForResource("Johnny B. Goode", withExtension: "vcf")!
let data = NSData(contentsOfURL: fileURL)!
let records = ABPersonCreatePeopleInSourceWithVCardRepresentation(nil, data as CFDataRef).takeRetainedValue() as [ABRecordRef]
let multiValue: ABMultiValueRef = ABRecordCopyValue(records[0], kABPersonSocialProfileProperty).takeRetainedValue()
let values = LabeledValue<SocialProfile>.read(multiValue)
expect(values[0].label) == kABWorkLabel as String
expect(values[0].value) == SocialProfile(URL: "http://twitter.com/jbgoode", service: SocialProfile.Services.Twitter, username: "jbgoode", userIdentifier: nil)
expect(values[1].label) == kABWorkLabel as String
expect(values[1].value) == SocialProfile(URL: "http://facebook.com/johnny.b.goode", service: SocialProfile.Services.Facebook, username: "johnny.b.goode", userIdentifier: nil)
}
}
}
}
|
7b1667ef598bdc91c2919382985baca1
| 59.625 | 190 | 0.641237 | false | false | false | false |
muukii/StackScrollView
|
refs/heads/master
|
StackScrollView/StackScrollView.swift
|
mit
|
1
|
// StackScrollView.swift
//
// Copyright (c) 2016 muukii
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
open class StackScrollView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
private enum LayoutKeys {
static let top = "me.muukii.StackScrollView.top"
static let right = "me.muukii.StackScrollView.right"
static let left = "me.muukii.StackScrollView.left"
static let bottom = "me.muukii.StackScrollView.bottom"
static let width = "me.muukii.StackScrollView.width"
static let height = "me.muukii.StackScrollView.height"
}
private static func defaultLayout() -> UICollectionViewFlowLayout {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = .zero
return layout
}
@available(*, unavailable)
open override var dataSource: UICollectionViewDataSource? {
didSet {
}
}
@available(*, unavailable)
open override var delegate: UICollectionViewDelegate? {
didSet {
}
}
private var direction: UICollectionView.ScrollDirection {
(collectionViewLayout as! UICollectionViewFlowLayout).scrollDirection
}
// MARK: - Initializers
public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
setup()
}
public convenience init(frame: CGRect) {
self.init(frame: frame, collectionViewLayout: StackScrollView.defaultLayout())
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private(set) public var views: [UIView] = []
private func identifier(_ v: UIView) -> String {
return v.hashValue.description
}
private func setup() {
backgroundColor = .white
switch direction {
case .vertical:
alwaysBounceVertical = true
case .horizontal:
alwaysBounceHorizontal = true
@unknown default:
fatalError()
}
delaysContentTouches = false
keyboardDismissMode = .interactive
backgroundColor = .clear
super.delegate = self
super.dataSource = self
}
open override func touchesShouldCancel(in view: UIView) -> Bool {
return true
}
open func append(view: UIView) {
views.append(view)
register(Cell.self, forCellWithReuseIdentifier: identifier(view))
reloadData()
}
open func append(views _views: [UIView]) {
views += _views
_views.forEach { view in
register(Cell.self, forCellWithReuseIdentifier: identifier(view))
}
reloadData()
}
@available(*, unavailable, message: "Unimplemented")
func append(lazy: @escaping () -> UIView) {
}
open func insert(views _views: [UIView], at index: Int, animated: Bool, completion: @escaping () -> Void) {
layoutIfNeeded()
var _views = _views
_views.removeAll(where: views.contains(_:))
views.insert(contentsOf: _views, at: index)
_views.forEach { view in
register(Cell.self, forCellWithReuseIdentifier: identifier(view))
}
let batchUpdates: () -> Void = {
self.performBatchUpdates({
self.insertItems(at: (index ..< index.advanced(by: _views.count)).map({ IndexPath(item: $0, section: 0) }))
}, completion: { _ in completion() })
}
if animated {
UIView.animate(
withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: [
.beginFromCurrentState,
.allowUserInteraction,
.overrideInheritedCurve,
.overrideInheritedOptions,
.overrideInheritedDuration
],
animations: batchUpdates,
completion: nil)
} else {
UIView.performWithoutAnimation(batchUpdates)
}
}
open func insert(views _views: [UIView], before view: UIView, animated: Bool, completion: @escaping () -> Void = {}) {
guard let index = views.firstIndex(of: view) else {
completion()
return
}
insert(views: _views, at: index, animated: animated, completion: completion)
}
open func insert(views _views: [UIView], after view: UIView, animated: Bool, completion: @escaping () -> Void = {}) {
guard let index = views.firstIndex(of: view)?.advanced(by: 1) else {
completion()
return
}
insert(views: _views, at: index, animated: animated, completion: completion)
}
open func remove(view: UIView, animated: Bool, completion: @escaping () -> Void = {}) {
layoutIfNeeded()
if let index = views.firstIndex(of: view) {
views.remove(at: index)
if animated {
UIView.animate(
withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: [
.beginFromCurrentState,
.allowUserInteraction,
.overrideInheritedCurve,
.overrideInheritedOptions,
.overrideInheritedDuration
],
animations: {
self.performBatchUpdates({
self.deleteItems(at: [IndexPath(item: index, section: 0)])
}, completion: { _ in completion() })
}) { (finish) in
}
} else {
UIView.performWithoutAnimation {
performBatchUpdates({
self.deleteItems(at: [IndexPath(item: index, section: 0)])
}, completion: { _ in completion() })
}
}
}
}
open func remove(views: [UIView], animated: Bool, completion: @escaping () -> Void = {}) {
layoutIfNeeded()
var indicesForRemove: [Int] = []
for view in views {
if let index = self.views.firstIndex(of: view) {
indicesForRemove.append(index)
}
}
// It seems that the layout is not updated properly unless the order is aligned.
indicesForRemove.sort(by: >)
for index in indicesForRemove {
self.views.remove(at: index)
}
if animated {
UIView.animate(
withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: [
.beginFromCurrentState,
.allowUserInteraction,
.overrideInheritedCurve,
.overrideInheritedOptions,
.overrideInheritedDuration
],
animations: {
self.performBatchUpdates({
self.deleteItems(at: indicesForRemove.map { IndexPath.init(item: $0, section: 0) })
}, completion: { _ in completion() })
})
} else {
UIView.performWithoutAnimation {
performBatchUpdates({
self.deleteItems(at: indicesForRemove.map { IndexPath.init(item: $0, section: 0) })
}, completion: { _ in completion() })
}
}
}
/// This method might fail if the view is out of bounds. Use `func scroll(to view: UIView, at position: UICollectionView.ScrollPosition, animated: Bool)` instead
@available(*, deprecated, message: "Use `scroll(to view: UIView, at position: UICollectionView.ScrollPosition, animated: Bool)` instead")
open func scroll(to view: UIView, animated: Bool) {
let targetRect = view.convert(view.bounds, to: self)
scrollRectToVisible(targetRect, animated: true)
}
open func scroll(to view: UIView, at position: UICollectionView.ScrollPosition, animated: Bool) {
if let index = views.firstIndex(of: view) {
scrollToItem(at: IndexPath(item: index, section: 0), at: position, animated: animated)
}
}
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return views.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let view = views[indexPath.item]
let _identifier = identifier(view)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: _identifier, for: indexPath)
if view.superview == cell.contentView {
return cell
}
precondition(cell.contentView.subviews.isEmpty)
if view is ManualLayoutStackCellType {
cell.contentView.addSubview(view)
} else {
view.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
cell.contentView.addSubview(view)
let top = view.topAnchor.constraint(equalTo: cell.contentView.topAnchor)
let right = view.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor)
let bottom = view.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor)
let left = view.leftAnchor.constraint(equalTo: cell.contentView.leftAnchor)
top.identifier = LayoutKeys.top
right.identifier = LayoutKeys.right
bottom.identifier = LayoutKeys.bottom
left.identifier = LayoutKeys.left
NSLayoutConstraint.activate([
top,
right,
bottom,
left,
])
}
return cell
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let view = views[indexPath.item]
if let view = view as? ManualLayoutStackCellType {
switch direction {
case .vertical:
return view.size(maxWidth: collectionView.bounds.width, maxHeight: nil)
case .horizontal:
return view.size(maxWidth: nil, maxHeight: collectionView.bounds.height)
@unknown default:
fatalError()
}
} else {
switch direction {
case .vertical:
let width: NSLayoutConstraint = {
guard let c = view.constraints.first(where: { $0.identifier == LayoutKeys.width }) else {
let width = view.widthAnchor.constraint(equalToConstant: collectionView.bounds.width)
width.identifier = LayoutKeys.width
width.isActive = true
return width
}
return c
}()
width.constant = collectionView.bounds.width
let size = view.superview?.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) ?? view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
return size
case .horizontal:
let heightConstraint: NSLayoutConstraint = {
guard let c = view.constraints.first(where: { $0.identifier == LayoutKeys.height }) else {
let heightConstraint = view.heightAnchor.constraint(equalToConstant: collectionView.bounds.height)
heightConstraint.identifier = LayoutKeys.height
heightConstraint.isActive = true
return heightConstraint
}
return c
}()
heightConstraint.constant = collectionView.bounds.height
let size = view.superview?.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) ?? view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
return size
@unknown default:
fatalError()
}
}
}
public func updateLayout(animated: Bool) {
if animated {
UIView.animate(
withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: [
.beginFromCurrentState,
.allowUserInteraction,
.overrideInheritedCurve,
.overrideInheritedOptions,
.overrideInheritedDuration
],
animations: {
self.performBatchUpdates(nil, completion: nil)
self.layoutIfNeeded()
}) { (finish) in
}
} else {
UIView.performWithoutAnimation {
self.performBatchUpdates(nil, completion: nil)
self.layoutIfNeeded()
}
}
}
final class Cell: UICollectionViewCell {
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
return layoutAttributes
}
}
}
|
8e536156b7aff63e7cdc6815cd8dcb86
| 29.515012 | 165 | 0.656475 | false | false | false | false |
jeden/jsonablest
|
refs/heads/master
|
jsonablest/JsonablestTests/EncodingTests.swift
|
mit
|
1
|
//
// EncodingTests.swift
// EncodingTests
//
// Created by Antonio Bello on 6/4/16.
//
//
import XCTest
import Jsonablest
private let someTimeInterval: TimeInterval = 1494261446.378659
private let someTimestamp = Date(timeIntervalSince1970: someTimeInterval)
class EncodingTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testAutomaticEncodeSuccess() {
let expectedDictionary: JsonDictionary = [
"oneString": "one",
"twoInt": 2,
"threeFloat": 3.0,
"fourDouble": 4.0,
"fiveBool": true,
"sixDate": someTimestamp.toIso8610(),
"sevenOptional": 7,
]
let structure = StructWithNoExplicitEncode(oneString: "one", twoInt: 2, threeFloat: 3.0, fourDouble: 4.0, fiveBool: true, sixDate: Date(timeIntervalSince1970: someTimeInterval), sevenOptional: 7, eightNil: nil)
let exportedDictionary = structure.jsonEncode()
XCTAssert(exportedDictionary == expectedDictionary, "No match: \(exportedDictionary)")
}
func testAutomaticEncodeShouldFailWithWrongValue() {
let value = SimpleInt(value: 1)
let correctExpectation: JsonDictionary = ["value": 1]
let wrongExpectation: JsonDictionary = [ "value": 2]
let exported = value.jsonEncode()
XCTAssert(correctExpectation == exported, "The actual json encoding doesn't match with the expected")
XCTAssertFalse(wrongExpectation == exported, "the json encoding should be different than the expected wrong dictionary")
}
func testAutomaticEncodeWithEmbeddedJsonEncodables() {
let embedded = SimpleInt(value: 10)
let value = EmbeddingStruct(embedded: embedded)
let expected: JsonDictionary = [
"embedded": [
"value": 10
] as JsonType
]
let exported = value.jsonEncode()
XCTAssert(expected == exported, "The generated json doens't match the expected one")
}
func testAutomaticEncodeWithIgnoredFields() {
let value = FieldsWithIgnores(exported: "yes", ignored: true)
let expected: JsonDictionary = [
"exported": "yes"
]
let exported = value.jsonEncode()
XCTAssert(expected == exported, "The generated json doens't match the expected one")
}
func testAutomaticEncodeWithReplacementFields() {
let value = FieldsWithReplacements(original: "yes", replaced: "it should be replaced")
let expected: JsonDictionary = [
"original": "yes",
"replacement": "it should be replaced"
]
let exported = value.jsonEncode()
XCTAssert(expected == exported, "The generated json doens't match the expected one")
}
}
// MARK: Internal structures
/// A struct not having a jsonEncode() method, so using the default
// one implemented in the protocol extension
private struct StructWithNoExplicitEncode : JsonEncodable {
let oneString : String
let twoInt: Int
let threeFloat: Float
let fourDouble: Double
let fiveBool: Bool
let sixDate: Date
let sevenOptional: Int?
let eightNil: Bool?
}
private struct SimpleInt : JsonEncodable {
let value: Int
}
private struct EmbeddingStruct : JsonEncodable {
let embedded: SimpleInt
}
private struct FieldsWithIgnores : JsonEncodable {
let exported: String
let ignored: Bool
}
extension FieldsWithIgnores : JsonEncodingIgnorable {
var jsonFieldIgnores : [String] {
return ["ignored"]
}
}
private struct FieldsWithReplacements : JsonEncodable {
let original: String
let replaced: String
}
extension FieldsWithReplacements : JsonEncodingReplaceable {
var jsonFieldReplacements : [String : String] {
return [ "replaced": "replacement" ]
}
}
private func == (op1: JsonDictionary, op2: JsonDictionary) -> Bool {
return NSDictionary(dictionary: op1).isEqual(to: op2)
}
|
087dfac0b96fd4990de25e726943e1c6
| 27.895522 | 212 | 0.731921 | false | true | false | false |
bwide/Sorting-Algorithms-Playground
|
refs/heads/master
|
Sorting algorithms.playground/Pages/QuickSort.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [Previous](@previous)
import UIKit
import PlaygroundSupport
let size = 200
let array = VisualSortableArray.init(arraySize: size)
func elementAt(index: Int) -> Int {
return array.get(index: index)
}
func swap(i: Int, j: Int){
return array.swap(i: i, j: j)
}
func select(i: Int, j: Int) -> Bool {
return array.select(i: i, j: j)
}
PlaygroundPage.current.liveView = array.view
DispatchQueue.global(qos: .background).async {
sleep(2)
func quickSort(array: VisualSortableArray, fromLeftIndex leftIndex: Int, toRightIndex rightIndex: Int) {
let index = partition(array: array, fromLeftIndex: leftIndex, toRightIndex: rightIndex)
if leftIndex < index - 1 {
quickSort(array: array, fromLeftIndex: leftIndex, toRightIndex: index - 1)
}
if index < rightIndex {
quickSort(array: array, fromLeftIndex: index, toRightIndex: rightIndex)
}
}
func partition(array: VisualSortableArray, fromLeftIndex leftIndex: Int, toRightIndex rightIndex: Int) -> Int {
var localLeftIndex = leftIndex
var localRightIndex = rightIndex
let pivot = elementAt(index: (localLeftIndex + localRightIndex) / 2)
while localLeftIndex <= localRightIndex {
while elementAt(index: localLeftIndex) < pivot {
localLeftIndex += 1
select(i: localLeftIndex, j: localRightIndex)
}
while localRightIndex > 0 && elementAt(index: localRightIndex) > pivot {
localRightIndex -= 1
select(i: localLeftIndex, j: localRightIndex)
}
if localLeftIndex <= localRightIndex {
if localLeftIndex != localRightIndex {
swap(i: localLeftIndex, j: localRightIndex)
}
localLeftIndex += 1
if localRightIndex > 0 {
localRightIndex -= 1
select(i: localLeftIndex, j: localRightIndex)
}
}
}
return localLeftIndex
}
quickSort(array: array, fromLeftIndex: 0, toRightIndex: array.count - 1)
}
//: [Next](@next)
|
f04d312784e6e45e11982a8aa60b8a11
| 28.474359 | 115 | 0.572423 | false | false | false | false |
aboutsajjad/Bridge
|
refs/heads/master
|
Bridge/DownloadCoordinator/DownloadTableViewCell.swift
|
mit
|
1
|
//
// DownloadTableViewCell.swift
// Bridge
//
// Created by Sajjad Aboutalebi on 5/11/18.
// Copyright © 2018 Sajjad Aboutalebi. All rights reserved.
//
import UIKit
import MZDownloadManager
import SnapKit
import MBCircularProgressBar
class DownloadTableViewCell: UITableViewCell {
lazy var progressview: MBCircularProgressBarView = {
let pv = MBCircularProgressBarView()
pv.maxValue = 100
pv.progressAngle = 90
pv.progressLineWidth = 1
pv.progressColor = .blue
pv.progressStrokeColor = .purple
pv.backgroundColor = .white
return pv
}()
lazy var titlelabel: UILabel = {
let lb = UILabel()
lb.font = lb.font.withSize(16)
lb.numberOfLines = 2
return lb
}()
lazy var remainingLabel: UILabel = {
let lb = UILabel()
lb.font = lb.font.withSize(15)
lb.textColor = .gray
return lb
}()
lazy var speedLabel: UILabel = {
let lb = UILabel()
lb.font = lb.font.withSize(14)
lb.numberOfLines = 0
lb.textColor = .lightGray
return lb
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(progressview)
addSubview(titlelabel)
addSubview(remainingLabel)
addSubview(speedLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
progressview.snp.makeConstraints { (maker) in
maker.top.left.equalToSuperview().offset(5)
maker.height.equalTo(70)
maker.width.equalTo(progressview.snp.height)
maker.bottom.equalToSuperview().offset(-5)
}
titlelabel.snp.remakeConstraints { (maker) in
maker.top.equalToSuperview()
maker.left.equalTo(progressview.snp.right).offset(5)
maker.right.equalToSuperview()
}
remainingLabel.snp.remakeConstraints { (maker) in
maker.top.equalTo(titlelabel.snp.bottom)
maker.left.equalTo(progressview.snp.right).offset(5)
}
speedLabel.snp.remakeConstraints { (maker) in
maker.top.equalTo(remainingLabel.snp.bottom)
maker.left.equalTo(progressview.snp.right).offset(5)
maker.bottom.equalToSuperview()
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func updateCellForRowAtIndexPath(_ indexPath : IndexPath, downloadModel: MZDownloadModel) {
titlelabel.text = downloadModel.fileName
remainingLabel.text = "\((Double(downloadModel.progress)*1000).rounded()/10)% - \(downloadModel.downloadedFile?.size.roundTo() ?? "0") \(downloadModel.downloadedFile?.unit ?? "KB") of \(downloadModel.file?.size.roundTo() ?? "0") \(downloadModel.file?.unit ?? "KB")"
speedLabel.text = "\(downloadModel.speed?.speed.roundTo() ?? "0") \(downloadModel.speed?.unit ?? "KB")/s - \(downloadModel.remainingTime?.hours ?? 0) houre(s) and \(downloadModel.remainingTime?.minutes ?? 0) remaining"
progressview.value = CGFloat(downloadModel.progress) * 100
}
}
|
7af74ea6bd07fdb49b7638c7212c61b4
| 33.435644 | 273 | 0.627085 | false | false | false | false |
garygriswold/Bible.js
|
refs/heads/master
|
SafeBible2/SafeBible_ios/SafeBible/Models/ReaderViewQueue.swift
|
mit
|
1
|
//
// ReaderViewQueue.swift
// Settings
//
// Created by Gary Griswold on 11/9/18.
// Copyright © 2018 ShortSands. All rights reserved.
//
import UIKit
class ReaderViewQueue {
static let shared = ReaderViewQueue()
private enum PreviousCall {
case first
case next
case prior
case preload
}
private static let QUEUE_MAX: Int = 10
private static let EXTRA_NEXT: Int = 1
private static let EXTRA_PRIOR: Int = 1
private var queue: [ReaderViewController]
private var unused: Set<ReaderViewController>
private var previousCall: PreviousCall
private init() {
self.queue = [ReaderViewController]()
self.unused = Set<ReaderViewController>()
self.previousCall = .first
}
func first(reference: Reference) -> ReaderViewController {
self.previousCall = .first
for controller in self.queue {
self.addUnused(controller: controller)
}
self.queue.removeAll()
let controller = self.getUnused(reference: reference)
self.queue.append(controller)
return controller
}
/**
* The ReaderViewController is one that is already in the queue.
* So, it is guarantteed to be found within the list.
*/
func next(controller: UIViewController) -> ReaderViewController? {
self.previousCall = .next
if let index = self.findController(controller: controller) {
if index < (queue.count - 1) {
return self.queue[index + 1]
} else {
return appendAfter()
}
} else {
return nil
}
}
func prior(controller: UIViewController) -> ReaderViewController? {
self.previousCall = .prior
if let index = self.findController(controller: controller) {
if index > 0 {
return self.queue[index - 1]
} else {
return insertBefore()
}
} else {
return nil
}
}
/**
* UIPageViewController is usually calling next and prior to preload the next and prior pages,
* but never for the initial set, and only most of the time when the page is swiped.
* This method is called after any page is loaded to add one additional pages before and or after
*/
func preload() {
switch self.previousCall {
case .first:
_ = self.appendAfter()
_ = self.insertBefore()
case .next:
_ = self.appendAfter()
case .prior:
_ = self.insertBefore()
case .preload:
_ = 1 // do nothing
}
self.previousCall = .preload
}
func updateCSS(css: String) {
print("update Rule in ReaderViewQueue: \(css)")
for webView in self.queue {
webView.execJavascript(message: css)
}
}
func reloadIfActive(reference: Reference) {
for reader in self.queue {
if reader.reference == reference {
reader.reloadReference()
return
}
}
}
private func appendAfter() -> ReaderViewController {
let reference = self.queue.last!.reference!
let controller = self.getUnused(reference: reference.nextChapter())
self.queue.append(controller)
if self.queue.count > ReaderViewQueue.QUEUE_MAX {
let first = self.queue.removeFirst()
self.addUnused(controller: first)
}
return controller
}
private func insertBefore() -> ReaderViewController {
let reference = self.queue[0].reference!
let controller = self.getUnused(reference: reference.priorChapter())
self.queue.insert(controller, at: 0)
if self.queue.count > ReaderViewQueue.QUEUE_MAX {
let last = self.queue.removeLast()
self.addUnused(controller: last)
}
return controller
}
private func getUnused(reference: Reference) -> ReaderViewController {
var webView = self.unused.popFirst()
if webView == nil {
webView = ReaderViewController()
}
webView!.clearWebView() // Needed to clear old content off page, 0.4 ms to 0.0ms
webView!.loadReference(reference: reference) // The page is loaded when this is called
return webView!
}
private func addUnused(controller: ReaderViewController) {
controller.view.removeFromSuperview()
self.unused.insert(controller)
}
private func findController(controller: UIViewController) -> Int? {
guard let readController = controller as? ReaderViewController
else { fatalError("ReaderViewQueue.findController must receive ReaderViewController") }
let reference = readController.reference!
for index in 0..<self.queue.count {
if self.queue[index].reference == reference {
return index
}
}
return nil
}
}
|
2c912fbf9cc5dcbd8c23220c14e55cac
| 30.487654 | 100 | 0.590472 | false | false | false | false |
mattjgalloway/emoncms-ios
|
refs/heads/master
|
EmonCMSiOS/Controllers/LoginController.swift
|
mit
|
1
|
//
// LoginController.swift
// EmonCMSiOS
//
// Created by Matt Galloway on 13/09/2016.
// Copyright © 2016 Matt Galloway. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import Locksmith
final class LoginController {
enum LoginControllerError: Error {
case Generic
case KeychainFailed
}
private var _account = Variable<Account?>(nil)
let account: Observable<Account?>
init() {
self.account = _account.asObservable().shareReplay(1)
self.loadAccount()
}
private func loadAccount() {
guard
let accountURL = UserDefaults.standard.string(forKey: SharedConstants.UserDefaultsKeys.accountURL.rawValue),
let accountUUIDString = UserDefaults.standard.string(forKey: SharedConstants.UserDefaultsKeys.accountUUID.rawValue),
let accountUUID = UUID(uuidString: accountUUIDString)
else { return }
guard
let data = Locksmith.loadDataForUserAccount(userAccount: accountUUIDString),
let apikey = data["apikey"] as? String
else { return }
let account = Account(uuid: accountUUID, url: accountURL, apikey: apikey)
self._account.value = account
}
func login(withAccount account: Account) throws {
do {
if let currentAccount = _account.value {
if currentAccount == account {
return
}
}
let data = ["apikey": account.apikey]
do {
try Locksmith.saveData(data: data, forUserAccount: account.uuid.uuidString)
} catch LocksmithError.duplicate {
// We already have it, let's try updating it
try Locksmith.updateData(data: data, forUserAccount: account.uuid.uuidString)
}
UserDefaults.standard.set(account.url, forKey: SharedConstants.UserDefaultsKeys.accountURL.rawValue)
UserDefaults.standard.set(account.uuid.uuidString, forKey: SharedConstants.UserDefaultsKeys.accountUUID.rawValue)
self._account.value = account
} catch {
throw LoginControllerError.KeychainFailed
}
}
func logout() throws {
guard let accountURL = UserDefaults.standard.string(forKey: SharedConstants.UserDefaultsKeys.accountUUID.rawValue) else {
throw LoginControllerError.Generic
}
do {
try Locksmith.deleteDataForUserAccount(userAccount: accountURL)
UserDefaults.standard.removeObject(forKey: SharedConstants.UserDefaultsKeys.accountURL.rawValue)
self._account.value = nil
} catch {
throw LoginControllerError.KeychainFailed
}
}
}
|
2c74364d5816368ed266f6ff35f4982e
| 29.353659 | 125 | 0.709522 | false | false | false | false |
MukeshKumarS/Swift
|
refs/heads/master
|
stdlib/public/core/HeapBuffer.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
typealias _HeapObject = SwiftShims.HeapObject
@warn_unused_result
@_silgen_name("swift_bufferAllocate")
func _swift_bufferAllocate(
bufferType: AnyClass, _ size: Int, _ alignMask: Int) -> AnyObject
/// A class containing an ivar "value" of type Value, and
/// containing storage for an array of Element whose size is
/// determined at create time.
///
/// The analogous C++-ish class template would be:
///
/// template <class Value, class Element>
/// struct _HeapBuffer {
/// Value value;
/// Element baseAddress[]; // length determined at creation time
///
/// _HeapBuffer() = delete
/// static shared_ptr<_HeapBuffer> create(Value init, int capacity);
/// }
///
/// Note that the Element array is RAW MEMORY. You are expected to
/// construct and---if necessary---destroy Elements there yourself,
/// either in a derived class, or it can be in some manager object
/// that owns the _HeapBuffer.
public // @testable (test/Prototypes/MutableIndexableDict.swift)
class _HeapBufferStorage<Value,Element> : NonObjectiveCBase {
public override init() {}
/// The type used to actually manage instances of
/// `_HeapBufferStorage<Value,Element>`.
typealias Buffer = _HeapBuffer<Value, Element>
deinit {
Buffer(self)._value.destroy()
}
@warn_unused_result
final func __getInstanceSizeAndAlignMask() -> (Int,Int) {
return Buffer(self)._allocatedSizeAndAlignMask()
}
}
/// Management API for `_HeapBufferStorage<Value, Element>`
public // @testable
struct _HeapBuffer<Value, Element> : Equatable {
/// A default type to use as a backing store.
typealias Storage = _HeapBufferStorage<Value, Element>
// _storage is passed inout to _isUnique. Although its value
// is unchanged, it must appear mutable to the optimizer.
var _storage: Builtin.NativeObject?
public // @testable
var storage: AnyObject? {
return _storage.map { Builtin.castFromNativeObject($0) }
}
@warn_unused_result
static func _valueOffset() -> Int {
return _roundUpToAlignment(sizeof(_HeapObject.self), alignof(Value.self))
}
@warn_unused_result
static func _elementOffset() -> Int {
return _roundUpToAlignment(_valueOffset() + sizeof(Value.self),
alignof(Element.self))
}
@warn_unused_result
static func _requiredAlignMask() -> Int {
// We can't use max here because it can allocate an array.
let heapAlign = alignof(_HeapObject.self) &- 1
let valueAlign = alignof(Value.self) &- 1
let elementAlign = alignof(Element.self) &- 1
return (heapAlign < valueAlign
? (valueAlign < elementAlign ? elementAlign : valueAlign)
: (heapAlign < elementAlign ? elementAlign : heapAlign))
}
var _address: UnsafeMutablePointer<Int8> {
return UnsafeMutablePointer(
Builtin.bridgeToRawPointer(self._nativeObject))
}
var _value: UnsafeMutablePointer<Value> {
return UnsafeMutablePointer(
_HeapBuffer._valueOffset() + _address)
}
public // @testable
var baseAddress: UnsafeMutablePointer<Element> {
return UnsafeMutablePointer(_HeapBuffer._elementOffset() + _address)
}
@warn_unused_result
func _allocatedSize() -> Int {
return _swift_stdlib_malloc_size(_address)
}
@warn_unused_result
func _allocatedAlignMask() -> Int {
return _HeapBuffer._requiredAlignMask()
}
@warn_unused_result
func _allocatedSizeAndAlignMask() -> (Int, Int) {
return (_allocatedSize(), _allocatedAlignMask())
}
/// Return the actual number of `Elements` we can possibly store.
@warn_unused_result
func _capacity() -> Int {
return (_allocatedSize() - _HeapBuffer._elementOffset())
/ strideof(Element.self)
}
init() {
self._storage = nil
}
public // @testable
init(_ storage: _HeapBufferStorage<Value,Element>) {
self._storage = Builtin.castToNativeObject(storage)
}
init(_ storage: AnyObject) {
_sanityCheck(
_usesNativeSwiftReferenceCounting(storage.dynamicType),
"HeapBuffer manages only native objects"
)
self._storage = Builtin.castToNativeObject(storage)
}
init<T : AnyObject>(_ storage: T?) {
self = storage.map { _HeapBuffer($0) } ?? _HeapBuffer()
}
init(nativeStorage: Builtin.NativeObject?) {
self._storage = nativeStorage
}
/// Create a `_HeapBuffer` with `self.value = initializer` and
/// `self._capacity() >= capacity`.
public // @testable
init(
_ storageClass: AnyClass,
_ initializer: Value, _ capacity: Int
) {
_sanityCheck(capacity >= 0, "creating a _HeapBuffer with negative capacity")
_sanityCheck(
_usesNativeSwiftReferenceCounting(storageClass),
"HeapBuffer can only create native objects"
)
let totalSize = _HeapBuffer._elementOffset() +
capacity * strideof(Element.self)
let alignMask = _HeapBuffer._requiredAlignMask()
let object: AnyObject = _swift_bufferAllocate(
storageClass, totalSize, alignMask)
self._storage = Builtin.castToNativeObject(object)
self._value.initialize(initializer)
}
public // @testable
var value : Value {
unsafeAddress {
return UnsafePointer(_value)
}
nonmutating unsafeMutableAddress {
return _value
}
}
/// `true` if storage is non-`nil`.
var hasStorage: Bool {
return _storage != nil
}
subscript(i: Int) -> Element {
unsafeAddress {
return UnsafePointer(baseAddress + i)
}
nonmutating unsafeMutableAddress {
return baseAddress + i
}
}
var _nativeObject: Builtin.NativeObject {
return _storage!
}
@warn_unused_result
static func fromNativeObject(x: Builtin.NativeObject) -> _HeapBuffer {
return _HeapBuffer(nativeStorage: x)
}
@warn_unused_result
public // @testable
mutating func isUniquelyReferenced() -> Bool {
return _isUnique(&_storage)
}
@warn_unused_result
public // @testable
mutating func isUniquelyReferencedOrPinned() -> Bool {
return _isUniqueOrPinned(&_storage)
}
}
// HeapBuffers are equal when they reference the same buffer
@warn_unused_result
public // @testable
func == <Value, Element> (
lhs: _HeapBuffer<Value, Element>,
rhs: _HeapBuffer<Value, Element>) -> Bool {
return lhs._nativeObject == rhs._nativeObject
}
|
fdf26bb67081d81d39bdc2e01e61d29b
| 28.133047 | 80 | 0.667207 | false | false | false | false |
tryswift/TryParsec
|
refs/heads/swift/4.0
|
Sources/TryParsec/Parser+Combinator.swift
|
mit
|
1
|
import Runes
//infix operator >>- : RunesMonadicPrecedenceLeft // redefine
/// Parses zero or one occurrence of `p`.
/// - SeeAlso: Haskell Parsec's `optionMaybe`.
public func zeroOrOne<In, Out>(_ p: Parser<In, Out>) -> Parser<In, Out?>
{
return (p <&> { Optional($0) }) <|> pure(nil)
}
/// Parses zero or more occurrences of `p`.
/// - Note: Returning parser never fails.
public func many<In, Out, Outs: RangeReplaceableCollection>(_ p: Parser<In, Out>) -> Parser<In, Outs> where Outs.Iterator.Element == Out
{
return many1(p) <|> pure(Outs())
}
/// Parses one or more occurrences of `p`.
public func many1<In, Out, Outs: RangeReplaceableCollection>(_ p: Parser<In, Out>) -> Parser<In, Outs> where Outs.Iterator.Element == Out
{
return cons <^> p <*> many(p)
}
/// Parses one or more occurrences of `p` until `end` succeeds,
/// and returns the list of values returned by `p`.
public func manyTill<In, Out, Out2, Outs: RangeReplaceableCollection>(
_ p: Parser<In, Out>,
_ end: Parser<In, Out2>
) -> Parser<In, Outs>
where Outs.Iterator.Element == Out
{
return fix { recur in { _ in
(end *> pure(Outs())) <|> (cons <^> p <*> recur(()))
}}(())
}
/// Skips zero or more occurrences of `p`.
/// - Note: Returning parser never fails.
public func skipMany<In, Out>(_ p: Parser<In, Out>) -> Parser<In, ()>
{
return skipMany1(p) <|> pure(())
}
/// Skips one or more occurrences of `p`.
public func skipMany1<In, Out>(_ p: Parser<In, Out>) -> Parser<In, ()>
{
return p *> skipMany(p)
}
/// Separates zero or more occurrences of `p` using separator `sep`.
/// - Note: Returning parser never fails.
public func sepBy<In, Out, Outs: RangeReplaceableCollection, Sep>(
_ p: Parser<In, Out>,
_ separator: Parser<In, Sep>
) -> Parser<In, Outs>
where Outs.Iterator.Element == Out
{
return sepBy1(p, separator) <|> pure(Outs())
}
/// Separates one or more occurrences of `p` using separator `sep`.
public func sepBy1<In, Out, Outs: RangeReplaceableCollection, Sep>(
_ p: Parser<In, Out>,
_ separator: Parser<In, Sep>
) -> Parser<In, Outs>
where Outs.Iterator.Element == Out
{
return cons <^> p <*> many(separator *> p)
}
/// Separates zero or more occurrences of `p` using optionally-ended separator `sep`.
/// - Note: Returning parser never fails.
public func sepEndBy<In, Out, Outs: RangeReplaceableCollection, Sep>(
_ p: Parser<In, Out>,
_ separator: Parser<In, Sep>
) -> Parser<In, Outs>
where Outs.Iterator.Element == Out
{
return sepEndBy1(p, separator) <|> pure(Outs())
}
/// Separates one or more occurrences of `p` using optionally-ended separator `sep`.
public func sepEndBy1<In, Out, Outs: RangeReplaceableCollection, Sep>(
_ p: Parser<In, Out>,
_ separator: Parser<In, Sep>
) -> Parser<In, Outs>
where Outs.Iterator.Element == Out
{
return p >>- { x in
((separator *> sepEndBy(p, separator)) >>- { xs in
pure(Outs(x) + xs)
}) <|> pure(Outs(x))
}
}
/// Parses `n` occurrences of `p`.
public func count<In, Out, Outs: RangeReplaceableCollection>(
_ n: Int,
_ p: Parser<In, Out>
) -> Parser<In, Outs>
where Outs.Iterator.Element == Out
{
guard n > 0 else { return pure(Outs()) }
return cons <^> p <*> count(n-1, p)
}
///
/// Parses zero or more occurrences of `p`, separated by `op`
/// which left-associates multiple outputs from `p` by applying its binary operation.
///
/// If there are zero occurrences of `p`, default value `x` is returned.
///
/// - Note: Returning parser never fails.
///
public func chainl<In, Out>(
_ p: Parser<In, Out>,
_ op: Parser<In, (Out, Out) -> Out>,
_ x: Out
) -> Parser<In, Out>
{
return chainl1(p, op) <|> pure(x)
}
///
/// Parses one or more occurrences of `p`, separated by `op`
/// which left-associates multiple outputs from `p` by applying its binary operation.
///
/// This parser can be used to eliminate left recursion which typically occurs in expression grammars.
///
/// For example (pseudocode):
///
/// ```
/// let expr = chainl1(term, symbol("-") *> pure(-))
/// ```
///
/// can be interpretted as:
///
/// ```
/// // [EBNF] expr = term { - term }
/// let expr = curry({ $1.reduce($0, combine: -) }) <^> term <*> many(symbol("-") *> term)
/// ```
///
/// but more efficient since `chainl1` doesn't use `many` to convert to
/// `RangeReplaceableCollectionType` first and then `reduce`.
///
public func chainl1<In, Out>(
_ p: Parser<In, Out>,
_ op: Parser<In, (Out, Out) -> Out>
) -> Parser<In, Out>
{
return p >>- { x in
fix { recur in { x in
(op >>- { f in
p >>- { y in
recur(f(x, y))
}
}) <|> pure(x)
}}(x)
}
}
///
/// Parses zero or more occurrences of `p`, separated by `op`
/// which right-associates multiple outputs from `p` by applying its binary operation.
///
/// If there are zero occurrences of `p`, default value `x` is returned.
///
/// - Note: Returning parser never fails.
///
public func chainr<In, Out>(
_ p: Parser<In, Out>,
_ op: Parser<In, (Out, Out) -> Out>,
_ x: Out
) -> Parser<In, Out>
{
return chainr1(p, op) <|> pure(x)
}
/// Parses one or more occurrences of `p`, separated by `op`
/// which right-associates multiple outputs from `p` by applying its binary operation.
public func chainr1<In, Out>(
_ p: Parser<In, Out>,
_ op: Parser<In, (Out, Out) -> Out>
) -> Parser<In, Out>
{
return fix { recur in { _ in
p >>- { x in
(op >>- { f in
recur(()) >>- { y in
pure(f(x, y))
}
}) <|> pure(x)
}
}}(())
}
/// Applies `p` without consuming any input.
public func lookAhead<In, Out>(_ p: Parser<In, Out>) -> Parser<In, Out>
{
return Parser { input in
let reply = parse(p, input)
switch reply {
case .fail:
return reply
case let .done(_, output):
return .done(input, output)
}
}
}
/// Folds `parsers` using Alternative's `<|>`.
public func choice<In, Out, S: Sequence>(_ parsers: S) -> Parser<In, Out> where S.Iterator.Element == Parser<In, Out>
{
return parsers.reduce(empty(), { $0 <|> $1 })
}
|
e1050c9ec0b7968282877d5d6602d074
| 28.124424 | 137 | 0.585918 | false | false | false | false |
1457792186/JWSwift
|
refs/heads/master
|
SwiftWX/LGWeChatKit/LGChatKit/conversion/imagePick/LGAssetViewController.swift
|
apache-2.0
|
1
|
//
// LGAssetViewController.swift
// LGWeChatKit
//
// Created by jamy on 10/28/15.
// Copyright © 2015 jamy. All rights reserved.
//
import UIKit
import Photos
private let reuseIdentifier = "assetviewcell"
class LGAssetViewController: UIViewController {
var collectionView: UICollectionView!
var currentIndex: IndexPath!
var selectButton: UIButton!
var playButton: UIBarButtonItem!
var cellSize: CGSize!
var assetModels = [LGAssetModel]()
var selectedInfo: NSMutableArray?
var selectIndex = 0
lazy var imageManager: PHCachingImageManager = {
return PHCachingImageManager()
}()
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
cellSize = (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize
collectionView.selectItem(at: IndexPath(item: selectIndex, section: 0), animated: false, scrollPosition: .centeredHorizontally)
}
func setupCollectionView() {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: view.bounds.width, height: view.bounds.height - 64)
layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
collectionView.register(LGAssetViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
collectionView.backgroundColor = UIColor.white
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.dataSource = self
collectionView.delegate = self
view.addSubview(collectionView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupNavgationBar()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
func setupNavgationBar() {
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "CellGreySelected"), for: UIControlState())
button.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
button.addTarget(self, action: #selector(LGAssetViewController.selectCurrentImage), for: .touchUpInside)
let item = UIBarButtonItem(customView: button)
navigationItem.rightBarButtonItem = item
selectButton = button
let cancelButton = UIBarButtonItem(title: "取消", style: .done, target: self, action: #selector(LGAssetViewController.dismissView))
navigationItem.leftBarButtonItem = cancelButton
}
func selectCurrentImage() {
let indexPaths = collectionView.indexPathsForVisibleItems
let indexpath = indexPaths.first
let cell = collectionView.cellForItem(at: indexpath!) as! LGAssetViewCell
let asset = assetModels[(indexpath?.row)!]
if asset.select {
asset.select = false
selectedInfo?.remove(cell.imageView.image!)
selectButton.setImage(UIImage(named: "CellGreySelected"), for: UIControlState())
} else {
asset.select = true
selectedInfo?.add(cell.imageView.image!)
selectButton.setImage(UIImage(named: "CellBlueSelected"), for: UIControlState())
}
}
func dismissView() {
self.dismiss(animated: true, completion: nil)
}
}
// MARK: - collectionView delegate
extension LGAssetViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return assetModels.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! LGAssetViewCell
// cell.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "imageTapGesture:"))
let assetModel = assetModels[indexPath.row]
let viewModel = LGAssetViewModel(assetMode: assetModel)
viewModel.updateImage(cellSize)
cell.viewModel = viewModel
if assetModel.select {
selectButton.setImage(UIImage(named: "CellBlueSelected"), for: UIControlState())
} else {
selectButton.setImage(UIImage(named: "CellGreySelected"), for: UIControlState())
}
currentIndex = indexPath
return cell
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let assetModel = assetModels[indexPath.row]
let viewModel = LGAssetViewModel(assetMode: assetModel)
let cell = cell as! LGAssetViewCell
if viewModel.livePhoto.value.size.width != 0 || (viewModel.asset.value.mediaType == .video) {
cell.stopPlayer()
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let assetModel = assetModels[indexPath.row]
let viewModel = LGAssetViewModel(assetMode: assetModel)
let cell = collectionView.cellForItem(at: indexPath) as! LGAssetViewCell
if viewModel.livePhoto.value.size.width != 0 || (viewModel.asset.value.mediaType == .video) {
cell.playLivePhoto()
} else {
if UIApplication.shared.isStatusBarHidden == false {
UIApplication.shared.setStatusBarHidden(true, with: .slide)
navigationController?.navigationBar.isHidden = true
} else {
navigationController?.navigationBar.isHidden = false
UIApplication.shared.setStatusBarHidden(false, with: .slide)
}
}
}
}
// MARK: - scrollView delegate
extension LGAssetViewController {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetX = Int(collectionView.contentOffset.x / view.bounds.width + 0.5)
self.title = "\(offsetX + 1)" + "/" + "\(assetModels.count)"
if offsetX >= 0 && offsetX < assetModels.count && selectButton != nil {
let assetModel = assetModels[offsetX]
if assetModel.select {
selectButton.setImage(UIImage(named: "CellBlueSelected"), for: UIControlState())
} else {
selectButton.setImage(UIImage(named: "CellGreySelected"), for: UIControlState())
}
}
}
}
|
64ef8ca46b2aeba7b21d1de76ad113f9
| 37.322034 | 138 | 0.666814 | false | false | false | false |
nakau1/NerobluCore
|
refs/heads/master
|
NerobluCoreDemo/AppDelegate.swift
|
apache-2.0
|
1
|
// =============================================================================
// NerobluCoreDemo
// Copyright (C) NeroBlu. All rights reserved.
// =============================================================================
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
return true
}
}
|
e19667b93318ae94891a84480aca39cd
| 29.4375 | 122 | 0.521561 | false | false | false | false |
MobileToolkit/Glover
|
refs/heads/master
|
Sources/Configuration.swift
|
mit
|
2
|
//
// Configuration.swift
// Glover
//
// Created by Sebastian Owodzin on 12/03/2016.
// Copyright © 2016 mobiletoolkit.org. All rights reserved.
//
import Foundation
import CoreData
open class Configuration {
fileprivate lazy var applicationDocumentsDirectory: URL = {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
}()
var model: NSManagedObjectModel
var persistentStoreConfigurations: [PersistentStoreConfiguration] = []
open func addPersistentStoreConfiguration(_ persistentStoreConfiguration: PersistentStoreConfiguration) {
persistentStoreConfigurations.append(persistentStoreConfiguration)
}
public init(model: NSManagedObjectModel) {
self.model = model
}
open class func singleSQLiteStoreConfiguration(_ model: NSManagedObjectModel) -> Configuration {
let configuration = Configuration(model: model)
let storeURL = configuration.applicationDocumentsDirectory.appendingPathComponent("gloverDB.sqlite")
let storeConfig = PersistentStoreConfiguration(type: .SQLite, url: storeURL)
configuration.addPersistentStoreConfiguration(storeConfig)
return configuration
}
open class func singleBinaryStoreConfiguration(_ model: NSManagedObjectModel) -> Configuration {
let configuration = Configuration(model: model)
let storeURL = configuration.applicationDocumentsDirectory.appendingPathComponent("gloverDB.bin")
let storeConfig = PersistentStoreConfiguration(type: .Binary, url: storeURL)
configuration.addPersistentStoreConfiguration(storeConfig)
return configuration
}
open class func singleInMemoryStoreConfiguration(_ model: NSManagedObjectModel) -> Configuration {
let configuration = Configuration(model: model)
configuration.addPersistentStoreConfiguration(PersistentStoreConfiguration(type: .InMemory))
return configuration
}
}
|
d24a0eab48778793e380574c6784fb82
| 33.086207 | 109 | 0.750632 | false | true | false | false |
LYM-mg/MGOFO
|
refs/heads/master
|
MGOFO/MGOFO/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// MGOFO
//
// Created by i-Techsys.com on 2017/5/9.
// Copyright © 2017年 i-Techsys. All rights reserved.
// 7728ab18dd2abf89a6299740e270f4c6
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//后台任务
var backgroundTask:UIBackgroundTaskIdentifier! = nil
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
setUpKeyWindow()
setUpAllThird()
return true
}
fileprivate func setUpKeyWindow() {
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.backgroundColor = UIColor.white
let homeVc = HomeViewController()
let sideVc = SideViewController()
let homeNav = BaseNavigationController(rootViewController: homeVc)
let revealController = SWRevealViewController(rearViewController: sideVc, frontViewController: homeNav)
revealController?.delegate = self
self.window?.rootViewController = revealController
self.window?.makeKeyAndVisible()
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
//如果已存在后台任务,先将其设为完成
/*
if self.backgroundTask != nil {
application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskInvalid
}
*/
//如果要后台运行
//注册后台任务
self.backgroundTask = application.beginBackgroundTask(expirationHandler: {
() -> Void in
//如果没有调用endBackgroundTask,时间耗尽时应用程序将被终止
application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskInvalid
})
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
extension AppDelegate: SWRevealViewControllerDelegate {
@nonobjc func revealController(_ revealController: SWRevealViewController, animationControllerFor operation: SWRevealControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> Any? {
if operation != SWRevealControllerOperationReplaceRightController {
return nil
}
return nil
}
}
extension AppDelegate {
fileprivate func setUpAllThird() {
// 注册高德地图以及设置支持https
AMapServices.shared().enableHTTPS = true
AMapServices.shared().apiKey = "7728ab18dd2abf89a6299740e270f4c6"
}
}
|
841e0a8572d3f7581ad11b354021bd26
| 38 | 285 | 0.702834 | false | false | false | false |
wireapp/wire-ios
|
refs/heads/develop
|
Wire-iOS/Sources/UserInterface/SelfProfile/TeamAccountView.swift
|
gpl-3.0
|
1
|
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import WireDataModel
final class TeamAccountView: AccountView {
override var collapsed: Bool {
didSet {
self.imageView.isHidden = collapsed
}
}
private let imageView: TeamImageView
private var teamObserver: NSObjectProtocol!
private var conversationListObserver: NSObjectProtocol!
override init?(account: Account, user: ZMUser? = nil, displayContext: DisplayContext) {
if let content = user?.team?.teamImageViewContent ?? account.teamImageViewContent {
imageView = TeamImageView(content: content, style: .big)
} else {
return nil
}
super.init(account: account, user: user, displayContext: displayContext)
isAccessibilityElement = true
accessibilityTraits = .button
shouldGroupAccessibilityChildren = true
imageView.contentMode = .scaleAspectFill
imageViewContainer.addSubview(imageView)
selectionView.pathGenerator = { size in
let radius = 6
let radii = CGSize(width: radius, height: radius)
let path = UIBezierPath(roundedRect: CGRect(origin: .zero, size: size),
byRoundingCorners: UIRectCorner.allCorners,
cornerRadii: radii)
return path
}
createConstraints()
update()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTap(_:)))
addGestureRecognizer(tapGesture)
if let team = user?.team {
teamObserver = TeamChangeInfo.add(observer: self, for: team)
team.requestImage()
}
}
private func createConstraints() {
let inset: CGFloat = CGFloat.TeamAccountView.imageInset
[imageView, imageViewContainer].prepareForLayout()
NSLayoutConstraint.activate([
imageView.leadingAnchor.constraint(equalTo: imageViewContainer.leadingAnchor, constant: inset),
imageView.topAnchor.constraint(equalTo: imageViewContainer.topAnchor, constant: inset),
imageView.trailingAnchor.constraint(equalTo: imageViewContainer.trailingAnchor, constant: -inset),
imageView.bottomAnchor.constraint(equalTo: imageViewContainer.bottomAnchor, constant: -inset)
])
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func update() {
super.update()
accessibilityValue = String(format: "conversation_list.header.self_team.accessibility_value".localized, self.account.teamName ?? "") + " " + accessibilityState
accessibilityIdentifier = "\(self.account.teamName ?? "") team"
}
func createDotConstraints() -> [NSLayoutConstraint] {
let dotSize: CGFloat = 9
let dotInset: CGFloat = 2
[dotView, imageViewContainer].prepareForLayout()
return [ dotView.centerXAnchor.constraint(equalTo: imageViewContainer.trailingAnchor, constant: -dotInset),
dotView.centerYAnchor.constraint(equalTo: imageViewContainer.topAnchor, constant: dotInset),
dotView.widthAnchor.constraint(equalTo: dotView.heightAnchor),
dotView.widthAnchor.constraint(equalToConstant: dotSize)
]
}
}
extension TeamAccountView: TeamObserver {
func teamDidChange(_ changeInfo: TeamChangeInfo) {
if changeInfo.imageDataChanged {
changeInfo.team.requestImage()
}
guard let content = changeInfo.team.teamImageViewContent else { return }
imageView.content = content
}
}
|
ade5642882cae9278fbc317d9518074b
| 35.727273 | 167 | 0.660666 | false | false | false | false |
hyperconnect/SQLite.swift
|
refs/heads/master
|
Carthage/Checkouts/SQLite.swift/Sources/SQLite/Extensions/Cipher.swift
|
mit
|
2
|
#if SQLITE_SWIFT_SQLCIPHER
import SQLCipher
/// Extension methods for [SQLCipher](https://www.zetetic.net/sqlcipher/).
/// @see [sqlcipher api](https://www.zetetic.net/sqlcipher/sqlcipher-api/)
extension Connection {
/// - Returns: the SQLCipher version
public var cipherVersion: String? {
return (try? scalar("PRAGMA cipher_version")) as? String
}
/// Specify the key for an encrypted database. This routine should be
/// called right after sqlite3_open().
///
/// @param key The key to use.The key itself can be a passphrase, which is converted to a key
/// using [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2) key derivation. The result
/// is used as the encryption key for the database.
///
/// Alternatively, it is possible to specify an exact byte sequence using a blob literal.
/// With this method, it is the calling application's responsibility to ensure that the data
/// provided is a 64 character hex string, which will be converted directly to 32 bytes (256 bits)
/// of key data.
/// e.g. x'2DD29CA851E7B56E4697B0E1F08507293D761A05CE4D1B628663F411A8086D99'
/// @param db name of the database, defaults to 'main'
public func key(_ key: String, db: String = "main") throws {
try _key_v2(db: db, keyPointer: key, keySize: key.utf8.count)
}
public func key(_ key: Blob, db: String = "main") throws {
try _key_v2(db: db, keyPointer: key.bytes, keySize: key.bytes.count)
}
/// Change the key on an open database. If the current database is not encrypted, this routine
/// will encrypt it.
/// To change the key on an existing encrypted database, it must first be unlocked with the
/// current encryption key. Once the database is readable and writeable, rekey can be used
/// to re-encrypt every page in the database with a new key.
public func rekey(_ key: String, db: String = "main") throws {
try _rekey_v2(db: db, keyPointer: key, keySize: key.utf8.count)
}
public func rekey(_ key: Blob, db: String = "main") throws {
try _rekey_v2(db: db, keyPointer: key.bytes, keySize: key.bytes.count)
}
// MARK: - private
private func _key_v2(db: String, keyPointer: UnsafePointer<UInt8>, keySize: Int) throws {
try check(sqlite3_key_v2(handle, db, keyPointer, Int32(keySize)))
try cipher_key_check()
}
private func _rekey_v2(db: String, keyPointer: UnsafePointer<UInt8>, keySize: Int) throws {
try check(sqlite3_rekey_v2(handle, db, keyPointer, Int32(keySize)))
}
// When opening an existing database, sqlite3_key_v2 will not immediately throw an error if
// the key provided is incorrect. To test that the database can be successfully opened with the
// provided key, it is necessary to perform some operation on the database (i.e. read from it).
private func cipher_key_check() throws {
let _ = try scalar("SELECT count(*) FROM sqlite_master;")
}
}
#endif
|
9719fc73b40a6da4f8c7ecc13d7bff85
| 45.651515 | 113 | 0.659305 | false | false | false | false |
itsbriany/Weather
|
refs/heads/master
|
Weather/Weather/WeatherEntryModel.swift
|
apache-2.0
|
1
|
//
// WeatherEntryModel.swift
// Weather
//
// Created by Brian Yip on 2016-02-11.
// Copyright © 2016 Brian Yip. All rights reserved.
//
import Foundation
public class WeatherEntryModel: NSCopying {
// MARK: Properties
var summary: String?
var title: String?
// MARK: Constructors
init(weatherEntryModel: WeatherEntryModel) {
self.summary = weatherEntryModel.summary
self.title = weatherEntryModel.title
}
init(summary: String, title: String) {
self.summary = summary
self.title = title
}
init() {
self.summary = ""
self.title = ""
}
// MARK: NSCopying implementation
@objc public func copyWithZone(zone: NSZone) -> AnyObject {
return WeatherEntryModel(weatherEntryModel: self)
}
// MARK: Interface
func reset() {
self.summary?.removeAll()
self.title?.removeAll()
}
func copy() -> WeatherEntryModel {
return copyWithZone(nil) as! WeatherEntryModel
}
}
|
45f7fb1cef26059e8730bf716cf427ee
| 19.901961 | 63 | 0.597183 | false | false | false | false |
CartoDB/mobile-ios-samples
|
refs/heads/master
|
AdvancedMap.Swift/Feature Demo/RotationListener.swift
|
bsd-2-clause
|
1
|
//
// MapClickListener.swift
// AdvancedMap.Swift
//
// Created by Aare Undo on 24/07/2017.
// Copyright © 2017 CARTO. All rights reserved.
//
import Foundation
import UIKit
import CartoMobileSDK
class RotationListener: NTMapEventListener {
var delegate: RotationDelegate?
var map: NTMapView!
var previousAngle: CGFloat?
var previousZoom: CGFloat?
override func onMapMoved() {
let angle = CGFloat(map.getRotation())
let zoom = CGFloat(map.getZoom())
if (previousAngle != angle) {
delegate?.rotated(angle: angle)
previousAngle = angle
} else if (previousZoom != zoom) {
delegate?.zoomed(zoom: zoom)
previousZoom = zoom
}
}
}
protocol RotationDelegate {
func rotated(angle: CGFloat)
func zoomed(zoom: CGFloat)
}
|
38ea826361f47edf77d62d5e087abb5c
| 20.463415 | 48 | 0.611364 | false | false | false | false |
JQJoe/RxDemo
|
refs/heads/develop
|
Carthage/Checkouts/RxSwift/RxExample/RxExample/Example.swift
|
apache-2.0
|
8
|
//
// Example.swift
// RxExample
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
typealias Image = UIImage
#elseif os(macOS)
import Cocoa
import AppKit
typealias Image = NSImage
#endif
let MB = 1024 * 1024
func exampleError(_ error: String, location: String = "\(#file):\(#line)") -> NSError {
return NSError(domain: "ExampleError", code: -1, userInfo: [NSLocalizedDescriptionKey: "\(location): \(error)"])
}
extension String {
func toFloat() -> Float? {
let numberFormatter = NumberFormatter()
return numberFormatter.number(from: self)?.floatValue
}
func toDouble() -> Double? {
let numberFormatter = NumberFormatter()
return numberFormatter.number(from: self)?.doubleValue
}
}
func showAlert(_ message: String) {
#if os(iOS)
UIAlertView(title: "RxExample", message: message, delegate: nil, cancelButtonTitle: "OK").show()
#elseif os(macOS)
let alert = NSAlert()
alert.messageText = message
alert.runModal()
#endif
}
|
3ed8f9716fe80194e28233f9a0a69c47
| 24 | 116 | 0.646957 | false | false | false | false |
practicalswift/Pythonic.swift
|
refs/heads/master
|
src/Pythonic-test.swift
|
mit
|
1
|
#!/usr/bin/env swift -I .
import Pythonic
// ** (power operator)
assert(1 + 2**2 + 2 == 7)
assert(1 + 2.0**2.0 + 2 == 7)
assert(1**1 + 2.0**2.0 + 2 == 7)
assert(2 * 2 ** 2 * 3 ** 2 * 3 ** 3 == 1944)
assert(2**2 == 4)
assert(2.0**2.0 == 4)
// abs
assert(abs(-0.1) == 0.1)
assert(abs(-1) == 1)
// all
assert(!all(["", "bar", "baz"]))
assert(!all([false, false, false]))
assert(!all([false, false, true]))
assert(all(["foo", "bar", "baz"]))
assert(all([0.0001, 0.0001]))
assert(all([true, true, true]))
// any
assert(!any([0, 0]))
assert(!any([false, false, false]))
assert(any(["", "foo", "bar", "baz"]))
assert(any([0.1, 0]))
assert(any([false, false, true]))
// bin
assert(bin(2) == "0b10")
assert(bin(7) == "0b111")
assert(bin(1024) == "0b10000000000")
// bool
assert(!bool(""))
assert(!bool(0))
assert(bool("foo"))
assert(bool(1))
assert(bool([1]))
// assert(!bool(set([]))) // error: could not find an overload for 'assert' that accepts the supplied arguments
// chr
assert(chr(97) == "a")
assert(chr(ord("b")) == "b")
assert(ord(chr(255)) == 255)
// cmp
assert(cmp("bar", "bar") == 0)
assert(cmp("bar", "foo") == -1)
assert(cmp("foo", "bar") == 1)
assert(cmp(0, 0) == 0)
assert(cmp(0, 1) == -1)
assert(cmp(1, 0) == 1)
assert(cmp([1, 2, 3, 100], [1, 2, 3, 100]) == 0)
assert(cmp([1, 2, 3, 100], [1, 2, 3, 1]) == 1)
assert(cmp([1, 2, 3, 100], [2, 3, 4, 5]) == -1)
assert(cmp([8, 1, 9, 2], [100, 3, 7, 8]) == -1)
assert(cmp([8, 1, 9, 2], [3, 7, 8, 1]) == 1)
assert(cmp([8, 1, 9, 2], [7, 8, 1, 10000]) == 1)
assert(cmp([8, 1, 9, 2], [8, 1, 100, 100]) == -1)
assert(cmp([8, 1, 9, 2], [1, 100, 100, 100]) == 1)
assert(cmp([8, 1, 9, 2], [100, 100, 100, 100]) == -1)
assert(cmp([1, 9, 2, 100], [100, 100, 100, 100]) == -1)
assert(cmp([9, 2, 100, 100], [100, 100, 100, 100]) == -1)
assert(cmp([2, 100, 100, 100], [100, 100, 100, 100]) == -1)
assert(cmp([100, 100, 100, 100], [100, 100, 100, 100]) == 0)
assert(cmp([0, 0], [0, 0]) == 0)
assert(cmp([0, 0], [0, 1]) == -1)
assert(cmp([0, 0], [1, 0]) == -1)
assert(cmp([0, 0], [1, 1]) == -1)
assert(cmp([0, 1], [0, 0]) == 1)
assert(cmp([0, 1], [0, 1]) == 0)
assert(cmp([0, 1], [1, 0]) == -1)
assert(cmp([0, 1], [1, 1]) == -1)
assert(cmp([1, 0], [0, 0]) == 1)
assert(cmp([1, 0], [0, 1]) == 1)
assert(cmp([1, 0], [1, 0]) == 0)
assert(cmp([1, 0], [1, 1]) == -1)
assert(cmp([1, 1], [0, 0]) == 1)
assert(cmp([1, 1], [0, 1]) == 1)
assert(cmp([1, 1], [1, 0]) == 1)
assert(cmp([1, 1], [1, 1]) == 0)
assert(cmp([1, 1, 1], [0, 0]) == 1)
assert(cmp([1, 1, 0], [0, 0]) == 1)
assert(cmp([1, 1], [0, 0, 0]) == 1)
assert(cmp([1, 1], [0, 0, 1]) == 1)
assert(cmp([0, 1, 1, 1], [0, 0]) == 1)
assert(cmp([1, 1, 1, 0], [0, 0]) == 1)
assert(cmp([1, 1], [1, 0, 0, 0]) == 1)
assert(cmp([1, 1], [0, 1, 0, 1]) == 1)
assert(cmp([1, 1, 1], [0, 0, 0]) == 1)
assert(cmp([1, 1, 0], [0, 1, 0]) == 1)
assert(cmp([1, 1], [0, 1, 0, 0]) == 1)
assert(cmp([1, 1, 0], [0, 0, 1]) == 1)
assert(cmp([1, 1, 1], [0, 1, 0]) == 1)
assert(cmp([1, 1, 0], [0, 0, 0]) == 1)
assert(cmp([1, 1], [0, 0, 1, 0]) == 1)
assert(cmp([1, 1], [1, 0, 0, 1]) == 1)
assert(cmp([0, 1, 1, 1], [0, -1, 0]) == 1)
assert(cmp([1, 1, -1, 1, 0], [0, 0]) == 1)
assert(cmp([1, 1, -1], [1, 0, 0, 0]) == 1)
assert(cmp([1, 1], [0, -1, 1, 0, 1]) == 1)
assert(cmp([1, 1, 1], [0, -1, 0, 0]) == 1)
assert(cmp([1, 1, 0], [0, 1, -1, 0]) == 1)
assert(cmp([1, 1], [0, 1, 0, 0, -1]) == 1)
assert(cmp([1, 1, 0], [0, -1, 0, 1]) == 1)
assert(cmp([1, 1, 1], [-1, 0, 1, 0]) == 1)
assert(cmp([1, 1, 0, -1], [0, 0, 0]) == 1)
assert(cmp([1, -1, 1], [0, 0, 1, 0]) == 1)
assert(cmp([-1, 1, 1], [1, 0, 0, 1]) == -1)
assert(cmp([-1, -1, 1], [1, 0, 0, 1]) == -1)
assert(cmp([-1, -1, -1], [1, 0, 0, 1]) == -1)
assert(cmp([-1, -1, -1], [0, 0, 0, 1]) == -1)
assert(cmp([-1, -1, -1], [0, 0, 0, 0]) == -1)
// double (truthness)
assert(bool(0.00000001))
assert(bool(1.0))
assert(!bool(0.0))
// double.is_integer/isInteger
assert(!0.000000000001.is_integer())
assert(!1.1.is_integer())
assert(1.0.is_integer())
// file
// TODO: Missing test.
// float
assert(!bool(float(0.0)))
assert(bool(float(0 + 0.0001)))
assert(bool(float(0.00000001)))
assert(bool(float(1.0)))
// float.is_integer
assert(!float(1.1).is_integer())
assert(float(1.0).is_integer())
assert(float(100).is_integer())
// hex
assert(hex(0) == "0x0")
assert(hex(1) == "0x1")
assert(hex(10) == "0xa")
assert(hex(100) == "0x64")
assert(hex(1000) == "0x3e8")
assert(hex(10000000) == "0x989680")
// int
assert(int(1.1) == 1)
assert(int(9.9) == 9)
// int (truthness)
assert(bool(1))
assert(!bool(0))
// json
assert(json.dumps([1, 2, 3]).replace("\n", "").replace(" ", "") == "[1,2,3]")
// len
assert(len("") == 0)
assert(len("\t") == 1)
assert(len("foo") == 3)
assert(len(["foo", "bar", "baz"]) == 3)
assert(len(["foo", "bar"]) == 2)
assert(len(["foo"]) == 1)
// list
assert(list([1, 2, 3]) == [1, 2, 3])
assert(list([1, 2, 3]).count(1) == 1)
// list (truthness)
assert(bool([1, 2, 3]))
assert(bool([1, 2]))
assert(bool([1]))
// list(set)
assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(0) == 0)
assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(1) == 1)
assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(2) == 1)
assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(3) == 1)
assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(4) == 1)
assert(list(set([1, 2, 3, 1, 2, 3, 4])).count(5) == 0)
// list.count
assert([1, 2, 2, 3, 3, 3].count(1) == 1)
assert([1, 2, 2, 3, 3, 3].count(2) == 2)
assert([1, 2, 2, 3, 3, 3].count(3) == 3)
assert([1, 2, 3].count(4) == 0)
// list.index
assert(["foo", "bar", "baz"].index("baz") == 2)
assert([1, 2, 3].index(3) == 2)
assert(list(["a", "b", "c"]).index("b") == 1)
// literals
assert(0b0 == 0)
assert(0b111111111111111111111111111111111111111111111111111111111111111 == 9223372036854775807)
assert(0o00 == 0)
assert(0o10 == 8)
assert(0o11 == 9)
assert(0x00 == 0)
assert(0xff == 255)
assert(1.25e-2 == 0.0125)
assert(1.25e2 == 125)
// long
assert(long(1.1) == 1)
// math.acos
assert(math.acos(-1) == math.pi)
// math.asin
assert(math.asin(1) == math.pi / 2)
// math.atan
assert(math.atan(1) == math.pi / 4)
// math.cos
assert(math.cos(math.pi) == -1)
// math.degrees
assert(math.degrees(math.pi) == 180)
// math.factorial
assert(math.factorial(0) == 1)
assert(math.factorial(20) == 2432902008176640000)
// math.pow
assert(math.pow(2, 2) == 4)
assert(math.pow(2.0, 2.0) == 4.0)
// math.radians
assert(math.radians(270) == math.pi * 1.5)
// math.sin
assert(math.sin(math.pi / 2) == 1)
// math.sqrt
assert(math.sqrt(9) == 3)
// math.tan
// Python returns 0.999... for tan(π / 4)
assert(math.tan(math.pi / 4) <= 1)
assert(math.tan(math.pi / 4) > 0.9999999)
// max
assert(max(1, 2) == 2)
assert(max(1, 2, 3) == 3)
assert(max([1, 2, 3]) == 3)
assert(max([1, 2]) == 2)
// min
assert(min(1, 2) == 1)
assert(min(1, 2, 3) == 1)
assert(min([1, 2, 3]) == 1)
assert(min([1, 2]) == 1)
// object
assert(bool(object()))
// oct
assert(oct(0) == "0")
assert(oct(1) == "01")
assert(oct(10) == "012")
assert(oct(100) == "0144")
assert(oct(1000) == "01750")
// assert(oct(100000000000) == "01351035564000")
// open
assert(open("Pythonic-test.txt").read().splitlines()[2] == "This test file is being read")
// ord
assert(ord("a") == 97)
assert(ord(chr(98)) == 98)
// os.getcwd()
assert(bool(os.getcwd()))
// os.path.exists
assert(!os.path.exists("/tmp.foo/"))
assert(os.path.exists("/tmp/"))
assert(os.path.exists("Pythonic-test.txt"))
// os.path.join
assert(os.path.join("a", "b", "c") == "a/b/c")
assert(os.path.join("/a", "b", "c") == "/a/b/c")
// os.system (+ os.unlink + os.path.exists)
os.unlink("/tmp/pythonic-test.txt")
assert(os.system("/usr/bin/touch /tmp/pythonic-test.txt") == 0)
assert(os.path.exists("/tmp/pythonic-test.txt"))
os.unlink("/tmp/pythonic-test.txt")
// pow
assert(pow(2.0, 2.0) == 4.0)
// random.random
assert(random.random() < 1)
// random.randint
assert(random.randint(0, 10) <= 10)
// random.randrange
assert(random.randrange(0, 10) <= 9)
// range
assert(range(0) == [])
assert(range(0, 10, 2) == [0, 2, 4, 6, 8])
assert(range(0, 5, -1) == [])
assert(range(0, 50, 7) == [0, 7, 14, 21, 28, 35, 42, 49])
assert(range(1, 0) == [])
assert(range(1, 11) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
assert(range(10) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
// re.search
assert(!re.search("^bar", "foobarbaz"))
assert(!re.search("hello", "foobarbaz"))
assert(re.search("[\r\n]", "foo\rfoo").group(0) == "\r")
assert(re.search("\r\n", "foo\r\nfoo").group(0) == "\r\n")
assert(bool(re.search("^foo", "foobarbaz")))
assert(re.search("^foo", "foobarbaz").group(0) == "foo")
assert(bool(re.search("^foo.*baz$", "foobarbaz")))
assert(bool(re.search("foo", "foobarbaz")))
assert(bool(re.search("o", "foobarbaz")))
// re.match
assert(!re.match("^(.*)(([fo]+|[bar]+)|([bar]+|[baz+]))(.*)$", "foobarbazfoobarbaz").groups()[2])
assert(!re.match("^(.*)(([fo]+|[bar]+)|([bar]+|[baz+]))(.*)$", "foobarbazfoobarbaz").groups()[4])
assert(!re.match("o", "foobarbaz"))
assert(!re.search("zoo", "barfoobar"))
assert(len(re.match("^((foo|bar|baz)|foobar)*$", "foobarbazfoobarbaz").groups()) == 2)
assert(len(re.search("foo", "barfoobar").groups()) == 0)
assert(list(re.match("(.*) down (.*) on (.*)", "Bugger all down here on earth!").groups()) == ["Bugger all", "here", "earth!"])
assert(list(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").groups()) == ["Hello foo bar baz", "foo", "bar", "baz"])
assert(list(re.match("Hello[ \t]*(.*)world", "Hello Python world").groups())[0] == "Python ")
assert(list(re.search("/(.*)/(.*)/(.*)", "/var/tmp/foo").groups()) == ["var", "tmp", "foo"])
assert(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").group(0) == "Hello foo bar baz")
assert(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").group(1) == "Hello foo bar baz")
assert(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").group(2) == "foo")
assert(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").group(3) == "bar")
assert(re.match("(Hello (foo) (bar) (baz))", "Hello foo bar baz").group(4) == "baz")
assert(re.match("/(.*)/(.*)/(.*)", "/var/tmp/foo").groups()[0] == "var")
assert(re.match("/(.*)/(.*)/(.*)", "/var/tmp/foo").groups()[1] == "tmp")
assert(re.match("/(.*)/(.*)/(.*)", "/var/tmp/foo").groups()[2] == "foo")
assert(re.match("Hello[ \t]*(.*)world", "Hello Python world").group(0) == "Hello Python world")
assert(re.match("Hello[ \t]*(.*)world", "Hello Python world").group(1) == "Python ")
assert(re.match("^((foo|bar|baz)|foobar)*$", "foobarbazfoobarbaz").groups()[0] == "baz")
assert(re.match("^((foo|bar|baz)|foobar)*$", "foobarbazfoobarbaz").groups()[1] == "baz")
assert(re.match("^(.*)(([fo]+|[bar]+)|([bar]+|[baz+]))(.*)$", "foobarbazfoobarbaz").groups()[0] == "foobarbazfoobarba")
assert(re.match("^(.*)(([fo]+|[bar]+)|([bar]+|[baz+]))(.*)$", "foobarbazfoobarbaz").groups()[1] == "z")
assert(re.match("^(.*)(([fo]+|[bar]+)|([bar]+|[baz+]))(.*)$", "foobarbazfoobarbaz").groups()[3] == "z")
assert(bool(re.match("^foo", "foobarbaz")))
assert(bool(re.match("foo", "foobarbaz")))
assert(bool(re.search("foo", "barfoobar")))
// re.split
assert(re.split("/", "") == [""])
assert(re.split("/", "/") == ["", ""])
assert(re.split("/", "foo/") == ["foo", ""])
assert(re.split("/", "foo/bar") == ["foo", "bar"])
assert(re.split("/", "foo/bar/") == ["foo", "bar", ""])
assert(re.split("/", "foo/bar/baz") == ["foo", "bar", "baz"])
assert(re.split("/", "foo/bar/baz/") == ["foo", "bar", "baz", ""])
assert(re.split("[0-9]", "e8f8z888ee88ch838h23fhh3h2ui388sh3") == ["e", "f", "z", "", "", "ee", "", "ch", "", "", "h", "", "fhh", "h", "ui", "", "", "sh", ""])
assert(re.split("[0-9]", "foo/bar/baz") == ["foo/bar/baz"])
assert(re.split("[0-9]", "foo/bar/baz/") == ["foo/bar/baz/"])
assert(re.split("[XY]+", "aXYbXYc") == ["a", "b", "c"])
assert(re.split("[\r\n]", "\r\n\t\t\r\n\r\t\n\r\r\n\n\t\t") == ["", "", "\t\t", "", "", "\t", "", "", "", "", "\t\t"])
assert(re.split("[\r\n]+", "foo\naw\tef\roa\r\nwef") == ["foo", "aw\tef", "oa", "wef"])
assert(re.split("[^a-z]", "e8f8z888ee88ch838h23fhh3h2ui388sh3") == ["e", "f", "z", "", "", "ee", "", "ch", "", "", "h", "", "fhh", "h", "ui", "", "", "sh", ""])
assert(re.split("[a-z]", "e8f8z888ee88ch838h23fhh3h2ui388sh3") == ["", "8", "8", "888", "", "88", "", "838", "23", "", "", "3", "2", "", "388", "", "3"])
assert(re.split("a-z", "e8f8z888ee88ch838h23fhh3h2ui388sh3") == ["e8f8z888ee88ch838h23fhh3h2ui388sh3"])
assert(re.split("[^a-zA-Z0-9]", "foo bar baz") == ["foo", "bar", "baz"])
assert(re.split("\\s(?=\\w+:)", "foo:bar baz:foobar") == ["foo:bar", "baz:foobar"])
assert(re.split("[^a-z]", "foo1bar2baz3foo11bar22baz33foo111bar222baz333") == ["foo", "bar", "baz", "foo", "", "bar", "", "baz", "", "foo", "", "", "bar", "", "", "baz", "", "", ""])
assert(re.split("[^a-z]+", "foo12345foobar123baz1234567foobarbaz123456789bazbarfoo") == ["foo", "foobar", "baz", "foobarbaz", "bazbarfoo"])
assert(re.split("[^a-z]+", "foo12345foobar123baz1234567foobarbaz123456789bazbarfoo12345") == ["foo", "foobar", "baz", "foobarbaz", "bazbarfoo", ""])
assert(re.split("[^a-z]+", "12345foo12345foobar123baz1234567foobarbaz123456789bazbarfoo12345") == ["", "foo", "foobar", "baz", "foobarbaz", "bazbarfoo", ""])
assert(re.split("([^a-z]+)", "foo12345foobar123baz1234567foobarbaz123456789bazbarfoo") == ["foo", "12345", "foobar", "123", "baz", "1234567", "foobarbaz", "123456789", "bazbarfoo"])
assert(re.split("([^a-z]+)", "foo12345foobar123baz1234567foobarbaz123456789bazbarfoo12345") == ["foo", "12345", "foobar", "123", "baz", "1234567", "foobarbaz", "123456789", "bazbarfoo", "12345", ""])
assert(re.split("([^a-z]+)", "12345foo12345foobar123baz1234567foobarbaz123456789bazbarfoo12345") == ["", "12345", "foo", "12345", "foobar", "123", "baz", "1234567", "foobarbaz", "123456789", "bazbarfoo", "12345", ""])
assert(re.split("([^a-zA-Z0-9])", "foo bar baz") == ["foo", " ", "bar", " ", "baz"])
assert(re.split("(abc)", "abcfooabcfooabcfoo") == ["", "abc", "foo", "abc", "foo", "abc", "foo"])
assert(re.split("abc", "abcfooabcfooabcfoo") == ["", "foo", "foo", "foo"])
// assert(re.split("(a)b(c)", "abcfooabcfooabcfoo") == ["", "a", "c", "foo", "a", "c", "foo", "a", "c", "foo"]) // Failing edge case which is not Python compatible yet.
// re.sub
assert(re.sub("^foo", "bar", "foofoo") == "barfoo")
assert(re.sub("^zfoo", "bar", "foofoo") == "foofoo")
assert(re.sub("([^a-zA-Z0-9])foo([^a-zA-Z0-9])", "\\1bar\\2", "foobarfoobar foo bar foo bar") == "foobarfoobar bar bar bar bar")
// round
assert(round(1.1) == 1)
// set
assert(!(set([1, 2, 3]) < set([1, 2, 3])))
assert(!(set([4]) < set([1, 2, 3])))
assert(set([1, 1, 1, 2, 2, 3, 3, 4]) == set([1, 2, 3, 4]))
assert(set([1, 2, 3]) & set([3, 4, 5]) == set([3]))
assert(set([1, 2, 3]) - set([3, 4, 5]) == set([1, 2]))
assert(set([1, 2, 3]) | set([3, 4, 5]) == set([1, 2, 3, 4, 5]))
assert(bool(set([1, 2, 3])))
assert(set([1, 2]) < set([1, 2, 3]))
assert(bool(set([1, 2])))
assert(set([1]) < set([1, 2, 3]))
assert(bool(set([1])))
// set + split
assert(set("foo bar".split(" ")) == set(["foo", "bar"]))
// set.isdisjoint
assert(!set([1, 2, 3]).isdisjoint(set([3, 4, 5])))
assert(set([1, 2, 3]).isdisjoint(set([4, 8, 16])))
// str (conversion)
assert(str(123) == "123")
assert(str(1.23) == "1.23")
// str (indexing)
assert("foobar"[0] == "f")
assert("\r\t"[0] == "\r")
assert("\r\t"[1] == "\t")
// str (truthness)
assert(bool(" "))
assert(!bool(""))
// str (positive and negative indexing)
assert("foo"[-1] == "o")
assert("foo"[-2] == "o")
assert("foo"[0] == "f")
assert("foo"[len("foo")-1] == "o")
// str * int (repeat string)
assert("foo" * 3 == "foofoofoo")
assert("foo" * 3 == "foofoofoo")
assert(-1 * "foo" == "")
assert(0 * "foo" == "")
assert(1 * "foo" == "foo")
assert(2 * "foo" * 2 == "foofoofoofoo")
assert(2 * "foo" == "foofoo")
// str % tuple
assert("Hello %d! Number %s" % (1, "world") == "Hello 1! Number world")
assert("Hello %d!" % (1) == "Hello 1!")
assert("Hello %s! Number %d" % ("world", 1) == "Hello world! Number 1")
assert("Hello %s!" % ("world") == "Hello world!")
assert("With commit %d, this string building syntax is now %s!" % (197, "supported") == "With commit 197, this string building syntax is now supported!")
assert("foo %% bar %011d baz %s" % (100, "foobar") == "foo % bar 00000000100 baz foobar")
assert("foo %d" % (123) == "foo 123")
// str.capitalize
assert("".capitalize() == "")
assert("f".capitalize() == "F")
assert("fo".capitalize() == "Fo")
assert("foo baR".capitalize() == "Foo bar")
assert("foo".capitalize() == "Foo")
// str.center
assert("foo".center(5) == " foo ")
assert("foo".center(6, "-") == "-foo--")
assert("foobar".center(9, "-") == "--foobar-")
assert("foobar".center(4) == "foobar")
// str.count
assert("foo".count("f") == 1)
assert("foo".count("o") == 2)
assert("foo".count("b") == 0)
// str.endswith
assert("foobar".endswith("bar"))
// str.expandtabs
assert(len("\t".expandtabs()) == 8)
assert(len("\t".expandtabs(10)) == 10)
assert(len("\t\t".expandtabs(10)) == 20)
assert(len(("\t" * 2).expandtabs()) == 16)
assert("\t".expandtabs() == " " * 8)
// str.find
assert("foo".find("foobarfoobar") == -1)
assert("foobar".find("") == 0)
assert("foobar".find("bar") == 3)
assert("foobar".find("f") == 0)
assert("foobar".find("foobar") == 0)
assert("foobar".find("foobars") == -1)
assert("foobar".find("zbar") == -1)
// str.in (translated to "str1 in str" when running as Python code)
assert(!"foo".`in`("baz"))
assert(!"foobar".`in`(""))
assert("".`in`("foobar"))
assert("foo".`in`("foobar"))
assert("ob".`in`("foobar"))
// str.index
assert("foobar".index("foobar") == 0)
assert("foobar".index("") == 0)
assert("foobar".index("f") == 0)
assert("foobar".index("bar") == 3)
// str.isalnum
assert(!"foo ".isalnum())
assert("foo1".isalnum())
// str.isalpha
assert(!"foo1".isalpha())
assert("fooo".isalpha())
// str.isdigit
assert(!"foo1".isdigit())
assert("123".isdigit())
// str.islower
assert(!"FOO".islower())
assert("foo".islower())
// str.isspace
assert(!" x ".isspace())
assert(!" a\t".isspace())
assert(" ".isspace())
assert(" \t".isspace())
// str.istitle
assert(!"foo foo".istitle())
assert(!"foo".istitle())
assert("Foo Foo".istitle())
assert("Foo".istitle())
// str.isupper
assert(!"foo".isupper())
assert("FOO".isupper())
// str.join
assert(":".join(["foo", "bar", "baz"]) == "foo:bar:baz")
// str.ljust
assert("foo".ljust(5) == "foo ")
assert("foo".ljust(10, "-") == "foo-------")
assert("foobar".ljust(4) == "foobar")
// str.lower
assert("FooBar".lower() == "foobar")
// str.lstrip
assert(" \n\t foobar \n\t ".lstrip() == "foobar \n\t ")
// str.partition
assert("the first part\nthe second part".partition("\n") == ("the first part", "\n", "the second part"))
assert("the first part".partition("\n") == ("the first part", "", ""))
assert("the first part\n".partition("\n") == ("the first part", "\n", ""))
assert("\nthe second part".partition("\n") == ("", "\n", "the second part"))
// str.replace
assert("fzzbar".replace("z", "o") == "foobar")
// str.rfind
// assert("Foo Bar Baz Baz Qux".rfind("fubar") == -1) - Python raises ValueError
assert("Foo Bar Baz Baz Qux".rfind("Bar") == 4)
assert("Foo Bar Baz Baz Qux".rfind("Baz") == 12)
// assert("Foo Bar Baz Baz Qux".rfind("y") == -1) - Python raises ValueError
assert("Foo Bar Baz Baz Qux".rfind("Q") == 16)
assert("Foo Bar Baz Baz Qux".rfind("z") == 14)
// str.rindex
// assert("Foo Bar Baz Baz Qux".rindex("fubar") == -1) - Python raises ValueError
assert("Foo Bar Baz Baz Qux".rindex("Bar") == 4)
assert("Foo Bar Baz Baz Qux".rindex("Baz") == 12)
// assert("Foo Bar Baz Baz Qux".rindex("y") == -1) - Python raises ValueError
assert("Foo Bar Baz Baz Qux".rindex("Q") == 16)
assert("Foo Bar Baz Baz Qux".rindex("z") == 14)
// str.rjust
assert("foo".rjust(5) == " foo")
assert("foo".rjust(10, "-") == "-------foo")
assert("foobar".rjust(4) == "foobar")
// str.rpartition
assert("Foo Bar Baz Baz Qux".rpartition("fubar") == ("", "", "Foo Bar Baz Baz Qux"))
assert("Foo Bar Baz Baz Qux".rpartition("Bar") == ("Foo ", "Bar", " Baz Baz Qux"))
assert("Foo Bar Baz Baz Qux".rpartition("Baz") == ("Foo Bar Baz ", "Baz", " Qux"))
assert("Foo Bar Baz Baz Qux".rpartition("y") == ("", "", "Foo Bar Baz Baz Qux"))
assert("Foo Bar Baz Baz Qux".rpartition("Q") == ("Foo Bar Baz Baz ", "Q", "ux"))
assert("Foo Bar Baz Baz Qux".rpartition("z") == ("Foo Bar Baz Ba", "z", " Qux"))
// str.rstrip
assert(" \n\t foobar \n\t ".rstrip() == " \n\t foobar")
// str.split
assert("a\t\n\r\t\n\t\n\r\nb\r\nc\t".split() == ["a", "b", "c"])
assert("foo bar".split(" ") == ["foo", "bar"])
assert("foo:bar:baz".split(":") == ["foo", "bar", "baz"])
assert("foo\r\n \r\nbar\rfoo\nfoo\n\nfoo\n\n\nfoo".split() == ["foo", "bar", "foo", "foo", "foo", "foo"])
assert("foo\r\nbar\rfoo\nfoo\n\nfoo\n\n\nfoo".split() == ["foo", "bar", "foo", "foo", "foo", "foo"])
assert(len(open("Pythonic-test.txt").read().split()) == 23)
// str.splitlines
assert("foo\naw\tef\roa\r\nwef".splitlines() == ["foo", "aw\tef", "oa", "wef"])
assert("foo\rfoo\nfoo\r\nfoo\n\rfoo\nfoo".splitlines() == ["foo", "foo", "foo", "foo", "", "foo", "foo"])
assert("\nfoo\rfoo\nfoo\r\nfoo\n\rfoo\nfoo\n".splitlines() == ["", "foo", "foo", "foo", "foo", "", "foo", "foo"])
// str.startswith
assert("foobar".startswith("foo"))
// str.strip
assert(" \n foobar \n ".strip() == "foobar")
assert(" foobar ".strip() == "foobar")
assert("".strip() == "")
assert("foobar".strip() == "foobar")
assert(" \n\t foobar \n\t ".strip() == "foobar")
// str.swapcase
assert("foo".swapcase() == "FOO")
assert("FooBar".swapcase() == "fOObAR")
assert("›ƒé".swapcase() == "›ƒé")
// str.title
assert("foo bar".title() == "Foo Bar")
// str.upper
assert("FooBar".upper() == "FOOBAR")
// str.zfill
assert("foo".zfill(-1) == "foo")
assert("foo".zfill(0) == "foo")
assert("foo".zfill(1) == "foo")
assert("foo".zfill(10) == "0000000foo")
assert(len("foo".zfill(1000)) == 1000)
// sum
assert(sum([1, 2, 3]) == 6)
assert(sum([1, 2, 3], 1) == 7)
assert(sum([1.1, 1.2]) == 2.3)
// sys.argv
if len(sys.argv) == 1 && sys.argv[0] == "./Pythonic-test.swift" {
// Make sure test case passes also when run using shebang line.
sys.argv = ["./Pythonic-test", "arg1", "arg2"]
}
assert(sys.argv[0].startswith("./Pythonic-test"))
assert(sys.argv[1] == "arg1")
assert(sys.argv[2] == "arg2")
assert(len(sys.argv) == 3)
// sys.platform
assert(sys.platform == "darwin")
// time.time
assert(time.time() > 1405028001.224846)
// datetime
assert(datetime(2014, 7, 4) == datetime.strptime("07/04/14", "%m/%d/%y"))
assert(datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M").strftime("%d/%m/%y %H:%M") == "21/11/06 16:30")
assert(datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M").strftime("%d/%m/%y %H:%M") == "21/11/06 16:30")
// tuple – comparison of 2-part tuples
assert((1, 1) == (1, 1))
assert(!((1, 1) == (1, 214)))
// tuple – comparison of 3-part tuples
assert((1, 1, 1) == (1, 1, 1))
assert(!((1, 1, 1) == (1, 1, 214)))
// uuid
assert(len(uuid.uuid4().hex) == 32)
// xrange
assert(list(xrange(10)) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
assert(list(xrange(1, 10)) == [1, 2, 3, 4, 5, 6, 7, 8, 9])
let performPythonIncompatibleTests = true
if performPythonIncompatibleTests {
// dict (semantics + copy())
var dict1 = ["foo": 1]
assert(dict1["foo"] != nil)
assert(dict1["bar"] == nil)
var dict2 = dict1
dict2["bar"] = 2
assert(dict1["foo"] != nil)
assert(dict1["bar"] == nil)
assert(dict2["foo"] != nil)
assert(dict2["bar"] != nil)
var dict3 = dict1
dict3["bar"] = 3
assert(dict1["foo"] != nil)
assert(dict1["bar"] == nil)
assert(dict3["foo"] != nil)
assert(dict3["bar"] != nil)
// dict
assert(!dict<str, str>())
assert(bool(["foo": "bar"]))
assert(len(dict<str, str>()) == 0)
// dict.clear
var dict4 = ["foo": "bar"]
assert(bool(dict4))
dict4.clear()
assert(!bool(dict4))
// dict.fromkeys
assert(dict.fromkeys(["a", "b", "c"], 1) == ["a": 1, "c": 1, "b": 1])
// dict.items
var h = ["foo": 1, "bar": 2, "baz": 3]
var arrayOfTuples = h.items()
// NOTE: list.sort() sorts in place in Python, but not in Swift.
arrayOfTuples.sortInPlace() { $0.1 < $1.1 }
assert(arrayOfTuples[0].0 == "foo" && arrayOfTuples[0].1 == 1)
assert(arrayOfTuples[1].0 == "bar" && arrayOfTuples[1].1 == 2)
assert(arrayOfTuples[2].0 == "baz" && arrayOfTuples[2].1 == 3)
// divmod
assert(divmod(100, 9).0 == 11)
assert(divmod(100, 9).1 == 1)
assert(divmod(101.0, 8.0).0 == 12.0)
assert(divmod(101.0, 8.0).1 == 5.0)
assert(divmod(102.0, 7).0 == 14.0)
assert(divmod(102.0, 7).1 == 4.0)
assert(divmod(103, 6.0).0 == 17.0)
assert(divmod(103, 6.0).1 == 1.0)
// double.isInteger
let d1 = 1.0
let d2 = 1.1
assert(d1.isInteger())
assert(!d2.isInteger())
// float.isInteger
assert(float(1.0).isInteger())
assert(!float(1.1).isInteger())
// hasattr
class Baz {
let foo = "foobar"
let bar = "foobar"
}
let baz = Baz()
assert(hasattr(baz, "foo"))
assert(hasattr(baz, "baz") == false)
// list
assert(!list<int>())
// list.count + list.index + list.reverseInPlace
var arr: [String] = ["foo", "bar", "baz", "foo"]
assert(arr.count("foo") == 2)
arr.remove("foo")
assert(arr.count("foo") == 1)
assert(arr.index("bar") == 0)
arr.append("hello")
assert(arr.index("hello") == 3)
arr.reverseInPlace()
assert(arr.index("hello") == 0)
// list.index
assert(["foo", "bar", "baz"].index(1) == nil)
assert([1, 2, 3].index("foo") == nil)
assert([1, 2, 3].index(4) == nil)
// list.pop
var mutableArray = [1, 2, 3]
assert(mutableArray.pop() == 3)
assert(mutableArray.pop(0) == 1)
assert(mutableArray.pop(1) == nil)
assert(mutableArray.pop(0) == 2)
assert(mutableArray.pop() == nil)
// list.remove
var anotherMutableArray = [3, 2, 1, 3]
anotherMutableArray.remove(0)
assert(anotherMutableArray == [3, 2, 1, 3])
anotherMutableArray.remove(2)
assert(anotherMutableArray == [3, 1, 3])
anotherMutableArray.remove(1)
assert(anotherMutableArray == [3, 3])
anotherMutableArray.remove(3)
assert(anotherMutableArray == [3])
anotherMutableArray.remove(3)
assert(anotherMutableArray == [])
// len
assert(len(list<str>()) == 0)
assert(len(["foo": "bar"]) == 1)
assert(len(["foo": "bar", "baz": "foo"]) == 2)
// map
var mapObj = ["foo": "foobar"]
assert(len(mapObj) == 1)
assert(mapObj["foo"] != nil)
// map.get
assert(mapObj.get("foo") == "foobar")
// map.has_key/hasKey
assert(mapObj.has_key("foo"))
assert(mapObj.hasKey("foo"))
// map.pop
assert(mapObj.pop("foo") == "foobar")
assert(len(mapObj) == 0)
// map.popItem
mapObj["foo"] = "bar"
let t = mapObj.popItem()
assert(len(mapObj) == 0)
// map.clear
mapObj.clear()
assert(len(mapObj) == 0)
assert(mapObj["foobar"] == nil)
// open(…) [modes: w, a, r (default)] + fh.write + fh.close + os.path.exists
let temporaryTestFile = "/tmp/pythonic-io.txt"
var f = open(temporaryTestFile, "w")
f.write("foo")
f.close()
f = open(temporaryTestFile, "a")
f.write("bar\n")
f.close()
f = open(temporaryTestFile)
var foundText = false
for line in f {
if line == "foobar" {
foundText = true
}
}
assert(foundText)
assert(os.path.exists(temporaryTestFile))
os.unlink(temporaryTestFile)
assert(!os.path.exists(temporaryTestFile))
// os.popen3
var (stdin, stdout, stderr) = os.popen3("/bin/echo foo")
var foundOutput = false
for line in stdout {
if line == "foo" {
foundOutput = true
}
}
assert(foundOutput)
// os.popen2
foundOutput = false
(stdin, stdout) = os.popen2("/bin/echo foo")
for line in stdout {
if line == "foo" {
foundOutput = true
}
}
assert(foundOutput)
// random.choice
let array = ["foo", "bar"]
let randomChoice = random.choice(array)
assert(randomChoice == "foo" || randomChoice == "bar")
// re.search
assert(!re.search("", "foobarbaz"))
// re.search.group
assert(re.search("^foo", "foobarbaz")[0] == "foo")
// set
var emptyIntSet: Set<Int> = set()
assert(!emptyIntSet)
assert(set([1, 2, 3]) + set([3, 4, 5]) == set([1, 2, 3, 4, 5]))
assert(set([set([1, 2, 3]), set([1, 2, 3]), set([2, 4, 8])]) != set([set([1, 2, 3]), set([2, 4, 9])]))
assert(set([set([1, 2, 3]), set([1, 2, 3]), set([2, 4, 8])]) == set([set([1, 2, 3]), set([2, 4, 8])]))
assert(bool(set([1, 2, 3])))
var set1 = Set<Int>()
assert(len(set1) == 0)
set1 += 1
assert(len(set1) == 1)
assert(set1 == Set([1]))
set1.insert(2) // TODO: Should add Python style set.add(element).
assert(set1 == Set([1, 2]))
set1.insert(3)
assert(set1 == Set([1, 2, 3]))
set1.insert(1)
assert(set1 == Set([1, 2, 3]))
set1.insert(2)
assert(set1 == Set([1, 2, 3]))
set1.insert(3)
assert(set1 == Set([1, 2, 3]))
set1.remove(2)
assert(set1 == Set([1, 3]))
set1.remove(2)
assert(set1 == Set([1, 3]))
set1 -= 2
assert(set1 == Set([1, 3]))
var set2 = Set([1, 8, 16, 32, 64, 128])
assert(set2 == Set([128, 64, 32, 16, 8, 1]))
var set3 = set1 + set2
assert(set3 == Set([128, 64, 32, 16, 8, 1, 3]))
var set4 = set1 - set2
assert(set4 == Set([3]))
set4 += set2
assert(set4 == Set([128, 64, 32, 16, 8, 1, 3]))
set4 -= set2
assert(set4 == Set([3]))
var set5 = Set(set4)
assert(set5 == Set([3]))
assert(set5 == set4)
var set6 = Set([1, 2, 3]) & Set([1, 3])
assert(set6 == Set([1, 3]))
set6 &= set6
assert(set6 == Set([1, 3]))
var set7 = Set([1, 2, 3]) | Set([1, 3])
assert(set7 == Set([1, 2, 3]))
set7 |= set7
assert(set7 == Set([1, 2, 3]))
var set8: Set<Int> = [1, 2, 3]
assert(len(set8) == 3)
var set9 = Set([0, 1, 2])
set9.insert(3)
set9.insert(3)
assert(set9 == Set([0, 1, 2, 3]))
var set10 = Set([2, 4, 8, 16])
assert(set9 + set10 == Set([0, 1, 2, 3, 4, 8, 16]))
assert(set9 - set10 == Set([0, 1, 3]))
assert(set9 & set10 == Set([2]))
assert(set([1, 2, 3]).contains(1))
assert(!set([1, 2, 3]).contains(4))
// statistics.mean
assert(statistics.mean([-1.0, 2.5, 3.25, 5.75]) == 2.625)
assert(statistics.mean([0.5, 0.75, 0.625, 0.375]) == 0.5625)
assert(statistics.mean([1, 2, 3, 4, 4]) == 2.8)
// statistics.median
assert(statistics.median([1, 3, 5, 7]) == 4.0)
assert(statistics.median([1, 3, 5]) == 3)
assert(statistics.median([2, 3, 4, 5]) == 3.5)
// statistics.median_high
assert(statistics.median_high([1, 3, 5]) == 3)
assert(statistics.median_high([1, 3, 5, 7]) == 5)
// statistics.median_low
assert(statistics.median_low([1, 3, 5]) == 3)
assert(statistics.median_low([1, 3, 5, 7]) == 3)
// str (handling of "\r\n" not compatible with Python)
assert("\r\n\t"[0] == "\r\n")
assert("\r\n\t"[1] == "\t")
// str.endsWith
assert("foobar".endsWith("bar"))
// str.index
assert("foobar".index("foobars") == -1)
assert("foobar".index("zbar") == -1)
// str.split
assert("foobar".split("") == ["foobar"])
// str.startsWith
assert("foobar".startsWith("foo"))
// str.title
assert("they're bill's friends from the UK".title() == "They're Bill's Friends From The Uk")
// str[(Int?, Int?)]
assert("Python"[(nil, 2)] == "Py")
assert("Python"[(2, nil)] == "thon")
assert("Python"[(2, 4)] == "th")
assert("Python"[(nil, -3)] == "Pyt")
assert("Python"[(-3, nil)] == "hon")
// str[range]
assert("foobar"[0..<3] == "foo")
// time.sleep
time.sleep(0.001)
// datetime
let day = datetime.strptime("11/08/14 21:13", "%d/%m/%y %H:%M")
assert(day.strftime("%a %A %w %d %b %B %m %y %Y") == "Mon Monday 1 11 Aug August 08 14 2014")
assert(day.strftime("%H %I %p %M %S %f %j %%") == "21 09 pm 13 00 000000 223 %" || day.strftime("%H %I %p %M %S %f %j %%") == "21 09 PM 13 00 000000 223 %")
assert(day.strftime("It's day number %d; the month is %B.") == "It's day number 11; the month is August.")
assert(day.isoformat(" ") == "2014-08-11 21:13:00")
// timedelta
let year = timedelta(days: 365)
let anotherYear = timedelta(weeks: 40, days: 84, hours: 23, minutes: 50, seconds: 600)
assert(year.total_seconds() == 31536000.0)
assert(year == anotherYear)
// datetime & timedelta
let oneDayDelta = timedelta(days: 1)
let nextDay = day + oneDayDelta
let previousDay = day - oneDayDelta
assert(nextDay - previousDay == oneDayDelta * 2)
let otherDay = day.replace(day: 15, hour: 22)
assert(otherDay - nextDay == timedelta(days: 3, seconds: 60 * 60))
// zip
let zipped = zip([3, 4], [9, 16])
// let (l1, r1) = zipped[0]
// assert(l1 == 3 && r1 == 9)
// let (l2, r2) = zipped[1]
// assert(l2 == 4 && r2 == 16)
// file.__iter__ , as in "for line in open(filename)"
var filehandletest = ""
for line in fileHandleFromString("line 1\nline 2\n") {
filehandletest += line + "\n"
}
assert(filehandletest == "line 1\nline 2\n")
assert(["line 1", "line 2"] == Array(fileHandleFromString("line 1\nline 2\n")))
assert(["line 1"] == Array(fileHandleFromString("line 1\n")))
assert(["line 1"] == Array(fileHandleFromString("line 1")))
assert(["line 1", "", "line 3"] == Array(fileHandleFromString("line 1\n\nline 3")))
assert(["", "line 2", "line 3"] == Array(fileHandleFromString("\nline 2\nline 3")))
assert(["", "", "line 3"] == Array(fileHandleFromString("\n\nline 3")))
// Others:
assert("foobar"[0..<2] == "fo")
assert(bool("x" as Character))
}
let performTestsRequiringNetworkConnectivity = false
if performTestsRequiringNetworkConnectivity &&
performPythonIncompatibleTests {
let getTest = requests.get("http://httpbin.org/get")
print("GET:")
print(getTest.text)
let postDataString = "…"
let postTestWithString = requests.post("http://httpbin.org/post", postDataString)
print("POST(str):")
print(postTestWithString.text)
let postDataDict = ["…": "…", "key": "value", "number": "123"]
let postTestWithDict = requests.post("http://httpbin.org/post", postDataDict)
print("POST(dict):")
print(postTestWithDict.text)
}
sys.exit()
|
0f9ab0ddd5060969ecf66f4668e95a3d
| 32.038278 | 217 | 0.555076 | false | false | false | false |
ciamic/VirtualTourist
|
refs/heads/master
|
VirtualTourist/VirtualTouristMapViewController.swift
|
mit
|
1
|
//
// VirtualTouristMapViewController.swift
//
// Copyright (c) 2017 michelangelo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import MapKit
import CoreData
class VirtualTouristMapViewController: UIViewController {
// MARK: Outlets
@IBOutlet weak var mapView: MKMapView!
@IBOutlet var longPressGestureRecognizer: UILongPressGestureRecognizer!
@IBOutlet weak var removePinLabel: UILabel!
@IBOutlet weak var editBarButtonItem: UIBarButtonItem!
// MARK: Properties
fileprivate var isEditMode = false //true if we are in edit mode (i.e. can delete Pins)
private lazy var fetchedResultsController: NSFetchedResultsController<Pin> = {
let request = NSFetchRequest<Pin>(entityName: "Pin")
request.sortDescriptors = [NSSortDescriptor(key: "latitude", ascending: true)]
let fetchedResultsController = NSFetchedResultsController<Pin>(fetchRequest: request, managedObjectContext: CoreDataStack.shared.mainContext, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultsController
}()
private struct AlphaValues {
static let Opaque: CGFloat = 1.0
static let Transparent: CGFloat = 0.0
}
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
loadAndSetCoordinatesPreferences()
longPressGestureRecognizer.addTarget(self, action: #selector(longPressureGestureRecognized(_:)))
mapView.addGestureRecognizer(longPressGestureRecognizer)
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
loadAnnotationsFromFetchedResultsController()
} catch {
debugPrint(error.localizedDescription)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Actions
@IBAction func editBarButtonItemTapped(_ sender: UIBarButtonItem) {
isEditMode = !isEditMode
UIView.animate(withDuration: 0.5) {
if self.isEditMode {
self.removePinLabel.alpha = AlphaValues.Opaque
self.editBarButtonItem.title = "Done"
} else {
self.removePinLabel.alpha = AlphaValues.Transparent
self.editBarButtonItem.title = "Edit"
}
}
}
// MARK: Utility
@objc private func longPressureGestureRecognized(_ gestureRecognizer: UIGestureRecognizer) {
if gestureRecognizer.state == .ended {
let touchPoint = gestureRecognizer.location(in: mapView)
let coordinates = mapView.convert(touchPoint, toCoordinateFrom: mapView)
addPin(withLatitude: coordinates.latitude, withLongitude: coordinates.longitude)
}
}
private func addPin(withLatitude latitude: Double, withLongitude longitude: Double) {
let _ = Pin(latitude: latitude, longitude: longitude, inContext: CoreDataStack.shared.mainContext)
//DispatchQueue.main.async {
// CoreDataStack.shared.save()
//}
}
private func loadAnnotationsFromFetchedResultsController() {
mapView.removeAnnotations(mapView.annotations)
if let pins = fetchedResultsController.fetchedObjects {
for pin in pins {
mapView.addAnnotation(pin)
}
}
}
}
// MARK: MKMapViewDelegate
extension VirtualTouristMapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "Pin"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
} else {
annotationView!.annotation = annotation
}
annotationView!.canShowCallout = false
return annotationView
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let pin = view.annotation as? Pin else {
return
}
if isEditMode {
CoreDataStack.shared.mainContext.delete(pin)
} else {
if let collectionVC = storyboard?.instantiateViewController(withIdentifier: "collectionViewController") as? VirtualTouristCollectionViewController {
collectionVC.pin = pin
mapView.deselectAnnotation(pin, animated: false)
navigationController?.pushViewController(collectionVC, animated: true)
}
}
}
private struct MapKeys {
static let RegionHasBeenSaved = "com.VirtualTourist.RegionHasBeenSaved"
static let LastRegionLatitude = "com.VirtualTourist.Latitude"
static let LastRegionLongitude = "com.VirtualTourist.Longitude"
static let LastRegionLongitudeDelta = "com.VirtualTourist.LongitudeDelta"
static let LastRegionLatitudeDelta = "com.VirtualTourist.LatitudeDelta"
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
storeCoordinatesPreferences()
}
private func storeCoordinatesPreferences() {
let defaults = UserDefaults.standard
defaults.setValue(true, forKey: MapKeys.RegionHasBeenSaved)
let region = mapView.region
defaults.set(region.center.latitude, forKey: MapKeys.LastRegionLatitude)
defaults.set(region.center.longitude, forKey: MapKeys.LastRegionLongitude)
defaults.set(region.span.latitudeDelta, forKey: MapKeys.LastRegionLatitudeDelta)
defaults.set(region.span.longitudeDelta, forKey: MapKeys.LastRegionLongitudeDelta)
}
fileprivate func loadAndSetCoordinatesPreferences() {
let defaults = UserDefaults.standard
if defaults.bool(forKey: MapKeys.RegionHasBeenSaved) {
var region = MKCoordinateRegion()
region.center.latitude = defaults.double(forKey: MapKeys.LastRegionLatitude)
region.center.longitude = defaults.double(forKey: MapKeys.LastRegionLongitude)
region.span.latitudeDelta = defaults.double(forKey: MapKeys.LastRegionLatitudeDelta)
region.span.longitudeDelta = defaults.double(forKey: MapKeys.LastRegionLongitudeDelta)
mapView.setRegion(region, animated: true)
}
}
}
// MARK: NSFetchedResultControllerDelegate
extension VirtualTouristMapViewController: NSFetchedResultsControllerDelegate {
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChange anObject: Any,
at indexPath: IndexPath?,
for type: NSFetchedResultsChangeType,
newIndexPath: IndexPath?) {
let pin = anObject as! Pin
switch type {
case .insert:
mapView.addAnnotation(pin)
case .delete:
mapView.removeAnnotation(pin)
/* This would cause the delegate to be notified even when photos relative to the
pin would get updated/removed (i.e. in VirtualTouristCollectionViewController)
case .move:
fallthrough
case .update:
break
*/
default:
return
}
DispatchQueue.main.async {
CoreDataStack.shared.save()
}
}
}
|
ac2277133eef6ac3f05dfc81c9ec71a2
| 38.62037 | 190 | 0.677378 | false | false | false | false |
Fenrikur/ef-app_ios
|
refs/heads/master
|
Domain Model/EurofurenceModelTests/Schedule/TheFirstTimeSyncFinishes_ApplicationShould.swift
|
mit
|
1
|
import EurofurenceModel
import XCTest
class TheFirstTimeSyncFinishes_ApplicationShould: XCTestCase {
func testRestrictEventsToTheFirstConDayWhenRunningBeforeConStarts() {
let response = ModelCharacteristics.randomWithoutDeletions
let firstDay = unwrap(response.conferenceDays.changed.min(by: { $0.date < $1.date }))
let context = EurofurenceSessionTestBuilder().with(.distantPast).build()
let schedule = context.eventsService.makeEventsSchedule()
let delegate = CapturingEventsScheduleDelegate()
schedule.setDelegate(delegate)
context.performSuccessfulSync(response: response)
let expectedEvents = response.events.changed.filter({ $0.dayIdentifier == firstDay.identifier })
EventAssertion(context: context, modelCharacteristics: response)
.assertEvents(delegate.events, characterisedBy: expectedEvents)
}
}
|
3fc5eac3a875726680d4efd92195510a
| 44.15 | 104 | 0.748616 | false | true | false | false |
buyiyang/iosstar
|
refs/heads/master
|
iOSStar/Scenes/User/bankCard/BindingBankCardVC.swift
|
gpl-3.0
|
3
|
//
// BindingBankCardVC.swift
// iOSStar
//
// Created by sum on 2017/5/15.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import SVProgressHUD
class BindingBankCardVC: UITableViewController {
//持卡人姓名
@IBOutlet var name: UITextField!
//银行卡号
@IBOutlet var cardNum: UITextField!
//手机号
@IBOutlet var phone: UITextField!
//验证码
@IBOutlet var vaildCode: UITextField!
//定时器
var openProvince = ""
var openCityStr = ""
@IBOutlet var openCity: UITextField!
private var timer: Timer?
//时间戳
private var codeTime = 60
//时间戳
var timeStamp = ""
//token
var vToken = ""
// cityPickerView
var cityPickerView = UIPickerView()
// cityToolBar
var cityToolBar = UIToolbar()
// cityList
var dataCity = Array<Dictionary<String, AnyObject>>()
// cityPickerView选择的row (省份)
var selectRow = 0
// cityPickerView选择的Componentow (市)
var selectComponent = 0
//发送验证码
@IBOutlet var SendCode: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.tableFooterView = UIView.init()
initCity()
initCityPickerView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 获取cityData
func initCity() {
let address : String = Bundle.main.path(forResource: "City", ofType: "plist")!
let dic = NSDictionary.init(contentsOfFile: address) as! [String : Array<Any>]
dataCity = dic["city"]! as! Array<Dictionary<String, AnyObject>> as Array<Dictionary<String, AnyObject>>
// print(dataCity)
}
// cityPickerView
func initCityPickerView(){
cityPickerView = UIPickerView.init()
cityPickerView.delegate = self
cityPickerView.dataSource = self
cityToolBar = UIToolbar.init(frame: CGRect.init(x: 0,
y: self.view.frame.size.height - self.cityToolBar.frame.size.height - 44.0,
width: self.view.frame.size.width,
height: 44))
openCity.inputView = cityPickerView
openCity.inputAccessoryView = cityToolBar
// 确定按钮
let sure : UIButton = UIButton.init(frame: CGRect.init(x: 0,
y: 0,
width: 40,
height: 44))
sure.setTitle("确定", for: .normal)
sure.setTitleColor(UIColor.init(hexString: "666666"), for: .normal)
sure.addTarget(self, action: #selector(sureClick), for: .touchUpInside)
let sureItem : UIBarButtonItem = UIBarButtonItem.init(customView: sure)
let space : UIButton = UIButton.init(frame: CGRect.init(x: 40, y: 0, width: self.view.frame.size.width-140, height: 44))
space.setTitle("", for: .normal)
let spaceItem : UIBarButtonItem = UIBarButtonItem.init(customView: space)
// 取消按钮
let cancel : UIButton = UIButton.init(frame: CGRect.init(x: self.view.frame.size.width-44,
y: 0,
width: 40,
height: 44))
cancel.setTitle("取消", for: .normal)
cancel.addTarget(self, action: #selector(cancelClick), for: .touchUpInside)
cancel.setTitleColor(UIColor.init(hexString: "666666"), for: .normal)
cancel.setTitleColor(UIColor.init(hexString: "666666"), for: .normal)
let cancelItem : UIBarButtonItem = UIBarButtonItem.init(customView: cancel)
cityToolBar.setItems([sureItem,spaceItem,cancelItem], animated: true)
}
@IBAction func sendCode(_ sender: Any) {
if !isTelNumber(num: phone.text!) {
SVProgressHUD.showErrorMessage(ErrorMessage: "请输入正确的手机号", ForDuration: 2, completion: nil)
return
}
if checkTextFieldEmpty([phone]) && isTelNumber(num: phone.text!) {
let sendVerificationCodeRequestModel = SendVerificationCodeRequestModel()
sendVerificationCodeRequestModel.phone = (self.phone.text!)
sendVerificationCodeRequestModel.type = 3
AppAPIHelper.login().SendVerificationCode(model: sendVerificationCodeRequestModel, complete: { [weak self] (result) in
SVProgressHUD.dismiss()
self?.SendCode.isEnabled = true
if let response = result {
if response["result"] as! Int == 1 {
self?.timer = Timer.scheduledTimer(timeInterval: 1,target:self!,selector: #selector(self?.updatecodeBtnTitle),userInfo: nil,repeats: true)
self?.timeStamp = String.init(format: "%ld", response["timeStamp"] as! Int)
self?.vToken = String.init(format: "%@", response["vToken"] as! String)
}else{
SVProgressHUD.showErrorMessage(ErrorMessage: "验证码获取失败", ForDuration: 2, completion: nil)
}
}
}, error: { (error) in
self.didRequestError(error)
self.SendCode.isEnabled = true
})
}
}
//MARK:- 更新秒数
func updatecodeBtnTitle() {
if codeTime == 0 {
SendCode.isEnabled = true
SendCode.setTitle("重新发送", for: .normal)
codeTime = 60
timer?.invalidate()
SendCode.setTitleColor(UIColor.init(hexString: "ffffff"), for: .normal)
SendCode.backgroundColor = UIColor(hexString: AppConst.Color.orange)
return
}
SendCode.isEnabled = false
codeTime = codeTime - 1
let title: String = "\(codeTime)秒重新发送"
SendCode.setTitle(title, for: .normal)
SendCode.setTitleColor(UIColor.init(hexString: "000000"), for: .normal)
SendCode.backgroundColor = UIColor(hexString: "ECECEC")
}
@IBAction func bingCard(_ sender: Any) {
if checkTextFieldEmpty([phone,cardNum,name,openCity,vaildCode]){
let string = "yd1742653sd" + self.timeStamp + self.vaildCode.text! + self.phone.text!
if string.md5_string() != self.vToken{
SVProgressHUD.showErrorMessage(ErrorMessage: "验证码错误", ForDuration: 1.0, completion: nil)
return
}
let model = BindCardListRequestModel()
model.bankUsername = name.text!
model.account = cardNum.text!
model.prov = openProvince
model.city = openCityStr
AppAPIHelper.user().bindcard(requestModel: model, complete: { [weak self](result) in
SVProgressHUD.showSuccessMessage(SuccessMessage: "绑定成功", ForDuration: 1, completion: {
self?.navigationController?.popViewController(animated: true)
})
}, error: { (error) in
self.didRequestError(error)
})
}
}
}
extension BindingBankCardVC : UIPickerViewDelegate,UIPickerViewDataSource {
// city确定按钮事件
func sureClick(){
let dic : Dictionary = dataCity[selectComponent]
openProvince = dataCity[selectComponent]["name"] as! String
if let name = dic["name"] as? String{
if let arr : Array = (dic[name] as AnyObject) as? Array<AnyObject> {
if let nameDic = arr[selectRow]["name"] {
if nameDic != nil {
openCityStr = nameDic as! String
openCity.text = openProvince + " " + openCityStr
}
openCity.resignFirstResponder()
selectRow = 0
selectComponent = 0
cityPickerView.selectRow(selectComponent, inComponent: 0, animated: true)
cityPickerView.selectRow(0, inComponent: 1, animated: true)
}
}
}
}
func cancelClick(){
selectRow = 0
selectComponent = 0
cityPickerView.selectRow(0
, inComponent: 0, animated: true)
cityPickerView.selectRow(0
, inComponent: 1, animated: true)
openCity.resignFirstResponder()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return dataCity.count
}else{
let dic : Dictionary = dataCity[selectComponent]
let name = dic["name"] as! String
let arr : Array = dic[name] as! Array<AnyObject>
return arr.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return dataCity[row]["name"] as? String
}else{
let dic : Dictionary = dataCity[selectComponent]
let name = dic["name"] as! String
let arr : Array = (dic[name] as AnyObject) as! Array<AnyObject>
let nameDic = arr[row]["name"]
return nameDic as? String
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0{
selectComponent = row
openProvince = dataCity[row]["name"] as! String
pickerView.reloadComponent(1)
}else{
selectRow = row
}
}
}
|
b8de100f93bd8fd05dc3251d0043ee78
| 36.003534 | 162 | 0.543163 | false | false | false | false |
zxpLearnios/MyProject
|
refs/heads/master
|
test_projectDemo1/TVC && NAV/MyCustomTVC.swift
|
mit
|
1
|
//
// MyCustomTVC.swift
// test_Colsure
//
// Created by Jingnan Zhang on 16/5/10.
// Copyright © 2016年 Jingnan Zhang. All rights reserved.
// 1. 自定义TVC, 使用提醒按钮 2. 有判断类型; 3. plusBtn 做动画,从某处到tabbar的指定位置,动画结束后,主动刷新tabbar的子控件,在tabbar里加了判断,移除plusBtn,将此处加自定义的只有图片的tabbarItem即可;实现切屏时的位移问题的处理。 即只要是通过addSubView上到tabbar的估计在横竖屏切换时都会出错,必须是tabbar自带的东西才不会出错的。
import UIKit
class MyCustomTVC: UITabBarController, UITabBarControllerDelegate, CAAnimationDelegate {
var childVCs = [UIViewController]()
var customTabBar = MyTabBar()
var plusBtn = MyPlusButton() // 真正的和其他item平均分占了tabbar,如在自定义的tabbar里加plusBtn,则最左边的item的有效范围始终会挡住plusBtn的左半部
var toPoint = CGPoint.zero
var isCompleteAnimate = false
// MARK: xib\代码 都会调之,但此类型只会调一次
override class func initialize() {
self.doInit()
}
// MARK: 做一些事
class func doInit() {
// 所有的字控制器的tabbarItem的 字体属性
let tabbarItem = UITabBarItem.appearance() // 不能用UIBarButtonItem
let itemAttributeNormal = [NSFontAttributeName: UIFont.systemFont(ofSize: 10), NSForegroundColorAttributeName: UIColor.red]
let itemAttributeHighlight = [NSFontAttributeName: UIFont.systemFont(ofSize: 10), NSForegroundColorAttributeName: UIColor.green]
tabbarItem.setTitleTextAttributes(itemAttributeNormal, for: UIControlState())
tabbarItem.setTitleTextAttributes(itemAttributeHighlight, for: .selected) // 用highlight无效
// 此处设置tabbarItem的图片无效(估计纯代码情况下也是无效)
// tabBarItem.image = UIImage(named: "Customer_select")
// tabBarItem.selectedImage = UIImage(named: "Customer_unselect")
}
override func viewDidLoad() {
super.viewDidLoad()
// -1
self.delegate = self
// 0. 以便子控制器的view做转场动画时看到白色
self.view.backgroundColor = UIColor.white
// 1, 加子控制器
let fistVC = firstChildVC()
self.addChildViewControllers(fistVC, title: "第一个", itemImage: UIImage(named: "tabBar_me_icon"), itemSelectedImage: UIImage(named: "tabBar_me_click_icon"))
let secondVC = secondChildVC()
self.addChildViewControllers(secondVC, title: "第二个", itemImage: UIImage(named: "tabBar_essence_icon"), itemSelectedImage: UIImage(named: "tabBar_essence_click_icon"))
let thirdVC = ThirdChildVC()
self.addChildViewControllers(thirdVC, title: "第三个", itemImage: UIImage(named: "tabBar_friendTrends_icon"), itemSelectedImage: UIImage(named: "tabBar_friendTrends_click_icon"))
// 2。 KVO替换原tabbar
self.setValue(customTabBar, forKey: "tabBar")
// 4.设置tabbaralpha
self.tabBar.alpha = 0.8
let time = DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {
self.addPlusButton()
}
self.addChildViewControllers(UIViewController(), title: "", itemImage: UIImage(named: "tabBar_publish_icon"), itemSelectedImage: UIImage(named: "tabBar_publish_icon"))
// 5. 屏幕旋转通知
kDevice.beginGeneratingDeviceOrientationNotifications()
kNotificationCenter.addObserver(self, selector: #selector(orientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// for item in self.tabBar.subviews {
// if item.isKindOfClass(UIControl) {
// item.removeFromSuperview() // 此时不要
// }
// }
// MARK: 判断类型
// is 和 item.isKindOfClass 都是判断一个实例是否是某种类型
// print(self.childViewControllers)
}
// 横屏变竖屏后,会再次调用之,故须做处理, 即不能在此处加加号按钮了,因为横屏变竖屏显示testVC后,就会进入此法,此时加号按钮会显示在testVC底部,且进入TabbarVC后plusBtn的位置也不对, 故在viewDidLoad里加plusBtn但需要延迟等viewDidAppear后才可以加,确保只会执行一次; 此时屏幕还是横着的
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// 3.添加加号按钮, 必须在视图显示完毕后添加
// addPlusButton()
}
// MARK: 屏幕旋转了
@objc fileprivate func orientationDidChange(){
if kDevice.orientation == .portrait {
}
if kDevice.orientation == .landscapeRight || kDevice.orientation == .landscapeLeft {
}
}
// MARK: 添加加号按钮
func addPlusButton(){
// 设置加号按钮
self.tabBar.addSubview(plusBtn)
//
let width = self.view.width / 4 // customTabBar.buttonW
plusBtn.bounds = CGRect(x: 0, y: 0, width: width, height: 50)
plusBtn.setImage(UIImage(named: "tabBar_publish_icon"), for: UIControlState())
// plusBtn.setTitle("加号", forState: .Normal)
plusBtn.addTarget(self, action: #selector(btnAction), for: .touchUpInside)
// 动画
let tabbarCenter = self.view.convert(self.tabBar.center, to: self.tabBar)
let ani = CABasicAnimation.init(keyPath: "position")
ani.duration = 0.5
ani.fromValue = NSValue.init(cgPoint: CGPoint(x: kwidth * 0.2, y: -kheight * 0.7))
toPoint = CGPoint(x: width * 1.5, y: tabbarCenter.y)
ani.toValue = NSValue.init(cgPoint: toPoint)
ani.delegate = self
let time = DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {
self.plusBtn.isHidden = false
self.plusBtn.layer.add(ani, forKey: "")
}
}
func btnAction(_ plusBtn:MyPlusButton) {
plusBtn.isSelected = !plusBtn.isSelected
print("点击了加号按钮")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: 添加子控制器
fileprivate func addChildViewControllers(_ viewController:UIViewController, title:String, itemImage:UIImage?, itemSelectedImage:UIImage?){
let newItemSelectdImg = itemSelectedImage?.withRenderingMode(.alwaysOriginal)
if self.viewControllers?.count == 3 {
// 只有图片的tabbaritem
let item = MyCustomTabBarItem.init(image: itemImage, selectedImage: itemSelectedImage)
viewController.tabBarItem = item
}else{
// 当navigationItem.title != tabBarItem.title 时,必须如此设置:先设置title,在设置navigationItem.title,设置tabBarItem.title已经无用了
// viewController.title = title
// viewController.navigationItem.title = "我的账户"
viewController.title = title
viewController.tabBarItem.image = itemImage
viewController.tabBarItem.selectedImage = newItemSelectdImg
}
let nav = MyCustomNav.init(rootViewController: viewController)
self.addChildViewController(nav)
}
// MARK: UITabBarControllerDelegate
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
let index = self.viewControllers?.index(of: viewController)
if index != nil {
if index == 3 {
self.perform(#selector(btnAction), with: plusBtn, afterDelay: 0)
// viewController.tabBarItem.selectedImage = nil // 可以在此处设置点击item时的选中图片,因为点击item选中控制器被禁止了
// self.selectedIndex = 3 // 因为这样会选中并显示控制器
return false
}else{
return true
}
}else{
return false
}
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if flag {
plusBtn.center = toPoint
isCompleteAnimate = true
self.tabBar.layoutSubviews() // 主动刷新
}
}
}
|
9db46f4a1c4d9567376377d769cd85f9
| 34.497778 | 209 | 0.623263 | false | false | false | false |
apple/swift-nio-http2
|
refs/heads/main
|
Sources/NIOHTTP2PerformanceTester/StreamTeardownBenchmark.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import NIOEmbedded
import NIOHPACK
import NIOHTTP2
final class StreamTeardownBenchmark: Benchmark {
private let concurrentStreams: Int
// A manually constructed headers frame.
private var headersFrame: ByteBuffer = {
var headers = HPACKHeaders()
headers.add(name: ":method", value: "GET", indexing: .indexable)
headers.add(name: ":authority", value: "localhost", indexing: .nonIndexable)
headers.add(name: ":path", value: "/", indexing: .indexable)
headers.add(name: ":scheme", value: "https", indexing: .indexable)
headers.add(name: "user-agent",
value: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
indexing: .nonIndexable)
headers.add(name: "accept-encoding", value: "gzip, deflate", indexing: .indexable)
var hpackEncoder = HPACKEncoder(allocator: .init())
var buffer = ByteBuffer()
buffer.writeRepeatingByte(0, count: 9)
buffer.moveReaderIndex(forwardBy: 9)
try! hpackEncoder.encode(headers: headers, to: &buffer)
let encodedLength = buffer.readableBytes
buffer.moveReaderIndex(to: buffer.readerIndex - 9)
// UInt24 length
buffer.setInteger(UInt8(0), at: buffer.readerIndex)
buffer.setInteger(UInt16(encodedLength), at: buffer.readerIndex + 1)
// Type
buffer.setInteger(UInt8(0x01), at: buffer.readerIndex + 3)
// Flags, turn on END_HEADERs.
buffer.setInteger(UInt8(0x04), at: buffer.readerIndex + 4)
// 4 byte stream identifier, set to zero for now as we update it later.
buffer.setInteger(UInt32(0), at: buffer.readerIndex + 5)
return buffer
}()
private let emptySettings: ByteBuffer = {
var buffer = ByteBuffer()
buffer.reserveCapacity(9)
// UInt24 length, is 0 bytes.
buffer.writeInteger(UInt8(0))
buffer.writeInteger(UInt16(0))
// Type
buffer.writeInteger(UInt8(0x04))
// Flags, none.
buffer.writeInteger(UInt8(0x00))
// 4 byte stream identifier, set to zero.
buffer.writeInteger(UInt32(0))
return buffer
}()
private var settingsACK: ByteBuffer {
// Copy the empty SETTINGS and add the ACK flag
var settingsCopy = self.emptySettings
settingsCopy.setInteger(UInt8(0x01), at: settingsCopy.readerIndex + 4)
return settingsCopy
}
init(concurrentStreams: Int) {
self.concurrentStreams = concurrentStreams
}
func setUp() { }
func tearDown() { }
func createChannel() throws -> EmbeddedChannel {
let channel = EmbeddedChannel()
_ = try channel.configureHTTP2Pipeline(mode: .server) { streamChannel -> EventLoopFuture<Void> in
return streamChannel.pipeline.addHandler(DoNothingServer())
}.wait()
try channel.pipeline.addHandler(SendGoawayHandler(expectedStreams: self.concurrentStreams)).wait()
try channel.connect(to: .init(unixDomainSocketPath: "/fake"), promise: nil)
// Gotta do the handshake here.
var initialBytes = ByteBuffer(string: "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
initialBytes.writeImmutableBuffer(self.emptySettings)
initialBytes.writeImmutableBuffer(self.settingsACK)
try channel.writeInbound(initialBytes)
while try channel.readOutbound(as: ByteBuffer.self) != nil { }
return channel
}
func destroyChannel(_ channel: EmbeddedChannel) throws {
_ = try channel.finish()
}
func run() throws -> Int {
var bodyByteCount = 0
var completedIterations = 0
while completedIterations < 10_000 {
let channel = try self.createChannel()
bodyByteCount &+= try self.sendInterleavedRequestsAndTerminate(self.concurrentStreams, channel)
completedIterations += self.concurrentStreams
try self.destroyChannel(channel)
}
return bodyByteCount
}
private func sendInterleavedRequestsAndTerminate(_ interleavedRequests: Int, _ channel: EmbeddedChannel) throws -> Int {
var streamID = HTTP2StreamID(1)
for _ in 0 ..< interleavedRequests {
self.headersFrame.setInteger(UInt32(Int32(streamID)), at: self.headersFrame.readerIndex + 5)
try channel.writeInbound(self.headersFrame)
streamID = streamID.advanced(by: 2)
}
var count = 0
while let data = try channel.readOutbound(as: ByteBuffer.self) {
count &+= data.readableBytes
channel.embeddedEventLoop.run()
}
// We need to have got a GOAWAY back, precondition that the count is large enough.
precondition(count == 17)
return count
}
}
fileprivate class DoNothingServer: ChannelInboundHandler {
public typealias InboundIn = HTTP2Frame.FramePayload
public typealias OutboundOut = HTTP2Frame.FramePayload
}
fileprivate class SendGoawayHandler: ChannelInboundHandler {
public typealias InboundIn = HTTP2Frame
public typealias OutboundOut = HTTP2Frame
private static let goawayFrame: HTTP2Frame = HTTP2Frame(
streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .enhanceYourCalm, opaqueData: nil)
)
private let expectedStreams: Int
private var seenStreams: Int
init(expectedStreams: Int) {
self.expectedStreams = expectedStreams
self.seenStreams = 0
}
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
if event is NIOHTTP2StreamCreatedEvent {
self.seenStreams += 1
if self.seenStreams == self.expectedStreams {
// Send a GOAWAY to tear all streams down.
context.writeAndFlush(self.wrapOutboundOut(SendGoawayHandler.goawayFrame), promise: nil)
}
}
}
}
|
63571ef7e220cfcfde70c360a8fe14c0
| 34.895028 | 145 | 0.643374 | false | false | false | false |
bparish628/iFarm-Health
|
refs/heads/master
|
iOS/iFarm-Health/Classes/News/NewsViewController.swift
|
apache-2.0
|
1
|
//
// NewsViewController.swift
// iFarm-Health
//
// Created by Benji Parish on 9/26/17.
// Copyright © 2017 Benji Parish. All rights reserved.
//
import UIKit
class NewsViewController: UITableViewController {
var articles = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
// let filePath = Bundle.main.path(forResource:"News", ofType: "plist")
//
// if let path = filePath {
// articles = NSArray(contentsOfFile: path)! as [AnyObject]
// print(articles)
// }
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return articles.count
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
b31dd27783b671e8ac42d3439bfbfa32
| 31.072917 | 136 | 0.651835 | false | false | false | false |
lacklock/NiceGesture
|
refs/heads/master
|
NiceGestureDemo/PanViewController.swift
|
mit
|
1
|
//
// PanViewController.swift
// NiceGesture
//
// Created by 卓同学 on 16/4/4.
// Copyright © 2016年 zhuo. All rights reserved.
//
import UIKit
class PanViewController: UIViewController {
@IBOutlet weak var lbState: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
lbState.nc_addPanGesture()
.whenEnded {[unowned self] (recognizer) -> Void in
self.lbState.text=recognizer.state.toString()
self.lbState.transform=CGAffineTransformIdentity
self.view.layoutIfNeeded()
}.whenChanged {[unowned self] (recognizer) -> Void in
self.lbState.text=recognizer.state.toString()
let touchPoint = recognizer.locationInView(self.view)
let offsetX=touchPoint.x-self.view.center.x
let offsetY=touchPoint.y-self.view.center.y
self.lbState.transform=CGAffineTransformMakeTranslation(offsetX, offsetY)
}
// lbState.nc_addPanGesture().whenStatesHappend([.Ended,.Changed]) { (gestureRecognizer) -> Void in
// print("another way :\(gestureRecognizer.state.toString())")
// }
}
}
|
cc82d5bf8fc9cae0e864a7cf17e32288
| 31 | 106 | 0.611842 | false | false | false | false |
MJsaka/MJZZ
|
refs/heads/master
|
MJZZ/StatisticData.swift
|
gpl-3.0
|
1
|
//
// MJZZStatisticData.swift
// MJZZ
//
// Created by MJsaka on 15/10/21.
// Copyright © 2015年 MJsaka. All rights reserved.
//
import UIKit
class MJZZTime : NSObject , NSCoding{
let year : Int
let month : Int
let day : Int
let hour : Int
let minute : Int
override convenience init() {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let comp : NSDateComponents = calendar.components([.Year, .Month, .Day , .Hour , .Minute], fromDate: NSDate())
self.init(year: comp.year , month: comp.month , day: comp.day ,hour: comp.hour , minute: comp.minute)
}
init(year aYear:Int , month aMonth : Int , day aDay : Int ,hour aHour : Int , minute aMinute : Int){
year = aYear
month = aMonth
day = aDay
hour = aHour
minute = aMinute
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(year, forKey: "year")
aCoder.encodeInteger(month, forKey: "month")
aCoder.encodeInteger(day, forKey: "day")
aCoder.encodeInteger(hour, forKey: "hour")
aCoder.encodeInteger(minute, forKey: "minute")
}
required init?(coder aDecoder: NSCoder) {
year = aDecoder.decodeIntegerForKey("year")
month = aDecoder.decodeIntegerForKey("month")
day = aDecoder.decodeIntegerForKey("day")
hour = aDecoder.decodeIntegerForKey("hour")
minute = aDecoder.decodeIntegerForKey("minute")
}
}
@objc protocol MJZZDataProtocol{
var data : [MJZZDataProtocol] {get set}
var duration : Int {get set}
var time : MJZZTime {get set}
func deleteDataAtIndexes(indexes : [Int], withSelectedDataIndex dataIndex: MJZZDataIndex , withSelectedDataScope dataScope : MJZZDataScope)
}
class MJZZData : NSObject , MJZZDataProtocol , NSCoding {
var data : [MJZZDataProtocol]
var duration : Int = 0
var time : MJZZTime
override convenience init() {
self.init(withTime : MJZZTime())
}
init(withTime aTime : MJZZTime){
data = [MJZZDataProtocol]()
time = aTime
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(duration, forKey: "duration")
aCoder.encodeObject(time, forKey: "time")
aCoder.encodeObject(data, forKey: "data")
}
required init(coder aDecoder: NSCoder) {
duration = aDecoder.decodeIntegerForKey("duration")
time = aDecoder.decodeObjectForKey("time") as! MJZZTime
data = aDecoder.decodeObjectForKey("data") as! [MJZZDataProtocol]
}
func deleteDataAtIndexes(indexes : [Int], withSelectedDataIndex dataIndex: MJZZDataIndex , withSelectedDataScope dataScope : MJZZDataScope){
return
}
}
class MJZZDayData : MJZZData {
func appendOnceData(aData : MJZZData){
data.insert(aData, atIndex: 0)
duration += aData.duration
}
override func deleteDataAtIndexes(indexes : [Int], withSelectedDataIndex dataIndex: MJZZDataIndex , withSelectedDataScope dataScope : MJZZDataScope){
if dataScope == MJZZDataScope.day {
for index in indexes {
duration -= data[index].duration
}
if duration == 0 {
return
}
for (var i = indexes.count - 1; i >= 0; --i) {
let index = indexes[i]
data.removeAtIndex(index)
}
}
}
}
class MJZZMonthData : MJZZData {
func appendOnceData (aData : MJZZData){
var aDayData : MJZZDayData
if !data.isEmpty && data.first!.time.day == aData.time.day{
aDayData = data.first as! MJZZDayData
}else{
aDayData = MJZZDayData(withTime: aData.time)
data.insert(aDayData, atIndex: 0)
}
aDayData.appendOnceData(aData)
duration += aData.duration
}
override func deleteDataAtIndexes(indexes : [Int], withSelectedDataIndex dataIndex: MJZZDataIndex , withSelectedDataScope dataScope : MJZZDataScope){
if dataScope == MJZZDataScope.month {
for index in indexes {
duration -= data[index].duration
}
if duration == 0 {
return
}
for (var i = indexes.count - 1; i >= 0; --i) {
let index = indexes[i]
data.removeAtIndex(index)
}
} else {
duration -= data[dataIndex.dayIndex].duration
data[dataIndex.dayIndex].deleteDataAtIndexes(indexes, withSelectedDataIndex: dataIndex, withSelectedDataScope: dataScope)
if data[dataIndex.dayIndex].duration == 0 {
data.removeAtIndex(dataIndex.dayIndex)
} else {
duration += data[dataIndex.dayIndex].duration
}
}
}
}
class MJZZYearData : MJZZData {
func appendOnceData (aData : MJZZData){
var aMonthData : MJZZMonthData
if !data.isEmpty && data.first!.time.month == aData.time.month {
aMonthData = data.first as! MJZZMonthData
}else{
aMonthData = MJZZMonthData(withTime: aData.time)
data.insert(aMonthData, atIndex: 0)
}
aMonthData.appendOnceData(aData)
duration += aData.duration
}
override func deleteDataAtIndexes(indexes : [Int], withSelectedDataIndex dataIndex: MJZZDataIndex , withSelectedDataScope dataScope : MJZZDataScope){
if dataScope == MJZZDataScope.year {
for index in indexes {
duration -= data[index].duration
}
if duration == 0 {
return
}
for (var i = indexes.count - 1; i >= 0; --i) {
let index = indexes[i]
data.removeAtIndex(index)
}
} else {
duration -= data[dataIndex.monthIndex].duration
data[dataIndex.monthIndex].deleteDataAtIndexes(indexes, withSelectedDataIndex: dataIndex, withSelectedDataScope: dataScope)
if data[dataIndex.monthIndex].duration == 0 {
data.removeAtIndex(dataIndex.monthIndex)
} else {
duration += data[dataIndex.monthIndex].duration
}
}
}
}
var singletonStatisticData : MJZZStatisticData = MJZZStatisticData()
class MJZZStatisticData : MJZZData{
var bestOnceDuration : Int = 0
class func appendOnceData (aData : MJZZData){
var aYearData : MJZZYearData
if !singletonStatisticData.data.isEmpty && singletonStatisticData.data.first!.time.year == aData.time.year {
aYearData = singletonStatisticData.data.first as! MJZZYearData
}else{
aYearData = MJZZYearData(withTime: aData.time)
singletonStatisticData.data.insert(aYearData, atIndex: 0)
}
aYearData.appendOnceData(aData)
singletonStatisticData.duration += aData.duration
if aData.duration > singletonStatisticData.bestOnceDuration {
singletonStatisticData.bestOnceDuration = aData.duration
NSNotificationCenter.defaultCenter().postNotificationName("MJZZNotificationBestDurationChanged", object: singletonStatisticData)
}
NSNotificationCenter.defaultCenter().postNotificationName("MJZZNotificationStatisticDataChanged", object: singletonStatisticData)
}
class func deleteDataAtIndexes(indexes : [Int], withSelectedDataIndex dataIndex: MJZZDataIndex , withSelectedDataScope dataScope : MJZZDataScope){
singletonStatisticData.duration -= singletonStatisticData.data[dataIndex.yearIndex].duration
singletonStatisticData.data[dataIndex.yearIndex].deleteDataAtIndexes(indexes, withSelectedDataIndex: dataIndex, withSelectedDataScope: dataScope)
if singletonStatisticData.data[dataIndex.yearIndex].duration == 0 {
singletonStatisticData.data.removeAtIndex(dataIndex.yearIndex)
} else {
singletonStatisticData.duration += singletonStatisticData.data[dataIndex.yearIndex].duration
}
}
class func sharedData() -> MJZZStatisticData {
return singletonStatisticData
}
convenience init(){
self.init(withTime : MJZZTime())
}
override init(withTime aTime: MJZZTime) {
super.init(withTime: aTime)
}
override func encodeWithCoder(aCoder: NSCoder) {
super.encodeWithCoder(aCoder)
aCoder.encodeInteger(bestOnceDuration, forKey: "bestOnceDuration")
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
bestOnceDuration = aDecoder.decodeIntegerForKey("bestOnceDuration")
}
}
|
5f8790b9e8263c7552bc12324aacbd0d
| 38.870968 | 153 | 0.63981 | false | false | false | false |
SuPair/firefox-ios
|
refs/heads/master
|
Client/Frontend/Settings/AppSettingsOptions.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
import Shared
import Account
import SwiftKeychainWrapper
import LocalAuthentication
// This file contains all of the settings available in the main settings screen of the app.
private var ShowDebugSettings: Bool = false
private var DebugSettingsClickCount: Int = 0
// For great debugging!
class HiddenSetting: Setting {
unowned let settings: SettingsTableViewController
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var hidden: Bool {
return !ShowDebugSettings
}
}
// Sync setting for connecting a Firefox Account. Shown when we don't have an account.
class ConnectSetting: WithoutAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var title: NSAttributedString? {
return NSAttributedString(string: Strings.FxASignInToSync, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override var accessibilityIdentifier: String? { return "SignInToSync" }
override func onClick(_ navigationController: UINavigationController?) {
let fxaParams = FxALaunchParams(query: ["entrypoint": "preferences"])
let viewController = FxAContentViewController(profile: profile, fxaOptions: fxaParams)
viewController.delegate = self
viewController.url = settings.profile.accountConfiguration.signInURL
navigationController?.pushViewController(viewController, animated: true)
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.imageView?.image = UIImage.templateImageNamed("FxA-Default")
cell.imageView?.tintColor = UIColor.theme.tableView.disabledRowText
cell.imageView?.layer.cornerRadius = (cell.imageView?.frame.size.width)! / 2
cell.imageView?.layer.masksToBounds = true
}
}
class SyncNowSetting: WithAccountSetting {
let imageView = UIImageView(frame: CGRect(width: 30, height: 30))
let syncIconWrapper = UIImage.createWithColor(CGSize(width: 30, height: 30), color: UIColor.clear)
let syncBlueIcon = UIImage(named: "FxA-Sync-Blue")?.createScaled(CGSize(width: 20, height: 20))
let syncIcon = UIImage(named: "FxA-Sync")?.createScaled(CGSize(width: 20, height: 20))
// Animation used to rotate the Sync icon 360 degrees while syncing is in progress.
let continuousRotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
override init(settings: SettingsTableViewController) {
super.init(settings: settings)
NotificationCenter.default.addObserver(self, selector: #selector(stopRotateSyncIcon), name: .ProfileDidFinishSyncing, object: nil)
}
fileprivate lazy var timestampFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}()
fileprivate var syncNowTitle: NSAttributedString {
if !DeviceInfo.hasConnectivity() {
return NSAttributedString(
string: Strings.FxANoInternetConnection,
attributes: [
NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.errorText,
NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultMediumFont
]
)
}
return NSAttributedString(
string: NSLocalizedString("Sync Now", comment: "Sync Firefox Account"),
attributes: [
NSAttributedStringKey.foregroundColor: self.enabled ? UIColor.theme.tableView.syncText : UIColor.theme.tableView.headerTextLight,
NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFont
]
)
}
fileprivate let syncingTitle = NSAttributedString(string: Strings.SyncingMessageWithEllipsis, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText, NSAttributedStringKey.font: UIFont.systemFont(ofSize: DynamicFontHelper.defaultHelper.DefaultStandardFontSize, weight: UIFont.Weight.regular)])
func startRotateSyncIcon() {
DispatchQueue.main.async {
self.imageView.layer.add(self.continuousRotateAnimation, forKey: "rotateKey")
}
}
@objc func stopRotateSyncIcon() {
DispatchQueue.main.async {
self.imageView.layer.removeAllAnimations()
}
}
override var accessoryType: UITableViewCellAccessoryType { return .none }
override var style: UITableViewCellStyle { return .value1 }
override var image: UIImage? {
guard let syncStatus = profile.syncManager.syncDisplayState else {
return syncIcon
}
switch syncStatus {
case .inProgress:
return syncBlueIcon
default:
return syncIcon
}
}
override var title: NSAttributedString? {
guard let syncStatus = profile.syncManager.syncDisplayState else {
return syncNowTitle
}
switch syncStatus {
case .bad(let message):
guard let message = message else { return syncNowTitle }
return NSAttributedString(string: message, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.errorText, NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFont])
case .warning(let message):
return NSAttributedString(string: message, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.warningText, NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFont])
case .inProgress:
return syncingTitle
default:
return syncNowTitle
}
}
override var status: NSAttributedString? {
guard let timestamp = profile.syncManager.lastSyncFinishTime else {
return nil
}
let formattedLabel = timestampFormatter.string(from: Date.fromTimestamp(timestamp))
let attributedString = NSMutableAttributedString(string: formattedLabel)
let attributes = [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)]
let range = NSRange(location: 0, length: attributedString.length)
attributedString.setAttributes(attributes, range: range)
return attributedString
}
override var enabled: Bool {
if !DeviceInfo.hasConnectivity() {
return false
}
return profile.hasSyncableAccount()
}
fileprivate lazy var troubleshootButton: UIButton = {
let troubleshootButton = UIButton(type: .roundedRect)
troubleshootButton.setTitle(Strings.FirefoxSyncTroubleshootTitle, for: .normal)
troubleshootButton.addTarget(self, action: #selector(self.troubleshoot), for: .touchUpInside)
troubleshootButton.tintColor = UIColor.theme.tableView.rowActionAccessory
troubleshootButton.titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultSmallFont
troubleshootButton.sizeToFit()
return troubleshootButton
}()
fileprivate lazy var warningIcon: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "AmberCaution"))
imageView.sizeToFit()
return imageView
}()
fileprivate lazy var errorIcon: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "RedCaution"))
imageView.sizeToFit()
return imageView
}()
fileprivate let syncSUMOURL = SupportUtils.URLForTopic("sync-status-ios")
@objc fileprivate func troubleshoot() {
let viewController = SettingsContentViewController()
viewController.url = syncSUMOURL
settings.navigationController?.pushViewController(viewController, animated: true)
}
override func onConfigureCell(_ cell: UITableViewCell) {
cell.textLabel?.attributedText = title
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = .byWordWrapping
if let syncStatus = profile.syncManager.syncDisplayState {
switch syncStatus {
case .bad(let message):
if let _ = message {
// add the red warning symbol
// add a link to the MANA page
cell.detailTextLabel?.attributedText = nil
cell.accessoryView = troubleshootButton
addIcon(errorIcon, toCell: cell)
} else {
cell.detailTextLabel?.attributedText = status
cell.accessoryView = nil
}
case .warning(_):
// add the amber warning symbol
// add a link to the MANA page
cell.detailTextLabel?.attributedText = nil
cell.accessoryView = troubleshootButton
addIcon(warningIcon, toCell: cell)
case .good:
cell.detailTextLabel?.attributedText = status
fallthrough
default:
cell.accessoryView = nil
}
} else {
cell.accessoryView = nil
}
cell.accessoryType = accessoryType
cell.isUserInteractionEnabled = !profile.syncManager.isSyncing && DeviceInfo.hasConnectivity()
// Animation that loops continously until stopped
continuousRotateAnimation.fromValue = 0.0
continuousRotateAnimation.toValue = CGFloat(Double.pi)
continuousRotateAnimation.isRemovedOnCompletion = true
continuousRotateAnimation.duration = 0.5
continuousRotateAnimation.repeatCount = .infinity
// To ensure sync icon is aligned properly with user's avatar, an image is created with proper
// dimensions and color, then the scaled sync icon is added as a subview.
imageView.contentMode = .center
imageView.image = image
cell.imageView?.subviews.forEach({ $0.removeFromSuperview() })
cell.imageView?.image = syncIconWrapper
cell.imageView?.addSubview(imageView)
if let syncStatus = profile.syncManager.syncDisplayState {
switch syncStatus {
case .inProgress:
self.startRotateSyncIcon()
default:
self.stopRotateSyncIcon()
}
}
}
fileprivate func addIcon(_ image: UIImageView, toCell cell: UITableViewCell) {
cell.contentView.addSubview(image)
cell.textLabel?.snp.updateConstraints { make in
make.leading.equalTo(image.snp.trailing).offset(5)
make.trailing.lessThanOrEqualTo(cell.contentView)
make.centerY.equalTo(cell.contentView)
}
image.snp.makeConstraints { make in
make.leading.equalTo(cell.contentView).offset(17)
make.top.equalTo(cell.textLabel!).offset(2)
}
}
override func onClick(_ navigationController: UINavigationController?) {
if !DeviceInfo.hasConnectivity() {
return
}
NotificationCenter.default.post(name: .UserInitiatedSyncManually, object: nil)
profile.syncManager.syncEverything(why: .syncNow)
}
}
// Sync setting that shows the current Firefox Account status.
class AccountStatusSetting: WithAccountSetting {
override init(settings: SettingsTableViewController) {
super.init(settings: settings)
NotificationCenter.default.addObserver(self, selector: #selector(updateAccount), name: .FirefoxAccountProfileChanged, object: nil)
}
@objc func updateAccount(notification: Notification) {
DispatchQueue.main.async {
self.settings.tableView.reloadData()
}
}
override var image: UIImage? {
if let image = profile.getAccount()?.fxaProfile?.avatar.image {
return image.createScaled(CGSize(width: 30, height: 30))
}
let image = UIImage(named: "placeholder-avatar")
return image?.createScaled(CGSize(width: 30, height: 30))
}
override var accessoryType: UITableViewCellAccessoryType {
if let account = profile.getAccount() {
switch account.actionNeeded {
case .needsVerification:
// We link to the resend verification email page.
return .disclosureIndicator
case .needsPassword:
// We link to the re-enter password page.
return .disclosureIndicator
case .none:
// We link to FxA web /settings.
return .disclosureIndicator
case .needsUpgrade:
// In future, we'll want to link to an upgrade page.
return .none
}
}
return .disclosureIndicator
}
override var title: NSAttributedString? {
if let account = profile.getAccount() {
if let displayName = account.fxaProfile?.displayName {
return NSAttributedString(string: displayName, attributes: [NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText])
}
if let email = account.fxaProfile?.email {
return NSAttributedString(string: email, attributes: [NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText])
}
return NSAttributedString(string: account.email, attributes: [NSAttributedStringKey.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.syncText])
}
return nil
}
override var status: NSAttributedString? {
if let account = profile.getAccount() {
var string: String
switch account.actionNeeded {
case .none:
return nil
case .needsVerification:
string = Strings.FxAAccountVerifyEmail
break
case .needsPassword:
string = Strings.FxAAccountVerifyPassword
break
case .needsUpgrade:
string = Strings.FxAAccountUpgradeFirefox
break
}
let orange = UIColor.theme.tableView.warningText
let range = NSRange(location: 0, length: string.count)
let attrs = [NSAttributedStringKey.foregroundColor: orange]
let res = NSMutableAttributedString(string: string)
res.setAttributes(attrs, range: range)
return res
}
return nil
}
override func onClick(_ navigationController: UINavigationController?) {
let fxaParams = FxALaunchParams(query: ["entrypoint": "preferences"])
let viewController = FxAContentViewController(profile: profile, fxaOptions: fxaParams)
viewController.delegate = self
if let account = profile.getAccount() {
switch account.actionNeeded {
case .none:
let viewController = SyncContentSettingsViewController()
viewController.profile = profile
navigationController?.pushViewController(viewController, animated: true)
return
case .needsVerification:
var cs = URLComponents(url: account.configuration.settingsURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email))
if let url = try? cs?.asURL() {
viewController.url = url
}
case .needsPassword:
var cs = URLComponents(url: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email))
if let url = try? cs?.asURL() {
viewController.url = url
}
case .needsUpgrade:
// In future, we'll want to link to an upgrade page.
return
}
}
navigationController?.pushViewController(viewController, animated: true)
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if let imageView = cell.imageView {
imageView.subviews.forEach({ $0.removeFromSuperview() })
imageView.frame = CGRect(width: 30, height: 30)
imageView.layer.cornerRadius = (imageView.frame.height) / 2
imageView.layer.masksToBounds = true
imageView.image = image
}
}
}
// For great debugging!
class RequirePasswordDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount(), account.actionNeeded != FxAActionNeeded.needsPassword {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onClick(_ navigationController: UINavigationController?) {
profile.getAccount()?.makeSeparated()
settings.tableView.reloadData()
}
}
// For great debugging!
class RequireUpgradeDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount(), account.actionNeeded != FxAActionNeeded.needsUpgrade {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onClick(_ navigationController: UINavigationController?) {
profile.getAccount()?.makeDoghouse()
settings.tableView.reloadData()
}
}
// For great debugging!
class ForgetSyncAuthStateDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let _ = profile.getAccount() {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onClick(_ navigationController: UINavigationController?) {
profile.getAccount()?.syncAuthState.invalidate()
settings.tableView.reloadData()
}
}
class DeleteExportedDataSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onClick(_ navigationController: UINavigationController?) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let fileManager = FileManager.default
do {
let files = try fileManager.contentsOfDirectory(atPath: documentsPath)
for file in files {
if file.hasPrefix("browser.") || file.hasPrefix("logins.") {
try fileManager.removeItemInDirectory(documentsPath, named: file)
}
}
} catch {
print("Couldn't delete exported data: \(error).")
}
}
}
class ExportBrowserDataSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onClick(_ navigationController: UINavigationController?) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
do {
let log = Logger.syncLogger
try self.settings.profile.files.copyMatching(fromRelativeDirectory: "", toAbsoluteDirectory: documentsPath) { file in
log.debug("Matcher: \(file)")
return file.hasPrefix("browser.") || file.hasPrefix("logins.") || file.hasPrefix("metadata.")
}
} catch {
print("Couldn't export browser data: \(error).")
}
}
}
class ExportLogDataSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Debug: copy log files to app container", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onClick(_ navigationController: UINavigationController?) {
Logger.copyPreviousLogsToDocuments();
}
}
/*
FeatureSwitchSetting is a boolean switch for features that are enabled via a FeatureSwitch.
These are usually features behind a partial release and not features released to the entire population.
*/
class FeatureSwitchSetting: BoolSetting {
let featureSwitch: FeatureSwitch
let prefs: Prefs
init(prefs: Prefs, featureSwitch: FeatureSwitch, with title: NSAttributedString) {
self.featureSwitch = featureSwitch
self.prefs = prefs
super.init(prefs: prefs, defaultValue: featureSwitch.isMember(prefs), attributedTitleText: title)
}
override var hidden: Bool {
return !ShowDebugSettings
}
override func displayBool(_ control: UISwitch) {
control.isOn = featureSwitch.isMember(prefs)
}
override func writeBool(_ control: UISwitch) {
self.featureSwitch.setMembership(control.isOn, for: self.prefs)
}
}
class EnableBookmarkMergingSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Enable Bidirectional Bookmark Sync ", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onClick(_ navigationController: UINavigationController?) {
AppConstants.shouldMergeBookmarks = true
}
}
class ForceCrashSetting: HiddenSetting {
override var title: NSAttributedString? {
return NSAttributedString(string: "Debug: Force Crash", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onClick(_ navigationController: UINavigationController?) {
Sentry.shared.crash()
}
}
// Show the current version of Firefox
class VersionSetting: Setting {
unowned let settings: SettingsTableViewController
override var accessibilityIdentifier: String? { return "FxVersion" }
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var title: NSAttributedString? {
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
let buildNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String
return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.selectionStyle = .none
}
override func onClick(_ navigationController: UINavigationController?) {
DebugSettingsClickCount += 1
if DebugSettingsClickCount >= 5 {
DebugSettingsClickCount = 0
ShowDebugSettings = !ShowDebugSettings
settings.tableView.reloadData()
}
}
}
// Opens the license page in a new tab
class LicenseAndAcknowledgementsSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override var url: URL? {
return URL(string: WebServer.sharedInstance.URLForResource("license", module: "about"))
}
override func onClick(_ navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens about:rights page in the content view controller
class YourRightsSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Your Rights", comment: "Your Rights settings section title"), attributes:
[NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override var url: URL? {
return URL(string: "https://www.mozilla.org/about/legal/terms/firefox/")
}
override func onClick(_ navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens the on-boarding screen again
class ShowIntroductionSetting: Setting {
let profile: Profile
override var accessibilityIdentifier: String? { return "ShowTour" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
navigationController?.dismiss(animated: true, completion: {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.browserViewController.presentIntroViewController(true)
}
})
}
}
class SendFeedbackSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Menu item in settings used to open input.mozilla.org where people can submit feedback"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override var url: URL? {
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
return URL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)")
}
override func onClick(_ navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
class SendAnonymousUsageDataSetting: BoolSetting {
init(prefs: Prefs, delegate: SettingsDelegate?) {
let statusText = NSMutableAttributedString()
statusText.append(NSAttributedString(string: Strings.SendUsageSettingMessage, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight]))
statusText.append(NSAttributedString(string: " "))
statusText.append(NSAttributedString(string: Strings.SendUsageSettingLink, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.general.highlightBlue]))
super.init(
prefs: prefs, prefKey: AppConstants.PrefSendUsageData, defaultValue: true,
attributedTitleText: NSAttributedString(string: Strings.SendUsageSettingTitle),
attributedStatusText: statusText,
settingDidChange: {
AdjustIntegration.setEnabled($0)
LeanPlumClient.shared.set(attributes: [LPAttributeKey.telemetryOptIn: $0])
LeanPlumClient.shared.set(enabled: $0)
}
)
}
override var url: URL? {
return SupportUtils.URLForTopic("adjust")
}
override func onClick(_ navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens the SUMO page in a new tab
class OpenSupportPageSetting: Setting {
init(delegate: SettingsDelegate?) {
super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]),
delegate: delegate)
}
override func onClick(_ navigationController: UINavigationController?) {
navigationController?.dismiss(animated: true) {
if let url = URL(string: "https://support.mozilla.org/products/ios") {
self.delegate?.settingsOpenURLInNewTab(url)
}
}
}
}
// Opens the search settings pane
class SearchSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var style: UITableViewCellStyle { return .value1 }
override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) }
override var accessibilityIdentifier: String? { return "Search" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = SearchSettingsTableViewController()
viewController.model = profile.searchEngines
viewController.profile = profile
navigationController?.pushViewController(viewController, animated: true)
}
}
class LoginsSetting: Setting {
let profile: Profile
var tabManager: TabManager!
weak var navigationController: UINavigationController?
weak var settings: AppSettingsTableViewController?
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "Logins" }
init(settings: SettingsTableViewController, delegate: SettingsDelegate?) {
self.profile = settings.profile
self.tabManager = settings.tabManager
self.navigationController = settings.navigationController
self.settings = settings as? AppSettingsTableViewController
let loginsTitle = NSLocalizedString("Logins", comment: "Label used as an item in Settings. When touched, the user will be navigated to the Logins/Password manager.")
super.init(title: NSAttributedString(string: loginsTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]),
delegate: delegate)
}
func deselectRow () {
if let selectedRow = self.settings?.tableView.indexPathForSelectedRow {
self.settings?.tableView.deselectRow(at: selectedRow, animated: true)
}
}
override func onClick(_: UINavigationController?) {
guard let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() else {
settings?.navigateToLoginsList()
LeanPlumClient.shared.track(event: .openedLogins)
return
}
if authInfo.requiresValidation() {
AppAuthenticator.presentAuthenticationUsingInfo(authInfo,
touchIDReason: AuthenticationStrings.loginsTouchReason,
success: {
self.settings?.navigateToLoginsList()
LeanPlumClient.shared.track(event: .openedLogins)
},
cancel: {
self.deselectRow()
},
fallback: {
AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self.settings)
self.deselectRow()
})
} else {
settings?.navigateToLoginsList()
LeanPlumClient.shared.track(event: .openedLogins)
}
}
}
class TouchIDPasscodeSetting: Setting {
let profile: Profile
var tabManager: TabManager!
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "TouchIDPasscode" }
init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) {
self.profile = settings.profile
self.tabManager = settings.tabManager
let localAuthContext = LAContext()
let title: String
if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) {
if #available(iOS 11.0, *), localAuthContext.biometryType == .faceID {
title = AuthenticationStrings.faceIDPasscodeSetting
} else {
title = AuthenticationStrings.touchIDPasscodeSetting
}
} else {
title = AuthenticationStrings.passcode
}
super.init(title: NSAttributedString(string: title, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]),
delegate: delegate)
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = AuthenticationSettingsViewController()
viewController.profile = profile
navigationController?.pushViewController(viewController, animated: true)
}
}
@available(iOS 11, *)
class ContentBlockerSetting: Setting {
let profile: Profile
var tabManager: TabManager!
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "TrackingProtection" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
self.tabManager = settings.tabManager
super.init(title: NSAttributedString(string: Strings.SettingsTrackingProtectionSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = ContentBlockerSettingViewController(prefs: profile.prefs)
viewController.profile = profile
viewController.tabManager = tabManager
navigationController?.pushViewController(viewController, animated: true)
}
}
class ClearPrivateDataSetting: Setting {
let profile: Profile
var tabManager: TabManager!
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "ClearPrivateData" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
self.tabManager = settings.tabManager
let clearTitle = Strings.SettingsDataManagementSectionName
super.init(title: NSAttributedString(string: clearTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = ClearPrivateDataTableViewController()
viewController.profile = profile
viewController.tabManager = tabManager
navigationController?.pushViewController(viewController, animated: true)
}
}
class PrivacyPolicySetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override var url: URL? {
return URL(string: "https://www.mozilla.org/privacy/firefox/")
}
override func onClick(_ navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
class ChinaSyncServiceSetting: WithoutAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .none }
var prefs: Prefs { return settings.profile.prefs }
let prefKey = "useChinaSyncService"
override var title: NSAttributedString? {
return NSAttributedString(string: "本地同步服务", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override var status: NSAttributedString? {
return NSAttributedString(string: "禁用后使用全球服务同步数据", attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight])
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIColor.theme.tableView.controlTint
control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)
control.isOn = prefs.boolForKey(prefKey) ?? BrowserProfile.isChinaEdition
cell.accessoryView = control
cell.selectionStyle = .none
}
@objc func switchValueChanged(_ toggle: UISwitch) {
prefs.setObject(toggle.isOn, forKey: prefKey)
}
}
class StageSyncServiceDebugSetting: WithoutAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .none }
var prefs: Prefs { return settings.profile.prefs }
var prefKey: String = "useStageSyncService"
override var accessibilityIdentifier: String? { return "DebugStageSync" }
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let _ = profile.getAccount() {
return true
}
return false
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: use stage servers", comment: "Debug option"), attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override var status: NSAttributedString? {
// Derive the configuration we display from the profile. Currently, this could be either a custom
// FxA server or FxA stage servers.
let isOn = prefs.boolForKey(prefKey) ?? false
let isCustomSync = prefs.boolForKey(PrefsKeys.KeyUseCustomSyncService) ?? false
var configurationURL = ProductionFirefoxAccountConfiguration().authEndpointURL
if isCustomSync {
configurationURL = CustomFirefoxAccountConfiguration(prefs: profile.prefs).authEndpointURL
} else if isOn {
configurationURL = StageFirefoxAccountConfiguration().authEndpointURL
}
return NSAttributedString(string: configurationURL.absoluteString, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight])
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIColor.theme.tableView.controlTint
control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)
control.isOn = prefs.boolForKey(prefKey) ?? false
cell.accessoryView = control
cell.selectionStyle = .none
}
@objc func switchValueChanged(_ toggle: UISwitch) {
prefs.setObject(toggle.isOn, forKey: prefKey)
settings.tableView.reloadData()
}
}
class HomePageSetting: Setting {
let profile: Profile
var tabManager: TabManager!
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "Homepage" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
self.tabManager = settings.tabManager
super.init(title: NSAttributedString(string: Strings.SettingsHomePageSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = HomePageSettingsViewController()
viewController.profile = profile
viewController.tabManager = tabManager
navigationController?.pushViewController(viewController, animated: true)
}
}
class NewTabPageSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "NewTab" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: Strings.SettingsNewTabSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = NewTabContentSettingsViewController(prefs: profile.prefs)
viewController.profile = profile
navigationController?.pushViewController(viewController, animated: true)
}
}
@available(iOS 12.0, *)
class SiriPageSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "SiriSettings" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: Strings.SettingsSiriSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = SiriSettingsViewController(prefs: profile.prefs)
viewController.profile = profile
navigationController?.pushViewController(viewController, animated: true)
}
}
class OpenWithSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "OpenWith.Setting" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: Strings.SettingsOpenWithSectionName, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = OpenWithSettingsViewController(prefs: profile.prefs)
navigationController?.pushViewController(viewController, animated: true)
}
}
class AdvanceAccountSetting: HiddenSetting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return "AdvanceAccount.Setting" }
override var title: NSAttributedString? {
return NSAttributedString(string: Strings.SettingsAdvanceAccountTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText])
}
override init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(settings: settings)
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = AdvanceAccountSettingViewController()
viewController.profile = profile
navigationController?.pushViewController(viewController, animated: true)
}
override var hidden: Bool {
return !ShowDebugSettings || profile.hasAccount()
}
}
class ThemeSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var style: UITableViewCellStyle { return .value1 }
override var accessibilityIdentifier: String? { return "DisplayThemeOption" }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: Strings.SettingsDisplayThemeTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
navigationController?.pushViewController(ThemeSettingsController(), animated: true)
}
}
|
d5388c0f4720953deb933841dab45f7c
| 40.211434 | 327 | 0.696928 | false | false | false | false |
OscarSwanros/swift
|
refs/heads/master
|
test/DebugInfo/linetable.swift
|
apache-2.0
|
3
|
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
// RUN: %target-swift-frontend %s -S -g -o - | %FileCheck %s --check-prefix ASM-CHECK
// REQUIRES: CPU=i386 || CPU=x86_64
import Swift
func markUsed<T>(_ t: T) {}
class MyClass
{
var x : Int64
init(input: Int64) { x = input }
func do_something(_ input: Int64) -> Int64
{
return x * input
}
}
func call_me(_ code: @escaping () -> Void)
{
code ()
}
func main(_ x: Int64) -> Void
// CHECK: define hidden {{.*}} void @_T09linetable4main{{[_0-9a-zA-Z]*}}F
{
var my_class = MyClass(input: 10)
// Linetable continuity. Don't go into the closure expression.
// ASM-CHECK: .loc [[FILEID:[0-9]]] [[@LINE+1]] 5
call_me (
// ASM-CHECK-NOT: .loc [[FILEID]] [[@LINE+1]] 5
// CHECK: define {{.*}} @_T09linetable4mainys5Int64VFyycfU_Tf2in_n({{.*}})
{
var result = my_class.do_something(x)
markUsed(result)
// CHECK: call {{.*}} @swift_rt_swift_release {{.*}}
// CHECK: bitcast
// CHECK: llvm.lifetime.end
// CHECK: call {{.*}} @swift_rt_swift_release {{.*}}, !dbg ![[CLOSURE_END:.*]]
// CHECK-NEXT: ret void, !dbg ![[CLOSURE_END]]
// CHECK: ![[CLOSURE_END]] = !DILocation(line: [[@LINE+1]],
}
)
// The swift_releases at the end should not jump to the point where
// that memory was retained/allocated and also not to line 0.
// ASM-CHECK-NOT: .loc [[FILEID]] 0 0
// ASM-CHECK: .loc [[FILEID]] [[@LINE+2]] 1
// ASM-CHECK: ret
}
// ASM-CHECK: {{^_?_T09linetable4mainys5Int64VFyycfU_Tf2in_n:}}
// ASM-CHECK-NOT: retq
// The end-of-prologue should have a valid location (0 is ok, too).
// ASM-CHECK: .loc [[FILEID]] {{0|34}} {{[0-9]+}} prologue_end
main(30)
|
e4a1a45ff28b79b0ea570daee942ec8b
| 28.77193 | 85 | 0.594579 | false | false | false | false |
davefoxy/SwiftBomb
|
refs/heads/master
|
SwiftBomb/Classes/Requests/LocationsRequests.swift
|
mit
|
1
|
//
// LocationsRequests.swift
// SwiftBomb
//
// Created by David Fox on 25/04/2016.
// Copyright © 2016 David Fox. All rights reserved.
//
import Foundation
extension SwiftBomb {
/**
Fetches a paginated list of `LocationResource` instances. This list can be filtered to a search term, paginated and sorted.
- parameter query: An optional search term used to filter for a particular location.
- parameter pagination: An optional `PaginationDefinition` to define the limit and offset when paginating results.
- parameter sort: An optional `SortDefinition` to define how the results should be sorted.
- parameter fields: An optional array of fields to return in the response. See the available options at http://www.giantbomb.com/api/documentation#toc-0-20. Pass nil to return everything.
- parameter completion: A closure returning an optional generic `PaginatedResults` object containing the returned `LocationResource` objects and pagination information and also, an optional `SwiftBombRequestError` object if the request failed.
*/
public static func fetchLocations(_ query: String? = nil, pagination: PaginationDefinition? = nil, sort: SortDefinition? = nil, fields: [String]? = nil, completion: @escaping (PaginatedResults<LocationResource>?, _ error: SwiftBombRequestError?) -> Void) {
let instance = SwiftBomb.framework
guard
let requestFactory = instance.requestFactory,
let networkingManager = instance.networkingManager else {
completion(nil, .frameworkConfigError)
return
}
let request = requestFactory.locationRequest(query, pagination: pagination, sort: sort, fields: fields)
networkingManager.performPaginatedRequest(request, objectType: LocationResource.self, completion: completion)
}
}
extension RequestFactory {
func locationRequest(_ query: String? = nil, pagination: PaginationDefinition? = nil, sort: SortDefinition? = nil, fields: [String]? = nil) -> SwiftBombRequest {
var request = SwiftBombRequest(configuration: configuration, path: "locations", method: .get, pagination: pagination, sort: sort, fields: fields)
addAuthentication(&request)
if let query = query {
request.addURLParameter("filter", value: "name:\(query)")
}
return request
}
}
extension LocationResource {
/**
Fetches extended info for this location. Also re-populates base data in the case where this object is a stub from another parent resource.
- parameter fields: An optional array of fields to return in the response. See the available options at http://www.giantbomb.com/api/documentation#toc-0-20. Pass nil to return everything.
- parameter completion: A closure containing an optional `SwiftBombRequestError` if the request failed.
*/
public func fetchExtendedInfo(_ fields: [String]? = nil, completion: @escaping (_ error: SwiftBombRequestError?) -> Void) {
let api = SwiftBomb.framework
guard
let networkingManager = api.networkingManager,
let id = id,
let request = api.requestFactory?.simpleRequest("location/\(id)/", fields: fields) else {
completion(.frameworkConfigError)
return
}
networkingManager.performDetailRequest(request, resource: self, completion: completion)
}
}
|
449578095015f3259101d42221978974
| 46.581081 | 260 | 0.687305 | false | true | false | false |
Bouke/HAP
|
refs/heads/master
|
Sources/HAP/Utils/Data+Extensions.swift
|
mit
|
1
|
import Foundation
// Removed in Xcode 8 beta 3
func + (lhs: Data, rhs: Data) -> Data {
var result = lhs
result.append(rhs)
return result
}
extension Data {
init?(hex: String) {
var result = [UInt8]()
var from = hex.startIndex
while from < hex.endIndex {
guard let to = hex.index(from, offsetBy: 2, limitedBy: hex.endIndex) else {
return nil
}
guard let num = UInt8(hex[from..<to], radix: 16) else {
return nil
}
result.append(num)
from = to
}
self = Data(result)
}
}
extension RandomAccessCollection where Iterator.Element == UInt8 {
var hex: String {
self.reduce("") { $0 + String(format: "%02x", $1) }
}
}
|
15c7f0254b650496f118f64ed3619824
| 23.71875 | 87 | 0.525917 | false | false | false | false |
Hout/SwiftMoment
|
refs/heads/master
|
CalendarViewDemo/Pods/SwiftMoment/SwiftMoment/SwiftMoment/Duration.swift
|
bsd-2-clause
|
5
|
//
// Duration.swift
// SwiftMoment
//
// Created by Adrian on 19/01/15.
// Copyright (c) 2015 Adrian Kosmaczewski. All rights reserved.
//
import Foundation
public struct Duration: Equatable {
let interval: NSTimeInterval
public init(value: NSTimeInterval) {
self.interval = value
}
public init(value: Int) {
self.interval = NSTimeInterval(value)
}
public var years: Double {
return interval / 31536000 // 365 days
}
public var quarters: Double {
return interval / 7776000 // 3 months
}
public var months: Double {
return interval / 2592000 // 30 days
}
public var days: Double {
return interval / 86400 // 24 hours
}
public var hours: Double {
return interval / 3600 // 60 minutes
}
public var minutes: Double {
return interval / 60
}
public var seconds: Double {
return interval
}
public func ago() -> Moment {
return moment().substract(self)
}
public func add(duration: Duration) -> Duration {
return Duration(value: self.interval + duration.interval)
}
public func substract(duration: Duration) -> Duration {
return Duration(value: self.interval - duration.interval)
}
public func isEqualTo(duration: Duration) -> Bool {
return self.interval == duration.interval
}
}
extension Duration: Printable {
public var description: String {
let formatter = NSDateComponentsFormatter()
formatter.allowedUnits = .CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitWeekOfMonth | .CalendarUnitDay | .CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond
let referenceDate = NSDate(timeIntervalSinceReferenceDate: 0)
let intervalDate = NSDate(timeInterval: self.interval, sinceDate: referenceDate)
return formatter.stringFromDate(referenceDate, toDate: intervalDate)!
}
}
|
edbce6cd4456d120113a70f740772e92
| 24.697368 | 181 | 0.65489 | false | false | false | false |
cotkjaer/SilverbackFramework
|
refs/heads/master
|
SilverbackFramework/HexagonCollectionViewFlowLayout.swift
|
mit
|
1
|
//
// HexagonCollectionViewFlowLayout.swift
// SilverbackFramework
//
// Created by Christian Otkjær on 30/06/15.
// Copyright (c) 2015 Christian Otkjær. All rights reserved.
//
import UIKit
public class HexagonCell: UICollectionViewCell
{
// let hexView = HexView()
//
// override public var contentView : UIView { return self.hexView }
}
public class HexagonCollectionViewFlowLayout: UICollectionViewFlowLayout
{
/// describes whether each line of hexes should have the same number of hexes in it, or if every other line will have itemsPerLine and the rest will have itemsPerLine - 1
public var alternateLineLength = true { didSet { invalidateLayout() } }
public var itemsPerLine : Int? { didSet { invalidateLayout() } }
public init(flowLayout: UICollectionViewFlowLayout)
{
super.init()
sectionInset = flowLayout.sectionInset
itemSize = flowLayout.itemSize
minimumLineSpacing = flowLayout.minimumLineSpacing
minimumInteritemSpacing = flowLayout.minimumInteritemSpacing
scrollDirection = flowLayout.scrollDirection
}
required public init?(coder aDecoder: NSCoder)
{
super.init(coder:aDecoder)
}
// Mark: Item Size
private func updateCellSize()
{
if let itemsPLine = itemsPerLine, let boundsSize = self.collectionView?.bounds.size
{
let lineLength = (scrollDirection == .Horizontal ? boundsSize.height : boundsSize.width)
let boundsLength = lineLength / (CGFloat(itemsPLine) + (alternateLineLength ? 0.0 : 0.5))
var size = CGSize(width: boundsLength, height: boundsLength)
switch scrollDirection
{
case .Horizontal:
size.width /= sin60
case .Vertical:
size.height = size.height / sin60
}
itemSize = size
}
}
//Mark: - UICollectionViewLayout overrides
public override func invalidateLayout()
{
updateCellSize()
super.invalidateLayout()
}
override public func prepareLayout()
{
attributesCache.removeAll(keepCapacity: true)
super.prepareLayout()
}
override public func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]?
{
if let numberOfItems = self.collectionView?.numberOfItemsInSection(0)
{
return (0..<numberOfItems).map({ self.layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: $0, inSection: 0))! } )
}
return nil
}
var attributesCache = Dictionary<NSIndexPath, UICollectionViewLayoutAttributes>()
func rowAndColForIndexPath(indexPath: NSIndexPath) -> (row: Int, col: Int)
{
let itemsInUpperLine = (itemsPerLine ?? 1) - (alternateLineLength ? 1 : 0)
let itemsInLowerLine = (itemsPerLine ?? 1)
let twoLinesItemCount = itemsInLowerLine + itemsInUpperLine
var col = (indexPath.item % twoLinesItemCount)
var row = (indexPath.item / twoLinesItemCount)
row = row * 2
if col >= itemsInUpperLine
{
row += 1
col -= itemsInUpperLine
}
debugPrint("item: \(indexPath.item) -> (\(row), \(col))")
return (row, col)
}
override public func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?
{
if let attributes = attributesCache[indexPath]
{
return attributes
}
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
attributes.size = self.itemSize
let (row, col) = rowAndColForIndexPath(indexPath)
if scrollDirection == .Vertical
{
let horiOffset : CGFloat = ((row % 2) != 0) ? 0 : self.itemSize.width * 0.5
let vertOffset : CGFloat = 0
attributes.center = CGPoint(
x: ( (col * self.itemSize.width) + (0.5 * self.itemSize.width) + horiOffset),
y: ( ( (row * 0.75) * self.itemSize.height) + (0.5 * self.itemSize.height) + vertOffset) )
}
else
{
let horiOffset : CGFloat = 0
let vertOffset : CGFloat = ((row % 2) != 0) ? 0 : self.itemSize.height * 0.5
attributes.center = CGPoint(
x: ( ( (row * 0.75) * itemSize.width) + (0.5 * itemSize.width) + horiOffset),
y: ( (col * itemSize.height) + (0.5 * itemSize.height) + vertOffset) )
}
attributesCache[indexPath] = attributes
return attributes
}
override public func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool
{
return false
}
// private var lastIndexPath : NSIndexPath?
// {
// if let collectionView = self.collectionView
// {
// let section = collectionView.numberOfSections() - 1
//
// if section >= 0
// {
// let item = collectionView.numberOfItemsInSection(section) - 1
//
// if item >= 0
// {
// return NSIndexPath(forItem: item, inSection: section)
// }
// }
// }
//
// return nil
// }
private var cachedCollectionViewContentSize : CGSize?
override public func collectionViewContentSize() -> CGSize
{
if let size = cachedCollectionViewContentSize
{
return size
}
if let collectionView = self.collectionView,
let lastIndexPath = collectionView.lastIndexPath,
let attributes = layoutAttributesForItemAtIndexPath(lastIndexPath)
{
return CGSize(
width: max(collectionView.bounds.width, attributes.frame.maxX),
height: max(collectionView.bounds.height, attributes.frame.maxY))
}
return CGSizeZero
}
}
|
661a809c4a80993e5028584179c6efcf
| 29.961538 | 174 | 0.562578 | false | false | false | false |
apple/swift-protobuf
|
refs/heads/main
|
Sources/SwiftProtobuf/TimeUtils.swift
|
apache-2.0
|
3
|
// Sources/SwiftProtobuf/TimeUtils.swift - Generally useful time/calendar functions
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Generally useful time/calendar functions and constants
///
// -----------------------------------------------------------------------------
let minutesPerDay: Int32 = 1440
let minutesPerHour: Int32 = 60
let secondsPerDay: Int32 = 86400
let secondsPerHour: Int32 = 3600
let secondsPerMinute: Int32 = 60
let nanosPerSecond: Int32 = 1000000000
internal func timeOfDayFromSecondsSince1970(seconds: Int64) -> (hh: Int32, mm: Int32, ss: Int32) {
let secondsSinceMidnight = Int32(mod(seconds, Int64(secondsPerDay)))
let ss = mod(secondsSinceMidnight, secondsPerMinute)
let mm = mod(div(secondsSinceMidnight, secondsPerMinute), minutesPerHour)
let hh = Int32(div(secondsSinceMidnight, secondsPerHour))
return (hh: hh, mm: mm, ss: ss)
}
internal func julianDayNumberFromSecondsSince1970(seconds: Int64) -> Int64 {
// January 1, 1970 is Julian Day Number 2440588.
// See http://aa.usno.navy.mil/faq/docs/JD_Formula.php
return div(seconds + 2440588 * Int64(secondsPerDay), Int64(secondsPerDay))
}
internal func gregorianDateFromSecondsSince1970(seconds: Int64) -> (YY: Int32, MM: Int32, DD: Int32) {
// The following implements Richards' algorithm (see the Wikipedia article
// for "Julian day").
// If you touch this code, please test it exhaustively by playing with
// Test_Timestamp.testJSON_range.
let JJ = julianDayNumberFromSecondsSince1970(seconds: seconds)
let f = JJ + 1401 + div(div(4 * JJ + 274277, 146097) * 3, 4) - 38
let e = 4 * f + 3
let g = Int64(div(mod(e, 1461), 4))
let h = 5 * g + 2
let DD = div(mod(h, 153), 5) + 1
let MM = mod(div(h, 153) + 2, 12) + 1
let YY = div(e, 1461) - 4716 + div(12 + 2 - MM, 12)
return (YY: Int32(YY), MM: Int32(MM), DD: Int32(DD))
}
internal func nanosToString(nanos: Int32) -> String {
if nanos == 0 {
return ""
} else if nanos % 1000000 == 0 {
return ".\(threeDigit(abs(nanos) / 1000000))"
} else if nanos % 1000 == 0 {
return ".\(sixDigit(abs(nanos) / 1000))"
} else {
return ".\(nineDigit(abs(nanos)))"
}
}
|
88c690393c12a999b0ffcc73e77e9ecf
| 37.307692 | 102 | 0.637605 | false | false | false | false |
Ataraxiis/MGW-Esport
|
refs/heads/develop
|
Carthage/Checkouts/RxSwift/RxCocoa/Common/Observable+Bind.swift
|
apache-2.0
|
28
|
//
// Observable+Bind.swift
// Rx
//
// Created by Krunoslav Zaher on 8/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
extension ObservableType {
/**
Creates new subscription and sends elements to observer.
In this form it's equivalent to `subscribe` method, but it communicates intent better, and enables
writing more consistent binding code.
- parameter observer: Observer that receives events.
- returns: Disposable object that can be used to unsubscribe the observer.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func bindTo<O: ObserverType where O.E == E>(observer: O) -> Disposable {
return self.subscribe(observer)
}
/**
Creates new subscription and sends elements to variable.
In case error occurs in debug mode, `fatalError` will be raised.
In case error occurs in release mode, `error` will be logged.
- parameter variable: Target variable for sequence elements.
- returns: Disposable object that can be used to unsubscribe the observer.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func bindTo(variable: Variable<E>) -> Disposable {
return subscribe { e in
switch e {
case let .Next(element):
variable.value = element
case let .Error(error):
let error = "Binding error to variable: \(error)"
#if DEBUG
rxFatalError(error)
#else
print(error)
#endif
case .Completed:
break
}
}
}
/**
Subscribes to observable sequence using custom binder function.
- parameter binder: Function used to bind elements from `self`.
- returns: Object representing subscription.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func bindTo<R>(binder: Self -> R) -> R {
return binder(self)
}
/**
Subscribes to observable sequence using custom binder function and final parameter passed to binder function
after `self` is passed.
public func bindTo<R1, R2>(binder: Self -> R1 -> R2, curriedArgument: R1) -> R2 {
return binder(self)(curriedArgument)
}
- parameter binder: Function used to bind elements from `self`.
- parameter curriedArgument: Final argument passed to `binder` to finish binding process.
- returns: Object representing subscription.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func bindTo<R1, R2>(binder: Self -> R1 -> R2, curriedArgument: R1) -> R2 {
return binder(self)(curriedArgument)
}
/**
Subscribes an element handler to an observable sequence.
In case error occurs in debug mode, `fatalError` will be raised.
In case error occurs in release mode, `error` will be logged.
- parameter onNext: Action to invoke for each element in the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.ud")
public func bindNext(onNext: E -> Void) -> Disposable {
return subscribe(onNext: onNext, onError: { error in
let error = "Binding error: \(error)"
#if DEBUG
rxFatalError(error)
#else
print(error)
#endif
})
}
}
|
ac9aaf78f9815188d8f0d6dd049d6f1e
| 32.149533 | 112 | 0.625317 | false | false | false | false |
ivanbruel/Moya-ObjectMapper
|
refs/heads/master
|
Sample/Demo-ReactiveSwift/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Demo-ReactiveSwift
//
// Created by Robin Picard on 12/04/2019.
// Copyright © 2019 Ash Furrow. All rights reserved.
//
import Moya
import ReactiveCocoa
import ReactiveSwift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var zenButton: UIBarButtonItem!
@IBOutlet weak var searchButton: UIBarButtonItem!
@IBOutlet var tableView: UITableView! {
didSet {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
tableView.dataSource = self
tableView.reactive.reloadData <~ viewModel.reloadDataSignal
}
}
private let viewModel: ReactiveDemoViewModel = ReactiveDemoViewModel(networking: GitHubProvider)
override func viewDidLoad() {
super.viewDidLoad()
initializeViewModel()
}
fileprivate func initializeViewModel() {
viewModel.downloadZenSignal.observeValues { [weak self] result in
switch result {
case .success(let value): self?.showMessage(message: value)
case .failure(let error): self?.showError(error: error)
}
}
viewModel.downloadRepoSignal.observeValues { [weak self] result in
switch result {
case .success: break
case .failure: self?.presentUsernamePrompt()
}
}
viewModel.downloadRepositories(username: "p-rob")
}
fileprivate func showError(error: Error) {
let alert = UIAlertController(title: "An error has occured!", message: error.localizedDescription, preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
alert.dismiss(animated: true, completion: nil)
})
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
fileprivate func showMessage(message: String) {
let alert = UIAlertController(title: "Info", message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
alert.dismiss(animated: true, completion: nil)
})
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
fileprivate func presentUsernamePrompt() {
var usernameTextField: UITextField?
let promptController = UIAlertController(title: "Username", message: nil, preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { [weak self] _ in
if let username = usernameTextField?.text {
self?.viewModel.downloadRepositories(username: username)
}
})
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
promptController.addAction(ok)
promptController.addAction(cancel)
promptController.addTextField { (textField) -> Void in
usernameTextField = textField
}
present(promptController, animated: true, completion: nil)
}
// MARK: - User Interaction
@IBAction func searchWasPressed(_ sender: UIBarButtonItem) {
presentUsernamePrompt()
}
@IBAction func zenWasPressed(_ sender: UIBarButtonItem) {
viewModel.downloadZen()
}
}
extension ViewController: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.datasource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
let repo = viewModel.datasource[indexPath.row]
cell.textLabel?.text = repo.name
return cell
}
}
|
3ab0166b57312364602342b72225e2c5
| 31.907407 | 126 | 0.712155 | false | false | false | false |
VirgilSecurity/virgil-sdk-keys-ios
|
refs/heads/master
|
Source/Cards/Client/CardClient+Queries.swift
|
bsd-3-clause
|
1
|
//
// Copyright (C) 2015-2020 Virgil Security Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// (1) Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// (3) Neither the name of the copyright holder 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 AUTHOR ''AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>
//
import Foundation
// MARK: - Queries
extension CardClient: CardClientProtocol {
/// HTTP header key for getCard response that marks outdated cards
@objc public static let xVirgilIsSuperseededKey = "x-virgil-is-superseeded"
/// HTTP header value for xVirgilIsSuperseededKey key for getCard response that marks outdated cards
@objc public static let xVirgilIsSuperseededTrue = "true"
private func createRetry() -> RetryProtocol {
return ExpBackoffRetry(config: self.retryConfig)
}
/// Returns `GetCardResponse` with `RawSignedModel` of card from the Virgil Cards Service with given ID, if exists
///
/// - Parameter cardId: String with unique Virgil Card identifier
/// - Returns: `GetCardResponse` if card found
/// - Throws:
/// - `CardClientError.constructingUrl`, if url initialization failed
/// - Rethrows from `ServiceRequest`
/// - Rethrows `ServiceError` or `NSError` from `BaseClient`
@objc open func getCard(withId cardId: String) throws -> GetCardResponse {
guard let url = URL(string: "card/v5/\(cardId)", relativeTo: self.serviceUrl) else {
throw CardClientError.constructingUrl
}
let tokenContext = TokenContext(service: "cards", operation: "get", forceReload: false)
let request = try ServiceRequest(url: url, method: .get)
let response = try self.sendWithRetry(request,
retry: self.createRetry(),
tokenContext: tokenContext)
.startSync()
.get()
let isOutdated: Bool
// Swift dictionaries doesn't support case-insensitive keys, NSDictionary does
let allHeaders = (response.response.allHeaderFields as NSDictionary)
if let xVirgilIsSuperseeded = allHeaders[CardClient.xVirgilIsSuperseededKey] as? String,
xVirgilIsSuperseeded == CardClient.xVirgilIsSuperseededTrue {
isOutdated = true
}
else {
isOutdated = false
}
return GetCardResponse(rawCard: try self.processResponse(response), isOutdated: isOutdated)
}
/// Creates Virgil Card instance on the Virgil Cards Service
/// Also makes the Card accessible for search/get queries from other users
/// `RawSignedModel` should contain appropriate signatures
///
/// - Parameter model: Signed `RawSignedModel`
/// - Returns: `RawSignedModel` of created card
/// - Throws:
/// - `CardClientError.constructingUrl`, if url initialization failed
/// - Rethrows from `ServiceRequest`
/// - Rethrows `ServiceError` or `NSError` from `BaseClient`
@objc open func publishCard(model: RawSignedModel) throws -> RawSignedModel {
guard let url = URL(string: "card/v5", relativeTo: self.serviceUrl) else {
throw CardClientError.constructingUrl
}
let tokenContext = TokenContext(service: "cards", operation: "publish", forceReload: false)
let request = try ServiceRequest(url: url, method: .post, params: model)
let response = try self.sendWithRetry(request,
retry: self.createRetry(),
tokenContext: tokenContext)
.startSync()
.get()
return try self.processResponse(response)
}
/// Performs search of Virgil Cards using given identities on the Virgil Cards Service
///
/// - Parameter identities: Identities of cards to search
/// - Returns: Array with `RawSignedModel`s of matched Virgil Cards
/// - Throws:
/// - CardClientError.constructingUrl, if url initialization failed
/// - ServiceError, if service returned correctly-formed error json
/// - NSError with CardClient.serviceErrorDomain error domain,
/// http status code as error code, and description string if present in http body
/// - Rethrows from `ServiceRequest`, `HttpConnectionProtocol`, `JsonDecoder`, `BaseClient`
@objc public func searchCards(identities: [String]) throws -> [RawSignedModel] {
guard let url = URL(string: "card/v5/actions/search", relativeTo: self.serviceUrl) else {
throw CardClientError.constructingUrl
}
let tokenContext = TokenContext(service: "cards", operation: "search", forceReload: false)
let request = try ServiceRequest(url: url,
method: .post,
params: ["identities": identities])
let response = try self.sendWithRetry(request,
retry: self.createRetry(),
tokenContext: tokenContext)
.startSync()
.get()
return try self.processResponse(response)
}
/// Returns list of cards that were replaced with newer ones
///
/// - Parameter cardIds: card ids to check
/// - Returns: List of old card ids
/// - Throws:
/// - CardClientError.constructingUrl, if url initialization failed
/// - ServiceError, if service returned correctly-formed error json
/// - NSError with CardClient.serviceErrorDomain error domain,
/// http status code as error code, and description string if present in http body
/// - Rethrows from `ServiceRequest`, `HttpConnectionProtocol`, `JsonDecoder`, `BaseClient`
@objc public func getOutdated(cardIds: [String]) throws -> [String] {
guard let url = URL(string: "card/v5/actions/outdated", relativeTo: self.serviceUrl) else {
throw CardClientError.constructingUrl
}
let tokenContext = TokenContext(service: "cards", operation: "get-outdated", forceReload: false)
let request = try ServiceRequest(url: url,
method: .post,
params: ["card_ids": cardIds])
let response = try self.sendWithRetry(request,
retry: self.createRetry(),
tokenContext: tokenContext)
.startSync()
.get()
return try self.processResponse(response)
}
/// Revokes card. Revoked card gets isOutdated flag to be set to true.
/// Also, such cards could be obtained using get query, but will be absent in search query result.
///
/// - Parameter cardId: identifier of card to revoke
/// - Throws:
/// - CardClientError.constructingUrl, if url initialization failed
/// - ServiceError, if service returned correctly-formed error json
/// - NSError with CardClient.serviceErrorDomain error domain,
/// http status code as error code, and description string if present in http body
/// - Rethrows from `ServiceRequest`, `HttpConnectionProtocol`, `JsonDecoder`, `BaseClient`
@objc public func revokeCard(withId cardId: String) throws {
guard let url = URL(string: "card/v5/actions/revoke/\(cardId)", relativeTo: self.serviceUrl) else {
throw CardClientError.constructingUrl
}
let tokenContext = TokenContext(service: "cards", operation: "revoke", forceReload: false)
let request = try ServiceRequest(url: url,
method: .post)
let response = try self.sendWithRetry(request,
retry: self.createRetry(),
tokenContext: tokenContext)
.startSync()
.get()
try self.validateResponse(response)
}
}
|
240df3b28e6e48a3153591db66d09ea3
| 45.172414 | 118 | 0.63875 | false | false | false | false |
hibu/apptentive-ios
|
refs/heads/master
|
Demo/iOSDemo/DataViewController.swift
|
bsd-3-clause
|
1
|
//
// DataViewController.swift
// iOS Demo
//
// Created by Frank Schmitt on 4/27/16.
// Copyright © 2016 Apptentive, Inc. All rights reserved.
//
import UIKit
class DataViewController: UITableViewController {
@IBOutlet var modeControl: UISegmentedControl!
let dataSources = [PersonDataSource(), DeviceDataSource()]
override func setEditing(editing: Bool, animated: Bool) {
dataSources.forEach { $0.editing = editing }
let numberOfRows = self.tableView.numberOfRowsInSection(1)
var indexPaths = [NSIndexPath]()
if editing {
for row in numberOfRows..<(numberOfRows + 3) {
indexPaths.append(NSIndexPath(forRow: row, inSection: 1))
}
self.tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Top)
} else {
for row in (numberOfRows - 3)..<numberOfRows {
indexPaths.append(NSIndexPath(forRow: row, inSection: 1))
}
self.tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Top)
}
super.setEditing(editing, animated: animated)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.titleView = modeControl
self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateMode(modeControl)
}
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
if indexPath.section == 1 {
if indexPath.row >= tableView.numberOfRowsInSection(1) - 3 {
return .Insert
} else {
return .Delete
}
}
return .None
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let dataSource = tableView.dataSource as? DataSource where dataSource == dataSources[0] && indexPath.section == 0 && self.editing {
if let navigationController = self.storyboard?.instantiateViewControllerWithIdentifier("NameEmailNavigation") as? UINavigationController, let stringViewController = navigationController.viewControllers.first as? StringViewController {
stringViewController.title = indexPath.row == 0 ? "Edit Name" : "Edit Email"
stringViewController.string = indexPath.row == 0 ? Apptentive.sharedConnection().personName : Apptentive.sharedConnection().personEmailAddress
self.presentViewController(navigationController, animated: true, completion: nil)
}
}
}
@IBAction func updateMode(sender: UISegmentedControl) {
let dataSource = dataSources[sender.selectedSegmentIndex]
dataSource.refresh()
self.tableView.dataSource = dataSource;
self.tableView.reloadData()
}
@IBAction func returnToDataList(sender: UIStoryboardSegue) {
if let value = (sender.sourceViewController as? StringViewController)?.string {
if let selectedIndex = self.tableView.indexPathForSelectedRow?.row {
if selectedIndex == 0 {
Apptentive.sharedConnection().personName = value
} else {
Apptentive.sharedConnection().personEmailAddress = value
}
}
tableView.reloadSections(NSIndexSet(index:0), withRowAnimation: .Automatic)
}
}
func addCustomData(index: Int) {
print("Adding type with index \(index)")
}
}
class DataSource: NSObject, UITableViewDataSource {
var editing = false
override init() {
super.init()
self.refresh()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier("Datum", forIndexPath: indexPath)
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Standard Data"
} else {
return "Custom Data"
}
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return indexPath.section == 1
}
func refresh() {
}
// TODO: convert to enum?
func labelForAdding(index: Int) -> String {
switch index {
case 0:
return "Add String"
case 1:
return "Add Number"
default:
return "Add Boolean"
}
}
func reuseIdentifierForAdding(index: Int) -> String {
switch index {
case 0:
return "String"
case 1:
return "Number"
default:
return "Boolean"
}
}
}
class PersonDataSource: DataSource {
var customKeys = [String]()
var customData = [String : NSObject]()
override func refresh() {
if let customData = (Apptentive.sharedConnection().customPersonData as NSDictionary) as? [String : NSObject] {
self.customData = customData
self.customKeys = customData.keys.sort { $0 < $1 }
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2
} else {
return self.customKeys.count + (self.editing ? 3 : 0)
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell
if indexPath.section == 0 || indexPath.row < self.customKeys.count {
cell = tableView.dequeueReusableCellWithIdentifier("Datum", forIndexPath: indexPath)
let key: String
let value: String?
if indexPath.section == 0 {
if indexPath.row == 0 {
key = "Name"
value = Apptentive.sharedConnection().personName
} else {
key = "Email"
value = Apptentive.sharedConnection().personEmailAddress
}
} else {
key = self.customKeys[indexPath.row]
value = self.customData[key]?.description
}
cell.textLabel?.text = key
cell.detailTextLabel?.text = value
} else {
cell = tableView.dequeueReusableCellWithIdentifier(self.reuseIdentifierForAdding(indexPath.row - self.customKeys.count), forIndexPath: indexPath)
}
return cell
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 {
return
} else if editingStyle == .Delete {
Apptentive.sharedConnection().removeCustomPersonDataWithKey(self.customKeys[indexPath.row])
self.refresh()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
} else if editingStyle == .Insert {
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? CustomDataCell, let key = cell.keyField.text {
switch self.reuseIdentifierForAdding(indexPath.row - self.customKeys.count) {
case "String":
if let textField = cell.valueControl as? UITextField, string = textField.text {
Apptentive.sharedConnection().addCustomPersonDataString(string, withKey: key)
textField.text = nil
}
case "Number":
if let textField = cell.valueControl as? UITextField, numberString = textField.text, number = NSNumberFormatter().numberFromString(numberString) {
Apptentive.sharedConnection().addCustomPersonDataNumber(number, withKey: key)
textField.text = nil
}
case "Boolean":
if let switchControl = cell.valueControl as? UISwitch {
Apptentive.sharedConnection().addCustomPersonDataBool(switchControl.on, withKey: key)
switchControl.on = true
}
default:
break;
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
self.refresh()
tableView.reloadSections(NSIndexSet(index:1), withRowAnimation: .Automatic)
cell.keyField.text = nil
}
}
}
}
class DeviceDataSource: DataSource {
var deviceKeys = [String]()
var deviceData = [String : AnyObject]()
var customDeviceKeys = [String]()
var customDeviceData = [String : NSObject]()
override func refresh() {
self.deviceData = Apptentive.sharedConnection().deviceInfo
self.deviceKeys = self.deviceData.keys.sort { $0 < $1 }
if let customDataKeyIndex = self.deviceKeys.indexOf("custom_data") {
self.deviceKeys.removeAtIndex(customDataKeyIndex)
}
if let customDeviceData = (Apptentive.sharedConnection().customDeviceData as NSDictionary) as? [String : NSObject] {
self.customDeviceData = customDeviceData
self.customDeviceKeys = customDeviceData.keys.sort { $0 < $1 }
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return self.deviceKeys.count
} else {
return self.customDeviceKeys.count + (self.editing ? 3 : 0)
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell
if indexPath.section == 0 || indexPath.row < self.customDeviceKeys.count {
cell = tableView.dequeueReusableCellWithIdentifier("Datum", forIndexPath: indexPath)
let key: String
let value: String?
if indexPath.section == 0 {
key = self.deviceKeys[indexPath.row]
value = self.deviceData[key]?.description
} else {
key = self.customDeviceKeys[indexPath.row]
value = self.customDeviceData[key]?.description
}
cell.textLabel?.text = key
cell.detailTextLabel?.text = value
cell.selectionStyle = indexPath.section == 0 ? .None : .Default
} else {
cell = tableView.dequeueReusableCellWithIdentifier(self.reuseIdentifierForAdding(indexPath.row - self.customDeviceKeys.count), forIndexPath: indexPath)
}
return cell
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 {
return
} else if editingStyle == .Delete {
Apptentive.sharedConnection().removeCustomDeviceDataWithKey(self.customDeviceKeys[indexPath.row])
self.refresh()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
} else if editingStyle == .Insert {
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? CustomDataCell, let key = cell.keyField.text {
switch self.reuseIdentifierForAdding(indexPath.row - self.customDeviceKeys.count) {
case "String":
if let textField = cell.valueControl as? UITextField, string = textField.text {
Apptentive.sharedConnection().addCustomDeviceDataString(string, withKey: key)
textField.text = nil
}
case "Number":
if let textField = cell.valueControl as? UITextField, numberString = textField.text, number = NSNumberFormatter().numberFromString(numberString) {
Apptentive.sharedConnection().addCustomDeviceDataNumber(number, withKey: key)
textField.text = nil
}
case "Boolean":
if let switchControl = cell.valueControl as? UISwitch {
Apptentive.sharedConnection().addCustomDeviceDataBool(switchControl.on, withKey: key)
switchControl.on = true
}
default:
break;
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
self.refresh()
tableView.reloadSections(NSIndexSet(index:1), withRowAnimation: .Automatic)
cell.keyField.text = nil
}
}
}
}
|
5013b4ffb89aaebb707e6b457a8f75ee
| 31.81982 | 237 | 0.730442 | false | false | false | false |
realm/SwiftLint
|
refs/heads/main
|
Source/SwiftLintFramework/Models/Example.swift
|
mit
|
1
|
/// Captures code and context information for an example of a triggering or
/// non-triggering style
public struct Example {
/// The contents of the example
public private(set) var code: String
/// The untyped configuration to apply to the rule, if deviating from the default configuration.
/// The structure should match what is expected as a configuration value for the rule being tested.
///
/// For example, if the following YAML would be used to configure the rule:
///
/// ```
/// severity: warning
/// ```
///
/// Then the equivalent configuration value would be `["severity": "warning"]`.
public private(set) var configuration: Any?
/// Whether the example should be tested by prepending multibyte grapheme clusters
///
/// - SeeAlso: addEmoji(_:)
public private(set) var testMultiByteOffsets: Bool
/// Whether tests shall verify that the example wrapped in a comment doesn't trigger
private(set) var testWrappingInComment: Bool
/// Whether tests shall verify that the example wrapped into a string doesn't trigger
private(set) var testWrappingInString: Bool
/// Whether tests shall verify that the disabled rule (comment in the example) doesn't trigger
private(set) var testDisableCommand: Bool
/// Whether the example should be tested on Linux
public private(set) var testOnLinux: Bool
/// The path to the file where the example was created
public private(set) var file: StaticString
/// The line in the file where the example was created
public var line: UInt
/// Specifies whether the example should be excluded from the rule documentation.
///
/// It can be set to `true` if an example has mainly been added as another test case, but is not suitable
/// as a user example. User examples should be easy to understand. They should clearly show where and
/// why a rule is applied and where not. Complex examples with rarely used language constructs or
/// pathological use cases which are indeed important to test but not helpful for understanding can be
/// hidden from the documentation with this option.
let excludeFromDocumentation: Bool
/// Specifies whether the test example should be the only example run during the current test case execution.
var isFocused: Bool
}
public extension Example {
/// Create a new Example with the specified code, file, and line.
/// - Parameters:
/// - code: The contents of the example.
/// - configuration: The untyped configuration to apply to the rule, if deviating from the default
/// configuration.
/// - testMultibyteOffsets: Whether the example should be tested by prepending multibyte grapheme clusters.
/// - testWrappingInComment:Whether test shall verify that the example wrapped in a comment doesn't trigger.
/// - testWrappingInString: Whether tests shall verify that the example wrapped into a string doesn't trigger.
/// - testDisableCommand: Whether tests shall verify that the disabled rule (comment in the example) doesn't
/// trigger.
/// - testOnLinux: Whether the example should be tested on Linux.
/// - file: The path to the file where the example is located.
/// Defaults to the file where this initializer is called.
/// - line: The line in the file where the example is located.
/// Defaults to the line where this initializer is called.
init(_ code: String, configuration: Any? = nil, testMultiByteOffsets: Bool = true,
testWrappingInComment: Bool = true, testWrappingInString: Bool = true, testDisableCommand: Bool = true,
testOnLinux: Bool = true, file: StaticString = #file, line: UInt = #line,
excludeFromDocumentation: Bool = false) {
self.code = code
self.configuration = configuration
self.testMultiByteOffsets = testMultiByteOffsets
self.testOnLinux = testOnLinux
self.file = file
self.line = line
self.excludeFromDocumentation = excludeFromDocumentation
self.testWrappingInComment = testWrappingInComment
self.testWrappingInString = testWrappingInString
self.testDisableCommand = testDisableCommand
self.isFocused = false
}
/// Returns the same example, but with the `code` that is passed in
/// - Parameter code: the new code to use in the modified example
func with(code: String) -> Example {
var new = self
new.code = code
return new
}
/// Returns a copy of the Example with all instances of the "↓" character removed.
func removingViolationMarkers() -> Example {
return with(code: code.replacingOccurrences(of: "↓", with: ""))
}
}
extension Example {
func skipWrappingInCommentTest() -> Self {
var new = self
new.testWrappingInComment = false
return new
}
func skipWrappingInStringTest() -> Self {
var new = self
new.testWrappingInString = false
return new
}
func skipMultiByteOffsetTest() -> Self {
var new = self
new.testMultiByteOffsets = false
return new
}
func skipDisableCommandTest() -> Self {
var new = self
new.testDisableCommand = false
return new
}
/// Makes the current example focused. This is for debugging purposes only.
func focused() -> Example { // swiftlint:disable:this unused_declaration
var new = self
new.isFocused = true
return new
}
}
extension Example: Hashable {
public static func == (lhs: Example, rhs: Example) -> Bool {
// Ignoring file/line metadata because two Examples could represent
// the same idea, but captured at two different points in the code
return lhs.code == rhs.code
}
public func hash(into hasher: inout Hasher) {
// Ignoring file/line metadata because two Examples could represent
// the same idea, but captured at two different points in the code
hasher.combine(code)
}
}
extension Example: Comparable {
public static func < (lhs: Example, rhs: Example) -> Bool {
return lhs.code < rhs.code
}
}
extension Array where Element == Example {
/// Make these examples skip wrapping in comment tests.
func skipWrappingInCommentTests() -> Self {
map { $0.skipWrappingInCommentTest() }
}
/// Make these examples skip wrapping in string tests.
func skipWrappingInStringTests() -> Self {
map { $0.skipWrappingInStringTest() }
}
/// Make these examples skip multi-byte offset tests.
func skipMultiByteOffsetTests() -> Self {
map { $0.skipMultiByteOffsetTest() }
}
/// Make these examples skip disable command tests.
func skipDisableCommandTests() -> Self {
map { $0.skipDisableCommandTest() }
}
}
|
8240c53882eb06b3d96af1348a629cba
| 41.487952 | 116 | 0.661562 | false | true | false | false |
SamirTalwar/advent-of-code
|
refs/heads/main
|
2018/AOC_13_2.swift
|
mit
|
1
|
enum Turning {
case left
case straight
case right
}
enum Direction: CustomStringConvertible {
case north
case east
case south
case west
var description: String {
switch self {
case .north:
return "^"
case .east:
return ">"
case .south:
return "v"
case .west:
return "<"
}
}
var isHorizontal: Bool {
return self == .east || self == .west
}
var isVertical: Bool {
return self == .north || self == .south
}
func turn(_ turning: Turning) -> Direction {
switch (self, turning) {
case (.north, .left):
return .west
case (.east, .left):
return .north
case (.south, .left):
return .east
case (.west, .left):
return .south
case (.north, .right):
return .east
case (.east, .right):
return .south
case (.south, .right):
return .west
case (.west, .right):
return .north
case (_, .straight):
return self
}
}
}
struct Position: Equatable, Comparable, Hashable, CustomStringConvertible {
let x: Int
let y: Int
var description: String {
return "(\(x), \(y))"
}
static func < (lhs: Position, rhs: Position) -> Bool {
if lhs.y != rhs.y {
return lhs.y < rhs.y
} else {
return lhs.x < rhs.x
}
}
func move(_ direction: Direction) -> Position {
switch direction {
case .north:
return Position(x: x, y: y - 1)
case .east:
return Position(x: x + 1, y: y)
case .south:
return Position(x: x, y: y + 1)
case .west:
return Position(x: x - 1, y: y)
}
}
}
enum TrackPiece {
case empty
case horizontal
case vertical
case turningLeftFromNorthOrSouth
case turningRightFromNorthOrSouth
case intersection
}
extension TrackPiece: CustomStringConvertible {
var description: String {
switch self {
case .empty:
return " "
case .horizontal:
return "-"
case .vertical:
return "|"
case .turningLeftFromNorthOrSouth:
return "\\"
case .turningRightFromNorthOrSouth:
return "/"
case .intersection:
return "+"
}
}
}
struct Tracks: CustomStringConvertible {
private let tracks: [[TrackPiece]]
init(_ tracks: [[TrackPiece]]) {
self.tracks = tracks
}
var description: String {
return tracks.map { row in row.map { cell in cell.description }.joined() }.joined(separator: "\n")
}
subscript(position: Position) -> TrackPiece {
return tracks[position.y][position.x]
}
}
struct Cart: CustomStringConvertible {
let position: Position
let direction: Direction
let intersectionTurning: Turning
var description: String {
return "\(position) \(direction)"
}
func move(tracks: Tracks) -> Cart {
let newPosition = position.move(direction)
var newDirection = direction
var newIntersectionTurning = intersectionTurning
switch tracks[newPosition] {
case .empty:
fatalError("A cart ended up on a piece of empty track.")
case .horizontal:
if direction.isVertical {
fatalError("A cart ended up going vertically on a horizontal track.")
}
case .vertical:
if direction.isHorizontal {
fatalError("A cart ended up going horizontally on a vertical track.")
}
case .turningLeftFromNorthOrSouth:
newDirection = direction.isVertical ? direction.turn(.left) : direction.turn(.right)
case .turningRightFromNorthOrSouth:
newDirection = direction.isVertical ? direction.turn(.right) : direction.turn(.left)
case .intersection:
newDirection = direction.turn(intersectionTurning)
switch intersectionTurning {
case .left:
newIntersectionTurning = .straight
case .straight:
newIntersectionTurning = .right
case .right:
newIntersectionTurning = .left
}
}
return Cart(
position: newPosition,
direction: newDirection,
intersectionTurning: newIntersectionTurning
)
}
}
func main() {
let tracksAndCarts = StdIn().enumerated().map { line in
line.element.enumerated().map { character in
parseTrack(position: Position(x: character.offset, y: line.offset), character: character.element)
}
}
let columns = tracksAndCarts.map { row in row.count }.max()!
let tracks = Tracks(tracksAndCarts.map { row in
pad(row.map { track, _ in track }, to: columns, with: .empty)
})
let initialCarts = tracksAndCarts.flatMap { row in row.compactMap { _, cart in cart } }
var carts = initialCarts
while carts.count > 1 {
carts.sort(by: comparing { cart in cart.position })
var i = 0
while carts.count > 1, i < carts.count {
carts[i] = carts[i].move(tracks: tracks)
var crash = false
for crashIndex in carts.startIndex ..< carts.endIndex {
if crashIndex >= carts.endIndex {
break
}
if crashIndex != i, carts[crashIndex].position == carts[i].position {
crash = true
carts.remove(at: crashIndex)
if crashIndex < i {
i -= 1
}
}
}
if crash {
carts.remove(at: i)
} else {
i += 1
}
}
}
carts[0] = carts[0].move(tracks: tracks)
print(carts[0].position)
}
func parseTrack(position: Position, character: Character) -> (TrackPiece, Cart?) {
switch character {
case " ":
return (.empty, nil)
case "-":
return (.horizontal, nil)
case "|":
return (.vertical, nil)
case "\\":
return (.turningLeftFromNorthOrSouth, nil)
case "/":
return (.turningRightFromNorthOrSouth, nil)
case "+":
return (.intersection, nil)
case "^":
return (.vertical, Cart(position: position, direction: .north, intersectionTurning: .left))
case "v":
return (.vertical, Cart(position: position, direction: .south, intersectionTurning: .left))
case "<":
return (.horizontal, Cart(position: position, direction: .west, intersectionTurning: .left))
case ">":
return (.horizontal, Cart(position: position, direction: .east, intersectionTurning: .left))
default:
preconditionFailure("\"\(character)\" is an invalid track piece.")
}
}
func pad<T>(_ array: [T], to size: Int, with value: T) -> [T] {
if array.count < size {
return array + Array(repeating: value, count: size - array.count)
}
return array
}
|
0bd194d572616017283392076aec436f
| 27.356863 | 109 | 0.545153 | false | false | false | false |
nathantannar4/InputBarAccessoryView
|
refs/heads/master
|
Example/Sources/InputBar Examples/InputBarStyle.swift
|
mit
|
1
|
//
// InputBarStyle.swift
// Example
//
// Created by Nathan Tannar on 8/18/17.
// Copyright © 2017-2020 Nathan Tannar. All rights reserved.
//
import Foundation
import InputBarAccessoryView
enum InputBarStyle: String, CaseIterable {
case imessage = "iMessage"
case slack = "Slack"
case githawk = "GitHawk"
case facebook = "Facebook"
case noTextView = "No InputTextView"
case `default` = "Default"
func generate() -> InputBarAccessoryView {
switch self {
case .imessage: return iMessageInputBar()
case .slack: return SlackInputBar()
case .githawk: return GitHawkInputBar()
case .facebook: return FacebookInputBar()
case .noTextView: return NoTextViewInputBar()
case .default: return InputBarAccessoryView()
}
}
}
|
8184c6705d88a812a1ea7d976918077d
| 25.612903 | 61 | 0.658182 | false | false | false | false |
DuCalixte/iTunesSearchPattern
|
refs/heads/develop
|
iTunesSearchPattern/SearchItunesController.swift
|
mit
|
1
|
//
// SearchItunesController.swift
// iTunesSearchPattern
//
// Created by STANLEY CALIXTE on 10/25/14.
// Copyright (c) 2014 STANLEY CALIXTE. All rights reserved.
//
import Foundation
import UIKit
class SearchItunesController: UIViewController, UITableViewDataSource, UITableViewDelegate, ITunesAPIControllerProtocol {
@IBOutlet weak var tableView: UITableView!
// @IBOutlet var tableView : UITableView?
@IBOutlet weak var searchField: UITextField!
let kCellIdentifier: String = "SearchResultCell"
var api : ITunesAPIController?
var imageCache = [String : UIImage]()
var albums = [Album]()
var entities = [Entity]()
var mediaOption: String = "music"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
api = ITunesAPIController(delegate: self)
self.tableView?.autoresizingMask = UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleTopMargin
// UIViewAutoresizingFlexibleTopMargin;
// UIViewAutoresizingFlexibleHeight;
self.tableView.delegate = self;
self.tableView.dataSource = self;
// self.tableView.delegate = self
self.tableView.showsVerticalScrollIndicator=true
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
api!.searchItunesFor("Beatles", mediaType: self.mediaOption)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count:Int = 0
switch self.mediaOption{
case "music":
count = self.albums.count
break;
default:
count = self.entities.count
}
return count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell: UITableViewCell = (tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as UITableViewCell?)!
switch self.mediaOption{
case "music":
self.setCellFromAlbum(tableView, displayCell: cell, forRowAtIndexPath: indexPath)
break;
default:
break;
}
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.layer.transform = CATransform3DMakeScale(0.1,0.1,1)
UIView.animateWithDuration(0.25, animations: {
cell.layer.transform = CATransform3DMakeScale(1,1,1)
})
}
func setCellFromAlbum(tableView: UITableView, displayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath){
let album = self.albums[indexPath.row]
cell.textLabel.text = album.title
cell.imageView.image = UIImage(named: "Blank52")
// Get the formatted price string for display in the subtitle
let formattedPrice = album.price
// Grab the artworkUrl60 key to get an image URL for the app's thumbnail
let urlString = album.thumbnailImageURL
// Check our image cache for the existing key. This is just a dictionary of UIImages
//var image: UIImage? = self.imageCache.valueForKey(urlString) as? UIImage
var image = self.imageCache[urlString]
if( image == nil ) {
// If the image does not exist, we need to download it
var imgURL: NSURL = NSURL(string: urlString)!
// Download an NSData representation of the image at the URL
let request: NSURLRequest = NSURLRequest(URL: imgURL)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if error == nil {
image = UIImage(data: data)
// Store the image in to our cache
self.imageCache[urlString] = image
dispatch_async(dispatch_get_main_queue(), {
if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
cellToUpdate.imageView.image = image
}
})
}
else {
println("Error: \(error.localizedDescription)")
}
})
}
else {
dispatch_async(dispatch_get_main_queue(), {
if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
cellToUpdate.imageView.image = image
}
})
}
cell.detailTextLabel?.text = formattedPrice
}
func didReceiveAPIResults(results: NSDictionary){
switch self.mediaOption{
case "music":
self.updateAlbumsContent(results)
break;
default:
break;
}
}
func updateAlbumsContent(results: NSDictionary){
var resultsArr: NSArray = results["results"] as NSArray
dispatch_async(dispatch_get_main_queue(), {
self.albums = Album.albumsWithJSON(resultsArr)
self.tableView!.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}
@IBAction func onOptionChange(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex
{
case 0:
mediaOption = "music"
break;
case 1:
mediaOption = "movie"
default:
mediaOption = "all"
}
}
@IBAction func onSearch(sender: UIButton) {
if self.searchField.text != ""{
api!.searchItunesFor(self.searchField.text, mediaType: self.mediaOption)
}
}
}
|
009d283e74e0c6f194cd611b2b6ab38b
| 34.827586 | 202 | 0.611004 | false | false | false | false |
cybertunnel/SplashBuddy
|
refs/heads/master
|
SplashBuddy/View/MainViewController_Actions.swift
|
apache-2.0
|
1
|
//
// MainViewController_Actions.swift
// SplashBuddy
//
// Created by Francois Levaux on 02.03.17.
// Copyright © 2017 François Levaux-Tiffreau. All rights reserved.
//
import Foundation
extension MainViewController {
func setupInstalling() {
indeterminateProgressIndicator.startAnimation(self)
indeterminateProgressIndicator.isHidden = false
installingLabel.stringValue = NSLocalizedString("Installing…", comment: "")
statusLabel.stringValue = ""
continueButton.isEnabled = false
}
func errorWhileInstalling() {
indeterminateProgressIndicator.isHidden = true
installingLabel.stringValue = ""
continueButton.isEnabled = true
statusLabel.textColor = .red
let _failedSoftwareArray = SoftwareArray.sharedInstance.failedSoftwareArray()
if _failedSoftwareArray.count == 1 {
if let failedDisplayName = _failedSoftwareArray[0].displayName {
statusLabel.stringValue = String.localizedStringWithFormat(NSLocalizedString(
"%@ failed to install. Support has been notified.",
comment: "A specific application failed to install"), failedDisplayName)
} else {
statusLabel.stringValue = NSLocalizedString(
"An application failed to install. Support has been notified.",
comment: "One (unnamed) application failed to install")
}
} else {
statusLabel.stringValue = NSLocalizedString(
"Some applications failed to install. Support has been notified.",
comment: "More than one application failed to install")
}
}
func canContinue() {
continueButton.isEnabled = true
}
func doneInstalling() {
indeterminateProgressIndicator.isHidden = true
installingLabel.stringValue = ""
statusLabel.textColor = .labelColor
statusLabel.stringValue = NSLocalizedString(
"All applications were installed. Please click continue.",
comment: "All applications were installed. Please click continue.")
}
}
|
294a56073718ae62cd69230721ab3ca1
| 29.402597 | 93 | 0.605297 | false | false | false | false |
zmeyc/SQLite.swift
|
refs/heads/master
|
Sources/SQLite/Extensions/FTS4.swift
|
mit
|
1
|
//
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
extension Module {
@warn_unused_result public static func FTS4(_ column: Expressible, _ more: Expressible...) -> Module {
return FTS4([column] + more)
}
@warn_unused_result public static func FTS4(_ columns: [Expressible] = [], tokenize tokenizer: Tokenizer? = nil) -> Module {
var columns = columns
if let tokenizer = tokenizer {
columns.append("=".join([Expression<Void>(literal: "tokenize"), Expression<Void>(literal: tokenizer.description)]))
}
return Module(name: "fts4", arguments: columns)
}
}
extension VirtualTable {
/// Builds an expression appended with a `MATCH` query against the given
/// pattern.
///
/// let emails = VirtualTable("emails")
///
/// emails.filter(emails.match("Hello"))
/// // SELECT * FROM "emails" WHERE "emails" MATCH 'Hello'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: An expression appended with a `MATCH` query against the given
/// pattern.
@warn_unused_result public func match(_ pattern: String) -> Expression<Bool> {
return "MATCH".infix(tableName(), pattern)
}
@warn_unused_result public func match(_ pattern: Expression<String>) -> Expression<Bool> {
return "MATCH".infix(tableName(), pattern)
}
@warn_unused_result public func match(_ pattern: Expression<String?>) -> Expression<Bool?> {
return "MATCH".infix(tableName(), pattern)
}
/// Builds a copy of the query with a `WHERE … MATCH` clause.
///
/// let emails = VirtualTable("emails")
///
/// emails.match("Hello")
/// // SELECT * FROM "emails" WHERE "emails" MATCH 'Hello'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A query with the given `WHERE … MATCH` clause applied.
@warn_unused_result public func match(_ pattern: String) -> QueryType {
return filter(match(pattern))
}
@warn_unused_result public func match(_ pattern: Expression<String>) -> QueryType {
return filter(match(pattern))
}
@warn_unused_result public func match(_ pattern: Expression<String?>) -> QueryType {
return filter(match(pattern))
}
}
public struct Tokenizer {
public static let Simple = Tokenizer("simple")
public static let Porter = Tokenizer("porter")
@warn_unused_result public static func Unicode61(removeDiacritics: Bool? = nil, tokenchars: Set<Character> = [], separators: Set<Character> = []) -> Tokenizer {
var arguments = [String]()
if let removeDiacritics = removeDiacritics {
arguments.append("removeDiacritics=\(removeDiacritics ? 1 : 0)".quote())
}
if !tokenchars.isEmpty {
let joined = tokenchars.map { String($0) }.joined(separator: "")
arguments.append("tokenchars=\(joined)".quote())
}
if !separators.isEmpty {
let joined = separators.map { String($0) }.joined(separator: "")
arguments.append("separators=\(joined)".quote())
}
return Tokenizer("unicode61", arguments)
}
@warn_unused_result public static func Custom(_ name: String) -> Tokenizer {
return Tokenizer(Tokenizer.moduleName.quote(), [name.quote()])
}
public let name: String
public let arguments: [String]
private init(_ name: String, _ arguments: [String] = []) {
self.name = name
self.arguments = arguments
}
private static let moduleName = "SQLite.swift"
}
extension Tokenizer : CustomStringConvertible {
public var description: String {
return ([name] + arguments).joined(separator: " ")
}
}
extension Connection {
public func registerTokenizer(_ submoduleName: String, next: (String) -> (String, Range<String.Index>)?) throws {
fatalError("Not implemented") // FIXME
// try check(_SQLiteRegisterTokenizer(handle, Tokenizer.moduleName, submoduleName) { input, offset, length in
// let string = String.fromCString(input)!
//
// guard let (token, range) = next(string) else { return nil }
//
// let view = string.utf8
// offset.memory += string.substringToIndex(range.startIndex).utf8.count
// length.memory = Int32(range.startIndex.samePositionIn(view).distanceTo(range.endIndex.samePositionIn(view)))
// return token
// })
}
}
|
4dfed63719a84493571404c0157b5b46
| 34.289308 | 164 | 0.650864 | false | false | false | false |
nyin005/Forecast-App
|
refs/heads/master
|
Forecast/Forecast/AppDelegate.swift
|
gpl-3.0
|
1
|
//
// AppDelegate.swift
// Forecast
//
// Created by appledev110 on 11/11/16.
// Copyright © 2016 appledev110. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var tabVC : TabViewController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.backgroundColor = UIColor.white
// let vc = UIViewController()
// vc.view.backgroundColor = UIColor.white
// self.window?.rootViewController = vc
self.window?.makeKeyAndVisible()
// vc.removeFromParentViewController()
tabVC = TabViewController()
self.window?.rootViewController = tabVC
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
f4bf4b3e077692a1413ea2a753b68d8d
| 46.8 | 285 | 0.736782 | false | false | false | false |
SwiftOnEdge/Reactive
|
refs/heads/master
|
Sources/StreamKit/Signal.swift
|
mit
|
1
|
//
// Signal.swift
// Edge
//
// Created by Tyler Fleming Cloutier on 5/29/16.
//
//
import Foundation
public final class Signal<Value>: SignalType, InternalSignalType, SpecialSignalGenerator {
internal var observers = Bag<Observer<Value>>()
private var handlerDisposable: Disposable?
public var cancelDisposable: Disposable?
public var signal: Signal<Value> {
return self
}
/// Initializes a Signal that will immediately invoke the given generator,
/// then forward events sent to the given observer.
///
/// The disposable returned from the closure will be automatically disposed
/// if a terminating event is sent to the observer. The Signal itself will
/// remain alive until the observer is released. This is because the observer
/// captures a self reference.
public init(_ startHandler: @escaping (Observer<Value>) -> Disposable?) {
let observer = Observer(with: CircuitBreaker(holding: self))
let handlerDisposable = startHandler(observer)
// The cancel disposable should send interrupted and then dispose of the
// disposable produced by the startHandler.
cancelDisposable = ActionDisposable {
observer.sendInterrupted()
handlerDisposable?.dispose()
}
}
deinit {
cancelDisposable?.dispose()
}
/// Creates a Signal that will be controlled by sending events to the returned
/// observer.
///
/// The Signal will remain alive until a terminating event is sent to the
/// observer.
public static func pipe() -> (Signal, Observer<Value>) {
var observer: Observer<Value>!
let signal = self.init { innerObserver in
observer = innerObserver
return nil
}
return (signal, observer)
}
}
extension Signal: CustomDebugStringConvertible {
public var debugDescription: String {
let obs = Array(self.observers.map { String(describing: $0) })
return "Signal[\(obs.joined(separator: ", "))]"
}
}
public protocol SpecialSignalGenerator {
/// The type of values being sent on the signal.
associatedtype Value
init(_ generator: @escaping (Observer<Value>) -> Disposable?)
}
public extension SpecialSignalGenerator {
/// Creates a Signal that will immediately send one value
/// then complete.
public init(value: Value) {
self.init { observer in
observer.sendNext(value)
observer.sendCompleted()
return nil
}
}
/// Creates a Signal that will immediately fail with the
/// given error.
public init(error: Error) {
self.init { observer in
observer.sendFailed(error)
return nil
}
}
/// Creates a Signal that will immediately send the values
/// from the given sequence, then complete.
public init<S: Sequence>(values: S) where S.Iterator.Element == Value {
self.init { observer in
var disposed = false
for value in values {
observer.sendNext(value)
if disposed {
break
}
}
observer.sendCompleted()
return ActionDisposable {
disposed = true
}
}
}
/// Creates a Signal that will immediately send the values
/// from the given sequence, then complete.
public init(values: Value...) {
self.init(values: values)
}
/// A Signal that will immediately complete without sending
/// any values.
public static var empty: Self {
return self.init { observer in
observer.sendCompleted()
return nil
}
}
/// A Signal that never sends any events to its observers.
public static var never: Self {
return self.init { _ in return nil }
}
}
/// An internal protocol for adding methods that require access to the observers
/// of the signal.
internal protocol InternalSignalType: SignalType {
var observers: Bag<Observer<Value>> { get }
}
/// Note that this type is not parameterized by an Error type which is in line
/// with the Swift error handling model.
/// A good reference for a discussion of the pros and cons is here:
/// https://github.com/ReactiveX/RxSwift/issues/650
public protocol SignalType {
/// The type of values being sent on the signal.
associatedtype Value
/// The exposed raw signal that underlies the `SignalType`.
var signal: Signal<Value> { get }
var cancelDisposable: Disposable? { get }
}
public extension SignalType {
/// Adds an observer to the `Signal` which observes any future events from the `Signal`.
/// If the `Signal` has already terminated, the observer will immediately receive an
/// `Interrupted` event.
///
/// Returns a Disposable which can be used to disconnect the observer. Disposing
/// of the Disposable will have no effect on the `Signal` itself.
@discardableResult
public func add(observer: Observer<Value>) -> Disposable? {
let token = signal.observers.insert(observer)
return ActionDisposable {
self.signal.observers.remove(using: token)
}
}
/// Convenience override for add(observer:) to allow trailing-closure style
/// invocations.
@discardableResult
public func on(action: @escaping Observer<Value>.Action) -> Disposable? {
return self.add(observer: Observer(action))
}
/// Observes the Signal by invoking the given callback when `next` events are
/// received.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callbacks. Disposing of the Disposable will have no effect on the Signal
/// itself.
@discardableResult
public func onNext(next: @escaping (Value) -> Void) -> Disposable? {
return self.add(observer: Observer(next: next))
}
/// Observes the Signal by invoking the given callback when a `completed` event is
/// received.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callback. Disposing of the Disposable will have no effect on the Signal
/// itself.
@discardableResult
public func onCompleted(completed: @escaping () -> Void) -> Disposable? {
return self.add(observer: Observer(completed: completed))
}
/// Observes the Signal by invoking the given callback when a `failed` event is
/// received.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callback. Disposing of the Disposable will have no effect on the Signal
/// itself.
@discardableResult
public func onFailed(error: @escaping (Error) -> Void) -> Disposable? {
return self.add(observer: Observer(failed: error))
}
/// Observes the Signal by invoking the given callback when an `interrupted` event is
/// received. If the Signal has already terminated, the callback will be invoked
/// immediately.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callback. Disposing of the Disposable will have no effect on the Signal
/// itself.
@discardableResult
public func onInterrupted(interrupted: @escaping () -> Void) -> Disposable? {
return self.add(observer: Observer(interrupted: interrupted))
}
}
public extension SignalType {
public var identity: Signal<Value> {
return self.map { $0 }
}
/// Maps each value in the signal to a new value.
public func map<U>(_ transform: @escaping (Value) -> U) -> Signal<U> {
return Signal { observer in
return self.on { event -> Void in
observer.send(event.map(transform))
}
}
}
/// Maps errors in the signal to a new error.
public func mapError<F: Error>(_ transform: @escaping (Error) -> F) -> Signal<Value> {
return Signal { observer in
return self.on { event -> Void in
observer.send(event.mapError(transform))
}
}
}
/// Preserves only the values of the signal that pass the given predicate.
public func filter(_ predicate: @escaping (Value) -> Bool) -> Signal<Value> {
return Signal { observer in
return self.on { (event: Event<Value>) -> Void in
guard let value = event.value else {
observer.send(event)
return
}
if predicate(value) {
observer.sendNext(value)
}
}
}
}
/// Splits the signal into two signals. The first signal in the tuple matches the
/// predicate, the second signal does not match the predicate
public func partition(_ predicate: @escaping (Value) -> Bool) -> (Signal<Value>, Signal<Value>) {
let (left, leftObserver) = Signal<Value>.pipe()
let (right, rightObserver) = Signal<Value>.pipe()
self.on { (event: Event<Value>) -> Void in
guard let value = event.value else {
leftObserver.send(event)
rightObserver.send(event)
return
}
if predicate(value) {
leftObserver.sendNext(value)
} else {
rightObserver.sendNext(value)
}
}
return (left, right)
}
/// Aggregate values into a single combined value. Mirrors the Swift Collection
public func reduce<T>(initial: T, _ combine: @escaping (T, Value) -> T) -> Signal<T> {
return Signal { observer in
var accumulator = initial
return self.on { event in
observer.send(event.map { value in
accumulator = combine(accumulator, value)
return accumulator
})
}
}
}
public func flatMap<U>(_ transform: @escaping (Value) -> U?) -> Signal<U> {
return Signal { observer in
return self.on { event -> Void in
if let e = event.flatMap(transform) {
observer.send(e)
}
}
}
}
public func flatMap<U>(_ transform: @escaping (Value) -> Signal<U>) -> Signal<U> {
return map(transform).joined()
}
}
extension SignalType where Value: SignalType {
/// Listens to every `Source` produced from the current `Signal`
/// Starts each `Source` and forwards on all values and errors onto
/// the `Signal` which is returned. In this way it joins each of the
/// `Source`s into a single `Signal`.
///
/// The joined `Signal` completes when the current `Signal` and all of
/// its produced `Source`s complete.
///
/// Note: This means that each `Source` will be started as it is received.
public func joined() -> Signal<Value.Value> {
// Start the number in flight at 1 for `self`
return Signal { observer in
var numberInFlight = 1
var disposables = [Disposable]()
func decrementInFlight() {
numberInFlight -= 1
if numberInFlight == 0 {
observer.sendCompleted()
}
}
func incrementInFlight() {
numberInFlight += 1
}
self.on { event in
switch event {
case .next(let source):
incrementInFlight()
source.on { event in
switch event {
case .completed, .interrupted:
decrementInFlight()
case .next, .failed:
observer.send(event)
}
}
source.cancelDisposable.map { disposables.append($0) }
(source as? Source<Value.Value>)?.start()
case .failed(let error):
observer.sendFailed(error)
case .completed:
decrementInFlight()
case .interrupted:
observer.sendInterrupted()
}
}
return ActionDisposable {
for disposable in disposables {
disposable.dispose()
}
}
}
}
}
|
2e326fe4223acee26bc220cc5912d5e1
| 31.194937 | 101 | 0.578674 | false | false | false | false |
srn214/Floral
|
refs/heads/master
|
Floral/Pods/RxSwiftExt/Source/RxSwift/ObservableType+Weak.swift
|
mit
|
1
|
//
// ObservableType+Weak.swift
// RxSwiftExt
//
// Created by Ian Keen on 17/04/2016.
// Copyright © 2016 RxSwift Community. All rights reserved.
//
import Foundation
import RxSwift
extension ObservableType {
/**
Leverages instance method currying to provide a weak wrapper around an instance function
- parameter obj: The object that owns the function
- parameter method: The instance function represented as `InstanceType.instanceFunc`
*/
fileprivate func weakify<A: AnyObject, B>(_ obj: A, method: ((A) -> (B) -> Void)?) -> ((B) -> Void) {
return { [weak obj] value in
guard let obj = obj else { return }
method?(obj)(value)
}
}
fileprivate func weakify<A: AnyObject>(_ obj: A, method: ((A) -> () -> Void)?) -> (() -> Void) {
return { [weak obj] in
guard let obj = obj else { return }
method?(obj)()
}
}
/**
Subscribes an event handler to an observable sequence.
- parameter weak: Weakly referenced object containing the target function.
- parameter on: Function to invoke on `weak` for each event in the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe<A: AnyObject>(weak obj: A, _ on: @escaping (A) -> (Event<Element>) -> Void) -> Disposable {
return self.subscribe(weakify(obj, method: on))
}
/**
Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence.
- parameter weak: Weakly referenced object containing the target function.
- parameter onNext: Function to invoke on `weak` for each element in the observable sequence.
- parameter onError: Function to invoke on `weak` upon errored termination of the observable sequence.
- parameter onCompleted: Function to invoke on `weak` upon graceful termination of the observable sequence.
- parameter onDisposed: Function to invoke on `weak` upon any type of termination of sequence (if the sequence has
gracefully completed, errored, or if the generation is cancelled by disposing subscription)
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe<A: AnyObject>(
weak obj: A,
onNext: ((A) -> (Element) -> Void)? = nil,
onError: ((A) -> (Error) -> Void)? = nil,
onCompleted: ((A) -> () -> Void)? = nil,
onDisposed: ((A) -> () -> Void)? = nil)
-> Disposable {
let disposable: Disposable
if let disposed = onDisposed {
disposable = Disposables.create(with: weakify(obj, method: disposed))
} else {
disposable = Disposables.create()
}
let observer = AnyObserver { [weak obj] (e: Event<Element>) in
guard let obj = obj else { return }
switch e {
case .next(let value):
onNext?(obj)(value)
case .error(let e):
onError?(obj)(e)
disposable.dispose()
case .completed:
onCompleted?(obj)()
disposable.dispose()
}
}
return Disposables.create(self.asObservable().subscribe(observer), disposable)
}
/**
Subscribes an element handler to an observable sequence.
- parameter weak: Weakly referenced object containing the target function.
- parameter onNext: Function to invoke on `weak` for each element in the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribeNext<A: AnyObject>(weak obj: A, _ onNext: @escaping (A) -> (Element) -> Void) -> Disposable {
return self.subscribe(onNext: weakify(obj, method: onNext))
}
/**
Subscribes an error handler to an observable sequence.
- parameter weak: Weakly referenced object containing the target function.
- parameter onError: Function to invoke on `weak` upon errored termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribeError<A: AnyObject>(weak obj: A, _ onError: @escaping (A) -> (Error) -> Void) -> Disposable {
return self.subscribe(onError: weakify(obj, method: onError))
}
/**
Subscribes a completion handler to an observable sequence.
- parameter weak: Weakly referenced object containing the target function.
- parameter onCompleted: Function to invoke on `weak` graceful termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribeCompleted<A: AnyObject>(weak obj: A, _ onCompleted: @escaping (A) -> () -> Void) -> Disposable {
return self.subscribe(onCompleted: weakify(obj, method: onCompleted))
}
}
|
c9e9f0cb0f8c24c4559bfce69faef042
| 38.235294 | 118 | 0.689869 | false | false | false | false |
material-components/material-components-ios
|
refs/heads/develop
|
components/Ripple/examples/CardCellsWithRippleExample.swift
|
apache-2.0
|
2
|
// Copyright 2019-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 UIKit
import MaterialComponents.MaterialCards_Theming
import MaterialComponents.MaterialColorScheme
import MaterialComponents.MaterialContainerScheme
import MaterialComponents.MaterialTypographyScheme
class CardCellsWithRippleExample: UIViewController,
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout
{
enum ToggleMode: Int {
case edit = 1
case reorder
}
let collectionView = UICollectionView(
frame: .zero,
collectionViewLayout: UICollectionViewFlowLayout())
var toggle = ToggleMode.edit
@objc var containerScheme: MDCContainerScheming
@objc var colorScheme: MDCColorScheming {
return containerScheme.colorScheme
}
@objc var typographyScheme: MDCTypographyScheming {
return containerScheme.typographyScheme
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
containerScheme = MDCContainerScheme()
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.frame = view.bounds
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = colorScheme.backgroundColor
collectionView.alwaysBounceVertical = true
collectionView.register(MDCCardCollectionCell.self, forCellWithReuseIdentifier: "Cell")
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.allowsMultipleSelection = true
view.addSubview(collectionView)
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Reorder",
style: .plain,
target: self,
action: #selector(toggleModes))
let longPressGesture = UILongPressGestureRecognizer(
target: self,
action: #selector(reorderCards(gesture:)))
longPressGesture.cancelsTouchesInView = false
collectionView.addGestureRecognizer(longPressGesture)
let guide = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
collectionView.leftAnchor.constraint(equalTo: guide.leftAnchor),
collectionView.rightAnchor.constraint(equalTo: guide.rightAnchor),
collectionView.topAnchor.constraint(equalTo: view.topAnchor),
collectionView.bottomAnchor.constraint(equalTo: guide.bottomAnchor),
])
collectionView.contentInsetAdjustmentBehavior = .always
self.updateTitle()
}
func preiOS11Constraints() {
self.view.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "H:|[view]|",
options: [],
metrics: nil,
views: ["view": collectionView]))
self.view.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|[view]|",
options: [],
metrics: nil,
views: ["view": collectionView]))
}
func updateTitle() {
switch toggle {
case .edit:
navigationItem.rightBarButtonItem?.title = "Reorder"
self.title = "Cards (Edit)"
case .reorder:
navigationItem.rightBarButtonItem?.title = "Edit"
self.title = "Cards (Reorder)"
}
}
@objc func toggleModes() {
switch toggle {
case .edit:
toggle = .reorder
case .reorder:
toggle = .edit
}
self.updateTitle()
collectionView.reloadData()
}
func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
guard let cardCell = cell as? MDCCardCollectionCell else { return cell }
cardCell.enableRippleBehavior = true
cardCell.applyTheme(withScheme: containerScheme)
cardCell.isSelectable = (toggle == .edit)
cardCell.isAccessibilityElement = true
cardCell.accessibilityLabel = title
return cardCell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard toggle == .edit else { return }
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
guard toggle == .edit else { return }
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(
_ collectionView: UICollectionView,
numberOfItemsInSection section: Int
) -> Int {
return 30
}
func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath
) -> CGSize {
let cardSize = (collectionView.bounds.size.width / 3) - 12
return CGSize(width: cardSize, height: cardSize)
}
func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int
) -> UIEdgeInsets {
return UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
}
func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int
) -> CGFloat {
return 8
}
func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int
) -> CGFloat {
return 8
}
func collectionView(
_ collectionView: UICollectionView,
canMoveItemAt indexPath: IndexPath
) -> Bool {
return toggle == .reorder
}
func collectionView(
_ collectionView: UICollectionView,
moveItemAt sourceIndexPath: IndexPath,
to destinationIndexPath: IndexPath
) {
}
@objc func reorderCards(gesture: UILongPressGestureRecognizer) {
switch gesture.state {
case .began:
guard
let selectedIndexPath = collectionView.indexPathForItem(
at:
gesture.location(in: collectionView))
else { break }
let cell = collectionView.cellForItem(at: selectedIndexPath)
guard let cardCell = cell as? MDCCardCollectionCell else { break }
collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
if toggle == .reorder {
cardCell.isDragged = true
}
case .changed:
guard let gestureView = gesture.view else { break }
collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gestureView))
case .ended:
collectionView.endInteractiveMovement()
default:
collectionView.cancelInteractiveMovement()
}
}
}
extension CardCellsWithRippleExample {
@objc class func catalogMetadata() -> [String: Any] {
return [
"breadcrumbs": ["Ripple", "Card Cell with Ripple"],
"primaryDemo": false,
"presentable": true,
]
}
}
|
2f4da3b692f4437709f41a2d5314e750
| 29.08871 | 99 | 0.722058 | false | false | false | false |
CodePath2017Group4/travel-app
|
refs/heads/master
|
RoadTripPlanner/DetailView.swift
|
mit
|
1
|
//
// DetailView.swift
// RoadTripPlanner
//
// Created by Deepthy on 10/26/17.
// Copyright © 2017 Deepthy. All rights reserved.
//
import UIKit
@IBDesignable class DetailView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setup()
}
var transitionProgress: CGFloat = 0 {
didSet {
updateViews()
}
}
let imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
return imageView
}()
let overlayView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(red: 0.655, green: 0.737, blue: 0.835, alpha: 0.8)
return view
}()
let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 20)
label.textColor = UIColor.white
label.textAlignment = .center
return label
}()
let subtitleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 17)
label.textColor = UIColor.white
label.textAlignment = .center
label.numberOfLines = 0
return label
}()
func updateViews() {
let progress = min(max(transitionProgress, 0), 1)
let antiProgress = 1.0 - progress
let titleLabelOffsetTop: CGFloat = 20.0
let titleLabelOffsetMiddle: CGFloat = bounds.height/2 - 44
let titleLabelOffset = transitionProgress * titleLabelOffsetMiddle + antiProgress * titleLabelOffsetTop
let subtitleLabelOffsetTop: CGFloat = 64
let subtitleLabelOffsetMiddle: CGFloat = bounds.height/2
let subtitleLabelOffset = transitionProgress * subtitleLabelOffsetMiddle + antiProgress * subtitleLabelOffsetTop
titleLabel.frame = CGRect(x: 0, y: titleLabelOffset, width: bounds.width, height: 44)
subtitleLabel.preferredMaxLayoutWidth = bounds.width
subtitleLabel.frame = CGRect(x: 0, y: subtitleLabelOffset, width: bounds.width, height: subtitleLabel.font.lineHeight)
imageView.alpha = progress
}
func setup() {
addSubview(imageView)
addSubview(overlayView)
addSubview(titleLabel)
addSubview(subtitleLabel)
clipsToBounds = true
titleLabel.text = "Title of Business"
//subtitleLabel.text = "Description of Business"
imageView.image = UIImage(named: "sf")
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = bounds
overlayView.frame = bounds
updateViews()
}
}
|
4b0acb2a424282c0e80e06d1ef31d09d
| 27.065421 | 126 | 0.612388 | false | false | false | false |
ibm-bluemix-mobile-services/bms-clientsdk-swift-security
|
refs/heads/master
|
Sample/BMSSecuritySample/BMSSecuritySample/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// GoogleMCA
//
// Created by Ilan Klein on 15/02/2016.
// Copyright © 2016 ibm. All rights reserved.
//
import UIKit
import BMSCore
import BMSSecurity
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBOutlet weak var answerTextView: UILabel!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func logout(sender: AnyObject) {
MCAAuthorizationManager.sharedInstance.logout(nil)
}
@IBAction func login(sender: AnyObject) {
let callBack:BmsCompletionHandler = {(response: Response?, error: NSError?) in
var ans:String = "";
if error == nil {
ans="response:\(response?.responseText), no error"
} else {
ans="ERROR , error=\(error)"
}
dispatch_async(dispatch_get_main_queue(), {
self.answerTextView.text = ans
})
}
let request = Request(url: AppDelegate.customResourceURL, method: HttpMethod.GET)
request.sendWithCompletionHandler(callBack)
}
}
|
a881c59fb900d1da139f8494c9ddefda
| 27.869565 | 89 | 0.615211 | false | false | false | false |
sora0077/iTunesMusic
|
refs/heads/master
|
Demo/Views/HistoryViewController.swift
|
mit
|
1
|
//
// HistoryViewController.swift
// iTunesMusic
//
// Created by 林達也 on 2016/10/18.
// Copyright © 2016年 jp.sora0077. All rights reserved.
//
import UIKit
import SnapKit
import RxSwift
import RxCocoa
import iTunesMusic
private class TableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
final class HistoryViewController: UIViewController {
fileprivate let tableView = UITableView()
fileprivate let history = Model.History.shared
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell")
tableView.delegate = self
tableView.dataSource = self
tableView.snp.makeConstraints { make in
make.edges.equalTo(0)
}
history.changes
.subscribe(tableView.rx.itemUpdates())
.addDisposableTo(disposeBag)
}
}
extension HistoryViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return history.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let (track, played) = history[indexPath.row]
cell.textLabel?.text = track.name
cell.detailTextLabel?.text = "\(played)"
return cell
}
}
extension HistoryViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let (track, _) = history[indexPath.row]
guard track.canPreview else { return }
UIApplication.shared.open(appURL(path: "/track/\(track.id)"))
}
}
|
f41a7750a80cb9915f502b97c390f70a
| 27.857143 | 100 | 0.687129 | false | false | false | false |
roecrew/AudioKit
|
refs/heads/master
|
AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Drum Synthesizers.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: ## Drum Synthesizers
//: These can also be hooked up to MIDI or a sequencer.
import XCPlayground
import AudioKit
//: Set up instruments:
var kick = AKSynthKick()
var snare = AKSynthSnare(duration: 0.07)
var mix = AKMixer(kick, snare)
var reverb = AKReverb(mix)
AudioKit.output = reverb
AudioKit.start()
reverb.loadFactoryPreset(.MediumRoom)
//: Generate a cheap electro beat
var counter = 0
AKPlaygroundLoop(frequency: 4.44) {
let onFirstBeat = counter == 0
let everyOtherBeat = counter % 4 == 2
let randomHit = (0...3).randomElement() == 0
if onFirstBeat || randomHit {
kick.play(noteNumber:60, velocity: 100)
kick.stop(noteNumber:60)
}
if everyOtherBeat {
let velocity = (1...100).randomElement()
snare.play(noteNumber:60, velocity: velocity)
snare.stop(noteNumber:60)
}
counter += 1
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
|
b550e93183f6d09169cb66305bb5a76b
| 23.552632 | 60 | 0.684887 | false | false | false | false |
PJayRushton/TeacherTools
|
refs/heads/master
|
Pods/Marshal/Sources/ValueType.swift
|
mit
|
2
|
//
// M A R S H A L
//
// ()
// /\
// ()--' '--()
// `. .'
// / .. \
// ()' '()
//
//
import Foundation
// MARK: - ValueType
public protocol ValueType {
associatedtype Value = Self
static func value(from object: Any) throws -> Value
}
extension ValueType {
public static func value(from object: Any) throws -> Value {
guard let objectValue = object as? Value else {
throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object))
}
return objectValue
}
}
// MARK: - ValueType Implementations
extension String: ValueType {}
extension Int: ValueType {}
extension UInt: ValueType {}
extension Bool: ValueType {}
extension Float: ValueType {
public static func value(from object: Any) throws -> Float {
guard let value = object as? NSNumber else {
throw MarshalError.typeMismatch(expected: NSNumber.self, actual: type(of: object))
}
return value.floatValue
}
}
extension Double: ValueType {
public static func value(from object: Any) throws -> Double {
guard let value = object as? NSNumber else {
throw MarshalError.typeMismatch(expected: NSNumber.self, actual: type(of: object))
}
return value.doubleValue
}
}
extension Int64: ValueType {
public static func value(from object: Any) throws -> Int64 {
guard let value = object as? NSNumber else {
throw MarshalError.typeMismatch(expected: NSNumber.self, actual: type(of: object)) }
return value.int64Value
}
}
extension Array where Element: ValueType {
public static func value(from object: Any, discardingErrors: Bool = false) throws -> [Element] {
guard let anyArray = object as? [Any] else {
throw MarshalError.typeMismatch(expected: self, actual: type(of: object))
}
if discardingErrors {
return anyArray.compactMap {
let value = try? Element.value(from: $0)
guard let element = value as? Element else {
return nil
}
return element
}
}
else {
return try anyArray.map {
let value = try Element.value(from: $0)
guard let element = value as? Element else {
throw MarshalError.typeMismatch(expected: Element.self, actual: type(of: value))
}
return element
}
}
}
public static func value(from object: Any) throws -> [Element?] {
guard let anyArray = object as? [Any] else {
throw MarshalError.typeMismatch(expected: self, actual: type(of: object))
}
return anyArray.map {
let value = try? Element.value(from: $0)
guard let element = value as? Element else {
return nil
}
return element
}
}
}
extension Dictionary where Value: ValueType {
public static func value(from object: Any) throws -> Dictionary<Key, Value> {
guard let objectValue = object as? [Key: Any] else {
throw MarshalError.typeMismatch(expected: self, actual: type(of: object))
}
var result: [Key: Value] = [:]
for (k, v) in objectValue {
guard let value = try Value.value(from: v) as? Value else {
throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: any))
}
result[k] = value
}
return result
}
}
extension Set where Element: ValueType {
public static func value(from object: Any) throws -> Set<Element> {
let elementArray: [Element] = try [Element].value(from: object)
return Set<Element>(elementArray)
}
}
extension URL: ValueType {
public static func value(from object: Any) throws -> URL {
guard let urlString = object as? String else {
throw MarshalError.typeMismatch(expected: String.self, actual: type(of: object))
}
guard let objectValue = URL(string: urlString) else {
throw MarshalError.typeMismatch(expected: "valid URL", actual: urlString)
}
return objectValue
}
}
extension Int8: ValueType {
public static func value(from object: Any) throws -> Int8 {
guard let value = object as? Int else {
throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object))
}
return Int8(value)
}
}
extension Int16: ValueType {
public static func value(from object: Any) throws -> Int16 {
guard let value = object as? Int else {
throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object))
}
return Int16(value)
}
}
extension Int32: ValueType {
public static func value(from object: Any) throws -> Int32 {
guard let value = object as? Int else {
throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object))
}
return Int32(value)
}
}
extension UInt8: ValueType {
public static func value(from object: Any) throws -> UInt8 {
guard let value = object as? UInt else {
throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object))
}
return UInt8(value)
}
}
extension UInt16: ValueType {
public static func value(from object: Any) throws -> UInt16 {
guard let value = object as? UInt else {
throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object))
}
return UInt16(value)
}
}
extension UInt32: ValueType {
public static func value(from object: Any) throws -> UInt32 {
guard let value = object as? UInt else {
throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object))
}
return UInt32(value)
}
}
extension UInt64: ValueType {
public static func value(from object: Any) throws -> UInt64 {
guard let value = object as? NSNumber else {
throw MarshalError.typeMismatch(expected: NSNumber.self, actual: type(of: object))
}
return value.uint64Value
}
}
extension Character: ValueType {
public static func value(from object: Any) throws -> Character {
guard let value = object as? String else {
throw MarshalError.typeMismatch(expected: Value.self, actual: type(of: object))
}
return Character(value)
}
}
#if swift(>=4.1)
#else
extension Collection {
func compactMap<ElementOfResult>(
_ transform: (Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {
return try flatMap(transform)
}
}
#endif
|
c4a1a3a33b2b033934ff761b3b8a6441
| 30.136986 | 100 | 0.601261 | false | false | false | false |
mkihmouda/LoadMore
|
refs/heads/master
|
BulkRequest/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// BulkRequestAPI
//
// Created by Mac on 3/2/17.
// Copyright © 2017 Mac. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,UIScrollViewDelegate {
@IBOutlet var tableView: UITableView!
var lastId = 0
var reachEnd = false
var intArray = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
callMessageAPI()
defineCollectionAndTableViewCells()
self.tableView.dataSource = self
self.tableView.delegate = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return intArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell", for: indexPath) as! MessageCell
cell.textLabel?.text = "\(intArray[indexPath.row])"
if indexPath.row == lastId - 3 {
callMessageAPI()
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100.0
}
func callMessageAPI(){
if !reachEnd {
let messageAPI = callAPI()
messageAPI.callMessageAPI(completed: {
print(self.intArray.count)
self.lastId = self.intArray.count
self.tableView.reloadData()
}, delegate : self)
}
}
// MARK: register nib cell
func defineCollectionAndTableViewCells(){
let userDetailsNIB = UINib(nibName: "MessageCell", bundle: nil)
tableView.register(userDetailsNIB, forCellReuseIdentifier: "messageCell")
}
}
|
74816cca25028832a7834a99572304b6
| 22.1 | 111 | 0.551227 | false | false | false | false |
naveenrana1309/NRControls
|
refs/heads/master
|
NRControls/Classes/NRControls.swift
|
mit
|
1
|
//
// NRControls.swift
//
//
// Created by Naveen Rana on 21/08/16.
// Developed by Naveen Rana. All rights reserved.
//
import Foundation
import MessageUI
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
/// This completionhandler use for call back image picker controller delegates.
public typealias ImagePickerControllerCompletionHandler = (_ controller: UIImagePickerController, _ info: [UIImagePickerController.InfoKey: Any]) -> Void
/// This completionhandler use for call back mail controller delegates.
public typealias MailComposerCompletionHandler = (_ result:MFMailComposeResult ,_ error: NSError?) -> Void
/// This completionhandler use for call back alert(Alert) controller delegates.
public typealias AlertControllerCompletionHandler = (_ alertController: UIAlertController, _ index: Int) -> Void
/// This completionhandler use for call back alert(ActionSheet) controller delegates.
public typealias AlertTextFieldControllerCompletionHandler = (_ alertController: UIAlertController, _ index: Int, _ text: String) -> Void
/// This completionhandler use for call back of selected image using image picker controller delegates.
public typealias CompletionImagePickerController = (_ selectedImage: UIImage?) -> Void
/// This completionhandler use for call back of selected url using DocumentPicker controller delegates.
public typealias DocumentPickerCompletionHandler = (_ selectedDocuments: [URL]?) -> Void
/// This class is used for using a common controls like alert, action sheet and imagepicker controller with proper completion Handlers.
open class NRControls: NSObject,UIImagePickerControllerDelegate,MFMailComposeViewControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate{
/// This completionhandler use for call back image picker controller delegates.
var imagePickerControllerHandler: ImagePickerControllerCompletionHandler?
/// This completionhandler use for call back mail controller delegates.
var mailComposerCompletionHandler: MailComposerCompletionHandler?
/// This completionhandler use for call back mail controller delegates.
var documentPickerCompletionHandler: DocumentPickerCompletionHandler?
///Shared instance
public static let sharedInstance = NRControls()
/**
This function is used for taking a picture from iphone camera or camera roll.
- Parameters:
- viewController: Source viewcontroller from which you want to present this popup.
- completionHandler: This completion handler will give you image or nil.
*/
//MARK: UIImagePickerController
open func takeOrChoosePhoto(_ viewController: UIViewController, completionHandler: @escaping CompletionImagePickerController) {
let actionSheetController: UIAlertController = UIAlertController(title: "", message: "Choose photo", preferredStyle: .actionSheet)
//Create and add the Cancel action
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
//Just dismiss the action sheet
completionHandler(nil)
}
actionSheetController.addAction(cancelAction)
//Create and add first option action
//Create and add a second option action
let takePictureAction: UIAlertAction = UIAlertAction(title: "Take Picture", style: .default) { action -> Void in
self.openImagePickerController(.camera, isVideo: false, inViewController: viewController) { (controller, info) -> Void in
let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
completionHandler(image)
}
}
actionSheetController.addAction(takePictureAction)
//Create and add a second option action
let choosePictureAction: UIAlertAction = UIAlertAction(title: "Choose from library", style: .default) { action -> Void in
self.openImagePickerController(.photoLibrary, isVideo: false, inViewController: viewController) { (controller, info) -> Void in
let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
completionHandler(image)
}
}
actionSheetController.addAction(choosePictureAction)
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad) {
// In this case the device is an iPad.
if let popoverController = actionSheetController.popoverPresentationController {
popoverController.sourceView = viewController.view
popoverController.sourceRect = viewController.view.bounds
}
}
viewController.present(actionSheetController, animated: true, completion: nil)
}
/**
This function is used open image picker controller.
- Parameters:
- sourceType: PhotoLibrary, Camera, SavedPhotosAlbum
- inViewController: Source viewcontroller from which you want to present this imagecontroller.
- isVideo: if you want to capture video then set it to yes, by default value is false.
- completionHandler: Gives you the call back with Imagepickercontroller and information about image.
*/
open func openImagePickerController(_ sourceType: UIImagePickerController.SourceType, isVideo: Bool = false, inViewController:UIViewController, completionHandler: @escaping ImagePickerControllerCompletionHandler)-> Void {
self.imagePickerControllerHandler = completionHandler
let controller = UIImagePickerController()
controller.allowsEditing = false
controller.delegate = self;
if UIImagePickerController.isSourceTypeAvailable(sourceType){
controller.sourceType = sourceType
}
else
{
print("this source type not supported in this device")
}
if (UI_USER_INTERFACE_IDIOM() == .pad) { //iPad support
// In this case the device is an iPad.
if let popoverController = controller.popoverPresentationController {
popoverController.sourceView = inViewController.view
popoverController.sourceRect = inViewController.view.bounds
}
}
inViewController.present(controller, animated: true, completion: nil)
}
//MARK: UIImagePickerController Delegates
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
print("didFinishPickingMediaWithInfo")
self.imagePickerControllerHandler!(picker, info)
picker.dismiss(animated: true, completion: nil)
}
open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
/**
This function is used for open Mail Composer.
- Parameters:
- recipientsEmailIds: email ids of recipents for you want to send emails.
- viewcontroller: Source viewcontroller from which you want to present this mail composer.
- subject: Subject of mail.
- message: body of mail.
- attachment: optional this is nsdata of video/photo or any other document.
- completionHandler: Gives you the call back with result and error if any.
*/
//MARK: MFMailComposeViewController
open func openMailComposerInViewController(_ recipientsEmailIds:[String], viewcontroller: UIViewController, subject: String = "", message: String = "" ,attachment: Data? = nil,completionHandler: @escaping MailComposerCompletionHandler){
if !MFMailComposeViewController.canSendMail() {
print("No mail configured. please configure your mail first")
return()
}
self.mailComposerCompletionHandler = completionHandler
let mailComposerViewController = MFMailComposeViewController()
mailComposerViewController.mailComposeDelegate = self
mailComposerViewController.setSubject(subject)
mailComposerViewController.setMessageBody(message, isHTML: true)
mailComposerViewController.setToRecipients(recipientsEmailIds)
if let _ = attachment {
if (attachment!.count>0)
{
mailComposerViewController.addAttachmentData(attachment!, mimeType: "image/jpeg", fileName: "attachment.jpeg")
}
}
viewcontroller.present(mailComposerViewController, animated: true, completion:nil)
}
//MARK: MFMailComposeViewController Delegates
open func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion:nil)
if self.mailComposerCompletionHandler != nil {
self.mailComposerCompletionHandler!(result, error as NSError?)
}
}
//MARK: AlertController
/**
This function is used for open Alert View.
- Parameters:
- viewcontroller: Source viewcontroller from which you want to present this mail composer.
- title: title of the alert.
- message: message of the alert .
- buttonsTitlesArray: array of button titles eg: ["Cancel","Ok"].
- completionHandler: Gives you the call back with alertController and index of selected button .
*/
open func openAlertViewFromViewController(_ viewController: UIViewController, title: String = "", message: String = "", buttonsTitlesArray: [String], completionHandler: AlertControllerCompletionHandler?){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
for element in buttonsTitlesArray {
let action:UIAlertAction = UIAlertAction(title: element, style: .default, handler: { (action) -> Void in
if let _ = completionHandler {
completionHandler!(alertController, buttonsTitlesArray.index(of: element)!)
}
})
alertController.addAction(action)
}
viewController.present(alertController, animated: true, completion: nil)
}
/**
This function is used for open Action Sheet.
- Parameters:
- viewcontroller: Source viewcontroller from which you want to present this mail composer.
- title: title of the alert.
- message: message of the alert .
- buttonsTitlesArray: array of button titles eg: ["Cancel","Ok"].
- completionHandler: Gives you the call back with alertController and index of selected button .
*/
open func openActionSheetFromViewController(_ viewController: UIViewController, title: String, message: String, buttonsTitlesArray: [String], completionHandler: AlertControllerCompletionHandler?){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
for element in buttonsTitlesArray {
let action:UIAlertAction = UIAlertAction(title: element, style: .default, handler: { (action) -> Void in
if let _ = completionHandler {
completionHandler!(alertController, buttonsTitlesArray.index(of: element)!)
}
})
alertController.addAction(action)
}
viewController.present(alertController, animated: true, completion: nil)
}
/**
This function is used for openAlertView with textfield.
- Parameters:
- viewcontroller: source viewcontroller from which you want to present this mail composer.
- title: title of the alert.
- message: message of the alert.
- placeHolder: placeholder of the textfield.
- isSecure: true if you want texfield secure, by default is false.
- isNumberKeyboard: true if keyboard is of type numberpad, .
- buttonsTitlesArray: array of button titles eg: ["Cancel","Ok"].
- completionHandler: Gives you the call back with alertController,index and text of textfield.
*/
open func openAlertViewWithTextFieldFromViewController(_ viewController: UIViewController, title: String = "", message: String = "", placeHolder: String = "", isSecure: Bool = false, buttonsTitlesArray: [String], isNumberKeyboard: Bool = false, completionHandler: AlertTextFieldControllerCompletionHandler?){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
for element in buttonsTitlesArray {
let action: UIAlertAction = UIAlertAction(title: element, style: .default, handler: { (action) -> Void in
if let _ = completionHandler {
if let _ = alertController.textFields , alertController.textFields?.count > 0 , let text = alertController.textFields?.first?.text {
completionHandler!(alertController, buttonsTitlesArray.index(of: element)!, text)
}
}
})
alertController.addAction(action)
}
alertController.addTextField { (textField : UITextField!) -> Void in
textField.isSecureTextEntry = isSecure
textField.placeholder = placeHolder
if isNumberKeyboard {
textField.keyboardType = .numberPad
}
else {
textField.keyboardType = .emailAddress
}
}
viewController.present(alertController, animated: false, completion: nil)
}
}
|
c5721df66c1916cf91a4694c96434642
| 42.326284 | 312 | 0.66669 | false | false | false | false |
YifengBai/YuDou
|
refs/heads/master
|
YuDou/YuDou/Classes/Main/Controller/BaseAnchorViewController.swift
|
mit
|
1
|
//
// BaseAnchorViewController.swift
// YuDou
//
// Created by Bemagine on 2017/1/16.
// Copyright © 2017年 bemagine. All rights reserved.
//
import UIKit
let kItemMargin : CGFloat = 10
private let kHeaderViewH : CGFloat = 50
let kNormalItemW = (kScreenW - 3 * kItemMargin) / 2
let kNormalItemH = kNormalItemW * 3 / 4
let kPrettyItemH = kNormalItemW * 4 / 3
private let HeaderViewId = "collectionSectionHeaderId"
let GameCellId = "GameCellId"
let BeautyCellId = "BeautyCellId"
class BaseAnchorViewController: BaseViewController {
var baseVM : BaseViewModel!
lazy var collectionView : UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH)
layout.sectionInset = UIEdgeInsetsMake(0, kItemMargin, 0, kItemMargin)
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.backgroundColor = UIColor.white
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "GameCell", bundle: nil), forCellWithReuseIdentifier: GameCellId)
collectionView.register(UINib(nibName: "BeautyCell", bundle: nil), forCellWithReuseIdentifier: BeautyCellId)
collectionView.register(UINib(nibName: "SectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: HeaderViewId)
return collectionView
}()
fileprivate var startOffY : CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
setupUI()
loadData()
}
}
extension BaseAnchorViewController {
override func setupUI() {
contentView = collectionView
view.addSubview(collectionView)
super.setupUI()
}
func loadData() {
}
}
extension BaseAnchorViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return baseVM.groupData.count;
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return baseVM.groupData[section].anchors.count;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 取出数据
let groupD = self.baseVM.groupData[indexPath.section]
let item = groupD.anchors[indexPath.item]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GameCellId, for: indexPath) as! GameCell
cell.roomModel = item
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: HeaderViewId, for: indexPath) as! SectionHeaderView
header.group = baseVM.groupData[indexPath.section]
return header
}
}
extension BaseAnchorViewController : UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let nextOffY = scrollView.contentOffset.y
var scrollDrection : ScrollDirection!
if nextOffY > startOffY {
scrollDrection = .ScrollDown
} else {
scrollDrection = .ScrollUp
}
// guard let parentVC = self.parent as? BaseViewController else { return }
// parentVC.navigationBarTransform(direction: scrollDrection)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationNavigationBarTransform), object: scrollDrection)
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
startOffY = scrollView.contentOffset.y
}
}
|
9a6d96314f2d27a845096d8856b1f517
| 31.757353 | 187 | 0.683726 | false | false | false | false |
phatblat/3DTouchDemo
|
refs/heads/master
|
3DTouchDemo/TouchCanvas/TouchCanvas/ReticleView.swift
|
mit
|
1
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `ReticleView` allows visualization of the azimuth and altitude related properties of a `UITouch` via an indicator similar to the sighting devices such as a telescope.
*/
import UIKit
class ReticleView: UIView {
// MARK: Properties
var actualAzimuthAngle: CGFloat = 0.0 {
didSet {
setNeedsLayout()
}
}
var actualAzimuthUnitVector = CGVector(dx: 0, dy: 0) {
didSet {
setNeedsLayout()
}
}
var actualAltitudeAngle: CGFloat = 0.0 {
didSet {
setNeedsLayout()
}
}
var predictedAzimuthAngle: CGFloat = 0.0 {
didSet {
setNeedsLayout()
}
}
var predictedAzimuthUnitVector = CGVector(dx: 0, dy: 0) {
didSet {
setNeedsLayout()
}
}
var predictedAltitudeAngle: CGFloat = 0.0 {
didSet {
setNeedsLayout()
}
}
let reticleLayer = CALayer()
let radius: CGFloat = 80
var reticleImage: UIImage!
let reticleColor = UIColor(hue: 0.516, saturation: 0.38, brightness: 0.85, alpha: 0.4)
let dotRadius: CGFloat = 8
let lineWidth: CGFloat = 2
var predictedDotLayer = CALayer()
var predictedLineLayer = CALayer()
let predictedIndicatorColor = UIColor(hue: 0.53, saturation: 0.86, brightness: 0.91, alpha: 1.0)
var dotLayer = CALayer()
var lineLayer = CALayer()
let indicatorColor = UIColor(hue: 0.0, saturation: 0.86, brightness: 0.91, alpha: 1.0)
// MARK: Initialization
override init(frame: CGRect) {
super.init(frame: frame)
reticleLayer.contentsGravity = kCAGravityCenter
reticleLayer.position = layer.position
layer.addSublayer(reticleLayer)
configureDotLayer(layer: predictedDotLayer, withColor: predictedIndicatorColor)
predictedDotLayer.hidden = true
configureLineLayer(layer: predictedLineLayer, withColor: predictedIndicatorColor)
predictedLineLayer.hidden = true
configureDotLayer(layer: dotLayer, withColor: indicatorColor)
configureLineLayer(layer: lineLayer, withColor: indicatorColor)
reticleLayer.addSublayer(predictedDotLayer)
reticleLayer.addSublayer(predictedLineLayer)
reticleLayer.addSublayer(dotLayer)
reticleLayer.addSublayer(lineLayer)
renderReticleImage()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: UIView Overrides
override func intrinsicContentSize() -> CGSize {
return reticleImage.size
}
override func layoutSubviews() {
super.layoutSubviews()
CATransaction.setDisableActions(true)
reticleLayer.position = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2)
layoutIndicator()
CATransaction.setDisableActions(false)
}
// MARK: Convenience
func renderReticleImage() {
let imageRadius = ceil(radius * 1.2)
let imageSize = CGSize(width: imageRadius * 2, height: imageRadius * 2)
UIGraphicsBeginImageContextWithOptions(imageSize, false, contentScaleFactor)
let ctx = UIGraphicsGetCurrentContext()
CGContextTranslateCTM(ctx, imageRadius, imageRadius)
CGContextSetLineWidth(ctx, 2)
CGContextSetStrokeColorWithColor(ctx, reticleColor.CGColor)
CGContextStrokeEllipseInRect(ctx, CGRect(x: -radius, y: -radius, width: radius * 2, height: radius * 2))
// Draw targeting lines.
let path = CGPathCreateMutable()
var transform = CGAffineTransformIdentity
for _ in 0..<4 {
CGPathMoveToPoint(path, &transform, radius * 0.5, 0)
CGPathAddLineToPoint(path, &transform, radius * 1.15, 0)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
}
CGContextAddPath(ctx, path)
CGContextStrokePath(ctx)
reticleImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
reticleLayer.contents = reticleImage.CGImage
reticleLayer.bounds = CGRect(x: 0, y: 0, width: imageRadius * 2, height: imageRadius * 2)
reticleLayer.contentsScale = contentScaleFactor
}
func layoutIndicator() {
// Predicted.
layoutIndicatorForAzimuthAngle(predictedAzimuthAngle, azimuthUnitVector: predictedAzimuthUnitVector, altitudeAngle: predictedAltitudeAngle, lineLayer: predictedLineLayer, dotLayer: predictedDotLayer)
// Actual.
layoutIndicatorForAzimuthAngle(actualAzimuthAngle, azimuthUnitVector: actualAzimuthUnitVector, altitudeAngle: actualAltitudeAngle, lineLayer: lineLayer, dotLayer: dotLayer)
}
func layoutIndicatorForAzimuthAngle(azimuthAngle: CGFloat, azimuthUnitVector: CGVector, altitudeAngle: CGFloat, lineLayer targetLineLayer: CALayer, dotLayer targetDotLayer: CALayer) {
let reticleBounds = reticleLayer.bounds
let centeringTransform = CGAffineTransformMakeTranslation(reticleBounds.width / 2, reticleBounds.height / 2)
var rotationTransform = CGAffineTransformMakeRotation(azimuthAngle)
// Draw the indicator opposite the azimuth by rotating pi radians, for easy visualization.
rotationTransform = CGAffineTransformRotate(rotationTransform, CGFloat(M_PI))
/*
Make the length of the indicator's line representative of the `altitudeAngle`. When the angle is
zero radians (parallel to the screen surface) the line will be at its longest. At `M_PI`/2 radians,
only the dot on top of the indicator will be visible directly beneath the touch location.
*/
let altitudeRadius = (1.0 - altitudeAngle / CGFloat(M_PI_2)) * radius
var lineTransform = CGAffineTransformMakeScale(altitudeRadius, 1)
lineTransform = CGAffineTransformConcat(lineTransform, rotationTransform)
lineTransform = CGAffineTransformConcat(lineTransform, centeringTransform)
targetLineLayer.setAffineTransform(lineTransform)
var dotTransform = CGAffineTransformMakeTranslation(-azimuthUnitVector.dx * altitudeRadius, -azimuthUnitVector.dy * altitudeRadius)
dotTransform = CGAffineTransformConcat(dotTransform, centeringTransform)
targetDotLayer.setAffineTransform(dotTransform)
}
func configureDotLayer(layer targetLayer: CALayer, withColor color: UIColor) {
targetLayer.backgroundColor = color.CGColor
targetLayer.bounds = CGRect(x: 0, y: 0, width: dotRadius * 2, height: dotRadius * 2)
targetLayer.cornerRadius = dotRadius
targetLayer.position = CGPoint.zero
}
func configureLineLayer(layer targetLayer: CALayer, withColor color: UIColor) {
targetLayer.backgroundColor = color.CGColor
targetLayer.bounds = CGRect(x: 0, y: 0, width: 1, height: lineWidth)
targetLayer.anchorPoint = CGPoint(x: 0, y: 0.5)
targetLayer.position = CGPoint.zero
}
}
|
dc9fc93f25d6f9c930ce11ba40023873
| 38.12766 | 207 | 0.66789 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.