repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sonsongithub/reddift | refs/heads/master | framework/Network/Session+account.swift | mit | 1 | //
// Session+account.swift
// reddift
//
// Created by sonson on 2015/05/19.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
extension Session {
/**
Get preference
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
@discardableResult
public func getPreference(_ completion: @escaping (Result<Preference>) -> Void) throws -> URLSessionDataTask {
guard let request = URLRequest.requestForOAuth(with: Session.OAuthEndpointURL, path: "/api/v1/me/prefs", method: "GET", token: token)
else { throw ReddiftError.canNotCreateURLRequest as NSError }
let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<Preference> in
return Result(from: Response(data: data, urlResponse: response), optional: error)
.flatMap(response2Data)
.flatMap(data2Json)
.flatMap(json2Preference)
}
return executeTask(request, handleResponse: closure, completion: completion)
}
/**
DOES NOT WORK, I CAN NOT UNDERSTAND WHY IT DOES NOT.
Patch preference with Preference object.
- parameter preference: Preference object.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
@discardableResult
public func patchPreference(_ preference: Preference, completion: @escaping (Result<Preference>) -> Void) throws -> URLSessionDataTask {
let json = preference.json()
do {
let data = try JSONSerialization.data(withJSONObject: json, options: [])
guard let request = URLRequest.requestForOAuth(with: Session.OAuthEndpointURL, path: "/api/v1/me/prefs", data: data, method: "PATCH", token: token)
else { throw ReddiftError.canNotCreateURLRequest as NSError }
let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<Preference> in
return Result(from: Response(data: data, urlResponse: response), optional: error)
.flatMap(response2Data)
.flatMap(data2Json)
.flatMap(json2Preference)
}
return executeTask(request, handleResponse: closure, completion: completion)
} catch { throw error }
}
/**
Get friends
- parameter paginator: Paginator object for paging contents.
- parameter limit: The maximum number of comments to return. Default is 25.
- parameter count: A positive integer (default: 0)
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
@discardableResult
public func getFriends(_ paginator: Paginator, count: Int = 0, limit: Int = 1, completion: @escaping (Result<RedditAny>) -> Void) throws -> URLSessionDataTask {
do {
let parameter = paginator.dictionaryByAdding(parameters: [
"limit": "\(limit)",
"show": "all",
"count": "\(count)"
// "sr_detail": "true",
])
guard let request = URLRequest.requestForOAuth(with: baseURL, path: "/prefs/friends", parameter: parameter, method: "GET", token: token)
else { throw ReddiftError.canNotCreateURLRequest as NSError }
let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<RedditAny> in
return Result(from: Response(data: data, urlResponse: response), optional: error)
.flatMap(response2Data)
.flatMap(data2Json)
.flatMap(json2RedditAny)
}
return executeTask(request, handleResponse: closure, completion: completion)
} catch { throw error }
}
/**
Get blocked
- parameter paginator: Paginator object for paging contents.
- parameter limit: The maximum number of comments to return. Default is 25.
- parameter count: A positive integer (default: 0)
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
@discardableResult
public func getBlocked(_ paginator: Paginator, count: Int = 0, limit: Int = 25, completion: @escaping (Result<[User]>) -> Void) throws -> URLSessionDataTask {
do {
let parameter = paginator.dictionaryByAdding(parameters: [
"limit": "\(limit)",
"show": "all",
"count": "\(count)"
// "sr_detail": "true",
])
guard let request = URLRequest.requestForOAuth(with: baseURL, path: "/prefs/blocked", parameter: parameter, method: "GET", token: token)
else { throw ReddiftError.canNotCreateURLRequest as NSError }
let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<[User]> in
return Result(from: Response(data: data, urlResponse: response), optional: error)
.flatMap(response2Data)
.flatMap(data2Json)
.flatMap(json2RedditAny)
.flatMap(redditAny2Object)
}
return executeTask(request, handleResponse: closure, completion: completion)
} catch { throw error }
}
/**
Return a breakdown of subreddit karma.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
@discardableResult
public func getKarma(_ completion: @escaping (Result<[SubredditKarma]>) -> Void) throws -> URLSessionDataTask {
guard let request = URLRequest.requestForOAuth(with: baseURL, path: "/api/v1/me/karma", method: "GET", token: token)
else { throw ReddiftError.canNotCreateURLRequest as NSError }
let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<[SubredditKarma]> in
return Result(from: Response(data: data, urlResponse: response), optional: error)
.flatMap(response2Data)
.flatMap(data2Json)
.flatMap(json2RedditAny)
.flatMap(redditAny2Object)
}
return executeTask(request, handleResponse: closure, completion: completion)
}
/**
Return a list of trophies for the current user.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
@discardableResult
public func getTrophies(_ completion: @escaping (Result<[Trophy]>) -> Void) throws -> URLSessionDataTask {
guard let request = URLRequest.requestForOAuth(with: baseURL, path: "/api/v1/me/trophies", method: "GET", token: token)
else { throw ReddiftError.canNotCreateURLRequest as NSError }
let closure = {(data: Data?, response: URLResponse?, error: NSError?) -> Result<[Trophy]> in
return Result(from: Response(data: data, urlResponse: response), optional: error)
.flatMap(response2Data)
.flatMap(data2Json)
.flatMap(json2RedditAny)
.flatMap(redditAny2Object)
}
return executeTask(request, handleResponse: closure, completion: completion)
}
public func requestForGettingProfile() throws -> URLRequest {
guard let request = URLRequest.requestForOAuth(with: baseURL, path: "/api/v1/me", method: "GET", token: token)
else { throw ReddiftError.canNotCreateURLRequest as NSError }
return request
}
/**
Gets the identity of the user currently authenticated via OAuth.
- parameter completion: The completion handler to call when the load request is complete.
- returns: Data task which requests search to reddit.com.
*/
@discardableResult
public func getProfile(_ completion: @escaping (Result<Account>) -> Void) throws -> URLSessionDataTask {
guard let request = URLRequest.requestForOAuth(with: baseURL, path: "/api/v1/me", method: "GET", token: token)
else { throw ReddiftError.canNotCreateURLRequest as NSError }
let closure: (_ data: Data?, _ response: URLResponse?, _ error: NSError?) -> Result<Account> = accountInResult
return executeTask(request, handleResponse: closure, completion: completion)
}
}
| c27d2e04bcca2d6629b87ba6e824daad | 50.715976 | 164 | 0.635812 | false | false | false | false |
tgyhlsb/iPath | refs/heads/master | iPath/iPath/Controllers/RouteDetailsViewController/RouteDetailsViewController+TableView.swift | mit | 1 | //
// RouteDetailsViewController+TableView.swift
// iPath
//
// Created by Tanguy Hélesbeux on 17/10/2016.
// Copyright © 2016 Tanguy Helesbeux. All rights reserved.
//
import UIKit
extension RouteDetailsViewController: UITableViewDataSource {
// MARK: - PUBLIC -
// MARK: - INTERNAL -
internal func initializeTableView() {
self.tableView.dataSource = self
}
internal func reloadTableView() {
self.tableView.reloadData()
}
// MARK: - PRIVATE -
// MARK: UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let path = self.activePath else { return 0 }
return path.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "placeCell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
}
cell?.textLabel?.text = self.place(for: indexPath)?.name
return cell!
}
private func place(for indexPath: IndexPath) -> Place? {
return self.activePath?[indexPath.row]
}
}
| fc1ab069c8dce722f70962b77f99853b | 25.055556 | 100 | 0.624023 | false | false | false | false |
ykyouhei/KYWheelTabController | refs/heads/master | KYWheelTabController/Classes/ViewControllers/KYWheelTabController.swift | mit | 1 | //
// KYWheelTabController.swift
// KYWheelTabController
//
// Created by kyo__hei on 2016/02/20.
// Copyright © 2016年 kyo__hei. All rights reserved.
//
import UIKit
open class KYWheelTabController: UITabBarController {
/* ====================================================================== */
// MARK: Properties
/* ====================================================================== */
@IBInspectable open var tintColor: UIColor = UIColor(colorLiteralRed: 0, green: 122/255, blue: 1, alpha: 1) {
didSet {
wheelMenuView.tintColor = tintColor
}
}
override open var viewControllers: [UIViewController]? {
didSet {
wheelMenuView.tabBarItems = tabBarItems
}
}
open internal(set) lazy var wheelMenuView: WheelMenuView = {
return WheelMenuView(
frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 201, height: 201)),
tabBarItems: self.tabBarItems)
}()
fileprivate var tabBarItems: [UITabBarItem] {
return viewControllers?.map { $0.tabBarItem } ?? []
}
/* ====================================================================== */
// MARK: Life Cycle
/* ====================================================================== */
override open func viewDidLoad() {
super.viewDidLoad()
tabBar.isHidden = true
wheelMenuView.tintColor = tintColor
wheelMenuView.delegate = self
wheelMenuView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(wheelMenuView)
view.addConstraints([
NSLayoutConstraint(
item: wheelMenuView,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .width,
multiplier: 1.0,
constant: 201
),
NSLayoutConstraint(
item: wheelMenuView,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height,
multiplier: 1.0,
constant: 201
),
NSLayoutConstraint(
item: wheelMenuView,
attribute: .centerX,
relatedBy: .equal,
toItem: view,
attribute: .centerX,
multiplier: 1.0,
constant: 0
),
NSLayoutConstraint(
item: wheelMenuView,
attribute: .bottom,
relatedBy: .equal,
toItem: view,
attribute: .bottom,
multiplier: 1.0,
constant: 44
)
])
}
}
extension KYWheelTabController: WheelMenuViewDelegate {
public func wheelMenuView(_ view: WheelMenuView, didSelectItem: UITabBarItem) {
selectedIndex = view.selectedIndex
}
}
| 0b877784736691db15850a14e62b4304 | 28.705882 | 113 | 0.470627 | false | false | false | false |
Ehrippura/firefox-ios | refs/heads/development | Client/Frontend/Browser/PrintHelper.swift | mpl-2.0 | 12 | /* 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 WebKit
class PrintHelper: TabHelper {
fileprivate weak var tab: Tab?
class func name() -> String {
return "PrintHelper"
}
required init(tab: Tab) {
self.tab = tab
if let path = Bundle.main.path(forResource: "PrintHelper", ofType: "js"), let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String {
let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false)
tab.webView!.configuration.userContentController.addUserScript(userScript)
}
}
func scriptMessageHandlerName() -> String? {
return "printHandler"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let tab = tab, let webView = tab.webView {
let printController = UIPrintInteractionController.shared
printController.printFormatter = webView.viewPrintFormatter()
printController.present(animated: true, completionHandler: nil)
}
}
}
| dbebacfe0f73a788810ac1f365410aec | 38.457143 | 183 | 0.698045 | false | false | false | false |
uxmstudio/UXMPDFKit | refs/heads/master | Pod/Classes/Form/PDFFormPageView.swift | mit | 1 | //
// PDFFormView.swift
// Pods
//
// Created by Chris Anderson on 5/26/16.
//
//
import UIKit
struct PDFFormViewOptions {
var type: String
var rect: CGRect
var flags: [PDFFormFlag]?
var name: String = ""
var exportValue: String = ""
var options: [String]?
}
struct PDFFormFlag: Equatable {
let rawValue: UInt
static let ReadOnly = PDFFormFlag(rawValue:1 << 0)
static let Required = PDFFormFlag(rawValue:1 << 1)
static let NoExport = PDFFormFlag(rawValue:1 << 2)
static let TextFieldMultiline = PDFFormFlag(rawValue:1 << 12)
static let TextFieldPassword = PDFFormFlag(rawValue:1 << 13)
static let ButtonNoToggleToOff = PDFFormFlag(rawValue:1 << 14)
static let ButtonRadio = PDFFormFlag(rawValue:1 << 15)
static let ButtonPushButton = PDFFormFlag(rawValue:1 << 16)
static let ChoiceFieldIsCombo = PDFFormFlag(rawValue:1 << 17)
static let ChoiceFieldEditable = PDFFormFlag(rawValue:1 << 18)
static let ChoiceFieldSorted = PDFFormFlag(rawValue:1 << 19)
}
func ==(lhs: PDFFormFlag, rhs: PDFFormFlag) -> Bool {
return lhs.rawValue == rhs.rawValue
}
open class PDFFormPage: NSObject {
let page: Int
var fields: [PDFFormFieldObject] = []
let zoomScale: CGFloat = 1.0
init(page: Int) {
self.page = page
}
func showForm(_ contentView: PDFPageContentView) {
let formView = PDFFormPageView(
frame: contentView.contentView.cropBoxRect,
boundingBox: contentView.containerView.frame,
cropBox: contentView.contentView.cropBoxRect,
fields: self.fields)
formView.zoomScale = contentView.zoomScale
if contentView.contentView.subviews.filter({ $0 is PDFFormPageView }).count <= 0 {
contentView.contentView.addSubview(formView)
}
contentView.viewDidZoom = { scale in
formView.updateWithZoom(scale)
}
contentView.sendSubviewToBack(formView)
}
func createFormField(_ dict: PDFDictionary) {
fields.append(PDFFormFieldObject(dict: dict))
}
func renderInContext(_ context: CGContext, size: CGRect) {
let formView = PDFFormPageView(
frame: size,
boundingBox: size,
cropBox: size,
fields: self.fields)
formView.renderInContext(context)
}
}
open class PDFFormPageView: UIView {
var fields: [PDFFormFieldObject]
var fieldViews: [PDFFormField] = []
var zoomScale: CGFloat = 1.0
let cropBox: CGRect
let boundingBox: CGRect
let baseFrame: CGRect
init(frame: CGRect, boundingBox: CGRect, cropBox: CGRect, fields: [PDFFormFieldObject]) {
self.baseFrame = frame
self.cropBox = cropBox
self.boundingBox = boundingBox
self.fields = fields
super.init(frame: frame)
for field in fields {
guard let fieldView = field.createFormField() else { continue }
addSubview(fieldView)
adjustFrame(fieldView)
fieldViews.append(fieldView)
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateWithZoom(_ zoomScale: CGFloat) {
for field in fieldViews {
field.updateForZoomScale(zoomScale)
field.refresh()
}
}
func adjustFrame(_ field: PDFFormField) {
let factor: CGFloat = 1.0
let correctedFrame = CGRect(
x: (field.baseFrame.origin.x - cropBox.origin.x) * factor,
y: (cropBox.height - field.baseFrame.origin.y - field.baseFrame.height - cropBox.origin.y) * factor,
width: field.baseFrame.width * factor,
height: field.baseFrame.height * factor)
field.frame = correctedFrame
}
func renderInContext(_ context: CGContext) {
for field in fieldViews {
field.renderInContext(context)
}
}
}
| 8dbbbb37102b9f53fbb9d937155c5562 | 30.236641 | 112 | 0.619013 | false | false | false | false |
ruslanskorb/CoreStore | refs/heads/master | CoreStoreDemo/CoreStoreDemo/MIgrations Demo/OrganismV2.swift | mit | 1 | //
// OrganismV2.swift
// CoreStoreDemo
//
// Created by John Rommel Estropia on 2015/06/21.
// Copyright © 2018 John Rommel Estropia. All rights reserved.
//
import Foundation
import CoreData
class OrganismV2: NSManagedObject, OrganismProtocol {
@NSManaged var dna: Int64
@NSManaged var hasHead: Bool
@NSManaged var hasTail: Bool
@NSManaged var numberOfFlippers: Int32
// MARK: OrganismProtocol
func mutate() {
self.hasHead = arc4random_uniform(2) == 1
self.hasTail = arc4random_uniform(2) == 1
self.numberOfFlippers = Int32(arc4random_uniform(9) / 2 * 2)
}
}
| 6bf60111d540b6eb91d8e15b0a56b50a | 22.814815 | 68 | 0.657854 | false | false | false | false |
Ashok28/Kingfisher | refs/heads/master | Demo/Demo/Kingfisher-Demo/ViewControllers/TransitionViewController.swift | mit | 2 | //
// TransitionViewController.swift
// Kingfisher
//
// Created by onevcat on 2018/11/18.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Kingfisher
class TransitionViewController: UIViewController {
enum PickerComponent: Int, CaseIterable {
case transitionType
case duration
}
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var transitionPickerView: UIPickerView!
let durations: [TimeInterval] = [0.5, 1, 2, 4, 10]
let transitions: [String] = ["none", "fade", "flip - left", "flip - right", "flip - top", "flip - bottom"]
override func viewDidLoad() {
super.viewDidLoad()
title = "Transition"
setupOperationNavigationBar()
imageView.kf.indicatorType = .activity
}
func makeTransition(type: String, duration: TimeInterval) -> ImageTransition {
switch type {
case "none": return .none
case "fade": return .fade(duration)
case "flip - left": return .flipFromLeft(duration)
case "flip - right": return .flipFromRight(duration)
case "flip - top": return .flipFromTop(duration)
case "flip - bottom": return .flipFromBottom(duration)
default: return .none
}
}
func reloadImageView() {
let typeIndex = transitionPickerView.selectedRow(inComponent: PickerComponent.transitionType.rawValue)
let transitionType = transitions[typeIndex]
let durationIndex = transitionPickerView.selectedRow(inComponent: PickerComponent.duration.rawValue)
let duration = durations[durationIndex]
let t = makeTransition(type: transitionType, duration: duration)
let url = ImageLoader.sampleImageURLs[0]
KF.url(url)
.forceTransition()
.transition(t)
.set(to: imageView)
}
}
extension TransitionViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch PickerComponent(rawValue: component)! {
case .transitionType: return transitions[row]
case .duration: return String(durations[row])
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
reloadImageView()
}
}
extension TransitionViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return PickerComponent.allCases.count
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch PickerComponent(rawValue: component)! {
case .transitionType: return transitions.count
case .duration: return durations.count
}
}
}
| 41001600347fa374f7bb783308f0f22e | 37.252427 | 111 | 0.686548 | false | false | false | false |
truemetal/vapor-2-heroku-auth-template | refs/heads/master | Sources/App/Setup/AppConfig.swift | mit | 1 | //
// AppConfig.swift
// App
//
// Created by Bogdan Pashchenko on 02.11.2019.
//
import Authentication
import FluentPostgreSQL
import Vapor
typealias AppModel = PostgreSQLModel & Content & Parameter
typealias AppDatabase = PostgreSQLDatabase
let databaseId = DatabaseIdentifier<AppDatabase>.psql
let db = PostgreSQLDatabase(config: PostgreSQLDatabaseConfig(url: Environment.get("DATABASE_URL")!)!)
public class AppConfig {
public init() {}
public func app(_ env: Environment? = nil) throws -> Application {
return try Application(config: Config.default(), environment: env ?? .detect(), services: try configure())
}
func configure() throws -> Services {
var services = Services.default()
try services.register(FluentPostgreSQLProvider())
try services.register(AuthenticationProvider())
try services.register(AppRouterConfig().router, as: Router.self)
services.register(middlewares)
services.register(try databases())
services.register(migrations)
services.register(AppWebSocketsServer(), as: WebSocketServer.self)
return services
}
var middlewares: MiddlewareConfig {
var middlewares = MiddlewareConfig()
middlewares.use(ErrorMiddleware.self)
middlewares.use(HerokuHttpsMiddleware())
return middlewares
}
func databases() throws -> DatabasesConfig {
var databases = DatabasesConfig()
databases.enableLogging(on: databaseId)
databases.add(database: db, as: databaseId)
return databases
}
var migrations: MigrationConfig {
var migrations = MigrationConfig()
migrations.add(model: User.self, database: databaseId)
migrations.add(model: AccessToken.self, database: databaseId)
migrations.add(migration: SeedUsers.self, database: databaseId)
return migrations
}
}
| 84487d72e545cd5aa925ae3d77622dbb | 30.483871 | 114 | 0.677766 | false | true | false | false |
huonw/swift | refs/heads/master | test/attr/attr_objc_swift3_deprecated.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify %s -swift-version 3 -warn-swift3-objc-inference-complete
// REQUIRES: objc_interop
import Foundation
class ObjCSubclass : NSObject {
func foo() { } // expected-warning{{inference of '@objc' for members of Objective-C-derived classes is deprecated}}
// expected-note@-1{{add '@objc' to continue exposing an Objective-C entry point (Swift 3 behavior)}}{{3-3=@objc }}
// expected-note@-2{{add '@nonobjc' to suppress the Objective-C entry point (Swift 4 behavior)}}{{3-3=@nonobjc }}
var bar: NSObject? = nil // expected-warning{{inference of '@objc' for members of Objective-C-derived classes is deprecated}}
// expected-note@-1{{add '@objc' to continue exposing an Objective-C entry point (Swift 3 behavior)}}{{3-3=@objc }}
// expected-note@-2{{add '@nonobjc' to suppress the Objective-C entry point (Swift 4 behavior)}}{{3-3=@nonobjc }}
}
class DynamicMembers {
dynamic func foo() { } // expected-warning{{inference of '@objc' for 'dynamic' members is deprecated}}{{3-3=@objc }}
dynamic var bar: NSObject? = nil // expected-warning{{inference of '@objc' for 'dynamic' members is deprecated}}{{3-3=@objc }}
}
class GenericClass<T>: NSObject {}
class SubclassOfGeneric: GenericClass<Int> {
func foo() { } // expected-warning{{inference of '@objc' for members of Objective-C-derived classes is deprecated}}
// expected-note@-1{{add '@objc' to continue exposing an Objective-C entry point (Swift 3 behavior)}}{{3-3=@objc }}
// expected-note@-2{{add '@nonobjc' to suppress the Objective-C entry point (Swift 4 behavior)}}{{3-3=@nonobjc }}
}
@objc(SubclassOfGenericCustom)
class SubclassOfGenericCustomName: GenericClass<Int> {
func foo() { } // expected-warning{{inference of '@objc' for members of Objective-C-derived classes is deprecated}}
// expected-note@-1{{add '@objc' to continue exposing an Objective-C entry point (Swift 3 behavior)}}{{3-3=@objc }}
// expected-note@-2{{add '@nonobjc' to suppress the Objective-C entry point (Swift 4 behavior)}}{{3-3=@nonobjc }}
}
// Suppress diagnostices about references to inferred @objc declarations
// in this mode.
func test(sc: ObjCSubclass, dm: DynamicMembers) {
_ = #selector(sc.foo)
_ = #selector(getter: dm.bar)
_ = #keyPath(DynamicMembers.bar)
}
| f2895af575509d43fdde12432857440b | 53.697674 | 152 | 0.704082 | false | false | false | false |
Yurssoft/QuickFile | refs/heads/master | QuickFile/Views/YSDriveFileTableViewCell.swift | mit | 1 | //
// YSDriveFileTableViewCell.swift
// YSGGP
//
// Created by Yurii Boiko on 9/23/16.
// Copyright © 2016 Yurii Boiko. All rights reserved.
//
import UIKit
import DownloadButton
protocol YSDriveFileTableViewCellDelegate: class {
func downloadButtonPressed(_ id: String)
func stopDownloadButtonPressed(_ id: String)
}
class YSDriveFileTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var fileInfoLabel: UILabel!
@IBOutlet weak var fileImageView: UIImageView!
weak var delegate: YSDriveFileTableViewCellDelegate?
var file: YSDriveFileProtocol?
@IBOutlet weak var downloadButton: PKDownloadButton!
@IBOutlet weak var titleRightMarginConstraint: NSLayoutConstraint!
override func prepareForReuse() {
super.prepareForReuse()
downloadButton.delegate = nil
}
func configureForDrive(_ file: YSDriveFileProtocol?, _ delegate: YSDriveFileTableViewCellDelegate?, _ download: YSDownloadProtocol?) {
self.file = file
self.delegate = delegate
downloadButton.delegate = self
guard let file = file else { return }
nameLabel?.text = file.name
fileInfoLabel?.text = size
fileImageView?.image = UIImage(named: file.isAudio ? "song" : "folder")
if file.isAudio {
if file.localFileExists() {
downloadButton.isHidden = true
titleRightMarginConstraint.constant = 0.0
return
}
updateDownloadButton(download: download)
} else {
downloadButton.isHidden = true
titleRightMarginConstraint.constant = 0.0
}
}
func updateDownloadButton(download: YSDownloadProtocol?) {
downloadButton.superview?.bringSubview(toFront: downloadButton)
downloadButton.isHidden = false
titleRightMarginConstraint.constant = downloadButton.frame.width + 8
if let download = download {
switch download.downloadStatus {
case .downloading(let progress):
downloadButton.state = .downloading
downloadButton.stopDownloadButton.progress = CGFloat(progress)
case .pending:
downloadButton.state = .pending
downloadButton.pendingView.startSpin()
case .downloaded:
break
case .downloadError:
downloadButton.state = .startDownload
downloadButton.startDownloadButton.cleanDefaultAppearance()
downloadButton.startDownloadButton.setImage(UIImage.init(named: "cloud_download_error"), for: .normal)
case .cancelled:
downloadButton.state = .startDownload
downloadButton.startDownloadButton.cleanDefaultAppearance()
downloadButton.startDownloadButton.setImage(UIImage.init(named: "cloud_download"), for: .normal)
}
} else {
downloadButton.state = .startDownload
downloadButton.startDownloadButton.cleanDefaultAppearance()
downloadButton.startDownloadButton.setImage(UIImage.init(named: "cloud_download"), for: .normal)
}
}
func configureForPlaylist(_ file: YSDriveFileProtocol?) {
self.file = file
fileImageView?.image = UIImage(named: "song")
downloadButton.isHidden = true
guard let file = file else { return }
accessoryType = file.isPlayed ? .checkmark : .none
if file.isCurrentlyPlaying {
if let nameLabelFont = nameLabel?.font, let fileInfoLabelFont = fileInfoLabel?.font {
nameLabel?.font = UIFont.boldSystemFont(ofSize: nameLabelFont.pointSize)
fileInfoLabel?.font = UIFont.boldSystemFont(ofSize: fileInfoLabelFont.pointSize)
}
nameLabel.textColor = YSConstants.kDefaultBlueColor
fileInfoLabel.textColor = YSConstants.kDefaultBlueColor
} else {
if let nameLabelFont = nameLabel?.font, let fileInfoLabelFont = fileInfoLabel?.font {
nameLabel?.font = UIFont.systemFont(ofSize: nameLabelFont.pointSize)
fileInfoLabel?.font = UIFont.systemFont(ofSize: fileInfoLabelFont.pointSize)
}
nameLabel.textColor = UIColor.black
fileInfoLabel.textColor = UIColor.black
}
titleRightMarginConstraint.constant = 0.0
nameLabel?.text = file.name
fileInfoLabel?.text = size
}
var size: String {
guard let file = file else { return "" }
if file.isAudio, file.size.count > 0, var sizeInt = Int(file.size) {
sizeInt = sizeInt / 1024 / 1024
return sizeInt > 0 ? "\(sizeInt) MB" : file.mimeType
} else {
return file.mimeType
}
}
}
extension YSDriveFileTableViewCell: PKDownloadButtonDelegate {
func downloadButtonTapped(_ downloadButton: PKDownloadButton!, currentState state: PKDownloadButtonState) {
switch state {
case .startDownload:
downloadButton.state = .pending
downloadButton.pendingView.startSpin()
delegate?.downloadButtonPressed(file?.id ?? "")
case .pending, .downloading:
downloadButton.state = .startDownload
delegate?.stopDownloadButtonPressed(file?.id ?? "")
case .downloaded:
downloadButton.isHidden = true
}
}
}
| b7f992b7e0788233b93d4fbf8e678c83 | 39.422222 | 138 | 0.64541 | false | false | false | false |
csmulhern/neptune | refs/heads/master | Neptune/Neptune/CollectionViewController.swift | unlicense | 1 | import UIKit
public typealias CollectionRunning = Running<UICollectionView>
public typealias CollectionItem = Item<UICollectionView>
public typealias CollectionSection = Section<UICollectionView>
// MARK: - CollectionView
extension UICollectionView: CollectionView {
public typealias RunningViewType = UICollectionReusableView
public typealias ItemViewType = UICollectionViewCell
}
// MARK: - CollectionViewController
open class CollectionViewController: UIViewController, CollectionDataSourceDelegate {
open private(set) var collectionView: UICollectionView!
open let collectionViewLayout: UICollectionViewLayout
open var modelDataSource = CollectionDataSource() {
didSet {
self.modelDataSource.setCollectionView(self.collectionView, delegate: self)
}
}
public required init(collectionViewLayout: UICollectionViewLayout) {
self.collectionViewLayout = collectionViewLayout
super.init(nibName: nil, bundle: nil)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
for indexPath in self.collectionView.indexPathsForSelectedItems ?? [] {
self.collectionView.deselectItem(at: indexPath, animated: animated)
}
}
open override func viewDidLoad() {
super.viewDidLoad()
self.collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.collectionViewLayout)
self.view.addSubview(self.collectionView)
self.modelDataSource.setCollectionView(self.collectionView, delegate: self)
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.collectionView.frame = view.bounds
}
open func collectionViewSizeConstraints() -> CGSize {
return CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
}
}
| 56b8e8d84c270540a82f59b92b886a8a | 32.295082 | 115 | 0.737075 | false | false | false | false |
cruisediary/Diving | refs/heads/master | Diving/Scenes/UserDetail/UserDetailRouter.swift | mit | 1 | //
// UserDetailRouter.swift
// Diving
//
// Created by CruzDiary on 5/23/16.
// Copyright (c) 2016 DigitalNomad. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
protocol UserDetailRouterInput {
func navigateToSomewhere()
}
class UserDetailRouter {
weak var viewController: UserDetailViewController!
// MARK: Navigation
func navigateToSomewhere() {
// NOTE: Teach the router how to navigate to another scene. Some examples follow:
// 1. Trigger a storyboard segue
// viewController.performSegueWithIdentifier("ShowSomewhereScene", sender: nil)
// 2. Present another view controller programmatically
// viewController.presentViewController(someWhereViewController, animated: true, completion: nil)
// 3. Ask the navigation controller to push another view controller onto the stack
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
// 4. Present a view controller from a different storyboard
// let storyboard = UIStoryboard(name: "OtherThanMain", bundle: nil)
// let someWhereViewController = storyboard.instantiateInitialViewController() as! SomeWhereViewController
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
}
// MARK: Communication
func passDataToNextScene(segue: UIStoryboardSegue) {
// NOTE: Teach the router which scenes it can communicate with
if segue.identifier == "ShowSomewhereScene" {
passDataToSomewhereScene(segue)
}
}
func passDataToSomewhereScene(segue: UIStoryboardSegue) {
// NOTE: Teach the router how to pass data to the next scene
// let someWhereViewController = segue.destinationViewController as! SomeWhereViewController
// someWhereViewController.output.name = viewController.output.name
}
}
| 3fc987298534939a2ef0f043a0034943 | 36.701754 | 114 | 0.69986 | false | false | false | false |
Meru-Interactive/iOSC | refs/heads/master | swiftOSC/Types/Timetag.swift | mit | 1 | //
// OSCTypes.swift
// SwiftOSC
//
// Created by Devin Roth on 6/26/16.
// Copyright © 2016 Devin Roth Music. All rights reserved.
//
import Foundation
public typealias Timetag = UInt64
extension Timetag: OSCType {
public var tag: String {
get {
return "t"
}
}
public var data: Data {
get {
var int = self.bigEndian
let buffer = UnsafeBufferPointer(start: &int, count: 1)
return Data(buffer: buffer)
}
}
public init(currentTimeAdd seconds: Double){
self = Timer.sharedTime.timetag
self += UInt64(seconds * 0x1_0000_0000)
}
public init(seconds: Double){
self = UInt64(seconds * 0x1_0000_0000)
}
init(_ data: Data){
var int = UInt64()
let buffer = UnsafeMutableBufferPointer(start: &int, count: 1)
_ = data.copyBytes(to: buffer)
self = int.byteSwapped
}
}
| 2b8198cacc565a0db91e7d3dba525aa4 | 22.7 | 70 | 0.57173 | false | false | false | false |
ali-zahedi/AZViewer | refs/heads/master | AZViewer/AZPhotoCollectionViewCell.swift | apache-2.0 | 1 | //
// AZPhotoCollectionViewCell.swift
// AZViewer
//
// Created by Ali Zahedi on 7/22/17.
// Copyright © 2017 Ali Zahedi. All rights reserved.
//
import UIKit
class AZPhotoCollectionViewCell: AZCollectionViewCell {
// MARK: Public
// MARK: Internal
static var size: CGSize{
let wh: CGFloat = (UIScreen.main.bounds.width / 4 ) - (AZPhotoCollectionView.spacing * 1.5)
return CGSize(width: wh, height: wh)
}
var object: AZModelPhoto! {
didSet{
self.updateUI()
}
}
// MARK: Private
fileprivate var imageView: AZImageView = AZImageView()
// MARK: Init
override init(frame: CGRect) {
super.init(frame: frame)
self.defaultInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.defaultInit()
}
// MARK: Function
fileprivate func defaultInit(){
for v in [imageView] as [UIView]{
v.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(v)
}
self.prepareImageView()
}
// update
fileprivate func updateUI(){
self.imageView.image = self.object.image
self.prepareBorder()
}
// update border
func selected(){
self.object.selected = !self.object.selected
self.prepareBorder()
}
fileprivate func prepareBorder(){
if self.object.selected{
self.setBorder()
}else{
self.clearBorder()
}
}
fileprivate func setBorder(){
self.imageView.layer.borderColor = AZStyle.shared.sectionPhotoViewControllerImageSelectedTintColor.cgColor
self.imageView.layer.borderWidth = 2
}
fileprivate func clearBorder(){
self.imageView.layer.borderWidth = 0
}
}
// prepare
extension AZPhotoCollectionViewCell{
// image view
fileprivate func prepareImageView(){
_ = self.imageView.aZConstraints.parent(parent: self).top().right().left().bottom()
self.imageView.contentMode = .scaleAspectFill
self.imageView.clipsToBounds = true
}
}
| d4ab48339902eff238b171af3f86cbdc | 21.79 | 114 | 0.580079 | false | false | false | false |
ustwo/formvalidator-swift | refs/heads/master | Tests/Unit Tests/Conditions/Logic/OrConditionTests.swift | mit | 1 | //
// OrConditionTests.swift
// FormValidatorSwift
//
// Created by Aaron McTavish on 13/01/2016.
// Copyright © 2016 ustwo. All rights reserved.
//
import XCTest
@testable import FormValidatorSwift
final class OrConditionTests: XCTestCase {
let firstCondition = RangeCondition(configuration: ConfigurationSeeds.RangeSeeds.zeroToFour)
let secondCondition = AlphanumericCondition()
// MARK: - Test Initializers
func testOrCondition_DefaultInit() {
// Given
let condition = OrCondition()
let expectedCount = 1
// When
let actualCount = condition.conditions.count
// Test
XCTAssertEqual(actualCount,
expectedCount,
"Expected number of conditions to be: \(expectedCount) but found: \(actualCount)")
}
// MARK: - Test Success
func testOrCondition_Success() {
// Given
let testInput = ""
var condition = OrCondition(conditions: [firstCondition, secondCondition])
let expectedResult = true
// When
condition.localizedViolationString = "Min 0 Max 4 or must only contain alphanumeric"
// Initial Tests
AssertCondition(firstCondition, testInput: testInput, expectedResult: true)
AssertCondition(secondCondition, testInput: testInput, expectedResult: false)
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
// MARK: - Test Failure
func testOrCondition_Failure() {
// Given
let testInput = "1A234?"
var condition = OrCondition(conditions: [firstCondition, secondCondition])
let expectedResult = false
// When
condition.localizedViolationString = "Min 0 Max 4 or must only contain alphanumeric"
// Initial Tests
AssertCondition(firstCondition, testInput: testInput, expectedResult: false)
AssertCondition(secondCondition, testInput: testInput, expectedResult: false)
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
}
| 9ec82e67982fe46fed575a695d1774cf | 28.855263 | 105 | 0.626267 | false | true | false | false |
HongliYu/firefox-ios | refs/heads/master | Client/Frontend/Settings/SettingsTableViewController.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 Account
import Shared
import UIKit
struct SettingsUX {
static let TableViewHeaderFooterHeight = CGFloat(44)
}
extension UILabel {
// iOS bug: NSAttributed string color is ignored without setting font/color to nil
func assign(attributed: NSAttributedString?) {
guard let attributed = attributed else { return }
let attribs = attributed.attributes(at: 0, effectiveRange: nil)
if attribs[NSAttributedStringKey.foregroundColor] == nil {
// If the text color attribute isn't set, use the table view row text color.
textColor = UIColor.theme.tableView.rowText
} else {
textColor = nil
}
attributedText = attributed
}
}
// A base setting class that shows a title. You probably want to subclass this, not use it directly.
class Setting: NSObject {
fileprivate var _title: NSAttributedString?
fileprivate var _footerTitle: NSAttributedString?
fileprivate var _cellHeight: CGFloat?
fileprivate var _image: UIImage?
weak var delegate: SettingsDelegate?
// The url the SettingsContentViewController will show, e.g. Licenses and Privacy Policy.
var url: URL? { return nil }
// The title shown on the pref.
var title: NSAttributedString? { return _title }
var footerTitle: NSAttributedString? { return _footerTitle }
var cellHeight: CGFloat? { return _cellHeight}
fileprivate(set) var accessibilityIdentifier: String?
// An optional second line of text shown on the pref.
var status: NSAttributedString? { return nil }
// Whether or not to show this pref.
var hidden: Bool { return false }
var style: UITableViewCellStyle { return .subtitle }
var accessoryType: UITableViewCellAccessoryType { return .none }
var textAlignment: NSTextAlignment { return .natural }
var image: UIImage? { return _image }
fileprivate(set) var enabled: Bool = true
// Called when the cell is setup. Call if you need the default behaviour.
func onConfigureCell(_ cell: UITableViewCell) {
cell.detailTextLabel?.assign(attributed: status)
cell.detailTextLabel?.attributedText = status
cell.detailTextLabel?.numberOfLines = 0
cell.textLabel?.assign(attributed: title)
cell.textLabel?.textAlignment = textAlignment
cell.textLabel?.numberOfLines = 1
cell.textLabel?.lineBreakMode = .byTruncatingTail
cell.accessoryType = accessoryType
cell.accessoryView = nil
cell.selectionStyle = enabled ? .default : .none
cell.accessibilityIdentifier = accessibilityIdentifier
cell.imageView?.image = _image
if let title = title?.string {
if let detailText = cell.detailTextLabel?.text {
cell.accessibilityLabel = "\(title), \(detailText)"
} else if let status = status?.string {
cell.accessibilityLabel = "\(title), \(status)"
} else {
cell.accessibilityLabel = title
}
}
cell.accessibilityTraits = UIAccessibilityTraitButton
cell.indentationWidth = 0
cell.layoutMargins = .zero
// So that the separator line goes all the way to the left edge.
cell.separatorInset = .zero
if let cell = cell as? ThemedTableViewCell {
cell.applyTheme()
}
}
// Called when the pref is tapped.
func onClick(_ navigationController: UINavigationController?) { return }
// Helper method to set up and push a SettingsContentViewController
func setUpAndPushSettingsContentViewController(_ navigationController: UINavigationController?) {
if let url = self.url {
let viewController = SettingsContentViewController()
viewController.settingsTitle = self.title
viewController.url = url
navigationController?.pushViewController(viewController, animated: true)
}
}
init(title: NSAttributedString? = nil, footerTitle: NSAttributedString? = nil, cellHeight: CGFloat? = nil, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) {
self._title = title
self._footerTitle = footerTitle
self._cellHeight = cellHeight
self.delegate = delegate
self.enabled = enabled ?? true
}
}
// A setting in the sections panel. Contains a sublist of Settings
class SettingSection: Setting {
fileprivate let children: [Setting]
init(title: NSAttributedString? = nil, footerTitle: NSAttributedString? = nil, cellHeight: CGFloat? = nil, children: [Setting]) {
self.children = children
super.init(title: title, footerTitle: footerTitle, cellHeight: cellHeight)
}
var count: Int {
var count = 0
for setting in children where !setting.hidden {
count += 1
}
return count
}
subscript(val: Int) -> Setting? {
var i = 0
for setting in children where !setting.hidden {
if i == val {
return setting
}
i += 1
}
return nil
}
}
private class PaddedSwitch: UIView {
fileprivate static let Padding: CGFloat = 8
init(switchView: UISwitch) {
super.init(frame: .zero)
addSubview(switchView)
frame.size = CGSize(width: switchView.frame.width + PaddedSwitch.Padding, height: switchView.frame.height)
switchView.frame.origin = CGPoint(x: PaddedSwitch.Padding, y: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// A helper class for settings with a UISwitch.
// Takes and optional settingsDidChange callback and status text.
class BoolSetting: Setting {
let prefKey: String? // Sometimes a subclass will manage its own pref setting. In that case the prefkey will be nil
fileprivate let prefs: Prefs
fileprivate let defaultValue: Bool
fileprivate let settingDidChange: ((Bool) -> Void)?
fileprivate let statusText: NSAttributedString?
init(prefs: Prefs, prefKey: String? = nil, defaultValue: Bool, attributedTitleText: NSAttributedString, attributedStatusText: NSAttributedString? = nil, settingDidChange: ((Bool) -> Void)? = nil) {
self.prefs = prefs
self.prefKey = prefKey
self.defaultValue = defaultValue
self.settingDidChange = settingDidChange
self.statusText = attributedStatusText
super.init(title: attributedTitleText)
}
convenience init(prefs: Prefs, prefKey: String? = nil, defaultValue: Bool, titleText: String, statusText: String? = nil, settingDidChange: ((Bool) -> Void)? = nil) {
var statusTextAttributedString: NSAttributedString?
if let statusTextString = statusText {
statusTextAttributedString = NSAttributedString(string: statusTextString, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight])
}
self.init(prefs: prefs, prefKey: prefKey, defaultValue: defaultValue, attributedTitleText: NSAttributedString(string: titleText, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]), attributedStatusText: statusTextAttributedString, settingDidChange: settingDidChange)
}
override var status: NSAttributedString? {
return statusText
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitchThemed()
control.onTintColor = UIConstants.SystemBlueColor
control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)
control.accessibilityIdentifier = prefKey
displayBool(control)
if let title = title {
if let status = status {
control.accessibilityLabel = "\(title.string), \(status.string)"
} else {
control.accessibilityLabel = title.string
}
cell.accessibilityLabel = nil
}
cell.accessoryView = PaddedSwitch(switchView: control)
cell.selectionStyle = .none
}
@objc func switchValueChanged(_ control: UISwitch) {
writeBool(control)
settingDidChange?(control.isOn)
UnifiedTelemetry.recordEvent(category: .action, method: .change, object: .setting, value: self.prefKey, extras: ["to": control.isOn])
}
// These methods allow a subclass to control how the pref is saved
func displayBool(_ control: UISwitch) {
guard let key = prefKey else {
return
}
control.isOn = prefs.boolForKey(key) ?? defaultValue
}
func writeBool(_ control: UISwitch) {
guard let key = prefKey else {
return
}
prefs.setBool(control.isOn, forKey: key)
}
}
class PrefPersister: SettingValuePersister {
fileprivate let prefs: Prefs
let prefKey: String
init(prefs: Prefs, prefKey: String) {
self.prefs = prefs
self.prefKey = prefKey
}
func readPersistedValue() -> String? {
return prefs.stringForKey(prefKey)
}
func writePersistedValue(value: String?) {
if let value = value {
prefs.setString(value, forKey: prefKey)
} else {
prefs.removeObjectForKey(prefKey)
}
}
}
class StringPrefSetting: StringSetting {
init(prefs: Prefs, prefKey: String, defaultValue: String? = nil, placeholder: String, accessibilityIdentifier: String, settingIsValid isValueValid: ((String?) -> Bool)? = nil, settingDidChange: ((String?) -> Void)? = nil) {
super.init(defaultValue: defaultValue, placeholder: placeholder, accessibilityIdentifier: accessibilityIdentifier, persister: PrefPersister(prefs: prefs, prefKey: prefKey), settingIsValid: isValueValid, settingDidChange: settingDidChange)
}
}
class WebPageSetting: StringPrefSetting {
init(prefs: Prefs, prefKey: String, defaultValue: String? = nil, placeholder: String, accessibilityIdentifier: String, settingDidChange: ((String?) -> Void)? = nil) {
super.init(prefs: prefs,
prefKey: prefKey,
defaultValue: defaultValue,
placeholder: placeholder,
accessibilityIdentifier: accessibilityIdentifier,
settingIsValid: WebPageSetting.isURLOrEmpty,
settingDidChange: settingDidChange)
textField.keyboardType = .URL
textField.autocapitalizationType = .none
textField.autocorrectionType = .no
}
override func prepareValidValue(userInput value: String?) -> String? {
guard let value = value else {
return nil
}
return URIFixup.getURL(value)?.absoluteString
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.accessoryType = .checkmark
textField.textAlignment = .left
}
static func isURLOrEmpty(_ string: String?) -> Bool {
guard let string = string, !string.isEmpty else {
return true
}
return URL(string: string)?.isWebPage() ?? false
}
}
protocol SettingValuePersister {
func readPersistedValue() -> String?
func writePersistedValue(value: String?)
}
/// A helper class for a setting backed by a UITextField.
/// This takes an optional settingIsValid and settingDidChange callback
/// If settingIsValid returns false, the Setting will not change and the text remains red.
class StringSetting: Setting, UITextFieldDelegate {
var Padding: CGFloat = 15
fileprivate let defaultValue: String?
fileprivate let placeholder: String
fileprivate let settingDidChange: ((String?) -> Void)?
fileprivate let settingIsValid: ((String?) -> Bool)?
fileprivate let persister: SettingValuePersister
let textField = UITextField()
init(defaultValue: String? = nil, placeholder: String, accessibilityIdentifier: String, persister: SettingValuePersister, settingIsValid isValueValid: ((String?) -> Bool)? = nil, settingDidChange: ((String?) -> Void)? = nil) {
self.defaultValue = defaultValue
self.settingDidChange = settingDidChange
self.settingIsValid = isValueValid
self.placeholder = placeholder
self.persister = persister
super.init()
self.accessibilityIdentifier = accessibilityIdentifier
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if let id = accessibilityIdentifier {
textField.accessibilityIdentifier = id + "TextField"
}
if let placeholderColor = UIColor.theme.general.settingsTextPlaceholder {
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedStringKey.foregroundColor: placeholderColor])
} else {
textField.placeholder = placeholder
}
cell.tintColor = self.persister.readPersistedValue() != nil ? UIColor.theme.tableView.rowActionAccessory : UIColor.clear
textField.textAlignment = .center
textField.delegate = self
textField.tintColor = UIColor.theme.tableView.rowActionAccessory
textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
cell.isUserInteractionEnabled = true
cell.accessibilityTraits = UIAccessibilityTraitNone
cell.contentView.addSubview(textField)
textField.snp.makeConstraints { make in
make.height.equalTo(44)
make.trailing.equalTo(cell.contentView).offset(-Padding)
make.leading.equalTo(cell.contentView).offset(Padding)
}
textField.text = self.persister.readPersistedValue() ?? defaultValue
textFieldDidChange(textField)
}
override func onClick(_ navigationController: UINavigationController?) {
textField.becomeFirstResponder()
}
fileprivate func isValid(_ value: String?) -> Bool {
guard let test = settingIsValid else {
return true
}
return test(prepareValidValue(userInput: value))
}
/// This gives subclasses an opportunity to treat the user input string
/// before it is saved or tested.
/// Default implementation does nothing.
func prepareValidValue(userInput value: String?) -> String? {
return value
}
@objc func textFieldDidChange(_ textField: UITextField) {
let color = isValid(textField.text) ? UIColor.theme.tableView.rowText : UIColor.theme.general.destructiveRed
textField.textColor = color
}
@objc func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return isValid(textField.text)
}
@objc func textFieldDidEndEditing(_ textField: UITextField) {
let text = textField.text
if !isValid(text) {
return
}
self.persister.writePersistedValue(value: prepareValidValue(userInput: text))
// Call settingDidChange with text or nil.
settingDidChange?(text)
}
}
class CheckmarkSetting: Setting {
let onChanged: () -> Void
let isEnabled: () -> Bool
private let subtitle: NSAttributedString?
override var status: NSAttributedString? {
return subtitle
}
init(title: NSAttributedString, subtitle: NSAttributedString?, accessibilityIdentifier: String? = nil, isEnabled: @escaping () -> Bool, onChanged: @escaping () -> Void) {
self.subtitle = subtitle
self.onChanged = onChanged
self.isEnabled = isEnabled
super.init(title: title)
self.accessibilityIdentifier = accessibilityIdentifier
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.accessoryType = .checkmark
cell.tintColor = isEnabled() ? UIColor.theme.tableView.rowActionAccessory : UIColor.clear
}
override func onClick(_ navigationController: UINavigationController?) {
// Force editing to end for any focused text fields so they can finish up validation first.
navigationController?.view.endEditing(true)
if !isEnabled() {
onChanged()
}
}
}
/// A helper class for a setting backed by a UITextField.
/// This takes an optional isEnabled and mandatory onClick callback
/// isEnabled is called on each tableview.reloadData. If it returns
/// false then the 'button' appears disabled.
class ButtonSetting: Setting {
var Padding: CGFloat = 8
let onButtonClick: (UINavigationController?) -> Void
let destructive: Bool
let isEnabled: (() -> Bool)?
init(title: NSAttributedString?, destructive: Bool = false, accessibilityIdentifier: String, isEnabled: (() -> Bool)? = nil, onClick: @escaping (UINavigationController?) -> Void) {
self.onButtonClick = onClick
self.destructive = destructive
self.isEnabled = isEnabled
super.init(title: title)
self.accessibilityIdentifier = accessibilityIdentifier
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if isEnabled?() ?? true {
cell.textLabel?.textColor = destructive ? UIColor.theme.general.destructiveRed : UIColor.theme.general.highlightBlue
} else {
cell.textLabel?.textColor = UIColor.theme.tableView.disabledRowText
}
cell.textLabel?.snp.makeConstraints({ make in
make.height.equalTo(44)
make.trailing.equalTo(cell.contentView).offset(-Padding)
make.leading.equalTo(cell.contentView).offset(Padding)
})
cell.textLabel?.textAlignment = .center
cell.accessibilityTraits = UIAccessibilityTraitButton
cell.selectionStyle = .none
}
override func onClick(_ navigationController: UINavigationController?) {
// Force editing to end for any focused text fields so they can finish up validation first.
navigationController?.view.endEditing(true)
if isEnabled?() ?? true {
onButtonClick(navigationController)
}
}
}
// A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to
// the fxAccount happen.
class AccountSetting: Setting, FxAContentViewControllerDelegate {
unowned var settings: SettingsTableViewController
var profile: Profile {
return settings.profile
}
override var title: NSAttributedString? { return nil }
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if settings.profile.getAccount() != nil {
cell.selectionStyle = .none
}
}
override var accessoryType: UITableViewCellAccessoryType { return .none }
func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags flags: FxALoginFlags) {
// This method will get called twice: once when the user signs in, and once
// when the account is verified by email – on this device or another.
// If the user hasn't dismissed the fxa content view controller,
// then we should only do that (thus finishing the sign in/verification process)
// once the account is verified.
// By the time we get to here, we should be syncing or just about to sync in the
// background, most likely from FxALoginHelper.
if flags.verified {
_ = settings.navigationController?.popToRootViewController(animated: true)
// Reload the data to reflect the new Account immediately.
settings.tableView.reloadData()
// And start advancing the Account state in the background as well.
settings.refresh()
}
}
func contentViewControllerDidCancel(_ viewController: FxAContentViewController) {
NSLog("didCancel")
_ = settings.navigationController?.popToRootViewController(animated: true)
}
}
class WithAccountSetting: AccountSetting {
override var hidden: Bool { return !profile.hasAccount() }
}
class WithoutAccountSetting: AccountSetting {
override var hidden: Bool { return profile.hasAccount() }
}
@objc
protocol SettingsDelegate: AnyObject {
func settingsOpenURLInNewTab(_ url: URL)
}
// The base settings view controller.
class SettingsTableViewController: ThemedTableViewController {
typealias SettingsGenerator = (SettingsTableViewController, SettingsDelegate?) -> [SettingSection]
fileprivate let Identifier = "CellIdentifier"
fileprivate let SectionHeaderIdentifier = "SectionHeaderIdentifier"
var settings = [SettingSection]()
weak var settingsDelegate: SettingsDelegate?
var profile: Profile!
var tabManager: TabManager!
var hasSectionSeparatorLine = true
/// Used to calculate cell heights.
fileprivate lazy var dummyToggleCell: UITableViewCell = {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "dummyCell")
cell.accessoryView = UISwitchThemed()
return cell
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Identifier)
tableView.register(ThemedTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
tableView.tableFooterView = UIView(frame: CGRect(width: view.frame.width, height: 30))
tableView.estimatedRowHeight = 44
tableView.estimatedSectionHeaderHeight = 44
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
settings = generateSettings()
NotificationCenter.default.addObserver(self, selector: #selector(syncDidChangeState), name: .ProfileDidStartSyncing, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(syncDidChangeState), name: .ProfileDidFinishSyncing, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(firefoxAccountDidChange), name: .FirefoxAccountChanged, object: nil)
applyTheme()
}
override func applyTheme() {
settings = generateSettings()
super.applyTheme()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
refresh()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
[Notification.Name.ProfileDidStartSyncing, Notification.Name.ProfileDidFinishSyncing, Notification.Name.FirefoxAccountChanged].forEach { name in
NotificationCenter.default.removeObserver(self, name: name, object: nil)
}
}
// Override to provide settings in subclasses
func generateSettings() -> [SettingSection] {
return []
}
@objc fileprivate func syncDidChangeState() {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
@objc fileprivate func refresh() {
// Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app.
if let account = self.profile.getAccount() {
account.advance().upon { state in
DispatchQueue.main.async { () -> Void in
self.tableView.reloadData()
}
}
} else {
self.tableView.reloadData()
}
}
@objc func firefoxAccountDidChange() {
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
let cell = ThemedTableViewCell(style: setting.style, reuseIdentifier: nil)
setting.onConfigureCell(cell)
cell.backgroundColor = UIColor.theme.tableView.rowBackground
return cell
}
return super.tableView(tableView, cellForRowAt: indexPath)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return settings.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = settings[section]
return section.count
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as? ThemedTableSectionHeaderFooterView else {
return nil
}
let sectionSetting = settings[section]
if let sectionTitle = sectionSetting.title?.string {
headerView.titleLabel.text = sectionTitle.uppercased()
}
// Hide the top border for the top section to avoid having a double line at the top
if section == 0 || !hasSectionSeparatorLine {
headerView.showTopBorder = false
} else {
headerView.showTopBorder = true
}
headerView.applyTheme()
return headerView
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let sectionSetting = settings[section]
guard let sectionFooter = sectionSetting.footerTitle?.string,
let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as? ThemedTableSectionHeaderFooterView else {
return nil
}
footerView.titleLabel.text = sectionFooter
footerView.titleAlignment = .top
footerView.showBottomBorder = false
footerView.applyTheme()
return footerView
}
// To hide a footer dynamically requires returning nil from viewForFooterInSection
// and setting the height to zero.
// However, we also want the height dynamically calculated, there is a magic constant
// for that: `UITableViewAutomaticDimension`.
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let sectionSetting = settings[section]
if let _ = sectionSetting.footerTitle?.string {
return UITableViewAutomaticDimension
}
return 0
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let section = settings[indexPath.section]
// Workaround for calculating the height of default UITableViewCell cells with a subtitle under
// the title text label.
if let setting = section[indexPath.row], setting is BoolSetting && setting.status != nil {
return calculateStatusCellHeightForSetting(setting)
}
if let setting = section[indexPath.row], let height = setting.cellHeight {
return height
}
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let section = settings[indexPath.section]
if let setting = section[indexPath.row], setting.enabled {
setting.onClick(navigationController)
}
}
fileprivate func calculateStatusCellHeightForSetting(_ setting: Setting) -> CGFloat {
dummyToggleCell.layoutSubviews()
let topBottomMargin: CGFloat = 10
let width = dummyToggleCell.contentView.frame.width - 2 * dummyToggleCell.separatorInset.left
return
heightForLabel(dummyToggleCell.textLabel!, width: width, text: setting.title?.string) +
heightForLabel(dummyToggleCell.detailTextLabel!, width: width, text: setting.status?.string) +
2 * topBottomMargin
}
fileprivate func heightForLabel(_ label: UILabel, width: CGFloat, text: String?) -> CGFloat {
guard let text = text else { return 0 }
let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let attrs = [NSAttributedStringKey.font: label.font as Any]
let boundingRect = NSString(string: text).boundingRect(with: size,
options: .usesLineFragmentOrigin, attributes: attrs, context: nil)
return boundingRect.height
}
}
| be02eba66359f2a5915ae266c7320733 | 37.90625 | 309 | 0.677283 | false | false | false | false |
prebid/prebid-mobile-ios | refs/heads/master | InternalTestApp/PrebidMobileDemoRendering/Model/TestCase.swift | apache-2.0 | 1 | /* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
//This enum is used to create labels for Test Cases and filter
enum TestCaseTag : String, Comparable {
// MARK: - Tags
//Connection
case server = "📡"
//Appearance
case banner = "Banner"
case interstitial = "Interstitial"
case video = "Video"
case mraid = "MRAID"
case native = "Native"
//SDK (Integration)
case inapp = "In-App"
case gam = "GAM"
case admob = "AdMob"
case max = "MAX"
// MARK: - Group
static var connections: [TestCaseTag] {
return [ .server]
}
static var appearance: [TestCaseTag] {
return [.banner, .interstitial, .video, .mraid, .native]
}
static var integrations: [TestCaseTag] {
return [.inapp, .gam, .admob, .max]
}
// MARK: - Util methods
// Returns only "appearance" tags that present in the input array
static func extractAppearances(from tags: [TestCaseTag]) -> [TestCaseTag] {
return collectTags(from: TestCaseTag.appearance, in: tags)
}
// Returns only "integrations" tags that present in the input array
static func extractIntegrations(from tags: [TestCaseTag]) -> [TestCaseTag] {
return collectTags(from: TestCaseTag.integrations, in: tags)
}
// Returns only "connections" tags that present in the input array
static func extractConnections(from tags: [TestCaseTag]) -> [TestCaseTag] {
return collectTags(from: TestCaseTag.connections, in: tags)
}
// Returns intersection of two arrays of tags
// We need a sorted list to have consistent appearance in UI
static func collectTags(from targetTags: [TestCaseTag], in tags: [TestCaseTag]) -> [TestCaseTag] {
return tags
.intersection(targetTags)
.sorted(by: <=)
}
static func <(lhs: TestCaseTag, rhs: TestCaseTag) -> Bool {
return lhs.rawValue <= rhs.rawValue
}
}
struct TestCase {
let title: String
let tags: [TestCaseTag]
let exampleVCStoryboardID: String
let configurationClosure: ((_ vc: UIViewController) -> Void)?
func byAdding(tag: TestCaseTag) -> TestCase {
return TestCase(title: title,
tags: tags + [tag],
exampleVCStoryboardID: exampleVCStoryboardID,
configurationClosure: configurationClosure)
}
}
struct TestCaseForTableCell {
let configurationClosureForTableCell: ((_ cell: inout UITableViewCell?) -> Void)?
}
| ef01ddb9a421b4729049778d9b656b6f | 29.77451 | 102 | 0.648933 | false | true | false | false |
domenicosolazzo/practice-swift | refs/heads/master | Apps/VendingMachine/VendingMachine/VendingMachine.swift | apache-2.0 | 3 | //
// VendingMachine.swift
// VendingMachine
//
// Created by Pasan Premaratne on 1/23/16.
// Copyright © 2016 Treehouse. All rights reserved.
//
import Foundation
import UIKit
// Protocols
protocol VendingMachineType {
var selection: [VendingSelection] { get }
var inventory: [VendingSelection: ItemType] { get set }
var amountDeposited: Double { get set }
init(inventory: [VendingSelection: ItemType])
func vend(_ selection: VendingSelection, quantity: Double) throws
func deposit(_ amount: Double)
func itemForCurrentSelection(_ selection: VendingSelection) -> ItemType?
}
protocol ItemType {
var price: Double { get }
var quantity: Double { get set }
}
// Error Types
enum InventoryError: Error {
case invalidResource
case conversionError
case invalidKey
}
enum VendingMachineError: Error {
case invalidSelection
case outOfStock
case insufficientFunds(required: Double)
}
// Helper Classes
class PlistConverter {
class func dictionaryFromFile(_ resource: String, ofType type: String) throws -> [String : AnyObject] {
guard let path = Bundle.main.path(forResource: resource, ofType: type) else {
throw InventoryError.invalidResource
}
guard let dictionary = NSDictionary(contentsOfFile: path),
let castDictionary = dictionary as? [String: AnyObject] else {
throw InventoryError.conversionError
}
return castDictionary
}
}
class InventoryUnarchiver {
class func vendingInventoryFromDictionary(_ dictionary: [String : AnyObject]) throws -> [VendingSelection : ItemType] {
var inventory: [VendingSelection : ItemType] = [:]
for (key, value) in dictionary {
if let itemDict = value as? [String : Double],
let price = itemDict["price"], let quantity = itemDict["quantity"] {
let item = VendingItem(price: price, quantity: quantity)
guard let key = VendingSelection(rawValue: key) else {
throw InventoryError.invalidKey
}
inventory.updateValue(item, forKey: key)
}
}
return inventory
}
}
// Concrete Types
enum VendingSelection: String {
case Soda
case DietSoda
case Chips
case Cookie
case Sandwich
case Wrap
case CandyBar
case PopTart
case Water
case FruitJuice
case SportsDrink
case Gum
func icon() -> UIImage {
if let image = UIImage(named: self.rawValue) {
return image
} else {
return UIImage(named: "Default")!
}
}
}
struct VendingItem: ItemType {
let price: Double
var quantity: Double
}
class VendingMachine: VendingMachineType {
let selection: [VendingSelection] = [.Soda, .DietSoda, .Chips, .Cookie, .Sandwich, .Wrap, .CandyBar, .PopTart, .Water, .FruitJuice, .SportsDrink, .Gum]
var inventory: [VendingSelection: ItemType]
var amountDeposited: Double = 10.0
required init(inventory: [VendingSelection : ItemType]) {
self.inventory = inventory
}
func vend(_ selection: VendingSelection, quantity: Double) throws {
guard var item = inventory[selection] else {
throw VendingMachineError.invalidSelection
}
guard item.quantity > 0 else {
throw VendingMachineError.outOfStock
}
item.quantity -= quantity
inventory.updateValue(item, forKey: selection)
let totalPrice = item.price * quantity
if amountDeposited >= totalPrice {
amountDeposited -= totalPrice
} else {
let amountRequired = totalPrice - amountDeposited
throw VendingMachineError.insufficientFunds(required: amountRequired)
}
}
func itemForCurrentSelection(_ selection: VendingSelection) -> ItemType? {
return inventory[selection]
}
func deposit(_ amount: Double) {
amountDeposited += amount
}
}
| 3bd7e2519af31b528dae178a8c03d2db | 23.08 | 155 | 0.616516 | false | false | false | false |
Ramotion/adaptive-tab-bar | refs/heads/master | adaptive-tab-bar/AdaptiveController/AdaptiveController/AdaptiveDateState.swift | mit | 1 | //
// AdaptiveDateState.swift
// AdaptiveTabBarControllerSample
//
// Created by Arcilite on 18.09.14.
// Copyright (c) 2014 Ramotion. All rights reserved.
//
import UIKit
public let kSmallTitleAdaptiveState = "kImageAdaptiveState"
public let kImageAdaptiveState = "kNormalImageAdaptiveState"
public class AdaptiveDateState: AdaptiveState {
public override init() {
super.init()
super.addNewCustomAdaptiveStates(customAdaptiveStates: [kSmallTitleAdaptiveState, kImageAdaptiveState])
}
public convenience init(installDate: Date, currentDate: Date, countDaysToSmallTextState: Int, countDaysToImageState: Int) {
self.init()
let remainsDays = daysBetweenDates(installDate: installDate, currentDate: currentDate)
currentItemState = stateRemainDays(remainDays: remainsDays, countDaysToSmallTextState: countDaysToSmallTextState, countDaysToImageState: countDaysToImageState)
}
func daysBetweenDates(installDate: Date, currentDate: Date) -> Int {
let units = Set<Calendar.Component>([.day])
let components = NSCalendar.current.dateComponents(units, from: installDate, to: currentDate)
return (components.day ?? 0) + 1
}
func stateRemainDays(remainDays: Int, countDaysToSmallTextState: Int, countDaysToImageState: Int) -> String {
var mode: String = kDefaultAdaptiveState
if remainDays > countDaysToSmallTextState && remainDays < countDaysToImageState {
mode = kSmallTitleAdaptiveState
} else if remainDays > countDaysToImageState {
mode = kImageAdaptiveState
}
return mode
}
}
| 61f6e3422e34475c455db6a2be75af6a | 37.162791 | 167 | 0.728215 | false | false | false | false |
artsy/eidolon | refs/heads/master | Kiosk/Bid Fulfillment/BidDetailsPreviewView.swift | mit | 2 | import UIKit
import Artsy_UILabels
import Artsy_UIButtons
import UIImageViewAligned
import RxSwift
import RxCocoa
class BidDetailsPreviewView: UIView {
let _bidDetails = Variable<BidDetails?>(nil)
var bidDetails: BidDetails? {
didSet {
self._bidDetails.value = bidDetails
}
}
@objc dynamic let artworkImageView = UIImageViewAligned()
@objc dynamic let artistNameLabel = ARSansSerifLabel()
@objc dynamic let artworkTitleLabel = ARSerifLabel()
@objc dynamic let currentBidPriceLabel = ARSerifLabel()
override func awakeFromNib() {
self.backgroundColor = .white
artistNameLabel.numberOfLines = 1
artworkTitleLabel.numberOfLines = 1
currentBidPriceLabel.numberOfLines = 1
artworkImageView.alignRight = true
artworkImageView.alignBottom = true
artworkImageView.contentMode = .scaleAspectFit
artistNameLabel.font = UIFont.sansSerifFont(withSize: 14)
currentBidPriceLabel.font = UIFont.serifBoldFont(withSize: 14)
let artwork = _bidDetails
.asObservable()
.filterNil()
.map { bidDetails in
return bidDetails.saleArtwork?.artwork
}
.take(1)
artwork
.subscribe(onNext: { [weak self] artwork in
if let url = artwork?.defaultImage?.thumbnailURL() {
self?.bidDetails?.setImage(url, self!.artworkImageView)
} else {
self?.artworkImageView.image = nil
}
})
.disposed(by: rx.disposeBag)
artwork
.map { artwork in
return artwork?.artists?.first?.name
}
.map { name in
return name ?? ""
}
.bind(to: artistNameLabel.rx.text)
.disposed(by: rx.disposeBag)
artwork
.map { artwork -> NSAttributedString in
guard let artwork = artwork else {
return NSAttributedString()
}
return artwork.titleAndDate
}
.mapToOptional()
.bind(to: artworkTitleLabel.rx.attributedText)
.disposed(by: rx.disposeBag)
_bidDetails
.asObservable()
.filterNil()
.take(1)
.map { bidDetails in
guard let cents = bidDetails.bidAmountCents.value else { return "" }
guard let currencySymbol = bidDetails.saleArtwork?.currencySymbol else { return "" }
return "Your bid: " + centsToPresentableDollarsString(cents.currencyValue, currencySymbol: currencySymbol)
}
.bind(to: currentBidPriceLabel.rx.text)
.disposed(by: rx.disposeBag)
for subview in [artworkImageView, artistNameLabel, artworkTitleLabel, currentBidPriceLabel] {
self.addSubview(subview)
}
self.constrainHeight("60")
artworkImageView.alignTop("0", leading: "0", bottom: "0", trailing: nil, to: self)
artworkImageView.constrainWidth("84")
artworkImageView.constrainHeight("60")
artistNameLabel.alignAttribute(.top, to: .top, of: self, predicate: "0")
artistNameLabel.constrainHeight("16")
artworkTitleLabel.alignAttribute(.top, to: .bottom, of: artistNameLabel, predicate: "8")
artworkTitleLabel.constrainHeight("16")
currentBidPriceLabel.alignAttribute(.top, to: .bottom, of: artworkTitleLabel, predicate: "4")
currentBidPriceLabel.constrainHeight("16")
UIView.alignAttribute(.leading, ofViews: [artistNameLabel, artworkTitleLabel, currentBidPriceLabel], to:.trailing, ofViews: [artworkImageView, artworkImageView, artworkImageView], predicate: "20")
UIView.alignAttribute(.trailing, ofViews: [artistNameLabel, artworkTitleLabel, currentBidPriceLabel], to:.trailing, ofViews: [self, self, self], predicate: "0")
}
}
| 36d28bf915e44a78ee6562d8f27ff6ad | 35.387387 | 204 | 0.611538 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV | refs/heads/master | PopcornTime/UI/tvOS/Presentation Controllers/TVFadeToBlackAnimatedTransitioning.swift | gpl-3.0 | 1 |
import Foundation
typealias PreloadTorrentViewControllerAnimatedTransitioning = TVFadeToBlackAnimatedTransitioning
class TVFadeToBlackAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
let isPresenting: Bool
init(isPresenting: Bool) {
self.isPresenting = isPresenting
super.init()
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 1.0
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
isPresenting ? animatePresentationWithTransitionContext(transitionContext) : animateDismissalWithTransitionContext(transitionContext)
}
func animatePresentationWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
guard
let presentedControllerView = transitionContext.view(forKey: .to)
else {
return
}
transitionContext.containerView.addSubview(presentedControllerView)
presentedControllerView.frame = transitionContext.containerView.bounds
presentedControllerView.isHidden = true
let view = UIView(frame: transitionContext.containerView.bounds)
view.backgroundColor = .black
view.alpha = 0.0
transitionContext.containerView.addSubview(view)
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .curveEaseIn, animations: {
view.alpha = 1.0
}, completion: { completed in
view.removeFromSuperview()
presentedControllerView.isHidden = false
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
func animateDismissalWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning) {
guard
let presentingControllerView = transitionContext.view(forKey: .to),
let presentedControllerView = transitionContext.view(forKey: .from)
else {
return
}
transitionContext.containerView.addSubview(presentingControllerView)
transitionContext.containerView.addSubview(presentedControllerView)
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .curveEaseOut, animations: {
presentedControllerView.alpha = 0.0
}, completion: { _ in
presentedControllerView.removeFromSuperview()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
| 730fdfd27922cd184e02a2eb62e220f2 | 40.426471 | 189 | 0.70962 | false | false | false | false |
snakajima/vs-metal | refs/heads/master | src/VSContext.swift | mit | 1 | //
// VSContext.swift
// vs-metal
//
// Created by SATOSHI NAKAJIMA on 6/22/17.
// Copyright © 2017 SATOSHI NAKAJIMA. All rights reserved.
//
import Foundation
import AVFoundation
import MetalKit
import MetalPerformanceShaders
// A wrapper of MTLTexture so that we can compare
struct VSTexture:Equatable {
/// Metal texture
let texture:MTLTexture
let identity:Int
let sampleBuffer:CMSampleBuffer?
public static func ==(lhs: VSTexture, rhs: VSTexture) -> Bool {
return lhs.identity == rhs.identity
}
/// VSRuntime:encode() will call this function in the completion handler.
public func touchSampleBuffer() {
if let buffer = sampleBuffer {
let _ = CMSampleBufferGetPresentationTimeStamp(buffer)
}
}
}
/// VSContext object manages the context of video pipeline for a VSRuntime object,
/// such as texture stack and pixel format.
class VSContext: NSObject {
/// Metal device
let device:MTLDevice
/// Metal library
lazy var library:MTLLibrary = self.device.newDefaultLibrary()!
/// The pixel format of texture
var pixelFormat = MTLPixelFormat.bgra8Unorm
/// texture for output (to prevent recycling)
var textureOut:VSTexture?
/// Becomes true when a source texture is updated
private(set) var hasUpdate = false
/// The default group size for Metal shaders
let threadGroupSize = MTLSizeMake(16,16,1)
/// The default group count for Metal shaders
private(set) var threadGroupCount = MTLSizeMake(1, 1, 1) // to be filled later
private struct NamedBuffer {
let key:String
let buffer:MTLBuffer
}
private let commandQueue: MTLCommandQueue
private var namedBuffers = [NamedBuffer]()
private var width = 1, height = 1 // to be set later
private var descriptor = MTLTextureDescriptor()
private var sourceTexture:VSTexture?
private var stack = [VSTexture]() // main texture stack
private var pool = [VSTexture]() // texture pool for reuse
private var prevs = [VSTexture]() // layers from previous session
private var retained = [VSTexture]() // layers retained by the app
private var frameCount = 0 // only for debugging
private var skippedFrameCount = 0 // only for debugging
/// Initializer
///
/// - Parameter device: Metal context
init(device:MTLDevice) {
self.device = device
commandQueue = device.makeCommandQueue()
}
deinit {
print("VSContext:frame skip rate = ", skippedFrameCount, frameCount, Float(skippedFrameCount) / Float(frameCount))
}
var texturesInStack:[VSTexture] {
return self.stack
}
/// This function set the video source
///
/// - Parameters:
/// - texture: metal texture
/// - sampleBuffer: sample buffer the metal texture was created from (optional)
func set(texture:MTLTexture, sampleBuffer sampleBufferIn:CMSampleBuffer?) {
assert(Thread.current == Thread.main)
// For the very first time
if width != texture.width || height != texture.height {
width = texture.width
height = texture.height
// Paranoia
stack.removeAll()
pool.removeAll()
prevs.removeAll()
descriptor.textureType = .type2D
descriptor.pixelFormat = pixelFormat
descriptor.width = width
descriptor.height = height
descriptor.usage = [.shaderRead, .shaderWrite]
threadGroupCount.width = (width + threadGroupSize.width - 1) / threadGroupSize.width
threadGroupCount.height = (height + threadGroupSize.height - 1) / threadGroupSize.height
}
frameCount += 1 // debug only
if (hasUpdate) {
// Previous texture has not been processed yet. Ignore the new frame.
skippedFrameCount += 1 // debug only
return
}
hasUpdate = true
assert(stack.count < 10) // to detect texture leak (a few is fine for recurring pipeline)
// NOTE: We need to retain the sample buffer (if any) until GPU finishes using it.
// See VSRuntime.encode() for more details.
sourceTexture = VSTexture(texture:texture, identity:-1, sampleBuffer: sampleBufferIn)
push(texture:sourceTexture!)
}
/// Pop a texture from the texture stack
///
/// - Returns: a texture to be processed by Metal
/// - Throws: VSContextError.underUnderflow when the stack is empty
func pop() -> VSTexture? {
if let texture = stack.popLast() {
return texture
}
return nil
}
/// Pop a texture from the previous frame.
///
/// - Returns: a texture from the previous frame
func prev() -> VSTexture {
if let texture = prevs.popLast() {
return texture
}
print("VSContext: prev returning source")
return sourceTexture!
}
/// Push a texture into the texture stack
///
/// - Parameter texture: a texture
func push(texture:VSTexture) {
stack.append(texture)
}
/// Pop the top most texture and insert it at the bottom of stack
func shift() {
if let texture = stack.popLast() {
stack.insert(texture, at: 0)
}
}
/// Return a texture appropriate to write to.
///
/// - Returns: a texture
func get() -> VSTexture {
// Find a texture in the pool, which is not in the stack
for texture in pool {
if !stack.contains(texture) && !prevs.contains(texture) && !retained.contains(texture) && (textureOut==nil || texture != textureOut!) {
return texture
}
}
print("VSContext:get, making a new Texture", pool.count)
let ret = VSTexture(texture:device.makeTexture(descriptor: descriptor), identity:pool.count, sampleBuffer: nil)
pool.append(ret)
return ret
}
/// Moves all the remaining texture in the current stack to the previous stack,
/// and resets the hasUpdate property.
func flush() {
hasUpdate = false
prevs = stack
stack.removeAll()
}
/// Makes a command buffer for nodes the video pipeline to use
///
/// - Returns: a command buffer
func makeCommandBuffer(label labelIn:String? = nil) -> MTLCommandBuffer {
let commandBuffer = commandQueue.makeCommandBuffer()
if let label = labelIn {
commandBuffer.label = label
}
return commandBuffer
}
/// Register a named buffer for a NSNode object
///
/// - Parameters:
/// - key: name of the buffer
/// - buffer: buffer (array of Float)
func registerNamedBuffer(key:String, buffer:MTLBuffer) {
print("VSContext:registerNamedBuffer", key)
namedBuffers.append(NamedBuffer(key:key, buffer:buffer))
}
/// Update the values of named buffer
///
/// - Parameter dictionary: a dictionary of names and Float values
func updateNamedBuffers(with dictionary:[String:[Float]]) {
for buffer in namedBuffers {
if let values = dictionary[buffer.key] {
let length = MemoryLayout.size(ofValue: values[0]) * values.count
if length <= buffer.buffer.length {
memcpy(buffer.buffer.contents(), values, length)
}
}
}
}
func retain(texture:VSTexture) {
retained.append(texture)
}
func release(texture:VSTexture) {
if let index = retained.index(of: texture) {
retained.remove(at: index)
} else {
print("VSContext:release #### no texture")
}
}
func retainedTextureCount() -> Int {
return retained.count
}
func releaseAllRetainedTextures() {
retained.removeAll()
}
}
extension VSContext: VSCaptureSessionDelegate {
func didCaptureOutput(session:VSCaptureSession, texture:MTLTexture, sampleBuffer:CMSampleBuffer, presentationTime:CMTime) {
self.set(texture: texture, sampleBuffer: sampleBuffer)
}
}
| 107cc3b45e28ddba1f68715b3333a249 | 32.088 | 147 | 0.617988 | false | false | false | false |
chicio/HackerRank | refs/heads/master | 30DaysOfCode/Day22BinarySearchTrees.swift | mit | 1 | //
// Day22BinarySearchTrees.swift
// HackerRank
//
// Created by Fabrizio Duroni on 09/10/2016.
//
// https://www.hackerrank.com/challenges/30-binary-search-trees
import Foundation
// Start of Node class
class Node {
var data: Int
var left: Node?
var right: Node?
init(d : Int) {
data = d
}
} // End of Node class
// Start of Tree class
class Tree {
func insert(root: Node?, data: Int) -> Node? {
if root == nil {
return Node(d: data)
}
if data <= (root?.data)! {
root?.left = insert(root: root?.left, data: data)
} else {
root?.right = insert(root: root?.right, data: data)
}
return root
}
func getHeight(root: Node?) -> Int {
if let rootNode = root {
let left:Int = getHeight(root: rootNode.left)
let right:Int = getHeight(root: rootNode.right)
if left > right {
return left + 1
} else {
return right + 1
}
} else {
return -1
}
}
}
var root: Node?
var tree = Tree()
var t = Int(readLine()!)!
while t > 0 {
root = tree.insert(root: root, data: Int(readLine()!)!)
t = t - 1
}
print(tree.getHeight(root: root))
| 44ff534753976bd400508fc5f11c99b9 | 18.210526 | 64 | 0.458219 | false | false | false | false |
darina/omim | refs/heads/master | iphone/Maps/Core/Theme/Renderers/UITableViewRenderer.swift | apache-2.0 | 5 | extension UITableView {
@objc override func applyTheme() {
if styleName.isEmpty {
styleName = "TableView"
}
for style in StyleManager.shared.getStyle(styleName)
where !style.isEmpty && !style.hasExclusion(view: self) {
UITableViewRenderer.render(self, style: style)
}
}
}
class UITableViewRenderer: UIViewRenderer {
class func render(_ control: UITableView, style: Style) {
super.render(control, style: style)
if let backgroundColor = style.backgroundColor {
control.backgroundView = UIImageView(image: backgroundColor.getImage())
}
if let separatorColor = style.separatorColor {
control.separatorColor = separatorColor
}
UIViewRenderer.renderBorder(control, style: style)
UIViewRenderer.renderShadow(control, style: style)
}
}
| b90fd8f01d715d7510cdd07fd8cbe218 | 31.44 | 77 | 0.710234 | false | false | false | false |
Maaimusic/BTree | refs/heads/master | Sources/BTreeIndex.swift | mit | 1 | //
// BTreeIndex.swift
// BTree
//
// Created by Károly Lőrentey on 2016-02-11.
// Copyright © 2015–2017 Károly Lőrentey.
//
/// An index into a collection that uses a B-tree for storage.
///
/// BTree indices belong to a specific tree instance. Trying to use them with any other tree
/// instance (including one holding the exact same elements, or one derived from a mutated version of the
/// original instance) will cause a runtime error.
///
/// This index satisfies `Collection`'s requirement for O(1) access, but
/// it is only suitable for read-only processing -- most tree mutations will
/// invalidate all existing indexes.
///
/// - SeeAlso: `BTreeCursor` for an efficient way to modify a batch of values in a B-tree.
public struct BTreeIndex<Key: Comparable, Value> {
typealias Node = BTreeNode<Key, Value>
typealias State = BTreeWeakPath<Key, Value>
@usableFromInline internal private(set) var state: State
@usableFromInline internal init(_ state: State) {
self.state = state
}
/// Advance to the next index.
///
/// - Requires: self is valid and not the end index.
/// - Complexity: Amortized O(1).
@usableFromInline mutating func increment() {
state.moveForward()
}
/// Advance to the previous index.
///
/// - Requires: self is valid and not the start index.
/// - Complexity: Amortized O(1).
@usableFromInline mutating func decrement() {
state.moveBackward()
}
/// Advance this index by `distance` elements.
///
/// - Complexity: O(log(*n*)) where *n* is the number of elements in the tree.
@usableFromInline mutating func advance(by distance: Int) {
state.move(toOffset: state.offset + distance)
}
@discardableResult
@usableFromInline mutating func advance(by distance: Int, limitedBy limit: BTreeIndex) -> Bool {
let originalDistance = limit.state.offset - state.offset
if (distance >= 0 && originalDistance >= 0 && distance > originalDistance)
|| (distance <= 0 && originalDistance <= 0 && distance < originalDistance) {
self = limit
return false
}
state.move(toOffset: state.offset + distance)
return true
}
}
extension BTreeIndex: Comparable {
/// Return true iff `a` is equal to `b`.
@inlinable public static func ==(a: BTreeIndex, b: BTreeIndex) -> Bool {
precondition(a.state.root === b.state.root, "Indices to different trees cannot be compared")
return a.state.offset == b.state.offset
}
/// Return true iff `a` is less than `b`.
@inlinable public static func <(a: BTreeIndex, b: BTreeIndex) -> Bool {
precondition(a.state.root === b.state.root, "Indices to different trees cannot be compared")
return a.state.offset < b.state.offset
}
}
/// A mutable path in a B-tree, holding weak references to nodes on the path.
/// This path variant does not support modifying the tree itself; it is suitable for use in indices.
///
/// After a path of this kind has been created, the original tree might mutated in a way that invalidates
/// the path, setting some of its weak references to nil, or breaking the consistency of its trail of slot indices.
/// The path checks for this during navigation, and traps if it finds itself invalidated.
///
@usableFromInline internal struct BTreeWeakPath<Key: Comparable, Value>: BTreePath {
typealias Node = BTreeNode<Key, Value>
@usableFromInline var _root: Weak<Node>
@usableFromInline var offset: Int
@usableFromInline var _path: [Weak<Node>]
@usableFromInline var _slots: [Int]
@usableFromInline var _node: Weak<Node>
@usableFromInline var slot: Int?
@usableFromInline init(root: Node) {
self._root = Weak(root)
self.offset = root.count
self._path = []
self._slots = []
self._node = Weak(root)
self.slot = nil
}
@usableFromInline var root: Node {
guard let root = _root.value else { invalid() }
return root
}
@usableFromInline var count: Int { return root.count }
@usableFromInline var length: Int { return _path.count + 1}
@usableFromInline var node: Node {
guard let node = _node.value else { invalid() }
return node
}
@usableFromInline internal func expectRoot(_ root: Node) {
expectValid(_root.value === root)
}
@usableFromInline internal func expectValid(_ expression: @autoclosure () -> Bool, file: StaticString = #file, line: UInt = #line) {
precondition(expression(), "Invalid BTreeIndex", file: file, line: line)
}
@usableFromInline internal func invalid(_ file: StaticString = #file, line: UInt = #line) -> Never {
preconditionFailure("Invalid BTreeIndex", file: file, line: line)
}
@usableFromInline mutating func popFromSlots() {
assert(self.slot != nil)
let node = self.node
offset += node.count - node.offset(ofSlot: slot!)
slot = nil
}
@usableFromInline mutating func popFromPath() {
assert(_path.count > 0 && slot == nil)
let child = node
_node = _path.removeLast()
expectValid(node.children[_slots.last!] === child)
slot = _slots.removeLast()
}
@usableFromInline mutating func pushToPath() {
assert(self.slot != nil)
let child = node.children[slot!]
_path.append(_node)
_node = Weak(child)
_slots.append(slot!)
slot = nil
}
@usableFromInline mutating func pushToSlots(_ slot: Int, offsetOfSlot: Int) {
assert(self.slot == nil)
offset -= node.count - offsetOfSlot
self.slot = slot
}
@usableFromInline func forEach(ascending: Bool, body: (Node, Int) -> Void) {
if ascending {
var child: Node? = node
body(child!, slot!)
for i in (0 ..< _path.count).reversed() {
guard let node = _path[i].value else { invalid() }
let slot = _slots[i]
expectValid(node.children[slot] === child)
child = node
body(node, slot)
}
}
else {
for i in 0 ..< _path.count {
guard let node = _path[i].value else { invalid() }
let slot = _slots[i]
expectValid(node.children[slot] === (i < _path.count - 1 ? _path[i + 1].value : _node.value))
body(node, slot)
}
body(node, slot!)
}
}
@usableFromInline func forEachSlot(ascending: Bool, body: (Int) -> Void) {
if ascending {
body(slot!)
_slots.reversed().forEach(body)
}
else {
_slots.forEach(body)
body(slot!)
}
}
}
| 033b00236ed79fe7abcca4ade512e00e | 34.180412 | 136 | 0.61304 | false | false | false | false |
chris-wood/reveiller | refs/heads/master | Pods/SwiftCharts/SwiftCharts/Views/ChartPointTextCircleView.swift | apache-2.0 | 5 | //
// ChartPointTextCircleView.swift
// swift_charts
//
// Created by ischuetz on 14/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public class ChartPointTextCircleView: UILabel {
private let targetCenter: CGPoint
public var viewTapped: ((ChartPointTextCircleView) -> ())?
public var selected: Bool = false {
didSet {
if self.selected {
self.textColor = UIColor.whiteColor()
self.layer.borderColor = UIColor.whiteColor().CGColor
self.layer.backgroundColor = UIColor.blackColor().CGColor
} else {
self.textColor = UIColor.blackColor()
self.layer.borderColor = UIColor.blackColor().CGColor
self.layer.backgroundColor = UIColor.whiteColor().CGColor
}
}
}
public init(chartPoint: ChartPoint, center: CGPoint, diameter: CGFloat, cornerRadius: CGFloat, borderWidth: CGFloat, font: UIFont) {
self.targetCenter = center
super.init(frame: CGRectMake(0, center.y - diameter / 2, diameter, diameter))
self.textColor = UIColor.blackColor()
self.text = chartPoint.text
self.font = font
self.layer.cornerRadius = cornerRadius
self.layer.borderWidth = borderWidth
self.textAlignment = NSTextAlignment.Center
self.layer.borderColor = UIColor.grayColor().CGColor
let c = UIColor(red: 1, green: 1, blue: 1, alpha: 0.85)
self.layer.backgroundColor = c.CGColor
self.userInteractionEnabled = true
}
override public func didMoveToSuperview() {
super.didMoveToSuperview()
UIView.animateWithDuration(0.7, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: {
let w: CGFloat = self.frame.size.width
let h: CGFloat = self.frame.size.height
let frame = CGRectMake(self.targetCenter.x - (w/2), self.targetCenter.y - (h/2), w, h)
self.frame = frame
}, completion: {finished in})
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
viewTapped?(self)
}
}
| 1d6f93b2a575f7df17d3dcd103d8860b | 33.394366 | 153 | 0.615479 | false | false | false | false |
Constructor-io/constructorio-client-swift | refs/heads/master | AutocompleteClient/FW/API/Parser/Browse/BrowseResponseParser.swift | mit | 1 | //
// BrowseResponseParser.swift
// AutocompleteClient
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import Foundation
class BrowseResponseParser: AbstractBrowseResponseParser {
func parse(browseResponseData: Data) throws -> CIOBrowseResponse {
do {
let json = try JSONSerialization.jsonObject(with: browseResponseData) as? JSONObject
guard let response = json?["response"] as? JSONObject else {
throw CIOError(errorType: .invalidResponse)
}
let facetsObj: [JSONObject]? = response["facets"] as? [JSONObject]
let resultsObj: [JSONObject]? = response["results"] as? [JSONObject]
let sortOptionsObj: [JSONObject]? = response["sort_options"] as? [JSONObject]
let groupsObj = response["groups"] as? [JSONObject]
let facets: [CIOFilterFacet] = (facetsObj)?.compactMap { obj in return CIOFilterFacet(json: obj) } ?? []
let results: [CIOResult] = (resultsObj)?.compactMap { obj in return CIOResult(json: obj) } ?? []
let sortOptions: [CIOSortOption] = (sortOptionsObj)?.compactMap({ obj in return CIOSortOption(json: obj) }) ?? []
let groups: [CIOFilterGroup] = groupsObj?.compactMap({ obj in return CIOFilterGroup(json: obj) }) ?? []
let totalNumResults = response["total_num_results"] as? Int ?? 0
let collection: CIOCollectionData? = CIOCollectionData(json: response["collection"] as? JSONObject)
let resultID = json?["result_id"] as? String ?? ""
let resultSources: CIOResultSources? = CIOResultSources(json: response["result_sources"] as? JSONObject)
return CIOBrowseResponse(
facets: facets,
groups: groups,
results: results,
sortOptions: sortOptions,
totalNumResults: totalNumResults,
resultID: resultID,
collection: collection,
resultSources: resultSources
)
} catch {
throw CIOError(errorType: .invalidResponse)
}
}
}
| 5476a2b6d058251d26607ff03cfc56e6 | 42.28 | 126 | 0.613216 | false | false | false | false |
che1404/RGViperChat | refs/heads/master | RGViperChat/Chat/Presenter/ChatPresenterSpec.swift | mit | 1 | //
// Created by Roberto Garrido
// Copyright (c) 2017 Roberto Garrido. All rights reserved.
//
// swiftlint:disable function_body_length
import Quick
import Nimble
import Cuckoo
@testable import RGViperChat
class ChatPresenterSpec: QuickSpec {
var presenter: ChatPresenter!
var mockView: MockChatViewProtocol!
var mockWireframe: MockChatWireframeProtocol!
var mockInteractor: MockChatInteractorInputProtocol!
var chat: Chat!
let messageText = "message"
let date = Date()
let senderID = "senderID"
let senderDisplayName = "senderDisplayName"
var message: Message!
override func spec() {
beforeEach {
self.mockInteractor = MockChatInteractorInputProtocol()
self.mockView = MockChatViewProtocol()
self.mockWireframe = MockChatWireframeProtocol()
self.presenter = ChatPresenter()
self.chat = Chat(chatID: "chatID", displayName: "displayName", senderID: "senderID", senderDisplayName: "senderDisplayName", receiverID: "receiverID", lastMessage: "last message")
self.presenter.chat = self.chat
self.presenter.view = self.mockView
self.presenter.wireframe = self.mockWireframe
self.presenter.interactor = self.mockInteractor
self.message = Message(senderID: self.senderID, senderDisplayName: self.senderDisplayName, text: self.messageText, date: self.date)
}
context("When the view gets loaded") {
beforeEach {
stub(self.mockInteractor) { mock in
when(mock).startListeningIncomingMessages(fromChat: any()).thenDoNothing()
}
stub(self.mockView) { mock in
when(mock).showChatTitle(title: any()).thenDoNothing()
}
self.presenter.viewWasLoaded()
}
it("Shows the receiver display name as title") {
verify(self.mockView).showChatTitle(title: equal(to: self.chat.displayName))
}
it("Selects the start listening incoming messages use case on the interactor") {
verify(self.mockInteractor).startListeningIncomingMessages(fromChat: equal(to: self.chat, equalWhen: ==))
}
}
context("When send button was tapped") {
beforeEach {
stub(self.mockInteractor) { mock in
when(mock).send(message: any(), toChat: any()).thenDoNothing()
}
self.presenter.didPressSend(withMessageText: self.messageText, date: self.date, senderID: self.senderID, senderDisplayName: self.senderDisplayName)
}
it("Sends a message using the interactor") {
verify(self.mockInteractor).send(message: equal(to: self.message), toChat: equal(to: self.chat, equalWhen: ==))
}
}
context("When a message is received") {
beforeEach {
stub(self.mockView) { mock in
when(mock).add(message: any()).thenDoNothing()
}
self.presenter.messageReceived(message: self.message)
}
it("Add it to the view") {
verify(self.mockView).add(message: equal(to: self.message))
}
}
context("When the back button is tapped") {
beforeEach {
stub(self.mockInteractor) { mock in
when(mock).stopListeningIncomingMessages().thenDoNothing()
}
stub(self.mockWireframe) { mock in
when(mock).dismissChatModule().thenDoNothing()
}
self.presenter.backButtonTapped()
}
it("Stops listening for incoming messages") {
verify(self.mockInteractor).stopListeningIncomingMessages()
}
it("Dismisses the module") {
verify(self.mockWireframe).dismissChatModule()
}
}
context("When a message was successfully sent") {
beforeEach {
stub(self.mockView) { mock in
when(mock).dofinishSendingMessage().thenDoNothing()
}
stub(self.mockView) { mock in
when(mock).playMessageSuccessfullySentSound().thenDoNothing()
}
self.presenter.messageSuccessfullySent()
}
it("Finishes sending the message") {
verify(self.mockView).dofinishSendingMessage()
}
it("Plays a sent sound") {
verify(self.mockView).playMessageSuccessfullySentSound()
}
}
afterEach {
self.chat = nil
self.mockInteractor = nil
self.mockView = nil
self.mockWireframe = nil
self.presenter.view = nil
self.presenter.wireframe = nil
self.presenter.interactor = nil
self.presenter = nil
}
}
}
| ff8c06bf3c8e105fca2fc38734b1f39b | 34.482517 | 191 | 0.574103 | false | false | false | false |
mercadopago/px-ios | refs/heads/develop | MercadoPagoSDK/MercadoPagoSDK/PXSpruce/Animations/PXDefaultAnimations.swift | mit | 1 | import UIKit
/// Direction that a slide animation should use.
///
/// - up: start the view below its current position, and then slide upwards to where it currently is
/// - down: start the view above its current position, and then slide downwards to where it currently is
/// - left: start the view to the right of its current position, and then slide left to where it currently is
/// - right: start the view to the left of its current position, and then slide right to where it currently is
enum SlideDirection {
/// start the view below its current position, and then slide upwards to where it currently is
case up
/// start the view above its current position, and then slide downwards to where it currently is
case down
/// start the view to the right of its current position, and then slide left to where it currently is
case left
/// start the view to the left of its current position, and then slide right to where it currently is
case right
}
/// How much the angle of an animation should change. This value changes based off of which type of `StockAnimation` is used.
///
/// - slightly: slightly animate the object
/// - moderately: the object should move a moderate amount
/// - severely: the object should move very noticeably
/// - toAngle: provide your own angle value that you feel the object should rotate
enum Angle {
/// slightly animate the object
case slightly
/// the object should move a moderate amount
case moderately
/// the object should move very noticeably
case severely
/// provide your own value that you feel the object should move. The value you should provide should be a `Double`
case toAngle(CGFloat)
}
/// How much the scale of an animation should change. This value changes based off of which type of `StockAnimation` is used.
///
/// - slightly: slightly animate the object
/// - moderately: the object should scale a moderate amount
/// - severely: the object should scale very noticeably
/// - toScale: provide your own scale value that you feel the object should grow/shrink
enum Scale {
/// slightly animate the object
case slightly
/// the object should scale a moderate amount
case moderately
/// the object should scale very noticeably
case severely
/// provide your own scale value that you feel the object should grow/shrink
case toScale(CGFloat)
}
/// How much the distance of a view animation should change. This value changes based off of which type of `StockAnimation` is used.
///
/// - slightly: slightly move the object
/// - moderately: the object should move a moderate amount
/// - severely: the object should move very noticeably
/// - byPoints: provide your own distance value that you feel the object should slide over
enum Distance {
/// slightly move the object
case slightly
/// the object should move a moderate amount
case moderately
/// the object should move very noticeably
case severely
/// provide your own distance value that you feel the object should slide over
case byPoints(CGFloat)
}
/// A few stock animations that you can use with Spruce. We want to make it really easy for you to include animations so we tried to include the basics. Use these stock animations to `slide`, `fade`, `spin`, `expand`, or `contract` your views.
enum StockAnimation {
/// Have your view slide to where it currently is. Provide a `SlideDirection` and `Size` to determine what the animation should look like.
case slide(SlideDirection, Distance)
/// Fade the view in
case fadeIn
/// Spin the view in the direction of the size. Provide a `Size` to define how much the view should spin
case spin(Angle)
/// Have the view grow in size. Provide a `Size` to define by which scale the view should grow
case expand(Scale)
/// Have the view shrink in size. Provide a `Size` to define by which scale the view should shrink
case contract(Scale)
/// Provide custom prepare and change functions for the view to animate
case custom(prepareFunction: PrepareHandler, animateFunction: ChangeFunction)
/// Given the `StockAnimation`, how should Spruce prepare your view for animation. Since we want all of the views to end the animation where they are supposed to be positioned, we have to reverse their animation effect.
var prepareFunction: PrepareHandler {
get {
switch self {
case .slide:
let offset = slideOffset
return { view in
let currentTransform = view.transform
let offsetTransform = CGAffineTransform(translationX: offset.x, y: offset.y)
view.transform = currentTransform.concatenating(offsetTransform)
}
case .fadeIn:
return { view in
view.alpha = 0.0
}
case .spin:
let angle = spinAngle
return { view in
let currentTransform = view.transform
let spinTransform = CGAffineTransform(rotationAngle: angle)
view.transform = currentTransform.concatenating(spinTransform)
}
case .expand, .contract:
let scale = self.scale
return { view in
let currentTransform = view.transform
let scaleTransform = CGAffineTransform(scaleX: scale, y: scale)
view.transform = currentTransform.concatenating(scaleTransform)
}
case .custom(let prepare, _):
return prepare
}
}
}
/// Reset any of the transforms on the view so that the view will end up in its original position. If a `custom` animation is used, then that animation `ChangeFunction` is returned.
var animationFunction: ChangeFunction {
get {
switch self {
case .slide:
return { view in
view.transform = CGAffineTransform(translationX: 0.0, y: 0.0)
}
case .fadeIn:
return { view in
view.alpha = 1.0
}
case .spin:
return { view in
view.transform = CGAffineTransform(rotationAngle: 0.0)
}
case .expand, .contract:
return { view in
view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}
case .custom(_, let animation):
return animation
}
}
}
/// Given the animation is a `slide`, return the slide offset
var slideOffset: CGPoint {
get {
switch self {
case .slide(let direction, let size):
switch (direction, size) {
case (.up, .slightly):
return CGPoint(x: 0.0, y: 10.0)
case (.up, .moderately):
return CGPoint(x: 0.0, y: 30.0)
case (.up, .severely):
return CGPoint(x: 0.0, y: 50.0)
case (.up, .byPoints(let value)):
return CGPoint(x: 0.0, y: -value)
case (.down, .slightly):
return CGPoint(x: 0.0, y: -10.0)
case (.down, .moderately):
return CGPoint(x: 0.0, y: -30.0)
case (.down, .severely):
return CGPoint(x: 0.0, y: -50.0)
case (.down, .byPoints(let value)):
return CGPoint(x: 0.0, y: -value)
case (.left, .slightly):
return CGPoint(x: 10.0, y: 0.0)
case (.left, .moderately):
return CGPoint(x: 30.0, y: 0.0)
case (.left, .severely):
return CGPoint(x: 50.0, y: 0.0)
case (.left, .byPoints(let value)):
return CGPoint(x: -value, y: 0.0)
case (.right, .slightly):
return CGPoint(x: -10.0, y: 0.0)
case (.right, .moderately):
return CGPoint(x: -30.0, y: 0.0)
case (.right, .severely):
return CGPoint(x: -50.0, y: 0.0)
case (.right, .byPoints(let value)):
return CGPoint(x: -value, y: 0.0)
}
default:
return CGPoint.zero
}
}
}
/// Given the animation is a `spin`, then this will return the angle that the view should spin.
var spinAngle: CGFloat {
get {
switch self {
case .spin(let size):
switch size {
case .slightly:
return CGFloat(Double.pi / 4)
case .moderately:
return CGFloat(Double.pi / 2)
case .severely:
return CGFloat(Double.pi)
case .toAngle(let value):
return value
}
default:
return 0.0
}
}
}
/// Given the animation is either `expand` or `contract`, this will return the scale from which the view should grow/shrink
var scale: CGFloat {
switch self {
case .contract(let size):
switch size {
case .slightly:
return 1.1
case .moderately:
return 1.3
case .severely:
return 1.5
case .toScale(let value):
return value
}
case .expand(let size):
switch size {
case .slightly:
return 0.9
case .moderately:
return 0.7
case .severely:
return 0.5
case .toScale(let value):
return value
}
default:
return 0.0
}
}
}
| 2f44ef8d1989b92834b5fb694374a777 | 37.822394 | 243 | 0.569269 | false | false | false | false |
googlearchive/gcm-playground | refs/heads/master | ios/GCM Playground/ViewController.swift | apache-2.0 | 1 | // Copyright Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
let registerNewClient: String = "register_new_client"
let unregisterClient: String = "unregister_client"
let statusRegistered: String = "registered"
let statusUnegistered: String = "unregistered"
let keyAction: String = "action"
let keyStatus: String = "status"
let keyRegistrationToken: String = "registration_token"
let keyStringIdentifier: String = "stringIdentifier"
let gcmAddress: String = "@gcm.googleapis.com"
let topicPrefix: String = "/topics/"
let identifierPlaceholder: String = "<a_name_to_recognize_the_device>"
@IBOutlet weak var registrationStatus: UITextView!
@IBOutlet weak var stringIdentifierField: UITextField!
@IBOutlet weak var downstreamPayloadField: UITextView!
@IBOutlet weak var registerButton: UIButton!
@IBOutlet weak var unregisterButton: UIButton!
@IBOutlet weak var progressIndicator: UIActivityIndicatorView!
@IBOutlet weak var topicNameField: UITextField!
@IBOutlet weak var topicSubscribeButton: UIButton!
@IBOutlet weak var upstreamMessageField: UITextField!
@IBOutlet weak var upstreamMessageSendButton: UIButton!
var apnsToken: NSData!
var token: String = ""
var appDelegate: AppDelegate!
var stringIdentifier: String?
var registrationOptions = [String: AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
// iOS registered the device and sent a token
NSNotificationCenter.defaultCenter().addObserver(self, selector: "saveApnsToken:",
name: appDelegate.apnsRegisteredKey, object: nil)
// Got a new GCM reg token
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateRegistrationStatus:",
name: appDelegate.registrationKey, object: nil)
// GCM Token needs to be refreshed
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onTokenRefresh:",
name: appDelegate.tokenRefreshKey, object: nil)
// New message received
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleReceivedMessage:",
name: appDelegate.messageKey, object: nil)
self.stringIdentifierField.delegate = self
self.topicNameField.delegate = self
self.upstreamMessageField.delegate = self
self.stringIdentifierField.text = identifierPlaceholder
}
// Hide the keyboard when click on "Return" or "Done" or similar
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
////////////////////////////////////////
// Actions (Listeners)
////////////////////////////////////////
// Register button click handler.
@IBAction func registerClient(sender: UIButton) {
// Get the fields values
stringIdentifier = stringIdentifierField.text
// Validate field values
if (stringIdentifier == "") {
showAlert("Invalid input", message: "Please provide an identifier for your device.")
return
}
progressIndicator.startAnimating()
// Register with GCM and get token
let instanceIDConfig = GGLInstanceIDConfig.defaultConfig()
instanceIDConfig.delegate = appDelegate
GGLInstanceID.sharedInstance().startWithConfig(instanceIDConfig)
registrationOptions = [kGGLInstanceIDRegisterAPNSOption:apnsToken,
kGGLInstanceIDAPNSServerTypeSandboxOption:true]
GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(appDelegate.senderId!,
scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
}
// Unregister button click handler.
@IBAction func unregisterFromAppServer(sender: UIButton) {
let message = [keyAction: unregisterClient, keyRegistrationToken: token]
progressIndicator.startAnimating()
sendMessage(message)
}
// Topic field editing handler.
@IBAction func topicChangeHandler(sender: UITextField) {
let userInput = topicNameField.text
if (userInput != "") {
topicSubscribeButton.enabled = true
} else {
topicSubscribeButton.enabled = false
}
}
// Send upstream message button handler.
@IBAction func sendUpstreamMessage(sender: UIButton) {
let text = upstreamMessageField.text!
if (text == "") {
showAlert("Can't send message", message: "Please enter a message to send")
return
}
let message = ["message": text]
sendMessage(message)
showAlert("Message sent successfully", message: "")
}
// Subscribe to topic button handler.
@IBAction func subscribeToTopic(sender: UIButton) {
let topic = topicNameField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// Topic must begin with "/topics/" and have a name after the prefix
if (topic == "" || !topic.hasPrefix(topicPrefix) || topic.characters.count <= topicPrefix.characters.count) {
showAlert("Invalid topic name", message: "Make sure topic is in format \"/topics/topicName\"")
return
}
GCMPubSub.sharedInstance().subscribeWithToken(token, topic: topic,
options: nil, handler: {(NSError error) -> Void in
if (error != nil) {
// Error 3001 is "already subscribed". Treat as success.
if error.code == 3001 {
print("Already subscribed to \(topic)")
self.updateUI("Subscribed to topic \(topic)", registered: true)
} else {
print("Subscription failed: \(error.localizedDescription)");
self.updateUI("Subscription failed for topic \(topic)", registered: false)
}
} else {
NSLog("Subscribed to \(topic)");
self.updateUI("Subscribed to topic \(topic)", registered: true)
}
})
}
// Make it easier to delete that giant placeholder text. :)
@IBAction func identifierDidBeginEditing(sender: UITextField) {
print ("Sender text is \(sender.text)")
if sender.text == identifierPlaceholder {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
sender.selectAll(self)
})
}
}
////////////////////////////////////////
// Utility functions
////////////////////////////////////////
// Save the iOS APNS token
func saveApnsToken(notification: NSNotification) {
if let info = notification.userInfo as? Dictionary<String,NSData> {
if let deviceToken = info["deviceToken"] {
apnsToken = deviceToken
} else {
print("Could not decode the NSNotification that contains APNS token.")
}
} else {
print("Could not decode the NSNotification userInfo that contains APNS token.")
}
}
// Got a new GCM registration token
func updateRegistrationStatus(notification: NSNotification) {
if let info = notification.userInfo as? Dictionary<String,String> {
if let error = info["error"] {
registrationError(error)
} else if let regToken = info["registrationToken"] {
updateUI("Registration SUCCEEDED", registered: true)
}
} else {
print("Software failure.")
}
}
// Show the passed error message on the UI
func registrationError(error: String) {
updateUI("Registration FAILED", registered: false)
showAlert("Error registering with GCM", message: error)
}
// GCM token should be refreshed
func onTokenRefresh() {
// A rotation of the registration tokens is happening, so the app needs to request a new token.
print("The GCM registration token needs to be changed.")
GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(appDelegate.senderId!,
scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler)
}
// Callback for GCM registration
func registrationHandler(registrationToken: String!, error: NSError!) {
if (registrationToken != nil) {
token = registrationToken
print("Registration Token: \(registrationToken)")
registerWithAppServer()
} else {
print("Registration to GCM failed with error: \(error.localizedDescription)")
registrationError(error.localizedDescription)
}
}
// Handles a new downstream message.
func handleReceivedMessage(notification: NSNotification) {
progressIndicator.stopAnimating()
if let info = notification.userInfo as? Dictionary<String,AnyObject> {
if let action = info[keyAction] as? String {
if let status = info[keyStatus] as? String {
// We have an action and status
if (action == registerNewClient && status == statusRegistered) {
self.updateUI("Registration COMPLETE!", registered: true)
topicSubscribeButton.enabled = true
return
} else if (action == unregisterClient && status == statusUnegistered) {
token = ""
updateUI("Unregistration COMPLETE!", registered: false)
return
}
}
}
downstreamPayloadField.text = info.description
} else {
print("Software failure. Guru meditation.")
}
}
// Calls the app server to register the current reg token.
func registerWithAppServer() {
let message = [keyAction: registerNewClient, keyRegistrationToken: token, keyStringIdentifier: stringIdentifierField.text!]
sendMessage(message)
}
// Sends an upstream message.
func sendMessage(message: NSDictionary) {
// The resolution for timeIntervalSince1970 is in millisecond. So this will work
// when you are sending no more than 1 message per millisecond.
// To use in production, there should be a database of all used IDs to make sure
// we don't use an already-used ID.
let nextMessageID: String = NSDate().timeIntervalSince1970.description
let to: String = appDelegate.senderId! + gcmAddress
GCMService.sharedInstance().sendMessage(message as [NSObject : AnyObject], to: to, withId: nextMessageID)
}
////////////////////////////////////////
// UI functions
////////////////////////////////////////
func updateUI(status: String, registered: Bool) {
// Set status and token text
registrationStatus.text = status
// Button enabling
registerButton.enabled = !registered
unregisterButton.enabled = registered
// Topic and upstream message field
topicNameField.enabled = registered
upstreamMessageField.enabled = registered
upstreamMessageSendButton.enabled = registered
}
// Shows a toast with passed text.
func showAlert(title:String, message:String) {
let alert = UIAlertController(title: title,
message: message, preferredStyle: .Alert)
let dismissAction = UIAlertAction(title: "Dismiss", style: .Destructive, handler: nil)
alert.addAction(dismissAction)
self.presentViewController(alert, animated: true, completion: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
| f40c9f4b3854f03ed97b117e894cee4e | 35.503165 | 127 | 0.692935 | false | false | false | false |
superk589/CGSSGuide | refs/heads/master | DereGuide/View/UpdatingStatusView.swift | mit | 2 | //
// UpdatingStatusView.swift
// DereGuide
//
// Created by zzk on 16/7/22.
// Copyright © 2016 zzk. All rights reserved.
//
import UIKit
import SnapKit
protocol UpdatingStatusViewDelegate: class {
func cancelUpdate(updateStatusView: UpdatingStatusView)
}
class UpdatingStatusView: UIView {
weak var delegate: UpdatingStatusViewDelegate?
let statusLabel = UILabel()
private let loadingView = LoadingImageView()
let cancelButton = UIButton()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
layer.cornerRadius = 10
loadingView.hideWhenStopped = true
addSubview(loadingView)
loadingView.snp.makeConstraints { (make) in
make.left.equalTo(5)
make.centerY.equalToSuperview()
make.width.height.equalTo(40)
}
cancelButton.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
cancelButton.setImage(#imageLiteral(resourceName: "433-x").withRenderingMode(.alwaysTemplate), for: UIControl.State())
cancelButton.tintColor = .white
cancelButton.layer.cornerRadius = 10
cancelButton.layer.masksToBounds = true
cancelButton.addTarget(self, action: #selector(cancelUpdate), for: .touchUpInside)
addSubview(cancelButton)
cancelButton.snp.makeConstraints { (make) in
make.centerY.equalToSuperview()
make.width.height.equalTo(40)
make.right.equalTo(-5)
}
statusLabel.textColor = .white
addSubview(statusLabel)
statusLabel.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.left.equalTo(loadingView.snp.right)
make.right.equalTo(cancelButton.snp.left)
}
statusLabel.textAlignment = .center
statusLabel.font = UIFont.boldSystemFont(ofSize: 17)
statusLabel.adjustsFontSizeToFitWidth = true
statusLabel.baselineAdjustment = .alignCenters
}
private var isShowing = false
func show() {
isShowing = true
stopFading()
if let window = UIApplication.shared.keyWindow {
window.addSubview(self)
snp.remakeConstraints { (make) in
make.width.equalTo(240)
make.height.equalTo(50)
make.centerX.equalToSuperview()
make.centerY.equalToSuperview().offset(-95)
}
}
}
func hide(animated: Bool) {
isShowing = false
stopAnimating()
cancelButton.isHidden = true
if animated {
layer.removeAllAnimations()
UIView.animate(withDuration: 2.5, animations: { [weak self] in
self?.alpha = 0
}) { [weak self] (finished) in
self?.alpha = 1
if let strongSelf = self, !strongSelf.isShowing {
self?.removeFromSuperview()
}
}
} else {
removeFromSuperview()
}
}
private var isAnimating = false
private func startAnimating() {
isAnimating = true
loadingView.startAnimating()
}
private func stopAnimating() {
isAnimating = false
loadingView.stopAnimating()
}
private func stopFading() {
layer.removeAllAnimations()
}
func setup(_ text: String, animated: Bool, cancelable: Bool) {
if animated && !isAnimating {
startAnimating()
}
statusLabel.text = text
cancelButton.isHidden = !cancelable
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func cancelUpdate() {
stopAnimating()
hide(animated: false)
delegate?.cancelUpdate(updateStatusView: self)
}
}
| 4696d96370b220f0c035e073117a7a61 | 29.503817 | 126 | 0.600601 | false | false | false | false |
alexzatsepin/omim | refs/heads/master | iphone/Maps/Bookmarks/Categories/Sharing/BookmarksSharingViewController.swift | apache-2.0 | 1 | import SafariServices
@objc
protocol BookmarksSharingViewControllerDelegate: AnyObject {
func didShareCategory()
}
final class BookmarksSharingViewController: MWMTableViewController {
@objc var category: MWMCategory!
@objc weak var delegate: BookmarksSharingViewControllerDelegate?
private var sharingTags: [MWMTag]?
private var sharingUserStatus: MWMCategoryAuthorType?
private var manager: MWMBookmarksManager {
return MWMBookmarksManager.shared()
}
private let kPropertiesControllerIdentifier = "chooseProperties"
private let kTagsControllerIdentifier = "tags"
private let kNameControllerIdentifier = "guideName"
private let kDescriptionControllerIdentifier = "guideDescription"
private let kEditOnWebSegueIdentifier = "editOnWeb"
private let privateSectionIndex = 0
private let publicSectionIndex = 1
private let editOnWebSectionIndex = 2
private let rowsInEditOnWebSection = 1
private let directLinkUpdateRowIndex = 2
private let publishUpdateRowIndex = 2
private var rowsInPublicSection: Int {
return (category.accessStatus == .public && uploadAndPublishCell.cellState != .updating) ? 3 : 2
}
private var rowsInPrivateSection: Int {
return (category.accessStatus == .private && getDirectLinkCell.cellState != .updating) ? 3 : 2
}
@IBOutlet weak var uploadAndPublishCell: UploadActionCell!
@IBOutlet weak var getDirectLinkCell: UploadActionCell!
@IBOutlet weak var updatePublishCell: UITableViewCell!
@IBOutlet weak var updateDirectLinkCell: UITableViewCell!
@IBOutlet weak var directLinkInstructionsLabel: UILabel!
@IBOutlet weak var editOnWebButton: UIButton! {
didSet {
editOnWebButton.setTitle(L("edit_on_web").uppercased(), for: .normal)
}
}
@IBOutlet private weak var licenseAgreementTextView: UITextView! {
didSet {
let htmlString = String(coreFormat: L("ugc_routes_user_agreement"),
arguments: [MWMAuthorizationViewModel.termsOfUseLink()])
let attributes: [NSAttributedStringKey : Any] = [NSAttributedStringKey.font: UIFont.regular14(),
NSAttributedStringKey.foregroundColor: UIColor.blackSecondaryText()]
licenseAgreementTextView.attributedText = NSAttributedString.string(withHtml: htmlString,
defaultAttributes: attributes)
licenseAgreementTextView.delegate = self
}
}
override func viewDidLoad() {
super.viewDidLoad()
assert(category != nil, "We can't share nothing")
title = L("sharing_options")
configureActionCells()
switch category.accessStatus {
case .local:
break
case .public:
getDirectLinkCell.cellState = .disabled
uploadAndPublishCell.cellState = .completed
directLinkInstructionsLabel.text = L("unable_get_direct_link_desc")
case .private:
getDirectLinkCell.cellState = .completed
case .authorOnly:
break
case .other:
break
}
}
private func configureActionCells() {
uploadAndPublishCell.config(titles: [ .normal : L("upload_and_publish"),
.inProgress : L("upload_and_publish_progress_text"),
.updating : L("direct_link_updating_text"),
.completed : L("upload_and_publish_success") ],
image: UIImage(named: "ic24PxGlobe"),
delegate: self)
getDirectLinkCell.config(titles: [ .normal : L("upload_and_get_direct_link"),
.inProgress : L("direct_link_progress_text"),
.updating : L("direct_link_updating_text"),
.completed : L("direct_link_success"),
.disabled : L("upload_and_publish_success")],
image: UIImage(named: "ic24PxLink"),
delegate: self)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case publicSectionIndex:
return rowsInPublicSection
case privateSectionIndex:
return rowsInPrivateSection
case editOnWebSectionIndex:
return rowsInEditOnWebSection
default:
return 0
}
}
override func tableView(_ tableView: UITableView,
titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return L("limited_access")
case 1:
return L("public_access")
case 2:
return L("edit_on_web")
default:
return nil
}
}
override func tableView(_ tableView: UITableView,
willSelectRowAt indexPath: IndexPath) -> IndexPath? {
let cell = tableView.cellForRow(at: indexPath)
if cell == getDirectLinkCell && getDirectLinkCell.cellState != .normal
|| cell == uploadAndPublishCell && uploadAndPublishCell.cellState != .normal {
return nil
}
return indexPath
}
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath)
if cell == uploadAndPublishCell {
startUploadAndPublishFlow()
} else if cell == getDirectLinkCell {
uploadAndGetDirectLink(update: false)
} else if cell == updatePublishCell {
updatePublic()
} else if cell == updateDirectLinkCell {
updateDirectLink()
}
}
private func updatePublic() {
MWMAlertViewController.activeAlert().presentDefaultAlert(withTitle: L("any_access_update_alert_title"),
message: L("any_access_update_alert_message"),
rightButtonTitle: L("any_access_update_alert_update"),
leftButtonTitle: L("cancel")) {
self.uploadAndPublish(update: true)
}
}
private func updateDirectLink() {
MWMAlertViewController.activeAlert().presentDefaultAlert(withTitle: L("any_access_update_alert_title"),
message: L("any_access_update_alert_message"),
rightButtonTitle: L("any_access_update_alert_update"),
leftButtonTitle: L("cancel")) {
self.uploadAndGetDirectLink(update: true)
}
}
private func startUploadAndPublishFlow() {
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatPublic])
let alert = EditOnWebAlertViewController(with: L("bookmark_public_upload_alert_title"),
message: L("bookmark_public_upload_alert_subtitle"),
acceptButtonTitle: L("bookmark_public_upload_alert_ok_button"))
alert.onAcceptBlock = { [unowned self] in
self.dismiss(animated: true)
self.performAfterValidation(anchor: self.uploadAndPublishCell) { [weak self] in
if let self = self {
if (self.category.trackCount + self.category.bookmarksCount > 2) {
self.showEditName()
} else {
MWMAlertViewController.activeAlert().presentInfoAlert(L("error_public_not_enought_title"),
text: L("error_public_not_enought_subtitle"))
}
}
}
}
alert.onCancelBlock = { [unowned self] in self.dismiss(animated: true) }
present(alert, animated: true)
}
private func uploadAndPublish(update: Bool) {
if !update {
guard let tags = sharingTags, let userStatus = sharingUserStatus else {
assert(false, "not enough data for public sharing")
return
}
manager.setCategory(category.categoryId, authorType: userStatus)
manager.setCategory(category.categoryId, tags: tags)
}
uploadAndPublishCell.cellState = update ? .updating : .inProgress
if update {
self.tableView.deleteRows(at: [IndexPath(row: self.publishUpdateRowIndex,
section: self.publicSectionIndex)],
with: .automatic)
}
manager.uploadAndPublishCategory(withId: category.categoryId, progress: nil) { (_, error) in
if let error = error as NSError? {
self.uploadAndPublishCell.cellState = .normal
self.showErrorAlert(error)
} else {
self.uploadAndPublishCell.cellState = .completed
Statistics.logEvent(kStatSharingOptionsUploadSuccess, withParameters:
[kStatTracks : self.category.trackCount,
kStatPoints : self.category.bookmarksCount])
self.getDirectLinkCell.cellState = .disabled
self.directLinkInstructionsLabel.text = L("unable_get_direct_link_desc")
self.tableView.beginUpdates()
let directLinkUpdateIndexPath = IndexPath(row: self.directLinkUpdateRowIndex,
section: self.privateSectionIndex)
if (self.tableView.cellForRow(at: directLinkUpdateIndexPath) != nil) {
self.tableView.deleteRows(at: [directLinkUpdateIndexPath], with: .automatic)
}
self.tableView.insertRows(at: [IndexPath(row: self.publishUpdateRowIndex,
section: self.publicSectionIndex)],
with: .automatic)
self.tableView.endUpdates()
if update {
Toast.toast(withText: L("direct_link_updating_success")).show()
}
}
}
}
private func uploadAndGetDirectLink(update: Bool) {
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatPrivate])
performAfterValidation(anchor: getDirectLinkCell) { [weak self] in
guard let s = self else {
assert(false, "Unexpected self == nil")
return
}
s.getDirectLinkCell.cellState = update ? .updating : .inProgress
if update {
s.tableView.deleteRows(at: [IndexPath(item: s.directLinkUpdateRowIndex,
section: s.privateSectionIndex)],
with: .automatic)
}
s.manager.uploadAndGetDirectLinkCategory(withId: s.category.categoryId, progress: nil) { (_, error) in
if let error = error as NSError? {
s.getDirectLinkCell.cellState = .normal
s.showErrorAlert(error)
} else {
s.getDirectLinkCell.cellState = .completed
s.delegate?.didShareCategory()
Statistics.logEvent(kStatSharingOptionsUploadSuccess, withParameters:
[kStatTracks : s.category.trackCount,
kStatPoints : s.category.bookmarksCount])
s.tableView.insertRows(at: [IndexPath(item: s.directLinkUpdateRowIndex,
section: s.privateSectionIndex)],
with: .automatic)
if update {
Toast.toast(withText: L("direct_link_updating_success")).show()
}
}
}
}
}
private func performAfterValidation(anchor: UIView, action: @escaping MWMVoidBlock) {
if MWMFrameworkHelper.isNetworkConnected() {
signup(anchor: anchor, onComplete: { success in
if success {
action()
} else {
Statistics.logEvent(kStatSharingOptionsError, withParameters: [kStatError : 1])
}
})
} else {
Statistics.logEvent(kStatSharingOptionsError, withParameters: [kStatError : 0])
MWMAlertViewController.activeAlert().presentDefaultAlert(withTitle: L("common_check_internet_connection_dialog_title"),
message: L("common_check_internet_connection_dialog"),
rightButtonTitle: L("downloader_retry"),
leftButtonTitle: L("cancel")) {
self.performAfterValidation(anchor: anchor,
action: action)
}
}
}
private func showErrorAlert(_ error: NSError) {
guard error.code == kCategoryUploadFailedCode,
let statusCode = error.userInfo[kCategoryUploadStatusKey] as? Int,
let status = MWMCategoryUploadStatus(rawValue: statusCode) else {
assert(false)
return
}
switch (status) {
case .networkError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 1])
self.showUploadError()
case .serverError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 2])
self.showUploadError()
case .authError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 3])
self.showUploadError()
case .malformedData:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 4])
self.showMalformedDataError()
case .accessError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 5])
self.showAccessError()
case .invalidCall:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 6])
assert(false, "sharing is not available for paid bookmarks")
}
}
private func showUploadError() {
MWMAlertViewController.activeAlert().presentInfoAlert(L("unable_upload_errorr_title"),
text: L("upload_error_toast"))
}
private func showMalformedDataError() {
let alert = EditOnWebAlertViewController(with: L("html_format_error_title"),
message: L("html_format_error_subtitle"),
acceptButtonTitle: L("edit_on_web").uppercased())
alert.onAcceptBlock = {
self.dismiss(animated: true, completion: {
self.performSegue(withIdentifier: self.kEditOnWebSegueIdentifier, sender: nil)
})
}
alert.onCancelBlock = {
self.dismiss(animated: true)
}
navigationController?.present(alert, animated: true)
}
private func showAccessError() {
let alert = EditOnWebAlertViewController(with: L("public_or_limited_access_after_edit_online_error_title"),
message: L("public_or_limited_access_after_edit_online_error_message"),
acceptButtonTitle: L("edit_on_web").uppercased())
alert.onAcceptBlock = {
self.dismiss(animated: true, completion: {
self.performSegue(withIdentifier: self.kEditOnWebSegueIdentifier, sender: nil)
})
}
alert.onCancelBlock = {
self.dismiss(animated: true)
}
navigationController?.present(alert, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == kEditOnWebSegueIdentifier {
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatEditOnWeb])
if let vc = segue.destination as? EditOnWebViewController {
vc.delegate = self
vc.category = category
}
}
}
private func showEditName() {
let storyboard = UIStoryboard.instance(.sharing)
let guideNameController = storyboard.instantiateViewController(withIdentifier: kNameControllerIdentifier)
as! GuideNameViewController
guideNameController.guideName = category.title
guideNameController.delegate = self
navigationController?.pushViewController(guideNameController, animated: true)
}
private func showEditDescr() {
let storyboard = UIStoryboard.instance(.sharing)
let guideDescrController = storyboard.instantiateViewController(withIdentifier: kDescriptionControllerIdentifier)
as! GuideDescriptionViewController
guideDescrController.guideDescription = category.detailedAnnotation
guideDescrController.delegate = self
replaceTopViewController(guideDescrController, animated: true)
}
private func showSelectTags() {
let storyboard = UIStoryboard.instance(.sharing)
let tagsController = storyboard.instantiateViewController(withIdentifier: kTagsControllerIdentifier)
as! SharingTagsViewController
tagsController.delegate = self
replaceTopViewController(tagsController, animated: true)
}
private func showSelectProperties() {
let storyboard = UIStoryboard.instance(.sharing)
let propertiesController = storyboard.instantiateViewController(withIdentifier: kPropertiesControllerIdentifier)
as! SharingPropertiesViewController
propertiesController.delegate = self
replaceTopViewController(propertiesController, animated: true)
}
private func replaceTopViewController(_ viewController: UIViewController, animated: Bool) {
guard var viewControllers = navigationController?.viewControllers else {
assert(false)
return
}
viewControllers.removeLast()
viewControllers.append(viewController)
navigationController?.setViewControllers(viewControllers, animated: animated)
}
}
extension BookmarksSharingViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
let safari = SFSafariViewController(url: URL)
present(safari, animated: true, completion: nil)
return false
}
}
extension BookmarksSharingViewController: UploadActionCellDelegate {
func cellDidPressShareButton(_ cell: UploadActionCell, senderView: UIView) {
guard let url = manager.sharingUrl(forCategoryId: category.categoryId) else {
assert(false, "must provide guide url")
return
}
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatCopyLink])
let message = String(coreFormat: L("share_bookmarks_email_body_link"), arguments: [url.absoluteString])
let shareController = MWMActivityViewController.share(for: nil, message: message) {
_, success, _, _ in
if success {
Statistics.logEvent(kStatSharingLinkSuccess, withParameters: [kStatFrom : kStatSharingOptions])
}
}
shareController?.present(inParentViewController: self, anchorView: senderView)
}
}
extension BookmarksSharingViewController: SharingTagsViewControllerDelegate {
func sharingTagsViewController(_ viewController: SharingTagsViewController, didSelect tags: [MWMTag]) {
navigationController?.popViewController(animated: true)
sharingTags = tags
uploadAndPublish(update: false)
}
func sharingTagsViewControllerDidCancel(_ viewController: SharingTagsViewController) {
navigationController?.popViewController(animated: true)
}
}
extension BookmarksSharingViewController: SharingPropertiesViewControllerDelegate {
func sharingPropertiesViewController(_ viewController: SharingPropertiesViewController,
didSelect userStatus: MWMCategoryAuthorType) {
sharingUserStatus = userStatus
showSelectTags()
}
}
extension BookmarksSharingViewController: EditOnWebViewControllerDelegate {
func editOnWebViewControllerDidFinish(_ viewController: EditOnWebViewController) {
navigationController?.popViewController(animated: true)
}
}
extension BookmarksSharingViewController: GuideNameViewControllerDelegate {
func viewController(_ viewController: GuideNameViewController, didFinishEditing text: String) {
category.title = text
showEditDescr()
}
}
extension BookmarksSharingViewController: GuideDescriptionViewControllerDelegate {
func viewController(_ viewController: GuideDescriptionViewController, didFinishEditing text: String) {
category.detailedAnnotation = text
showSelectProperties()
}
}
| 39c484e75604ddfec687e9c56413bccb | 40.385859 | 125 | 0.647125 | false | false | false | false |
IdrissPiard/UnikornTube_Client | refs/heads/master | UnikornTube/UploadVideoVC.swift | mit | 1 | //
// UploadVideoVC.swift
// UnikornTube
//
// Created by Damien Serin on 03/06/2015.
// Copyright (c) 2015 SimpleAndNew. All rights reserved.
//
import UIKit
class UploadVideoVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
@IBOutlet weak var coverImage: UIImageView!
var videoPickerController = UIImagePickerController()
var coverPickerController = UIImagePickerController()
var moviePath : String!
var coverUrl : NSURL!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func uploadButtonTapped(sender: AnyObject) {
videoUploadRequest()
}
@IBAction func selectVideoButtonTapped(sender: AnyObject) {
videoPickerController.allowsEditing = false
videoPickerController.delegate = self;
videoPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
videoPickerController.mediaTypes = [kUTTypeMovie as NSString]
self.presentViewController(videoPickerController, animated: true, completion: nil)
}
@IBAction func selectCoverButtonTapped(sender: AnyObject) {
coverPickerController.allowsEditing = false
coverPickerController.delegate = self;
coverPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
coverPickerController.mediaTypes = [kUTTypeImage as NSString]
self.presentViewController(coverPickerController, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
{
if picker == self.videoPickerController {
var mediaType = info[UIImagePickerControllerMediaType] as! CFString!
var compareResult = CFStringCompare(mediaType, kUTTypeMovie, CFStringCompareFlags.CompareCaseInsensitive)
if(compareResult == CFComparisonResult.CompareEqualTo){
var videoUrl = info[UIImagePickerControllerMediaURL] as! NSURL
var moviePath = videoUrl.path
if(UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(moviePath)){
//UISaveVideoAtPathToSavedPhotosAlbum(moviePath, nil, nil, nil)
}
self.moviePath = moviePath
println(self.moviePath)
}
}
if picker == self.coverPickerController {
var coverUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
var image = info[UIImagePickerControllerOriginalImage] as! UIImage
self.coverImage.image = image
var coverPath = coverUrl.path
self.coverUrl = coverUrl
println(self.coverUrl)
}
self.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
func videoUploadRequest(){
//var json: JSON = ["meta_data": ["title":"titre", "idUser":"42", "description":"desc"]]
let manager = AFHTTPRequestOperationManager()
let url = "http://192.168.200.40:9000/upload"
manager.requestSerializer = AFJSONRequestSerializer(writingOptions: nil)
var videoURL = NSURL.fileURLWithPath(self.moviePath)
var imageData = UIImageJPEGRepresentation(self.coverImage.image, CGFloat(1))
println(videoURL)
var params = ["meta_data" : "{\"title\":\"titre\", \"idUser\":42, \"description\":\"ladesc\"}"]
var json : String = "{ \"meta_data\" : [{\"title\":\"titre\", \"idUser\":42, \"description\":\"ladesc\"}]}"
println(json)
AFNetworkActivityLogger.sharedLogger().level = AFHTTPRequestLoggerLevel.AFLoggerLevelDebug
manager.POST( url, parameters: params,
constructingBodyWithBlock: { (data: AFMultipartFormData!) in
var res = data.appendPartWithFileURL(videoURL, name: "video_data", error: nil)
data.appendPartWithFileData(imageData, name: "cover_data", fileName: "cover.jpg", mimeType: "image/jpeg")
println("was file added properly to the body? \(res)")
},
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
println("Yes thies was a success")
},
failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
println("We got an error here.. \(error)")
println(operation.responseString)
})
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 6e8b26021277bb6901cb68b6646293e2 | 38.737226 | 123 | 0.647686 | false | false | false | false |
think-dev/MadridBUS | refs/heads/master | MadridBUS/Source/Business/BusGeoNodeArrivals.swift | mit | 1 | import Foundation
import ObjectMapper
final class BusGeoNodeArrivalsDTO: DTO {
var nodeId: String = ""
var language: String = ""
init(nodeId: String, language: Language = .spanish) {
super.init()
self.nodeId = nodeId
self.language = language.rawValue
}
required init?(map: Map) {
fatalError("init(map:) has not been implemented")
}
override func mapping(map: Map) {
super.mapping(map: map)
nodeId <- map["idStop"]
language <- map["cultureInfo"]
}
}
| 32844f94ffe21eb6365c2b66dcfed238 | 23.043478 | 57 | 0.593128 | false | false | false | false |
brentdax/swift | refs/heads/master | stdlib/public/core/StringLegacy.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
extension _StringVariant {
@usableFromInline
func _repeated(_ count: Int) -> _SwiftStringStorage<CodeUnit> {
_sanityCheck(count > 0)
let c = self.count
let storage = _copyToNativeStorage(
of: CodeUnit.self,
unusedCapacity: (count - 1) * c)
var p = storage.start + c
for _ in 1 ..< count {
p.initialize(from: storage.start, count: c)
p += c
}
_sanityCheck(p == storage.start + count * c)
storage.count = p - storage.start
return storage
}
}
extension String {
/// Creates a new string representing the given string repeated the specified
/// number of times.
///
/// For example, you can use this initializer to create a string with ten
/// `"ab"` strings in a row.
///
/// let s = String(repeating: "ab", count: 10)
/// print(s)
/// // Prints "abababababababababab"
///
/// - Parameters:
/// - repeatedValue: The string to repeat.
/// - count: The number of times to repeat `repeatedValue` in the resulting
/// string.
@inlinable // FIXME(sil-serialize-all)
public init(repeating repeatedValue: String, count: Int) {
precondition(count >= 0, "Negative count not allowed")
guard count > 1 else {
self = count == 0 ? "" : repeatedValue
return
}
self = String(repeatedValue._guts._repeated(count))
}
/// A Boolean value indicating whether a string has no characters.
@inlinable // FIXME(sil-serialize-all)
public var isEmpty: Bool {
return _guts.count == 0
}
}
// TODO: since this is generally useful, make public via evolution proposal.
extension BidirectionalCollection {
@inlinable
internal func _ends<Suffix: BidirectionalCollection>(
with suffix: Suffix, by areEquivalent: (Element,Element) -> Bool
) -> Bool where Suffix.Element == Element {
var (i,j) = (self.endIndex,suffix.endIndex)
while i != self.startIndex, j != suffix.startIndex {
self.formIndex(before: &i)
suffix.formIndex(before: &j)
if !areEquivalent(self[i],suffix[j]) { return false }
}
return j == suffix.startIndex
}
}
extension BidirectionalCollection where Element: Equatable {
@inlinable
internal func _ends<Suffix: BidirectionalCollection>(
with suffix: Suffix
) -> Bool where Suffix.Element == Element {
return _ends(with: suffix, by: ==)
}
}
extension StringProtocol {
/// Returns a Boolean value indicating whether the string begins with the
/// specified prefix.
///
/// The comparison is both case sensitive and Unicode safe. The
/// case-sensitive comparison will only match strings whose corresponding
/// characters have the same case.
///
/// let cafe = "Café du Monde"
///
/// // Case sensitive
/// print(cafe.hasPrefix("café"))
/// // Prints "false"
///
/// The Unicode-safe comparison matches Unicode scalar values rather than the
/// code points used to compose them. The example below uses two strings
/// with different forms of the `"é"` character---the first uses the composed
/// form and the second uses the decomposed form.
///
/// // Unicode safe
/// let composedCafe = "Café"
/// let decomposedCafe = "Cafe\u{0301}"
///
/// print(cafe.hasPrefix(composedCafe))
/// // Prints "true"
/// print(cafe.hasPrefix(decomposedCafe))
/// // Prints "true"
///
/// - Parameter prefix: A possible prefix to test against this string.
/// - Returns: `true` if the string begins with `prefix`; otherwise, `false`.
@inlinable
public func hasPrefix<Prefix: StringProtocol>(_ prefix: Prefix) -> Bool {
return self.starts(with: prefix)
}
/// Returns a Boolean value indicating whether the string ends with the
/// specified suffix.
///
/// The comparison is both case sensitive and Unicode safe. The
/// case-sensitive comparison will only match strings whose corresponding
/// characters have the same case.
///
/// let plans = "Let's meet at the café"
///
/// // Case sensitive
/// print(plans.hasSuffix("Café"))
/// // Prints "false"
///
/// The Unicode-safe comparison matches Unicode scalar values rather than the
/// code points used to compose them. The example below uses two strings
/// with different forms of the `"é"` character---the first uses the composed
/// form and the second uses the decomposed form.
///
/// // Unicode safe
/// let composedCafe = "café"
/// let decomposedCafe = "cafe\u{0301}"
///
/// print(plans.hasSuffix(composedCafe))
/// // Prints "true"
/// print(plans.hasSuffix(decomposedCafe))
/// // Prints "true"
///
/// - Parameter suffix: A possible suffix to test against this string.
/// - Returns: `true` if the string ends with `suffix`; otherwise, `false`.
@inlinable
public func hasSuffix<Suffix: StringProtocol>(_ suffix: Suffix) -> Bool {
return self._ends(with: suffix)
}
}
extension String {
public func hasPrefix(_ prefix: String) -> Bool {
let prefixCount = prefix._guts.count
if prefixCount == 0 { return true }
// TODO: replace with 2-way vistor
if self._guts._isSmall && prefix._guts._isSmall {
let selfSmall = self._guts._smallUTF8String
let prefixSmall = prefix._guts._smallUTF8String
if selfSmall.isASCII && prefixSmall.isASCII {
return selfSmall.withUnmanagedASCII { selfASCII in
return prefixSmall.withUnmanagedASCII { prefixASCII in
if prefixASCII.count > selfASCII.count { return false }
return (0 as CInt) == _swift_stdlib_memcmp(
selfASCII.rawStart,
prefixASCII.rawStart,
prefixASCII.count)
}
}
}
}
if _fastPath(!self._guts._isOpaque && !prefix._guts._isOpaque) {
if self._guts.isASCII && prefix._guts.isASCII {
let result: Bool
let selfASCII = self._guts._unmanagedASCIIView
let prefixASCII = prefix._guts._unmanagedASCIIView
if prefixASCII.count > selfASCII.count {
// Prefix is longer than self.
result = false
} else {
result = (0 as CInt) == _swift_stdlib_memcmp(
selfASCII.rawStart,
prefixASCII.rawStart,
prefixASCII.count)
}
_fixLifetime(self)
_fixLifetime(prefix)
return result
}
else {
}
}
return self.starts(with: prefix)
}
public func hasSuffix(_ suffix: String) -> Bool {
let suffixCount = suffix._guts.count
if suffixCount == 0 { return true }
// TODO: replace with 2-way vistor
if self._guts._isSmall && suffix._guts._isSmall {
let selfSmall = self._guts._smallUTF8String
let suffixSmall = suffix._guts._smallUTF8String
if selfSmall.isASCII && suffixSmall.isASCII {
return selfSmall.withUnmanagedASCII { selfASCII in
return suffixSmall.withUnmanagedASCII { suffixASCII in
if suffixASCII.count > selfASCII.count { return false }
return (0 as CInt) == _swift_stdlib_memcmp(
selfASCII.rawStart + (selfASCII.count - suffixASCII.count),
suffixASCII.rawStart,
suffixASCII.count)
}
}
}
}
if _fastPath(!self._guts._isOpaque && !suffix._guts._isOpaque) {
if self._guts.isASCII && suffix._guts.isASCII {
let result: Bool
let selfASCII = self._guts._unmanagedASCIIView
let suffixASCII = suffix._guts._unmanagedASCIIView
if suffixASCII.count > selfASCII.count {
// Suffix is longer than self.
result = false
} else {
result = (0 as CInt) == _swift_stdlib_memcmp(
selfASCII.rawStart + (selfASCII.count - suffixASCII.count),
suffixASCII.rawStart,
suffixASCII.count)
}
_fixLifetime(self)
_fixLifetime(suffix)
return result
}
}
return self._ends(with: suffix)
}
}
// Conversions to string from other types.
extension String {
/// Creates a string representing the given value in base 10, or some other
/// specified base.
///
/// The following example converts the maximal `Int` value to a string and
/// prints its length:
///
/// let max = String(Int.max)
/// print("\(max) has \(max.count) digits.")
/// // Prints "9223372036854775807 has 19 digits."
///
/// Numerals greater than 9 are represented as Roman letters. These letters
/// start with `"A"` if `uppercase` is `true`; otherwise, with `"a"`.
///
/// let v = 999_999
/// print(String(v, radix: 2))
/// // Prints "11110100001000111111"
///
/// print(String(v, radix: 16))
/// // Prints "f423f"
/// print(String(v, radix: 16, uppercase: true))
/// // Prints "F423F"
///
/// - Parameters:
/// - value: The value to convert to a string.
/// - radix: The base to use for the string representation. `radix` must be
/// at least 2 and at most 36. The default is 10.
/// - uppercase: Pass `true` to use uppercase letters to represent numerals
/// greater than 9, or `false` to use lowercase letters. The default is
/// `false`.
@inlinable // FIXME(sil-serialize-all)
public init<T : BinaryInteger>(
_ value: T, radix: Int = 10, uppercase: Bool = false
) {
self = value._description(radix: radix, uppercase: uppercase)
}
}
extension _StringGuts {
@inlinable
func _repeated(_ n: Int) -> _StringGuts {
_sanityCheck(n > 1)
if self._isSmall {
// TODO: visitor pattern for something like this...
if let small = self._smallUTF8String._repeated(n) {
return _StringGuts(small)
}
}
return _visitGuts(self, range: nil, args: n,
ascii: { ascii, n in return _StringGuts(_large: ascii._repeated(n)) },
utf16: { utf16, n in return _StringGuts(_large: utf16._repeated(n)) },
opaque: { opaque, n in return _StringGuts(_large: opaque._repeated(n)) })
}
}
| 306a1175f8b19dffb0dc96a0c951b6d4 | 33.129032 | 80 | 0.614745 | false | false | false | false |
BanyaKrylov/Learn-Swift | refs/heads/master | 5.1/HW4.playground/Contents.swift | apache-2.0 | 1 | import UIKit
//Homework 4
let decimal = 17
let binary = 0b10001
let octal = 0o21
let hexadecimal = 0x11
let exponent = 1.25e2
let hexExponent = 0xFp-2
var number = 1_123_456
var char: Character = "a"
var str: String = "Hello"
let longString = """
Это
многострочный
литерал
"""
var conc = String(number) + String(char) + longString
conc.count
var str2 = "This is String literal"
let char2 = "a"
var num1 = 1, num2 = 2
let concatenation: String = str2 + String(char2) + String(num1 + num2)
print(concatenation)
let w = """
* * *
* * *
* *
"""
print(w)
var day = 21
var month = "January"
var year = 2020
print(String(year) + " " + month + " " + String(day))
| fefd6b4110b42cb6bd2e5a1d05b51339 | 13.630435 | 70 | 0.649331 | false | false | false | false |
InAppPurchase/InAppPurchase | refs/heads/master | InAppPurchase/IAPModel.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2015 Chris Davis
//
// 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.
//
// IAPModel.swift
// InAppPurchase
//
// Created by Chris Davis on 15/12/2015.
// Email: [email protected]
// Copyright © 2015 nthState. All rights reserved.
//
import Foundation
// MARK: Class
public class IAPModel : IAPHydrateable, CustomDebugStringConvertible
{
// MARK: Properties
public var validReceipt:Bool
public var isPartial:Bool
public var entitlements:[IAPEntitlementModel]
public var debugDescription: String {
var output = "IAPModel: \n" +
"validReceipt: \(validReceipt)\n" +
"isPartial: \(isPartial)\n" +
"entitlements:\n"
for entitlement in entitlements
{
output += "\t \(entitlement)\n"
}
return output
}
// MARK: Initalizers
/**
Initalizer
*/
init()
{
validReceipt = false
isPartial = false
entitlements = [IAPEntitlementModel]()
}
/**
Initalizer with hydration
- parameter dic: The dictionary of values
*/
convenience required public init(dic:NSDictionary)
{
self.init()
hydrate(dic)
}
// MARK: Hydration
/**
Hydrate the object
- parameter dic: The dictionary of values
*/
func hydrate(dic:NSDictionary)
{
if let _validReceipt = dic["validReceipt"] as? Bool
{
validReceipt = _validReceipt
}
if let _isPartial = dic["isPartial"] as? Bool
{
isPartial = _isPartial
}
if let _entitlements = dic["entitlements"] as? NSArray
{
entitlements = _entitlements.flatMap() { IAPEntitlementModel(dic: $0 as! NSDictionary) }
}
}
}
| 9f3d8c35e128eeb1c3ab1f467a211d70 | 28.09 | 100 | 0.638364 | false | false | false | false |
1457792186/JWSwift | refs/heads/develop | BabyTunes/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift | apache-2.0 | 25 | //
// ShareReplayScope.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/28/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
/// Subject lifetime scope
public enum SubjectLifetimeScope {
/**
**Each connection will have it's own subject instance to store replay events.**
**Connections will be isolated from each another.**
Configures the underlying implementation to behave equivalent to.
```
source.multicast(makeSubject: { MySubject() }).refCount()
```
**This is the recommended default.**
This has the following consequences:
* `retry` or `concat` operators will function as expected because terminating the sequence will clear internal state.
* Each connection to source observable sequence will use it's own subject.
* When the number of subscribers drops from 1 to 0 and connection to source sequence is disposed, subject will be cleared.
```
let xs = Observable.deferred { () -> Observable<TimeInterval> in
print("Performing work ...")
return Observable.just(Date().timeIntervalSince1970)
}
.share(replay: 1, scope: .whileConnected)
_ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") })
_ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") })
_ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") })
```
Notice how time interval is different and `Performing work ...` is printed each time)
```
Performing work ...
next 1495998900.82141
completed
Performing work ...
next 1495998900.82359
completed
Performing work ...
next 1495998900.82444
completed
```
*/
case whileConnected
/**
**One subject will store replay events for all connections to source.**
**Connections won't be isolated from each another.**
Configures the underlying implementation behave equivalent to.
```
source.multicast(MySubject()).refCount()
```
This has the following consequences:
* Using `retry` or `concat` operators after this operator usually isn't advised.
* Each connection to source observable sequence will share the same subject.
* After number of subscribers drops from 1 to 0 and connection to source observable sequence is dispose, this operator will
continue holding a reference to the same subject.
If at some later moment a new observer initiates a new connection to source it can potentially receive
some of the stale events received during previous connection.
* After source sequence terminates any new observer will always immediatelly receive replayed elements and terminal event.
No new subscriptions to source observable sequence will be attempted.
```
let xs = Observable.deferred { () -> Observable<TimeInterval> in
print("Performing work ...")
return Observable.just(Date().timeIntervalSince1970)
}
.share(replay: 1, scope: .forever)
_ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") })
_ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") })
_ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") })
```
Notice how time interval is the same, replayed, and `Performing work ...` is printed only once
```
Performing work ...
next 1495999013.76356
completed
next 1495999013.76356
completed
next 1495999013.76356
completed
```
*/
case forever
}
extension ObservableType {
/**
Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer.
This operator is equivalent to:
* `.whileConnected`
```
// Each connection will have it's own subject instance to store replay events.
// Connections will be isolated from each another.
source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount()
```
* `.forever`
```
// One subject will store replay events for all connections to source.
// Connections won't be isolated from each another.
source.multicast(Replay.create(bufferSize: replay)).refCount()
```
It uses optimized versions of the operators for most common operations.
- parameter replay: Maximum element count of the replay buffer.
- parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum.
- seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html)
- returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected)
-> Observable<E> {
switch scope {
case .forever:
switch replay {
case 0: return self.multicast(PublishSubject()).refCount()
default: return self.multicast(ReplaySubject.create(bufferSize: replay)).refCount()
}
case .whileConnected:
switch replay {
case 0: return ShareWhileConnected(source: self.asObservable())
case 1: return ShareReplay1WhileConnected(source: self.asObservable())
default: return self.multicast(makeSubject: { ReplaySubject.create(bufferSize: replay) }).refCount()
}
}
}
}
fileprivate final class ShareReplay1WhileConnectedConnection<Element>
: ObserverType
, SynchronizedUnsubscribeType {
typealias E = Element
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
typealias Parent = ShareReplay1WhileConnected<Element>
private let _parent: Parent
private let _subscription = SingleAssignmentDisposable()
private let _lock: RecursiveLock
private var _disposed: Bool = false
fileprivate var _observers = Observers()
fileprivate var _element: Element?
init(parent: Parent, lock: RecursiveLock) {
_parent = parent
_lock = lock
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
}
final func on(_ event: Event<E>) {
_lock.lock()
let observers = _synchronized_on(event)
_lock.unlock()
dispatch(observers, event)
}
final private func _synchronized_on(_ event: Event<E>) -> Observers {
if _disposed {
return Observers()
}
switch event {
case .next(let element):
_element = element
return _observers
case .error, .completed:
let observers = _observers
self._synchronized_dispose()
return observers
}
}
final func connect() {
_subscription.setDisposable(_parent._source.subscribe(self))
}
final func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element {
_lock.lock(); defer { _lock.unlock() }
if let element = _element {
observer.on(.next(element))
}
let disposeKey = _observers.insert(observer.on)
return SubscriptionDisposable(owner: self, key: disposeKey)
}
final private func _synchronized_dispose() {
_disposed = true
if _parent._connection === self {
_parent._connection = nil
}
_observers = Observers()
}
final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
_lock.lock()
let shouldDisconnect = _synchronized_unsubscribe(disposeKey)
_lock.unlock()
if shouldDisconnect {
_subscription.dispose()
}
}
@inline(__always)
final private func _synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool {
// if already unsubscribed, just return
if self._observers.removeKey(disposeKey) == nil {
return false
}
if _observers.count == 0 {
_synchronized_dispose()
return true
}
return false
}
#if TRACE_RESOURCES
deinit {
_ = Resources.decrementTotal()
}
#endif
}
// optimized version of share replay for most common case
final fileprivate class ShareReplay1WhileConnected<Element>
: Observable<Element> {
fileprivate typealias Connection = ShareReplay1WhileConnectedConnection<Element>
fileprivate let _source: Observable<Element>
fileprivate let _lock = RecursiveLock()
fileprivate var _connection: Connection?
init(source: Observable<Element>) {
self._source = source
}
override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E {
_lock.lock()
let connection = _synchronized_subscribe(observer)
let count = connection._observers.count
let disposable = connection._synchronized_subscribe(observer)
_lock.unlock()
if count == 0 {
connection.connect()
}
return disposable
}
@inline(__always)
private func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Connection where O.E == E {
let connection: Connection
if let existingConnection = _connection {
connection = existingConnection
}
else {
connection = ShareReplay1WhileConnectedConnection<Element>(
parent: self,
lock: _lock)
_connection = connection
}
return connection
}
}
fileprivate final class ShareWhileConnectedConnection<Element>
: ObserverType
, SynchronizedUnsubscribeType {
typealias E = Element
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
typealias Parent = ShareWhileConnected<Element>
private let _parent: Parent
private let _subscription = SingleAssignmentDisposable()
private let _lock: RecursiveLock
private var _disposed: Bool = false
fileprivate var _observers = Observers()
init(parent: Parent, lock: RecursiveLock) {
_parent = parent
_lock = lock
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
}
final func on(_ event: Event<E>) {
_lock.lock()
let observers = _synchronized_on(event)
_lock.unlock()
dispatch(observers, event)
}
final private func _synchronized_on(_ event: Event<E>) -> Observers {
if _disposed {
return Observers()
}
switch event {
case .next:
return _observers
case .error, .completed:
let observers = _observers
self._synchronized_dispose()
return observers
}
}
final func connect() {
_subscription.setDisposable(_parent._source.subscribe(self))
}
final func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element {
_lock.lock(); defer { _lock.unlock() }
let disposeKey = _observers.insert(observer.on)
return SubscriptionDisposable(owner: self, key: disposeKey)
}
final private func _synchronized_dispose() {
_disposed = true
if _parent._connection === self {
_parent._connection = nil
}
_observers = Observers()
}
final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
_lock.lock()
let shouldDisconnect = _synchronized_unsubscribe(disposeKey)
_lock.unlock()
if shouldDisconnect {
_subscription.dispose()
}
}
@inline(__always)
final private func _synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool {
// if already unsubscribed, just return
if self._observers.removeKey(disposeKey) == nil {
return false
}
if _observers.count == 0 {
_synchronized_dispose()
return true
}
return false
}
#if TRACE_RESOURCES
deinit {
_ = Resources.decrementTotal()
}
#endif
}
// optimized version of share replay for most common case
final fileprivate class ShareWhileConnected<Element>
: Observable<Element> {
fileprivate typealias Connection = ShareWhileConnectedConnection<Element>
fileprivate let _source: Observable<Element>
fileprivate let _lock = RecursiveLock()
fileprivate var _connection: Connection?
init(source: Observable<Element>) {
self._source = source
}
override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E {
_lock.lock()
let connection = _synchronized_subscribe(observer)
let count = connection._observers.count
let disposable = connection._synchronized_subscribe(observer)
_lock.unlock()
if count == 0 {
connection.connect()
}
return disposable
}
@inline(__always)
private func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Connection where O.E == E {
let connection: Connection
if let existingConnection = _connection {
connection = existingConnection
}
else {
connection = ShareWhileConnectedConnection<Element>(
parent: self,
lock: _lock)
_connection = connection
}
return connection
}
}
| 736820b0f3b5fbf8349d525ca0e84374 | 29.200873 | 164 | 0.625651 | false | false | false | false |
cliqz-oss/browser-ios | refs/heads/development | Utils/KeychainCache.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import XCGLogger
import SwiftKeychainWrapper
import SwiftyJSON
private let log = Logger.keychainLogger
public protocol JSONLiteralConvertible {
func asJSON() -> JSON
}
open class KeychainCache<T: JSONLiteralConvertible> {
open let branch: String
open let label: String
open var value: T? {
didSet {
checkpoint()
}
}
public init(branch: String, label: String, value: T?) {
self.branch = branch
self.label = label
self.value = value
}
open class func fromBranch(_ branch: String, withLabel label: String?, withDefault defaultValue: T? = nil, factory: (JSON) -> T?) -> KeychainCache<T> {
if let l = label {
if let s = KeychainWrapper.standard.string(forKey: "\(branch).\(l)") {
if let t = factory(JSON.parse(s)) {
log.info("Read \(branch) from Keychain with label \(branch).\(l).")
return KeychainCache(branch: branch, label: l, value: t)
} else {
log.warning("Found \(branch) in Keychain with label \(branch).\(l), but could not parse it.")
}
} else {
log.warning("Did not find \(branch) in Keychain with label \(branch).\(l).")
}
} else {
log.warning("Did not find \(branch) label in Keychain.")
}
// Fall through to missing.
log.warning("Failed to read \(branch) from Keychain.")
let label = label ?? Bytes.generateGUID()
return KeychainCache(branch: branch, label: label, value: defaultValue)
}
open func checkpoint() {
log.info("Storing \(self.branch) in Keychain with label \(self.branch).\(self.label).")
// TODO: PII logging.
if let value = value,
let jsonString = value.asJSON().stringValue() {
KeychainWrapper.sharedAppContainerKeychain.set(jsonString, forKey: "\(branch).\(label)")
} else {
KeychainWrapper.sharedAppContainerKeychain.removeObject(forKey: "\(branch).\(label)")
}
}
}
| 3202a1a43af4b7c82a09d2afed81016b | 35 | 155 | 0.608466 | false | false | false | false |
hackcity2017/iOS-client-application | refs/heads/master | hackcity/StepsCollectionViewCell.swift | mit | 1 | //
// StepsCollectionViewCell.swift
// hackcity
//
// Created by Remi Robert on 26/03/2017.
// Copyright © 2017 Remi Robert. All rights reserved.
//
import UIKit
class StepsCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var stepsLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.containerView.layer.cornerRadius = 5
self.layer.masksToBounds = false
self.layer.shadowOffset = CGSize(width: 0, height: 0)
self.layer.shadowRadius = 5
self.layer.shadowOpacity = 0.1
}
func configure(value: Double) {
self.stepsLabel.text = "\(value / 2)m"
}
}
| c2798152b4dfb335f9747434c2269631 | 24.142857 | 61 | 0.664773 | false | false | false | false |
bymafmaf/Twitter-Clone | refs/heads/master | TwitterClone/HomeTableViewCell.swift | mit | 1 | //
// HomeTableViewCell.swift
// TwitterClone
//
// Created by monus on 2/24/17.
// Copyright © 2017 Mufi. All rights reserved.
//
import UIKit
import DateToolsSwift
@objc
protocol ProfileImageClickable {
// protocol definition goes here
func profileImageClicked(recognizer: UITapGestureRecognizer)
}
class HomeTableViewCell: UITableViewCell {
@IBAction func retweetClicked(_ sender: UIButton) {
if !retweeted {
setRetweetCount(count: tweet!.retweetCount + 1)
retweeted = true
} else {
setRetweetCount(count: tweet!.retweetCount - 1)
}
}
@IBAction func favorClicked(_ sender: UIButton) {
if !favored {
setFavorCount(count: tweet!.favoritesCount + 1)
favored = true
} else {
setFavorCount(count: tweet!.favoritesCount - 1)
}
}
var favored: Bool = false
var retweeted: Bool = false
@IBOutlet weak var favorCount: UILabel!
@IBOutlet weak var retweetCount: UILabel!
@IBOutlet weak var retweetedImage: UIImageView!
@IBOutlet weak var nameOfPersonRetweeted: UILabel!
@IBOutlet weak var givenName: UILabel!
@IBOutlet weak var username: UILabel!
@IBOutlet weak var tweetText: UILabel!
@IBOutlet weak var hours: UILabel!
@IBOutlet weak var profileImage: UIImageView!
var callerDelegate: ProfileImageClickable?
var tweet: Tweet?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setRetweetCount (count: Int){
if tweet!.retweetCount < count {
TwitterClient.sharedInstance.retweet(tweet: self.tweet!, success: { (newDict: NSDictionary) -> Void in
let newTweet = Tweet(dictionary: newDict)
self.initializeTweet(tweet: newTweet)
}, failure: {(error: Error) -> Void in
print(error.localizedDescription)
})
} else {
TwitterClient.sharedInstance.unretweet(tweet: self.tweet!, success: { (newDict: NSDictionary) -> Void in
let newTweet = Tweet(dictionary: newDict)
self.initializeTweet(tweet: newTweet)
}, failure: {(error: Error) -> Void in
print(error.localizedDescription)
})
}
tweet!.retweetCount = count
retweetCount.text = String(describing: tweet!.retweetCount)
if tweet!.retweetCount > 0 {
retweetCount.isHidden = false
}
}
func setFavorCount (count: Int){
if tweet!.favoritesCount < count {
TwitterClient.sharedInstance.favor(tweet: self.tweet!, success: { (newDict: NSDictionary) -> Void in
let newTweet = Tweet(dictionary: newDict)
self.initializeTweet(tweet: newTweet)
}, failure: {(error: Error) -> Void in
print(error.localizedDescription)
})
} else {
TwitterClient.sharedInstance.unfavor(tweet: self.tweet!, success: { (newDict: NSDictionary) -> Void in
let newTweet = Tweet(dictionary: newDict)
self.initializeTweet(tweet: newTweet)
}, failure: {(error: Error) -> Void in
print(error.localizedDescription)
})
}
tweet!.favoritesCount = count
favorCount.text = String(describing: tweet!.favoritesCount)
if tweet!.favoritesCount > 0 {
favorCount.isHidden = false
}
}
func initializeTweet(tweet: Tweet){
self.tweet = tweet
if (tweet.retweeted){
nameOfPersonRetweeted.text = tweet.nameOfPersonRetweeted! + " retweeted"
} else {
retweetedImage.isHidden = true
nameOfPersonRetweeted.isHidden = true
}
if let time = tweet.timestamp {
hours.text = time.shortTimeAgoSinceNow
}
if tweet.favoritesCount == 0 {
favorCount.isHidden = true
} else {
favorCount.text = String(describing: tweet.favoritesCount)
}
if tweet.retweetCount == 0 {
retweetCount.isHidden = true
} else {
retweetCount.text = String(describing: tweet.retweetCount)
}
username.text = "@" + tweet.username!
givenName.text = tweet.givenName!
tweetText.text = tweet.text!
profileImage.setImageWith(tweet.profileImageUrl!)
if let delegate = callerDelegate {
let gesture = UITapGestureRecognizer(target: delegate, action: #selector(ProfileImageClickable.profileImageClicked(recognizer:)))
profileImage.addGestureRecognizer(gesture)
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 3622cad1782c2d66d7fae863a5b20b48 | 32.346667 | 141 | 0.598361 | false | false | false | false |
Romdeau4/16POOPS | refs/heads/master | iOS_app/Help's Kitchen/CustomTableViewController.swift | mit | 1 | //
// CustomTableViewController.swift
// Help's Kitchen
//
// Created by Stephen Ulmer on 2/15/17.
// Copyright © 2017 Stephen Ulmer. All rights reserved.
//
import UIKit
class CustomTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupDesign()
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
func setupDesign() {
view.backgroundColor = UIColor.black
tableView.separatorColor = CustomColor.amber500
}
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 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, 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.
}
*/
}
| 34708f334e831a6d8a5fcb9255f6164b | 30.939394 | 136 | 0.665718 | false | false | false | false |
Antondomashnev/FBSnapshotsViewer | refs/heads/master | FBSnapshotsViewer/Extensions/String+HTML.swift | mit | 1 | //
// String+HTML.swift
// FBSnapshotsViewer
//
// Created by Anton Domashnev on 20.05.17.
// Copyright © 2017 Anton Domashnev. All rights reserved.
//
import Foundation
extension String {
// This at the moment works inly partially due to current requirenments
func htmlUnescape() -> String {
var newString = self
let symbols = [
""": "\"",
"&": "&",
"'": "'",
"<": "<",
">": ">"
]
for symbol in symbols.keys {
guard self.range(of: symbol) != nil, let unescapedSymbol = symbols[symbol] else {
continue
}
newString = newString.replacingOccurrences(of: symbol, with: unescapedSymbol).htmlUnescape()
}
return newString
}
}
| e53c68c1afd7c1b309f6b840c2c5181a | 26.266667 | 104 | 0.53912 | false | false | false | false |
Romdeau4/16POOPS | refs/heads/master | Helps_Kitchen_iOS/Help's Kitchen/LoginViewController.swift | mit | 1 | //
// ZBTracker.swift
// ZBTracker
//
// Created by Stephen Ulmer on 1/4/17.
// Copyright © 2017 Stephen Ulmer. All rights reserved.
//
import UIKit
import Firebase
class LoginViewController: UIViewController {
let ref = FIRDatabase.database().reference(fromURL: DataAccess.URL)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////
////Sets attributes for UIViews in LoginController
////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
let inputsContainerView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.white
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 5
view.layer.masksToBounds = true
return view
}()
lazy var loginRegisterButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = UIColor(red: 255/255, green: 207/255, blue: 6/255, alpha: 1)
button.setTitle("Login", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(UIColor.black, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
button.addTarget(self, action: #selector(handleLoginRegister), for: .touchUpInside)
return button
}()
//calls Login or Register function depending on selected value in loginRegisterSegmentedControl
func handleLoginRegister() {
if loginRegisterSegmentedControl.selectedSegmentIndex == 0 {
handleLogin()
} else {
handleRegister()
}
}
//Attempts to log in to app through FIRAuth with email and password in corresponding fields
func handleLogin() {
guard let email = emailTextField.text, let password = passwordTextField.text else {
print("Uhoh")
return
}
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user: FIRUser?, error) in
if error != nil {
self.inputsContainerView.shake()
print(error!)
return
}
self.dismiss(animated: true, completion: nil)
})
}
//Attempts to register user through FIRAuth with name, email, and password in corresponding fields
func handleRegister() {
guard let email = emailTextField.text, let password = passwordTextField.text, let name = nameTextField.text else {
print("Uhoh")
return
}
FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user: FIRUser?, error) in
if error != nil {
print(error!)
return
}
guard let uid = user?.uid else {
return
}
let usersRef = self.ref.child("Users")
usersRef.child(uid).updateChildValues(["name": name, "email": email], withCompletionBlock: {(err, ref) in
if err != nil {
print(err!)
return
}
print("Saved user successfully")
})
})
}
let nameTextField: UITextField = {
let tf = UITextField()
tf.placeholder = "Name"
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
let emailTextField: UITextField = {
let tf = UITextField()
tf.placeholder = "Email Address"
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
let passwordTextField: UITextField = {
let tf = UITextField()
tf.placeholder = "Password"
tf.translatesAutoresizingMaskIntoConstraints = false
tf.isSecureTextEntry = true
return tf
}()
let profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "HKTransparent")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
return imageView
}()
lazy var loginRegisterSegmentedControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["Login", "Register"])
sc.translatesAutoresizingMaskIntoConstraints = false
sc.tintColor = UIColor(red: 255/255, green: 207/255, blue: 6/255, alpha: 1)
sc.selectedSegmentIndex = 0
sc.addTarget(self, action: #selector(handleLoginRegisterChange), for: .valueChanged)
return sc
}()
//changes UIViews on change of loginRegisterSegmentedControl
func handleLoginRegisterChange() {
let title = loginRegisterSegmentedControl.titleForSegment(at: loginRegisterSegmentedControl.selectedSegmentIndex)
loginRegisterButton.setTitle(title, for: .normal)
//change height of inputsContainerView
inputsContainerViewHeightAnchor?.constant = loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 100 : 150
//change height of nameTextField
nameTextFieldHeightAnchor?.isActive = false
nameTextFieldHeightAnchor = nameTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 0 : 1/3)
nameTextField.isHidden = loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? true : false
nameTextFieldHeightAnchor?.isActive = true
//Change height of emailTextField
emailTextFieldHeightAnchor?.isActive = false
emailTextFieldHeightAnchor = emailTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 1/2 : 1/3)
emailTextFieldHeightAnchor?.isActive = true
//Change height of passwordTextField
passwordTextFieldHeightAnchor?.isActive = false
passwordTextFieldHeightAnchor = passwordTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 1/2 : 1/3)
passwordTextFieldHeightAnchor?.isActive = true
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.black
view.addSubview(inputsContainerView)
view.addSubview(loginRegisterButton)
view.addSubview(profileImageView)
view.addSubview(loginRegisterSegmentedControl)
setupInputsContainerView()
setupLoginRegisterButton()
setupProfileImageView()
setupLoginRegisterSegmentedControl()
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////
////Sets constraints for UIViews in LoginController
////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func setupProfileImageView() {
//x, y, width, height
profileImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
profileImageView.bottomAnchor.constraint(equalTo: loginRegisterSegmentedControl.topAnchor, constant: -12).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 150).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
//Fields to manage switch between Login and Register
var inputsContainerViewHeightAnchor: NSLayoutConstraint?
var nameTextFieldHeightAnchor: NSLayoutConstraint?
var emailTextFieldHeightAnchor: NSLayoutConstraint?
var passwordTextFieldHeightAnchor: NSLayoutConstraint?
func setupInputsContainerView() {
//x, y, width, height
inputsContainerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
inputsContainerView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
inputsContainerView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -24).isActive = true
inputsContainerViewHeightAnchor = inputsContainerView.heightAnchor.constraint(equalToConstant: 100)
inputsContainerViewHeightAnchor?.isActive = true
//x, y, width, height
inputsContainerView.addSubview(nameTextField)
nameTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true
nameTextField.topAnchor.constraint(equalTo: inputsContainerView.topAnchor).isActive = true
nameTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
nameTextFieldHeightAnchor = nameTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 0)
nameTextFieldHeightAnchor?.isActive = true
nameTextField.isHidden = true
//x, y, width, height
inputsContainerView.addSubview(emailTextField)
emailTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true
emailTextField.topAnchor.constraint(equalTo: nameTextField.bottomAnchor).isActive = true
emailTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
emailTextFieldHeightAnchor = emailTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/2)
emailTextFieldHeightAnchor?.isActive = true
//x, y, width, height
inputsContainerView.addSubview(passwordTextField)
passwordTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant: 12).isActive = true
passwordTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor).isActive = true
passwordTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
passwordTextFieldHeightAnchor = passwordTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/2)
passwordTextFieldHeightAnchor?.isActive = true
}
func setupLoginRegisterButton() {
//need x, y, width, height
loginRegisterButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loginRegisterButton.topAnchor.constraint(equalTo: inputsContainerView.bottomAnchor, constant: 12).isActive = true
loginRegisterButton.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
loginRegisterButton.heightAnchor.constraint(equalToConstant: 36).isActive = true
}
func setupLoginRegisterSegmentedControl(){
//need x, y, width, height
loginRegisterSegmentedControl.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loginRegisterSegmentedControl.bottomAnchor.constraint(equalTo: inputsContainerView.topAnchor, constant: -12).isActive = true
loginRegisterSegmentedControl.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
loginRegisterSegmentedControl.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
| a60fa757569659d6e4983ddb5219de47 | 41.379433 | 205 | 0.636348 | false | false | false | false |
NickAger/elm-slider | refs/heads/master | ServerSlider/HTTPServer/Packages/Reflection-0.14.0/Tests/ReflectionTests/InternalTests.swift | mit | 2 | import XCTest
@testable import Reflection
public class InternalTests : XCTestCase {
func testShallowMetadata() {
func testShallowMetadata<T>(type: T.Type, expectedKind: Metadata.Kind) {
let shallowMetadata = Metadata(type: type)
XCTAssert(shallowMetadata.kind == expectedKind)
XCTAssert(shallowMetadata.valueWitnessTable.size == sizeof(type))
XCTAssert(shallowMetadata.valueWitnessTable.stride == strideof(type))
}
testShallowMetadata(type: Person.self, expectedKind: .struct)
testShallowMetadata(type: (String, Int).self, expectedKind: .tuple)
testShallowMetadata(type: ((String) -> Int).self, expectedKind: .function)
testShallowMetadata(type: Any.self, expectedKind: .existential)
testShallowMetadata(type: String.Type.self, expectedKind: .metatype)
testShallowMetadata(type: ReferencePerson.self, expectedKind: .class)
}
func testNominalMetadata() {
func testMetadata<T : NominalType>(metadata: T, expectedName: String) {
XCTAssert(metadata.nominalTypeDescriptor.numberOfFields == 3)
XCTAssert(metadata.nominalTypeDescriptor.fieldNames == ["firstName", "lastName", "age"])
XCTAssertNotNil(metadata.nominalTypeDescriptor.fieldTypesAccessor)
XCTAssert(metadata.fieldTypes! == [String.self, String.self, Int.self] as [Any.Type])
}
if let metadata = Metadata.Struct(type: Person.self) {
testMetadata(metadata: metadata, expectedName: "Person")
} else {
XCTFail()
}
if let metadata = Metadata.Class(type: ReferencePerson.self) {
testMetadata(metadata: metadata, expectedName: "ReferencePerson")
} else {
XCTFail()
}
}
func testTupleMetadata() {
guard let metadata = Metadata.Tuple(type: (Int, name: String, Float, age: Int).self) else {
return XCTFail()
}
for (label, expected) in zip(metadata.labels, [nil, "name", nil, "age"] as [String?]) {
XCTAssert(label == expected)
}
}
func testSuperclass() {
guard let metadata = Metadata.Class(type: SubclassedPerson.self) else {
return XCTFail()
}
XCTAssertNotNil(metadata.superclass) // ReferencePerson
}
}
func == (lhs: [Any.Type], rhs: [Any.Type]) -> Bool {
return zip(lhs, rhs).reduce(true) { $1.0 != $1.1 ? false : $0 }
}
extension InternalTests {
public static var allTests: [(String, (InternalTests) -> () throws -> Void)] {
return [
("testShallowMetadata", testShallowMetadata),
("testNominalMetadata", testNominalMetadata),
("testTupleMetadata", testTupleMetadata),
("testSuperclass", testSuperclass),
]
}
}
| 117557d72af2d1695439a4fc2316c7b0 | 40.130435 | 100 | 0.633545 | false | true | false | false |
ilyahal/VKMusic | refs/heads/master | Pods/SwiftyVK/Source/API/User.swift | apache-2.0 | 2 | extension _VKAPI {
///Methods for working with users. More - https://vk.com/dev/users
public struct Users {
///Returns detailed information on users. More - https://vk.com/dev/users.get
public static func get(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "users.get", parameters: parameters)
}
///Returns a list of users matching the search criteria. More - https://vk.com/dev/users.search
public static func search(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "users.search", parameters: parameters)
}
///Returns information whether a user installed the application. More - https://vk.com/dev/users.isAppUser
public static func isAppUser(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "users.isAppUser", parameters: parameters)
}
///Returns a list of IDs of users and communities followed by the user. More - https://vk.com/dev/users.getSubscriptions
public static func getSubscriptions(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "users.getSubscriptions", parameters: parameters)
}
///Returns a list of IDs of followers of the user in question, sorted by date added, most recent first. More - https://vk.com/dev/users.getFollowers
public static func getFollowers(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "users.getFollowers", parameters: parameters)
}
///Reports (submits a complain about) a user. More - https://vk.com/dev/users.report
public static func report(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "users.report", parameters: parameters)
}
///Indexes user's current location and returns a list of users who are in the vicinity. More - https://vk.com/dev/users.getNearby
public static func getNearby(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "users.getNearby", parameters: parameters)
}
}
}
| 504daa6595a3dde5e6fb2553211074d5 | 39.283019 | 152 | 0.654333 | false | false | false | false |
pepaslabs/TODOApp | refs/heads/master | TODOApp/TaskStore.swift | mit | 1 | //
// TaskStore.swift
// TODOApp
//
// Created by Pepas Personal on 7/19/15.
// Copyright (c) 2015 Pepas Personal. All rights reserved.
//
import Foundation
protocol StringStoreProtocol: class
{
func addString(text: String)
func count() -> Int
func stringTextAtIndex(index: Int) -> String?
func deleteStringAtIndex(index: Int)
func moveStringAtIndex(sourceIndex: Int, toIndex destinationIndex: Int)
func setStringText(text: String, atIndex index: Int)
}
class InMemoryStringStore: StringStoreProtocol
{
private var strings: [String] = [String]()
func addString(text: String)
{
strings.append(text)
}
func count() -> Int
{
return strings.count
}
func stringTextAtIndex(index: Int) -> String?
{
return strings.get(index)
}
func deleteStringAtIndex(index: Int)
{
strings.removeAtIndex(index)
}
func moveStringAtIndex(sourceIndex: Int, toIndex destinationIndex: Int)
{
let text = strings.removeAtIndex(sourceIndex)
strings.insert(text, atIndex: destinationIndex)
}
func setStringText(text: String, atIndex index: Int)
{
if index < strings.count
{
strings[index] = text
}
}
}
class NSUserDefaultsStringStore: StringStoreProtocol
{
private var strings: [String] = [String]()
private var name: String
private let stringsNSUserDefaultsKey: String
init(name: String)
{
self.name = name
stringsNSUserDefaultsKey = "_strings_\(name)_NSUserDefaultsKey"
strings = _loadTasksFromDisk()
}
func addString(text: String)
{
strings.append(text)
_writeTasksToDisk()
}
func count() -> Int
{
return strings.count
}
func stringTextAtIndex(index: Int) -> String?
{
return strings.get(index)
}
func deleteStringAtIndex(index: Int)
{
strings.removeAtIndex(index)
_writeTasksToDisk()
}
func moveStringAtIndex(sourceIndex: Int, toIndex destinationIndex: Int)
{
let text = strings.removeAtIndex(sourceIndex)
strings.insert(text, atIndex: destinationIndex)
_writeTasksToDisk()
}
func setStringText(text: String, atIndex index: Int)
{
if index < strings.count
{
strings[index] = text
_writeTasksToDisk()
}
}
private func _loadTasksFromDisk() -> [String]
{
if var strings = NSUserDefaults.standardUserDefaults().arrayForKey(stringsNSUserDefaultsKey) as? [String]
{
return strings
}
else
{
return [String]()
}
}
private func _writeTasksToDisk()
{
NSUserDefaults.standardUserDefaults().setObject(strings, forKey: stringsNSUserDefaultsKey)
}
}
protocol TaskStoreProtocol: class
{
func addTask(title: String)
func count() -> Int
func taskTitleAtIndex(index: Int) -> String?
func deleteTaskAtIndex(index: Int)
func moveTaskAtIndex(sourceIndex: Int, toIndex destinationIndex: Int)
func setTaskTitle(title: String, atIndex index: Int)
}
class BaseTaskStore: TaskStoreProtocol
{
private var stringStore: StringStoreProtocol
init(stringStore: StringStoreProtocol)
{
self.stringStore = stringStore
}
func addTask(title: String)
{
stringStore.addString(title)
}
func count() -> Int
{
return stringStore.count()
}
func taskTitleAtIndex(index: Int) -> String?
{
return stringStore.stringTextAtIndex(index)
}
func deleteTaskAtIndex(index: Int)
{
stringStore.deleteStringAtIndex(index)
}
func moveTaskAtIndex(sourceIndex: Int, toIndex destinationIndex: Int)
{
stringStore.moveStringAtIndex(sourceIndex, toIndex: destinationIndex)
}
func setTaskTitle(title: String, atIndex index: Int)
{
stringStore.setStringText(title, atIndex: index)
}
}
class InMemoryTaskStore: BaseTaskStore {}
class NSUserDefaultsTaskStore: BaseTaskStore {}
class TaskStoreRepository
{
static var sharedInstance: TaskStoreRepository = TaskStoreRepository()
private var stores = [String: TaskStoreProtocol]()
func taskStore(name: String) -> TaskStoreProtocol
{
if let store = stores[name]
{
return store
}
else
{
let stringStore = NSUserDefaultsStringStore(name: name)
let store = NSUserDefaultsTaskStore(stringStore: stringStore)
stores[name] = store
return store
}
}
}
protocol ListStoreProtocol: class
{
func addList(title: String)
func count() -> Int
func listTitleAtIndex(index: Int) -> String?
func deleteListAtIndex(index: Int)
func moveListAtIndex(sourceIndex: Int, toIndex destinationIndex: Int)
func setListTitle(title: String, atIndex index: Int)
}
class BaseListStore: ListStoreProtocol
{
private var stringStore: StringStoreProtocol
init(stringStore: StringStoreProtocol)
{
self.stringStore = stringStore
}
func addList(title: String)
{
stringStore.addString(title)
}
func count() -> Int
{
return stringStore.count()
}
func listTitleAtIndex(index: Int) -> String?
{
return stringStore.stringTextAtIndex(index)
}
func deleteListAtIndex(index: Int)
{
stringStore.deleteStringAtIndex(index)
}
func moveListAtIndex(sourceIndex: Int, toIndex destinationIndex: Int)
{
stringStore.moveStringAtIndex(sourceIndex, toIndex: destinationIndex)
}
func setListTitle(title: String, atIndex index: Int)
{
stringStore.setStringText(title, atIndex: index)
}
}
class InMemoryListStore: BaseListStore {}
class NSUserDefaultsListStore: BaseListStore {}
class ListStoreRepository
{
static var sharedInstance: ListStoreRepository = ListStoreRepository()
private var stores = [String: ListStoreProtocol]()
func listStore(name: String) -> ListStoreProtocol
{
if let store = stores[name]
{
return store
}
else
{
let stringStore = NSUserDefaultsStringStore(name: name)
let store = NSUserDefaultsListStore(stringStore: stringStore)
stores[name] = store
return store
}
}
}
| 08085934f6f58ad252e32d6e1e8eac65 | 22.761733 | 113 | 0.630356 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | refs/heads/master | Source/PullRefreshController.swift | apache-2.0 | 3 | //
// PullRefreshController.swift
// edX
//
// Created by Akiva Leffert on 8/26/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
private let StandardRefreshHeight : CGFloat = 80
public class PullRefreshView : UIView {
private let spinner = SpinnerView(size: .Large, color: .Primary)
public init() {
spinner.stopAnimating()
super.init(frame : CGRectZero)
addSubview(spinner)
spinner.snp_makeConstraints {make in
make.centerX.equalTo(self)
make.centerY.equalTo(self).offset(10)
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func intrinsicContentSize() -> CGSize {
return CGSizeMake(UIViewNoIntrinsicMetric, StandardRefreshHeight)
}
public var percentage : CGFloat = 1 {
didSet {
let totalAngle = CGFloat(2 * M_PI * 2) // two full rotations
let scale = (percentage * 0.9) + 0.1 // don't start from 0 scale because it looks weird
spinner.transform = CGAffineTransformConcat(CGAffineTransformMakeRotation(percentage * totalAngle), CGAffineTransformMakeScale(scale, scale))
}
}
}
public protocol PullRefreshControllerDelegate : class {
func refreshControllerActivated(controller : PullRefreshController)
}
public class PullRefreshController: NSObject, ContentInsetsSource {
public weak var insetsDelegate : ContentInsetsSourceDelegate?
public weak var delegate : PullRefreshControllerDelegate?
private let view : PullRefreshView
private var shouldStartOnTouchRelease : Bool = false
private(set) var refreshing : Bool = false
public override init() {
view = PullRefreshView()
super.init()
}
public func setupInScrollView(scrollView : UIScrollView) {
scrollView.addSubview(self.view)
self.view.snp_makeConstraints {make in
make.bottom.equalTo(scrollView.snp_top)
make.leading.equalTo(scrollView)
make.trailing.equalTo(scrollView)
make.width.equalTo(scrollView)
}
scrollView.oex_addObserver(self, forKeyPath: "bounds") { (observer, scrollView, _) -> Void in
observer.scrollViewDidScroll(scrollView)
}
}
private func triggered() {
if !refreshing {
refreshing = true
view.spinner.startAnimating()
self.insetsDelegate?.contentInsetsSourceChanged(self)
self.delegate?.refreshControllerActivated(self)
}
}
public var affectsScrollIndicators : Bool {
return false
}
public func endRefreshing() {
refreshing = false
UIView.animateWithDuration(0.3) {
self.insetsDelegate?.contentInsetsSourceChanged(self)
}
view.spinner.stopAnimating()
}
public var currentInsets : UIEdgeInsets {
return UIEdgeInsetsMake(refreshing ? view.frame.height : 0, 0, 0, 0)
}
public func scrollViewDidScroll(scrollView : UIScrollView) {
let pct = max(0, min(1, -scrollView.bounds.minY / view.frame.height))
if !refreshing && scrollView.dragging {
self.view.percentage = pct
}
else {
self.view.percentage = 1
}
if pct >= 1 && scrollView.dragging {
shouldStartOnTouchRelease = true
}
if shouldStartOnTouchRelease && !scrollView.dragging {
triggered()
shouldStartOnTouchRelease = false
}
}
}
| d55c15979f89fbc18192bc92797206b1 | 30.591304 | 153 | 0.636113 | false | false | false | false |
MakeSchool/TripPlanner | refs/heads/master | TripPlanner/Networking/API Clients/TripPlannerClient.swift | mit | 1 | //
// TripPlannerClient.swift
// TripPlanner
//
// Created by Benjamin Encz on 9/7/15.
// Copyright © 2015 Make School. All rights reserved.
//
import Foundation
import Result
import CoreLocation
typealias FetchTripsCallback = Result<[JSONTrip], Reason> -> Void
typealias UploadTripCallback = Result<JSONTrip, Reason> -> Void
typealias UpdateTripCallback = Result<JSONTrip, Reason> -> Void
typealias DeleteTripCallback = Result<JSONTripDeletionResponse, Reason> -> Void
class TripPlannerClient {
static let baseURL = "http://127.0.0.1:5000/"
let urlSession: NSURLSession
init(urlSession: NSURLSession = NSURLSession.sharedSession()) {
self.urlSession = urlSession
}
func fetchTrips(callback: FetchTripsCallback) {
let resource: Resource<[JSONTrip]> = Resource(
baseURL: TripPlannerClient.baseURL,
path: "trip/",
queryString: nil,
method: .GET,
requestBody: nil,
headers: ["Authorization": BasicAuth.generateBasicAuthHeader("user", password: "password")],
parse: parse
)
let client = HTTPClient()
client.apiRequest(self.urlSession, resource: resource, failure: { (reason: Reason, data: NSData?) -> () in
dispatch_async(dispatch_get_main_queue()) {
callback(.Failure(reason))
}
}) { (trips: [JSONTrip]) in
dispatch_async(dispatch_get_main_queue()) {
callback(.Success(trips))
}
}
}
func createDeleteTripRequest(tripServerID: TripServerID) -> TripPlannerClientDeleteTripRequest {
let resource: Resource<JSONTripDeletionResponse> = Resource(
baseURL: TripPlannerClient.baseURL,
path: "trip/\(tripServerID)",
queryString: nil,
method: .DELETE,
requestBody: nil,
headers: ["Authorization": BasicAuth.generateBasicAuthHeader("user", password: "password")],
parse: parse
)
return TripPlannerClientDeleteTripRequest(resource: resource, tripServerID: tripServerID)
}
func createUpdateTripRequest(trip: Trip) -> TripPlannerClientUpdateTripRequest {
let resource: Resource<JSONTrip> = Resource(
baseURL: TripPlannerClient.baseURL,
path: "trip/\(trip.serverID!)",
queryString: nil,
method: .PUT,
requestBody: JSONEncoding.encodeJSONTrip(trip),
headers: ["Authorization": BasicAuth.generateBasicAuthHeader("user", password: "password"), "Content-Type": "application/json"],
parse: parse
)
return TripPlannerClientUpdateTripRequest(resource: resource, trip: trip)
}
func createCreateTripRequest(trip: Trip) -> TripPlannerClientCreateTripRequest {
let resource: Resource<JSONTrip> = Resource(
baseURL: TripPlannerClient.baseURL,
path: "trip/",
queryString: nil,
method: .POST,
requestBody: JSONEncoding.encodeJSONTrip(trip),
headers: ["Authorization": BasicAuth.generateBasicAuthHeader("user", password: "password"), "Content-Type": "application/json"],
parse: parse
)
return TripPlannerClientCreateTripRequest(resource: resource, trip: trip)
}
}
// TODO: reduce redundancy
class TripPlannerClientDeleteTripRequest {
var resource: Resource<JSONTripDeletionResponse>
var tripServerID: TripServerID
required init(resource: Resource<JSONTripDeletionResponse>, tripServerID: TripServerID) {
self.resource = resource
self.tripServerID = tripServerID
}
func perform(urlSession: NSURLSession, callback: DeleteTripCallback) {
let client = HTTPClient()
client.apiRequest(urlSession, resource: resource, failure: { (reason: Reason, data: NSData?) -> () in
dispatch_async(dispatch_get_main_queue()) {
callback(.Failure(reason))
}
}) { (deletedTripResponse: JSONTripDeletionResponse) in
dispatch_async(dispatch_get_main_queue()) {
callback(.Success(deletedTripResponse))
}
}
}
}
class TripPlannerClientCreateTripRequest {
var resource: Resource<JSONTrip>
var trip: Trip
required init(resource: Resource<JSONTrip>, trip: Trip) {
self.resource = resource
self.trip = trip
}
func perform(urlSession: NSURLSession, callback: UploadTripCallback) {
let client = HTTPClient()
client.apiRequest(urlSession, resource: resource, failure: { (reason: Reason, data: NSData?) -> () in
dispatch_async(dispatch_get_main_queue()) {
callback(.Failure(reason))
}
}) { (uploadedTrip: JSONTrip) in
dispatch_async(dispatch_get_main_queue()) {
callback(.Success(uploadedTrip))
}
}
}
}
class TripPlannerClientUpdateTripRequest {
var resource: Resource<JSONTrip>
var trip: Trip
required init(resource: Resource<JSONTrip>, trip: Trip) {
self.resource = resource
self.trip = trip
}
func perform(urlSession: NSURLSession, callback: UpdateTripCallback) {
let client = HTTPClient()
client.apiRequest(urlSession, resource: resource, failure: { (reason: Reason, data: NSData?) -> () in
dispatch_async(dispatch_get_main_queue()) {
callback(.Failure(reason))
}
}) { (updatedTrip: JSONTrip) in
dispatch_async(dispatch_get_main_queue()) {
callback(.Success(updatedTrip))
}
}
}
} | 74a6f6947fd273b50e2e39f5c75d61e3 | 30.945122 | 134 | 0.682894 | false | false | false | false |
zwoptex/zwoptex-cocos2d | refs/heads/master | zwoptex-cocos2d/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// zwoptex-cocos2d
//
// Created by Robert Payne on 17/07/14.
// Copyright (c) 2014 Zwopple Limited. All rights reserved.
//
import UIKit
import OpenGLES
@UIApplicationMain
class AppDelegate: CCAppDelegate, UIApplicationDelegate {
override func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]!) -> Bool {
setupCocos2dWithOptions([
CCSetupShowDebugStats: true
])
return true
}
override func startScene() -> CCScene! {
// create scene
var scene = CCScene()
// load manifeest
var manifestFilePath = CCFileUtils.sharedFileUtils().fullPathForFilename("sprites.plist")
var manifest: NSDictionary? = NSDictionary(contentsOfFile: manifestFilePath)
// grab sheets in manifest
var sheets = manifest?["sheets"] as? NSArray
// iterate over every sheet in the manifest and add it to the sprite frame cache
for var i = 0; i < sheets?.count; ++i {
var sheet = sheets?[i] as? NSDictionary
var coordinatesFileName = sheet?["coordinatesFileName"] as? NSString
var textureFileName = sheet?["textureFileName"] as? NSString
println(CCFileUtils.sharedFileUtils().fullPathForFilename(coordinatesFileName))
println(CCFileUtils.sharedFileUtils().fullPathForFilename(textureFileName))
CCSpriteFrameCache.sharedSpriteFrameCache().addSpriteFramesWithFile(coordinatesFileName, textureFilename: textureFileName)
}
// create a list of animation frames for our army attack artwork
var frames: Array<CCSpriteFrame> = []
var idx = 0;
do {
// use string padding to ensure we get a 4 digit index
var frameName = String(format: "sprites/army_attack_%04d.png", idx++)
// grab the frame from sprite frame cache
var frame = CCSpriteFrameCache.sharedSpriteFrameCache().spriteFrameByName(frameName)
// if we didn't get a frame break as we're likely at the end of the animation
if !frame {
break
}
// append frame
frames.append(frame)
} while(true)
// if we have more than 1 frame create the sprite
if frames.count > 0 {
// create animation
var animation = CCAnimation(spriteFrames: frames, delay: 1.0/15.0)
// create sprite
var sprite = CCSprite(spriteFrame: frames[0])
// set position to center of screen
sprite.position = CGPointMake(CCDirector.sharedDirector().viewSize().width / 2.0,
CCDirector.sharedDirector().viewSize().height / 2.0)
// run animate action
sprite.runAction(CCActionRepeatForever(action: CCActionAnimate(animation: animation)))
// add sprite to scene
scene.addChild(sprite)
}
// return our scene
return scene
}
}
| b3092ff7dff95e7f3b90c9e83e20c433 | 35.494382 | 139 | 0.593288 | false | false | false | false |
alvesjtiago/hnr | refs/heads/master | HNR/Controllers/CommentsTableViewController.swift | mit | 1 | //
// CommentsTableViewController.swift
// HNR
//
// Created by Tiago Alves on 18/09/2017.
// Copyright © 2017 Tiago Alves. All rights reserved.
//
import UIKit
class CommentsTableViewController: UITableViewController {
var commentsIds : NSArray = []
var flatennedComments : [Comment] = []
override func viewDidLoad() {
super.viewDidLoad()
// Set automatic height calculation for cells
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 85.0
// Trigger refresh news when pull to refres is triggered
refreshControl?.addTarget(self, action: #selector(refreshComments), for: UIControlEvents.valueChanged)
// Start refresh when view is loaded
tableView.setContentOffset(CGPoint(x: 0, y: tableView.contentOffset.y - 30), animated: false)
tableView.refreshControl?.beginRefreshing()
refreshComments()
}
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 {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.flatennedComments.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "commentCell", for: indexPath) as! CommentCell
let comment = flatennedComments[indexPath.row]
cell.set(comment: comment)
cell.authorLabelLeadingConstraint.constant = CGFloat(cell.defaultAuthorLabelLeadingConstant + comment.indentLevel * 20)
cell.timeLabelLeadingConstraint.constant = CGFloat(cell.defaultTimeLabelLeadingConstant + comment.indentLevel * 20)
cell.contentLabelLeadingConstraint.constant = CGFloat(cell.defaultContentLabelLeadingConstant + comment.indentLevel * 20)
cell.layoutSubviews()
return cell
}
func refreshComments() {
API.sharedInstance.fetchComments(commentsIds: commentsIds as! [Int]) { (success, comments) in
// Update array of news and interface
var flattenComments = [Any]()
for comment in comments {
flattenComments += comment.flattenedComments() as! Array<Any>
}
self.flatennedComments = flattenComments.flatMap { $0 } as! [Comment]
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
if (!success) {
// Display error
let alertView: UIAlertController = UIAlertController.init(title: "Error fetching news",
message: "There was an error fetching the new Hacker News articles. Please make sure you're connected to the internet and try again.",
preferredStyle: .alert)
let dismissButton: UIAlertAction = UIAlertAction.init(title: "OK",
style: .default,
handler: nil)
alertView.addAction(dismissButton)
self.present(alertView, animated: true, completion: nil)
}
}
}
}
| 4b0ccaeadd2f0ed85c890d835adbbdef | 40.146067 | 208 | 0.601584 | false | false | false | false |
curoo/ConfidoIOS | refs/heads/master | ConfidoIOS/ByteBuffer.swift | mit | 3 | //
// ByteBuffer.swift
// ConfidoIOS
//
// Created by Rudolph van Graan on 25/09/2015.
//
//
import Foundation
public typealias Byte = UInt8
public enum BufferError : Error, CustomStringConvertible {
case wordLengthMismatch
public var description: String {
switch self {
case .wordLengthMismatch: return "WordLengthMismatch"
}
}
}
//TODO: Split the struct in two and adopt the protocols below to create a MutableBuffer
public protocol ByteBufferType {
var values: [Byte] { get }
// init()
// init(size: Int)
// init(bytes: [T])
// init(buffer: Self)
// init(data: NSData) throws
// init(hexData: String) throws
var size: Int { get }
var data: Data { get }
var base64String: String { get }
var hexString: String { get }
}
/**
public protocol ImmutableBufferType: BufferType {
var memory: UnsafeBufferPointer<Byte> { get }
}
public protocol MutableBufferType: BufferType {
var memory: UnsafeMutableBufferPointer<Byte> { get }
var size: Int { get set }
mutating func append(bytes: [T])
}
*/
public struct ByteBuffer {
public fileprivate(set) var values: [Byte]
public var pointer: UnsafePointer<Byte> {
get {
return UnsafePointer<Byte>(values)
}
}
public var mutablePointer: UnsafeMutablePointer<Byte> {
get {
return UnsafeMutablePointer<Byte>(mutating: values)
}
}
public var bufferPointer: UnsafeBufferPointer<Byte> {
get {
return UnsafeBufferPointer<Byte>(start: UnsafeMutablePointer(mutating: values), count: self.byteCount)
}
}
public var voidPointer: UnsafeRawPointer {
get {
return UnsafeRawPointer(values)
}
}
public init() {
values = []
}
public init(size: Int) {
values = [Byte](repeating: 0, count: size)
}
public init(bytes: [Byte]) {
self.values = bytes
}
//TODO: public init<B where B:BufferType, B.T == T>(buffer: B)
public init(_ buffer: ByteBuffer) {
self.values = buffer.values
}
public init(data: Data) throws {
let numberOfWords = data.count / MemoryLayout<Byte>.size
if data.count % MemoryLayout<Byte>.size != 0 {
throw BufferError.wordLengthMismatch
}
self.init(size: numberOfWords)
(data as NSData).getBytes(&values, length:data.count)
}
public init(hexData: String) throws {
let data = NSMutableData()
var temp = ""
for char in hexData.characters {
temp+=String(char)
if(temp.characters.count == 2) {
let scanner = Scanner(string: temp)
var value: UInt32 = 0
scanner.scanHexInt32(&value)
data.append(&value, length: 1)
temp = ""
}
}
try self.init(data: data as Data)
}
public var data: Data {
get { return Data(bytes: UnsafePointer<UInt8>(values), count: byteCount) }
}
public var base64String: String {
get { return data.base64EncodedString(options: []) }
}
public var hexString: String {
get {
var hexString = ""
self.bufferPointer.forEach { (byte) -> () in
hexString.append(String(format:"%02x", byte))
}
return hexString
}
}
public var size: Int {
get {
return values.count
}
set {
if newValue < values.count {
//truncate the buffer to the new size
values = Array(values[0..<newValue])
} else if newValue > values.count {
let newBuffer = [Byte](repeating: 0, count: newValue)
let newBufferPointer = UnsafeMutablePointer<Byte>(mutating: newBuffer)
newBufferPointer.moveInitialize(from: self.mutablePointer, count: values.count)
values = newBuffer
}
}
}
public var byteCount: Int {
get {
return values.count * elementSize
}
}
public mutating func append(_ bytes: [Byte]) {
let currentSize = self.size
let newSize = self.size + bytes.count
self.size = newSize
let appendLocation = self.mutablePointer.advanced(by: currentSize)
appendLocation.moveAssign(from: UnsafeMutablePointer(mutating: bytes), count: bytes.count)
}
public var elementSize: Int {
get {
return MemoryLayout<Byte>.size
}
}
}
| c82ed5c049bb993fcd19064cf6179bd6 | 27.770186 | 114 | 0.576425 | false | false | false | false |
ChristianKienle/highway | refs/heads/master | Sources/POSIX/abscwd.swift | mit | 1 | import Foundation
import Darwin
import Url
public func abscwd() -> Absolute {
#if Xcode
if let result = _getabsxcodecwd(file: #file) {
return Absolute(result)
}
#endif
func error() -> Never {
fputs("error: no current directory\n", stderr)
exit(EXIT_FAILURE)
}
let cwd = Darwin.getcwd(nil, Int(PATH_MAX))
if cwd == nil { error() }
defer { free(cwd) }
guard let path = String(validatingUTF8: cwd!) else { error() }
return Absolute(path)
}
private func _getabsxcodecwd(file: String) -> URL? {
// Special case:
// Xcode modifies the current working directory. If the user
// opens his highway project in Xcode and launches it
// he expects the cwd to be the directory that contains
// _highway/.
// In order to determine the cwd we get #file and move up the
// directory tree until we find '_highway/.build'
// or more generally, until we find:
// HWBundle.directoryName/HWBundle.buildDirectoryName
// The cwd then becomes the parent of HWBundle.directoryName.
let xcodeCWD = URL(fileURLWithPath: file)
let components = xcodeCWD.pathComponents
guard let buildDirIndex = components.index(of: ".build") else {
return nil
}
// Check if index before buildDirIndex exists and value is correct
let previousIndex = buildDirIndex - 1
guard components.indices.contains(previousIndex) else {
return nil
}
let prevValue = components[previousIndex]
let foundDirSequence = prevValue == "_highway"
guard foundDirSequence else {
return nil
}
let subComps = components[0..<previousIndex]
var result = URL(string: "file://")!
subComps.forEach { result = result.appendingPathComponent($0) }
return result
}
| 291449c2c93a9e288505caae7db2a72a | 32.425926 | 70 | 0.657618 | false | false | false | false |
jaredsinclair/JTSBGTask | refs/heads/master | JTSBGTask.swift | mit | 1 | //
// JTSBGTask.swift
// JTSBGTask
//
// Created by Jared Sinclair on 8/15/15.
// Copyright © 2015 Nice Boy LLC. All rights reserved.
//
import UIKit
/**
//-----------------------------------------------------------------------------
static func start() -> BackgroundTask?
Convenience for initializing a task with a default expiration handler;
@return Returns nil if background task time was denied.
//-----------------------------------------------------------------------------
func startWithExpirationHandler(handler: (() -> Void)?) -> Bool
Begins a background task.
@param handler The expiration handler. Optional. Will be called on whatever
thread UIKit pops the expiration handler for the task. The handler should
perform cleanup in a synchronous manner, since it is called when background
time is being brought to a halt.
@return Returns YES if a valid task id was created.
//-----------------------------------------------------------------------------
end()
Ends the background task for `taskId`, if the id is valid.
*/
public class BackgroundTask {
// MARK: Public
public static func start() -> BackgroundTask? {
let task = BackgroundTask();
let successful = task.startWithExpirationHandler(nil)
return (successful) ? task : nil
}
public func startWithExpirationHandler(handler: (() -> Void)?) -> Bool {
self.taskId = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler {
if let safeHandler = handler { safeHandler() }
self.end()
}
return (self.taskId != UIBackgroundTaskInvalid);
}
public func end() {
if (self.taskId != UIBackgroundTaskInvalid) {
let taskId = self.taskId
self.taskId = UIBackgroundTaskInvalid
UIApplication.sharedApplication().endBackgroundTask(taskId)
}
}
// MARK: Private
private var taskId: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
}
| 679aba0fdd3157ada81649095f840d41 | 27.380282 | 98 | 0.59603 | false | false | false | false |
jiapan1984/swift-datastructures-algorithms | refs/heads/master | stack.swift | mit | 1 | //: Playground - noun: a place where people can play
import Cocoa
struct Stack<Item> {
var items = [Item]()
mutating func push(_ item:Item){
items.append(item)
}
mutating func pop() -> Item? {
if items.isEmpty {
return nil
}
return items.removeLast()
}
func peek() -> Item? {
if items.isEmpty {
return nil
}
return items.last
}
var isEmpty:Bool {
return items.isEmpty
}
mutating func clear() {
items = [Item]()
}
}
func parenthesesCheck(_ a:Character, _ b:Character) -> Bool {
switch (a, b) {
case ("{", "}"), ("[", "]"), ("(", ")"):
return true
default:
return false
}
}
func parenthesesChecker(_ str:String) -> Bool {
var st = Stack<Character>()
for char in str.characters {
switch char {
case "{", "(", "[":
st.push(char)
case "}", ")", "]":
guard let top = st.pop() else {
return false
}
if !parenthesesCheck(top, char) {
return false
}
default :
break
}
}
if st.isEmpty {
return true
}
return false
}
var str1 = "{{{ }}}"
var str2 = "{[ [(fdsfkk )]{kkk } kk]}"
var str3 = "{[ [(fdsfkk )](((){kkk } kk]}"
print("str: \(str1), result: \(parenthesesChecker(str1))")
print("str: \(str2), result: \(parenthesesChecker(str2))")
print("str: \(str3), result: \(parenthesesChecker(str3))")
| 7828adebf2a0c418cae8ac3bc2dc8b49 | 22.059701 | 61 | 0.484142 | false | false | false | false |
Raizlabs/BonMot | refs/heads/master | Sources/XMLBuilder.swift | mit | 1 | //
// NamedStyles+XML.swift
// BonMot
//
// Created by Brian King on 8/29/16.
// Copyright © 2016 Rightpoint. All rights reserved.
//
#if os(OSX)
import AppKit
#else
import UIKit
#endif
extension NSAttributedString {
/// Generate an attributed string by parsing `fragment` using the `XMLStyler`
/// protocol to provide style and string insertions to decorate the XML. As
/// the XML fragment is traversed, the style of each node is provided by the
/// `XMLStyler` protocol. This style and the current style are combined to
/// decorate the content of the node, and the added style is removed when
/// the node is exited. The `XMLStyler` protocol can also insert
/// `NSAttributedString`s when entering and exiting nodes to support more
/// customized styling.
///
/// The `fragment` string will be wrapped in a top level element to ensure
/// that it is valid XML, unless `XMLParsingOptions.doNotWrapXML` is
/// specified as an option. If the XML is not valid, an error will be thrown.
///
/// - Parameters:
/// - fragment: The string containing the markup.
/// - baseStyle: The base style to use where the XML does not otherwise
/// specify styling options.
/// - styler: An optional custom styler to perform extra style operations.
/// - options: XML parsing options.
/// - Returns: A styled attriubuted string.
/// - Throws: Any errors encountered by the XML parser.
public static func composed(ofXML fragment: String, baseStyle: StringStyle? = nil, styler: XMLStyler? = nil, options: XMLParsingOptions = []) throws -> NSAttributedString {
let builder = XMLBuilder(
string: fragment,
styler: styler ?? NSAttributedString.defaultXMLStyler,
options: options,
baseStyle: baseStyle ?? StringStyle()
)
let attributedString = try builder.parseAttributedString()
return attributedString
}
/// Generate an attributed string by parsing `fragment` using the collection
/// of `XMLStyleRule`s to provide style and string insertions to decorate
/// the XML. As the XML fragment is traversed, the style of each node is
/// provided by the `StyleRule`s. This style and the current style are
/// combined to decorate the content of the node, and the added style is
/// removed when the node is exited. The `XMLStyleRule` can also insert
/// `NSAttributedString`s when entering and exiting nodes to support more
/// customized styling.
///
/// For more complex styling behavior, implement the `XMLStyler` protocol
/// instead.
///
/// The `fragment` string will be wrapped in a top level element to ensure
/// that it is valid XML, unless `XMLParsingOptions.doNotWrapXML` is
/// specified as an option. If the XML is not valid, an error will be thrown.
///
/// - Parameters:
/// - fragment: The string containing the markup.
/// - baseStyle: The base style to use where the XML does not otherwise
/// specify styling options.
/// - rules: Styling rules to evaluate while parsing the XML.
/// - options: XML parsing options.
/// - Returns: A styled attriubted string.
/// - Throws: Any errors encountered by the XML parser.
public static func composed(ofXML fragment: String, baseStyle: StringStyle? = nil, rules: [XMLStyleRule], options: XMLParsingOptions = []) throws -> NSAttributedString {
let builder = XMLBuilder(
string: fragment,
styler: XMLStyleRule.Styler(rules: rules),
options: options,
baseStyle: baseStyle ?? StringStyle()
)
let attributedString = try builder.parseAttributedString()
return attributedString
}
/// The default `XMLStyler` to use. By default, this styler will look up
/// element styles in the shared `NamedStyles` and insert special characters
/// when BON-namespaced elements are encountered.
@nonobjc public static var defaultXMLStyler: XMLStyler = {
var rules = Special.insertionRules
rules.append(.styles(NamedStyles.shared))
return XMLStyleRule.Styler(rules: rules)
}()
}
extension Special {
/// Rules describing how to insert values from `Special` into attributed strings.
public static var insertionRules: [XMLStyleRule] {
let rulePairs: [[XMLStyleRule]] = allCases.map {
let elementName = "BON:\($0.name)"
// Add the insertion rule and a style rule so we don't look up the style and generate a warning
return [XMLStyleRule.enter(element: elementName, insert: $0), XMLStyleRule.style(elementName, StringStyle())]
}
return rulePairs.flatMap { $0 }
}
}
/// A simple set of styling rules for styling XML. If your needs are more
/// complicated, use the `XMLStyler` protocol.
public enum XMLStyleRule {
/// A collection of named styles.
case styles(NamedStyles)
/// A name/style pairing.
case style(String, StringStyle)
/// A `Composable` to insert before entering tags whose name equals `element`.
case enter(element: String, insert: Composable)
/// A `Composable` to insert before exiting tags whose name equals `element`.
case exit(element: String, insert: Composable)
/// An `XMLStyler` implementation for handling `XMLStyleRule`s.
struct Styler: XMLStyler {
let rules: [XMLStyleRule]
func style(forElement name: String, attributes: [String: String], currentStyle: StringStyle) -> StringStyle? {
for rule in rules {
switch rule {
case let .style(string, style) where string == name:
return style
default:
break
}
}
for rule in rules {
if case let .styles(namedStyles) = rule {
return namedStyles.style(forName: name)
}
}
return nil
}
func prefix(forElement name: String, attributes: [String: String]) -> Composable? {
for rule in rules {
switch rule {
case let .enter(string, composable) where string == name:
return composable
default: break
}
}
return nil
}
func suffix(forElement name: String) -> Composable? {
for rule in rules {
switch rule {
case let .exit(string, composable) where string == name:
return composable
default: break
}
}
return nil
}
}
}
/// A contract to transform an XML string into an attributed string.
public protocol XMLStyler {
/// Return the style to apply for to the contents of the element. The style
/// is added onto the current style
func style(forElement name: String, attributes: [String: String], currentStyle: StringStyle) -> StringStyle?
/// Provide a `Composable` to add into the string being built before the
/// named element. This is done after the style for the element has been
/// applied, but before the contents of the element.
func prefix(forElement name: String, attributes: [String: String]) -> Composable?
/// Provide a `Composable` to add into the string being built when leaving
/// the element. This is done before the style of the element is removed.
func suffix(forElement name: String) -> Composable?
}
/// Options to control the behavior of the XML parser.
public struct XMLParsingOptions: OptionSet {
public let rawValue: Int
// Must be explicitly declared because it has to be marked public.
public init(rawValue: Int) { self.rawValue = rawValue }
/// Do not wrap the fragment with a top-level element. Wrapping the XML will
/// cause a copy of the entire XML string, so for very large strings, it is
/// recommended that you include a root node yourself and pass this option.
public static let doNotWrapXML = XMLParsingOptions(rawValue: 1)
}
/// Error wrapper that includes the line and column number of the error.
public struct XMLBuilderError: Error {
/// The error generated by XMLParser.
public let parserError: Error
/// The line number where the error occurred.
public let line: Int
/// The column where the error occurred.
public let column: Int
}
class XMLBuilder: NSObject, XMLParserDelegate {
static let internalTopLevelElement = "BonMotTopLevelContainer"
let parser: XMLParser
let options: XMLParsingOptions
var attributedString: NSMutableAttributedString
var styles: [StringStyle]
var xmlStylers: [XMLStyler]
// The XML parser sometimes splits strings, which can break localization-sensitive
// string transforms. Work around this by using the currentString variable to
// accumulate partial strings, and then reading them back out as a single string
// when the current element ends, or when a new one is started.
var currentString: String?
var topStyle: StringStyle {
guard let style = styles.last else { fatalError("Invalid Style Stack") }
return style
}
var topXMLStyler: XMLStyler {
guard let styler = xmlStylers.last else { fatalError("Invalid Style Stack") }
return styler
}
init(string: String,
styler: XMLStyler,
options: XMLParsingOptions,
baseStyle: StringStyle) {
let xml = (options.contains(.doNotWrapXML) ?
string :
"<\(XMLBuilder.internalTopLevelElement)>\(string)</\(XMLBuilder.internalTopLevelElement)>")
guard let data = xml.data(using: String.Encoding.utf8) else {
fatalError("Unable to convert to UTF8")
}
self.attributedString = NSMutableAttributedString()
self.parser = XMLParser(data: data)
self.options = options
self.xmlStylers = [styler]
// Remove the XMLStyler from the base style
var style = baseStyle
style.xmlStyler = nil
self.styles = [style]
super.init()
self.parser.shouldProcessNamespaces = false
self.parser.shouldReportNamespacePrefixes = false
self.parser.shouldResolveExternalEntities = false
self.parser.delegate = self
}
func parseAttributedString() throws -> NSMutableAttributedString {
guard parser.parse() else {
let line = parser.lineNumber
let shiftColumn = (line == 1 && options.contains(.doNotWrapXML) == false)
let shiftSize = XMLBuilder.internalTopLevelElement.lengthOfBytes(using: String.Encoding.utf8) + 2
let column = parser.columnNumber - (shiftColumn ? shiftSize : 0)
throw XMLBuilderError(parserError: parser.parserError!, line: line, column: column)
}
return attributedString
}
/// When a node is entered, a new style is derived from the current style
/// and the style for the node returned by the XMLStyler. If the style
/// contains an `XMLStyler`, it is pushed onto the `XMLStyler` stack and
///
/// - Parameters:
/// - elementName: The name of the XML element.
/// - attributes: The XML attributes.
func enter(element elementName: String, attributes: [String: String]) {
guard elementName != XMLBuilder.internalTopLevelElement else { return }
let xmlStyler = topXMLStyler
let namedStyle = xmlStyler.style(forElement: elementName, attributes: attributes, currentStyle: topStyle)
var newStyle = topStyle
if let namedStyle = namedStyle {
newStyle.add(stringStyle: namedStyle)
}
// Update the style stack. The XML styler is removed from the style and
// added to its own stack to prevent the XML parsing from being
// re-entrant and occuring on every character group.
xmlStylers.append(newStyle.xmlStyler ?? topXMLStyler)
newStyle.xmlStyler = nil
styles.append(newStyle)
// The prefix is looked up in the styler that styled this node, not the new styler
if let prefix = xmlStyler.prefix(forElement: elementName, attributes: attributes) {
prefix.append(to: attributedString, baseStyle: newStyle)
}
}
func exit(element elementName: String) {
if let suffix = topXMLStyler.suffix(forElement: elementName) {
suffix.append(to: attributedString, baseStyle: topStyle)
}
styles.removeLast()
xmlStylers.removeLast()
}
func foundNewString() {
guard let newString = currentString else {
return
}
let newAttributedString = topStyle.attributedString(from: newString)
attributedString.append(newAttributedString)
currentString = nil
}
@objc func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String]) {
foundNewString()
enter(element: elementName, attributes: attributeDict)
}
@objc func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
foundNewString()
guard elementName != XMLBuilder.internalTopLevelElement else { return }
exit(element: elementName)
}
@objc func parser(_ parser: XMLParser, foundCharacters string: String) {
currentString = (currentString ?? "").appending(string)
}
}
| 14ba425ea5e8646b0efeadbd67a9531d | 38.449568 | 178 | 0.652933 | false | false | false | false |
JGiola/swift | refs/heads/main | validation-test/Sema/type_checker_perf/slow/rdar17170728.swift | apache-2.0 | 14 | // RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asan
let i: Int? = 1
let j: Int?
let k: Int? = 2
// expected-error@+1 {{the compiler is unable to type-check this expression in reasonable time}}
let _ = [i, j, k].reduce(0 as Int?) {
$0 != nil && $1 != nil ? $0! + $1! : ($0 != nil ? $0! : ($1 != nil ? $1! : nil))
}
| 582ad77d44a712612b54cae28f592631 | 33.181818 | 96 | 0.593085 | false | false | false | false |
khaptonstall/ios-notepad | refs/heads/master | Notepad/Notepad/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Notepad
//
// Created by Kyle Haptonstall on 1/17/16.
// Copyright © 2016 Kyle Haptonstall. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UIApplication.sharedApplication().statusBarStyle = .LightContent
let navigationBarAppearace = UINavigationBar.appearance()
navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
navigationBarAppearace.tintColor = UIColor.whiteColor()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.KyleHaptonstall.Notepad" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Notepad", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 67a2cae6e5dd7c91687a3aacf76b8ec9 | 54.243478 | 291 | 0.722021 | false | false | false | false |
sztoth/PodcastChapters | refs/heads/develop | PodcastChapters/Utilities/Misc/SharedSettings.swift | mit | 1 | //
// SharedSettings.swift
// PodcastChapters
//
// Created by Szabolcs Toth on 2016. 03. 06..
// Copyright © 2016. Szabolcs Toth. All rights reserved.
//
import Cocoa
enum ColorSettings {
static var mainBackgroundColor: NSColor {
return darkBackgroundColor
}
static var subBackgroundColor: NSColor {
return lightBackgroundColor
}
static var normalActionColor: NSColor {
return greenishColor
}
static var highlightedActionColor: NSColor {
return whiteColor
}
static var textColor: NSColor {
return whiteColor
}
static var equalizerColor: NSColor {
return pinkColor
}
static var cellSelectionColor: NSColor {
return pinkColor
}
}
fileprivate extension ColorSettings {
static let darkBackgroundColor = try! NSColor(hexString: "#222831")
static let lightBackgroundColor = try! NSColor(hexString: "#393E46")
static let greenishColor = try! NSColor(hexString: "#00ADB5")
static let whiteColor = try! NSColor(hexString: "#EEEEEE")
static let pinkColor = try! NSColor(hexString: "#EA526F")
}
enum AnimationSettings {
static let duration = 0.21
static let distance = 8.0
static let timing = CAMediaTimingFunction.EaseInEaseOut
}
| e1abbe51cd3525681a25b095a5b6b563 | 23.132075 | 72 | 0.687256 | false | false | false | false |
wireapp/wire-ios | refs/heads/develop | Wire-iOS/Sources/UserInterface/Components/Views/SectionFooter.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import UIKit
final class SectionFooterView: UIView {
let titleLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
createConstraints()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupViews() {
titleLabel.font = .preferredFont(forTextStyle: .footnote)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.numberOfLines = 0
titleLabel.applyStyle(.footerLabel)
addSubview(titleLabel)
}
private func createConstraints() {
NSLayoutConstraint.activate([
titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: 16),
titleLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8)
])
}
}
final class SectionFooter: UICollectionReusableView {
let footerView = SectionFooterView()
var titleLabel: UILabel {
return footerView.titleLabel
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(footerView)
footerView.translatesAutoresizingMaskIntoConstraints = false
footerView.fitIn(view: self)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init?(coder aDecoder: NSCoder) is not implemented")
}
class func register(collectionView: UICollectionView) {
collectionView.register(SectionFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "SectionFooter")
}
}
class SectionTableFooter: UITableViewHeaderFooterView {
let footerView = SectionFooterView()
var titleLabel: UILabel {
return footerView.titleLabel
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
addSubview(footerView)
footerView.translatesAutoresizingMaskIntoConstraints = false
footerView.fitIn(view: self)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init?(coder aDecoder: NSCoder) is not implemented")
}
}
| feed89ea0c7433a3fdd48effad72d951 | 30.069307 | 160 | 0.70204 | false | false | false | false |
LoveAlwaysYoung/EnjoyUniversity | refs/heads/master | EnjoyUniversity/EnjoyUniversity/Classes/View/Activity/EUCreatedActivityViewController.swift | mit | 1 | //
// EUCreatedActivityViewController.swift
// EnjoyUniversity
//
// Created by lip on 17/4/1.
// Copyright © 2017年 lip. All rights reserved.
//
import UIKit
/// 我创建的活动
class EUCreatedActivityViewController: EUBaseAvtivityViewController {
/// 上层传入,用于删除
var activitylistviewmodel:ActivityListViewModel?
var row:Int = 0
/// 参与者数据源
lazy var participatorslist = UserInfoListViewModel()
/// 记录活动 ID
var avid:Int = 0
/// 参与者数据加载完成标记
var isFinished:Bool = false
var viewmodel:ActivityViewModel?{
didSet{
// 将其它操作移到 viewWillAppear 中,支持修改
let url = URL(string: viewmodel?.imageURL ?? "")
detailHeight = viewmodel?.detailHeight ?? 0
backgroudImage.kf.setImage(with: url,
placeholder: UIImage(named: "tempbackground"),
options: [.transition(.fade(1))],
progressBlock: nil,
completionHandler: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
loadData()
setupNavUI()
setupFunctionUI()
setupQRCodeUI()
setupChangeButton()
}
override func viewWillAppear(_ animated: Bool) {
titleLabel.text = viewmodel?.activitymodel.avTitle
placeLabel.text = viewmodel?.activitymodel.avPlace
priceLabel.text = viewmodel?.price
timeLabel.text = viewmodel?.allTime
detailLabel.text = viewmodel?.activitymodel.avDetail
avid = viewmodel?.activitymodel.avid ?? 0
warnLabel.text = viewmodel?.needRegister
self.participatornumLabel.text = "已报名\(self.participatorslist.activityParticipatorList.count)人/" + (self.viewmodel?.expectPeople ?? "人数不限")
if let img = viewmodel?.activityImg{
backgroudImage.image = img
}
// FIXME: - 活动详情独立的一页,类似于活动行
detailHeight = viewmodel?.detailHeight ?? 0
}
private func loadData(){
guard let avid = viewmodel?.activitymodel.avid else {
return
}
self.participatornumLabel.text = "正在加载..."
participatorslist.loadActivityMemberInfoList(avid: avid) { (isSuccess, hasMember) in
if !isSuccess{
self.participatornumLabel.text = "列表加载失败,请检查网络设置"
return
}
self.isFinished = true
if !hasMember{
self.participatornumLabel.text = "还没有小伙伴报名参加~"
return
}
self.participatornumLabel.text = "已报名\(self.participatorslist.activityParticipatorList.count)人/" + (self.viewmodel?.expectPeople ?? "人数不限")
}
}
}
// MARK: - UI 相关方法
extension EUCreatedActivityViewController{
fileprivate func setupNavUI(){
let rightshadow = UIImageView(frame: CGRect(x: UIScreen.main.bounds.width - 50, y: 30, width: 30, height: 30))
rightshadow.image = UIImage(named: "nav_background")
rightshadow.alpha = 0.7
view.addSubview(rightshadow)
let moreactionBtn = UIButton(frame: CGRect(x: 3, y: 3, width: 24, height: 24))
moreactionBtn.setImage(UIImage(named: "nav_point"), for: .normal)
moreactionBtn.isUserInteractionEnabled = true
rightshadow.isUserInteractionEnabled = true
moreactionBtn.addTarget(nil, action: #selector(moreActionBtnIsClicked), for: .touchUpInside)
rightshadow.addSubview(moreactionBtn)
/// 滑动区域大小下
scrollView.contentSize = CGSize(width: UIScreen.main.bounds.width, height: 600 + detailHeight)
}
fileprivate func setupFunctionUI(){
let functionview = UIView(frame: CGRect(x: 5, y: 190, width: UIScreen.main.bounds.width - 10, height: 70))
functionview.backgroundColor = UIColor.white
scrollView.addSubview(functionview)
let buttonWidth:CGFloat = 50
let margin = (functionview.bounds.width - 4 * buttonWidth) / 5
let checkBtn = EUActivityButton(frame: CGRect(x: margin, y: 8, width: buttonWidth, height: 62), image: UIImage(named: "av_check")!, text: "审核", shadowimage: UIImage(named: "av_shadow_orange")!)
functionview.addSubview(checkBtn)
let notifBtn = EUActivityButton(frame: CGRect(x: margin * 2 + buttonWidth, y: 8, width: buttonWidth, height: 62), image: UIImage(named: "av_notify")!, text: "通知", shadowimage: UIImage(named: "av_shadow_red")!)
functionview.addSubview(notifBtn)
let shareBtn = EUActivityButton(frame: CGRect(x: margin * 3 + buttonWidth * 2, y: 8, width: buttonWidth, height: 62), image: UIImage(named: "av_share")!, text: "分享", shadowimage: UIImage(named: "av_shadow_blue")!)
functionview.addSubview(shareBtn)
let registerBtn = EUActivityButton(frame: CGRect(x: margin * 4 + buttonWidth * 3, y: 8, width: buttonWidth, height: 62), image: UIImage(named: "av_register")!, text: "签到", shadowimage: UIImage(named: "av_shadow_purple")!)
functionview.addSubview(registerBtn)
// 添加监听事件
checkBtn.addTarget(nil, action: #selector(checkBtnIsClicked), for: .touchUpInside)
shareBtn.addTarget(nil, action: #selector(shareActivity), for: .touchUpInside)
notifBtn.addTarget(nil, action: #selector(notifyParticipators), for: .touchUpInside)
registerBtn.addTarget(nil, action: #selector(startRegister), for: .touchUpInside)
// 添加点击响应事件
let tapgesture = UITapGestureRecognizer(target: self, action: #selector(checkBtnIsClicked))
participatornumview.isUserInteractionEnabled = true
participatornumview.addGestureRecognizer(tapgesture)
}
fileprivate func setupQRCodeUI(){
let qrcodeview = UIView(frame: CGRect(x: 5, y: 520 + detailHeight, width: UIScreen.main.bounds.width - 10, height: 80))
qrcodeview.backgroundColor = UIColor.white
scrollView.addSubview(qrcodeview)
let qrtitlelabel = UILabel(frame: CGRect(x: 15, y: 20, width: 150, height: 15))
qrtitlelabel.text = "活动专属二维码"
qrtitlelabel.textColor = UIColor.black
qrtitlelabel.font = UIFont.boldSystemFont(ofSize: 15)
qrcodeview.addSubview(qrtitlelabel)
let qrdetaillabel = UILabel(frame: CGRect(x: 15, y: 50, width: 150, height: 14))
qrdetaillabel.text = "扫一扫了解详情"
qrdetaillabel.textColor = UIColor.lightGray
qrdetaillabel.font = UIFont.boldSystemFont(ofSize: 14)
qrcodeview.addSubview(qrdetaillabel)
let qrBtn = UIButton(frame: CGRect(x: UIScreen.main.bounds.width - 54, y: 32, width: 32, height: 32))
qrBtn.setImage(UIImage(named: "av_qrcode"), for: .normal)
qrBtn.addTarget(nil, action: #selector(showQRCode), for: .touchUpInside)
qrcodeview.addSubview(qrBtn)
}
fileprivate func setupChangeButton(){
let changeButton = UIButton(frame: CGRect(x: 12, y: UIScreen.main.bounds.height - 50, width: UIScreen.main.bounds.width - 24, height: 44))
changeButton.backgroundColor = UIColor.orange
changeButton.setTitle("修改活动", for: .normal)
changeButton.addTarget(nil, action: #selector(changeActiity), for: .touchUpInside)
view.addSubview(changeButton)
}
}
// MARK: - 监听方法集合
extension EUCreatedActivityViewController{
/// 更多按钮
@objc fileprivate func moreActionBtnIsClicked(){
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
let confirm = UIAlertAction(title: "删除活动", style: .destructive) { (_) in
SwiftyProgressHUD.showLoadingHUD()
EUNetworkManager.shared.deleteActivity(avid: self.avid, completion: { (isSuccess, hasPermission) in
SwiftyProgressHUD.hide()
if !isSuccess{
SwiftyProgressHUD.showFaildHUD(text: "网络异常", duration: 1)
return
}
if !hasPermission{
SwiftyProgressHUD.showFaildHUD(text: "没有权限", duration: 1)
return
}
SwiftyProgressHUD.showSuccessHUD(duration: 1)
self.activitylistviewmodel?.createdlist.remove(at: self.row)
_ = self.navigationController?.popViewController(animated: true)
})
}
alert.addAction(cancel)
alert.addAction(confirm)
present(alert, animated: true, completion: nil)
}
/// 审核
@objc fileprivate func checkBtnIsClicked(){
if !isFinished{
SwiftyProgressHUD.showFaildHUD(text: "列表加载中", duration: 1)
return
}
if viewmodel?.isFinished ?? true{
SwiftyProgressHUD.showFaildHUD(text: "活动已结束", duration: 1)
return
}
let vc = EUActivityParticipatorsViewController()
vc.participatorslist = participatorslist
vc.avid = avid
self.navigationController?.pushViewController(vc, animated: true)
}
/// 显示二维码
@objc fileprivate func showQRCode(){
let vc = EUShowQRCodeViewController()
vc.activityName = viewmodel?.activitymodel.avTitle
vc.qrString = viewmodel?.qrcodeString
self.navigationController?.pushViewController(vc, animated: true)
}
/// 通知按钮
@objc fileprivate func notifyParticipators(){
if viewmodel?.isFinished ?? true{
SwiftyProgressHUD.showFaildHUD(text: "活动已结束", duration: 1)
return
}
let vc = EUActivityNotificationController()
vc.avid = avid
vc.avname = viewmodel?.activitymodel.avTitle ?? ""
navigationController?.pushViewController(vc, animated: true)
}
/// 开始签到
@objc fileprivate func startRegister(){
if !(viewmodel?.needRegisterBool ?? false){
SwiftyProgressHUD.showFaildHUD(text: "无需签到", duration: 1)
return
}
if viewmodel?.isFinished ?? true{
SwiftyProgressHUD.showFaildHUD(text: "活动已结束", duration: 1)
return
}
guard let startime = Double(viewmodel?.activitymodel.avStarttime ?? ""),let avid = viewmodel?.activitymodel.avid else{
return
}
/// 4位数字,说明已经发起签到
if (viewmodel?.activitymodel.avRegister ?? 0) > 999{
let vc = EURegisterInfoViewController()
vc.participatorlist = self.participatorslist
vc.code = viewmodel?.activitymodel.avRegister ?? 0
vc.avid = avid
vc.activityName = self.viewmodel?.activitymodel.avTitle ?? ""
vc.activityviewmodel = viewmodel
self.navigationController?.pushViewController(vc, animated: true)
return
}
/// 最大时间差(超过这个值显示天数)
let MAXTIMEDIFFERENCE:TimeInterval = 172800
/// 最小时间差(超过这个时间显示警告)
let MINTIMEDIFFERENCE:TimeInterval = 21600
let date = Date()
let timedifference = -date.timeIntervalSince(Date(timeIntervalSince1970: startime/1000))
var alertmessage:String = ""
if timedifference < MINTIMEDIFFERENCE{
alertmessage = "您确定要发起签到吗?"
}else if timedifference < MAXTIMEDIFFERENCE{
// 显示小时
let days = lround(timedifference/3600)
alertmessage = "距离活动开始还有\(days)小时,您确定要发起签到吗?"
}else{
// 显示天数
let days = lround(timedifference/(3600*24))
alertmessage = "距离活动开始还有\(days)天,您确定要发起签到吗?"
}
let alert = UIAlertController(title: nil, message: alertmessage, preferredStyle: .alert)
let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
let confirm = UIAlertAction(title: "确定", style: .default) { (_) in
// 发起签到网络请求
SwiftyProgressHUD.showLoadingHUD()
EUNetworkManager.shared.startActivityRegist(avid: avid, completion: { (isSuccess, canStartRegister, code) in
SwiftyProgressHUD.hide()
guard let code = code,let intcode = Int(code) else{
return
}
if !isSuccess{
SwiftyProgressHUD.showFaildHUD(text: "网络异常", duration: 1)
return
}
if !canStartRegister{
SwiftyProgressHUD.showFaildHUD(text: "没有权限", duration: 1)
return
}
// 弹窗提醒签到码
let codealert = UIAlertController(title: nil, message: "本次活动的签到码为 \(intcode)", preferredStyle: .alert)
let codealertAction = UIAlertAction(title: "确定", style: .default, handler: { (_) in
// 发起签到成功跳到签到详情页
self.viewmodel?.activitymodel.avRegister = intcode
let vc = EURegisterInfoViewController()
vc.participatorlist = self.participatorslist
vc.code = intcode
vc.activityviewmodel = self.viewmodel
vc.avid = avid
vc.activityName = self.viewmodel?.activitymodel.avTitle ?? ""
self.navigationController?.pushViewController(vc, animated: true)
})
codealert.addAction(codealertAction)
self.present(codealert, animated: true, completion: nil)
})
}
alert.addAction(cancel)
alert.addAction(confirm)
present(alert, animated: true, completion: nil)
}
/// 修改活动
@objc fileprivate func changeActiity(){
if viewmodel?.isFinished ?? true{
SwiftyProgressHUD.showFaildHUD(text: "活动已结束", duration: 1)
return
}
let vc = EUStartActivityViewController()
vc.viewmodel = viewmodel
vc.addPicBtn.setImage(backgroudImage.image, for: .normal)
navigationController?.pushViewController(vc, animated: true)
}
/// 分享活动
@objc fileprivate func shareActivity(){
shareImageAndText(sharetitle: "分享活动:" + (viewmodel?.activitymodel.avTitle ?? ""),
sharedetail: viewmodel?.activitymodel.avDetail ?? "",
url: "http://www.euswag.com?avid=\(viewmodel?.activitymodel.avid ?? 0)",
image: backgroudImage.image,
currentViewController: self)
}
}
| b24c968ca5128ec32d6d162ced2ef552 | 37.111675 | 229 | 0.59037 | false | false | false | false |
mrdepth/EVEUniverse | refs/heads/master | Neocom/Neocom/Mail/ContactsSearchResults.swift | lgpl-2.1 | 2 | //
// ContactsSearchResults.swift
// Neocom
//
// Created by Artem Shimanski on 2/18/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import Combine
import EVEAPI
struct ContactsSearchResults: View {
var contacts: [Contact] = []
var onSelect: (Contact) -> Void
private func cell(_ contact: Contact) -> some View {
Button(action: {self.onSelect(contact)}) {
ContactCell(contact: contact)
}.buttonStyle(PlainButtonStyle())
}
var body: some View {
var contacts = self.contacts
let i = contacts.partition{$0.recipientType == .alliance}
let j = contacts[..<i].partition{$0.recipientType == .corporation}
let alliances = contacts[i...].sorted{($0.name ?? "") < ($1.name ?? "")}.prefix(100)
let corporations = contacts[j..<i].sorted{($0.name ?? "") < ($1.name ?? "")}.prefix(100)
let characters = contacts[..<j].sorted{($0.name ?? "") < ($1.name ?? "")}.prefix(100)
return List {
if !characters.isEmpty {
Section(header: Text("CHARACTERS")) {
ForEach(characters, id: \.objectID) { contact in
self.cell(contact)
}
}
}
if !corporations.isEmpty {
Section(header: Text("CORPORATIONS")) {
ForEach(corporations, id: \.objectID) { contact in
self.cell(contact)
}
}
}
if !alliances.isEmpty {
Section(header: Text("ALLIANCES")) {
ForEach(alliances, id: \.objectID) { contact in
self.cell(contact)
}
}
}
}.listStyle(GroupedListStyle())
}
}
#if DEBUG
struct ContactsSearchResults_Previews: PreviewProvider {
static var previews: some View {
ContactsSearchResults(contacts: []) { _ in}
.environmentObject(SharedState.testState())
}
}
#endif
| 5ff50764fa20562f85e9c1db44078b0f | 31.546875 | 96 | 0.523284 | false | false | false | false |
netguru/inbbbox-ios | refs/heads/develop | Inbbbox/Source Files/Extensions/UIImageViewExtension.swift | gpl-3.0 | 1 | //
// UIImageViewExtension.swift
// Inbbbox
//
// Created by Marcin Siemaszko on 07.03.2016.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import UIKit
import Haneke
extension UIImageView {
/// Loads image form URL
///
/// - parameter url: URL where image is located
/// - parameter placeholderImage: optional placeholder image
func loadImageFromURL(_ url: URL?, placeholderImage: UIImage? = nil) {
image = placeholderImage
guard let url = url else { return }
_ = Shared.imageCache.fetch(URL: url,
formatName: CacheManager.imageFormatName,
failure: nil,
success: { [weak self] image in
self?.image = image
}
)
}
}
| b3a21dd29a23f4ed49792597ad755858 | 29.862069 | 77 | 0.511732 | false | false | false | false |
ps2/rileylink_ios | refs/heads/dev | MinimedKit/Messages/GetPumpFirmwareVersionMessageBody.swift | mit | 1 | //
// GetPumpFirmwareVersionMessageBody.swift
// MinimedKit
//
// Created by Pete Schwamb on 10/10/18.
// Copyright © 2018 Pete Schwamb. All rights reserved.
//
import Foundation
public class GetPumpFirmwareVersionMessageBody: CarelinkLongMessageBody {
public let version: String
public required init?(rxData: Data) {
let stringEnd = rxData.firstIndex(of: 0) ?? rxData.count
guard rxData.count == type(of: self).length,
let vsn = String(data: rxData.subdata(in: 1..<stringEnd), encoding: String.Encoding.ascii) else {
return nil
}
version = vsn
super.init(rxData: rxData)
}
public required init?(rxData: NSData) {
fatalError("init(rxData:) has not been implemented")
}
}
| db56e8b7689b18befd57f19569a296cb | 28 | 109 | 0.64751 | false | false | false | false |
bradhilton/Table | refs/heads/master | Table/ContainerViewController.swift | mit | 1 | //
// ContainerViewController.swift
// Table
//
// Created by Bradley Hilton on 4/23/18.
// Copyright © 2018 Brad Hilton. All rights reserved.
//
public func ContainerController(key: AnyHashable = .auto, childController: Controller, presentedController: Controller? = nil) -> Controller {
return Controller(
key: key,
updateController: { (controller: ContainerViewController) in
controller.childController = childController
controller.presentedController = presentedController
}
)
}
public class ContainerViewController : UIViewController {
public var childController: Controller = Controller() {
didSet {
if let viewController = children.last {
if viewController.type == childController.type, viewController.key == childController.key {
viewController.update(with: childController)
} else {
let newViewController = childController.newViewController()
addChild(newViewController)
addChildView(newViewController.view)
if viewIsVisible {
transition(
from: viewController,
to: newViewController,
duration: UIView.inheritedAnimationDuration,
options: [.transitionCrossDissolve],
animations: {},
completion: { _ in
viewController.removeFromParent()
newViewController.didMove(toParent: self)
}
)
} else {
viewController.view.removeFromSuperview()
viewController.removeFromParent()
newViewController.didMove(toParent: self)
}
}
} else {
let newViewController = childController.newViewController()
addChild(newViewController)
addChildView(newViewController.view)
newViewController.didMove(toParent: self)
}
}
}
func addChildView(_ childView: UIView) {
UIView.performWithoutAnimation {
view.addSubview(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
childView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
childView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
childView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
childView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
}
override public var editButtonItem: UIBarButtonItem {
return children.last?.editButtonItem ?? super.editButtonItem
}
}
| 098c4813f9f6f9334d4a4fb8c5fd4ee3 | 40.291667 | 142 | 0.571477 | false | false | false | false |
jmelberg/acmehealth-swift | refs/heads/master | AcmeHealth/RequestAppointmentViewController.swift | apache-2.0 | 1 | /** Author: Jordan Melberg **/
/** Copyright © 2016, Okta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
class RequestAppointmentViewController: UITableViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@available(iOS 2.0, *)
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
@IBOutlet weak var date: UIDatePicker!
@IBOutlet weak var doctorLabel: UILabel!
@IBOutlet weak var doctorPicker: UIPickerView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var reasonText: UITextView!
@IBAction func datePickerValue(sender: AnyObject) {
datePickerChanged()
}
@IBAction func requestAppointment(sender: AnyObject) {
if date != nil || doctorLabel != nil || reasonText != nil{
requestAppointment()
} else {
print("Missing fields")
}
}
@IBAction func exitRequest(sender: AnyObject) {
self.navigationController?.popViewController(animated: true)
}
var datePickerHidden = true
var pickerHidden = true
override func viewDidLoad() {
super.viewDidLoad()
datePickerChanged()
self.doctorPicker.dataSource = self
self.doctorPicker.delegate = self
self.doctorLabel.text = "\(physicians[0]["name"]!)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 1 && indexPath.row == 0 {
toggleDatepicker()
}
if indexPath.section == 0 && indexPath.row == 0 {
togglePicker()
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if datePickerHidden && indexPath.section == 1 && indexPath.row == 1 {
return 0
}
else if pickerHidden && indexPath.section == 0 && indexPath.row == 1 {
return 0
}
else {
return super.tableView(tableView, heightForRowAt: indexPath)
}
}
func datePickerChanged () {
dateLabel.text = DateFormatter.localizedString(from: date.date, dateStyle: DateFormatter.Style.medium, timeStyle: DateFormatter.Style.short)
}
func toggleDatepicker() {
datePickerHidden = !datePickerHidden
tableView.beginUpdates()
tableView.endUpdates()
}
func togglePicker() {
pickerHidden = !pickerHidden
tableView.beginUpdates()
tableView.endUpdates()
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return physicians.count;
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let name = physicians[row]["name"] as? String
return name!
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
doctorLabel.text = physicians[row]["name"] as? String
togglePicker()
}
func formatDate(date : String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +SSSS"
let formattedDate = dateFormatter.date(from: date)
// Convert from date to string
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
return dateFormatter.string(from: formattedDate!)
}
func requestAppointment() {
let id = getPhysicianID(name: "\(self.doctorLabel.text!)")!
let formattedDate = formatDate(date: "\(self.date.date)")
let params = [
"comment" : self.reasonText.text,
"startTime": formattedDate!,
"providerId" : id,
"patient" : "\(user.firstName) \(user.lastName)",
"patientId" : user.id
] as [String : Any]
createAppointment(params: params){
response, error in
print(response!)
self.navigationController?.popViewController(animated: true)
}
}
}
| 924423c884b82d1570a76702fdc8072e | 31.771242 | 148 | 0.625848 | false | false | false | false |
ello/ello-ios | refs/heads/master | Sources/Utilities/DeepLinking.swift | mit | 1 | ////
/// DeepLinking.swift
//
struct DeepLinking {
static func showDiscover(navVC: UINavigationController?, currentUser: User?) {
if navVC?.visibleViewController is CategoryViewController { return }
let vc = CategoryViewController(currentUser: currentUser)
navVC?.pushViewController(vc, animated: true)
}
static func showSettings(navVC: UINavigationController?, currentUser: User?) {
guard
let currentUser = currentUser
else { return }
let settings = SettingsViewController(currentUser: currentUser)
navVC?.pushViewController(settings, animated: true)
}
static func showCategory(navVC: UINavigationController?, currentUser: User?, slug: String) {
guard !DeepLinking.alreadyOnCurrentCategory(navVC: navVC, slug: slug) else { return }
if let categoryVC = navVC?.visibleViewController as? CategoryViewController {
categoryVC.selectCategoryFor(slug: slug)
}
else {
let vc = CategoryViewController(currentUser: currentUser, slug: slug)
navVC?.pushViewController(vc, animated: true)
}
}
static func showArtistInvites(
navVC: UINavigationController?,
currentUser: User?,
slug: String? = nil
) {
if let slug = slug {
guard let navVC = navVC, !DeepLinking.alreadyOnArtistInvites(navVC: navVC, slug: slug)
else { return }
let vc = ArtistInviteDetailController(slug: slug)
vc.currentUser = currentUser
ArtistInviteDetailController.open(vc, in: navVC)
}
else {
let appVC = UIApplication.shared.keyWindow?.rootViewController as? AppViewController
let tabBarVC = appVC?.visibleViewController as? ElloTabBarController
tabBarVC?.selectedTab = .home
let tabBarNavVC = tabBarVC?.selectedViewController as? ElloNavigationController
let homeVC = tabBarNavVC?.viewControllers.first as? HomeViewController
homeVC?.showArtistInvitesViewController()
tabBarNavVC?.popToRootViewController(animated: false)
navVC?.dismiss(animated: true)
}
}
static func showProfile(navVC: UINavigationController?, currentUser: User?, username: String) {
let param = "~\(username)"
guard !DeepLinking.alreadyOnUserProfile(navVC: navVC, userParam: param) else { return }
let vc = ProfileViewController(userParam: param, username: username)
vc.currentUser = currentUser
navVC?.pushViewController(vc, animated: true)
}
static func showPostDetail(navVC: UINavigationController?, currentUser: User?, token: String) {
let param = "~\(token)"
guard !DeepLinking.alreadyOnPostDetail(navVC: navVC, postParam: param) else { return }
let vc = PostDetailViewController(postParam: param)
vc.currentUser = currentUser
navVC?.pushViewController(vc, animated: true)
}
static func showSearch(navVC: UINavigationController?, currentUser: User?, terms: String) {
if let searchVC = navVC?.visibleViewController as? SearchViewController {
searchVC.searchForPosts(terms)
}
else {
let vc = SearchViewController()
vc.currentUser = currentUser
vc.searchForPosts(terms)
navVC?.pushViewController(vc, animated: true)
}
}
static func alreadyOnCurrentCategory(navVC: UINavigationController?, slug: String) -> Bool {
if let categoryVC = navVC?.visibleViewController as? CategoryViewController,
case let .category(visibleSlug) = categoryVC.categorySelection
{
return slug == visibleSlug
}
return false
}
static func alreadyOnArtistInvites(navVC: UINavigationController?, slug: String) -> Bool {
let detailVC = navVC?.visibleViewController as? ArtistInviteDetailController
return detailVC?.artistInvite?.slug == slug
}
static func alreadyOnUserProfile(navVC: UINavigationController?, userParam: String) -> Bool {
if let profileVC = navVC?.visibleViewController as? ProfileViewController {
return userParam == profileVC.userParam
}
return false
}
static func alreadyOnPostDetail(navVC: UINavigationController?, postParam: String) -> Bool {
if let postDetailVC = navVC?.visibleViewController as? PostDetailViewController {
return postParam == postDetailVC.postParam
}
return false
}
}
| 68b89f49982fd2af6906becf9154ca67 | 37.275 | 99 | 0.663619 | false | false | false | false |
honghaoz/UW-Quest-iOS | refs/heads/master | UW Quest/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// UW Quest
//
// Created by Honghao on 9/7/14.
// Copyright (c) 2014 Honghao. All rights reserved.
//
import UIKit
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
var rootViewController: UIViewController?
if (Locator.user.isLoggedIn) {
rootViewController = Locator.slidingViewController
}
else {
rootViewController = Locator.loginViewController
}
// Setup basic view appearance
UINavigationBar.appearance().barTintColor = UQMainColor
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont.helveticaNeueLightFont(18), NSForegroundColorAttributeName: UIColor(white: 1.0, alpha: 0.9)]
UINavigationBar.appearance().translucent = false
self.window!.rootViewController = rootViewController
self.window!.makeKeyAndVisible()
// Parse set up
Parse.setApplicationId("JcvEfa2LZ6tdQQjDZ5nYAaJUslEOuU5qTrU9d4Yb", clientKey: "F66Ch6rXmkE75BcDXqS4cISJVcU4yh6CHmx5UZMP")
PFAnalytics.trackAppOpenedWithLaunchOptionsInBackground(launchOptions, block: nil)
// PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
ZHHParseDevice.trackDevice()
// Analytics set up
ARAnalytics.setupGoogleAnalyticsWithID("UA-45146473-5")
ARAnalytics.setupCrashlyticsWithAPIKey("d3ec53bc16086eec715f67dbf095bf3be047762c")
ARAnalytics.setupParseAnalyticsWithApplicationID("JcvEfa2LZ6tdQQjDZ5nYAaJUslEOuU5qTrU9d4Yb", clientKey: "F66Ch6rXmkE75BcDXqS4cISJVcU4yh6CHmx5UZMP")
ARAnalytics.event("App Launch")
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| cf7cf468184caefb8089b99e8a8ade7f | 47.628205 | 285 | 0.73082 | false | false | false | false |
smdls/C0 | refs/heads/master | C0/Document.swift | gpl-3.0 | 1 | /*
Copyright 2017 S
This file is part of C0.
C0 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.
C0 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 C0. If not, see <http://www.gnu.org/licenses/>.
*/
import Cocoa
protocol SceneEntityDelegate: class {
func changedUpdateWithPreference(_ sceneEntity: SceneEntity)
}
final class SceneEntity {
let preferenceKey = "preference", cutsKey = "cuts", materialsKey = "materials"
weak var delegate: SceneEntityDelegate?
var preference = Preference(), cutEntities = [CutEntity]()
init() {
let cutEntity = CutEntity()
cutEntity.sceneEntity = self
cutEntities = [cutEntity]
cutsFileWrapper = FileWrapper(directoryWithFileWrappers: [String(0): cutEntity.fileWrapper])
materialsFileWrapper = FileWrapper(directoryWithFileWrappers: [String(0): cutEntity.materialWrapper])
rootFileWrapper = FileWrapper(directoryWithFileWrappers: [
preferenceKey : preferenceFileWrapper,
cutsKey: cutsFileWrapper,
materialsKey: materialsFileWrapper
])
}
var rootFileWrapper = FileWrapper() {
didSet {
if let fileWrappers = rootFileWrapper.fileWrappers {
if let fileWrapper = fileWrappers[preferenceKey] {
preferenceFileWrapper = fileWrapper
}
if let fileWrapper = fileWrappers[cutsKey] {
cutsFileWrapper = fileWrapper
}
if let fileWrapper = fileWrappers[materialsKey] {
materialsFileWrapper = fileWrapper
}
}
}
}
var preferenceFileWrapper = FileWrapper()
var cutsFileWrapper = FileWrapper() {
didSet {
if let fileWrappers = cutsFileWrapper.fileWrappers {
let sortedFileWrappers = fileWrappers.sorted {
$0.key.localizedStandardCompare($1.key) == .orderedAscending
}
cutEntities = sortedFileWrappers.map {
return CutEntity(fileWrapper: $0.value, index: Int($0.key) ?? 0, sceneEntity: self)
}
}
}
}
var materialsFileWrapper = FileWrapper() {
didSet {
if let fileWrappers = materialsFileWrapper.fileWrappers {
let sortedFileWrappers = fileWrappers.sorted {
$0.key.localizedStandardCompare($1.key) == .orderedAscending
}
for (i, cutEntity) in cutEntities.enumerated() {
if i < sortedFileWrappers.count {
cutEntity.materialWrapper = sortedFileWrappers[i].value
}
}
}
}
}
func read() {
readPreference()
for cutEntity in cutEntities {
cutEntity.read()
}
}
func write() {
writePreference()
for cutEntity in cutEntities {
cutEntity.write()
}
}
func allWrite() {
isUpdatePreference = true
writePreference()
for cutEntity in cutEntities {
cutEntity.isUpdate = true
cutEntity.isUpdateMaterial = true
cutEntity.write()
}
}
var isUpdatePreference = false {
didSet {
if isUpdatePreference != oldValue {
delegate?.changedUpdateWithPreference(self)
}
}
}
func readPreference() {
if let data = preferenceFileWrapper.regularFileContents, let preference = Preference.with(data) {
self.preference = preference
}
}
func writePreference() {
if isUpdatePreference {
writePreference(with: preference.data)
isUpdatePreference = false
}
}
func writePreference(with data: Data) {
rootFileWrapper.removeFileWrapper(preferenceFileWrapper)
preferenceFileWrapper = FileWrapper(regularFileWithContents: data)
preferenceFileWrapper.preferredFilename = preferenceKey
rootFileWrapper.addFileWrapper(preferenceFileWrapper)
}
func insert(_ cutEntity: CutEntity, at index: Int) {
if index < cutEntities.count {
for i in (index ..< cutEntities.count).reversed() {
let cutEntity = cutEntities[i]
cutsFileWrapper.removeFileWrapper(cutEntity.fileWrapper)
cutEntity.fileWrapper.preferredFilename = String(i + 1)
cutsFileWrapper.addFileWrapper(cutEntity.fileWrapper)
materialsFileWrapper.removeFileWrapper(cutEntity.materialWrapper)
cutEntity.materialWrapper.preferredFilename = String(i + 1)
materialsFileWrapper.addFileWrapper(cutEntity.materialWrapper)
cutEntity.index = i + 1
}
}
cutEntity.fileWrapper.preferredFilename = String(index)
cutEntity.index = index
cutEntity.materialWrapper.preferredFilename = String(index)
cutsFileWrapper.addFileWrapper(cutEntity.fileWrapper)
materialsFileWrapper.addFileWrapper(cutEntity.materialWrapper)
cutEntities.insert(cutEntity, at: index)
cutEntity.sceneEntity = self
}
func removeCutEntity(at index: Int) {
let cutEntity = cutEntities[index]
cutsFileWrapper.removeFileWrapper(cutEntity.fileWrapper)
materialsFileWrapper.removeFileWrapper(cutEntity.materialWrapper)
cutEntity.sceneEntity = nil
cutEntities.remove(at: index)
for i in index ..< cutEntities.count {
let cutEntity = cutEntities[i]
cutsFileWrapper.removeFileWrapper(cutEntity.fileWrapper)
cutEntity.fileWrapper.preferredFilename = String(i)
cutsFileWrapper.addFileWrapper(cutEntity.fileWrapper)
materialsFileWrapper.removeFileWrapper(cutEntity.materialWrapper)
cutEntity.materialWrapper.preferredFilename = String(i)
materialsFileWrapper.addFileWrapper(cutEntity.materialWrapper)
cutEntity.index = i
}
}
var cuts: [Cut] {
return cutEntities.map { $0.cut }
}
}
final class CutEntity: Equatable {
weak var sceneEntity: SceneEntity!
var cut: Cut, index: Int
var fileWrapper = FileWrapper(), materialWrapper = FileWrapper()
var isUpdate = false, isUpdateMaterial = false, useWriteMaterial = false, isReadContent = true
init(fileWrapper: FileWrapper, index: Int, sceneEntity: SceneEntity? = nil) {
cut = Cut()
self.fileWrapper = fileWrapper
self.index = index
self.sceneEntity = sceneEntity
}
init(cut: Cut = Cut(), index: Int = 0) {
self.cut = cut
self.index = index
}
func read() {
if let s = fileWrapper.preferredFilename {
index = Int(s) ?? 0
} else {
index = 0
}
isReadContent = false
readContent()
}
func readContent() {
if !isReadContent {
if let data = fileWrapper.regularFileContents, let cut = Cut.with(data) {
self.cut = cut
}
if let materialsData = materialWrapper.regularFileContents, !materialsData.isEmpty {
if let materialCellIDs = NSKeyedUnarchiver.unarchiveObject(with: materialsData) as? [MaterialCellID] {
cut.materialCellIDs = materialCellIDs
useWriteMaterial = true
}
}
isReadContent = true
}
}
func write() {
if isUpdate {
writeCut(with: cut.data)
isUpdate = false
isUpdateMaterial = false
if useWriteMaterial {
writeMaterials(with: Data())
useWriteMaterial = false
}
}
if isUpdateMaterial {
writeMaterials(with: NSKeyedArchiver.archivedData(withRootObject: cut.materialCellIDs))
isUpdateMaterial = false
useWriteMaterial = true
}
}
func writeCut(with data: Data) {
sceneEntity.cutsFileWrapper.removeFileWrapper(fileWrapper)
fileWrapper = FileWrapper(regularFileWithContents: data)
fileWrapper.preferredFilename = String(index)
sceneEntity.cutsFileWrapper.addFileWrapper(fileWrapper)
}
func writeMaterials(with data: Data) {
sceneEntity.materialsFileWrapper.removeFileWrapper(materialWrapper)
materialWrapper = FileWrapper(regularFileWithContents: data)
materialWrapper.preferredFilename = String(index)
sceneEntity.materialsFileWrapper.addFileWrapper(materialWrapper)
isUpdateMaterial = false
}
static func == (lhs: CutEntity, rhs: CutEntity) -> Bool {
return lhs === rhs
}
}
final class Preference: NSObject, NSCoding {
var version = Bundle.main.version
var isFullScreen = false, windowFrame = NSRect()
var scene = Scene()
init(version: Int = Bundle.main.version, isFullScreen: Bool = false, windowFrame: NSRect = NSRect(), scene: Scene = Scene()) {
self.version = version
self.isFullScreen = isFullScreen
self.windowFrame = windowFrame
self.scene = scene
super.init()
}
static let dataType = "C0.Preference.1", versionKey = "0", isFullScreenKey = "1", windowFrameKey = "2", sceneKey = "3"
init?(coder: NSCoder) {
version = coder.decodeInteger(forKey: Preference.versionKey)
isFullScreen = coder.decodeBool(forKey: Preference.isFullScreenKey)
windowFrame = coder.decodeRect(forKey: Preference.windowFrameKey)
scene = coder.decodeObject(forKey: Preference.sceneKey) as? Scene ?? Scene()
super.init()
}
func encode(with coder: NSCoder) {
coder.encode(version, forKey: Preference.versionKey)
coder.encode(isFullScreen, forKey: Preference.isFullScreenKey)
coder.encode(windowFrame, forKey: Preference.windowFrameKey)
coder.encode(scene, forKey: Preference.sceneKey)
}
}
final class MaterialCellID: NSObject, NSCoding {
var material: Material, cellIDs: [UUID]
init(material: Material, cellIDs: [UUID]) {
self.material = material
self.cellIDs = cellIDs
super.init()
}
static let dataType = "C0.MaterialCellID.1", materialKey = "0", cellIDsKey = "1"
init?(coder: NSCoder) {
material = coder.decodeObject(forKey: MaterialCellID.materialKey) as? Material ?? Material()
cellIDs = coder.decodeObject(forKey: MaterialCellID.cellIDsKey) as? [UUID] ?? []
super.init()
}
func encode(with coder: NSCoder) {
coder.encode(material, forKey: MaterialCellID.materialKey)
coder.encode(cellIDs, forKey: MaterialCellID.cellIDsKey)
}
}
@NSApplicationMain final class AppDelegate: NSObject, NSApplicationDelegate {}
final class Document: NSDocument, NSWindowDelegate, SceneEntityDelegate {
let sceneEntity = SceneEntity()
var window: NSWindow {
return windowControllers.first!.window!
}
weak var screen: Screen!, sceneView: SceneView!
override init() {
super.init()
}
convenience init(type typeName: String) throws {
self.init()
fileType = typeName
}
override class func autosavesInPlace() -> Bool {
return true
}
override func makeWindowControllers() {
let storyboard = NSStoryboard(name: "Main", bundle: nil)
let windowController = storyboard.instantiateController(withIdentifier: "Document Window Controller") as! NSWindowController
addWindowController(windowController)
screen = windowController.contentViewController!.view as! Screen
let sceneView = SceneView()
sceneView.displayActionNode = screen.actionNode
sceneView.sceneEntity = sceneEntity
self.sceneView = sceneView
screen.contentView = sceneView
setupWindow(with: sceneEntity.preference)
sceneEntity.delegate = self
}
private func setupWindow(with preference: Preference) {
if preference.windowFrame.isEmpty, let frame = NSScreen.main()?.frame {
let fitSizeWithHiddenCommand = NSSize(width: 860, height: 740), fitSizeWithShownCommand = NSSize(width: 1050, height: 740)
let size = sceneView.isHiddenCommand ? fitSizeWithHiddenCommand : fitSizeWithShownCommand
let origin = NSPoint(x: round((frame.width - size.width)/2), y: round((frame.height - size.height)/2))
preference.windowFrame = NSRect(origin: origin, size: size)
}
window.setFrame(preference.windowFrame, display: false)
if preference.isFullScreen {
window.toggleFullScreen(nil)
}
window.delegate = self
}
override func fileWrapper(ofType typeName: String) throws -> FileWrapper {
sceneEntity.write()
return sceneEntity.rootFileWrapper
}
override func read(from fileWrapper: FileWrapper, ofType typeName: String) throws {
sceneEntity.rootFileWrapper = fileWrapper
sceneEntity.read()
}
func changedUpdateWithPreference(_ sceneEntity: SceneEntity) {
if sceneEntity.isUpdatePreference {
updateChangeCount(.changeDone)
}
}
func windowDidResize(_ notification: Notification) {
sceneEntity.preference.windowFrame = window.frame
sceneEntity.isUpdatePreference = true
}
func windowDidEnterFullScreen(_ notification: Notification) {
sceneEntity.preference.isFullScreen = true
sceneEntity.isUpdatePreference = true
}
func windowDidExitFullScreen(_ notification: Notification) {
sceneEntity.preference.isFullScreen = false
sceneEntity.isUpdatePreference = true
}
override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
guard let action = menuItem.action else {
return true
}
switch action {
case #selector(shownCommand(_:)):
menuItem.state = !sceneView.isHiddenCommand ? NSOnState : NSOffState
case #selector(hiddenCommand(_:)):
menuItem.state = sceneView.isHiddenCommand ? NSOnState : NSOffState
case #selector(exportMovie720pFromSelectionCut(_:)):
menuItem.title = String(format: "Export 720p Movie with %@...".localized, "C\(sceneView.timeline.selectionCutEntity.index + 1)")
case #selector(exportMovie1080pFromSelectionCut(_:)):
menuItem.title = String(format: "Export 1080p Movie with %@...".localized, "C\(sceneView.timeline.selectionCutEntity.index + 1)")
default:
break
}
return true
}
@IBAction func shownCommand(_ sender: Any?) {
for document in NSDocumentController.shared().documents {
(document as? Document)?.sceneView.isHiddenCommand = false
}
}
@IBAction func hiddenCommand(_ sender: Any?) {
for document in NSDocumentController.shared().documents {
(document as? Document)?.sceneView.isHiddenCommand = true
}
}
@IBAction func exportMovie720p(_ sender: Any?) {
sceneView.renderView.exportMovie(message: (sender as? NSMenuItem)?.title ?? "", size: CGSize(width: 1280, height: 720), fps: 24, isSelectionCutOnly: false)
}
@IBAction func exportMovie1080p(_ sender: Any?) {
sceneView.renderView.exportMovie(message: (sender as? NSMenuItem)?.title ?? "", size: CGSize(width: 1920, height: 1080), fps: 24, isSelectionCutOnly: false)
}
@IBAction func exportMovie720pFromSelectionCut(_ sender: Any?) {
sceneView.renderView.exportMovie(message: (sender as? NSMenuItem)?.title ?? "", name: "C\(sceneView.timeline.selectionCutEntity.index + 1)", size: CGSize(width: 1280, height: 720), fps: 24, isSelectionCutOnly: true)
}
@IBAction func exportMovie1080pFromSelectionCut(_ sender: Any?) {
sceneView.renderView.exportMovie(message: (sender as? NSMenuItem)?.title ?? "", name: "C\(sceneView.timeline.selectionCutEntity.index + 1)", size: CGSize(width: 1920, height: 1080), fps: 24, isSelectionCutOnly: true)
}
@IBAction func exportImage720p(_ sender: Any?) {
sceneView.renderView.exportImage(message: (sender as? NSMenuItem)?.title ?? "", size: CGSize(width: 1280, height: 720))
}
@IBAction func exportImage1080p(_ sender: Any?) {
sceneView.renderView.exportImage(message: (sender as? NSMenuItem)?.title ?? "", size: CGSize(width: 1920, height: 1080))
}
@IBAction func screenshot(_ sender: Any?) {
let savePanel = NSSavePanel()
savePanel.nameFieldStringValue = "screenshot"
savePanel.allowedFileTypes = [String(kUTTypePNG)]
savePanel.beginSheetModal(for: window) { [unowned savePanel] result in
if result == NSFileHandlingPanelOKButton, let url = savePanel.url {
do {
try self.screenshotImage?.PNGRepresentation?.write(to: url)
try FileManager.default.setAttributes([FileAttributeKey.extensionHidden: savePanel.isExtensionHidden], ofItemAtPath: url.path)
}
catch {
self.screen.errorNotification(NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError))
}
}
}
}
var screenshotImage: NSImage? {
let padding = 5.0.cf*sceneView.layer.contentsScale
let bounds = sceneView.clipView.layer.bounds.inset(by: -padding)
if let colorSpace = CGColorSpace(name: CGColorSpace.sRGB), let ctx = CGContext(data: nil, width: Int(bounds.width*sceneView.layer.contentsScale), height: Int(bounds.height*sceneView.layer.contentsScale), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue), let color = screen.rootView.layer.backgroundColor {
ctx.setFillColor(color)
ctx.fill(CGRect(x: 0, y: 0, width: bounds.width*sceneView.layer.contentsScale, height: bounds.height*sceneView.layer.contentsScale))
ctx.translateBy(x: padding*sceneView.layer.contentsScale, y: padding*sceneView.layer.contentsScale)
ctx.scaleBy(x: sceneView.layer.contentsScale, y: sceneView.layer.contentsScale)
CATransaction.disableAnimation {
sceneView.clipView.layer.render(in: ctx)
}
if let cgImage = ctx.makeImage() {
return NSImage(cgImage: cgImage, size: NSSize())
}
}
return nil
}
@IBAction func openHelp(_ sender: Any?) {
if let url = URL(string: "https://github.com/smdls/C0") {
NSWorkspace.shared().open(url)
}
}
}
| 208614c91bf6edfc71dfc2a11510cbeb | 39.4375 | 378 | 0.63694 | false | false | false | false |
KrishMunot/swift | refs/heads/master | test/SILGen/vtable_thunks.swift | apache-2.0 | 5 | // RUN: %target-swift-frontend -sdk %S/Inputs -emit-silgen -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module | FileCheck %s
protocol AddrOnly {}
@objc class B {
// We only allow B! -> B overrides for @objc methods.
// The IUO force-unwrap requires a thunk.
@objc func iuo(x: B, y: B!, z: B) -> B? {}
// f* don't require thunks, since the parameters and returns are object
// references.
func f(x: B, y: B) -> B? {}
func f2(x: B, y: B) -> B? {}
func f3(x: B, y: B) -> B {}
func f4(x: B, y: B) -> B {}
// Thunking monomorphic address-only params and returns
func g(x: AddrOnly, y: AddrOnly) -> AddrOnly? {}
func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly? {}
func g3(x: AddrOnly, y: AddrOnly) -> AddrOnly {}
func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {}
// Thunking polymorphic address-only params and returns
func h<T>(x: T, y: T) -> T? {}
func h2<T>(x: T, y: T) -> T? {}
func h3<T>(x: T, y: T) -> T {}
func h4<T>(x: T, y: T) -> T {}
// Thunking value params and returns
func i(x: Int, y: Int) -> Int? {}
func i2(x: Int, y: Int) -> Int? {}
func i3(x: Int, y: Int) -> Int {}
func i4(x: Int, y: Int) -> Int {}
// Note: i3, i4 are implicitly @objc
}
class D: B {
override func iuo(x: B?, y: B, z: B) -> B {}
override func f(x: B?, y: B) -> B {}
override func f2(x: B, y: B) -> B {}
override func f3(x: B?, y: B) -> B {}
override func f4(x: B, y: B) -> B {}
override func g(x: AddrOnly?, y: AddrOnly) -> AddrOnly {}
override func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly {}
override func g3(x: AddrOnly?, y: AddrOnly) -> AddrOnly {}
override func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {}
override func h<U>(x: U?, y: U) -> U {}
override func h2<U>(x: U, y: U) -> U {}
override func h3<U>(x: U?, y: U) -> U {}
override func h4<U>(x: U, y: U) -> U {}
override func i(x: Int?, y: Int) -> Int {}
override func i2(x: Int, y: Int) -> Int {}
// Int? cannot be represented in ObjC so the override has to be
// explicitly @nonobjc
@nonobjc override func i3(x: Int?, y: Int) -> Int {}
override func i4(x: Int, y: Int) -> Int {}
}
// Inherits the thunked impls from D
class E: D { }
// Overrides w/ its own thunked impls
class F: D {
override func f(x: B?, y: B) -> B {}
override func f2(x: B, y: B) -> B {}
override func f3(x: B?, y: B) -> B {}
override func f4(x: B, y: B) -> B {}
override func g(x: AddrOnly?, y: AddrOnly) -> AddrOnly {}
override func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly {}
override func g3(x: AddrOnly?, y: AddrOnly) -> AddrOnly {}
override func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {}
override func h<U>(x: U?, y: U) -> U {}
override func h2<U>(x: U, y: U) -> U {}
override func h3<U>(x: U?, y: U) -> U {}
override func h4<U>(x: U, y: U) -> U {}
override func i(x: Int?, y: Int) -> Int {}
override func i2(x: Int, y: Int) -> Int {}
// Int? cannot be represented in ObjC so the override has to be
// explicitly @nonobjc
@nonobjc override func i3(x: Int?, y: Int) -> Int {}
override func i4(x: Int, y: Int) -> Int {}
}
// CHECK-LABEL: sil private @_TTVFC13vtable_thunks1D3iuo
// CHECK: [[WRAP_X:%.*]] = enum $Optional<B>
// CHECK: [[FORCE_UNWRAP_FN:%.*]] = function_ref @_TFs45_stdlib_ImplicitlyUnwrappedOptional_unwrappedurFGSQx_x
// CHECK: apply [[FORCE_UNWRAP_FN]]<B>([[UNWRAP_Y_ADDR:%[0-9]*]],
// CHECK: [[UNWRAP_Y:%.*]] = load [[UNWRAP_Y_ADDR]]
// CHECK: [[RES:%.*]] = apply {{%.*}}([[WRAP_X]], [[UNWRAP_Y]], %2, %3)
// CHECK: [[WRAP_RES:%.*]] = enum $Optional<B>, {{.*}} [[RES]]
// CHECK: return [[WRAP_RES]]
// CHECK-LABEL: sil private @_TTVFC13vtable_thunks1D1g
// TODO: extra copies here
// CHECK: [[WRAPPED_X_ADDR:%.*]] = init_enum_data_addr [[WRAP_X_ADDR:%.*]] :
// CHECK: copy_addr [take] {{%.*}} to [initialization] [[WRAPPED_X_ADDR]]
// CHECK: inject_enum_addr [[WRAP_X_ADDR]]
// CHECK: [[RES_ADDR:%.*]] = alloc_stack
// CHECK: apply {{%.*}}([[RES_ADDR]], [[WRAP_X_ADDR]], %2, %3)
// CHECK: [[DEST_ADDR:%.*]] = init_enum_data_addr %0
// CHECK: copy_addr [take] [[RES_ADDR]] to [initialization] [[DEST_ADDR]]
// CHECK: inject_enum_addr %0
class ThrowVariance {
func mightThrow() throws {}
}
class NoThrowVariance: ThrowVariance {
override func mightThrow() {}
}
// rdar://problem/20657811
class X<T: B> {
func foo(x: T) { }
}
class Y: X<D> {
override func foo(x: D) { }
}
// rdar://problem/21154055
// Ensure reabstraction happens when necessary to get a value in or out of an
// optional.
class Foo {
func foo(x: Int -> Int) -> (Int -> Int)? {}
}
class Bar: Foo {
override func foo(x: (Int -> Int)?) -> Int -> Int {}
}
// rdar://problem/21364764
// Ensure we can override an optional with an IUO or vice-versa.
struct S {}
class Aap {
func cat(b: B?) -> B? {}
func dog(b: B!) -> B! {}
func catFast(s: S?) -> S? {}
func dogFast(s: S!) -> S! {}
func flip() -> (() -> S?) {}
func map() -> S -> () -> Aap? {}
}
class Noot : Aap {
override func cat(b: B!) -> B! {}
override func dog(b: B?) -> B? {}
override func catFast(s: S!) -> S! {}
override func dogFast(s: S?) -> S? {}
override func flip() -> (() -> S) {}
override func map() -> S? -> () -> Noot {}
}
// CHECK-LABEL: sil private @_TTVFC13vtable_thunks3Bar3foo{{.*}} : $@convention(method) (@owned @callee_owned (Int) -> Int, @guaranteed Bar) -> @owned Optional<Int -> Int>
// CHECK: function_ref @_TTRXFo_dSi_dSi_XFo_iSi_iSi_
// CHECK: [[IMPL:%.*]] = function_ref @_TFC13vtable_thunks3Bar3foo{{.*}}
// CHECK: apply [[IMPL]]
// CHECK: function_ref @_TTRXFo_dSi_dSi_XFo_iSi_iSi_
// CHECK-LABEL: sil private @_TTVFC13vtable_thunks4Noot4flip{{.*}}
// CHECK: [[IMPL:%.*]] = function_ref @_TFC13vtable_thunks4Noot4flip{{.*}}
// CHECK: [[INNER:%.*]] = apply %1(%0)
// CHECK: [[THUNK:%.*]] = function_ref @_TTRXFo__dV13vtable_thunks1S_XFo__dGSqS0___
// CHECK: [[OUTER:%.*]] = partial_apply [[THUNK]]([[INNER]])
// CHECK: return [[OUTER]]
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__dV13vtable_thunks1S_XFo__dGSqS0___
// CHECK: [[INNER:%.*]] = apply %0()
// CHECK: [[OUTER:%.*]] = enum $Optional<S>, #Optional.some!enumelt.1, %1 : $S
// CHECK: return [[OUTER]] : $Optional<S>
// CHECK-LABEL: sil private @_TTVFC13vtable_thunks4Noot3map{{.*}}
// CHECK: [[IMPL:%.*]] = function_ref @_TFC13vtable_thunks4Noot3map{{.*}}
// CHECK: [[INNER:%.*]] = apply %1(%0)
// CHECK: [[THUNK:%.*]] = function_ref @_TTRXFo_dGSqV13vtable_thunks1S__oXFo__oCS_4Noot__XFo_dS0__oXFo__oGSqCS_3Aap___
// CHECK: [[OUTER:%.*]] = partial_apply [[THUNK]]([[INNER]])
// CHECK: return [[OUTER]]
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqV13vtable_thunks1S__oXFo__oCS_4Noot__XFo_dS0__oXFo__oGSqCS_3Aap___
// CHECK: [[ARG:%.*]] = enum $Optional<S>, #Optional.some!enumelt.1, %0
// CHECK: [[INNER:%.*]] = apply %1(%2)
// CHECK: [[OUTER:%.*]] = convert_function [[INNER]] : $@callee_owned () -> @owned Noot to $@callee_owned () -> @owned Optional<Aap>
// CHECK: return [[OUTER]]
// CHECK-LABEL: sil_vtable D {
// CHECK: #B.iuo!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f2!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f3!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g2!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g3!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h2!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h3!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i2!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i3!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK-LABEL: sil_vtable E {
// CHECK: #B.iuo!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f2!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f3!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g2!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g3!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h2!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h3!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i2!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i3!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK-LABEL: sil_vtable F {
// CHECK: #B.iuo!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f!1: _TF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.f2!1: _TF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.f3!1: _TF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.f4!1: _TF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.g!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.g2!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.g3!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.g4!1: _TF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.h!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.h2!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.h3!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.h4!1: _TF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.i!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.i2!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.i3!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.i4!1: _TF{{[A-Z0-9a-z_]*}}1F
// CHECK-LABEL: sil_vtable NoThrowVariance {
// CHECK: #ThrowVariance.mightThrow!1: _TF
| cbcec19a5f85d4e9c144f2ac4f12c98b | 38.124031 | 171 | 0.522191 | false | false | false | false |
chenyunguiMilook/VisualDebugger | refs/heads/master | Sources/VisualDebugger/proto/CoordinateSystem.swift | mit | 1 | //
// CoordinateSystem.swift
// VisualDebugger
//
// Created by chenyungui on 2018/3/19.
//
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
#else
import Cocoa
#endif
public class CoordinateSystem : CALayer {
public enum Kind {
case yDown, yUp
}
public enum Axis {
case x, y
}
public let minWidth: CGFloat = 250
public var type: Kind
public var area:CGRect
public var segmentLength:CGFloat = 50
public var scale: CGFloat = 1.5
public var numSegments:Int
public var showOrigin:Bool
// for transform values to current coordinate system space
public internal(set) var matrix = CGAffineTransform.identity
internal var colorIndex:Int = 0
internal var minSegmentLength: CGFloat {
return minWidth / CGFloat(numSegments)
}
public init(type: Kind, area:CGRect, scale:CGFloat, numSegments:Int, showOrigin:Bool, precision:Int = 5) {
self.type = type
self.area = area
self.scale = scale
self.numSegments = numSegments
self.showOrigin = showOrigin
super.init()
self.backgroundColor = AppColor.white.cgColor
let rect = showOrigin ? area.rectFromOrigin : area
let maxValue = max(rect.size.width, rect.size.height)
let segmentValue = CGFloat(getDivision(Double(maxValue), segments: numSegments))
let xAxisData = AxisData(min: rect.minX, max: rect.maxX, segmentValue: segmentValue)
let yAxisData = AxisData(min: rect.minY, max: rect.maxY, segmentValue: segmentValue)
let valueRect = CGRect(x: xAxisData.startValue, y: yAxisData.startValue, width: xAxisData.lengthValue, height: yAxisData.lengthValue)
let xAxisY: CGFloat = (valueRect.minY < 0 && valueRect.maxY >= 0) ? 0 : yAxisData.startValue
let yAxisX: CGFloat = (valueRect.minX < 0 && valueRect.maxX >= 0) ? 0 : xAxisData.startValue
// calculate axis segments in value space
let xAxisSegment = AxisSegment(start: CGPoint(x: xAxisData.startValue, y: xAxisY), end: CGPoint(x: xAxisData.endValue, y: xAxisY))
let yAxisSegment = AxisSegment(start: CGPoint(x: yAxisX, y: yAxisData.startValue), end: CGPoint(x: yAxisX, y: yAxisData.endValue))
// get axis labels and transform to render space
let precision = calculatePrecision(Double(segmentValue))
let formater = NumberFormatter(precision: precision)
var xAxisLabels = xAxisSegment.getLabels(axis: .x, segmentValue: segmentValue, numSegments: xAxisData.numSegments, numFormater: formater)
var yAxisLabels = yAxisSegment.getLabels(axis: .y, segmentValue: segmentValue, numSegments: yAxisData.numSegments, numFormater: formater)
// calculate the proper segment length
let xLabelBounds = xAxisLabels.reduce(CGRect.zero) { $0.union($1.label.bounds) }
self.segmentLength = xLabelBounds.width < minSegmentLength ? minSegmentLength : xLabelBounds.width
self.segmentLength = ceil(segmentLength * scale)
// calculate the matrix for transform value from value space to render space
let scale = self.segmentLength / segmentValue
self.matrix = CGAffineTransform(translationX: -valueRect.origin.x, y: -valueRect.origin.y)
self.matrix.scaleBy(x: scale, y: scale)
if self.type == .yUp {
let renderHeight = valueRect.height * scale
self.matrix.scaleBy(x: 1, y: -1)
self.matrix.translateBy(x: 0, y: renderHeight)
}
// until now we got correct transform matrix
// get axis labels and transform to render space
xAxisLabels = xAxisLabels * self.matrix
yAxisLabels = yAxisLabels * self.matrix
// render axis to self
let thickness: CGFloat = 8
renderAxis(axis: .x, coordinate: self.type, labels: xAxisLabels, labelOffset: ceil(xLabelBounds.height), thickness: thickness, to: self)
renderAxis(axis: .y, coordinate: self.type, labels: yAxisLabels, labelOffset: ceil(xLabelBounds.width/2) + thickness, thickness: thickness, to: self)
// setup frame
self.frame = valueRect.applying(self.matrix)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func getNextColor() -> AppColor {
let color = AppColor.get(self.colorIndex % colors.count)
self.colorIndex += 1
return color
}
public func render(object: Debuggable, color: AppColor? = nil) {
object.debug(in: self, color: color)
}
}
func renderAxis(axis: CoordinateSystem.Axis, coordinate: CoordinateSystem.Kind, labels: [AxisLabel], labelOffset: CGFloat, thickness: CGFloat, to layer: CALayer) {
let path = AppBezierPath()
let half = thickness/2
let start = labels[0].position
var vector = (labels[1].position - start)
vector = vector.normalized(to: min(vector.length/2, thickness*3))
let end = labels.last!.position + vector
var labelOffsetX: CGFloat = 0
var labelOffsetY: CGFloat = 0
var lineOffsetX: CGFloat = 0
var lineOffsetY: CGFloat = 0
switch (axis, coordinate) {
case (.x, .yUp): labelOffsetY = labelOffset; lineOffsetY = half
case (.x, .yDown): labelOffsetY = -labelOffset; lineOffsetY = -half
case (.y, .yUp): labelOffsetX = -labelOffset; lineOffsetX = -half
case (.y, .yDown): labelOffsetX = -labelOffset; lineOffsetX = -half
}
// 1. draw main axis
path.move(to: start)
path.addLine(to: end)
// 2. draw short lines
for i in 0 ..< labels.count {
let position = labels[i].position
let lineEnd = CGPoint(x: position.x + lineOffsetX, y: position.y + lineOffsetY)
path.move(to: position)
path.addLine(to: lineEnd)
}
// 3. draw end arrow
path.append(AxisArrow().pathAtEndOfSegment(segStart: start, segEnd: end))
// 4. add bezier path layer
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = 0.5
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = AppColor.lightGray.cgColor
shapeLayer.fillColor = nil
shapeLayer.masksToBounds = false
layer.addSublayer(shapeLayer)
// 5. add labels layer
for label in labels {
let x = label.position.x + labelOffsetX
let y = label.position.y + labelOffsetY
let center = CGPoint(x: x, y: y)
label.label.setCenter(center)
layer.addSublayer(label.label)
}
}
| cd2ca46812954fe3bafe198574248c23 | 37.625731 | 163 | 0.65617 | false | false | false | false |
hemantasapkota/SwiftStore | refs/heads/master | Example/SwiftStoreExample/SwiftStoreExample/SimpleRowView.swift | mit | 1 | //
// RowView.swift
// SwiftStoreExample
//
// Created by Hemanta Sapkota on 31/05/2015.
// Copyright (c) 2015 Hemanta Sapkota. All rights reserved.
//
import Foundation
import UIKit
/* Simple Row View */
class SimpleRowView : UIView {
/* Label */
var label: UILabel!
/* Key Text */
var keyText: UITextField!
/* Value Text */
var valueText: UITextField!
/* Save Button */
var saveBtn: UIButton!
/* Delete */
var deleteBtn: UIButton!
/* Handler */
var onSave: ( (String, String) -> Void)?
/* Handler */
var onDelete: ( (String) -> Void)?
init(rowNumber: Int, key: String) {
super.init(frame: UIScreen.main.bounds)
label = UILabel()
label.text = "\(rowNumber)"
label.textColor = UIColor(rgba: "#2c3e50")
addSubview(label)
label.snp_makeConstraints { (make) -> Void in
make.top.equalTo(5)
make.left.equalTo(5)
}
keyText = UITextField()
keyText.layer.borderWidth = 0.5
keyText.layer.borderColor = UIColor(rgba: "#bdc3c7").cgColor
keyText.placeholder = "Key"
keyText.text = "\(key)"
keyText.isEnabled = false
addSubview(keyText)
keyText.snp_makeConstraints { (make) -> Void in
make.top.greaterThanOrEqualTo(5)
make.left.equalTo(label.snp_right).offset(10)
make.width.equalTo(self.snp_width).offset(-60)
make.height.equalTo(30)
}
valueText = UITextField()
valueText.placeholder = "Value"
valueText.layer.borderWidth = 0.5
valueText.layer.borderColor = UIColor(rgba: "#bdc3c7").cgColor
addSubview(valueText)
valueText.snp_makeConstraints { (make) -> Void in
make.top.greaterThanOrEqualTo(keyText.snp_bottom).offset(5)
make.left.equalTo(label.snp_right).offset(10)
make.width.equalTo(self.snp_width).offset(-60)
make.height.equalTo(30)
}
saveBtn = UIButton(type: UIButton.ButtonType.system)
saveBtn.setTitleColor(UIColor.white, for: UIControl.State())
saveBtn.setTitle("Save", for: UIControl.State())
saveBtn.backgroundColor = UIColor(rgba: "#27ae60")
addSubview(saveBtn)
saveBtn.snp_makeConstraints { (make) -> Void in
make.top.greaterThanOrEqualTo(valueText.snp_bottom).offset(5)
make.left.equalTo(valueText.snp_left)
make.width.equalTo(self.snp_width).dividedBy(3)
}
deleteBtn = UIButton(type: UIButton.ButtonType.system)
deleteBtn.setTitleColor(UIColor.white, for: UIControl.State())
deleteBtn.setTitle("Delete", for: UIControl.State())
deleteBtn.backgroundColor = UIColor(rgba: "#e74c3c")
addSubview(deleteBtn)
deleteBtn.snp_makeConstraints { (make) -> Void in
make.top.greaterThanOrEqualTo(valueText.snp_bottom).offset(5)
make.right.equalTo(valueText.snp_right)
make.width.equalTo(self.snp_width).dividedBy(3)
}
let sep = UILabel()
sep.backgroundColor = UIColor(rgba: "#bdc3c7")
addSubview(sep)
sep.snp_makeConstraints { (make) -> Void in
make.height.equalTo(0.5)
make.bottom.equalTo(self.snp_bottom)
make.width.equalTo(self.snp_width)
}
saveBtn.addTarget(self, action: #selector(SimpleRowView.handleSave), for: UIControl.Event.touchUpInside)
deleteBtn.addTarget(self, action: #selector(SimpleRowView.handleDelete), for: UIControl.Event.touchUpInside)
}
@objc func handleSave() {
if let executeSave = onSave {
let key = keyText.text!.trimmingCharacters(in: CharacterSet.whitespaces)
let value = valueText.text!.trimmingCharacters(in: CharacterSet.whitespaces)
executeSave(key, value)
}
}
@objc func handleDelete() {
valueText.text = ""
if let executeDelete = onDelete {
let key = keyText.text!.trimmingCharacters(in: CharacterSet.whitespaces)
executeDelete(key)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| a5ac83797b553dcb4a4db765dffb1014 | 32.821705 | 116 | 0.602796 | false | false | false | false |
lojals/curiosity_reader | refs/heads/master | curiosity_reader/curiosity_reader/src/components/LeftMenu.swift | gpl-2.0 | 1 | //
// LeftMenu.swift
// Yo Intervengo
//
// Created by Jorge Raul Ovalle Zuleta on 1/14/15.
// Copyright (c) 2015 Olinguito. All rights reserved.
//
import Foundation
import UIKit
@objc protocol LeftMenuDelegate{
optional func goTo(index:Int)
}
class LeftMenu: UIView{
var opened = false
var btnRep:UIButton!
var btnWiki:UIButton!
var btnStat:UIButton!
var btnProf:UIButton!
var btnSett:UIButton!
var delegate:LeftMenuDelegate?
var btnBack:UIButton!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.themeMain().colorWithAlphaComponent(0.98)
let spacer = 10
let size:CGFloat = frame.width - 40
btnRep = UIButton(frame: CGRect(x: 20, y: 76, width: size, height: 26))
btnWiki = UIButton(frame: CGRect(x: 20, y: btnRep.frame.maxY+10, width: size, height: 26))
btnStat = UIButton(frame: CGRect(x: 20, y: btnWiki.frame.maxY+10, width: size, height: 26))
btnProf = UIButton(frame: CGRect(x: 20, y: btnStat.frame.maxY+10, width: size, height: 26))
btnRep.setTitle("Inicio", forState: UIControlState.Normal)
btnWiki.setTitle("Perfil", forState: UIControlState.Normal)
btnStat.setTitle("Categorías", forState: UIControlState.Normal)
btnProf.setTitle("Acerca de", forState: UIControlState.Normal)
btnRep.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
btnWiki.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
btnStat.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
btnProf.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
btnRep.titleLabel?.font = UIFont.fontRegular(20)
btnWiki.titleLabel?.font = UIFont.fontRegular(20)
btnStat.titleLabel?.font = UIFont.fontRegular(20)
btnProf.titleLabel?.font = UIFont.fontRegular(20)
btnRep.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Right
btnWiki.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Right
btnStat.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Right
btnProf.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Right
btnRep.tag = 3330;
btnWiki.tag = 3331;
btnStat.tag = 3332;
btnProf.tag = 3333;
btnRep.addTarget(self, action: "goBtn:", forControlEvents: UIControlEvents.TouchUpInside)
btnWiki.addTarget(self, action: "goBtn:", forControlEvents: UIControlEvents.TouchUpInside)
btnStat.addTarget(self, action: "goBtn:", forControlEvents: UIControlEvents.TouchUpInside)
btnProf.addTarget(self, action: "goBtn:", forControlEvents: UIControlEvents.TouchUpInside)
btnBack = UIButton.buttonWithType(UIButtonType.System) as! UIButton
btnBack.frame = CGRectMake(0, 0, 50, 50)
btnBack.tintColor = UIColor.whiteColor()
btnBack.setImage(UIImage(named: "btnMenu"), forState: UIControlState.Normal)
btnBack.addTarget(self, action: "interact", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(btnBack)
self.addSubview(btnRep)
self.addSubview(btnWiki)
self.addSubview(btnStat)
self.addSubview(btnProf)
opened = false
}
func interact(){
var spAn = POPBasicAnimation(propertyNamed:kPOPViewCenter)
spAn.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
if opened{
spAn.toValue = NSValue(CGPoint: CGPointMake(-100, self.center.y))
}
else{
spAn.toValue = NSValue(CGPoint: CGPointMake(100, self.center.y))
}
opened = !opened
self.pop_addAnimation(spAn, forKey: "center")
}
func setColor(idBtn:Int){
btnRep.titleLabel?.font = UIFont.fontRegular(20)
btnWiki.titleLabel?.font = UIFont.fontRegular(20)
btnStat.titleLabel?.font = UIFont.fontRegular(20)
btnProf.titleLabel?.font = UIFont.fontRegular(20)
//sender.setTitleColor( UIColor.orangeYI() , forState: UIControlState.Normal)
(self.viewWithTag(idBtn) as! UIButton).titleLabel?.font = UIFont.fontBold(21)
}
func goBtn(sender:UIButton){
setColor(sender.tag)
self.delegate!.goTo!(sender.tag - 3330)
}
}
| 982e3c70cbc5a95e8e29bed752f887f0 | 38.57265 | 100 | 0.667603 | false | false | false | false |
skedgo/tripkit-ios | refs/heads/main | Sources/TripKitUI/views/results/TKUIRoutingSupportView+Show.swift | apache-2.0 | 1 | //
// TKUIRoutingSupportView+Show.swift
// TripKitUI-iOS
//
// Created by Adrian Schönig on 09.07.18.
// Copyright © 2018 SkedGo Pty Ltd. All rights reserved.
//
import UIKit
import TripKit
extension TKUIRoutingSupportView {
static func clear(from view: UIView) {
view.subviews
.filter { $0 is TKUIRoutingSupportView }
.forEach { $0.removeFromSuperview() }
}
static func show(
with error: Error,
for request: TripRequest? = nil,
in view: UIView,
aboveSubview: UIView? = nil,
topPadding: CGFloat = 0,
allowRequest: Bool
) -> TKUIRoutingSupportView {
// Start fresh
clear(from: view)
let message = buildPrefilledSupportMessage(for: request) ?? NSAttributedString(string: error.localizedDescription)
let supportView = TKUIRoutingSupportView.makeView(with: message, allowRoutingRequest: allowRequest)
supportView.backgroundColor = .tkBackground
supportView.translatesAutoresizingMaskIntoConstraints = false
if let above = aboveSubview {
view.insertSubview(supportView, aboveSubview: above)
} else {
view.addSubview(supportView)
}
supportView.topAnchor.constraint(equalTo: view.topAnchor, constant: topPadding).isActive = true
supportView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: supportView.trailingAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: supportView.bottomAnchor).isActive = true
return supportView
}
private static func buildPrefilledSupportMessage(for request: TripRequest?) -> NSAttributedString? {
guard
let fromAddress = request?.fromLocation.address,
let toAddress = request?.toLocation.address else {
return nil
}
// Set attributes
let font = TKStyleManager.boldCustomFont(forTextStyle: .body)
// Build the final string
let text = Loc.RoutingFrom(fromAddress, toIsNotYetSupported: toAddress)
let message = NSMutableAttributedString(string: text)
let attributes: [NSAttributedString.Key : Any] = [
.foregroundColor: UIColor.tkLabelPrimary,
.font: font
]
let fromRange = (text as NSString).range(of: fromAddress)
message.addAttributes(attributes, range: fromRange)
let toRange = (text as NSString).range(of: toAddress)
message.addAttributes(attributes, range: toRange)
return message
}
}
| c05bb65d6bf7487ab90ba3bb7c0676e6 | 30.253165 | 118 | 0.706359 | false | false | false | false |
Anders123fr/Swift-Extensions | refs/heads/master | Swift-Extensions/Extensions/UIAlert.swift | apache-2.0 | 1 | //
// UIAlert.swift
// SwiftExtensions
//
// Created by Anders Friis on 25/11/2016.
// Copyright © 2016 cromian. All rights reserved.
//
import UIKit
public extension UIAlertController {
// GLOBAL ALERT FUNCTIONS
// Shows a standard alert to the user with a title and an optional message.
// The alert then has an OK button
static func show(_ title: String, message: String? = nil) {
// Create the alert
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
// Add the OK button
alertController.addAction(UIAlertAction(title: kOK, style: UIAlertActionStyle.default) {
action in
})
alertController.view.tag = getAlertTag()
// Show alert that the current app version is too low and an update is required
if let vc = findCurrentViewController() {
vc.present(alertController, animated: true) {}
}
}
static func getAlertTag() -> Int {
return 191756
}
static func isAlertAlreadyShown() -> Bool {
if let rv = UIApplication.shared.keyWindow?.subviews.first,
let _ = rv.viewWithTag(getAlertTag()) {
return true
}
return false
}
}
| ea31c03b3e4e404840507e8934d5a6bb | 24.666667 | 119 | 0.709957 | false | false | false | false |
tectijuana/iOS | refs/heads/master | FernandoDominguez/p3.swift | mit | 2 | import Foundation
///lista de 20 enteros
var lista=[20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1]
let con=lista.count
var lista2:[Int]=[]
print("Lista original: ",lista)
var num=19
var acumu=0
var acumu1=0
for i in 0...con-1
{
acumu1=lista[num]
lista2+=[acumu1]
num=num-1
}
print("lista actualizada: ",lista2)
| 3710391ce5c66eeeaa83c485e88b64f4 | 11.538462 | 62 | 0.674847 | false | false | false | false |
contra/cordova-plugin-iosrtc | refs/heads/master | src/PluginGetUserMedia.swift | mit | 2 | import Foundation
import AVFoundation
class PluginGetUserMedia {
var rtcPeerConnectionFactory: RTCPeerConnectionFactory
init(rtcPeerConnectionFactory: RTCPeerConnectionFactory) {
NSLog("PluginGetUserMedia#init()")
self.rtcPeerConnectionFactory = rtcPeerConnectionFactory
}
func call(
constraints: NSDictionary,
callback: (data: NSDictionary) -> Void,
errback: (error: String) -> Void,
eventListenerForNewStream: (pluginMediaStream: PluginMediaStream) -> Void
) {
NSLog("PluginGetUserMedia#call()")
let audioRequested = constraints.objectForKey("audio") as? Bool ?? false
let videoRequested = constraints.objectForKey("video") as? Bool ?? false
let videoDeviceId = constraints.objectForKey("videoDeviceId") as? String
var rtcMediaStream: RTCMediaStream
var pluginMediaStream: PluginMediaStream?
var rtcAudioTrack: RTCAudioTrack?
var rtcVideoTrack: RTCVideoTrack?
var rtcVideoCapturer: RTCVideoCapturer?
var rtcVideoSource: RTCVideoSource?
var videoDevice: AVCaptureDevice?
if videoRequested == true {
switch AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) {
case AVAuthorizationStatus.NotDetermined:
NSLog("PluginGetUserMedia#call() | video authorization: not determined")
case AVAuthorizationStatus.Authorized:
NSLog("PluginGetUserMedia#call() | video authorization: authorized")
case AVAuthorizationStatus.Denied:
NSLog("PluginGetUserMedia#call() | video authorization: denied")
errback(error: "video denied")
return
case AVAuthorizationStatus.Restricted:
NSLog("PluginGetUserMedia#call() | video authorization: restricted")
errback(error: "video restricted")
return
}
}
if audioRequested == true {
switch AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeAudio) {
case AVAuthorizationStatus.NotDetermined:
NSLog("PluginGetUserMedia#call() | audio authorization: not determined")
case AVAuthorizationStatus.Authorized:
NSLog("PluginGetUserMedia#call() | audio authorization: authorized")
case AVAuthorizationStatus.Denied:
NSLog("PluginGetUserMedia#call() | audio authorization: denied")
errback(error: "audio denied")
return
case AVAuthorizationStatus.Restricted:
NSLog("PluginGetUserMedia#call() | audio authorization: restricted")
errback(error: "audio restricted")
return
}
}
rtcMediaStream = self.rtcPeerConnectionFactory.mediaStreamWithLabel(NSUUID().UUIDString)
if videoRequested == true {
// No specific video device requested.
if videoDeviceId == nil {
NSLog("PluginGetUserMedia#call() | video requested (device not specified)")
for device: AVCaptureDevice in (AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as! Array<AVCaptureDevice>) {
if device.position == AVCaptureDevicePosition.Front {
videoDevice = device
break
}
}
}
// Video device specified.
else {
NSLog("PluginGetUserMedia#call() | video requested (specified device id: \(videoDeviceId!))")
for device: AVCaptureDevice in (AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as! Array<AVCaptureDevice>) {
if device.uniqueID == videoDeviceId {
videoDevice = device
break
}
}
}
if videoDevice == nil {
NSLog("PluginGetUserMedia#call() | video requested but no suitable device found")
errback(error: "no suitable camera device found")
return
}
NSLog("PluginGetUserMedia#call() | chosen video device: \(videoDevice!)")
rtcVideoCapturer = RTCVideoCapturer(deviceName: videoDevice!.localizedName)
rtcVideoSource = self.rtcPeerConnectionFactory.videoSourceWithCapturer(rtcVideoCapturer,
constraints: RTCMediaConstraints()
)
rtcVideoTrack = self.rtcPeerConnectionFactory.videoTrackWithID(NSUUID().UUIDString,
source: rtcVideoSource
)
rtcMediaStream.addVideoTrack(rtcVideoTrack)
}
if audioRequested == true {
NSLog("PluginGetUserMedia#call() | audio requested")
rtcAudioTrack = self.rtcPeerConnectionFactory.audioTrackWithID(NSUUID().UUIDString)
rtcMediaStream.addAudioTrack(rtcAudioTrack!)
}
pluginMediaStream = PluginMediaStream(rtcMediaStream: rtcMediaStream)
pluginMediaStream!.run()
// Let the plugin store it in its dictionary.
eventListenerForNewStream(pluginMediaStream: pluginMediaStream!)
callback(data: [
"stream": pluginMediaStream!.getJSON()
])
}
}
| 6a41b77a3c95071675545738ed10032a | 31.167883 | 120 | 0.752439 | false | false | false | false |
maxadamski/swift-corelibs-foundation | refs/heads/master | TestFoundation/TestNSArray.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
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNSArray : XCTestCase {
var allTests : [(String, () -> ())] {
return [
("test_BasicConstruction", test_BasicConstruction),
("test_enumeration", test_enumeration),
("test_sequenceType", test_sequenceType),
("test_getObjects", test_getObjects),
("test_binarySearch", test_binarySearch)
]
}
func test_BasicConstruction() {
let array = NSArray()
let array2 : NSArray = ["foo", "bar"].bridge()
XCTAssertEqual(array.count, 0)
XCTAssertEqual(array2.count, 2)
}
func test_enumeration() {
let array : NSArray = ["foo", "bar", "baz"].bridge()
let e = array.objectEnumerator()
XCTAssertEqual((e.nextObject() as! NSString).bridge(), "foo")
XCTAssertEqual((e.nextObject() as! NSString).bridge(), "bar")
XCTAssertEqual((e.nextObject() as! NSString).bridge(), "baz")
XCTAssertNil(e.nextObject())
XCTAssertNil(e.nextObject())
let r = array.reverseObjectEnumerator()
XCTAssertEqual((r.nextObject() as! NSString).bridge(), "baz")
XCTAssertEqual((r.nextObject() as! NSString).bridge(), "bar")
XCTAssertEqual((r.nextObject() as! NSString).bridge(), "foo")
XCTAssertNil(r.nextObject())
XCTAssertNil(r.nextObject())
let empty = NSArray().objectEnumerator()
XCTAssertNil(empty.nextObject())
XCTAssertNil(empty.nextObject())
let reverseEmpty = NSArray().reverseObjectEnumerator()
XCTAssertNil(reverseEmpty.nextObject())
XCTAssertNil(reverseEmpty.nextObject())
}
func test_sequenceType() {
let array : NSArray = ["foo", "bar", "baz"].bridge()
var res = [String]()
for obj in array {
res.append((obj as! NSString).bridge())
}
XCTAssertEqual(res, ["foo", "bar", "baz"])
}
func test_getObjects() {
let array : NSArray = ["foo", "bar", "baz", "foo1", "bar2", "baz3",].bridge()
var objects = [AnyObject]()
array.getObjects(&objects, range: NSMakeRange(1, 3))
XCTAssertEqual(objects.count, 3)
let fetched = [
(objects[0] as! NSString).bridge(),
(objects[1] as! NSString).bridge(),
(objects[2] as! NSString).bridge(),
]
XCTAssertEqual(fetched, ["bar", "baz", "foo1"])
}
func test_binarySearch() {
let array = NSArray(array: [
NSNumber(int: 0), NSNumber(int: 1), NSNumber(int: 2), NSNumber(int: 2), NSNumber(int: 3),
NSNumber(int: 4), NSNumber(int: 4), NSNumber(int: 6), NSNumber(int: 7), NSNumber(int: 7),
NSNumber(int: 7), NSNumber(int: 8), NSNumber(int: 9), NSNumber(int: 9)])
// Not sure how to test fatal errors.
// NSArray throws NSInvalidArgument if range exceeds bounds of the array.
// let rangeOutOfArray = NSRange(location: 5, length: 15)
// let _ = array.indexOfObject(NSNumber(integer: 9), inSortedRange: rangeOutOfArray, options: [.InsertionIndex, .FirstEqual], usingComparator: compareIntNSNumber)
// NSArray throws NSInvalidArgument if both .FirstEqual and .LastEqaul are specified
// let searchForBoth: NSBinarySearchingOptions = [.FirstEqual, .LastEqual]
// let _ = objectIndexInArray(array, value: 9, startingFrom: 0, length: 13, options: searchForBoth)
let notFound = objectIndexInArray(array, value: 11, startingFrom: 0, length: 13)
XCTAssertEqual(notFound, NSNotFound, "NSArray return NSNotFound if object is not found.")
let notFoundInRange = objectIndexInArray(array, value: 7, startingFrom: 0, length: 5)
XCTAssertEqual(notFoundInRange, NSNotFound, "NSArray return NSNotFound if object is not found.")
let indexOfAnySeven = objectIndexInArray(array, value: 7, startingFrom: 0, length: 13)
XCTAssertTrue(Set([8, 9, 10]).contains(indexOfAnySeven), "If no options provided NSArray returns an arbitrary matching object's index.")
let indexOfFirstNine = objectIndexInArray(array, value: 9, startingFrom: 7, length: 6, options: [.FirstEqual])
XCTAssertTrue(indexOfFirstNine == 12, "If .FirstEqual is set NSArray returns the lowest index of equal objects.")
let indexOfLastTwo = objectIndexInArray(array, value: 2, startingFrom: 1, length: 7, options: [.LastEqual])
XCTAssertTrue(indexOfLastTwo == 3, "If .LastEqual is set NSArray returns the highest index of equal objects.")
let anyIndexToInsertNine = objectIndexInArray(array, value: 9, startingFrom: 0, length: 13, options: [.InsertionIndex])
XCTAssertTrue(Set([12, 13, 14]).contains(anyIndexToInsertNine), "If .InsertionIndex is specified and no other options provided NSArray returns any equal or one larger index than any matching object’s index.")
let lowestIndexToInsertTwo = objectIndexInArray(array, value: 2, startingFrom: 0, length: 5, options: [.InsertionIndex, .FirstEqual])
XCTAssertTrue(lowestIndexToInsertTwo == 2, "If both .InsertionIndex and .FirstEqual are specified NSArray returns the lowest index of equal objects.")
let highestIndexToInsertNine = objectIndexInArray(array, value: 9, startingFrom: 7, length: 6, options: [.InsertionIndex, .LastEqual])
XCTAssertTrue(highestIndexToInsertNine == 13, "If both .InsertionIndex and .LastEqual are specified NSArray returns the index of the least greater object...")
let indexOfLeastGreaterObjectThanFive = objectIndexInArray(array, value: 5, startingFrom: 0, length: 10, options: [.InsertionIndex, .LastEqual])
XCTAssertTrue(indexOfLeastGreaterObjectThanFive == 7, "If both .InsertionIndex and .LastEqual are specified NSArray returns the index of the least greater object...")
let endOfArray = objectIndexInArray(array, value: 10, startingFrom: 0, length: 13, options: [.InsertionIndex, .LastEqual])
XCTAssertTrue(endOfArray == array.count, "...or the index at the end of the array if the object is larger than all other elements.")
}
func objectIndexInArray(array: NSArray, value: Int, startingFrom: Int, length: Int, options: NSBinarySearchingOptions = []) -> Int {
return array.indexOfObject(NSNumber(integer: value), inSortedRange: NSRange(location: startingFrom, length: length), options: options, usingComparator: compareIntNSNumber)
}
func compareIntNSNumber(lhs: AnyObject, rhs: AnyObject) -> NSComparisonResult {
let lhsInt = (lhs as! NSNumber).integerValue
let rhsInt = (rhs as! NSNumber).integerValue
if lhsInt == rhsInt {
return .OrderedSame
}
if lhsInt < rhsInt {
return .OrderedAscending
}
return .OrderedDescending
}
}
| d46cad05f839467a7f35fd5356f7e387 | 48.145695 | 216 | 0.65382 | false | true | false | false |
NielsKoole/RealmSugar | refs/heads/master | RealmSugar/Source/RealmCollection+Notify.swift | apache-2.0 | 1 | //
// RealmCollection+Notify.swift
// RealmSugar
//
// Created by Niels Koole on 22/04/2017.
// Copyright © 2017 Niels Koole. All rights reserved.
//
import Foundation
import RealmSwift
public enum NotifyCollectionType {
case inserted
case modified
case deleted
}
// MARK: - Implement extension
extension List: NotifyRealmCollection { }
extension Results: NotifyRealmCollection { }
extension LinkingObjects: NotifyRealmCollection { }
// MARK: - Protocol definition + implementation
public protocol NotifyRealmCollection: class, RealmCollection { }
extension NotifyRealmCollection {
public func fireAndNotify(when type: NotifyCollectionType, handler: @escaping ((Self) -> Void)) -> NotificationToken {
return _notify(fire: true, types: [type], handler: handler)
}
public func fireAndNotify(when types: [NotifyCollectionType]? = nil, handler: @escaping ((Self) -> Void)) -> NotificationToken {
return _notify(fire: true, types: types, handler: handler)
}
public func notify(when type: NotifyCollectionType, handler: @escaping ((Self) -> Void)) -> NotificationToken {
return _notify(fire: false, types: [type], handler: handler)
}
public func notify(when types: [NotifyCollectionType]? = nil, handler: @escaping ((Self) -> Void)) -> NotificationToken {
return _notify(fire: false, types: types, handler: handler)
}
private func _notify(fire: Bool, types: [NotifyCollectionType]?, handler: @escaping ((Self) -> Void)) -> NotificationToken {
if fire { handler(self) }
return observe({ [weak self] (change) in
guard let s = self else { return }
switch change {
case .update(_, let deletions, let insertions, let modifications):
// If there are no types specified, we always notify :)
guard let types = types else { return handler(s) }
// Validate if the correct changes to the collection are followed
if types.filter({ $0 == .inserted }).isEmpty == false && insertions.isEmpty == false {
handler(s)
} else if types.filter({ $0 == .modified }).isEmpty == false && modifications.isEmpty == false {
handler(s)
} else if types.filter({ $0 == .deleted }).isEmpty == false && deletions.isEmpty == false {
handler(s)
}
break
default: break
}
})
}
}
| 42ae6961c21c6171845035a03f3aadd0 | 33.381579 | 132 | 0.598163 | false | false | false | false |
hollyschilling/EssentialElements | refs/heads/master | EssentialElements/EssentialElements/FormValidation/FormValidationManager.swift | mit | 1 | //
// FormValidationManager.swift
// EssentialElements
//
// Created by Holly Schilling on 2/27/17.
// Copyright © 2017 Better Practice Solutions. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
open class FormValidationManager {
public enum OverallAction {
case allValidate
case someFailures(Set<UITextField>)
case successAction
}
// BlockTimer will retain itself while active
// We keep it weak so it will automatically clear the reference
private weak var validateTimer : BlockTimer?
open var delay: TimeInterval = 1
public let overallBlock: (OverallAction) -> Void
open private(set) var registered: [(UITextField, (String) -> Bool, (Bool) -> Void)] = []
public init(overall: @escaping (OverallAction) -> Void) {
overallBlock = overall
}
open func register(field: UITextField?, validation: @escaping (String) -> Bool, action: @escaping (Bool) -> Void) {
guard let field = field else {
return
}
field.addTarget(self,
action: #selector(FormValidationManager.fieldDidLoseFocus(_:)),
for: UIControlEvents.editingDidEnd)
field.addTarget(self,
action: #selector(FormValidationManager.fieldChanged(_:)),
for: UIControlEvents.editingChanged)
field.addTarget(self,
action: #selector(FormValidationManager.pressedReturn(_:)),
for: UIControlEvents.editingDidEndOnExit)
registered.append((field, validation, action))
}
open func checkAllFields() -> Set<UITextField> {
var failed: Set<UITextField> = []
for (field, validation, _) in registered {
let text = field.text ?? ""
if !validation(text) {
failed.insert(field)
}
}
return failed
}
open func checkAllFieldsAndPerformActions() -> Set<UITextField> {
var failed: Set<UITextField> = []
for (field, validation, action) in registered {
let text = field.text ?? ""
let validates = validation(text)
action(validates)
if !validates {
failed.insert(field)
}
}
return failed
}
//MARK: - UITextField Actions
@IBAction open func fieldChanged(_ sender: UITextField) {
guard let senderIndex = registered.index(where: { $0.0==sender}) else {
return
}
if let validateTimer = validateTimer {
validateTimer.invalidate()
}
func doValidation() {
let failed = checkAllFields()
let action = registered[senderIndex].2
action(!failed.contains(sender))
if failed.count > 0 {
overallBlock(.someFailures(failed))
} else {
overallBlock(.allValidate)
}
}
if delay > 0 {
validateTimer = BlockTimer(timeInterval: delay, action: doValidation)
} else {
doValidation()
}
}
@IBAction open func pressedReturn(_ sender: UITextField) {
guard let senderIndex = registered.index(where: { $0.0==sender}) else {
return
}
let failed = checkAllFields()
let action = registered[senderIndex].2
if failed.count == 0 {
sender.resignFirstResponder()
overallBlock(.successAction)
} else {
if failed.contains(sender) {
action(false)
sender.resignFirstResponder()
overallBlock(.someFailures(failed))
} else {
action(true)
let nextIndex = (senderIndex + 1) % registered.count
let nextField = registered[nextIndex].0
nextField.becomeFirstResponder()
}
overallBlock(.someFailures(failed))
}
}
@IBAction open func fieldDidLoseFocus(_ sender: UITextField) {
guard let senderIndex = registered.index(where: { $0.0==sender}) else {
return
}
if let validateTimer = validateTimer {
validateTimer.invalidate()
}
let failed = checkAllFields()
let action = registered[senderIndex].2
action(!failed.contains(sender))
if failed.count > 0 {
overallBlock(.someFailures(failed))
} else {
overallBlock(.allValidate)
}
}
}
| 8123d22ae57d765bc48a3b5ad4b9f9e5 | 32.44 | 119 | 0.581511 | false | false | false | false |
Antidote-for-Tox/Antidote-for-Mac | refs/heads/master | Antidote/BaseConstants.swift | gpl-3.0 | 1 | //
// BaseConstants.swift
// Antidote
//
// Created by Yoba on 04/01/2017.
// Copyright © 2017 Dmytro Vorobiov. All rights reserved.
//
struct BaseConstants {
static let offset = 10
static let edgeOffset = 20
static let dividerLineHeight: CGFloat = 1.0
static let primaryFontSize: CGFloat = 14.0
static let secondaryFontSize: CGFloat = 12.0
static let iconButtonSize: CGFloat = 30.0
static let dateLabelWidth: CGFloat = 70.0
struct Colors {
static let primaryFontColor = NSColor.black
static let secondaryFontColor = NSColor(white: 0.3, alpha: 0.5)
static let contourColor = NSColor(white: 0.3, alpha: 0.5)
static let messageDeliveredBorderColor = NSColor.green
static let messageSentBorderColor = NSColor.purple
static let senderNameColor = NSColor.purple
static let altPrimaryFontColor = NSColor.white
static let altSecondaryFontColor = NSColor.white
static let barBackgroundColor = NSColor.white
}
}
| 65e9985c61eb9b200a5aa195cb3e295d | 31.5 | 71 | 0.682692 | false | false | false | false |
steveholt55/Football-College-Trivia-iOS | refs/heads/master | FootballCollegeTrivia/Title/TitlePresenter.swift | mit | 1 | //
// Copyright © 2016 Brandon Jenniges. All rights reserved.
//
import UIKit
class TitlePresenter {
unowned let view: TitleView
var difficulty: Difficulty = .Rookie
var gameType: GameType = .Practice
required init(view: TitleView) {
self.view = view
}
func gameTypeSelected(gameType: GameType, view: UIView) {
self.gameType = gameType
showDifficultyPicker(view)
}
func difficultySelected(difficulty: Difficulty) {
self.difficulty = difficulty
self.view.playGame()
}
func showDifficultyPicker(sourceView: UIView) {
let controller = UIAlertController(title: "Choose a difficulty", message: "", preferredStyle: .ActionSheet)
controller.addAction(UIAlertAction(title: "Rookie", style: .Default, handler: { (UIAlertAction) -> Void in
self.difficultySelected(.Rookie)
}))
controller.addAction(UIAlertAction(title: "Starter", style: .Default, handler: { (UIAlertAction) -> Void in
self.difficultySelected(.Starter)
}))
controller.addAction(UIAlertAction(title: "Veteran", style: .Default, handler: { (UIAlertAction) -> Void in
self.difficultySelected(.Veteran)
}))
controller.addAction(UIAlertAction(title: "All-Pro", style: .Default, handler: { (UIAlertAction) -> Void in
self.difficultySelected(.AllPro)
}))
controller.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
controller.popoverPresentationController?.sourceRect = sourceView.bounds
controller.popoverPresentationController?.sourceView = sourceView
self.view.presentDifficultyPicker(controller)
}
} | 1cc55844442dd0475aec69467e5d8f93 | 37.555556 | 115 | 0.666667 | false | false | false | false |
ronaldho/smartlittlefoodie | refs/heads/master | characterfeeder/BreakfastListViewController.swift | mit | 1 | //
// BreakfastListViewController.swift
// characterfeeder
//
// Created by Ronald Ho on 2015-09-12.
// Copyright (c) 2015 healthyyou. All rights reserved.
//
import UIKit
class BreakfastListViewController: UIViewController {
@IBOutlet weak var locationOne: UIImageView!
@IBOutlet weak var locationTwo: UIImageView!
@IBOutlet weak var locationThree: UIImageView!
@IBOutlet weak var locationFour: UIImageView!
@IBOutlet weak var locationFive: UIImageView!
@IBOutlet weak var locationSix: UIImageView!
@IBOutlet weak var locationSeven: UIImageView!
@IBOutlet weak var locationEight: UIImageView!
@IBOutlet weak var locationNine: UIImageView!
var mealChoices = [String]();
// let recognizer, recognizer2 = UITapGestureRecognizer();
func tapHelper1(sender:UITapGestureRecognizer){
println("image tapped 1")
locationOne.highlighted = true;
tapResponder(1);
}
func tapHelper2(sender:UITapGestureRecognizer){
println("image tapped 2")
locationTwo.highlighted = true;
tapResponder(2);
}
func tapHelper3(sender:UITapGestureRecognizer){
println("image tapped 3")
locationThree.highlighted = true;
tapResponder(3);
}
func tapHelper4(sender:UITapGestureRecognizer){
println("image tapped 4")
locationFour.highlighted = true;
tapResponder(4);
}
func tapHelper5(sender:UITapGestureRecognizer){
println("image tapped 5")
locationFive.highlighted = true;
tapResponder(5);
}
func tapHelper6(sender:UITapGestureRecognizer){
println("image tapped 6")
locationSix.highlighted = true;
tapResponder(6);
}
func tapHelper7(sender:UITapGestureRecognizer){
println("image tapped 7")
locationSeven.highlighted = true;
tapResponder(7);
}
func tapHelper8(sender:UITapGestureRecognizer){
println("image tapped 8")
locationEight.highlighted = true;
tapResponder(8);
}
func tapHelper9(sender:UITapGestureRecognizer){
println("image tapped 9")
locationNine.highlighted = true;
tapResponder(9);
}
func tapResponder(foodTapped:Int){
println(foodTapped);
switch foodTapped{
case 1:
mealChoices.append("Apple")
case 2:
mealChoices.append("Carrot")
case 3:
mealChoices.append("Candy")
case 4:
mealChoices.append("Tomato")
case 5:
mealChoices.append("Milk")
case 6:
mealChoices.append("Pancake")
case 7:
mealChoices.append("Egg")
case 8:
mealChoices.append("Doughnut")
case 9:
mealChoices.append("Sausage")
default:
break
}
println(mealChoices);
}
// var breakfastListArray = ["Apple", "Oats", "Carrot", "Bacon", "Milk", "Pancake", "Egg", "Doughnut", "Sausage"]
override func viewDidLoad() {
super.viewDidLoad()
//sets the user interaction to true, so we can actually track when the image has been tapped
locationOne.userInteractionEnabled = true
locationTwo.userInteractionEnabled = true
locationThree.userInteractionEnabled = true
locationFour.userInteractionEnabled = true
locationFive.userInteractionEnabled = true
locationSix.userInteractionEnabled = true
locationSeven.userInteractionEnabled = true
locationEight.userInteractionEnabled = true
locationNine.userInteractionEnabled = true
//this is where we add the target, since our method to track the taps is in this class
//we can just type "self", and then put our method name in quotes for the action parameter
// recognizer.addTarget(self, action: "imageTapped")
let recognizer1 = UITapGestureRecognizer(target: self, action: "tapHelper1:")
let recognizer2 = UITapGestureRecognizer(target: self, action: "tapHelper2:")
let recognizer3 = UITapGestureRecognizer(target: self, action: "tapHelper3:")
let recognizer4 = UITapGestureRecognizer(target: self, action: "tapHelper4:")
let recognizer5 = UITapGestureRecognizer(target: self, action: "tapHelper5:")
let recognizer6 = UITapGestureRecognizer(target: self, action: "tapHelper6:")
let recognizer7 = UITapGestureRecognizer(target: self, action: "tapHelper7:")
let recognizer8 = UITapGestureRecognizer(target: self, action: "tapHelper8:")
let recognizer9 = UITapGestureRecognizer(target: self, action: "tapHelper9:")
//finally, this is where we add the gesture recognizer, so it actually functions correctly
locationOne.addGestureRecognizer(recognizer1)
locationTwo.addGestureRecognizer(recognizer2)
locationThree.addGestureRecognizer(recognizer3)
locationFour.addGestureRecognizer(recognizer4)
locationFive.addGestureRecognizer(recognizer5)
locationSix.addGestureRecognizer(recognizer6)
locationSeven.addGestureRecognizer(recognizer7)
locationEight.addGestureRecognizer(recognizer8)
locationNine.addGestureRecognizer(recognizer9)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
var lunchScene = segue.destinationViewController as! LunchListViewController
// Pass the selected object to the new view controller.
lunchScene.mealChoices = mealChoices
}
}
| e7e3c2016270015e32c5b4d462d008e0 | 33.264045 | 116 | 0.657977 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/TypeDecoder/foreign_types.swift | apache-2.0 | 30 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -I %S/../ClangImporter/Inputs/custom-modules -I %S/../Inputs/custom-modules -emit-executable -emit-module %s -g -o %t/foreign_types
// RUN: sed -ne '/\/\/ *DEMANGLE-TYPE: /s/\/\/ *DEMANGLE-TYPE: *//p' < %s > %t/input
// RUN: %lldb-moduleimport-test-with-sdk %t/foreign_types -type-from-mangled=%t/input | %FileCheck %s --check-prefix=CHECK-TYPE
// RUN: sed -ne '/\/\/ *DEMANGLE-DECL: /s/\/\/ *DEMANGLE-DECL: *//p' < %s > %t/input
// RUN: %lldb-moduleimport-test-with-sdk %t/foreign_types -decl-from-mangled=%t/input | %FileCheck %s --check-prefix=CHECK-DECL
// REQUIRES: objc_interop
import Foundation
import CoreCooling
import ErrorEnums
extension CCRefrigerator {
struct InternalNestedType {}
fileprivate struct PrivateNestedType {}
}
/*
do {
let x1 = CCRefrigeratorCreate(kCCPowerStandard)
let x2 = MyError.good
let x3 = MyError.Code.good
let x4 = RenamedError.good
let x5 = RenamedError.Code.good
let x5b = Wrapper.MemberError.A
let x5c = Wrapper.MemberError.Code.A
let x6 = Wrapper.MemberEnum.A
let x7 = WrapperByAttribute(0)
let x8 = IceCube(width: 0, height: 0, depth: 0)
let x9 = BlockOfIce(width: 0, height: 0, depth: 0)
}
do {
let x1 = CCRefrigerator.self
let x2 = MyError.self
let x3 = MyError.Code.self
let x4 = RenamedError.self
let x5 = RenamedError.Code.self
let x5b = Wrapper.MemberError.self
let x5c = Wrapper.MemberError.Code.self
let x6 = Wrapper.MemberEnum.self
let x7 = WrapperByAttribute.self
let x8 = IceCube.self
let x9 = BlockOfIce.self
}
*/
// DEMANGLE-TYPE: $sSo17CCRefrigeratorRefaD
// DEMANGLE-TYPE: $sSo7MyErrorVD
// DEMANGLE-TYPE: $sSo7MyErrorLeVD
// DEMANGLE-TYPE: $sSo14MyRenamedErrorVD
// DEMANGLE-TYPE: $sSo14MyRenamedErrorLeVD
// DEMANGLE-TYPE: $sSo13MyMemberErrorVD
// DEMANGLE-TYPE: $sSo13MyMemberErrorLeVD
// DEMANGLE-TYPE: $sSo12MyMemberEnumVD
// DEMANGLE-TYPE: $sSo18WrapperByAttributeaD
// DEMANGLE-TYPE: $sSo7IceCubeVD
// DEMANGLE-TYPE: $sSo10BlockOfIceaD
// DEMANGLE-TYPE: $sSo17CCRefrigeratorRefa13foreign_typesE18InternalNestedTypeVD
// DEMANGLE-TYPE: $sSo17CCRefrigeratorRefa13foreign_typesE17PrivateNestedType33_5415CB6AE6FCD935BF2278A4C9A5F9C3LLVD
// CHECK-TYPE: CCRefrigerator
// CHECK-TYPE: MyError.Code
// CHECK-TYPE: MyError
// CHECK-TYPE: RenamedError.Code
// CHECK-TYPE: RenamedError
// CHECK-TYPE: Wrapper.MemberError.Code
// CHECK-TYPE: Wrapper.MemberError
// CHECK-TYPE: Wrapper.MemberEnum
// CHECK-TYPE: WrapperByAttribute
// CHECK-TYPE: IceCube
// CHECK-TYPE: BlockOfIce
// CHECK-TYPE: CCRefrigerator.InternalNestedType
// CHECK-TYPE: CCRefrigerator.PrivateNestedType
// DEMANGLE-TYPE: $sSo17CCRefrigeratorRefamD
// DEMANGLE-TYPE: $sSo7MyErrorVmD
// DEMANGLE-TYPE: $sSC7MyErrorLeVmD
// DEMANGLE-TYPE: $sSo14MyRenamedErrorVmD
// DEMANGLE-TYPE: $sSC14MyRenamedErrorLeVmD
// DEMANGLE-TYPE: $sSo13MyMemberErrorVmD
// DEMANGLE-TYPE: $sSC13MyMemberErrorLeVmD
// DEMANGLE-TYPE: $sSo12MyMemberEnumVmD
// DEMANGLE-TYPE: $sSo18WrapperByAttributeamD
// DEMANGLE-TYPE: $sSo7IceCubeVmD
// DEMANGLE-TYPE: $sSo10BlockOfIceamD
// DEMANGLE-TYPE: $sSo17CCRefrigeratorRefa13foreign_typesE18InternalNestedTypeVmD
// DEMANGLE-TYPE: $sSo17CCRefrigeratorRefa13foreign_typesE17PrivateNestedType33_5415CB6AE6FCD935BF2278A4C9A5F9C3LLVmD
// CHECK-TYPE: CCRefrigerator.Type
// CHECK-TYPE: MyError.Code.Type
// CHECK-TYPE: MyError.Type
// CHECK-TYPE: RenamedError.Code.Type
// CHECK-TYPE: RenamedError.Type
// CHECK-TYPE: Wrapper.MemberError.Code.Type
// CHECK-TYPE: Wrapper.MemberError.Type
// CHECK-TYPE: Wrapper.MemberEnum.Type
// CHECK-TYPE: WrapperByAttribute.Type
// CHECK-TYPE: IceCube.Type
// CHECK-TYPE: BlockOfIce.Type
// CHECK-TYPE: CCRefrigerator.InternalNestedType.Type
// CHECK-TYPE: CCRefrigerator.PrivateNestedType.Type
// DEMANGLE-DECL: $sSo17CCRefrigeratorRefa
// DEMANGLE-DECL: $sSo7MyErrorV
// DEMANGLE-DECL: $sSo7MyErrorLeV
// DEMANGLE-DECL: $sSo14MyRenamedErrorV
// DEMANGLE-DECL: $sSo14MyRenamedErrorLeV
// DEMANGLE-DECL: $sSo13MyMemberErrorV
// DEMANGLE-DECL: $sSo13MyMemberErrorLeV
// DEMANGLE-DECL: $sSo12MyMemberEnumV
// DEMANGLE-DECL: $sSo18WrapperByAttributea
// DEMANGLE-DECL: $sSo7IceCubeV
// DEMANGLE-DECL: $sSo10BlockOfIcea
// DEMANGLE-DECL: $sSo17CCRefrigeratorRefa13foreign_typesE18InternalNestedTypeV
// DEMANGLE-DECL: $sSo17CCRefrigeratorRefa13foreign_typesE17PrivateNestedType33_5415CB6AE6FCD935BF2278A4C9A5F9C3LLV
// CHECK-DECL: CoreCooling.(file).CCRefrigerator
// CHECK-DECL: ErrorEnums.(file).MyError.Code
// CHECK-DECL: ErrorEnums.(file).MyError.Code
// CHECK-DECL: ErrorEnums.(file).RenamedError.Code
// CHECK-DECL: ErrorEnums.(file).RenamedError.Code
// CHECK-DECL: ErrorEnums.(file).Wrapper extension.MemberError.Code
// CHECK-DECL: ErrorEnums.(file).Wrapper extension.MemberError.Code
// CHECK-DECL: ErrorEnums.(file).Wrapper extension.MemberEnum
// CHECK-DECL: ErrorEnums.(file).WrapperByAttribute
// CHECK-DECL: CoreCooling.(file).IceCube
// CHECK-DECL: CoreCooling.(file).BlockOfIce
// CHECK-DECL: foreign_types.(file).CCRefrigerator extension.InternalNestedType
// CHECK-DECL: foreign_types.(file).CCRefrigerator extension.PrivateNestedType
| a71bdabb0a21ea42175053a96bac29c4 | 37.731343 | 159 | 0.763006 | false | false | false | false |
MuYangZhe/Swift30Projects | refs/heads/master | Project 09 - PhotoScroll/PhotoScroll/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// PhotoScroll
//
// Created by 牧易 on 17/7/19.
// Copyright © 2017年 MuYi. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let pageContrl = UIPageControl.appearance()
pageContrl.pageIndicatorTintColor = UIColor.gray
pageContrl.currentPageIndicatorTintColor = UIColor.red
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "PhotoScroll")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 0fbdbd78af626f2d5883d105a8b7aeee | 48.294737 | 285 | 0.686953 | false | false | false | false |
pisarm/Gojira | refs/heads/master | Gojira WatchKit Extension/Source/Views/ComplicationController.swift | mit | 1 | //
// ComplicationController.swift
// Gojira WatchKit Extension
//
// Created by Flemming Pedersen on 21/10/15.
// Copyright © 2015 pisarm.dk. All rights reserved.
//
import ClockKit
import WatchKit
class ComplicationController: NSObject, CLKComplicationDataSource {
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) {
handler([.None])
}
func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
// guard let allTotalData = DataFacade.sharedInstance.allTotalData(), totalData = allTotalData.first else {
// handler(nil)
// return
// }
//
// handler(NSDate(timeIntervalSince1970: totalData.created))
handler(nil)
}
func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
// guard let allTotalData = DataFacade.sharedInstance.allTotalData(), totalData = allTotalData.last else {
// handler(nil)
// return
// }
//
// handler(NSDate(timeIntervalSince1970: totalData.created))
handler(nil)
}
func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) {
handler(.ShowOnLockScreen)
}
// MARK: - Timeline Population
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
guard let totalData = DataFacade.sharedInstance.fetchNewestTotalData() else {
handler(nil)
return
}
handler(timelineEntry(totalData, family: complication.family))
}
func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// if let allTotalData = DataFacade.sharedInstance.allTotalData() {
// let entries = allTotalData
// .filter { NSDate(timeIntervalSince1970: $0.created).compare(date) == .OrderedDescending }
// .map { totalData -> CLKComplicationTimelineEntry in
// return self.timelineEntry(totalData, family: complication.family)!
// }
// handler(entries)
// } else {
// handler(nil)
// }
handler(nil)
}
func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// Call the handler with the timeline entries after to the given date
handler(nil)
}
func timelineEntry(totalData: TotalData, family: CLKComplicationFamily) -> CLKComplicationTimelineEntry? {
let titleString = DataFacade.sharedInstance.title
var totalString = ""
let diff = totalData.total - totalData.oldTotal
totalString = "\(totalData.total)"
if totalData.total > totalData.oldTotal {
totalString += " (+\(diff))"
} else if totalData.total < totalData.oldTotal {
totalString += " (\(diff))"
}
switch family {
case .CircularSmall:
let textTemplate = CLKComplicationTemplateCircularSmallSimpleText()
textTemplate.textProvider = CLKSimpleTextProvider(text: totalString)
return CLKComplicationTimelineEntry(date: NSDate(timeIntervalSince1970: totalData.created), complicationTemplate: textTemplate)
case .ModularLarge:
let textTemplate = CLKComplicationTemplateModularLargeTallBody()
textTemplate.headerTextProvider = CLKSimpleTextProvider(text: titleString)
textTemplate.bodyTextProvider = CLKSimpleTextProvider(text: totalString)
return CLKComplicationTimelineEntry(date: NSDate(timeIntervalSince1970: totalData.created), complicationTemplate: textTemplate)
case .ModularSmall:
let textTemplate = CLKComplicationTemplateModularSmallSimpleText()
textTemplate.textProvider = CLKSimpleTextProvider(text: totalString, shortText: totalString)
return CLKComplicationTimelineEntry(date: NSDate(timeIntervalSince1970: totalData.created), complicationTemplate: textTemplate)
case .UtilitarianLarge:
let textTemplate = CLKComplicationTemplateUtilitarianLargeFlat()
textTemplate.textProvider = CLKSimpleTextProvider(text: "\(titleString) \(totalString)")
return CLKComplicationTimelineEntry(date: NSDate(timeIntervalSince1970: totalData.created), complicationTemplate: textTemplate)
case .UtilitarianSmall:
let textTemplate = CLKComplicationTemplateUtilitarianSmallFlat()
textTemplate.textProvider = CLKSimpleTextProvider(text: totalString)
return CLKComplicationTimelineEntry(date: NSDate(timeIntervalSince1970: totalData.created), complicationTemplate: textTemplate)
}
}
// MARK: - Update Scheduling
func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) {
if DataFacade.sharedInstance.fetchTotalDataCount() == 0 {
return handler(NSDate())
}
let refresh = DataFacade.sharedInstance.refresh.rawValue
handler(NSDate(timeIntervalSinceNow: refresh))
}
func requestedUpdateDidBegin() {
refreshTotal()
}
func requestedUpdateBudgetExhausted() {
refreshTotal()
}
func refreshTotal() {
DataFacade.sharedInstance.refreshTotalData {
guard let _ = $0 else {
return
}
let server = CLKComplicationServer.sharedInstance()
guard let complications = server.activeComplications
where complications.count > 0 else {
return
}
complications.forEach { server.reloadTimelineForComplication($0) }
}
}
// MARK: - Placeholder Templates
func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
//TODO: Return icon when applicable
handler(nil)
}
}
| 92174b56ba26cb95937cb949707b844b | 41.666667 | 178 | 0.664814 | false | false | false | false |
wikimedia/apps-ios-wikipedia | refs/heads/twn | Wikipedia/Code/TalkPageFetcher.swift | mit | 1 |
class NetworkTalkPage {
let url: URL
let topics: [NetworkTopic]
var revisionId: Int?
let displayTitle: String
init(url: URL, topics: [NetworkTopic], revisionId: Int?, displayTitle: String) {
self.url = url
self.topics = topics
self.revisionId = revisionId
self.displayTitle = displayTitle
}
}
class NetworkBase: Codable {
let topics: [NetworkTopic]
}
class NetworkTopic: NSObject, Codable {
let html: String
let replies: [NetworkReply]
let sectionID: Int
let shas: NetworkTopicShas
var sort: Int?
enum CodingKeys: String, CodingKey {
case html
case shas
case replies
case sectionID = "id"
}
}
class NetworkTopicShas: Codable {
let html: String
let indicator: String
}
class NetworkReply: NSObject, Codable {
let html: String
let depth: Int16
let sha: String
var sort: Int!
enum CodingKeys: String, CodingKey {
case html
case depth
case sha
}
}
import Foundation
import WMF
enum TalkPageType: Int {
case user
case article
func canonicalNamespacePrefix(for siteURL: URL) -> String? {
//todo: PageNamespace
var namespaceRaw: String
switch self {
case .article:
namespaceRaw = "1"
case .user:
namespaceRaw = "3"
}
guard let namespace = MWKLanguageLinkController.sharedInstance().language(forSiteURL: siteURL)?.namespaces?[namespaceRaw] else {
return nil
}
return namespace.canonicalName + ":"
}
func titleWithCanonicalNamespacePrefix(title: String, siteURL: URL) -> String {
return (canonicalNamespacePrefix(for: siteURL) ?? "") + title
}
func titleWithoutNamespacePrefix(title: String) -> String {
if let firstColon = title.range(of: ":") {
var returnTitle = title
returnTitle.removeSubrange(title.startIndex..<firstColon.upperBound)
return returnTitle
} else {
return title
}
}
func urlTitle(for title: String) -> String? {
assert(title.contains(":"), "Title must already be prefixed with namespace.")
return title.wmf_denormalizedPageTitle()
}
}
enum TalkPageFetcherError: Error {
case talkPageDoesNotExist
}
class TalkPageFetcher: Fetcher {
private let sectionUploader = WikiTextSectionUploader()
func addTopic(to title: String, siteURL: URL, subject: String, body: String, completion: @escaping (Result<[AnyHashable : Any], Error>) -> Void) {
guard let url = postURL(for: title, siteURL: siteURL) else {
completion(.failure(RequestError.invalidParameters))
return
}
sectionUploader.addSection(withSummary: subject, text: body, forArticleURL: url) { (result, error) in
if let error = error {
completion(.failure(error))
return
}
guard let result = result else {
completion(.failure(RequestError.unexpectedResponse))
return
}
completion(.success(result))
}
}
func addReply(to topic: TalkPageTopic, title: String, siteURL: URL, body: String, completion: @escaping (Result<[AnyHashable : Any], Error>) -> Void) {
guard let url = postURL(for: title, siteURL: siteURL) else {
completion(.failure(RequestError.invalidParameters))
return
}
//todo: should sectionID in CoreData be string?
sectionUploader.append(toSection: String(topic.sectionID), text: body, forArticleURL: url) { (result, error) in
if let error = error {
completion(.failure(error))
return
}
guard let result = result else {
completion(.failure(RequestError.unexpectedResponse))
return
}
completion(.success(result))
}
}
func fetchTalkPage(urlTitle: String, displayTitle: String, siteURL: URL, revisionID: Int?, completion: @escaping (Result<NetworkTalkPage, Error>) -> Void) {
guard let taskURLWithRevID = getURL(for: urlTitle, siteURL: siteURL, revisionID: revisionID),
let taskURLWithoutRevID = getURL(for: urlTitle, siteURL: siteURL, revisionID: nil) else {
completion(.failure(RequestError.invalidParameters))
return
}
//todo: track tasks/cancel
session.jsonDecodableTask(with: taskURLWithRevID) { (networkBase: NetworkBase?, response: URLResponse?, error: Error?) in
if let statusCode = (response as? HTTPURLResponse)?.statusCode,
statusCode == 404 {
completion(.failure(TalkPageFetcherError.talkPageDoesNotExist))
return
}
if let error = error {
completion(.failure(error))
return
}
guard let networkBase = networkBase else {
completion(.failure(RequestError.unexpectedResponse))
return
}
//update sort
//todo performance: should we go back to NSOrderedSets or move sort up into endpoint?
for (topicIndex, topic) in networkBase.topics.enumerated() {
topic.sort = topicIndex
for (replyIndex, reply) in topic.replies.enumerated() {
reply.sort = replyIndex
}
}
let talkPage = NetworkTalkPage(url: taskURLWithoutRevID, topics: networkBase.topics, revisionId: revisionID, displayTitle: displayTitle)
completion(.success(talkPage))
}
}
func getURL(for urlTitle: String, siteURL: URL) -> URL? {
return getURL(for: urlTitle, siteURL: siteURL, revisionID: nil)
}
}
//MARK: Private
private extension TalkPageFetcher {
func getURL(for urlTitle: String, siteURL: URL, revisionID: Int?) -> URL? {
assert(urlTitle.contains(":"), "Title must already be prefixed with namespace.")
guard let host = siteURL.host,
let percentEncodedUrlTitle = urlTitle.addingPercentEncoding(withAllowedCharacters: .wmf_articleTitlePathComponentAllowed) else {
return nil
}
var pathComponents = ["page", "talk", percentEncodedUrlTitle]
if let revisionID = revisionID {
pathComponents.append(String(revisionID))
}
guard let taskURL = configuration.wikipediaMobileAppsServicesAPIURLComponentsForHost(host, appending: pathComponents).url else {
return nil
}
return taskURL
}
func postURL(for urlTitle: String, siteURL: URL) -> URL? {
assert(urlTitle.contains(":"), "Title must already be prefixed with namespace.")
guard let host = siteURL.host else {
return nil
}
let components = configuration.articleURLForHost(host, appending: [urlTitle])
return components.url
}
}
| 60ccfba9fb183ec755c2d148eaa23410 | 30.326271 | 160 | 0.585419 | false | false | false | false |
dreamsxin/swift | refs/heads/master | test/Generics/associated_type_typo.swift | apache-2.0 | 3 | // RUN: %target-parse-verify-swift
// RUN: not %target-swift-frontend -parse -debug-generic-signatures %s > %t.dump 2>&1
// RUN: FileCheck -check-prefix CHECK-GENERIC %s < %t.dump
protocol P1 {
associatedtype Assoc
}
protocol P2 {
associatedtype AssocP2 : P1
}
protocol P3 { }
protocol P4 { }
// expected-error@+1{{'T' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{30-35=Assoc}}
func typoAssoc1<T : P1>(x: T.assoc) { }
// expected-error@+2{{'T' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{40-45=Assoc}}
// expected-error@+1{{'U' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{51-56=Assoc}}
func typoAssoc2<T : P1, U : P1 where T.assoc == U.assoc>() { }
// CHECK-GENERIC-LABEL: .typoAssoc2
// CHECK-GENERIC: Generic signature: <T, U where T : P1, U : P1, T.Assoc == U.Assoc>
// expected-error@+3{{'T.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{50-55=Assoc}}
// expected-error@+2{{'U.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{27-32=Assoc}}
func typoAssoc3<T : P2, U : P2 where
U.AssocP2.assoc : P3, T.AssocP2.assoc : P4,
T.AssocP2 == U.AssocP2>() { }
// expected-error@+2{{'T' does not have a member type named 'Assocp2'; did you mean 'AssocP2'?}}{{32-39=AssocP2}}
// expected-error@+1{{'T.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{40-45=Assoc}}
func typoAssoc4<T : P2 where T.Assocp2.assoc : P3>(_: T) { }
// CHECK-GENERIC-LABEL: .typoAssoc4@
// CHECK-GENERIC-NEXT: Requirements:
// CHECK-GENERIC-NEXT: T witness marker
// CHECK-GENERIC-NEXT: T : P2 [explicit
// CHECK-GENERIC-NEXT: T[.P2].AssocP2 witness marker
// CHECK-GENERIC-NEXT: T[.P2].AssocP2 : P1 [protocol
// CHECK-GENERIC-NEXT: T[.P2].AssocP2[.P1].Assoc witness marker
// CHECK-GENERIC-NEXT: T[.P2].AssocP2[.P1].Assoc : P3 [explicit
// CHECK-GENERIC-NEXT: Generic signature
// <rdar://problem/19620340>
func typoFunc1<T : P1>(x: TypoType) { // expected-error{{use of undeclared type 'TypoType'}}
let _: T.Assoc -> () = { let _ = $0 } // expected-error{{'Assoc' is not a member type of 'T'}}
}
func typoFunc2<T : P1>(x: TypoType, y: T) { // expected-error{{use of undeclared type 'TypoType'}}
let _: T.Assoc -> () = { let _ = $0 } // expected-error{{'Assoc' is not a member type of 'T'}}
}
func typoFunc3<T : P1>(x: TypoType, y: (T.Assoc) -> ()) { // expected-error{{use of undeclared type 'TypoType'}}
}
| 5eba9fa397bcf2af0253d4fabd56134e | 40.766667 | 115 | 0.643655 | false | false | false | false |
eocleo/AlbumCore | refs/heads/master | AlbumDemo/AlbumDemo/AlbumViews/extension/UIColor+extension.swift | mit | 1 | //
// UIColor+extension.swift
// AlbumDemo
//
// Created by leo on 2017/8/23.
// Copyright © 2017年 leo. All rights reserved.
//
import UIKit
extension UIColor {
static let cellLine = UIColor.init(hexString: "#E8E8E8")
static let mainScheme = UIColor.init(hexString: "#329BFF")
static let placeholderText = UIColor.init(hexString: "#c2c2c2")
public convenience init(hexString: String) {
let hexString = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let scanner = Scanner(string: hexString)
if hexString.hasPrefix("#") {
scanner.scanLocation = 1
}
var color: UInt32 = 0
if scanner.scanHexInt32(&color) {
self.init(hex: color, useAlpha: hexString.characters.count > 7)
}
else {
self.init(hex: 0x000000)
}
}
public convenience init(hex: UInt32, useAlpha alphaChannel: Bool = false) {
let mask = 0xFF
let r = Int(hex >> (alphaChannel ? 24 : 16)) & mask
let g = Int(hex >> (alphaChannel ? 16 : 8)) & mask
let b = Int(hex >> (alphaChannel ? 8 : 0)) & mask
let a = alphaChannel ? Int(hex) & mask : 255
let red = CGFloat(r) / 255
let green = CGFloat(g) / 255
let blue = CGFloat(b) / 255
let alpha = CGFloat(a) / 255
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
| b2d3a019ed74cc4278753166e4956032 | 28.254902 | 93 | 0.567694 | false | false | false | false |
qwang216/ChatApp | refs/heads/master | ChatApp/ChatLogController.swift | mit | 1 | //
// ChatLogController.swift
// ChatApp
//
// Created by Jason Wang on 8/26/16.
// Copyright © 2016 Jason Wang. All rights reserved.
//
import UIKit
class ChatLogController: UICollectionViewController {
override func viewDidLoad() {
navigationController?.title = "chat log controller"
collectionView?.backgroundColor = .whiteColor()
view.addSubview(inputContainerView)
setupInputContainerComponent()
}
let inputContainerView: UIView = {
let view = UIView()
view.backgroundColor = .redColor()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
func setupInputContainerComponent() {
inputContainerView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true
inputContainerView.widthAnchor.constraintEqualToAnchor(view.widthAnchor).active = true
inputContainerView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor).active = true
inputContainerView.heightAnchor.constraintEqualToConstant(50).active = true
}
}
| 7d9e2d51038008995e59895792d1d8b3 | 31.666667 | 98 | 0.722635 | false | false | false | false |
cozkurt/coframework | refs/heads/main | COFramework/Sample/Views/Console/ConsoleViewController.swift | gpl-3.0 | 1 | //
// ConsoleViewController.swift
// Plume
//
// Created by cenker on 7/20/16.
// Copyright © 2016 Plume Design, Inc. All rights reserved.
//
import UIKit
import COFramework
class ConsoleViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, LoggerDelegate {
@IBOutlet var warnButton: UIButton!
@IBOutlet var infoButton: UIButton!
@IBOutlet var debugButton: UIButton!
@IBOutlet var customButton: UIButton!
@IBOutlet var errorButton: UIButton!
@IBOutlet var autoScrollLabel: UILabel!
@IBOutlet var closeButton: UIButton!
@IBOutlet var clearLogsButton: UIButton!
@IBOutlet var tableView:UITableView!
@IBOutlet var scrollSwitch:UISwitch!
@IBOutlet var logModeLabel:UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.estimatedRowHeight = 140
self.tableView.register(UINib(nibName: "ConsoleTableViewCell", bundle: nil), forCellReuseIdentifier: "consoleCell")
Logger.sharedInstance.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.updateLogMode()
self.scrollToBottom()
// DismissButton.sharedInstance.presentButton(toView: self.view, iconName: "x.circle", delay: 0) {
// NotificationsCenterManager.sharedInstance.post("DISMISS")
// }
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func loggerUpdated() {
runOnMainQueue {
self.scrollToBottom()
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "consoleCell", for: indexPath) as? ConsoleTableViewCell
cell?.label?.text = Logger.sharedInstance.logBuffer[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Logger.sharedInstance.logBuffer.count
}
@objc func scrollToBottom() {
if self.scrollSwitch?.isOn == false {
return
}
self.tableView.reloadData()
let numberOfRows = Logger.sharedInstance.logBuffer.count
if numberOfRows > 0 {
let indexPath = IndexPath(row: numberOfRows-1, section: 0)
tableView.scrollToRow(at: indexPath, at: UITableView.ScrollPosition.bottom, animated: false)
}
}
@objc func updateLogMode() {
switch Logger.sharedInstance.logLevel {
case .debug:
self.logModeLabel?.text = "Log Mode (debug):"
break
case .info:
self.logModeLabel?.text = "Log Mode (info):"
break
case .warning:
self.logModeLabel?.text = "Log Mode (warn):"
break
case .error:
self.logModeLabel?.text = "Log Mode (error):"
break
case .custom:
self.logModeLabel?.text = "Log Mode (custom):"
break
default:
self.logModeLabel?.text = ""
}
}
@IBAction func close() {
NotificationsCenterManager.sharedInstance.post("DISMISS")
}
@IBAction func logModeDebug() {
Logger.sharedInstance.logLevel = .debug
self.updateLogMode()
}
@IBAction func logModeInfo() {
Logger.sharedInstance.logLevel = .info
self.updateLogMode()
}
@IBAction func logModeWarning() {
Logger.sharedInstance.logLevel = .warning
self.updateLogMode()
}
@IBAction func logModeError() {
Logger.sharedInstance.logLevel = .error
self.updateLogMode()
}
@IBAction func logModeCustom() {
Logger.sharedInstance.logLevel = .custom
self.updateLogMode()
}
@IBAction func clearLogs() {
Logger.sharedInstance.clearLogs()
}
}
| 5eb83133d95ce5ceac3cde4e3f75b2b0 | 29.15493 | 123 | 0.620504 | false | false | false | false |
ryuichis/swift-ast | refs/heads/master | Tests/SemaTests/LexicalParentAssignmentTests.swift | apache-2.0 | 2 | /*
Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors
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 XCTest
@testable import AST
@testable import Sema
class LexicalParentAssignmentTests: XCTestCase {
func testTopLevelDeclaration() {
semaLexicalParentAssignmentAndTest("""
let a = 1
print(a)
break
""") { topLevelDecl in
for stmt in topLevelDecl.statements {
XCTAssertTrue(stmt.lexicalParent === topLevelDecl)
}
}
}
func testClassDeclaration() {
semaLexicalParentAssignmentAndTest("""
class foo {
#if os(macOS)
let a = 1
#endif
func bar() {}
}
""") { topLevelDecl in
guard let decl = topLevelDecl.statements[0] as? ClassDeclaration else {
XCTFail("Failed in getting a ClassDeclaration.")
return
}
for member in decl.members {
switch member {
case .declaration(let d):
XCTAssertTrue(d.lexicalParent === decl)
case .compilerControl(let s):
XCTAssertTrue(s.lexicalParent === decl)
}
}
}
}
func testConstantDeclaration() {
semaLexicalParentAssignmentAndTest("""
let a = 1, b = 2
""") { topLevelDecl in
guard let decl = topLevelDecl.statements[0] as? ConstantDeclaration else {
XCTFail("Failed in getting a ConstantDeclaration.")
return
}
for pttrnInit in decl.initializerList {
XCTAssertTrue(pttrnInit.initializerExpression?.lexicalParent === decl)
}
}
}
func testDeinitializerDeclaration() {
semaLexicalParentAssignmentAndTest("""
deinit {}
""") { topLevelDecl in
guard let decl = topLevelDecl.statements[0] as? DeinitializerDeclaration else {
XCTFail("Failed in getting a DeinitializerDeclaration.")
return
}
XCTAssertTrue(decl.body.lexicalParent === decl)
}
}
func testEnumDeclaration() {
semaLexicalParentAssignmentAndTest("""
enum foo {
#if os(macOS)
let a = 1
#endif
func bar() {}
case a
}
""") { topLevelDecl in
guard let decl = topLevelDecl.statements[0] as? EnumDeclaration else {
XCTFail("Failed in getting a EnumDeclaration.")
return
}
for member in decl.members {
switch member {
case .declaration(let d):
XCTAssertTrue(d.lexicalParent === decl)
case .compilerControl(let s):
XCTAssertTrue(s.lexicalParent === decl)
default:
continue
}
}
}
}
func testExtensionDeclaration() {
semaLexicalParentAssignmentAndTest("""
extension foo {
#if os(macOS)
var a: Int { return 1 }
#endif
func bar() {}
}
""") { topLevelDecl in
guard let decl = topLevelDecl.statements[0] as? ExtensionDeclaration else {
XCTFail("Failed in getting a ExtensionDeclaration.")
return
}
for member in decl.members {
switch member {
case .declaration(let d):
XCTAssertTrue(d.lexicalParent === decl)
case .compilerControl(let s):
XCTAssertTrue(s.lexicalParent === decl)
}
}
}
}
func testFunctionDeclaration() {
semaLexicalParentAssignmentAndTest("""
func foo(i: Int = 1, j: Int = 2) {}
""") { topLevelDecl in
guard let decl = topLevelDecl.statements[0] as? FunctionDeclaration else {
XCTFail("Failed in getting a FunctionDeclaration.")
return
}
XCTAssertTrue(decl.body?.lexicalParent === decl)
for param in decl.signature.parameterList {
XCTAssertTrue(param.defaultArgumentClause?.lexicalParent === decl)
}
}
}
func testInitializerDeclaration() {
semaLexicalParentAssignmentAndTest("""
init(i: Int = 1, j: Int = 2) {}
""") { topLevelDecl in
guard let decl = topLevelDecl.statements[0] as? InitializerDeclaration else {
XCTFail("Failed in getting a InitializerDeclaration.")
return
}
XCTAssertTrue(decl.body.lexicalParent === decl)
for param in decl.parameterList {
XCTAssertTrue(param.defaultArgumentClause?.lexicalParent === decl)
}
}
}
func testStructDeclaration() {
semaLexicalParentAssignmentAndTest("""
struct foo {
#if os(macOS)
let a = 1
#endif
func bar() {}
}
""") { topLevelDecl in
guard let decl = topLevelDecl.statements[0] as? StructDeclaration else {
XCTFail("Failed in getting a StructDeclaration.")
return
}
for member in decl.members {
switch member {
case .declaration(let d):
XCTAssertTrue(d.lexicalParent === decl)
case .compilerControl(let s):
XCTAssertTrue(s.lexicalParent === decl)
}
}
}
}
func testSubscriptDeclaration() {
semaLexicalParentAssignmentAndTest("""
subscript(i: Int = 1, j: Int = 2) -> Element {}
""") { topLevelDecl in
guard let decl = topLevelDecl.statements[0] as? SubscriptDeclaration else {
XCTFail("Failed in getting a SubscriptDeclaration.")
return
}
if case .codeBlock(let codeBlock) = decl.body {
XCTAssertTrue(codeBlock.lexicalParent === decl)
}
for param in decl.parameterList {
XCTAssertTrue(param.defaultArgumentClause?.lexicalParent === decl)
}
}
}
func testVariableDeclaration() {
semaLexicalParentAssignmentAndTest("""
var a = 1, b = 2
var c: Int { return 3 }
""") { topLevelDecl in
guard let decl1 = topLevelDecl.statements[0] as? VariableDeclaration,
let decl2 = topLevelDecl.statements[1] as? VariableDeclaration,
case .initializerList(let initList) = decl1.body,
case .codeBlock(_, _, let codeBlock) = decl2.body
else {
XCTFail("Failed in getting VariableDeclarations.")
return
}
for pttrnInit in initList {
XCTAssertTrue(pttrnInit.initializerExpression?.lexicalParent === decl1)
}
XCTAssertTrue(codeBlock.lexicalParent === decl2)
}
}
func testDeferStatement() {
semaLexicalParentAssignmentAndTest("""
defer {
let a = 1
print(a)
break
}
""") { topLevelDecl in
guard let deferStmt = topLevelDecl.statements.first as? DeferStatement else {
XCTFail("Failed in getting a defer statement.")
return
}
let codeBlock = deferStmt.codeBlock
XCTAssertTrue(codeBlock.lexicalParent === deferStmt)
for stmt in codeBlock.statements {
XCTAssertTrue(stmt.lexicalParent === codeBlock)
}
}
}
func testDoStatement() {
semaLexicalParentAssignmentAndTest("""
do {
} catch err1 where exp1 {
} catch err2 {
} catch {
}
""") { topLevelDecl in
guard let doStmt = topLevelDecl.statements.first as? DoStatement else {
XCTFail("Failed in getting a do statement.")
return
}
let codeBlock = doStmt.codeBlock
XCTAssertTrue(codeBlock.lexicalParent === doStmt)
let catch1 = doStmt.catchClauses[0]
XCTAssertTrue(catch1.whereExpression?.lexicalParent === doStmt)
XCTAssertTrue(catch1.codeBlock.lexicalParent === doStmt)
let catch2 = doStmt.catchClauses[1]
XCTAssertTrue(catch2.whereExpression?.lexicalParent === nil)
XCTAssertTrue(catch2.codeBlock.lexicalParent === doStmt)
let catch3 = doStmt.catchClauses[2]
XCTAssertTrue(catch3.whereExpression?.lexicalParent === nil)
XCTAssertTrue(catch3.codeBlock.lexicalParent === doStmt)
}
}
func testForInStatement() {
semaLexicalParentAssignmentAndTest("""
for a in b {
}
for a in b where a == c {
}
""") { topLevelDecl in
guard let forStmt1 = topLevelDecl.statements[0] as? ForInStatement,
let forStmt2 = topLevelDecl.statements[1] as? ForInStatement
else {
XCTFail("Failed in getting for statements.")
return
}
XCTAssertTrue(forStmt1.collection.lexicalParent === forStmt1)
XCTAssertTrue(forStmt1.item.whereClause?.lexicalParent === nil)
XCTAssertTrue(forStmt1.codeBlock.lexicalParent === forStmt1)
XCTAssertTrue(forStmt2.collection.lexicalParent === forStmt2)
XCTAssertTrue(forStmt2.item.whereClause?.lexicalParent === forStmt2)
XCTAssertTrue(forStmt2.codeBlock.lexicalParent === forStmt2)
}
}
func testGuardStatement() {
semaLexicalParentAssignmentAndTest("""
guard true, case .a(1) = b, let a = 1, var b = false else {
}
""") { topLevelDecl in
guard let guardStmt = topLevelDecl.statements[0] as? GuardStatement else {
XCTFail("Failed in getting a guard statement.")
return
}
XCTAssertTrue(guardStmt.codeBlock.lexicalParent === guardStmt)
for condition in guardStmt.conditionList {
switch condition {
case .expression(let expr):
XCTAssertTrue(expr.lexicalParent === guardStmt)
case .case(_, let expr):
XCTAssertTrue(expr.lexicalParent === guardStmt)
case .let(_, let expr):
XCTAssertTrue(expr.lexicalParent === guardStmt)
case .var(_, let expr):
XCTAssertTrue(expr.lexicalParent === guardStmt)
default:
continue
}
}
}
}
func testIfStatement() {
semaLexicalParentAssignmentAndTest("""
if true {
} else if true {
} else {
}
""") { topLevelDecl in
guard let ifStmt = topLevelDecl.statements[0] as? IfStatement else {
XCTFail("Failed in getting an if statement.")
return
}
XCTAssertTrue(ifStmt.codeBlock.lexicalParent === ifStmt)
if case .expression(let expr) = ifStmt.conditionList[0] {
XCTAssertTrue(expr.lexicalParent === ifStmt)
}
guard case .elseif(let elseIfStmt)? = ifStmt.elseClause else {
XCTFail("Failed in getting an elseif statement.")
return
}
XCTAssertTrue(elseIfStmt.lexicalParent === ifStmt)
XCTAssertTrue(elseIfStmt.codeBlock.lexicalParent === elseIfStmt)
if case .expression(let expr) = elseIfStmt.conditionList[0] {
XCTAssertTrue(expr.lexicalParent === elseIfStmt)
}
guard case .else(let elseCodeBlock)? = elseIfStmt.elseClause else {
XCTFail("Failed in getting an else block.")
return
}
XCTAssertTrue(elseCodeBlock.lexicalParent === elseIfStmt)
}
}
func testLabeledStatement() {
semaLexicalParentAssignmentAndTest("""
a: for a in b {}
b: while a {}
c: repeat {} while a
d: if a {}
e: do {} catch {}
""") { topLevelDecl in
for stmt in topLevelDecl.statements {
guard let labeledStmt = stmt as? LabeledStatement else {
XCTFail("Failed in getting a labeled statement.")
return
}
XCTAssertTrue(labeledStmt.lexicalParent === topLevelDecl)
XCTAssertTrue(labeledStmt.statement.lexicalParent === labeledStmt)
}
}
}
func testRepeatWhileStatement() {
semaLexicalParentAssignmentAndTest("""
repeat {} while foo
""") { topLevelDecl in
guard let repeatStmt = topLevelDecl.statements[0] as? RepeatWhileStatement else {
XCTFail("Failed in getting a repeat-while statement.")
return
}
XCTAssertTrue(repeatStmt.codeBlock.lexicalParent === repeatStmt)
XCTAssertTrue(repeatStmt.conditionExpression.lexicalParent === repeatStmt)
}
}
func testReturnStatement() {
semaLexicalParentAssignmentAndTest("""
return foo
return
""") { topLevelDecl in
guard let returnStmt1 = topLevelDecl.statements[0] as? ReturnStatement,
let returnStmt2 = topLevelDecl.statements[1] as? ReturnStatement
else {
XCTFail("Failed in getting return statements.")
return
}
XCTAssertTrue(returnStmt1.expression?.lexicalParent === returnStmt1)
XCTAssertTrue(returnStmt2.expression?.lexicalParent === nil)
}
}
func testSwitchStatement() {
semaLexicalParentAssignmentAndTest("""
switch foo {
case true:
print(a)
case (a, _), (b, _) where a == b:
print(b)
default:
print(a)
print(b)
}
""") { topLevelDecl in
guard let switchStmt = topLevelDecl.statements.first as? SwitchStatement,
case let .case(items1, stmts1) = switchStmt.cases[0],
case let .case(items2, stmts2) = switchStmt.cases[1],
case let .default(stmts3) = switchStmt.cases[2]
else {
XCTFail("Failed in getting a switch statement.")
return
}
XCTAssertTrue(switchStmt.expression.lexicalParent === switchStmt)
XCTAssertTrue(items1[0].whereExpression?.lexicalParent === nil)
for stmt in stmts1 {
XCTAssertTrue(stmt.lexicalParent === switchStmt)
}
XCTAssertTrue(items2[0].whereExpression?.lexicalParent === nil)
XCTAssertTrue(items2[1].whereExpression?.lexicalParent === switchStmt)
for stmt in stmts2 {
XCTAssertTrue(stmt.lexicalParent === switchStmt)
}
for stmt in stmts3 {
XCTAssertTrue(stmt.lexicalParent === switchStmt)
}
}
}
func testThrowStatement() {
semaLexicalParentAssignmentAndTest("""
throw foo
""") { topLevelDecl in
guard let throwStmt = topLevelDecl.statements[0] as? ThrowStatement else {
XCTFail("Failed in getting a throw statement.")
return
}
XCTAssertTrue(throwStmt.expression.lexicalParent === throwStmt)
}
}
func testWhileStatement() {
semaLexicalParentAssignmentAndTest("""
while true, case .a(1) = b, let a = 1, var b = false {
}
""") { topLevelDecl in
guard let whileStmt = topLevelDecl.statements[0] as? WhileStatement else {
XCTFail("Failed in getting a while statement.")
return
}
XCTAssertTrue(whileStmt.codeBlock.lexicalParent === whileStmt)
for condition in whileStmt.conditionList {
switch condition {
case .expression(let expr):
XCTAssertTrue(expr.lexicalParent === whileStmt)
case .case(_, let expr):
XCTAssertTrue(expr.lexicalParent === whileStmt)
case .let(_, let expr):
XCTAssertTrue(expr.lexicalParent === whileStmt)
case .var(_, let expr):
XCTAssertTrue(expr.lexicalParent === whileStmt)
default:
continue
}
}
}
}
func testAssignmentOperatorExpression() {
semaLexicalParentAssignmentAndTest("""
a = 1
""") { topLevelDecl in
guard let assignOpExpr = topLevelDecl.statements[0] as? AssignmentOperatorExpression else {
XCTFail("Failed in getting an assignment operator expression.")
return
}
XCTAssertTrue(assignOpExpr.leftExpression.lexicalParent === assignOpExpr)
XCTAssertTrue(assignOpExpr.rightExpression.lexicalParent === assignOpExpr)
}
}
func testBinaryOperatorExpression() {
semaLexicalParentAssignmentAndTest("""
a + b
""") { topLevelDecl in
guard let expr = topLevelDecl.statements[0] as? BinaryOperatorExpression else {
XCTFail("Failed in getting a BinaryOperatorExpression.")
return
}
XCTAssertTrue(expr.leftExpression.lexicalParent === expr)
XCTAssertTrue(expr.rightExpression.lexicalParent === expr)
}
}
func testExplicitMemberExpression() {
semaLexicalParentAssignmentAndTest("""
foo.0
foo.bar
foo.bar<T>
foo.bar(a:b:c:)
""") { topLevelDecl in
for stmt in topLevelDecl.statements {
guard let expr = stmt as? ExplicitMemberExpression else {
XCTFail("Failed in getting a ExplicitMemberExpression.")
return
}
switch expr.kind {
case .tuple(let e, _):
XCTAssertTrue(e.lexicalParent === expr)
case .namedType(let e, _):
XCTAssertTrue(e.lexicalParent === expr)
case .generic(let e, _, _):
XCTAssertTrue(e.lexicalParent === expr)
case .argument(let e, _, _):
XCTAssertTrue(e.lexicalParent === expr)
}
}
}
}
func testForcedValueExpression() {
semaLexicalParentAssignmentAndTest("""
a!
""") { topLevelDecl in
guard let expr = topLevelDecl.statements[0] as? ForcedValueExpression else {
XCTFail("Failed in getting a ForcedValueExpression.")
return
}
XCTAssertTrue(expr.postfixExpression.lexicalParent === expr)
}
}
func testFunctionCallExpressionAndClosureExpression() {
semaLexicalParentAssignmentAndTest("""
foo(a, b: b, &c, d: &d) {
print(a)
print(b)
}
""") { topLevelDecl in
guard let funcCallExpr = topLevelDecl.statements[0] as? FunctionCallExpression,
let args = funcCallExpr.argumentClause,
let closureExpr = funcCallExpr.trailingClosure,
let closureStmts = closureExpr.statements
else {
XCTFail("Failed in getting a FunctionCallExpression.")
return
}
XCTAssertTrue(funcCallExpr.postfixExpression.lexicalParent === funcCallExpr)
for arg in args {
switch arg {
case .expression(let e):
XCTAssertTrue(e.lexicalParent === funcCallExpr)
case .namedExpression(_, let e):
XCTAssertTrue(e.lexicalParent === funcCallExpr)
case .memoryReference(let e):
XCTAssertTrue(e.lexicalParent === funcCallExpr)
case .namedMemoryReference(_, let e):
XCTAssertTrue(e.lexicalParent === funcCallExpr)
default:
continue
}
}
XCTAssertTrue(closureExpr.lexicalParent === funcCallExpr)
for cs in closureStmts {
XCTAssertTrue(cs.lexicalParent === closureExpr)
}
}
}
func testInitializerExpression() {
semaLexicalParentAssignmentAndTest("""
foo.init(a:b:c:)
""") { topLevelDecl in
guard let expr = topLevelDecl.statements[0] as? InitializerExpression else {
XCTFail("Failed in getting a InitializerExpression.")
return
}
XCTAssertTrue(expr.postfixExpression.lexicalParent === expr)
}
}
func testKeyPathStringExpression() {
semaLexicalParentAssignmentAndTest("""
_ = #keyPath(foo)
""") { topLevelDecl in
guard let assignOpExpr = topLevelDecl.statements[0] as? AssignmentOperatorExpression,
let expr = assignOpExpr.rightExpression as? KeyPathStringExpression
else {
XCTFail("Failed in getting a key-path string expression.")
return
}
XCTAssertTrue(expr.expression.lexicalParent === expr)
}
}
func testLiteralExpression() {
semaLexicalParentAssignmentAndTest("""
_ = "\(1)\(2)\(3)"
_ = [1, 2, 3]
_ = [a: 1, b: 2, c: 3]
""") { topLevelDecl in
for stmt in topLevelDecl.statements {
guard let assignOpExpr = stmt as? AssignmentOperatorExpression,
let expr = assignOpExpr.rightExpression as? LiteralExpression
else {
XCTFail("Failed in getting a LiteralExpression.")
return
}
switch expr.kind {
case .interpolatedString(let es, _):
for e in es {
XCTAssertTrue(e.lexicalParent === expr)
}
case .array(let es):
for e in es {
XCTAssertTrue(e.lexicalParent === expr)
}
case .dictionary(let d):
for entry in d {
XCTAssertTrue(entry.key.lexicalParent === expr)
XCTAssertTrue(entry.value.lexicalParent === expr)
}
default:
continue
}
}
}
}
func testOptionalChainingExpression() {
semaLexicalParentAssignmentAndTest("""
a?
""") { topLevelDecl in
guard let expr = topLevelDecl.statements[0] as? OptionalChainingExpression else {
XCTFail("Failed in getting a OptionalChainingExpression.")
return
}
XCTAssertTrue(expr.postfixExpression.lexicalParent === expr)
}
}
func testParenthesizedExpression() {
semaLexicalParentAssignmentAndTest("""
(a)
""") { topLevelDecl in
guard let expr = topLevelDecl.statements[0] as? ParenthesizedExpression else {
XCTFail("Failed in getting a ParenthesizedExpression.")
return
}
XCTAssertTrue(expr.expression.lexicalParent === expr)
}
}
func testPostfixOperatorExpression() {
semaLexicalParentAssignmentAndTest("""
a++
""") { topLevelDecl in
guard let expr = topLevelDecl.statements[0] as? PostfixOperatorExpression else {
XCTFail("Failed in getting a PostfixOperatorExpression.")
return
}
XCTAssertTrue(expr.postfixExpression.lexicalParent === expr)
}
}
func testPostfixSelfExpression() {
semaLexicalParentAssignmentAndTest("""
a.self
""") { topLevelDecl in
guard let expr = topLevelDecl.statements[0] as? PostfixSelfExpression else {
XCTFail("Failed in getting a PostfixSelfExpression.")
return
}
XCTAssertTrue(expr.postfixExpression.lexicalParent === expr)
}
}
func testPrefixOperatorExpression() {
semaLexicalParentAssignmentAndTest("""
--a
""") { topLevelDecl in
guard let expr = topLevelDecl.statements[0] as? PrefixOperatorExpression else {
XCTFail("Failed in getting a PrefixOperatorExpression.")
return
}
XCTAssertTrue(expr.postfixExpression.lexicalParent === expr)
}
}
func testSelectorExpression() {
semaLexicalParentAssignmentAndTest("""
_ = #selector(foo)
_ = #selector(getter: bar)
_ = #selector(setter: bar)
""") { topLevelDecl in
for stmt in topLevelDecl.statements {
guard let assignOpExpr = stmt as? AssignmentOperatorExpression,
let expr = assignOpExpr.rightExpression as? SelectorExpression
else {
XCTFail("Failed in getting a SelectorExpression.")
return
}
switch expr.kind {
case .selector(let e):
XCTAssertTrue(e.lexicalParent === expr)
case .getter(let e):
XCTAssertTrue(e.lexicalParent === expr)
case .setter(let e):
XCTAssertTrue(e.lexicalParent === expr)
default:
continue
}
}
}
}
func testSelfExpression() {
semaLexicalParentAssignmentAndTest("""
self[a, b]
""") { topLevelDecl in
guard let expr = topLevelDecl.statements[0] as? SelfExpression else {
XCTFail("Failed in getting a SelfExpression.")
return
}
if case .subscript(let args) = expr.kind {
for arg in args {
XCTAssertTrue(arg.expression.lexicalParent === expr)
}
}
}
}
func testSequenceExpression() {
semaLexicalParentAssignmentAndTest("""
a + b ? c : d
""") { topLevelDecl in
guard let expr = topLevelDecl.statements[0] as? SequenceExpression else {
XCTFail("Failed in getting a SequenceExpression.")
return
}
for element in expr.elements {
switch element {
case .expression(let e):
XCTAssertTrue(e.lexicalParent === expr)
case .ternaryConditionalOperator(let e):
XCTAssertTrue(e.lexicalParent === expr)
default:
continue
}
}
}
}
func testSubscriptExpression() {
semaLexicalParentAssignmentAndTest("""
foo[a, b]
""") { topLevelDecl in
guard let expr = topLevelDecl.statements[0] as? SubscriptExpression else {
XCTFail("Failed in getting a SubscriptExpression.")
return
}
XCTAssertTrue(expr.postfixExpression.lexicalParent === expr)
for arg in expr.arguments {
XCTAssertTrue(arg.expression.lexicalParent === expr)
}
}
}
func testSuperclassExpression() {
semaLexicalParentAssignmentAndTest("""
super[a, b]
""") { topLevelDecl in
guard let expr = topLevelDecl.statements[0] as? SuperclassExpression else {
XCTFail("Failed in getting a SuperclassExpression.")
return
}
if case .subscript(let args) = expr.kind {
for arg in args {
XCTAssertTrue(arg.expression.lexicalParent === expr)
}
}
}
}
func testTernaryConditionalOperatorExpression() {
semaLexicalParentAssignmentAndTest("""
a ? b : c
""") { topLevelDecl in
guard let expr = topLevelDecl.statements[0] as? TernaryConditionalOperatorExpression else {
XCTFail("Failed in getting a TernaryConditionalOperatorExpression.")
return
}
XCTAssertTrue(expr.conditionExpression.lexicalParent === expr)
XCTAssertTrue(expr.trueExpression.lexicalParent === expr)
XCTAssertTrue(expr.falseExpression.lexicalParent === expr)
}
}
func testTryOperatorExpression() {
semaLexicalParentAssignmentAndTest("""
try foo()
try! foo()
try? foo()
""") { topLevelDecl in
for stmt in topLevelDecl.statements {
guard let expr = stmt as? TryOperatorExpression else {
XCTFail("Failed in getting a TryOperatorExpression.")
return
}
switch expr.kind {
case .try(let e):
XCTAssertTrue(e.lexicalParent === expr)
case .forced(let e):
XCTAssertTrue(e.lexicalParent === expr)
case .optional(let e):
XCTAssertTrue(e.lexicalParent === expr)
}
}
}
}
func testTupleExpression() {
semaLexicalParentAssignmentAndTest("""
(1, 2, 3)
""") { topLevelDecl in
guard let expr = topLevelDecl.statements[0] as? TupleExpression else {
XCTFail("Failed in getting a TupleExpression.")
return
}
for element in expr.elementList {
XCTAssertTrue(element.expression.lexicalParent === expr)
}
}
}
func testTypeCastingOperatorExpression() {
semaLexicalParentAssignmentAndTest("""
foo is Foo
foo as Foo
foo as? Foo
foo as! Foo
""") { topLevelDecl in
for stmt in topLevelDecl.statements {
guard let expr = stmt as? TypeCastingOperatorExpression else {
XCTFail("Failed in getting a TypeCastingOperatorExpression.")
return
}
switch expr.kind {
case .check(let e, _):
XCTAssertTrue(e.lexicalParent === expr)
case .cast(let e, _):
XCTAssertTrue(e.lexicalParent === expr)
case .conditionalCast(let e, _):
XCTAssertTrue(e.lexicalParent === expr)
case .forcedCast(let e, _):
XCTAssertTrue(e.lexicalParent === expr)
}
}
}
}
private func semaLexicalParentAssignmentAndTest(
_ content: String,
testAssigned: (TopLevelDeclaration) -> Void
) {
let topLevelDecl = parse(content)
XCTAssertFalse(topLevelDecl.lexicalParentAssigned)
XCTAssertNil(topLevelDecl.lexicalParent)
let lexicalParentAssignment = LexicalParentAssignment()
lexicalParentAssignment.assign([topLevelDecl])
XCTAssertTrue(topLevelDecl.lexicalParentAssigned)
XCTAssertNil(topLevelDecl.lexicalParent)
testAssigned(topLevelDecl)
}
static var allTests = [
("testTopLevelDeclaration", testTopLevelDeclaration),
("testClassDeclaration", testClassDeclaration),
("testConstantDeclaration", testConstantDeclaration),
("testDeinitializerDeclaration", testDeinitializerDeclaration),
("testEnumDeclaration", testEnumDeclaration),
("testExtensionDeclaration", testExtensionDeclaration),
("testFunctionDeclaration", testFunctionDeclaration),
("testInitializerDeclaration", testInitializerDeclaration),
("testStructDeclaration", testStructDeclaration),
("testSubscriptDeclaration", testSubscriptDeclaration),
("testVariableDeclaration", testVariableDeclaration),
("testDeferStatement", testDeferStatement),
("testDoStatement", testDoStatement),
("testForInStatement", testForInStatement),
("testGuardStatement", testGuardStatement),
("testIfStatement", testIfStatement),
("testLabeledStatement", testLabeledStatement),
("testRepeatWhileStatement", testRepeatWhileStatement),
("testReturnStatement", testReturnStatement),
("testSwitchStatement", testSwitchStatement),
("testThrowStatement", testThrowStatement),
("testWhileStatement", testWhileStatement),
("testAssignmentOperatorExpression", testAssignmentOperatorExpression),
("testBinaryOperatorExpression", testBinaryOperatorExpression),
("testExplicitMemberExpression", testExplicitMemberExpression),
("testForcedValueExpression", testForcedValueExpression),
("testFunctionCallExpressionAndClosureExpression",
testFunctionCallExpressionAndClosureExpression),
("testInitializerExpression", testInitializerExpression),
("testKeyPathStringExpression", testKeyPathStringExpression),
("testLiteralExpression", testLiteralExpression),
("testOptionalChainingExpression", testOptionalChainingExpression),
("testParenthesizedExpression", testParenthesizedExpression),
("testPostfixOperatorExpression", testPostfixOperatorExpression),
("testPostfixSelfExpression", testPostfixSelfExpression),
("testPrefixOperatorExpression", testPrefixOperatorExpression),
("testSelectorExpression", testSelectorExpression),
("testSelfExpression", testSelfExpression),
("testSequenceExpression", testSequenceExpression),
("testSubscriptExpression", testSubscriptExpression),
("testSuperclassExpression", testSuperclassExpression),
("testTernaryConditionalOperatorExpression", testTernaryConditionalOperatorExpression),
("testTryOperatorExpression", testTryOperatorExpression),
("testTupleExpression", testTupleExpression),
("testTypeCastingOperatorExpression", testTypeCastingOperatorExpression),
]
}
| 41257e87593f0f55a23b06c867d75127 | 30.84858 | 97 | 0.648739 | false | true | false | false |
banxi1988/BXAppKit | refs/heads/master | BXForm/Controller/MultipleSelectViewController.swift | mit | 1 | //
// MultipleSelectViewController.swift
// Youjia
//
// Created by Haizhen Lee on 15/11/12.
//
import UIKit
import SwiftyJSON
import BXModel
/// 表示一个 "选项" 对象.
/// 只要求有一个可用于显示的字符串.
/// 为了多选要求其支持 Hashable
public protocol Option:Hashable{
var displayLabel:String { get }
}
/// String 天然的满足 Option 协议的要求.
extension String: Option{
public var displayLabel: String{
return self
}
}
/// 选项 Cell 支持自定义,但是需要继承自 BaseOptionCell
///
open class BaseOptionCell:UITableViewCell,BXBindable{
public func bind(_ item:String,indexPath:IndexPath){
textLabel?.text = item
}
}
let optionCellIdentifier = "optionCell"
open class MultipleSelectViewController<T:Option>: UITableViewController{
open fileprivate(set) var options:[T] = []
open let dataSource = BaseSimpleTableViewAdapter<T>()
open fileprivate(set) var selectedItems :Set<T> = []
open var completionHandler : ( (Set<T>) -> Void )?
open var onSelectOption:((T) -> Void)?
open var multiple = true
open var showSelectToolbar = true
open var isSelectAll = false
public convenience init(){
self.init(options:[],style: .grouped)
}
public init(options:[T], style:UITableViewStyle = .plain){
self.options = options
dataSource.updateItems(options)
super.init(style: style)
tableView.register(BaseOptionCell.classForCoder(), forCellReuseIdentifier: optionCellIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func register(_ cellClass:BaseOptionCell.Type){
tableView.register(cellClass.classForCoder(), forCellReuseIdentifier: optionCellIdentifier)
}
open func updateOptions(_ options:[T]){
self.options.removeAll()
self.options.append(contentsOf: options)
dataSource.updateItems(options)
}
open func setInitialSelectedItems<S:Sequence>(_ items:S) where S.Iterator.Element == T{
selectedItems.removeAll()
selectedItems.formUnion(items)
}
open var selectAllButton:UIBarButtonItem?
fileprivate var originalToolbarHidden: Bool?
open override func loadView() {
super.loadView()
originalToolbarHidden = navigationController?.isToolbarHidden
if showSelectToolbar{
navigationController?.isToolbarHidden = false
navigationController?.toolbar.tintColor = FormColors.primaryColor
let leftSpaceItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let selectAllButton = UIBarButtonItem(title:isSelectAll ? "全不选": "全选", style: .plain, target: self, action: #selector(MultipleSelectViewController.selectAllButtonPressed(_:)))
selectAllButton.tintColor = UIColor.blue
toolbarItems = [leftSpaceItem,selectAllButton]
self.selectAllButton = selectAllButton
}
}
@objc func selectAllButtonPressed(_ sender:AnyObject){
isSelectAll = !isSelectAll
selectAllButton?.title = isSelectAll ? "全不选": "全选"
if isSelectAll{
selectedItems.formUnion(options)
}else{
selectedItems.removeAll()
}
tableView.reloadData()
}
open override func viewDidLoad() {
super.viewDidLoad()
dataSource.updateItems(options)//
tableView.dataSource = dataSource
dataSource.preConfigureCellBlock = { (cell,indexPath) in
let item = self.dataSource.item(at:indexPath)
if let mcell = cell as? BaseOptionCell{
mcell.bind(item.displayLabel,indexPath: indexPath)
}
cell.accessoryType = self.selectedItems.contains(item) ? .checkmark: .none
}
tableView.tableFooterView = UIView()
if multiple{
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(MultipleSelectViewController.selectDone(_:)))
self.navigationItem.rightBarButtonItem = doneButton
}
}
@objc func selectDone(_ sender:AnyObject){
self.completionHandler?(selectedItems)
#if DEBUG
NSLog("selectDone")
#endif
let poped = navigationController?.popViewController(animated: true)
if poped == nil{
dismiss(animated: true, completion: nil)
}
}
func onSelectItem(_ item:T,atIndexPath indexPath:IndexPath){
guard let cell = tableView.cellForRow(at: indexPath) else{
return
}
if selectedItems.contains(item){
selectedItems.remove(item)
}else{
selectedItems.insert(item)
}
let isChecked = selectedItems.contains(item)
cell.accessoryType = isChecked ? .checkmark : .none
if !multiple{
self.onSelectOption?(item)
selectDone(cell)
}
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if let state = originalToolbarHidden{
navigationController?.setToolbarHidden(state, animated: true)
}
}
// MARK: UITableViewDelegate
open override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let option = dataSource.item(at: indexPath)
onSelectItem(option, atIndexPath: indexPath)
}
}
| 459dc3f3497151561a00ea4c4d62936f | 27.28022 | 181 | 0.716534 | false | false | false | false |
hollyschilling/EssentialElements | refs/heads/master | EssentialElements/EssentialElements/FormValidation/FormValidators.swift | mit | 1 | //
// FormValidators.swift
// EssentialElements
//
// Created by Holly Schilling on 3/8/17.
// Copyright © 2017 Better Practice Solutions. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct FormValidators {
private static var emailRegex = try! NSRegularExpression(pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$", options: [.caseInsensitive])
private static var urlRegex = try! NSRegularExpression(pattern: "^https?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?$", options: [.caseInsensitive])
public static func verifyEmptyOr(next: @escaping (String) -> Bool) -> (String) -> Bool {
return { (text: String) in
if text.characters.count == 0 {
return true
} else {
return next(text)
}
}
}
public static func notEmpty(_ text: String) -> Bool {
return text.characters.count > 0
}
public static func isEmail(_ text: String) -> Bool {
let count = emailRegex.numberOfMatches(in: text, options: [], range: NSMakeRange(0, text.characters.count))
return count > 0
}
public static func isUrl(_ text: String) -> Bool {
let count = urlRegex.numberOfMatches(in: text, options: [], range: NSMakeRange(0, text.characters.count))
return count > 0
}
public static func matches(_ textField: UITextField) -> (String) -> Bool {
return { [weak textField] (currentText: String) -> Bool in
let matchText = textField?.text ?? ""
return matchText==currentText
}
}
public static func minimumLength(_ minLength: Int) -> (String) -> Bool {
return { (text: String) -> Bool in
return text.characters.count >= minLength
}
}
public static func maximumLength(_ maxLength: Int) -> (String) -> Bool {
return { (text: String) -> Bool in
return text.characters.count <= maxLength
}
}
public static func multiple(_ validators: [((String) -> Bool)]) -> (String) -> Bool {
return { (text: String) -> Bool in
for aVaidator in validators {
let result = aVaidator(text)
if result==false {
return result
}
}
return true
}
}
}
| aec37ec8c05d971a36f2ca1ce6fe8555 | 38.563218 | 160 | 0.617955 | false | false | false | false |
networkextension/SSencrypt | refs/heads/master | TCP_UDP/DNSPacket.swift | bsd-3-clause | 1 | //
// DNSPacket.swift
//Copyright (c) 2016, networkextension
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions are met:
//
//* Redistributions of source code must retain the above copyright notice, this
//list of conditions and the following disclaimer.
//
//* Redistributions in binary form must reproduce the above copyright notice,
//this list of conditions and the following disclaimer in the documentation
//and/or other materials provided with the distribution.
//
//* Neither the name of SSencrypt nor the names of its
//contributors may be used to endorse or promote products derived from
//this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
//AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
//OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
//OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
import Darwin
public enum QTYPE:UInt16,CustomStringConvertible{
case A = 0x0001
case NS = 0x0002
case CNAME = 0x005
case SOA = 0x0006
case WKS = 0x000B
case PTR = 0x000C
case MX = 0x000F
case SRV = 0x0021
case A6 = 0x0026
case ANY = 0x00FF
public var description: String {
switch self {
case A: return "A"
case NS : return "NS"
case CNAME : return "CNAME"
case SOA : return "SOA"
case WKS : return "WKS"
case PTR : return "PTR"
case MX : return "MX"
case SRV : return "SRV"
case A6 : return "A6"
case ANY : return "ANY"
}
}
}
class DNSPacket: NSObject {
var identifier:UInt16 = 0
var queryDomains:[String] = []
var answerDomains:[String:String] = [:]
var rawData:NSData
var qr:CChar = 0
var count:UInt16 = 0
var qType:UInt16 = 0
var qClass:UInt16 = 0
var reqCount:UInt16 = 0
var answerCount:UInt16 = 0
var ipString:[String] = []
var finished:Bool = true
// override init() {
//
// }
init(data:NSData) {
if data.length < 12 {
AxLogger.log("DNS data error data",level: .Error)
}
rawData = data
super.init()
let bytes:UnsafePointer<UInt16> = UnsafePointer<UInt16>.init(rawData.bytes)
var p:UnsafePointer<UInt16> = bytes
identifier = bytes.memory
p = bytes + 1
let op = p.memory.bigEndian
//print("#######################")
qr = CChar(op >> 15)
if qr == 0{
//NSLog("#######################DNS req")
}else {
let c = p.memory.bigEndian & 0x000F
if c == 0 {
//NSLog("#######################DNS resp OK")
}else {
//NSLog("#######################DNS resp err:\(c)")
}
}
p = p + 1
reqCount = p.memory.bigEndian
p = p + 1
answerCount = p.memory.bigEndian
p = p + 1
p += 2
var ptr:UnsafePointer<UInt8> = UnsafePointer<UInt8>.init(p)
if qr == 0 {
count = reqCount
}else {
count = answerCount
}
let endptr:UnsafePointer<UInt8> = ptr.advancedBy(rawData.length-6*2)
for _ in 0..<reqCount {
var domainString:String = ""
var domainLength = 0
while (ptr.memory != 0x0) {
let len = Int(ptr.memory)
ptr = ptr.successor()
if ptr.distanceTo(endptr) < len {
AxLogger.log("DNS error return ",level: .Debug)
}else {
if let s = NSString.init(bytes: ptr, length: len, encoding: NSUTF8StringEncoding){
domainString = domainString + (s as String) + "."
ptr = ptr + Int(len)
domainLength += len
domainLength += 1
}
}
}
ptr += 1
memcpy(&qType, ptr, 2)
qType = qType.bigEndian
ptr += 2
memcpy(&qClass, ptr, 2)
qClass = qClass.bigEndian
ptr += 2
queryDomains.append(domainString)
if qr == 1 {
if (ptr.distanceTo(endptr) <= 0 ) { return }
}
}
//NSLog("---- %@", data)
if qr == 1{
for _ in 0..<answerCount {
if (ptr.distanceTo(endptr) <= 0 ) {
finished = false
return
}
var px:UInt16 = 0
memcpy(&px, ptr, 2)
ptr += 2
px = px.bigEndian
let pxx = px >> 14
var domain:String = ""
if pxx == 3 {
//NSLog("cc %d", pxx)
let offset:UInt16 = px & 0x3fff
var ptr0:UnsafePointer<UInt8> = UnsafePointer<UInt8>.init(bytes)
ptr0 = ptr0.advancedBy(Int(offset))
domain = DNSPacket.findLabel(ptr0)
}else {
// packet 不全,导致后面无法解析
finished = false
return
}
var t:UInt16 = 0
memcpy(&t, ptr, 2)
t = t.bigEndian
guard let type :QTYPE = QTYPE(rawValue: t) else {
return
}
ptr += 2
var qclass:UInt16 = 0
memcpy(&qclass, ptr, 2)
qclass = qclass.bigEndian
ptr += 2
var ttl:Int32 = 0
memcpy(&ttl, ptr, 4)
ttl = ttl.byteSwapped
ptr += 4
var len:UInt16 = 0
memcpy(&len, ptr, 2)
len = len.bigEndian
ptr += 2
var domainString:String = ""
var domainLength = 0
if type == .A {
var ip:Int32 = 0
memcpy(&ip, ptr, Int(len))
ip = ip.byteSwapped
domainString = "\(ip>>24 & 0xFF).\(ip>>16 & 0xFF).\(ip>>8 & 0xFF).\(ip & 0xFF)"
ptr += Int(len)
ipString.append(domainString)
}else if type == .A6 {
let buffer = NSMutableData()
memcpy(buffer.mutableBytes, ptr, Int(len))
ptr += Int(len)
AxLogger.log("IPv6 AAAA record found \(buffer)",level: .Notify)
}else {
while (ptr.memory != 0x0) {
let len = Int(ptr.memory)
ptr = ptr.successor()
if ptr.distanceTo(endptr) < len {
finished = false
return
//NSLog("error return ")
}
if let s = NSString.init(bytes: ptr, length: len, encoding: NSUTF8StringEncoding) {
domainString = domainString + (s as String) + "."
}
ptr = ptr + Int(len)
domainLength += len
domainLength += 1
}
ptr += 1
}
AxLogger.log(" \(domain) \(domainString)",level: .Debug)
}
}
if let d = queryDomains.first {
if qr == 0 {
AxLogger.log("DNS Request: \(d) ",level: .Debug)
}else {
//NSLog("DNS Response Packet %@", d)
AxLogger.log("DNS Response: \(d) :\(ipString) ",level: .Debug)
if !self.ipString.isEmpty {
let r = DNSCache.init(d: d, i: ipString)
SFSettingModule.setting.addDNSCacheRecord(r)
AxLogger.log("DNS \(d) IN A \(ipString)", level: .Trace)
}else {
AxLogger.log("DNS \(d) IN not found record", level: .Trace)
}
}
}
//super.init()
}
static func findLabel(ptr0:UnsafePointer<UInt8>) ->String {
var ptr:UnsafePointer<UInt8> = ptr0
var domainString:String = ""
var domainLength = 0
while (ptr.memory != 0x0) {
let len = Int(ptr.memory)
ptr = ptr.successor()
// if ptr.distanceTo(endptr) < len {
// NSLog("error return ")
// }
if let s = NSString.init(bytes: ptr, length: len, encoding: NSUTF8StringEncoding) {
domainString = domainString + (s as String) + "."
}
ptr = ptr + Int(len)
domainLength += len
domainLength += 1
}
return domainString
}
deinit{
AxLogger.log("DNSPacket deinit",level: .Debug)
}
static func genPacketData(ip:String,domain:String,identifier:UInt16) ->NSData {
//IPv4
let respData = NSMutableData()
respData.write(identifier)
let x:UInt16 = 0x8180
let y:UInt32 = 0x00010001
let z:UInt32 = 0x00000000
respData.write(x.bigEndian)
respData.write(y.bigEndian)
respData.write(z.bigEndian)
let xx = domain.componentsSeparatedByString(".")
for p in xx {
let len:CChar = Int8(p.characters.count)
respData.write(len)
respData.write(p)
}
respData.write(CChar(0x00)) // .在那里
respData.write(UInt16(0x0001).bigEndian)
respData.write(UInt16(0x0001).bigEndian)
respData.write(UInt16(0xC00C).bigEndian)
respData.write(UInt16(0x0001).bigEndian)
respData.write(UInt16(0x0001).bigEndian)
respData.write(UInt32(0x000d2f00).bigEndian)
respData.write(UInt16(0x0004).bigEndian)
let ipD:UInt32 = inet_addr(ip.cStringUsingEncoding(NSUTF8StringEncoding)!)
respData.write(ipD)
return respData
}
}
| ddc7ca8190371c72c18d11bd47cfa806 | 32.662722 | 107 | 0.471876 | false | false | false | false |
codepath-volunteer-app/VolunteerMe | refs/heads/master | VolunteerMe/VolunteerMe/FeedCell.swift | mit | 1 | //
// FeedCell.swift
// VolunteerMe
//
// Created by Rajat Bhargava on 10/11/17.
// Copyright © 2017 volunteer_me. All rights reserved.
//
import UIKit
import AFNetworking
class FeedCell: UITableViewCell {
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var tagsLabel: UILabel!
@IBOutlet weak var feedTitleLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var eventTimeLabel: UILabel!
@IBOutlet weak var feedDescriptionLabel: UILabel!
var event: Event! {
didSet{
feedDescriptionLabel.text = event.eventDescription
dateLabel.text = event.humanReadableDateString
feedTitleLabel.text = event.name
eventTimeLabel.text = event.humanReadableTimeRange
tagsLabel.textColor = Color.SECONDARY_COLOR
if let tags = event.tags {
if tags.count > 0 {
profileImage.image = tags[0].getImage()
} else {
profileImage.image = Tag.DEFAULT_TAG_IMAGE
}
let tagNames: [String] = tags.map({ (tag: Tag) -> String? in
return tag.name
}).filter({ (tagName: String?) -> Bool in
return tagName != nil
}).map({ (tagName: String?) -> String in
return tagName!
})
let listOfTagNames = tagNames.joined(separator: ", ")
if listOfTagNames.count > 0 {
tagsLabel.text = "Tags: \(listOfTagNames)"
} else {
tagsLabel.text = nil
}
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
profileImage.layer.cornerRadius = 5
profileImage.clipsToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 0556ed8e272479ced89a2511f0622e3a | 29.898551 | 76 | 0.544559 | false | false | false | false |
bricklife/BoostRemote | refs/heads/master | BoostRemote/Data+HexString.swift | mit | 1 | //
// Data+HexString.swift
// BoostRemote
//
// Created by ooba on 10/08/2017.
// Copyright © 2017 bricklife.com. All rights reserved.
//
import Foundation
extension Data {
public init?(hexString: String) {
let hexString = hexString
.replacingOccurrences(of: "0x", with: "")
.components(separatedBy: CharacterSet(charactersIn: "0123456789abcdefABCDEF").inverted)
.joined()
let even = hexString.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }
let odd = hexString.enumerated().filter { $0.offset % 2 == 1 }.map { $0.element }
let bytes = zip(even, odd).compactMap { UInt8(String([$0.0, $0.1]), radix: 16) }
self.init(bytes)
}
public var hexString: String {
return map { String(format: "%02x", $0) }.joined(separator: " ")
}
}
| 56556b67321ef7b2bde68f67724697b3 | 28.4 | 99 | 0.575964 | false | false | false | false |
lerocha/ios-bootcamp-TwitterRedux | refs/heads/master | TwitterRedux/MenuViewController.swift | apache-2.0 | 1 | //
// MenuViewController.swift
// TwitterRedux
//
// Created by Luis Rocha on 4/20/17.
// Copyright © 2017 Luis Rocha. All rights reserved.
//
import UIKit
class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
let menuOptions = [ "Profile", "Timeline", "Mentions", "Log Out" ]
private var profileViewController: UIViewController!
private var timelineViewController: UIViewController!
private var mentionsViewController: UIViewController!
private var loginViewController: UIViewController!
var viewControllers: [UIViewController] = []
var hamburguerViewController: HamburgerViewController!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
let storyboard = UIStoryboard(name: "Main", bundle: nil)
profileViewController = storyboard.instantiateViewController(withIdentifier: "ProfileViewController")
timelineViewController = storyboard.instantiateViewController(withIdentifier: "TimelineViewController")
mentionsViewController = storyboard.instantiateViewController(withIdentifier: "MentionsViewController")
loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController")
viewControllers.append(profileViewController)
viewControllers.append(timelineViewController)
viewControllers.append(mentionsViewController)
viewControllers.append(loginViewController)
// Handle login notification to change content view to timeline.
NotificationCenter.default.addObserver(forName: User.loginNotificationName, object: nil, queue: OperationQueue.main) { (notification) in
print("loginNotificationName")
self.hamburguerViewController.contentViewController = self.timelineViewController
}
// Handle profile view notification.
NotificationCenter.default.addObserver(forName: User.profileOpenNotificationName, object: nil, queue: OperationQueue.main) { (notification: Notification) in
if let user = notification.userInfo?["user"] as? User {
print("profileOpenNotification; user=\(user.screenname!)");
self.hamburguerViewController.contentViewController = self.profileViewController
NotificationCenter.default.post(name: User.profileRefreshNotificationName, object: nil, userInfo: notification.userInfo)
}
}
// Sets initial content view depending
if User.currentUser == nil {
hamburguerViewController.contentViewController = loginViewController
} else {
hamburguerViewController.contentViewController = timelineViewController
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menuOptions.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MenuCell", for: indexPath) as! MenuCell
cell.menuText = menuOptions[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let contentViewController = viewControllers[indexPath.row]
if contentViewController == loginViewController {
TwitterClient.sharedInstance.logout()
}
if contentViewController == profileViewController {
var userInfo: [AnyHashable : Any] = [:]
userInfo["user"] = User.currentUser
NotificationCenter.default.post(name: User.profileRefreshNotificationName, object: nil, userInfo: userInfo)
}
hamburguerViewController.contentViewController = viewControllers[indexPath.row]
}
/*
// 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.
}
*/
}
| cd540ca85dc304dae68a9ca85314b001 | 42.980583 | 164 | 0.70883 | false | false | false | false |
soxjke/Redux-ReactiveSwift | refs/heads/master | Example/NutriCalc/NutriCalc/Screens/ViewController.swift | mit | 1 | //
// ViewController.swift
// NutriCalc
//
// Created by Petro Korienev on 12/15/17.
// Copyright © 2017 Sigma Software. All rights reserved.
//
import UIKit
import ReactiveCocoa
import ReactiveSwift
import Result
import SnapKit
class ViewController: UIViewController {
@IBOutlet private var minusWeightButton: UIButton!
@IBOutlet private var plusWeightButton: UIButton!
@IBOutlet private var minusHeightButton: UIButton!
@IBOutlet private var plusHeightButton: UIButton!
@IBOutlet private var minusAgeButton: UIButton!
@IBOutlet private var plusAgeButton: UIButton!
@IBOutlet private var maleOrFemaleSwitch: UISwitch!
@IBOutlet private var activitySlider: UISlider!
@IBOutlet private var kilocaloriesLabel: UILabel!
@IBOutlet private var weightTextField: UITextField!
@IBOutlet private var heightTextField: UITextField!
@IBOutlet private var ageTextField: UITextField!
@IBOutlet private var error: UILabel!
let viewModel = ViewModel(appStore: AppStore.shared)
override func viewDidLoad() {
super.viewDidLoad()
title = "NutriCalc"
setupBindings()
}
func setupBindings() {
setupButtonBindings()
setupFieldBindings()
setupOtherActions()
}
func setupButtonBindings() {
minusWeightButton.reactive.pressed = CocoaAction(viewModel.uiAction, input: .minusWeight)
plusWeightButton.reactive.pressed = CocoaAction(viewModel.uiAction, input: .plusWeight)
minusHeightButton.reactive.pressed = CocoaAction(viewModel.uiAction, input: .minusHeight)
plusHeightButton.reactive.pressed = CocoaAction(viewModel.uiAction, input: .plusHeight)
minusAgeButton.reactive.pressed = CocoaAction(viewModel.uiAction, input: .minusAge)
plusAgeButton.reactive.pressed = CocoaAction(viewModel.uiAction, input: .plusAge)
}
func setupFieldBindings() {
weightTextField.reactive.text <~ viewModel.weightProducer
heightTextField.reactive.text <~ viewModel.heightProducer
ageTextField.reactive.text <~ viewModel.ageProducer
kilocaloriesLabel.reactive.text <~ viewModel.kcalProducer
error.reactive.text <~ viewModel.errorProducer
}
func setupOtherActions() {
let action = viewModel.uiAction
weightTextField.reactive.continuousTextValues.skipNil().map(Int.init).skipNil().observeValues { action.apply(.setWeight(weight: $0)).start() }
heightTextField.reactive.continuousTextValues.skipNil().map(Int.init).skipNil().observeValues { action.apply(.setHeight(height: $0)).start() }
ageTextField.reactive.continuousTextValues.skipNil().map(Int.init).skipNil().observeValues { action.apply(.setAge(age: $0)).start() }
maleOrFemaleSwitch.reactive.isOnValues.observeValues { action.apply(.setMaleOrFemale(maleOrFemale: $0)).start() }
activitySlider.reactive.values.observeValues { action.apply(.setActivityType(activityType: $0)).start() }
}
}
| cd5b69207f39c7a0c667a98f229806f7 | 39.986486 | 150 | 0.722717 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | refs/heads/master | 41--Grab-Bag-of-Fun/Human/Human.playground/Contents.swift | cc0-1.0 | 1 | //: # 02 -- Human -- Pedro Trujillo
//: 1. *Create a Playground named Human.*
///OK
//: 2. *Make a class named BodyPart.*
class BodyPart
{
let Name: String
let id:Int
init( Name: String, id:Int)
{
self.Name = Name
self.id = id
}
func getName()->String
{return Name}
func getId()->Int
{return id}
}
//: 3. *Create 20 classes that are subclasses of BodyPart.*
//: - **1. Class Brain**
class Brain: BodyPart
{
var isSleeping:Bool
var isThinking:Bool
var emotionsDic:Dictionary<String, Double>
init()
{
self.isSleeping = false
self.isThinking = true
self.emotionsDic = [String:Double]()
super.init( Name: "Brain", id: 1)
}
func setThinkingState()
{
self.isThinking = !isThinking
}
func setSleeping()
{
self.isSleeping = !isSleeping
}
func setEmotion(emotion:String, value:Double)
{
self.emotionsDic[emotion]=value
}
}
//: - **2. Class Heart**
class Heart: BodyPart
{
var heartbeat:Double
var ventriclesDic:Dictionary<String, Bool>
var atriumsDic:Dictionary<String, Bool>
init(heartbeat:Double)
{
self.heartbeat = heartbeat
self.ventriclesDic = [String: Bool]()
self.atriumsDic = [String: Bool]()
super.init( Name: "Heart", id: 2)
}
func setVentricles(ventricle:String, status:Bool)
{
self.atriumsDic[ventricle]=status
}
func setHeartbeat(heartbeat:Double)
{
self.heartbeat = heartbeat
}
func setAtriums(atrium:String, status:Bool)
{
self.atriumsDic[atrium]=status
}
}
//: - **3. Class Lungs**
class Lung: BodyPart
{
var inhale:Bool
var capacity:Double
var positionLeft:Bool
init(inhale:Bool, capacity:Double, positionLeft:Bool)
{
self.inhale = inhale
self.capacity = capacity
self.positionLeft = positionLeft
super.init( Name: "Lung", id: 3)
}
func getPosition()->String
{
if self.positionLeft
{return "Left"}
else
{return "right"}
}
func setInhale()
{
self.inhale = !self.inhale
}
func setCapacity(capacity:Double)
{
self.capacity = capacity
}
}
//: - **4. Class Stomach**
class Stomach: BodyPart
{
var empty:Bool
var capacity:Double
var digesting:Bool
init(empty:Bool, capacity:Double, digesting:Bool)
{
self.empty = empty
self.capacity = capacity
self.digesting = digesting
super.init( Name: "Stomach", id: 4)
}
func isEmpty()->Bool
{
return empty
}
func setDigesting()
{
self.digesting = !self.digesting
}
func setCapacity(capacity:Double)
{
self.capacity = capacity
}
}
//: - **5. Class Kidney**
class Kidney: BodyPart
{
var excretion:Double
var filtration:Double
var positionLeft:Bool
init(excretion:Double, filtration:Double, positionLeft:Bool)
{
self.excretion = excretion
self.filtration = filtration
self.positionLeft = positionLeft
super.init( Name: "Kidney", id: 5)
}
func getPosition()->String
{
if self.positionLeft
{return "Left"}
else
{return "right"}
}
func getExcretion()->Double
{
return self.excretion
}
func setFiltration(filtration:Double)
{
self.filtration = filtration
}
}
//: - **6. Class Muscle**
class Muscle: BodyPart
{
var contract:Bool
var strength:Double
var tired:Bool
init(contract:Bool, strength:Double, tired:Bool)
{
self.contract = contract
self.strength = strength
self.tired = tired
super.init( Name: "Muscle", id: 6)
}
func isContract()->Bool
{
return contract
}
func isTired()->Bool
{
return self.tired
}
func setStrength(strength:Double)
{
self.strength = strength
}
}
//: - **7. Class Bone**
class Bone: BodyPart
{
var kindOf:String
var length:Double
var articulate:Bool
init(kindOf:String, length:Double, articulate:Bool)
{
self.kindOf = kindOf
self.length = length
self.articulate = articulate
super.init( Name: "Bone", id: 7)
}
func setKindOf(kindOf:String)
{
self.kindOf = kindOf
}
func isArticulate()->Bool
{
return self.articulate
}
func setLength(length:Double)
{
self.length = length
}
}
//: - **8. Class Blood**
class Blood: BodyPart
{
var RH:String
var quantity:Double
var presure:Double
init(RH:String, quantity:Double, presure:Double)
{
self.RH = RH
self.quantity = quantity
self.presure = presure
super.init( Name: "Blood", id: 8)
}
func getRH()->String
{
return self.RH
}
func getPresure()->Double
{
return self.presure
}
func setQuantity(quantity:Double)
{
self.quantity = quantity
}
}
//: - **9. Class Skin**
class Skin: BodyPart
{
var color:String
var length:Double
var hydrated:Bool
init(color:String, length:Double, hydrated:Bool)
{
self.color = color
self.length = length
self.hydrated = hydrated
super.init( Name: "Skin", id: 9)
}
func setColor(color:String)
{
self.color = color
}
func isHydrated()->Bool
{
return self.hydrated
}
func setLength(length:Double)
{
self.length = length
}
}
//: - **10. Class ears**
class Ear: BodyPart
{
var listening:Bool
var hearingCapacity:Double
var positionLeft:Bool
init(listening:Bool, hearingCapacity:Double, positionLeft:Bool)
{
self.listening = listening
self.hearingCapacity = hearingCapacity
self.positionLeft = positionLeft
super.init( Name: "Ear", id: 10)
}
func getPosition()->String
{
if self.positionLeft
{return "Left"}
else
{return "right"}
}
func setListening()
{
self.listening = !self.listening
}
func sethearingCapacity(hearingCapacity:Double)
{
self.hearingCapacity = hearingCapacity
}
}
//: - **11. Class eye**
class Eye: BodyPart
{
var color:String
var visualCapacity:Double
var positionLeft:Bool
init(color:String, visualCapacity:Double, positionLeft:Bool)
{
self.color = color
self.visualCapacity = visualCapacity
self.positionLeft = positionLeft
super.init( Name: "Eye", id: 11)
}
func getPosition()->String
{
if self.positionLeft
{return "Left"}
else
{return "right"}
}
func setColor(color:String)
{
self.color = color
}
func setvisualCapacity(visualCapacity:Double)
{
self.visualCapacity = visualCapacity
}
}
//: - **12. Class Head**
class Head: BodyPart
{
var brain:Brain
var leftEye:Eye
var rightEye:Eye
init(eyeColor:String, visualCapacity:Double)
{
self.brain = Brain()
self.leftEye = Eye(color: eyeColor, visualCapacity: visualCapacity, positionLeft: true)
self.rightEye = Eye(color: eyeColor, visualCapacity: visualCapacity, positionLeft: false)
super.init( Name: "Head", id: 12)
}
func printEyesPosition()
{
print("Position left eye: \(self.leftEye.getPosition())")
print("Position right eye: \(self.rightEye.getPosition())")
}
func setColorEyes(col:String)
{
self.leftEye.setColor(col)
self.rightEye.setColor(col)
}
func setEyeVisualCapacity(visualCapacity:Double)
{
self.leftEye.visualCapacity = visualCapacity
self.leftEye.visualCapacity = visualCapacity
}
}
//: - **13. Class Intestine**
class Intestine: BodyPart
{
var full:Bool
var capacity:Double
var digesting:Bool
init(full:Bool, capacity:Double, digesting:Bool)
{
self.full = full
self.capacity = capacity
self.digesting = digesting
super.init( Name: "Intestine", id: 13)
}
func isFull()->Bool
{
return full
}
func setDigesting()
{
self.digesting = !self.digesting
}
func setCapacity(capacity:Double)
{
self.capacity = capacity
}
}
//: - **14. Class DegistiveSystem**
class DigestiveSystem: BodyPart
{
var stomach:Stomach
var largeIntestine:Intestine
var smallIntestine:Intestine
init(Capacity:Double, digesting: Bool)
{
self.stomach = Stomach(empty: true, capacity: Capacity, digesting: digesting)
largeIntestine = Intestine(full:true, capacity:Capacity*2, digesting:true)
smallIntestine = Intestine(full:false, capacity:3.0, digesting:true)
super.init( Name: "DegistiveSystem", id: 14)
}
}
//: - **15. Class Torso**
protocol UrinarySystem
{
func aKidney() ->Kidney
}
extension UrinarySystem
{
func aKidney() ->Kidney
{
let kidney:Kidney = Kidney(excretion: 12.0, filtration: 15.0, positionLeft: true)
return kidney
}
}
protocol urinarySystemProtocol
{
func bladder() ->BodyPart
}
class Torso: BodyPart, UrinarySystem, urinarySystemProtocol
{
var head:Head
var heart:Heart
var digestiveSystem:DigestiveSystem
init(color:String, visualCapacity:Double, positionLeft:Bool, Capacity:Double)
{
self.head = Head(eyeColor:"Blue", visualCapacity:22.0)
self.heart = Heart(heartbeat: 30)
self.digestiveSystem = DigestiveSystem(Capacity: Capacity, digesting: true)
super.init( Name: "Torso", id: 15)
}
func getBodyPartID()->(head:Int, heart:Int, stomach:Int, brain: Int)
{
return (head:self.head.getId(), heart:self.heart.getId(), stomach:self.digestiveSystem.stomach.getId(), brain: self.head.brain.getId())
}
func bladder() ->BodyPart
{
let bladderPart:BodyPart = BodyPart(Name: "Blader", id: 16)
return bladderPart
}
}
//: - **16. Declare and instance a Torso**
var newTorso:Torso = Torso(color: "white", visualCapacity: 30.0, positionLeft: false, Capacity: 45.0)
newTorso.aKidney()
newTorso.bladder()
print(newTorso.getBodyPartID())
// references https://www.dzombak.com/blog/2015/06/Multiple-Inheritance-vs--Traits-or-Protocol-Extensions.html
| 00f42ceaaa2507d09e42df4d184120a3 | 18.822785 | 143 | 0.579548 | false | false | false | false |
Subsets and Splits