repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kstaring/swift
|
validation-test/compiler_crashers_fixed/28315-swift-declcontext-iscascadingcontextforlookup.swift
|
5
|
2491
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
=b<T=class B
}{
func b{enum B:T=(a
class
class
struct B:B{
class S<b<b{
struct B{
func a=b{enum B{for c
var e
class
case c
struct c
class A{map(a<T.c
let a{typealias e{struct c<T.E
func^(f.c<f:B:O{
"
func^
let a{
{
if true{
"
func g:O{typealias f
let : Int -> ($0
if true{struct Q<b<T=Swift.E=e
case c<f:T:O{[]as a{
func a=e== {struct c<T where g:f:O{enum b
protocol B{
func g:T:O{enum B:O{
"
=e
if true{
{
var e
{func b
struct c
let:a=e{
protocol B
struct B:T=b<T where H : Boole
func^(f: Int -> ($0
protocol B:a{
class A{typealias f
func g:B
func a!
class b
}
let a
struct c<h{
let:B{
struct Q<T where T>
let a=class a {class S<h{struct Q<T>:B{enum B<h
protocol a{enum b<>
func g:T>:B:B{enum b{class c
protocol A{
let a{
struct B{
class b
protocol B
if true{protocol a{
class c
class b<T:a!
struct B{enum b<T where g:O{
"
for c:a=class b{
let:A
if true{[]as a{enum b
struct B{enum B{struct Q<T where I=(a
protocol A:a
protocol B
case c
func^(f
if true{struct Q<>:d where H : Boole
struct c
}
if true{func i(
class A
}class B
case c
struct Q<
func a
func^(a!
struct c<
struct c
struct Q{enum B<T where T.c<T where I=c
struct A{enum b{
let:T.c
if true{
protocol a=e==class b{
func g:T:T.E=c
let : Boole
if case{
{
{
struct S{map(f: C {func < {class B{struct c
func b
var b<f: C {
func < {{
class A{
struct c<h
protocol B<T.E
{
protocol B:B:B
let:T:a{
protocol B{struct c
let a!
class S<T where H : Boole
struct c:{class a {
func g:B<T where I=e
if true{extension{
{
{for c<f: Int -> (a{
struct c<T where g:B:B:A{typealias f: C {enum B:O{for c
struct Q{enum b<T where g:B:a!
struct c,case{struct Q{struct Q{}
struct Q{
{func < {
{protocol B{
}
protocol A
case c<a
if true{struct Q<T where g:B:f:a!
var b{case
}
struct c<T=c,
}
{class B:a{
var b<T:B<T where I==e{enum b{class b{struct Q<T where I=e=class A
func b
struct c<>:b<>
protocol B<T.c
import a{struct S{
let:T=b
protocol a=e=c<T where B<T.E=class B{
class b<T where I=e{enum B{
case c<T where H : Int -> (f
}
if true{
struct Q<h
let:a
protocol A{extension{
class b{enum B{typealias e
"
struct c
let:a
}
struct Q{
}
import a
class a where g:B
|
apache-2.0
|
335b1313abe410908947765d3421d955
| 14.866242 | 78 | 0.677238 | 2.321528 | false | false | false | false |
diegosanchezr/Chatto
|
Chatto/Tests/ChatController/ChatCollectionViewLayoutTests.swift
|
1
|
2817
|
/*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import XCTest
@testable import Chatto
class ChatCollectionViewLayoutModelTests: XCTestCase {
func testThat_WhenEmptyDataIsProvided_ThenLayoutIsCorrectlyCreated() {
let width: CGFloat = 320
let layoutModel = ChatCollectionViewLayoutModel.createModel(width, itemsLayoutData: [])
XCTAssertEqual(width, layoutModel.calculatedForWidth)
XCTAssertEqual(CGSize(width: 320, height: 0), layoutModel.contentSize)
XCTAssertEqual([], layoutModel.layoutAttributes)
XCTAssertEqual([[]], layoutModel.layoutAttributesBySectionAndItem)
}
func testThatLayoutIsCorrectlyCreated() {
let width: CGFloat = 320
let layoutModel = ChatCollectionViewLayoutModel.createModel(
width,
itemsLayoutData: [(height: 10, bottomMargin: 1), (height: 15, bottomMargin: 2)]
)
let expectedLayoutAttributes = [
Atttributes(item: 0, frame: CGRect(x: 0, y: 0, width: width, height: 10)),
Atttributes(item: 1, frame: CGRect(x: 0, y: 11, width: width, height: 15))
]
XCTAssertEqual(width, layoutModel.calculatedForWidth)
XCTAssertEqual(CGSize(width: 320, height: 28), layoutModel.contentSize)
XCTAssertEqual(expectedLayoutAttributes, layoutModel.layoutAttributes)
XCTAssertEqual([expectedLayoutAttributes], layoutModel.layoutAttributesBySectionAndItem)
}
}
private func Atttributes(item item: Int, frame: CGRect) -> UICollectionViewLayoutAttributes {
let indexPath = NSIndexPath(forItem: item, inSection: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
attributes.frame = frame
return attributes
}
|
mit
|
d65b0d1199511cb391149637a7d99393
| 44.435484 | 96 | 0.745119 | 4.882149 | false | true | false | false |
pascaljette/PokeBattleDemo
|
PokeBattleDemo/PokeBattleDemo/Views/ResultScreen/ResultScreenViewController.swift
|
1
|
7016
|
// The MIT License (MIT)
//
// Copyright (c) 2015 pascaljette
//
// 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
import GearKit
/// Displays the result after the battle results have been computed.
class ResultScreenViewController : GKViewControllerBase {
//
// MARK: IBOutlets
//
/// Title of the damage dealt by player 1.
@IBOutlet weak var player1ScoreTitleLabel: UILabel!
/// Value of the damage dealt by player 1.
@IBOutlet weak var player1DamageLabel: UILabel!
/// Title of the damage dealt by player 1.
@IBOutlet weak var player2ScoreTitleLabel: UILabel!
/// Value of the damage dealt by player 2.
@IBOutlet weak var player2DamageLabel: UILabel!
/// Name of the player who won.
@IBOutlet weak var winnerLabel: UILabel!
/// Label that displays the win string.
@IBOutlet weak var winsLabel: UILabel!
/// Button used for one more game.
@IBOutlet weak var revengeButton: UIButton!
/// Button used for one more game with re-shuffle.
@IBOutlet weak var reShuffleButton: UIButton!
//
// MARK: Stored properties
//
var battleResult: BattleResult
//
// MARK: Initialization
//
/// Initialise with battle result computed from the engine.
///
/// - parameter battleResult: Result containing scores from both players.
init(battleResult: BattleResult) {
self.battleResult = battleResult
super.init(nibName: "ResultScreenViewController", bundle: nil)
}
/// Required initialiser. Unsupported so make it crash as soon as possible.
///
/// - parameter coder: Coder used to initialize the view controller (when instantiated from a storyboard).
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented (storyboard not supported)")
}
}
extension ResultScreenViewController {
//
// MARK: UIViewController overrides
//
/// View did load.
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.hidesBackButton = true
player1ScoreTitleLabel.text = NSLocalizedString("PLAYER_1_SCORE", comment: "Player 1 score")
player2ScoreTitleLabel.text = NSLocalizedString("PLAYER_2_SCORE", comment: "Player 2 score")
player1DamageLabel.text = String(battleResult.player1Result.score)
player2DamageLabel.text = String(battleResult.player2Result.score)
revengeButton.setTitle(NSLocalizedString("REVENGE_BUTTON", comment: "Revenge Button")
, forState: .Normal)
reShuffleButton.setTitle(NSLocalizedString("RESHUFFLE_BUTTON", comment: "Reshuffle Button")
, forState: .Normal)
winsLabel.text = NSLocalizedString("WINNER", comment: "Winner label")
winnerLabel.hidden = true
winsLabel.hidden = true
revengeButton.hidden = true
reShuffleButton.hidden = true
}
/// View did appear.
///
/// - parameter animated: Whether the view is being animated when it appears.
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// Retrieve the playing winner. Abort if it is a draw and displays the draw label.
guard let winner = battleResult.winner else{
winnerLabel.hidden = false
winnerLabel.text = NSLocalizedString("DRAW", comment: "Draw")
winsLabel.hidden = true
revengeButton.hidden = false
reShuffleButton.hidden = false
return
}
// Set winner text to the corresponding player name.
let winnerText: String
switch winner.id {
case .PLAYER_1:
winnerText = NSLocalizedString("PLAYER_1", comment: "Player 1")
case .PLAYER_2:
winnerText = NSLocalizedString("PLAYER_2", comment: "Player 2")
}
// Initially hide the winner text since we will be animating it.
winnerLabel.text = winnerText
winnerLabel.hidden = false
let initialScaleFactor: CGFloat = 10.0
// Animate the winning player label by making it grow (scale).
winnerLabel.transform = CGAffineTransformScale(winnerLabel.transform, 1.0 / initialScaleFactor, 1.0 / initialScaleFactor);
UIView.animateWithDuration(1.0, animations:{
self.winnerLabel.transform = CGAffineTransformScale(self.winnerLabel.transform, initialScaleFactor, initialScaleFactor);
}, completion: { _ in
// Display the additional UI elements after the animation completes.
self.winsLabel.hidden = false
self.revengeButton.hidden = false
self.reShuffleButton.hidden = false
})
}
}
extension ResultScreenViewController {
//
// MARK: IBAction
//
/// One more button has been pressed. Simply return to the root view controller. We will be using
/// the same pokemon draw for the new game.
///
/// - parameter sender: Object sending the event.
@IBAction func revengeButtonPressed(sender: AnyObject) {
self.navigationController?.popToRootViewControllerAnimated(true)
}
/// Re-shuffle button has been pressed. Trigger a reshuffle and return to the intro view controller.
///
/// - parameter sender: Object sending the event.
@IBAction func reShuffleButtonPressed(sender: AnyObject) {
guard let introViewController = self.navigationController?.viewControllers[0] as? IntroScreenViewController else {
return
}
introViewController.reshuffleDraw()
self.navigationController?.popToViewController(introViewController, animated: true)
}
}
|
mit
|
0c3f554bb32d5b8156995612441ba162
| 34.434343 | 132 | 0.657497 | 5.011429 | false | false | false | false |
delbert06/DYZB
|
DYZB/DYZB/NetworkTools.swift
|
1
|
941
|
//
// NetworkTools.swift
// DYZB
//
// Created by 胡迪 on 2016/12/8.
// Copyright © 2016年 D.Huhu. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType{
case get
case post
}
class NetworkTools {
class func requestData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping (_ result : Any) -> ()) {
// 1.获取类型
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
// 2.发送网络请求
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
// 3.获取结果
guard let result = response.result.value else {
print(response.result.error as Any)
return
}
// 4.将结果回调出去
finishedCallback(result)
}
}
}
|
mit
|
91c944a6c63b95713e34c2c987c57eb1
| 23.777778 | 159 | 0.553812 | 4.309179 | false | false | false | false |
jreese/euler
|
swift/problem2.swift
|
1
|
274
|
func fib(limit: Int) -> Int
{
var sum = 0
var last = 0
var current = 1
while last < limit {
(last, current) = (current, last + current)
if current % 2 == 0 {
sum += current
}
}
return sum
}
print(fib(4000000))
|
mit
|
83b737f76c2cf2b4244904c5e45bdb99
| 14.222222 | 51 | 0.481752 | 3.558442 | false | false | false | false |
strawberry224/Calculator
|
Calculator/Calculator/CalculatorBrain.swift
|
1
|
3533
|
//
// CalculatorBrain.swift
// Calculator
//
// Created by Shen Lijia on 16/1/6.
// Copyright © 2016年 Shen Lijia. All rights reserved.
//
import Foundation
class CalculatorBrain {
private enum Op: CustomStringConvertible {
case Operand(Double)
case UnaryOperation(String, Double -> Double)
case BinaryOperation(String, (Double, Double) -> Double)
var description: String {
get {
switch self {
case .Operand(let operand):
return "\(operand)"
case .UnaryOperation(let symbol, _):
return symbol
case .BinaryOperation(let symbol, _):
return symbol
}
}
}
}
private var opStack = [Op]()
private var knownOps = [String:Op]()
init() {
func learnOp(op: Op) {
knownOps[op.description] = op
}
knownOps["×"] = Op.BinaryOperation("×", *)
knownOps["÷"] = Op.BinaryOperation("÷") { $1 / $0 }
knownOps["+"] = Op.BinaryOperation("+", +)
knownOps["−"] = Op.BinaryOperation("−") { $1 - $0 }
knownOps["√"] = Op.UnaryOperation("√", sqrt)
}
typealias PropertyList = AnyObject
var program: PropertyList { // guaranteed to be a PropertyList
get {
return opStack.map { $0.description }
}
set {
if let opSymbols = newValue as? Array<String> {
var newOpStack = [Op]()
for opSymbol in opSymbols {
if let op = knownOps[opSymbol] {
newOpStack.append(op)
} else if let oprand = NSNumberFormatter().numberFromString(opSymbol)?.doubleValue {
newOpStack.append(.Operand(oprand))
}
}
}
}
}
private func evaluate(ops: [Op]) -> (result: Double?, remainingOps: [Op]) {
if !ops.isEmpty {
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case .Operand(let operand):
return (operand, remainingOps)
case .UnaryOperation(_, let operation):
let operandEvaluation = evaluate(remainingOps)
if let operand = operandEvaluation.result {
return (operation(operand), operandEvaluation.remainingOps)
}
case .BinaryOperation(_, let operation):
let op1Evaluation = evaluate(remainingOps)
if let operand1 = op1Evaluation.result {
let op2Evaluation = evaluate(op1Evaluation.remainingOps)
if let operand2 = op2Evaluation.result {
return (operation(operand1, operand2), op2Evaluation.remainingOps)
}
}
}
}
return (nil, ops)
}
func evaluate() -> Double? {
let (result, remainder) = evaluate(opStack)
print("\(opStack) = \(result) with \(remainder) left over")
return result
}
func pushOperand(operand: Double) -> Double? {
opStack.append(Op.Operand(operand))
return evaluate()
}
func performOperation(symbol: String) -> Double? {
if let operation = knownOps[symbol] {
opStack.append(operation)
}
return evaluate()
}
}
|
gpl-2.0
|
a669f259c2548053e68c689190a9d200
| 30.981818 | 104 | 0.510233 | 4.913408 | false | false | false | false |
casd82/powerup-iOS
|
Powerup/Avatar.swift
|
2
|
2716
|
/** This struct is a data model for avatar features (customizables). */
struct Avatar {
var id: Int
// Required accessories.
var face: Accessory
var eyes: Accessory
var hair: Accessory
var clothes: Accessory
// Optional accessories (Should be bought at the store).
var necklace: Accessory?
var glasses: Accessory?
var handbag: Accessory?
var hat: Accessory?
init(avatarID: Int, face: Accessory, eyes: Accessory, hair: Accessory, clothes: Accessory, necklace: Accessory?, glasses: Accessory?, handbag: Accessory?, hat: Accessory?) {
self.id = avatarID
self.face = face
self.eyes = eyes
self.hair = hair
self.clothes = clothes
self.necklace = necklace
self.glasses = glasses
self.handbag = handbag
self.hat = hat
}
init() {
self.id = DatabaseAccessor.sharedInstance.avatarID
self.face = Accessory(type: .face)
self.eyes = Accessory(type: .eyes)
self.hair = Accessory(type: .hair)
self.clothes = Accessory(type: .clothes)
self.necklace = nil
self.glasses = nil
self.handbag = nil
self.hat = nil
}
// A convenient way to get the avatar's accessory by its type.
func getAccessoryByType(_ type: AccessoryType) -> Accessory? {
switch type {
case .face:
return face
case .eyes:
return eyes
case .hair:
return hair
case .clothes:
return clothes
case .necklace:
return necklace
case .glasses:
return glasses
case .handbag:
return handbag
case .hat:
return hat
default:
return nil
}
}
// A convenient way to set the avatar's accessory by its type.
mutating func setAccessoryByType(_ type: AccessoryType, accessory: Accessory?) {
switch type {
// These accessories can't be set the nil.
case .face:
if accessory == nil { return }
face = accessory!
case .eyes:
if accessory == nil { return }
eyes = accessory!
case .hair:
if accessory == nil { return }
hair = accessory!
case .clothes:
if accessory == nil { return }
clothes = accessory!
case .necklace:
necklace = accessory
case .glasses:
glasses = accessory
case .handbag:
handbag = accessory
case .hat:
hat = accessory
default: break
}
}
}
|
gpl-2.0
|
edd33de34b6c62ef7658dec3e95e6b5a
| 26.714286 | 177 | 0.541973 | 4.587838 | false | false | false | false |
jholsapple/TheIronYard-Assignments
|
31 -- TheHitList -- John Holsapple/31 -- TheHitList -- John Holsapple/AppDelegate.swift
|
2
|
6492
|
//
// AppDelegate.swift
// 31 -- TheHitList -- John Holsapple
//
// Created by John Holsapple on 7/27/15.
// Copyright (c) 2015 John Holsapple -- The Iron Yard. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.tiy._1____TheHitList____John_Holsapple" 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("_1____TheHitList____John_Holsapple", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. 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
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("_1____TheHitList____John_Holsapple.sqlite")
var error: NSError? = nil
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 var error1 as NSError {
error = error1
coordinator = nil
// 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
error = 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 \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// 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.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
}
|
cc0-1.0
|
44c7f5f22e8244052a0a50539e2562b7
| 52.652893 | 290 | 0.696704 | 5.704745 | false | false | false | false |
cafielo/iOS_BigNerdRanch_5th
|
Chap4_WorldTrotter_bronze/ConversionViewController.swift
|
1
|
1707
|
//
// ConversionViewController.swift
// WorldTrotter
//
// Created by Joonwon Lee on 7/17/16.
// Copyright © 2016 Joonwon Lee. All rights reserved.
//
import UIKit
class ConversionViewController: UIViewController {
@IBOutlet weak var celsiusLabel: UILabel!
@IBOutlet weak var textField: UITextField!
var fahrenheitValue: Double?
var celsiusValue: Double? {
didSet {
updateCelsiusLabel()
}
}
let numberFormatter: NSNumberFormatter = {
let nf = NSNumberFormatter()
nf.numberStyle = .DecimalStyle
nf.minimumFractionDigits = 0
nf.maximumFractionDigits = 1
return nf
}()
override func viewDidLoad() {
super.viewDidLoad()
}
func updateCelsiusLabel() {
if let value = celsiusValue {
celsiusLabel.text = numberFormatter.stringFromNumber(value)
} else {
celsiusLabel.text = "???"
}
}
@IBAction func fahrenheitFieldEditingChanged(textField: UITextField) {
if let text = textField.text, value = Double(text) {
fahrenheitValue = value
} else {
fahrenheitValue = nil
}
}
@IBAction func disissKeyboard(sender: AnyObject) {
textField.resignFirstResponder()
}
}
extension ConversionViewController: UITextFieldDelegate {
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let hasCharacter = string.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet())
if hasCharacter != nil {
return false
}
return true
}
}
|
mit
|
e69f2a9c80f1c7914271dae3ac98134f
| 25.65625 | 132 | 0.631301 | 5.20122 | false | false | false | false |
gregomni/swift
|
test/Generics/sr15009.swift
|
3
|
507
|
// RUN: %target-typecheck-verify-swift -debug-generic-signatures -requirement-machine-protocol-signatures=on 2>&1 | %FileCheck %s
// CHECK: sr15009.(file).P@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.[P]A.[Q]B, Self.[P]A : Q>
protocol P { associatedtype A: Q where A.B == Self }
// CHECK: sr15009.(file).Q@
// CHECK-NEXT: Requirement signature: <Self where Self : CaseIterable, Self == Self.[Q]B.[P]A, Self.[Q]B : P>
protocol Q: CaseIterable { associatedtype B: P where B.A == Self }
|
apache-2.0
|
f5a24ae4c8591f6e05667a602110ef99
| 55.333333 | 129 | 0.688363 | 3.12963 | false | false | false | false |
joseph-zhong/CommuterBuddy-iOS
|
SwiftSideMenu/Utility/UIViewControllerExtensions.swift
|
4
|
8411
|
//
// UIViewControllerExtensions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 15/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
extension UIViewController {
// MARK: - Notifications
//TODO: Document this part
public func addNotificationObserver(_ name: String, selector: Selector) {
NotificationCenter.default.addObserver(self, selector: selector, name: NSNotification.Name(rawValue: name), object: nil)
}
public func removeNotificationObserver(_ name: String) {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: name), object: nil)
}
public func removeNotificationObserver() {
NotificationCenter.default.removeObserver(self)
}
#if os(iOS)
public func addKeyboardWillShowNotification() {
self.addNotificationObserver(NSNotification.Name.UIKeyboardWillShow.rawValue, selector: #selector(UIViewController.keyboardWillShowNotification(_:)))
}
public func addKeyboardDidShowNotification() {
self.addNotificationObserver(NSNotification.Name.UIKeyboardDidShow.rawValue, selector: #selector(UIViewController.keyboardDidShowNotification(_:)))
}
public func addKeyboardWillHideNotification() {
self.addNotificationObserver(NSNotification.Name.UIKeyboardWillHide.rawValue, selector: #selector(UIViewController.keyboardWillHideNotification(_:)))
}
public func addKeyboardDidHideNotification() {
self.addNotificationObserver(NSNotification.Name.UIKeyboardDidHide.rawValue, selector: #selector(UIViewController.keyboardDidHideNotification(_:)))
}
public func removeKeyboardWillShowNotification() {
self.removeNotificationObserver(NSNotification.Name.UIKeyboardWillShow.rawValue)
}
public func removeKeyboardDidShowNotification() {
self.removeNotificationObserver(NSNotification.Name.UIKeyboardDidShow.rawValue)
}
public func removeKeyboardWillHideNotification() {
self.removeNotificationObserver(NSNotification.Name.UIKeyboardWillHide.rawValue)
}
public func removeKeyboardDidHideNotification() {
self.removeNotificationObserver(NSNotification.Name.UIKeyboardDidHide.rawValue)
}
public func keyboardDidShowNotification(_ notification: Notification) {
if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.cgRectValue
keyboardDidShowWithFrame(frame)
}
}
public func keyboardWillShowNotification(_ notification: Notification) {
if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.cgRectValue
keyboardWillShowWithFrame(frame)
}
}
public func keyboardWillHideNotification(_ notification: Notification) {
if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.cgRectValue
keyboardWillHideWithFrame(frame)
}
}
public func keyboardDidHideNotification(_ notification: Notification) {
if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.cgRectValue
keyboardDidHideWithFrame(frame)
}
}
public func keyboardWillShowWithFrame(_ frame: CGRect) {
}
public func keyboardDidShowWithFrame(_ frame: CGRect) {
}
public func keyboardWillHideWithFrame(_ frame: CGRect) {
}
public func keyboardDidHideWithFrame(_ frame: CGRect) {
}
//EZSE: Makes the UIViewController register tap events and hides keyboard when clicked somewhere in the ViewController.
public func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
#endif
public func dismissKeyboard() {
view.endEditing(true)
}
// MARK: - VC Container
/// EZSwiftExtensions
public var top: CGFloat {
get {
if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController {
return visibleViewController.top
}
if let nav = self.navigationController {
if nav.isNavigationBarHidden {
return view.top
} else {
return nav.navigationBar.bottom
}
} else {
return view.top
}
}
}
/// EZSwiftExtensions
public var bottom: CGFloat {
get {
if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController {
return visibleViewController.bottom
}
if let tab = tabBarController {
if tab.tabBar.isHidden {
return view.bottom
} else {
return tab.tabBar.top
}
} else {
return view.bottom
}
}
}
/// EZSwiftExtensions
public var tabBarHeight: CGFloat {
get {
if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController {
return visibleViewController.tabBarHeight
}
if let tab = self.tabBarController {
return tab.tabBar.frame.size.height
}
return 0
}
}
/// EZSwiftExtensions
public var navigationBarHeight: CGFloat {
get {
if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController {
return visibleViewController.navigationBarHeight
}
if let nav = self.navigationController {
return nav.navigationBar.h
}
return 0
}
}
/// EZSwiftExtensions
public var navigationBarColor: UIColor? {
get {
if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController {
return visibleViewController.navigationBarColor
}
return navigationController?.navigationBar.tintColor
} set(value) {
navigationController?.navigationBar.barTintColor = value
}
}
/// EZSwiftExtensions
public var navBar: UINavigationBar? {
get {
return navigationController?.navigationBar
}
}
/// EZSwiftExtensions
public var applicationFrame: CGRect {
get {
return CGRect(x: view.x, y: top, width: view.w, height: bottom - top)
}
}
// MARK: - VC Flow
/// EZSwiftExtensions
public func pushVC(_ vc: UIViewController) {
navigationController?.pushViewController(vc, animated: true)
}
/// EZSwiftExtensions
public func popVC() {
_ = navigationController?.popViewController(animated: true)
}
/// EZSwiftExtensions
public func presentVC(_ vc: UIViewController) {
present(vc, animated: true, completion: nil)
}
/// EZSwiftExtensions
public func dismissVC(completion: (() -> Void)? ) {
dismiss(animated: true, completion: completion)
}
/// EZSwiftExtensions
public func addAsChildViewController(_ vc: UIViewController, toView: UIView) {
self.addChildViewController(vc)
toView.addSubview(vc.view)
vc.didMove(toParentViewController: self)
}
///EZSE: Adds image named: as a UIImageView in the Background
func setBackgroundImage(_ named: String) {
let image = UIImage(named: named)
let imageView = UIImageView(frame: view.frame)
imageView.image = image
view.addSubview(imageView)
view.sendSubview(toBack: imageView)
}
///EZSE: Adds UIImage as a UIImageView in the Background
@nonobjc func setBackgroundImage(_ image: UIImage) {
let imageView = UIImageView(frame: view.frame)
imageView.image = image
view.addSubview(imageView)
view.sendSubview(toBack: imageView)
}
}
|
mit
|
81e33c240486674b3fb735ad0eb12276
| 32.245059 | 157 | 0.654976 | 5.861324 | false | false | false | false |
toggl/superday
|
teferi/UI/Modules/Goals/NewGoal/NewGoalViewController.swift
|
1
|
3742
|
import UIKit
import RxSwift
import RxCocoa
class NewGoalViewController: UIViewController
{
@IBOutlet private weak var closeButton: UIButton!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var topDescriptionLabel: UILabel!
@IBOutlet fileprivate weak var timeDescriptionLabel: UILabel!
@IBOutlet private weak var middleDescriptionLabel: UILabel!
@IBOutlet private weak var newGoalButton: UIButton!
@IBOutlet weak var timesCollectionView: CustomCollectionView!
@IBOutlet weak var categoriesCollectionView: CustomCollectionView!
fileprivate var viewModel: NewGoalViewModel!
private var presenter: NewGoalPresenter!
private let disposeBag = DisposeBag()
func inject(presenter: NewGoalPresenter, viewModel: NewGoalViewModel)
{
self.presenter = presenter
self.viewModel = viewModel
}
override func viewDidLoad()
{
super.viewDidLoad()
titleLabel.text = L10n.newGoalTitle
topDescriptionLabel.text = L10n.newGoalTopDescription
middleDescriptionLabel.text = L10n.newGoalMiddleDescription
newGoalButton.setTitle(viewModel.buttonTitle, for: .normal)
let timeGradientOverlay = PickerGradientOverlay()
view.addSubview(timeGradientOverlay)
timeGradientOverlay.snp.makeConstraints { (make) in
make.edges.equalTo(timesCollectionView.snp.edges)
}
let categoryGradientOverlay = PickerGradientOverlay(middleGap: 10)
view.addSubview(categoryGradientOverlay)
categoryGradientOverlay.snp.makeConstraints { (make) in
make.edges.equalTo(categoriesCollectionView.snp.edges)
}
categoriesCollectionView.loops = true
timesCollectionView.customDelegate = self
categoriesCollectionView.customDelegate = self
timesCollectionView.customDatasource = CustomCollectionViewArrayDatasource<GoalTimeCell, GoalTime>(
items: viewModel.goalTimes,
cellIdentifier: "goalTimeCell",
initialValue: viewModel.initialTime,
configureCell: { _, goalTime, cell in
cell.goalTime = goalTime
return cell
})
categoriesCollectionView.customDatasource = CustomCollectionViewArrayDatasource<GoalCategoryCell, Category>(
items: viewModel.categories,
cellIdentifier: "goalCategoryCell",
initialValue: viewModel.initialCategory,
configureCell: { _, category, cell in
cell.category = category
return cell
})
createBindings()
}
private func createBindings()
{
closeButton.rx.tap
.subscribe(onNext: { [unowned self] in
self.presenter.dismiss()
})
.disposed(by: disposeBag)
newGoalButton.rx.tap
.subscribe(onNext: saveGoal)
.disposed(by: disposeBag)
}
private func saveGoal()
{
self.viewModel.saveGoal(completion: {
self.presenter.dismiss(showEnableNotifications: $0)
})
}
}
extension NewGoalViewController: CustomCollectionViewDelegate
{
func itemSelected(for collectionView: UICollectionView, at row: Int)
{
if collectionView == timesCollectionView {
let goalTime = viewModel.goalTimes[row]
timeDescriptionLabel.text = goalTime.unitString
viewModel.durationSelectedVariable.value = goalTime.goalTime
return
}
let category = viewModel.categories[row]
viewModel.categorySelectedVariable.value = category
}
}
|
bsd-3-clause
|
262ea5ef22dcc6891c85efb887dc4664
| 33.648148 | 116 | 0.661411 | 5.44687 | false | false | false | false |
sayheyrickjames/codepath-week3-mailbox
|
week3-homework-mailbox/MailboxViewController.swift
|
1
|
19097
|
//
// MailboxViewController.swift
// week3-homework-mailbox
//
// Created by Rick James! Chatas on 5/20/15.
// Copyright (c) 2015 SayHey. All rights reserved.
//
import UIKit
import MessageUI
class MailboxViewController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate, UIAlertViewDelegate, MFMailComposeViewControllerDelegate {
// all outlets
@IBOutlet weak var feedImageView: UIImageView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var laterIcon: UIImageView!
@IBOutlet weak var listIcon: UIImageView!
@IBOutlet weak var deleteIcon: UIImageView!
@IBOutlet weak var archiveIcon: UIImageView!
@IBOutlet weak var messageImageView: UIImageView!
@IBOutlet weak var messageContainerView: UIView!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var rescheduleImageView: UIImageView!
@IBOutlet weak var listImageView: UIImageView!
@IBOutlet weak var navSegmentedControl: UISegmentedControl!
@IBOutlet weak var laterScrollView: UIScrollView!
@IBOutlet weak var archiveScrollView: UIScrollView!
// starting center points
var originalMessageCenter: CGPoint!
var originalLaterIconCenter: CGPoint!
var originalArchiveIconCenter:CGPoint!
var originalDeleteIconCenter: CGPoint!
var originalFeedCenter: CGPoint!
var gutter: CGFloat!
var originalContainerViewCenterX: CGFloat!
// colors
let blueColor = UIColor(red: 107/255, green: 190/255, blue: 219/255, alpha: 1)
let yellowColor = UIColor(red: 254/255, green: 202/255, blue: 22/255, alpha: 1)
let brownColor = UIColor(red: 206/255, green: 150/255, blue: 98/255, alpha: 1)
let greenColor = UIColor(red: 85/255, green: 213/255, blue: 80/255, alpha: 1)
let redColor = UIColor(red: 231/255, green: 61/255, blue: 14/255, alpha: 1)
let grayColor = UIColor(red: 178/255, green: 178/255, blue: 178/255, alpha: 1)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// scroll settings
scrollView.frame.size = view.bounds.size
scrollView.contentSize = CGSize(width: 320, height: 1432)
originalMessageCenter = messageImageView.center
// starting values
listIcon.alpha = 0
deleteIcon.alpha = 0
originalLaterIconCenter = CGPoint(x: messageImageView.frame.width - 30, y: messageImageView.frame.height/2)
originalArchiveIconCenter = CGPoint(x: 30, y: messageImageView.frame.height/2)
originalFeedCenter = feedImageView.center
gutter = 30
rescheduleImageView.alpha = 0
rescheduleImageView.center = view.center
listImageView.alpha = 0
listImageView.center = view.center
originalContainerViewCenterX = 160
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// pan gesture recognizer
@IBAction func didPanMessage(sender: UIPanGestureRecognizer) {
var location = sender.locationInView(view)
var translation = sender.translationInView(view)
var velocity = sender.velocityInView(view)
var edgeGesture = UIScreenEdgePanGestureRecognizer(target: self, action: "onEdgePan:")
edgeGesture.edges = UIRectEdge.Left
containerView.addGestureRecognizer(edgeGesture)
// pan began
if (sender.state == UIGestureRecognizerState.Began){
//set the starting point of the message to its current position
originalMessageCenter = messageImageView.center
archiveIcon.alpha = 0
deleteIcon.alpha = 0
listIcon.alpha = 0
laterIcon.alpha = 0
}
// pan changed
else if (sender.state == UIGestureRecognizerState.Changed) {
messageImageView.center = CGPointMake(originalMessageCenter.x + translation.x, originalMessageCenter.y)
// short swipe left for later
if (messageImageView.center.x < 100 && messageImageView.center.x > -40) {
messageContainerView.backgroundColor = UIColor(red: 255/255, green: 211/255, blue: 32/255, alpha: 1)
deleteIcon.alpha = 0
listIcon.alpha = 0
laterIcon.alpha = 1
laterIcon.center = CGPointMake(messageImageView.frame.width + gutter + translation.x, messageImageView.center.y)
}
// long swipe left for list
else if (messageImageView.center.x <= -40) {
messageContainerView.backgroundColor = UIColor(red: 216/255, green: 166/255, blue: 117/255, alpha: 1)
deleteIcon.alpha = 0
laterIcon.alpha = 0
listIcon.alpha = 1
listIcon.center = CGPointMake(messageImageView.frame.width + gutter + translation.x, messageImageView.center.y)
}
// short swipe right to archive
else if (messageImageView.center.x > 220 && messageImageView.center.x < 360) {
messageContainerView.backgroundColor = UIColor(red: 98/255, green: 216/255, blue: 98/255, alpha: 1)
laterIcon.alpha = 0
deleteIcon.alpha = 0
archiveIcon.alpha = 1
archiveIcon.center = CGPointMake(translation.x - gutter, messageImageView.center.y)
}
// long swipe right to delete
else if (messageImageView.center.x >= 360) {
messageContainerView.backgroundColor = UIColor(red: 239/255, green: 84/255, blue: 12/255, alpha: 1)
archiveIcon.alpha = 0
deleteIcon.alpha = 1
deleteIcon.center = CGPointMake(translation.x - gutter, messageImageView.center.y)
}
// otherwise keep the background gray
else {
laterIcon.alpha = -translation.x / 60
archiveIcon.alpha = translation.x / 60
messageContainerView.backgroundColor = UIColor(red: 191/255, green: 191/255, blue: 191/255, alpha: 1)
laterIcon.center = CGPointMake(originalLaterIconCenter.x, originalLaterIconCenter.y)
archiveIcon.center = originalArchiveIconCenter
}
}
// pan ended
else if (sender.state == UIGestureRecognizerState.Ended) {
if (messageImageView.center.x < 100 && messageImageView.center.x > -40){
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.messageImageView.center.x = -self.view.frame.width
self.laterIcon.center.x = self.messageImageView.center.x + self.messageImageView.frame.width/2 + self.gutter
self.rescheduleImageView.alpha = 1
})
}
// list
else if (messageImageView.center.x <= -40) {
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.messageImageView.center.x = -self.view.frame.width
self.listIcon.center.x = self.messageImageView.center.x + self.messageImageView.frame.width/2 + self.gutter
self.listImageView.alpha = 1
})
}
// archive
else if (messageImageView.center.x > 220 && messageImageView.center.x < 360) {
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.messageImageView.center.x = self.view.frame.width * 2
self.archiveIcon.center.x = self.messageImageView.center.x - self.gutter
}, completion: { (Bool) -> Void in
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.feedImageView.center.y = self.feedImageView.center.y - self.messageImageView.frame.height
})
})
}
// delete
else if (messageImageView.center.x >= 360) {
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.messageImageView.center.x = self.view.frame.width * 2
self.deleteIcon.center.x = self.messageImageView.center.x - self.gutter
}, completion: { (Bool) -> Void in
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.feedImageView.center.y = self.feedImageView.center.y - self.messageImageView.frame.height
})
})
}
// didn't swipe far enough, return to original position
else {
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.messageImageView.center.x = self.view.frame.width/2
})
}
}
}
@IBAction func didTapReschedulePane(sender: UITapGestureRecognizer) {
self.archiveIcon.alpha = 0
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.rescheduleImageView.alpha = 0
self.messageImageView.center.x = self.view.frame.width/2
self.laterIcon.center.x = self.messageImageView.center.x + self.messageImageView.frame.width/2 + self.gutter
})
}
@IBAction func didTapListPane(sender: UITapGestureRecognizer) {
self.archiveIcon.alpha = 0
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.listImageView.alpha = 0
self.messageImageView.center.x = self.view.frame.width/2
self.listIcon.center.x = self.messageImageView.center.x + self.messageImageView.frame.width/2 + self.gutter
})
}
@IBAction func didPressResetButton(sender: AnyObject) {
messageImageView.center.x = view.frame.width/2
feedImageView.center = originalFeedCenter
}
@IBAction func didPressMenuButton(sender: AnyObject) {
if (containerView.center.x == view.frame.width/2) {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.containerView.center.x += 280
})
}
else {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.containerView.center.x = self.view.frame.width/2
})
}
}
@IBAction func didPressComposeButton(sender: AnyObject) {
if MFMailComposeViewController.canSendMail(){
var composer = MFMailComposeViewController()
composer.mailComposeDelegate = self
composer.setToRecipients(["[email protected]"])
composer.navigationBar.tintColor = blueColor
presentViewController(composer, animated: true, completion: {
UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: false)
})
}
}
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
switch result.value{
case MFMailComposeResultCancelled.value: println("Mail cancelled")
case MFMailComposeResultSaved.value: println("Mail saved")
case MFMailComposeResultSent.value: println("Mail sent")
case MFMailComposeResultFailed.value: println("Failed to send mail: \(error.localizedDescription)")
default:
break
}
dismissViewControllerAnimated(true, completion: nil)
}
// override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent)
// {
// if(event.subtype == UIEventSubtype.MotionShake)
// {
// //If the user has archived or deleted a message, bring up this alert
// if (self.feedImageView.frame == CGRect(x: 320, y: 0, width: 320, height: 1202))
// {
// //Alert declaration
// var alert = UIAlertController(title: "Undo last action?", message: "Are you sure you want to undo and move 1 item from Archive back into inbox?", preferredStyle: UIAlertControllerStyle.Alert)
// alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
// alert.addAction(UIAlertAction(title: "Undo", style: UIAlertActionStyle.Default, handler: {(alertAction) -> Void in
// self.undismissMessage()
// }))
// //Show alert
// self.presentViewController(alert, animated: true, completion: nil)
// }
// }
// }
//
// edge pan gesture recognizer
func onEdgePan(sender:UIScreenEdgePanGestureRecognizer) {
var translation = sender.translationInView(view)
if (sender.state == UIGestureRecognizerState.Began){
originalContainerViewCenterX = containerView.center.x
}
else if (sender.state == UIGestureRecognizerState.Changed) {
containerView.center.x = originalContainerViewCenterX + translation.x
}
else if (sender.state == UIGestureRecognizerState.Ended) {
if (translation.x < 100) {
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: nil, animations: { () -> Void in
self.containerView.center.x = 160
}, completion: { (Bool) -> Void in
})
} else if (translation.x >= 100) {
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: nil, animations: { () -> Void in
self.containerView.center.x = 440
}, completion: { (Bool) -> Void in
})
}
}
}
@IBAction func tapNavSegmentedControl(sender: AnyObject) {
if navSegmentedControl.selectedSegmentIndex == 0 {
// later icon selected
navSegmentedControl.tintColor = yellowColor
self.laterScrollView.alpha = 1
UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0, options: nil, animations: { () -> Void in
self.scrollView.frame.origin.x = 320
}, completion: { (Bool) -> Void in
self.scrollView.alpha = 0
})
UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0, options: nil, animations: { () -> Void in
self.archiveScrollView.frame.origin.x = 640
}, completion: { (Bool) -> Void in
self.archiveScrollView.alpha = 0
})
UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0, options: nil, animations: { () -> Void in
self.laterScrollView.frame.origin.x = 0
}, completion: { (Bool) -> Void in
self.laterScrollView.alpha = 1
})
} else if navSegmentedControl.selectedSegmentIndex == 1 {
// mailbox icon selected
navSegmentedControl.tintColor = blueColor
self.scrollView.alpha = 1
UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0, options: nil, animations: { () -> Void in
self.scrollView.frame.origin.x = 0
}, completion: { (Bool) -> Void in
self.scrollView.alpha = 1
})
UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0, options: nil, animations: { () -> Void in
self.archiveScrollView.frame.origin.x = 320
}, completion: { (Bool) -> Void in
self.archiveScrollView.alpha = 0
})
UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0, options: nil, animations: { () -> Void in
self.laterScrollView.frame.origin.x = -320
}, completion: { (Bool) -> Void in
self.laterScrollView.alpha = 0
})
} else {
// archive icon selected
navSegmentedControl.tintColor = greenColor
archiveScrollView.alpha = 1
UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0, options: nil, animations: { () -> Void in
self.scrollView.frame.origin.x = -320
}, completion: { (Bool) -> Void in
self.scrollView.alpha = 0
})
UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0, options: nil, animations: { () -> Void in
self.archiveScrollView.frame.origin.x = 0
}, completion: { (Bool) -> Void in
self.archiveScrollView.alpha = 1
})
UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0, options: nil, animations: { () -> Void in
self.laterScrollView.frame.origin.x = -640
}, completion: { (Bool) -> Void in
self.laterScrollView.alpha = 0
})
}
}
}
/*
// 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.
}
*/
|
gpl-2.0
|
a6a2e2d8de9fe35f4f8f833cf663c8e6
| 40.605664 | 209 | 0.566948 | 5.154386 | false | false | false | false |
eweill/Forge
|
Forge/Forge/SimpleKernel.swift
|
2
|
2251
|
/*
Copyright (c) 2016-2017 M.I. Hollemans
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 Metal
import MetalPerformanceShaders
/**
Simple wrapper around a compute shader.
*/
open class SimpleKernel {
let device: MTLDevice
let pipeline: MTLComputePipelineState
let name: String
public init(device: MTLDevice, functionName: String, useForgeLibrary: Bool = false) {
self.device = device
self.name = functionName
pipeline = makeFunction(device: device, name: functionName, useForgeLibrary: useForgeLibrary)
}
public func encode(commandBuffer: MTLCommandBuffer, sourceImage: MPSImage, destinationImage: MPSImage) {
if let encoder = commandBuffer.makeComputeCommandEncoder() {
encoder.pushDebugGroup(name)
encoder.setComputePipelineState(pipeline)
encoder.setTexture(sourceImage.texture, index: 0)
encoder.setTexture(destinationImage.texture, index: 1)
encoder.dispatch(pipeline: pipeline, image: destinationImage)
encoder.popDebugGroup()
encoder.endEncoding()
}
// Let Metal know the temporary image can be recycled.
if let image = sourceImage as? MPSTemporaryImage {
image.readCount -= 1
}
}
}
extension SimpleKernel: CustomKernel { }
|
mit
|
f00229643d0bf9e2314e77a1b3a0000d
| 37.810345 | 106 | 0.756553 | 4.719078 | false | false | false | false |
zdrzdr/QEDSwift
|
Pods/Kingfisher/Sources/ImageDownloader.swift
|
2
|
17544
|
//
// ImageDownloader.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2016 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.
#if os(OSX)
import AppKit
#else
import UIKit
#endif
/// Progress update block of downloader.
public typealias ImageDownloaderProgressBlock = DownloadProgressBlock
/// Completion block of downloader.
public typealias ImageDownloaderCompletionHandler = ((image: Image?, error: NSError?, imageURL: NSURL?, originalData: NSData?) -> ())
/// Download task.
public struct RetrieveImageDownloadTask {
let internalTask: NSURLSessionDataTask
/// Downloader by which this task is intialized.
public private(set) weak var ownerDownloader: ImageDownloader?
/**
Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error.
*/
public func cancel() {
ownerDownloader?.cancelDownloadingTask(self)
}
/// The original request URL of this download task.
public var URL: NSURL? {
return internalTask.originalRequest?.URL
}
/// The relative priority of this download task.
/// It represents the `priority` property of the internal `NSURLSessionTask` of this download task.
/// The value for it is between 0.0~1.0. Default priority is value of 0.5.
/// See documentation on `priority` of `NSURLSessionTask` for more about it.
public var priority: Float {
get {
return internalTask.priority
}
set {
internalTask.priority = newValue
}
}
}
private let defaultDownloaderName = "default"
private let downloaderBarrierName = "com.onevcat.Kingfisher.ImageDownloader.Barrier."
private let imageProcessQueueName = "com.onevcat.Kingfisher.ImageDownloader.Process."
private let instance = ImageDownloader(name: defaultDownloaderName)
/**
The error code.
- BadData: The downloaded data is not an image or the data is corrupted.
- NotModified: The remote server responsed a 304 code. No image data downloaded.
- InvalidURL: The URL is invalid.
*/
public enum KingfisherError: Int {
case BadData = 10000
case NotModified = 10001
case InvalidURL = 20000
}
/// Protocol of `ImageDownloader`.
@objc public protocol ImageDownloaderDelegate {
/**
Called when the `ImageDownloader` object successfully downloaded an image from specified URL.
- parameter downloader: The `ImageDownloader` object finishes the downloading.
- parameter image: Downloaded image.
- parameter URL: URL of the original request URL.
- parameter response: The response object of the downloading process.
*/
optional func imageDownloader(downloader: ImageDownloader, didDownloadImage image: Image, forURL URL: NSURL, withResponse response: NSURLResponse)
}
/// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server.
public class ImageDownloader: NSObject {
class ImageFetchLoad {
var callbacks = [CallbackPair]()
var responseData = NSMutableData()
var options: KingfisherOptionsInfo?
var downloadTaskCount = 0
var downloadTask: RetrieveImageDownloadTask?
}
// MARK: - Public property
/// This closure will be applied to the image download request before it being sent. You can modify the request for some customizing purpose, like adding auth token to the header or do a url mapping.
public var requestModifier: (NSMutableURLRequest -> Void)?
/// The duration before the download is timeout. Default is 15 seconds.
public var downloadTimeout: NSTimeInterval = 15.0
/// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored. You can use this set to specify the self-signed site.
public var trustedHosts: Set<String>?
/// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. You could change the configuration before a downloaing task starts. A configuration without persistent storage for caches is requsted for downloader working correctly.
public var sessionConfiguration = NSURLSessionConfiguration.ephemeralSessionConfiguration() {
didSet {
session = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
}
}
private var session: NSURLSession?
/// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more.
public weak var delegate: ImageDownloaderDelegate?
// MARK: - Internal property
let barrierQueue: dispatch_queue_t
let processQueue: dispatch_queue_t
typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHander: ImageDownloaderCompletionHandler?)
var fetchLoads = [NSURL: ImageFetchLoad]()
// MARK: - Public method
/// The default downloader.
public class var defaultDownloader: ImageDownloader {
return instance
}
/**
Init a downloader with name.
- parameter name: The name for the downloader. It should not be empty.
- returns: The downloader object.
*/
public init(name: String) {
if name.isEmpty {
fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.")
}
barrierQueue = dispatch_queue_create(downloaderBarrierName + name, DISPATCH_QUEUE_CONCURRENT)
processQueue = dispatch_queue_create(imageProcessQueueName + name, DISPATCH_QUEUE_CONCURRENT)
super.init()
session = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
}
func fetchLoadForKey(key: NSURL) -> ImageFetchLoad? {
var fetchLoad: ImageFetchLoad?
dispatch_sync(barrierQueue, { () -> Void in
fetchLoad = self.fetchLoads[key]
})
return fetchLoad
}
}
// MARK: - Download method
extension ImageDownloader {
/**
Download an image with a URL.
- parameter URL: Target URL.
- parameter progressBlock: Called when the download progress updated.
- parameter completionHandler: Called when the download progress finishes.
- returns: A downloading task. You could call `cancel` on it to stop the downloading process.
*/
public func downloadImageWithURL(URL: NSURL,
progressBlock: ImageDownloaderProgressBlock?,
completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask?
{
return downloadImageWithURL(URL, options: nil, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Download an image with a URL and option.
- parameter URL: Target URL.
- parameter options: The options could control download behavior. See `KingfisherOptionsInfo`.
- parameter progressBlock: Called when the download progress updated.
- parameter completionHandler: Called when the download progress finishes.
- returns: A downloading task. You could call `cancel` on it to stop the downloading process.
*/
public func downloadImageWithURL(URL: NSURL,
options: KingfisherOptionsInfo?,
progressBlock: ImageDownloaderProgressBlock?,
completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask?
{
return downloadImageWithURL(URL,
retrieveImageTask: nil,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
internal func downloadImageWithURL(URL: NSURL,
retrieveImageTask: RetrieveImageTask?,
options: KingfisherOptionsInfo?,
progressBlock: ImageDownloaderProgressBlock?,
completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask?
{
if let retrieveImageTask = retrieveImageTask where retrieveImageTask.cancelledBeforeDownlodStarting {
return nil
}
let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout
// We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL.
let request = NSMutableURLRequest(URL: URL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: timeout)
request.HTTPShouldUsePipelining = true
self.requestModifier?(request)
// There is a possiblility that request modifier changed the url to `nil` or empty.
if request.URL == nil || request.URL!.absoluteString.isEmpty {
completionHandler?(image: nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.InvalidURL.rawValue, userInfo: nil), imageURL: nil, originalData: nil)
return nil
}
var downloadTask: RetrieveImageDownloadTask?
setupProgressBlock(progressBlock, completionHandler: completionHandler, forURL: request.URL!) {(session, fetchLoad) -> Void in
if fetchLoad.downloadTask == nil {
let dataTask = session.dataTaskWithRequest(request)
fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self)
fetchLoad.options = options
dataTask.priority = options?.downloadPriority ?? NSURLSessionTaskPriorityDefault
dataTask.resume()
}
fetchLoad.downloadTaskCount += 1
downloadTask = fetchLoad.downloadTask
retrieveImageTask?.downloadTask = downloadTask
}
return downloadTask
}
// A single key may have multiple callbacks. Only download once.
internal func setupProgressBlock(progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?, forURL URL: NSURL, started: ((NSURLSession, ImageFetchLoad) -> Void)) {
dispatch_barrier_sync(barrierQueue, { () -> Void in
let loadObjectForURL = self.fetchLoads[URL] ?? ImageFetchLoad()
let callbackPair = (progressBlock: progressBlock, completionHander: completionHandler)
loadObjectForURL.callbacks.append(callbackPair)
self.fetchLoads[URL] = loadObjectForURL
if let session = self.session {
started(session, loadObjectForURL)
}
})
}
func cancelDownloadingTask(task: RetrieveImageDownloadTask) {
dispatch_barrier_sync(barrierQueue) { () -> Void in
if let URL = task.internalTask.originalRequest?.URL, imageFetchLoad = self.fetchLoads[URL] {
imageFetchLoad.downloadTaskCount -= 1
if imageFetchLoad.downloadTaskCount == 0 {
task.internalTask.cancel()
}
}
}
}
func cleanForURL(URL: NSURL) {
dispatch_barrier_sync(barrierQueue, { () -> Void in
self.fetchLoads.removeValueForKey(URL)
return
})
}
}
// MARK: - NSURLSessionTaskDelegate
extension ImageDownloader: NSURLSessionDataDelegate {
/**
This method is exposed since the compiler requests. Do not call it.
*/
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
completionHandler(NSURLSessionResponseDisposition.Allow)
}
/**
This method is exposed since the compiler requests. Do not call it.
*/
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if let URL = dataTask.originalRequest?.URL, fetchLoad = fetchLoadForKey(URL) {
fetchLoad.responseData.appendData(data)
for callbackPair in fetchLoad.callbacks {
callbackPair.progressBlock?(receivedSize: Int64(fetchLoad.responseData.length), totalSize: dataTask.response!.expectedContentLength)
}
}
}
/**
This method is exposed since the compiler requests. Do not call it.
*/
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let URL = task.originalRequest?.URL {
if let error = error { // Error happened
callbackWithImage(nil, error: error, imageURL: URL, originalData: nil)
} else { //Download finished without error
processImageForTask(task, URL: URL)
}
}
}
/**
This method is exposed since the compiler requests. Do not call it.
*/
public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
if let trustedHosts = trustedHosts where trustedHosts.contains(challenge.protectionSpace.host) {
let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
completionHandler(.UseCredential, credential)
return
}
}
completionHandler(.PerformDefaultHandling, nil)
}
private func callbackWithImage(image: Image?, error: NSError?, imageURL: NSURL, originalData: NSData?) {
if let callbackPairs = fetchLoadForKey(imageURL)?.callbacks {
self.cleanForURL(imageURL)
for callbackPair in callbackPairs {
callbackPair.completionHander?(image: image, error: error, imageURL: imageURL, originalData: originalData)
}
}
}
private func processImageForTask(task: NSURLSessionTask, URL: NSURL) {
// We are on main queue when receiving this.
dispatch_async(processQueue, { () -> Void in
if let fetchLoad = self.fetchLoadForKey(URL) {
let options = fetchLoad.options ?? KingfisherEmptyOptionsInfo
if let image = Image.kf_imageWithData(fetchLoad.responseData, scale: options.scaleFactor) {
self.delegate?.imageDownloader?(self, didDownloadImage: image, forURL: URL, withResponse: task.response!)
if options.backgroundDecode {
self.callbackWithImage(image.kf_decodedImage(scale: options.scaleFactor), error: nil, imageURL: URL, originalData: fetchLoad.responseData)
} else {
self.callbackWithImage(image, error: nil, imageURL: URL, originalData: fetchLoad.responseData)
}
} else {
// If server response is 304 (Not Modified), inform the callback handler with NotModified error.
// It should be handled to get an image from cache, which is response of a manager object.
if let res = task.response as? NSHTTPURLResponse where res.statusCode == 304 {
self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.NotModified.rawValue, userInfo: nil), imageURL: URL, originalData: nil)
return
}
self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.BadData.rawValue, userInfo: nil), imageURL: URL, originalData: nil)
}
} else {
self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.BadData.rawValue, userInfo: nil), imageURL: URL, originalData: nil)
}
})
}
}
|
mit
|
dfd60619d32e2f6ab5c296528005e7d8
| 42.969925 | 318 | 0.665071 | 5.587261 | false | false | false | false |
gongmingqm10/DriftBook
|
DriftReading/DriftReading/ConversationViewController.swift
|
1
|
2066
|
//
// ConversationViewController.swift
// DriftReading
//
// Created by Ming Gong on 8/21/15.
// Copyright © 2015 gongmingqm10. All rights reserved.
//
import UIKit
class ConversationViewController: UITableViewController {
@IBOutlet var conversationTable: UITableView!
let driftAPI = DriftAPI()
var conversations: [Conversation] = []
var selectedConversation: Conversation?
override func viewDidLoad() {
self.conversationTable.rowHeight = UITableViewAutomaticDimension
self.conversationTable.estimatedRowHeight = 80.0
}
override func viewDidAppear(animated: Bool) {
let user = DataUtils.sharedInstance.currentUser()
driftAPI.getMessages(user.userId, success: { (conversations) -> Void in
self.conversations = conversations
self.conversationTable.reloadData()
}) { (error) -> Void in
print(error.description)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ChattingSegue" {
let messageViewController = segue.destinationViewController as! MessageViewController
messageViewController.messages = selectedConversation!.messages
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.selectedConversation = conversations[indexPath.row]
self.performSegueWithIdentifier("ChattingSegue", sender: self)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return conversations.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = conversationTable.dequeueReusableCellWithIdentifier("ConversationTableCell", forIndexPath: indexPath) as! ConversationTableCell
let conversation = conversations[indexPath.row]
cell.populate(conversation)
return cell
}
}
|
mit
|
00c65c587f6a2de73acf8b9b200feaf8
| 36.563636 | 146 | 0.701695 | 5.536193 | false | false | false | false |
xuzhou524/Convenient-Swift
|
Libs/DGElasticPullToRefresh/DGElasticPullToRefreshExtensions.swift
|
1
|
5227
|
/*
The MIT License (MIT)
Copyright (c) 2015 Danil Gontovnik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import UIKit
import ObjectiveC
// MARK: -
// MARK: (NSObject) Extension
public extension NSObject {
// MARK: -
// MARK: Vars
fileprivate struct dg_associatedKeys {
static var observersArray = "observers"
}
fileprivate var dg_observers: [[String : NSObject]] {
get {
if let observers = objc_getAssociatedObject(self, &dg_associatedKeys.observersArray) as? [[String : NSObject]] {
return observers
} else {
let observers = [[String : NSObject]]()
self.dg_observers = observers
return observers
}
} set {
objc_setAssociatedObject(self, &dg_associatedKeys.observersArray, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: -
// MARK: Methods
public func dg_addObserver(_ observer: NSObject, forKeyPath keyPath: String) {
let observerInfo = [keyPath : observer]
if dg_observers.index(where: { $0 == observerInfo }) == nil {
dg_observers.append(observerInfo)
addObserver(observer, forKeyPath: keyPath, options: .new, context: nil)
}
}
public func dg_removeObserver(_ observer: NSObject, forKeyPath keyPath: String) {
let observerInfo = [keyPath : observer]
if let index = dg_observers.index(where: { $0 == observerInfo}) {
dg_observers.remove(at: index)
removeObserver(observer, forKeyPath: keyPath)
}
}
}
// MARK: -
// MARK: (UIScrollView) Extension
public extension UIScrollView {
// MARK: - Vars
fileprivate struct dg_associatedKeys {
static var pullToRefreshView = "pullToRefreshView"
}
fileprivate var pullToRefreshView: DGElasticPullToRefreshView? {
get {
return objc_getAssociatedObject(self, &dg_associatedKeys.pullToRefreshView) as? DGElasticPullToRefreshView
}
set {
objc_setAssociatedObject(self, &dg_associatedKeys.pullToRefreshView, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Methods (Public)
public func dg_addPullToRefreshWithActionHandler(_ actionHandler: @escaping () -> Void, loadingView: DGElasticPullToRefreshLoadingView?) {
isMultipleTouchEnabled = false
panGestureRecognizer.maximumNumberOfTouches = 1
let pullToRefreshView = DGElasticPullToRefreshView()
self.pullToRefreshView = pullToRefreshView
pullToRefreshView.actionHandler = actionHandler
pullToRefreshView.loadingView = loadingView
addSubview(pullToRefreshView)
pullToRefreshView.observing = true
}
public func dg_removePullToRefresh() {
pullToRefreshView?.disassociateDisplayLink()
pullToRefreshView?.observing = false
pullToRefreshView?.removeFromSuperview()
}
public func dg_setPullToRefreshBackgroundColor(_ color: UIColor) {
pullToRefreshView?.backgroundColor = color
}
public func dg_setPullToRefreshFillColor(_ color: UIColor) {
pullToRefreshView?.fillColor = color
}
public func dg_stopLoading() {
pullToRefreshView?.stopLoading()
}
}
// MARK: -
// MARK: (UIView) Extension
public extension UIView {
func dg_center(_ usePresentationLayerIfPossible: Bool) -> CGPoint {
if usePresentationLayerIfPossible, let presentationLayer = layer.presentation() as? CALayer {
// Position can be used as a center, because anchorPoint is (0.5, 0.5)
return presentationLayer.position
}
return center
}
}
// MARK: -
// MARK: (UIPanGestureRecognizer) Extension
public extension UIPanGestureRecognizer {
func dg_resign() {
isEnabled = false
isEnabled = true
}
}
// MARK: -
// MARK: (UIGestureRecognizerState) Extension
public extension UIGestureRecognizerState {
func dg_isAnyOf(_ values: [UIGestureRecognizerState]) -> Bool {
return values.contains(where: { $0 == self })
}
}
|
mit
|
49e89523791247f6eb19c0d2ec048dc6
| 30.871951 | 148 | 0.674957 | 5.069835 | false | false | false | false |
GreatfeatServices/gf-mobile-app
|
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/Delay.swift
|
11
|
5510
|
//
// Delay.swift
// RxSwift
//
// Created by tarunon on 2016/02/09.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import Foundation
class DelaySink<O: ObserverType>
: Sink<O>
, ObserverType {
typealias E = O.E
typealias Source = Observable<E>
typealias DisposeKey = Bag<Disposable>.KeyType
private let _lock = NSRecursiveLock()
private let _dueTime: RxTimeInterval
private let _scheduler: SchedulerType
private let _sourceSubscription = SingleAssignmentDisposable()
private let _cancelable = SerialDisposable()
// is scheduled some action
private var _active = false
// is "run loop" on different scheduler running
private var _running = false
private var _errorEvent: Event<E>? = nil
// state
private var _queue = Queue<(eventTime: RxTime, event: Event<E>)>(capacity: 0)
private var _disposed = false
init(observer: O, dueTime: RxTimeInterval, scheduler: SchedulerType, cancel: Cancelable) {
_dueTime = dueTime
_scheduler = scheduler
super.init(observer: observer, cancel: cancel)
}
// All of these complications in this method are caused by the fact that
// error should be propagated immediatelly. Error can bepotentially received on different
// scheduler so this process needs to be synchronized somehow.
//
// Another complication is that scheduler is potentially concurrent so internal queue is used.
func drainQueue(state: (), scheduler: AnyRecursiveScheduler<()>) {
_lock.lock() // {
let hasFailed = _errorEvent != nil
if !hasFailed {
_running = true
}
_lock.unlock() // }
if hasFailed {
return
}
var ranAtLeastOnce = false
while true {
_lock.lock() // {
let errorEvent = _errorEvent
let eventToForwardImmediatelly = ranAtLeastOnce ? nil : _queue.dequeue()?.event
let nextEventToScheduleOriginalTime: Date? = ranAtLeastOnce && !_queue.isEmpty ? _queue.peek().eventTime : nil
if let _ = errorEvent {
}
else {
if let _ = eventToForwardImmediatelly {
}
else if let _ = nextEventToScheduleOriginalTime {
_running = false
}
else {
_running = false
_active = false
}
}
_lock.unlock() // {
if let errorEvent = errorEvent {
self.forwardOn(errorEvent)
self.dispose()
return
}
else {
if let eventToForwardImmediatelly = eventToForwardImmediatelly {
ranAtLeastOnce = true
self.forwardOn(eventToForwardImmediatelly)
if case .completed = eventToForwardImmediatelly {
self.dispose()
return
}
}
else if let nextEventToScheduleOriginalTime = nextEventToScheduleOriginalTime {
let elapsedTime = _scheduler.now.timeIntervalSince(nextEventToScheduleOriginalTime)
let interval = _dueTime - elapsedTime
let normalizedInterval = interval < 0.0 ? 0.0 : interval
scheduler.schedule((), dueTime: normalizedInterval)
return
}
else {
return
}
}
}
}
func on(_ event: Event<E>) {
if event.isStopEvent {
_sourceSubscription.dispose()
}
switch event {
case .error(_):
_lock.lock() // {
let shouldSendImmediatelly = !_running
_queue = Queue(capacity: 0)
_errorEvent = event
_lock.unlock() // }
if shouldSendImmediatelly {
forwardOn(event)
dispose()
}
default:
_lock.lock() // {
let shouldSchedule = !_active
_active = true
_queue.enqueue((_scheduler.now, event))
_lock.unlock() // }
if shouldSchedule {
_cancelable.disposable = _scheduler.scheduleRecursive((), dueTime: _dueTime, action: self.drainQueue)
}
}
}
func run(source: Source) -> Disposable {
_sourceSubscription.setDisposable(source.subscribeSafe(self))
return Disposables.create(_sourceSubscription, _cancelable)
}
}
class Delay<Element>: Producer<Element> {
private let _source: Observable<Element>
private let _dueTime: RxTimeInterval
private let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) {
_source = source
_dueTime = dueTime
_scheduler = scheduler
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = DelaySink(observer: observer, dueTime: _dueTime, scheduler: _scheduler, cancel: cancel)
let subscription = sink.run(source: _source)
return (sink: sink, subscription: subscription)
}
}
|
apache-2.0
|
8a982b3e00eba72f939a17d7e426c787
| 32.591463 | 145 | 0.550372 | 5.348544 | false | false | false | false |
HuanDay/Booster
|
Booster/BModule/BSTFundDetailVC.swift
|
1
|
2641
|
//
// BSTFundDetailVC.swift
// Booster
//
// Created by Michael Zhai on 22/02/17.
// Copyright © 2017 Michael Zhai. All rights reserved.
//
import Foundation
class BSTFundDetailVC : BSTBaseVC, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var fundTableview: UITableView!
var imgNameList = [""]
override func viewDidLoad() {
super.viewDidLoad()
initTableView()
}
func setUp(investorType: String) {
self.imgNameList = FundDetailModel.getFundImgNameList(investorType: investorType)
}
func initTableView() {
let emptyView = UIView.init(frame: CGRect(x: 0, y: 0, width: Constants.SCREEN.SCREEN_WIDTH, height: 0))
emptyView.backgroundColor = UIColor.lightGray
fundTableview.tableFooterView = emptyView
fundTableview.dataSource = self
fundTableview.delegate = self
fundTableview.register(BSTFundCell.self, forCellReuseIdentifier: "BSTFundCell")
}
// tableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return imgNameList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BSTFundCell") as? BSTFundCell
cell?.setCell(imgName: self.imgNameList[indexPath.row])
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let ratio = CGFloat(1272)/CGFloat(608)
let height = Constants.SCREEN.SCREEN_WIDTH*ratio
return height
}
override func menuBtnOnClick() {
_ = self.navigationController?.popViewController(animated: true)
}
}
class BSTFundCell : UITableViewCell {
var imgView: UIImageView?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.initImgView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func initImgView() {
let width = self.frame.size.width
let height = self.frame.size.height
self.imgView = UIImageView.init(frame: CGRect.init(x:0, y: 0, width: width, height: height))
self.contentView.addSubview(self.imgView!)
self.imgView?.contentMode = .scaleAspectFit
}
func setCell(imgName: String) {
self.imageView?.image = UIImage.init(named: imgName)
}
}
|
mit
|
a9905da4f36bdae0aea2c88ef3d10407
| 29.697674 | 111 | 0.656818 | 4.536082 | false | false | false | false |
dmorenob/HermesFramework
|
Hermes/HermesGetSearchTweets.swift
|
1
|
2201
|
//
// HermesGetSearchTweets.swift
// Hermes
//
// Created by David Moreno Briz on 3/12/14.
// Copyright (c) 2014 David Moreno Briz. All rights reserved.
//
import Foundation
extension Hermes {
// Func to perform a GET to a search query (REST API)
func getSearchTweets(q: String, geocode: Array<String>?, lang: String?, locale: String?, result_type: String?, until: String?, count: Int?, since_id: Int?, max_id: Int?, include_entities: Bool?, callback: String?, completitionHandler: ((data: NSData!, response: NSURLResponse!, error: NSError!) -> Void)){
//We generate the array of query parameters form the params of this func.
var paramsForQuery = Array<(key: String, value: String)>()
paramsForQuery += [(key: "q",value: q)]
if geocode != nil {
paramsForQuery += [(key: "geocode",value: "\(geocode![0]),\(geocode![1]),\(geocode![2])km")]
}
if lang != nil {
paramsForQuery += [(key: "lang",value: lang!)]
}
if count != nil {
paramsForQuery += [(key: "count",value: count!.description)]
}
if since_id != nil {
paramsForQuery += [(key: "since_id",value: since_id!.description)]
}
if max_id != nil {
paramsForQuery += [(key: "max_id",value: max_id!.description)]
}
if locale != nil {
paramsForQuery += [(key: "locale",value: locale!)]
}
if result_type != nil {
paramsForQuery += [(key: "result_type",value: result_type!)]
}
if until != nil {
paramsForQuery += [(key: "until",value: until!)]
}
if callback != nil {
paramsForQuery += [(key: "callback",value: callback!)]
}
if include_entities != nil {
paramsForQuery += [(key: "include_entities",value: include_entities!.description)]
}
// And perform the GET request.
self.get("https://api.twitter.com/1.1/search/tweets.json", paramsForQuery: paramsForQuery, paramsForHeaderWhitoutSignature: self.generateParamsForHeaderWhitoutSignature(), paramsForBody: [], completitionHandler: completitionHandler)
}
}
|
mit
|
a0ee19a973704e0f2501b12fd61f4623
| 42.176471 | 309 | 0.585189 | 4.315686 | false | false | false | false |
eoger/firefox-ios
|
Client/Frontend/Browser/ButtonToast.swift
|
5
|
6107
|
/* 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 SnapKit
struct ButtonToastUX {
static let ToastHeight: CGFloat = 55.0
static let ToastPadding: CGFloat = 10.0
static let ToastButtonPadding: CGFloat = 10.0
static let ToastDelay = DispatchTimeInterval.milliseconds(900)
static let ToastButtonBorderRadius: CGFloat = 5
static let ToastButtonBorderWidth: CGFloat = 1
static let ToastLabelFont = UIFont.systemFont(ofSize: 15, weight: .semibold)
static let ToastDescriptionFont = UIFont.systemFont(ofSize: 13)
}
class ButtonToast: Toast {
class HighlightableButton: UIButton {
override var isHighlighted: Bool {
didSet {
backgroundColor = isHighlighted ? .white : .clear
}
}
}
init(labelText: String, descriptionText: String? = nil, imageName: String? = nil, buttonText: String? = nil, backgroundColor: UIColor = SimpleToastUX.ToastDefaultColor, textAlignment: NSTextAlignment = .left, completion: ((_ buttonPressed: Bool) -> Void)? = nil) {
super.init(frame: .zero)
self.completionHandler = completion
self.clipsToBounds = true
self.addSubview(createView(labelText, descriptionText: descriptionText, imageName: imageName, buttonText: buttonText, textAlignment: textAlignment))
self.toastView.backgroundColor = backgroundColor
self.toastView.snp.makeConstraints { make in
make.left.right.height.equalTo(self)
self.animationConstraint = make.top.equalTo(self).offset(ButtonToastUX.ToastHeight).constraint
}
self.snp.makeConstraints { make in
make.height.equalTo(ButtonToastUX.ToastHeight)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func createView(_ labelText: String, descriptionText: String?, imageName: String?, buttonText: String?, textAlignment: NSTextAlignment) -> UIView {
let horizontalStackView = UIStackView()
horizontalStackView.axis = .horizontal
horizontalStackView.alignment = .center
horizontalStackView.spacing = ButtonToastUX.ToastPadding
if let imageName = imageName {
let icon = UIImageView(image: UIImage.templateImageNamed(imageName))
icon.tintColor = UIColor.Photon.White100
horizontalStackView.addArrangedSubview(icon)
}
let labelStackView = UIStackView()
labelStackView.axis = .vertical
labelStackView.alignment = .leading
let label = UILabel()
label.textAlignment = textAlignment
label.textColor = UIColor.Photon.White100
label.font = ButtonToastUX.ToastLabelFont
label.text = labelText
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
labelStackView.addArrangedSubview(label)
var descriptionLabel: UILabel?
if let descriptionText = descriptionText {
label.lineBreakMode = .byClipping
label.numberOfLines = 1 // if showing a description we cant wrap to the second line
label.adjustsFontSizeToFitWidth = true
descriptionLabel = UILabel()
descriptionLabel?.textAlignment = textAlignment
descriptionLabel?.textColor = UIColor.Photon.White100
descriptionLabel?.font = ButtonToastUX.ToastDescriptionFont
descriptionLabel?.text = descriptionText
descriptionLabel?.lineBreakMode = .byTruncatingTail
labelStackView.addArrangedSubview(descriptionLabel!)
}
horizontalStackView.addArrangedSubview(labelStackView)
if let buttonText = buttonText {
let button = HighlightableButton()
button.layer.cornerRadius = ButtonToastUX.ToastButtonBorderRadius
button.layer.borderWidth = ButtonToastUX.ToastButtonBorderWidth
button.layer.borderColor = UIColor.Photon.White100.cgColor
button.setTitle(buttonText, for: [])
button.setTitleColor(toastView.backgroundColor, for: .highlighted)
button.titleLabel?.font = SimpleToastUX.ToastFont
button.titleLabel?.numberOfLines = 1
button.titleLabel?.lineBreakMode = .byClipping
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.minimumScaleFactor = 0.1
button.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(buttonPressed)))
button.snp.makeConstraints { (make) in
make.width.equalTo(button.titleLabel!.intrinsicContentSize.width + 2 * ButtonToastUX.ToastButtonPadding)
}
horizontalStackView.addArrangedSubview(button)
}
toastView.addSubview(horizontalStackView)
if textAlignment == .center {
label.snp.makeConstraints { make in
make.centerX.equalTo(toastView)
}
descriptionLabel?.snp.makeConstraints { make in
make.centerX.equalTo(toastView)
}
}
horizontalStackView.snp.makeConstraints { make in
make.centerX.equalTo(toastView)
make.centerY.equalTo(toastView)
make.width.equalTo(toastView.snp.width).offset(-2 * ButtonToastUX.ToastPadding)
}
return toastView
}
@objc func buttonPressed(_ gestureRecognizer: UIGestureRecognizer) {
completionHandler?(true)
dismiss(true)
}
override func showToast(viewController: UIViewController? = nil, delay: DispatchTimeInterval = SimpleToastUX.ToastDelayBefore, duration: DispatchTimeInterval? = SimpleToastUX.ToastDismissAfter, makeConstraints: @escaping (SnapKit.ConstraintMaker) -> Swift.Void) {
super.showToast(viewController: viewController, delay: delay, duration: duration, makeConstraints: makeConstraints)
}
}
|
mpl-2.0
|
42f9d0ebbeebd4639e0d93a4599fb5c7
| 41.409722 | 268 | 0.682495 | 5.541742 | false | false | false | false |
dbahat/conventions-ios
|
Conventions/Conventions/model/Events.swift
|
1
|
5683
|
//
// Events.swift
// Conventions
//
// Created by David Bahat on 3/5/16.
// Copyright © 2016 Amai. All rights reserved.
//
import Foundation
class Events {
private static let eventsApiUrl = URL(string: "https://api.sf-f.org.il/program/list_events.php?slug="+Convention.name)!;
private static let availableTicketsCacheLastRefreshTimeApi = URL(string: "https://api.sf-f.org.il/program/cache_get_last_updated.php?which=available_tickets&slug="+Convention.name)!
private static let fileName = Convention.name + "Events.json";
private static let cacheFile = NSHomeDirectory() + "/Library/Caches/" + "1_" + fileName;
private var events: Array<ConventionEvent> = [];
init(halls: Array<Hall>) {
guard let resourcePath = Bundle.main.resourcePath else {
return;
};
if let cachedEvents = try? Data(contentsOf: URL(fileURLWithPath: Events.cacheFile)) {
if let parsedCachedEvents = parse(cachedEvents, halls: halls) {
events = parsedCachedEvents
print("Cached events: ", events.count)
}
} else if let preInstalledEvents = try? Data(contentsOf: URL(fileURLWithPath: resourcePath + "/" + Events.fileName)) {
if let parsedPreInstalledEvents = parse(preInstalledEvents, halls: halls) {
events = parsedPreInstalledEvents
print("Preinstalled events: ", events.count)
}
}
}
func getAll() -> Array<ConventionEvent> {
return events;
}
func refresh(_ callback: ((_ success: Bool) -> Void)?) {
// Don't refresh events after the convention has ended
if (Convention.endDate.timeIntervalSince1970 < Date.now().clearTimeComponent().timeIntervalSince1970) {
callback?(true)
}
let request = URLRequest(url: Events.eventsApiUrl, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 60.0)
URLSession.shared.dataTask(with: request, completionHandler:{(data, response, error) -> Void in
guard let events = data else {
DispatchQueue.main.async {
callback?(false);
}
return;
}
let request = URLRequest(url: Events.availableTicketsCacheLastRefreshTimeApi, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 60.0)
URLSession.shared.dataTask(with: request, completionHandler:{(data, response, error) -> Void in
guard let availableTicketsCallResponse = response as? HTTPURLResponse else {
DispatchQueue.main.async {
callback?(false);
}
return
}
if (availableTicketsCallResponse.statusCode != 200) {
DispatchQueue.main.async {
callback?(false);
}
return
}
guard
let availableTicketsLastModifiedString = availableTicketsCallResponse.allHeaderFields["Last-Modified"] as? String,
let availableTicketsLastModifiedDate = Date.parse(availableTicketsLastModifiedString, dateFormat: "EEE, dd MMM yyyy HH:mm:ss zzz")
else {
print("failed to fetch tickets last modified value")
DispatchQueue.main.async {
callback?(false);
}
return
}
guard let parsedEvents = SffEventsParser().parse(data: events) else {
DispatchQueue.main.async {
callback?(false);
}
return
}
parsedEvents.forEach({$0.availableTicketsLastModified = availableTicketsLastModifiedDate})
if let serializedData = try? JSONSerialization.data(
withJSONObject: parsedEvents.map({$0.toJson()}),
options: JSONSerialization.WritingOptions.prettyPrinted) {
try? serializedData.write(to: URL(fileURLWithPath: Events.cacheFile), options: [.atomic])
}
// Using main thread for syncronizing access to events
DispatchQueue.main.async {
self.events = parsedEvents;
print("Downloaded events: ", self.events.count);
callback?(true);
}
}).resume()
}).resume()
}
private func parse(_ data: Data, halls: Array<Hall>) -> Array<ConventionEvent>? {
var result = Array<ConventionEvent>()
guard let parsedEvents = deserialize(data) as? NSArray
else {
print("Failed to deserialize events");
return result;
}
for event in parsedEvents {
if let parsedEvent = ConventionEvent.parse(event as! Dictionary<String, AnyObject>, halls: halls) {
result.append(parsedEvent)
}
}
print("parsed events: ", result.count);
return result
}
private func deserialize(_ data: Data) -> Any? {
do {
return try JSONSerialization.jsonObject(with: data, options: [])
} catch {
print("json error: \(error.localizedDescription)")
return nil
}
}
}
|
apache-2.0
|
3214e33aa7e33ef024b010e670d00941
| 39.877698 | 185 | 0.551566 | 5.421756 | false | false | false | false |
alickbass/ViewComponents
|
ViewComponents/UIImageViewStyle.swift
|
1
|
2513
|
//
// UIImageViewStyle.swift
// ViewComponents
//
// Created by Oleksii on 03/05/2017.
// Copyright © 2017 WeAreReasonablePeople. All rights reserved.
//
import UIKit
private enum UIImageViewStyleKey: Int, StyleKey {
case image = 250, highlightedImage, animationImages
case highlightedAnimationImages, animationDuration, animationRepeatCount
case isHighlighted
}
public extension AnyStyle where T: UIImageView {
private typealias ViewStyle<Item> = Style<T, Item, UIImageViewStyleKey>
public static func image(_ value: UIImage?) -> AnyStyle<T> {
return ViewStyle(value, key: .image, sideEffect: { $0.image = $1 }).toAnyStyle
}
public static func highlightedImage(_ value: UIImage?) -> AnyStyle<T> {
return ViewStyle(value, key: .highlightedImage, sideEffect: { $0.highlightedImage = $1 }).toAnyStyle
}
public static func animationImages(_ value: [UIImage]?) -> AnyStyle<T> {
return ViewStyle(value, key: .animationImages,
sideEffect: { $0.animationImages = $1 },
equality: { $0 == $1 },
hash: { $0.hashValue }
).toAnyStyle
}
public static func highlightedAnimationImages(_ value: [UIImage]?) -> AnyStyle<T> {
return ViewStyle(value, key: .highlightedAnimationImages,
sideEffect: { $0.highlightedAnimationImages = $1 },
equality: { $0 == $1 },
hash: { $0.hashValue }
).toAnyStyle
}
public static func animationDuration(_ value: TimeInterval) -> AnyStyle<T> {
return ViewStyle(value, key: .animationDuration, sideEffect: { $0.animationDuration = $1 }).toAnyStyle
}
public static func animationRepeatCount(_ value: Int) -> AnyStyle<T> {
return ViewStyle(value, key: .animationRepeatCount, sideEffect: { $0.animationRepeatCount = $1 }).toAnyStyle
}
public static func isHighlighted(_ value: Bool) -> AnyStyle<T> {
return ViewStyle(value, key: .isHighlighted, sideEffect: { $0.isHighlighted = $1 }).toAnyStyle
}
}
private extension Optional where Wrapped == [UIImage] {
static func == (lhs: [UIImage]?, rhs: [UIImage]?) -> Bool {
switch (lhs, rhs) {
case (nil, nil):
return true
case let (left?, right?):
return left == right
default:
return false
}
}
var hashValue: Int {
return map({ $0.reduce(5381, { (($0 << 5) &+ $0) &+ $1.hashValue }) }) ?? 0
}
}
|
mit
|
7074ea369029b8220ed1dc5aa653d42a
| 33.888889 | 116 | 0.617834 | 4.32358 | false | false | false | false |
ioan-chera/DoomMakerSwift
|
DoomMakerSwift/TextureName.swift
|
1
|
1414
|
/*
DoomMaker
Copyright (C) 2017 Ioan Chera
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
///
/// This holds the name of a texture, either in raw format or in string format
///
struct TextureName {
let data: [UInt8]
init(_ name: String = "-") {
self.init(bytes: [UInt8](name.utf8))
}
init(bytes: [UInt8]) {
var utf8 = bytes
if utf8.count > 8 {
utf8 = Array(utf8[0..<8])
}
data = utf8
}
var name: String {
// get {
let safeData = data + [UInt8(0)]
return String(cString: safeData)
// }
// set(value) {
// var utf8 = [UInt8](value.utf8)
// if utf8.count > 8 {
// utf8 = Array(utf8[0..<8])
// }
// data = utf8
// }
}
}
|
gpl-3.0
|
3a30137a691a67946b73da31b6ab8e45
| 25.679245 | 78 | 0.601839 | 3.790885 | false | false | false | false |
bcongdon/advent_of_code_2016
|
Day10-19/11.swift
|
1
|
3415
|
//
// 11.swift
//
//
// Created by Benjamin Congdon on 12/11/16.
//
//
//import Foundation
let part1_chips = [2, 1, 2, 1, 1]
let part1_gens = [1, 1, 1, 1, 1]
let part2_chips = part1_chips + [1, 1]
let part2_gens = part1_gens + [1, 1]
struct State {
var chips: [Int]
var gens: [Int]
var elevator: Int
var steps: Int
}
func is_valid(state: State) -> Bool {
if(!((1 ... 4) ~= state.elevator)) {
return false
}
for (idx, f) in state.chips.enumerate() {
if f != state.gens[idx] && state.gens.contains(f){
return false
}
}
return true;
}
func solved(state: State) -> Bool {
for c in state.chips + state.gens {
if c != 4 {
return false
}
}
return true
}
func floor_count(arr: [Int]) -> [Int] {
return (1...4).map({
(floor: Int) -> Int in
return arr.reduce(0) {prev, i in prev + (i == floor ? 1 : 0)}
})
}
func generalize(state: State) -> String {
// return String(state.chips + state.gens) + String(state.elevator)
return String(floor_count(state.chips) + floor_count(state.gens)) + String(state.elevator)
}
func bfs(start: State) -> Int {
var bfs_q = [start]
var seen = Set<String>()
while bfs_q.count > 0 {
let state = bfs_q.removeAtIndex(0)
if (seen.contains(generalize(state)) || !is_valid(state)){
continue
}
else if solved(state) {
return state.steps
}
else {
seen.insert(generalize(state))
}
// print(bfs_q.count)
var combined = state.chips + state.gens
for i in (0..<combined.count) {
if combined[i] != state.elevator {
continue
}
combined[i] -= 1
bfs_q.append(State(chips: Array(combined[0..<state.chips.count]),
gens: Array(combined[state.chips.count..<combined.count]),
elevator: state.elevator - 1, steps: state.steps + 1))
combined[i] += 2
bfs_q.append(State(chips: Array(combined[0..<state.chips.count]),
gens: Array(combined[state.chips.count..<combined.count]),
elevator: state.elevator + 1, steps: state.steps + 1))
combined[i] -= 1
for j in ((i + 1) ..< combined.count) {
if combined[j] != state.elevator {
continue
}
combined[i] -= 1
combined[j] -= 1
bfs_q.append(State(chips: Array(combined[0..<state.chips.count]),
gens: Array(combined[state.chips.count..<combined.count]),
elevator: state.elevator - 1, steps: state.steps + 1))
combined[i] += 2
combined[j] += 2
bfs_q.append(State(chips: Array(combined[0..<state.chips.count]),
gens: Array(combined[state.chips.count..<combined.count]),
elevator: state.elevator + 1, steps: state.steps + 1))
combined[i] -= 1
combined[j] -= 1
}
}
}
return -1
}
let state1 = State(chips: part1_chips, gens: part1_gens, elevator: 1, steps: 0)
let state2 = State(chips: part2_chips, gens: part2_gens, elevator: 1, steps: 0)
print("Part 1: \(bfs(state1))")
print("Part 2: \(bfs(state2))")
|
mit
|
d8f5550afe4c21e71b9a9d6a9169fd07
| 29.5 | 94 | 0.515959 | 3.2805 | false | false | false | false |
victorwon/SwiftBus
|
Pod/Classes/ColorExtension.swift
|
1
|
2428
|
//
// ColorExtension.swift
// Pods
//
// Created by Adam on 2015-09-21.
//
//
import Foundation
#if os(OSX)
typealias SwiftBusColor = NSColor
#else
import UIKit
typealias SwiftBusColor = UIColor
#endif
extension SwiftBusColor {
public convenience init(rgba: String) {
let colorValues = parseRGBAString(rgba)
self.init(red:colorValues.red, green:colorValues.green, blue:colorValues.blue, alpha:colorValues.alpha)
}
}
//Parsing the string
private func parseRGBAString(_ rgba: String) -> (red:CGFloat, green:CGFloat, blue:CGFloat, alpha:CGFloat) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = rgba.characters.index(rgba.startIndex, offsetBy: 1)
let hex = rgba.substring(from: index)
let scanner = Scanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexInt64(&hexValue) {
switch (hex.characters.count) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8")
}
} else {
print("Scan hex error")
}
} else {
print("Invalid RGB string, missing '#' as prefix")
}
return (red, green, blue, alpha)
}
|
mit
|
78264110bbf71442d0ae871a1b919815
| 34.188406 | 111 | 0.531713 | 3.781931 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker
|
Pods/HXPHPicker/Sources/HXPHPicker/Editor/View/Video/VideoEditorMusicViewCell.swift
|
1
|
13369
|
//
// VideoEditorMusicViewCell.swift
// HXPHPicker
//
// Created by Slience on 2021/8/26.
//
import UIKit
class VideoEditorMusicViewCell: UICollectionViewCell {
lazy var bgView: UIVisualEffectView = {
let visualEffect = UIBlurEffect.init(style: .light)
let view = UIVisualEffectView.init(effect: visualEffect)
view.layer.cornerRadius = 12
view.layer.masksToBounds = true
view.contentView.addSubview(musicIconView)
return view
}()
lazy var songNameLb: UILabel = {
let label = UILabel()
label.font = .mediumPingFang(ofSize: 16)
return label
}()
lazy var animationView: VideoEditorMusicAnimationView = {
let view = VideoEditorMusicAnimationView()
view.isHidden = true
return view
}()
lazy var flowLayout: UICollectionViewFlowLayout = {
let flowLayout = UICollectionViewFlowLayout.init()
flowLayout.scrollDirection = .horizontal
flowLayout.minimumLineSpacing = 0
flowLayout.minimumInteritemSpacing = 20
flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
return flowLayout
}()
lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(
frame: CGRect(x: 0, y: 0, width: 0, height: 50),
collectionViewLayout: flowLayout
)
collectionView.backgroundColor = .clear
collectionView.dataSource = self
collectionView.delegate = self
collectionView.isScrollEnabled = false
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.isUserInteractionEnabled = false
if #available(iOS 11.0, *) {
collectionView.contentInsetAdjustmentBehavior = .never
}
collectionView.register(
VideoEditorMusicLyricViewCell.self,
forCellWithReuseIdentifier: "VideoEditorMusicLyricViewCellID"
)
return collectionView
}()
lazy var shadeView: UIView = {
let view = UIView.init()
view.addSubview(collectionView)
view.layer.mask = maskLayer
return view
}()
lazy var maskLayer: CAGradientLayer = {
let maskLayer = CAGradientLayer.init()
maskLayer.colors = [UIColor.clear.cgColor, UIColor.white.cgColor, UIColor.white.cgColor, UIColor.clear.cgColor]
maskLayer.startPoint = CGPoint(x: 0, y: 1)
maskLayer.endPoint = CGPoint(x: 1, y: 1)
maskLayer.locations = [0.0, 0.1, 0.9, 1.0]
return maskLayer
}()
lazy var musicIconView: UIImageView = {
let view = UIImageView.init(image: "hx_editor_tools_music".image?.withRenderingMode(.alwaysTemplate))
view.tintColor = .white
view.size = view.image?.size ?? .zero
return view
}()
lazy var loadingView: UIActivityIndicatorView = {
let view = UIActivityIndicatorView(style: .white)
view.isHidden = true
return view
}()
var music: VideoEditorMusic! {
didSet {
if music.isLoading {
loadingView.isHidden = false
loadingView.startAnimating()
return
}
if music.lyrics.isEmpty {
music.parseLrc()
}
if let songName = music.songName, !songName.isEmpty,
let singer = music.singer, !singer.isEmpty {
songNameLb.text = songName + " - " + singer
}else {
songNameLb.text = music.songName
}
collectionView.reloadData()
if music.isSelected {
playMusic { _, _ in
}
}else {
resetStatus()
}
}
}
var isPlaying: Bool = false
var playTimer: DispatchSourceTimer?
func playMusic(completion: @escaping (String, VideoEditorMusic) -> Void) {
hideLoading()
if music.audioURL.isFileURL {
playLocalMusic(completion: completion)
}else {
playNetworkMusic(completion: completion)
}
}
func playLocalMusic(completion: @escaping (String, VideoEditorMusic) -> Void) {
music.localAudioPath = music.audioURL.path
didPlay(audioPath: music.audioURL.path)
music.isSelected = true
completion(music.audioURL.path, music)
}
func playNetworkMusic(completion: @escaping (String, VideoEditorMusic) -> Void) {
let key = music.audioURL.absoluteString
let audioTmpURL = PhotoTools.getAudioTmpURL(for: key)
if PhotoTools.isCached(forAudio: key) {
music.localAudioPath = audioTmpURL.path
didPlay(audioPath: audioTmpURL.path)
music.isSelected = true
completion(audioTmpURL.path, music)
return
}
showLoading()
PhotoManager.shared.downloadTask(
with: music.audioURL,
toFile: audioTmpURL,
ext: music
) { audioURL, error, ext in
self.hideLoading()
if let audioURL = audioURL,
let music = ext as? VideoEditorMusic {
if music == self.music {
self.didPlay(audioPath: audioURL.path)
}else {
PhotoManager.shared.playMusic(filePath: audioURL.path) {}
}
music.isSelected = true
completion(audioURL.path, music)
}else {
self.resetStatus()
}
}
}
func showLoading() {
loadingView.style = .gray
loadingView.startAnimating()
loadingView.isHidden = false
let visualEffect = UIBlurEffect(style: .extraLight)
bgView.effect = visualEffect
musicIconView.tintColor = "#333333".color
songNameLb.textColor = "#333333".color
songNameLb.isHidden = true
collectionView.isHidden = true
}
func hideLoading() {
songNameLb.isHidden = false
collectionView.isHidden = false
loadingView.stopAnimating()
loadingView.isHidden = true
}
func didPlay(audioPath: String) {
isPlaying = true
let visualEffect = UIBlurEffect.init(style: .extraLight)
bgView.effect = visualEffect
musicIconView.tintColor = "#333333".color
songNameLb.textColor = "#333333".color
animationView.startAnimation()
animationView.isHidden = false
collectionView.reloadData()
let startPointX = -(width - 15)
if music.isSelected {
playTimer?.cancel()
if music.lyricIsEmpty {
DispatchQueue.main.async {
self.scrollLyric(time: 10)
}
return
}
PhotoManager.shared.audioPlayFinish = { [weak self] in
guard let self = self else { return }
if self.music.lyricIsEmpty {
return
}
self.setPreciseContentOffset(x: startPointX, y: 0)
}
DispatchQueue.main.async {
guard let time = PhotoManager.shared.audioPlayer?.currentTime,
let duration = PhotoManager.shared.audioPlayer?.duration else {
return
}
let timeScale = CGFloat(time / duration)
let maxOffsetX = self.collectionView.contentSize.width - self.width + (self.width - 15) - startPointX
let timeOffsetX = maxOffsetX * timeScale + startPointX
self.setPreciseContentOffset(x: timeOffsetX, y: 0)
self.scrollLyric(time: duration)
}
}else {
if PhotoManager.shared.playMusic(filePath: audioPath, finished: { [weak self] in
guard let self = self else { return }
if self.music.lyricIsEmpty {
return
}
self.setPreciseContentOffset(x: startPointX, y: 0)
}) {
if music.lyricIsEmpty {
scrollLyric(time: 10)
return
}
if let time = PhotoManager.shared.audioPlayer?.duration {
scrollLyric(time: time)
}else if let time = music.time {
scrollLyric(time: time)
}else if let time = music.lyrics.last?.startTime {
scrollLyric(time: time + 5)
}
}
}
}
func scrollLyric(time: TimeInterval) {
playTimer?.cancel()
let startPointX = -(width - 15)
if !music.isSelected {
collectionView.setContentOffset(CGPoint(x: startPointX, y: 0), animated: false)
}
let maxOffsetX = collectionView.contentSize.width - width + (width - 15)
let duration: TimeInterval = 0.005
let marginX = (maxOffsetX - startPointX) / CGFloat(time * (1 / duration))
let playTimer = DispatchSource.makeTimerSource()
playTimer.schedule(deadline: .now(), repeating: .milliseconds(5), leeway: .milliseconds(0))
playTimer.setEventHandler(handler: { [weak self] in
guard let self = self else { return }
DispatchQueue.main.sync {
let offsetX = self.collectionView.contentOffset.x
if offsetX >= maxOffsetX {
if self.music.lyricIsEmpty {
self.setPreciseContentOffset(x: startPointX, y: 0)
}
return
}
self.setPreciseContentOffset(x: offsetX + marginX, y: 0)
}
})
playTimer.resume()
self.playTimer = playTimer
}
func setPreciseContentOffset(x: CGFloat, y: CGFloat) {
let point = CGPoint(x: x, y: y)
collectionView.bounds = CGRect(origin: point, size: collectionView.size)
}
func stopMusic() {
music.isSelected = false
if !music.audioURL.isFileURL {
PhotoManager.shared.suspendTask(music.audioURL)
}
PhotoManager.shared.stopPlayMusic()
resetStatus()
}
func resetStatus() {
isPlaying = false
hideLoading()
let visualEffect = UIBlurEffect.init(style: .light)
bgView.effect = visualEffect
musicIconView.tintColor = .white
songNameLb.textColor = .white
animationView.isHidden = true
animationView.stopAnimation()
collectionView.reloadData()
playTimer?.cancel()
collectionView.setContentOffset(.zero, animated: false)
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(bgView)
contentView.addSubview(shadeView)
contentView.addSubview(loadingView)
contentView.addSubview(animationView)
contentView.addSubview(songNameLb)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
bgView.frame = bounds
musicIconView.x = 15
musicIconView.y = 15
animationView.frame = CGRect(x: width - 60, y: 20, width: 20, height: 15)
songNameLb.x = musicIconView.frame.maxX + 10
songNameLb.width = animationView.x - 10 - songNameLb.x
songNameLb.height = 20
songNameLb.centerY = musicIconView.centerY
shadeView.frame = CGRect(
x: 0,
y: musicIconView.frame.maxY + 10,
width: width,
height: height - musicIconView.frame.maxY - 20
)
collectionView.frame = shadeView.bounds
maskLayer.frame = CGRect(x: 10, y: 0, width: shadeView.width - 20, height: shadeView.height)
loadingView.center = CGPoint(x: width * 0.5, y: height * 0.5)
}
deinit {
playTimer?.cancel()
}
}
extension VideoEditorMusicViewCell: UICollectionViewDataSource,
UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return music.lyrics.count
}
func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: "VideoEditorMusicLyricViewCellID",
for: indexPath
) as! VideoEditorMusicLyricViewCell
cell.lyricLb.textColor = isPlaying ? "#333333".color : .white
cell.lyric = music.lyrics[indexPath.item]
return cell
}
func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath
) -> CGSize {
let lyric = music.lyrics[indexPath.item]
let cellWidth = lyric.lyric.width(
ofFont: UIFont.mediumPingFang(ofSize: 16),
maxHeight: shadeView.height
)
return CGSize(width: cellWidth, height: shadeView.height)
}
}
|
mit
|
ce8356ae4285500ed500afecf6341a61
| 36.136111 | 119 | 0.586356 | 5.116341 | false | false | false | false |
jdarowski/RGSnackBar
|
RGSnackBar/Classes/RGMessageView.swift
|
1
|
1854
|
//
// RGMessageView.swift
// RGSnackBar
//
// Created by Jakub Darowski on 31/08/2017.
//
//
import UIKit
/**
* A generic message view. Should **not** be instantiated, but extended.
*
* Provides the basic variables and methods as well as some handy utility
* methods. Base for all potential message-displaying views.
*/
open class RGMessageView: UIView {
/// The message to be displayed in the view
open var message: RGMessage? {
didSet {
prepareForReuse()
if let msg = message {
layoutMessage(msg)
}
}
}
/**
* The main constructor.
*
* - Parameter frame: the desired frame of the message view
* - Parameter message: themessage to be displayed or nil
*/
public init(frame: CGRect = .zero, message msg: RGMessage?) {
message = msg
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// Prepare the view for displaying a new message
open func layoutMessage(_ message: RGMessage) {}
/**
* Apply styles. Should be called whenever style is changed or the view
* has been changed in any way.
*/
open func style() {}
/// Clear the view of any filled-in data
open func prepareForReuse() {}
/**
* A small utility method for disabling autoresizing masks for
* autolayout to work properly
*/
func disableTranslatingAutoresizing(_ view: UIView?) {
guard let actualView = view else {
return
}
actualView.translatesAutoresizingMaskIntoConstraints = false
for subview in subviews {
if subview.translatesAutoresizingMaskIntoConstraints {
disableTranslatingAutoresizing(subview)
}
}
}
}
|
mit
|
1a525143b8ef769047b7bd6fd30c0169
| 25.112676 | 75 | 0.613808 | 4.753846 | false | false | false | false |
srn214/Floral
|
Floral/Floral/Classes/Utils/UUID.swift
|
1
|
2185
|
//
// UUID.swift
// Floral
//
// Created by LDD on 2019/7/20.
// Copyright © 2019 文刂Rn. All rights reserved.
//
import UIKit
public enum UUIDStyle : Int {
/// 中划线分割 E56D8738-C2EB-4021-A249-D125AAFE7F57
case canonical
/// 中划线分割、大括号包裹 {E56D8738-C2EB-4021-A249-D125AAFE7F57}
case surroundingBraces
/// urn:uuid:123e4567-e89b-12d3-a456-426655440000
case urn
/// 一串字符串 E56D8738C2EB4021A249D125AAFE7F57
case noHyphens
/// 获取 UUID style 样式
///
/// - Returns: UUID style
public func next() -> UUIDStyle {
if let type = UUIDStyle(rawValue: self.rawValue + 1) {
return type
}
if let type = UUIDStyle(rawValue: 0) {
return type
}
return .canonical
}
/// UUID 字符串
public var text : String {
get {
switch(self) {
case .canonical:
return "Canonical"
case .surroundingBraces:
return "Surrounding Braces"
case .urn:
return "Uniform Resource Name (URN)"
case .noHyphens:
return "No hyphens"
}
}
}
/// UUID style 样式转换
///
/// - Parameter uuid: UUID
/// - Returns: 对应样式的UUID
public func uuidString(_ uuid : UUID) -> String {
switch(self) {
case .canonical:
return uuid.uuidString
case .surroundingBraces:
return "{\(uuid.uuidString)}"
case .urn:
return "urn:uuid:\(uuid.uuidString)"
case .noHyphens:
let uuidString = uuid.uuidString
let components = uuidString.components(separatedBy: "-")
let nohyphensString = components.joined()
return nohyphensString
}
}
}
extension UUIDStyle : CustomStringConvertible {
public var description: String {
return self.text
}
}
extension UUID {
public func uuidString(style: UUIDStyle) -> String {
return style.uuidString(self)
}
}
|
mit
|
275409ec6f819b68e2daa718e29b6b76
| 21.891304 | 68 | 0.538936 | 4.042226 | false | false | false | false |
tkremenek/swift
|
test/Migrator/optional_try_migration.swift
|
2
|
3123
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -c -swift-version 4 -primary-file %s -emit-migrated-file-path %t/optional_try_migration.result.swift
// RUN: %diff -u %S/optional_try_migration.swift.expected %t/optional_try_migration.result.swift
func fetchOptInt() throws -> Int? {
return 3
}
func fetchInt() throws -> Int {
return 3
}
func fetchAny() throws -> Any {
return 3
}
func testOnlyMigrateChangedBehavior() {
// No migration needed
let _ = try? fetchInt()
// Migration needed
let _ = try? fetchOptInt()
}
func testExplicitCasts() {
// No migration needed, because there's an explicit cast on the try already
let _ = (try? fetchOptInt()) as? Int
// Migration needed; the 'as? Int' is part of the sub-expression
let _ = try? fetchAny() as? Int
// No migration needed; the subexpression is non-optional so behavior has not changed
let _ = (try? fetchAny()) as? Int
// No migration needed, because there's an explicit cast on the try already
let _ = (try? fetchOptInt()) as! Int // expected-warning {{forced cast from 'Int??' to 'Int' only unwraps optionals; did you mean to use '!!'?}}
// No migration needed; the subexpression is non-optional
let _ = try? fetchAny() as! Int
// No migration needed; the subexpression is non-optional so behavior has not changed
let _ = (try? fetchAny()) as! Int
// Migration needed; the explicit cast is not directly on the try?
let _ = String(describing: try? fetchOptInt()) as Any
// No migration needed, because the try's subexpression is non-optional
let _ = String(describing: try? fetchInt()) as Any
}
func testOptionalChaining() {
struct Thing {
func fetchInt() throws -> Int { return 3 }
func fetchOptInt() throws -> Int { return 3 }
}
let thing = Thing()
let optThing: Thing? = Thing()
// Migration needed
let _ = try? optThing?.fetchInt()
// Migration needed
let _ = try? optThing?.fetchOptInt()
// No migration needed
let _ = try? optThing!.fetchOptInt()
// No migration needed, because of the explicit cast
let _ = (try? optThing?.fetchOptInt()) as? Int // expected-warning{{conditional downcast from 'Int?' to 'Int' does nothing}}
// Migration needed
let _ = try? thing.fetchInt()
// Migration needed
let _ = try? thing.fetchOptInt()
// No migration needed, because of the explicit cast
let _ = (try? thing.fetchOptInt()) as! Int // expected-warning {{forced cast from 'Int?' to 'Int' only unwraps optionals; did you mean to use '!'?}}
}
func testIfLet() {
// Migration needed
if let optionalX = try? fetchOptInt(),
let x = optionalX
{
print(x)
}
// Don't change 'try?'s that haven't changed behavior
if let x = try? fetchInt(),
let y = try? fetchInt() {
print(x, y)
}
}
func testCaseMatching() {
// Migration needed
if case let x?? = try? fetchOptInt() {
print(x)
}
// No migration needed
if case let x? = try? fetchInt() {
print(x)
}
}
|
apache-2.0
|
3188462e8d2b1ecca8f3b68a83b7056a
| 26.883929 | 152 | 0.629843 | 3.794654 | false | false | false | false |
GYLibrary/A_Y_T
|
GYVideo/Pods/EZPlayer/EZPlayer/EZPlayerFullScreenViewController.swift
|
1
|
3831
|
//
// EZFullScreenViewController.swift
// EZPlayer
//
// Created by yangjun zhu on 2016/12/28.
// Copyright © 2016年 yangjun zhu. All rights reserved.
//
import UIKit
open class EZPlayerFullScreenViewController: UIViewController {
weak var player: EZPlayer!
private var statusbarBackgroundView: UIView!
public var preferredlandscapeForPresentation = UIInterfaceOrientation.landscapeLeft
public var currentOrientation = UIDevice.current.orientation
// MARK: - Life cycle
deinit {
NotificationCenter.default.removeObserver(self)
}
override open func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.playerControlsHiddenDidChange(_:)), name: NSNotification.Name.EZPlayerControlsHiddenDidChange, object: nil)
self.view.backgroundColor = UIColor.black
self.statusbarBackgroundView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 20))
self.statusbarBackgroundView.backgroundColor = self.player.fullScreenStatusbarBackgroundColor
self.statusbarBackgroundView.autoresizingMask = [ .flexibleWidth,.flexibleLeftMargin,.flexibleRightMargin,.flexibleBottomMargin]
self.view.addSubview(self.statusbarBackgroundView)
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override open func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
// MARK: - Orientations
override open var shouldAutorotate : Bool {
return true
}
override open var supportedInterfaceOrientations : UIInterfaceOrientationMask {
switch self.player.fullScreenMode {
case .portrait:
return [.portrait]
case .landscape:
return [.landscapeLeft,.landscapeRight]
}
}
override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
self.currentOrientation = preferredlandscapeForPresentation == .landscapeLeft ? .landscapeRight : .landscapeLeft
switch self.player.fullScreenMode {
case .portrait:
self.currentOrientation = .portrait
return .portrait
case .landscape:
return self.preferredlandscapeForPresentation
}
}
// MARK: - status bar
private var statusBarHiddenAnimated = true
override open var prefersStatusBarHidden: Bool{
if self.statusBarHiddenAnimated {
UIView.animate(withDuration: ezAnimatedDuration, animations: {
self.statusbarBackgroundView.alpha = self.player.controlsHidden ? 0 : 1
}, completion: {finished in
})
}else{
self.statusbarBackgroundView.alpha = self.player.controlsHidden ? 0 : 1
}
return self.player.controlsHidden
}
override open var preferredStatusBarStyle: UIStatusBarStyle{
return self.player.fullScreenPreferredStatusBarStyle
}
// MARK: - notification
func playerControlsHiddenDidChange(_ notifiaction: Notification) {
self.statusBarHiddenAnimated = notifiaction.userInfo?[Notification.Key.EZPlayerControlsHiddenDidChangeByAnimatedKey] as? Bool ?? true
self.setNeedsStatusBarAppearanceUpdate()
}
override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.currentOrientation = UIDevice.current.orientation
}
}
|
mit
|
5105f0304a7e9c9c566e30679e7f8dd9
| 32.286957 | 185 | 0.706113 | 5.730539 | false | false | false | false |
GYLibrary/A_Y_T
|
GYVideo/Pods/BMPlayer/BMPlayer/Classes/BMPlayerManager.swift
|
1
|
1144
|
//
// BMPlayerManager.swift
// Pods
//
// Created by BrikerMan on 16/5/21.
//
//
import UIKit
import NVActivityIndicatorView
public let BMPlayerConf = BMPlayerManager.shared
public enum BMPlayerTopBarShowCase: Int {
case always = 0 /// 始终显示
case horizantalOnly = 1 /// 只在横屏界面显示
case none = 2 /// 不显示
}
open class BMPlayerManager {
/// 单例
open static let shared = BMPlayerManager()
/// 主题色
open var tintColor = UIColor.white
/// Loader样式
open var loaderType = NVActivityIndicatorType.ballRotateChase
/// 是否自动播放
open var shouldAutoPlay = true
open var topBarShowInCase = BMPlayerTopBarShowCase.always
/// 是否显示慢放和镜像按钮
open var slowAndMirror = false
/// 是否显示比例切换按钮
open var showScaleChangeButton = false
/// 是否打印log
open var allowLog = false
/**
打印log
- parameter info: log信息
*/
func log(_ info:String) {
if allowLog {
print(info)
}
}
}
|
mit
|
f7f1937d7d002c4fecd598d4540fe47d
| 18.433962 | 66 | 0.602913 | 4.007782 | false | false | false | false |
thehung111/visearch-widget-swift
|
ViSearchWidgets/ViSearchWidgets/Camera/Views/CameraView.swift
|
2
|
8519
|
import UIKit
import AVFoundation
/// Camera view with optional crop overlay
public class CameraView: UIView {
var session: AVCaptureSession!
var input: AVCaptureDeviceInput!
var device: AVCaptureDevice!
var imageOutput: AVCaptureStillImageOutput!
var preview: AVCaptureVideoPreviewLayer!
let cameraQueue = DispatchQueue(label: "com.visenze.CameraViewController.Queue")
let focusView = CropOverlay(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
public var currentPosition = CameraGlobals.shared.defaultCameraPosition
/// start camera capture session
public func startSession() {
#if (arch(i386) || arch(x86_64)) && os(iOS)
print("simulator is running. Disable camera session")
return
#endif
session = AVCaptureSession()
session.sessionPreset = AVCaptureSessionPresetPhoto
device = cameraWithPosition(position: currentPosition)
if let device = device , device.hasFlash {
do {
try device.lockForConfiguration()
// device.flashMode = .auto
device.flashMode = .off
device.unlockForConfiguration()
} catch _ {}
}
let outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
do {
input = try AVCaptureDeviceInput(device: device)
} catch let error as NSError {
input = nil
print("CameraView Error: \(error.localizedDescription)")
return
}
if session.canAddInput(input) {
session.addInput(input)
}
imageOutput = AVCaptureStillImageOutput()
imageOutput.outputSettings = outputSettings
session.addOutput(imageOutput)
cameraQueue.sync {
self.session.startRunning()
DispatchQueue.main.async() {
self.createPreview()
}
}
}
/// stop session
public func stopSession() {
cameraQueue.sync {
self.session?.stopRunning()
self.preview?.removeFromSuperlayer()
self.session = nil
self.input = nil
self.imageOutput = nil
self.preview = nil
self.device = nil
}
}
public override func layoutSubviews() {
super.layoutSubviews()
preview?.frame = bounds
}
public func configureFocus() {
if let gestureRecognizers = gestureRecognizers {
gestureRecognizers.forEach({ removeGestureRecognizer($0) })
}
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(focus(gesture:)))
addGestureRecognizer(tapGesture)
isUserInteractionEnabled = true
addSubview(focusView)
focusView.isHidden = true
let lines = focusView.horizontalLines + focusView.verticalLines + focusView.outerLines
lines.forEach { line in
line.alpha = 0
}
}
internal func focus(gesture: UITapGestureRecognizer) {
let point = gesture.location(in: self)
guard focusCamera(toPoint: point) else {
return
}
focusView.isHidden = false
focusView.center = point
focusView.alpha = 0
focusView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
bringSubview(toFront: focusView)
UIView.animateKeyframes(withDuration: 1.5, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.15, animations: { () -> Void in
self.focusView.alpha = 1
self.focusView.transform = CGAffineTransform.identity
})
UIView.addKeyframe(withRelativeStartTime: 0.80, relativeDuration: 0.20, animations: { () -> Void in
self.focusView.alpha = 0
self.focusView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
})
}, completion: { finished in
if finished {
self.focusView.isHidden = true
}
})
}
private func createPreview() {
preview = AVCaptureVideoPreviewLayer(session: session)
preview.videoGravity = AVLayerVideoGravityResizeAspectFill
preview.frame = bounds
layer.addSublayer(preview)
}
private func cameraWithPosition(position: AVCaptureDevicePosition) -> AVCaptureDevice? {
guard let devices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) as? [AVCaptureDevice] else {
return nil
}
return devices.filter { $0.position == position }.first
}
public func capturePhoto(completion: @escaping CameraShotCompletion) {
isUserInteractionEnabled = false
cameraQueue.sync {
let orientation = AVCaptureVideoOrientation(rawValue: UIDevice.current.orientation.rawValue)!
takePhoto(self.imageOutput, videoOrientation: orientation, cropSize: self.frame.size) { image in
DispatchQueue.main.async() {
self.isUserInteractionEnabled = true
completion(image)
}
}
}
}
public func focusCamera(toPoint: CGPoint) -> Bool {
guard let device = device, device.isFocusModeSupported(.continuousAutoFocus) else {
return false
}
do { try device.lockForConfiguration() } catch {
return false
}
// focus points are in the range of 0...1, not screen pixels
let focusPoint = CGPoint(x: toPoint.x / frame.width, y: toPoint.y / frame.height)
device.focusMode = AVCaptureFocusMode.continuousAutoFocus
device.exposurePointOfInterest = focusPoint
device.exposureMode = AVCaptureExposureMode.continuousAutoExposure
device.unlockForConfiguration()
return true
}
/// moving through different flash mode. We only allow on/off modes here
/// auto is disabled
public func cycleFlash() {
guard let device = device, device.hasFlash else {
return
}
do {
try device.lockForConfiguration()
if device.flashMode == .on {
device.flashMode = .off
}
// disable auto flash mode
// else if device.flashMode == .off {
// device.flashMode = .auto
// }
else {
device.flashMode = .on
}
device.unlockForConfiguration()
} catch _ { }
}
/// switch between front and back camera
public func swapCameraInput() {
guard let session = session, let input = input else {
return
}
session.beginConfiguration()
session.removeInput(input)
if input.device.position == AVCaptureDevicePosition.back {
currentPosition = AVCaptureDevicePosition.front
device = cameraWithPosition(position: currentPosition)
} else {
currentPosition = AVCaptureDevicePosition.back
device = cameraWithPosition(position: currentPosition)
}
guard let i = try? AVCaptureDeviceInput(device: device) else {
return
}
self.input = i
session.addInput(i)
session.commitConfiguration()
}
public func rotatePreview() {
guard preview != nil else {
return
}
switch UIApplication.shared.statusBarOrientation {
case .portrait:
preview?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
break
case .portraitUpsideDown:
preview?.connection.videoOrientation = AVCaptureVideoOrientation.portraitUpsideDown
break
case .landscapeRight:
preview?.connection.videoOrientation = AVCaptureVideoOrientation.landscapeRight
break
case .landscapeLeft:
preview?.connection.videoOrientation = AVCaptureVideoOrientation.landscapeLeft
break
default: break
}
}
}
|
mit
|
303b0063f07b9ad59af804c4fc3292b5
| 31.026316 | 117 | 0.580467 | 5.949022 | false | false | false | false |
domesticmouse/MovingCompass
|
MovingCompass/ViewController.swift
|
1
|
936
|
import UIKit
import GoogleMaps
class ViewController: UIViewController, GMSMapViewDelegate {
@IBOutlet var mapView: GMSMapView!
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
mapView.myLocationEnabled = true
mapView.settings.compassButton = true
mapView.settings.myLocationButton = true
}
// MARK: - GMSMapViewDelegate
func mapView(mapView: GMSMapView!, idleAtCameraPosition position: GMSCameraPosition!) {
label.text = "MapView idle"
}
func mapView(mapView: GMSMapView!, willMove gesture: Bool) {
label.text = "MapView willMove"
}
func mapView(mapView: GMSMapView!, didChangeCameraPosition position: GMSCameraPosition!) {
label.text = "MapView didChangeCameraPosition " +
"\(position.target.latitude),\(position.target.longitude) " +
"zoom: \(position.zoom) bearing: \(position.bearing)"
}
}
|
apache-2.0
|
026efdfbb351724eb1688369ac586413
| 27.363636 | 92 | 0.717949 | 4.751269 | false | false | false | false |
mitchellporter/SAInboxViewController
|
SAInboxViewController/SAInboxTransitioningContainerView.swift
|
1
|
4966
|
//
// SAInboxTransitioningContainerView.swift
// SAInboxViewController
//
// Created by Taiki Suzuki on 2015/08/15.
// Copyright (c) 2015年 Taiki Suzuki. All rights reserved.
//
import UIKit
class SAInboxTransitioningContainerView: UIView {
//MARK: - Inner Structs
private struct ImageInformation {
enum Position {
case Below, Above, Target
}
let tag: Int
let initialOrigin: CGPoint
let height: CGFloat
let isTarget: Bool
let position: Position
}
//MARK: - Instance Properties
private var imageInformations: [ImageInformation] = []
private(set) var targetPosition: CGPoint?
private(set) var targetHeight: CGFloat?
private(set) var headerImageView = UIImageView()
var headerImage: UIImage? {
set {
headerImageView.image = newValue
headerImageView.frame.size = CGSize(width: frame.size.width, height: 64)
addSubview(headerImageView)
}
get {
return headerImageView.image
}
}
var headerViewOrigin: CGPoint = CGPointZero
init() {
super.init(frame: CGRectZero)
backgroundColor = .clearColor()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - Internal Methods
extension SAInboxTransitioningContainerView {
func setupContainer(targetCell: UITableViewCell, cells: [UITableViewCell], superview: UIView) {
var imageTag: Int = 10001
var detectTarget = false
for cell in cells {
if let point = cell.superview?.convertPoint(cell.frame.origin, toView: superview) {
let isTarget: Bool
if targetCell == cell {
isTarget = true
detectTarget = true
targetPosition = point
targetHeight = CGRectGetHeight(cell.frame)
} else {
isTarget = false
}
let position: ImageInformation.Position
if isTarget {
position = .Target
} else if !detectTarget {
position = .Below
} else {
position = .Above
}
let imageView = UIImageView(frame: cell.bounds)
cell.selectionStyle = .None
imageView.image = cell.screenshotImage()
cell.selectionStyle = .Default
imageView.tag = imageTag
imageView.frame.origin = point
addSubview(imageView)
imageInformations += [ImageInformation(tag: imageTag++, initialOrigin: point, height: CGRectGetHeight(cell.frame), isTarget: isTarget, position: position)]
}
}
}
func resetContainer() {
if let views = subviews as? [UIView] {
for view in views { view.removeFromSuperview() }
}
imageInformations.removeAll(keepCapacity: false)
targetPosition = nil
}
func open() {
if let targetPosition = targetPosition {
for imageInformation in imageInformations {
let view = viewWithTag(imageInformation.tag)
if imageInformation.isTarget {
view?.alpha = 0
}
if imageInformation.initialOrigin.y <= targetPosition.y {
view?.frame.origin.y = imageInformation.initialOrigin.y - targetPosition.y
} else {
view?.frame.origin.y = frame.size.height + (imageInformation.initialOrigin.y - targetPosition.y) - imageInformation.height
}
}
}
}
func close() {
for imageInformation in imageInformations {
let view = viewWithTag(imageInformation.tag)
if imageInformation.isTarget {
view?.alpha = 1
}
view?.frame.origin.y = imageInformation.initialOrigin.y
}
}
func upperMoveToValue(value: CGFloat) {
for imageInformation in imageInformations {
if let targetPosition = targetPosition where targetPosition.y >= imageInformation.initialOrigin.y {
viewWithTag(imageInformation.tag)?.frame.origin.y = imageInformation.initialOrigin.y - targetPosition.y + value
}
}
}
func lowerMoveToValue(value: CGFloat) {
for imageInformation in imageInformations {
if let targetPosition = targetPosition where targetPosition.y < imageInformation.initialOrigin.y {
viewWithTag(imageInformation.tag)?.frame.origin.y = frame.size.height + (imageInformation.initialOrigin.y - targetPosition.y) - imageInformation.height - value
}
}
}
}
|
mit
|
af4e8e782c2e400e5bb0297efb3f2461
| 33.713287 | 175 | 0.571716 | 5.32618 | false | false | false | false |
xiandan/diaobaoweibo-swift
|
XWeibo-swift/Classes/Model/Profile/Controller/XProfileController.swift
|
1
|
3221
|
//
// XProfileController.swift
// XWeibo-swift
//
// Created by Apple on 15/10/26.
// Copyright © 2015年 Apple. All rights reserved.
//
import UIKit
class XProfileController: XBaseController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
apache-2.0
|
c23767f65d999c41813e1dedec0b7968
| 32.873684 | 157 | 0.685519 | 5.52921 | false | false | false | false |
zzeleznick/piazza-clone
|
Pizzazz/Pizzazz/ViewController.swift
|
1
|
1604
|
//
// ViewController.swift
// Pizzazz
//
// Created by Zach Zeleznick on 9/29/16.
// Copyright © 2016 zzeleznick. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var w: CGFloat!
var h: CGFloat!
override func viewDidLoad() {
super.viewDidLoad()
view = UIView(frame: UIScreen.main.bounds)
view.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
w = view.bounds.size.width
h = view.bounds.size.height
}
func addToolbar() {
let toolbar = UIToolbar()
toolbar.barTintColor = UIColor(white: 0.95, alpha: 1.0)
let moreButton = UIButton()
moreButton.setBackgroundImage(UIImage(named: "MoreIcon"), for: UIControlState())
moreButton.frame = CGRect(x: 0, y: 0, width: 30, height: 10)
let accountButton = UIButton()
accountButton.setTitle("Account", for: UIControlState())
accountButton.titleLabel?.font = UIFont(name: "Helvetica", size: 11)
accountButton.setTitleColor(UIColor(rgb: 0x3e7aab), for: UIControlState())
accountButton.frame = CGRect(x: 0, y: 0, width: 50, height: 30)
let item1 = UIBarButtonItem(customView: moreButton)
let item2 = UIBarButtonItem(customView: accountButton)
let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
target: self, action: nil)
toolbar.setItems([item1, spacer, item2], animated: true)
view.addUIElement(toolbar, frame: CGRect(x: 0, y: h-40, width: w, height: 40))
}
}
|
mit
|
1427c1d0ac6db6a06b93182b6e4244eb
| 33.847826 | 88 | 0.625078 | 4.068528 | false | false | false | false |
ayanna92/ayannacolden-programmeerproject
|
programmeerproject/UserMessageCell.swift
|
1
|
3834
|
//
// userMessageCell.swift
// programmeerproject
//
// Created by Ayanna Colden on 17/01/2017.
// Copyright © 2017 Ayanna Colden. All rights reserved.
//
import UIKit
import Firebase
// Source: https://www.letsbuildthatapp.com/course_video?id=402
class UserMessageCell: UITableViewCell {
var message: Message? {
didSet {
setupNameAndProfileImage()
detailTextLabel?.text = message?.text
if let seconds = message?.timestamp?.doubleValue {
let timestampDate = Date(timeIntervalSince1970: seconds)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm:ss a"
timeLabel.text = dateFormatter.string(from: timestampDate)
}
}
}
// MARK: Layout user messages.
fileprivate func setupNameAndProfileImage() {
if let id = message?.chatPartnerId() {
let ref = FIRDatabase.database().reference().child("users").child(id)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
self.textLabel?.text = dictionary["fullname"] as? String
if let profileImageUrl = dictionary["urlToImage"] as? String {
self.profileImageView.loadImageUsingCacheWithUrlString(profileImageUrl)
}
}
}, withCancel: nil)
}
}
override func layoutSubviews() {
super.layoutSubviews()
textLabel?.frame = CGRect(x: 64, y: textLabel!.frame.origin.y - 2, width: textLabel!.frame.width, height: textLabel!.frame.height)
detailTextLabel?.frame = CGRect(x: 64, y: detailTextLabel!.frame.origin.y + 2, width: detailTextLabel!.frame.width, height: detailTextLabel!.frame.height)
}
let profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.cornerRadius = 24
imageView.layer.masksToBounds = true
imageView.contentMode = .scaleAspectFill
return imageView
}()
let timeLabel: UILabel = {
let label = UILabel()
// label.text = "HH:MM:SS"
label.font = UIFont.systemFont(ofSize: 13)
label.textColor = UIColor.darkGray
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
addSubview(profileImageView)
addSubview(timeLabel)
//ios 9 constraint anchors
//need x,y,width,height anchors
profileImageView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true
profileImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 48).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 48).isActive = true
//need x,y,width,height anchors
timeLabel.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
timeLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 18).isActive = true
timeLabel.widthAnchor.constraint(equalToConstant: 100).isActive = true
timeLabel.heightAnchor.constraint(equalTo: (textLabel?.heightAnchor)!).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
apache-2.0
|
20f23a587321d80fc5fb7fc25844fc0e
| 35.855769 | 162 | 0.62275 | 5.272352 | false | false | false | false |
oliverbarreto/PersonalFavs
|
PersonalFavs/PersonalFavs/AppDelegate.swift
|
1
|
7753
|
//
// AppDelegate.swift
// PersonalFavs
//
// Created by David Oliver Barreto Rodríguez on 22/5/17.
// Copyright © 2017 David Oliver Barreto Rodríguez. All rights reserved.
//
import UIKit
import CoreData
import Contacts
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// Main Window
var window: UIWindow?
// Register iOS Permision for Contacts Framework
var contactStore = CNContactStore()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Checks for first launch
let firstLaunchObserver = FirstLaunchObserver()
if firstLaunchObserver.isFirstLaunch {
// Load pre-deefined model objects
DataStoreManager.shared.initWithDummyValues()
} else {
// Unarchive from disk
DataStoreManager.shared.loadFavFeeds()
DataStoreManager.shared.unarchiveModel()
}
// Manually set the window to later put the initial UICollectionVC
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
// Initialize basic Layout for the cells and create the UICollectionVC
let layout = UICollectionViewFlowLayout()
window?.rootViewController = HomeController(collectionViewLayout: layout)
//window?.rootViewController = UINavigationController(rootViewController: HomeController(collectionViewLayout: layout))
return true
}
// MARK: - Custom Methods
class func sharedDelegate() -> AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
func checkAccessStatus(completionHandler: @escaping (_ accessGranted: Bool) -> Void) {
let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
switch authorizationStatus {
case .authorized:
completionHandler(true)
case .denied, .notDetermined:
self.contactStore.requestAccess(for: CNEntityType.contacts, completionHandler: { (access, accessError) -> Void in
if access {
completionHandler(access)
} else {
//print("access denied")
if authorizationStatus == CNAuthorizationStatus.denied {
DispatchQueue.main.async(execute: {
let message = "\(accessError!.localizedDescription)\n\nPlease allow the app to access your contacts through the Settings."
self.showAlertMessage(message: message)
})
}
}
})
default:
completionHandler(false)
}
}
func showAlertMessage(message: String) {
let alertController = UIAlertController(title: "PersonalFavs", message: message, preferredStyle: UIAlertControllerStyle.alert)
let dismissAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (action) -> Void in
}
alertController.addAction(dismissAction)
let pushedViewControllers = (self.window?.rootViewController as! UINavigationController).viewControllers
let presentedViewController = pushedViewControllers[pushedViewControllers.count - 1]
presentedViewController.present(alertController, animated: true, completion: nil)
}
// MARK: - AppDelegate Methods
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: "PersonalFavs")
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)")
}
}
}
}
|
apache-2.0
|
b6e5670782d33301d5b1d2944c35904f
| 42.296089 | 285 | 0.655355 | 6.064163 | false | false | false | false |
ZhaoBingDong/EasySwifty
|
EasySwifty/Classes/Easy+TableView.swift
|
1
|
3836
|
//
// Easy+TableView.swift
// EaseSwifty
//
// Created by 董招兵 on 2017/8/6.
// Copyright © 2017年 大兵布莱恩特. All rights reserved.
//
import Foundation
import UIKit
public extension UITableView {
func insertRows(at indexPaths: [IndexPath]) {
if #available(iOS 11.0, *) {
self.performBatchUpdates({ [weak self] in
self?.insertRows(at: indexPaths, with: .none)
}) { (true) in
}
} else {
self.beginUpdates()
self.insertRows(at: indexPaths, with: .none)
self.endUpdates()
}
}
///找UITableViewCell 的重用
@discardableResult
func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath) -> T {
guard let cell = self.dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)")
}
return cell
}
///找UITableViewHeaderFooterView 的重用
@discardableResult
func dequeueReusableHeaderFooter<T: UITableViewHeaderFooterView>() -> T {
guard let view = dequeueReusableHeaderFooterView(withIdentifier: T.reuseIdentifier) as? T else {
fatalError("Could not dequeue HeaderFooter with identifier: \(T.reuseIdentifier)")
}
return view
}
///找UITableViewHeaderFooterView 的重用
@discardableResult
func dequeueReusableHeaderFooter<T: UITableViewHeaderFooterView>(_ reuseIdentifier : String) -> T {
guard let view = dequeueReusableHeaderFooterView(withIdentifier: reuseIdentifier) as? T else {
fatalError("Could not dequeue HeaderFooter with identifier: \(reuseIdentifier)")
}
return view
}
/// 注册cell 通过class 或者nib
func registerCell<T: UITableViewCell >(_ t : T.Type) {
if let xib = t.xib {
register(xib, forCellReuseIdentifier: t.reuseIdentifier)
} else {
register(t, forCellReuseIdentifier: t.reuseIdentifier)
}
}
/// 通过xib 或者 class 注册header footerview
func registerHeaderFooter<T : UITableViewHeaderFooterView>(_ t : T.Type) {
if let xib = t.xib {
register(xib, forHeaderFooterViewReuseIdentifier: t.reuseIdentifier)
} else {
register(t, forHeaderFooterViewReuseIdentifier: t.reuseIdentifier)
}
}
/// 通过 class 注册header footerview 并制定任意标识符
func registerHeaderFooter<T : UITableViewHeaderFooterView>(_ t : T.Type,reuseIdentifier : String) {
register(t, forHeaderFooterViewReuseIdentifier:reuseIdentifier)
}
}
/// 添加上拉下拉刷新的
protocol MJTableViewRefreshable where Self : UIViewController {
var tableView : UITableView { get set }
var pageNo : Int { get set}
func refreshingHandler(_ page : Int) //刷新后
}
//extension MJTableViewRefreshable {
//
// /// 默认实现 下拉刷新
// func addHeaderRefresh() {
// self.tableView.mj_header = MiaoTuHeader(refreshingBlock: { [weak self] in
// self?.pageNo = 1
// self?.refreshingHandler(self?.pageNo ?? 1)
// })
// }
//
// /// 默认实现 上拉加载更多
// func addFooterRefresh() {
// self.tableView.mj_footer = MiaoTuFooter(refreshingBlock: { [weak self] in
// self?.pageNo += 1
// self?.refreshingHandler(self?.pageNo ?? 1)
// })
// }
//
// func endRefresh() {
// if self.tableView.mj_header != nil {
// self.tableView.mj_header.endRefreshing()
// }
// if self.tableView.mj_footer != nil {
// self.tableView.mj_footer.endRefreshing()
// }
// }
//}
|
apache-2.0
|
02199b3dd59796f479212a2481afb44b
| 31.307018 | 113 | 0.615802 | 4.609512 | false | false | false | false |
haawa799/Metal-Flaps
|
SimpleMetal/Shaders related/Vertex.swift
|
1
|
1270
|
//
// Vertex.swift
// Triangle
//
// Created by Andrew K. on 6/24/14.
// Copyright (c) 2014 Andrew Kharchyshyn. All rights reserved.
//
import UIKit
@objc public class Vertex: NSObject
{
@objc public var x,y,z,u,v,nX,nY,nZ: Float
init(x:Float, y:Float, z:Float, u:Float ,v:Float ,nX:Float ,nY:Float ,nZ:Float)
{
self.x = x
self.y = y
self.z = z
self.u = u
self.v = v
self.nX = nX
self.nY = nY
self.nZ = nZ
super.init()
}
init(text: String)
{
let list = text.components(separatedBy: " ") as [NSString]
var counter = 0
self.x = (list[counter]).floatValue
counter += 1
self.y = (list[counter]).floatValue
counter += 1
self.z = (list[counter]).floatValue
counter += 1
self.u = (list[counter]).floatValue
counter += 1
self.v = (list[counter]).floatValue
counter += 1
self.nX = (list[counter]).floatValue
counter += 1
self.nY = (list[counter]).floatValue
counter += 1
self.nZ = (list[counter]).floatValue
counter += 1
super.init()
}
}
|
mit
|
ab19fa31cd14b0b61163bbb86369967d
| 20.525424 | 83 | 0.494488 | 3.638968 | false | false | false | false |
jakehirzel/swift-tip-calculator
|
CheckPlease WatchKit App Extension/InterfaceController.swift
|
1
|
2682
|
//
// InterfaceController.swift
// CheckPlease WatchKit App Extension
//
// Created by Jake Hirzel on 7/3/16.
// Copyright © 2016 Jake Hirzel. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
// MARK: Properties
@IBOutlet var totalBillPicker: WKInterfacePicker!
@IBOutlet var percentOne: WKInterfaceLabel!
@IBOutlet var percentTwo: WKInterfaceLabel!
@IBOutlet var percentThree: WKInterfaceLabel!
// Create instance of TipCalculator class
let tipCalculatorInstance = TipCalculator()
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
// Populate array of total amounts
tipCalculatorInstance.mealTotalArray = tipCalculatorInstance.createMealTotalArray()
// Map total amounts to the pickerItems array
let pickerItems: [WKPickerItem] = tipCalculatorInstance.mealTotalArray.map {
let pickerItem = WKPickerItem()
pickerItem.title = String(format: "$%.2f", $0)
return pickerItem
}
// Apply values to the picker
totalBillPicker.setItems(pickerItems)
// Set picker to $20
totalBillPicker.setSelectedItemIndex(40)
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
// Give the picker focus
totalBillPicker.focus()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
// MARK: Actions
@IBAction func pickerAction(_ value: Int) {
// Get displayed picker value
let currentMealValue = tipCalculatorInstance.mealTotalArray[value]
// Run the calculator
let tipResults = tipCalculatorInstance.tipCalculator(currentMealValue)
// Convert resulting floats to $0.00 format
let formattedTipOne = String(format: "15%% - $%.2f", tipResults.tipOne)
let formattedTipTwo = String(format: "18%% - $%.2f", tipResults.tipTwo)
let formattedTipThree = String(format: "20%% - $%.2f", tipResults.tipThree)
// Set tips to labels
percentOne.setText("\(formattedTipOne)")
percentTwo.setText("\(formattedTipTwo)")
percentThree.setText("\(formattedTipThree)")
// Add whimsical haptic feedback
WKInterfaceDevice.current().play(.directionDown)
}
}
|
mit
|
5ac4bd25a7119261fc03a092dbd0ef5a
| 30.174419 | 91 | 0.644909 | 5.011215 | false | false | false | false |
simplymadeapps/SMASaveSystem
|
Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CTR.swift
|
3
|
1259
|
//
// CTR.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 08/03/16.
// Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
//
// Counter (CTR)
//
struct CTRModeWorker: BlockModeWorker {
typealias Element = Array<UInt8>
let cipherOperation: CipherOperationOnBlock
private let iv: Element
private var counter: UInt = 0
init(iv: Array<UInt8>, cipherOperation: CipherOperationOnBlock) {
self.iv = iv
self.cipherOperation = cipherOperation
}
mutating func encrypt(plaintext: Array<UInt8>) -> Array<UInt8> {
let nonce = buildNonce(iv, counter: UInt64(counter))
counter = counter + 1
guard let ciphertext = cipherOperation(block: nonce) else {
return plaintext
}
return xor(plaintext, ciphertext)
}
mutating func decrypt(ciphertext: Array<UInt8>) -> Array<UInt8> {
return encrypt(ciphertext)
}
}
private func buildNonce(iv: Array<UInt8>, counter: UInt64) -> Array<UInt8> {
let noncePartLen = AES.blockSize / 2
let noncePrefix = Array(iv[0..<noncePartLen])
let nonceSuffix = Array(iv[noncePartLen..<iv.count])
let c = UInt64.withBytes(nonceSuffix) + counter
return noncePrefix + arrayOfBytes(c)
}
|
mit
|
c39ddc61399a4dfb314dcc2167914b83
| 26.955556 | 76 | 0.666137 | 4.058065 | false | false | false | false |
jboullianne/EndlessTunes
|
EndlessSoundFeed/ETDataManager.swift
|
1
|
2117
|
//
// ETDataManager.swift
// EndlessSoundFeed
//
// Created by Jean-Marc Boullianne on 7/18/17.
// Copyright © 2017 Jean-Marc Boullianne. All rights reserved.
//
import Foundation
class ETDataManager {
static let sharedInstance = ETDataManager()
//Recently Played Key Constant
let RECENTS_KEY = "RecentlyPlayed"
let MAX_RECENTS_SIZE = 12
var recentsDelegate:ETDataManagerRecentsDelagate?
var rpInfo:[[String]]
var rpImages:[UIImage?]
private init() {
rpInfo = []
rpImages = [UIImage?](repeating: nil, count: self.MAX_RECENTS_SIZE)
retrieveRecentlyPlayed()
}
//Load Recently Played Details From User Defaults
func retrieveRecentlyPlayed() {
if let temp = UserDefaults.standard.array(forKey: self.RECENTS_KEY) {
if let recents = temp as? [[String]] {
self.rpInfo = recents
}
}
}
//Add To Recently Played and Queue Synchronization to User Defaults
func addToRecents(track: Track) {
//Add Recent To Recents List
rpInfo.insert([track.title, track.sourceString, track.thumbnailURL], at: 0)
shiftRecents()
UserDefaults.standard.setValue(rpInfo, forKey: self.RECENTS_KEY)
recentsDelegate?.newRecentsReceived()
}
//Shift Images and Removes Excess Recents
func shiftRecents() {
self.rpImages.insert(nil, at: 0)
//Clear Old Recents out if list is too long
if rpInfo.count > self.MAX_RECENTS_SIZE {
rpInfo.removeLast()
rpImages.removeLast()
}
}
}
extension ETDataManager: ManagerDataPurger {
func purgeData() {
//Clear User Defaults For Manager
UserDefaults.standard.set(nil, forKey: self.RECENTS_KEY)
self.rpImages = [UIImage?](repeating: nil, count: self.MAX_RECENTS_SIZE)
self.rpInfo = []
}
}
protocol ETDataManagerRecentsDelagate {
func newRecentsReceived()
}
protocol ManagerDataPurger {
func purgeData()
}
|
gpl-3.0
|
ea36a77464cc9dcb16c8f7cec2c705c7
| 23.894118 | 83 | 0.617202 | 4.309572 | false | false | false | false |
Johennes/firefox-ios
|
Utils/ExtensionUtils.swift
|
1
|
2187
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import MobileCoreServices
public struct ExtensionUtils {
/// Look through the extensionContext for a url and title. Walks over all inputItems and then over all the attachments.
/// Has a completionHandler because ultimately an XPC call to the sharing application is done.
/// We can always extract a URL and sometimes a title. The favicon is currently just a placeholder, but
/// future code can possibly interact with a web page to find a proper icon.
public static func extractSharedItemFromExtensionContext(extensionContext: NSExtensionContext?, completionHandler: (ShareItem?, NSError!) -> Void) {
guard let extensionContext = extensionContext,
let inputItems = extensionContext.inputItems as? [NSExtensionItem] else {
completionHandler(nil, nil)
return
}
for inputItem in inputItems {
guard let attachments = inputItem.attachments as? [NSItemProvider] else { continue }
for attachment in attachments {
if attachment.hasItemConformingToTypeIdentifier(kUTTypeURL as String) {
attachment.loadItemForTypeIdentifier(kUTTypeURL as String, options: nil) { obj, err in
guard err == nil else {
completionHandler(nil, err)
return
}
guard let url = obj as? NSURL else {
completionHandler(nil, NSError(domain: "org.mozilla.fennec", code: 999, userInfo: ["Problem": "Non-URL result."]))
return
}
let title = inputItem.attributedContentText?.string
completionHandler(ShareItem(url: url.absoluteString!, title: title, favicon: nil), nil)
}
return
}
}
}
completionHandler(nil, nil)
}
}
|
mpl-2.0
|
7f0be6a40db53b66227526133f943176
| 45.531915 | 152 | 0.603109 | 5.651163 | false | false | false | false |
arvedviehweger/swift
|
test/Serialization/Recovery/typedefs.swift
|
1
|
8584
|
// RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swift-frontend -emit-module -o %t -module-name Lib -I %S/Inputs/custom-modules %s
// RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules | %FileCheck %s
// RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -enable-experimental-deserialization-recovery > %t.txt
// RUN: %FileCheck -check-prefix CHECK-RECOVERY %s < %t.txt
// RUN: %FileCheck -check-prefix CHECK-RECOVERY-NEGATIVE %s < %t.txt
// RUN: %target-swift-frontend -typecheck -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST -enable-experimental-deserialization-recovery -DVERIFY %s -verify
// RUN: %target-swift-frontend -emit-silgen -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST -enable-experimental-deserialization-recovery %s | %FileCheck -check-prefix CHECK-SIL %s
#if TEST
import Typedefs
import Lib
// CHECK-SIL-LABEL: sil hidden @_T08typedefs11testSymbolsyyF
func testSymbols() {
// Check that the symbols are not using 'Bool'.
// CHECK-SIL: function_ref @_T03Lib1xs5Int32Vfau
_ = Lib.x
// CHECK-SIL: function_ref @_T03Lib9usesAssocs5Int32VSgfau
_ = Lib.usesAssoc
} // CHECK-SIL: end sil function '_T08typedefs11testSymbolsyyF'
#if VERIFY
let _: String = useAssoc(ImportedType.self) // expected-error {{cannot convert call result type '_.Assoc?' to expected type 'String'}}
let _: Bool? = useAssoc(ImportedType.self) // expected-error {{cannot convert value of type 'Int32?' to specified type 'Bool?'}}
let _: Int32? = useAssoc(ImportedType.self)
let _: String = useAssoc(AnotherType.self) // expected-error {{cannot convert call result type '_.Assoc?' to expected type 'String'}}
let _: Bool? = useAssoc(AnotherType.self) // expected-error {{cannot convert value of type 'AnotherType.Assoc?' (aka 'Optional<Int32>') to specified type 'Bool?'}}
let _: Int32? = useAssoc(AnotherType.self)
let _ = wrapped // expected-error {{use of unresolved identifier 'wrapped'}}
let _ = unwrapped // okay
_ = usesWrapped(nil) // expected-error {{use of unresolved identifier 'usesWrapped'}}
_ = usesUnwrapped(nil) // expected-error {{nil is not compatible with expected argument type 'Int32'}}
public class UserSub: User {
override init() {}
}
// FIXME: Bad error message; really it's that the convenience init hasn't been
// inherited.
_ = UserSub(conveniently: 0) // expected-error {{argument passed to call that takes no arguments}}
public class UserConvenienceSub: UserConvenience {
override init() {}
}
_ = UserConvenienceSub(conveniently: 0)
#endif // VERIFY
#else // TEST
import Typedefs
// CHECK-LABEL: class User {
// CHECK-RECOVERY-LABEL: class User {
open class User {
// CHECK: var unwrappedProp: UnwrappedInt?
// CHECK-RECOVERY: var unwrappedProp: Int32?
public var unwrappedProp: UnwrappedInt?
// CHECK: var wrappedProp: WrappedInt?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedProp:
public var wrappedProp: WrappedInt?
// CHECK: func returnsUnwrappedMethod() -> UnwrappedInt
// CHECK-RECOVERY: func returnsUnwrappedMethod() -> Int32
public func returnsUnwrappedMethod() -> UnwrappedInt { fatalError() }
// CHECK: func returnsWrappedMethod() -> WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: func returnsWrappedMethod(
public func returnsWrappedMethod() -> WrappedInt { fatalError() }
// CHECK: subscript(_: WrappedInt) -> () { get }
// CHECK-RECOVERY-NEGATIVE-NOT: subscript(
public subscript(_: WrappedInt) -> () { return () }
// CHECK: init()
// CHECK-RECOVERY: init()
public init() {}
// CHECK: init(wrapped: WrappedInt)
// CHECK-RECOVERY-NEGATIVE-NOT: init(wrapped:
public init(wrapped: WrappedInt) {}
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
public convenience init(conveniently: Int) { self.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-LABEL: class UserConvenience
// CHECK-RECOVERY-LABEL: class UserConvenience
open class UserConvenience {
// CHECK: init()
// CHECK-RECOVERY: init()
public init() {}
// CHECK: convenience init(wrapped: WrappedInt)
// CHECK-RECOVERY-NEGATIVE-NOT: init(wrapped:
public convenience init(wrapped: WrappedInt) { self.init() }
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
public convenience init(conveniently: Int) { self.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-DAG: let x: MysteryTypedef
// CHECK-RECOVERY-DAG: let x: Int32
public let x: MysteryTypedef = 0
public protocol HasAssoc {
associatedtype Assoc
}
extension ImportedType: HasAssoc {}
public struct AnotherType: HasAssoc {
public typealias Assoc = MysteryTypedef
}
public func useAssoc<T: HasAssoc>(_: T.Type) -> T.Assoc? { return nil }
// CHECK-DAG: let usesAssoc: ImportedType.Assoc?
// CHECK-RECOVERY-DAG: let usesAssoc: Int32?
public let usesAssoc = useAssoc(ImportedType.self)
// CHECK-DAG: let usesAssoc2: AnotherType.Assoc?
// CHECK-RECOVERY-DAG: let usesAssoc2: AnotherType.Assoc?
public let usesAssoc2 = useAssoc(AnotherType.self)
// CHECK-DAG: let wrapped: WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: let wrapped:
public let wrapped = WrappedInt(0)
// CHECK-DAG: let unwrapped: UnwrappedInt
// CHECK-RECOVERY-DAG: let unwrapped: Int32
public let unwrapped: UnwrappedInt = 0
// CHECK-DAG: let wrappedMetatype: WrappedInt.Type
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedMetatype:
public let wrappedMetatype = WrappedInt.self
// CHECK-DAG: let wrappedOptional: WrappedInt?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedOptional:
public let wrappedOptional: WrappedInt? = nil
// CHECK-DAG: let wrappedIUO: WrappedInt!
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedIUO:
public let wrappedIUO: WrappedInt! = nil
// CHECK-DAG: let wrappedArray: [WrappedInt]
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedArray:
public let wrappedArray: [WrappedInt] = []
// CHECK-DAG: let wrappedDictionary: [Int : WrappedInt]
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedDictionary:
public let wrappedDictionary: [Int: WrappedInt] = [:]
// CHECK-DAG: let wrappedTuple: (WrappedInt, Int)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedTuple:
public let wrappedTuple: (WrappedInt, Int)? = nil
// CHECK-DAG: let wrappedTuple2: (Int, WrappedInt)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedTuple2:
public let wrappedTuple2: (Int, WrappedInt)? = nil
// CHECK-DAG: let wrappedClosure: ((WrappedInt) -> Void)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosure:
public let wrappedClosure: ((WrappedInt) -> Void)? = nil
// CHECK-DAG: let wrappedClosure2: (() -> WrappedInt)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosure2:
public let wrappedClosure2: (() -> WrappedInt)? = nil
// CHECK-DAG: let wrappedClosure3: ((Int, WrappedInt) -> Void)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosure3:
public let wrappedClosure3: ((Int, WrappedInt) -> Void)? = nil
// CHECK-DAG: let wrappedClosureInout: ((inout WrappedInt) -> Void)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosureInout:
public let wrappedClosureInout: ((inout WrappedInt) -> Void)? = nil
// CHECK-DAG: var wrappedFirst: WrappedInt?
// CHECK-DAG: var normalSecond: Int?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedFirst:
// CHECK-RECOVERY-DAG: var normalSecond: Int?
public var wrappedFirst: WrappedInt?, normalSecond: Int?
// CHECK-DAG: var normalFirst: Int?
// CHECK-DAG: var wrappedSecond: WrappedInt?
// CHECK-RECOVERY-DAG: var normalFirst: Int?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedSecond:
public var normalFirst: Int?, wrappedSecond: WrappedInt?
// CHECK-DAG: var wrappedThird: WrappedInt?
// CHECK-DAG: var wrappedFourth: WrappedInt?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedThird:
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedFourth:
public var wrappedThird, wrappedFourth: WrappedInt?
// CHECK-DAG: func usesWrapped(_ wrapped: WrappedInt)
// CHECK-RECOVERY-NEGATIVE-NOT: func usesWrapped(
public func usesWrapped(_ wrapped: WrappedInt) {}
// CHECK-DAG: func usesUnwrapped(_ unwrapped: UnwrappedInt)
// CHECK-RECOVERY-DAG: func usesUnwrapped(_ unwrapped: Int32)
public func usesUnwrapped(_ unwrapped: UnwrappedInt) {}
// CHECK-DAG: func returnsWrapped() -> WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: func returnsWrapped(
public func returnsWrapped() -> WrappedInt { fatalError() }
// CHECK-DAG: func returnsWrappedGeneric<T>(_: T.Type) -> WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: func returnsWrappedGeneric<
public func returnsWrappedGeneric<T>(_: T.Type) -> WrappedInt { fatalError() }
#endif // TEST
|
apache-2.0
|
ae61eb18ec9ecea762071ad21e2cc1d2
| 39.682464 | 184 | 0.729963 | 3.898274 | false | false | false | false |
colemancda/XcodeServerSDK
|
XcodeServerSDK/Server Entities/SourceControlBlueprint.swift
|
1
|
9635
|
//
// SourceControlBlueprint.swift
// Buildasaur
//
// Created by Honza Dvorsky on 11/01/2015.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
extension String {
public var base64Encoded: String? {
let data = dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
return data?.base64EncodedStringWithOptions(.EncodingEndLineWithLineFeed)
}
}
public class SourceControlBlueprint : XcodeServerEntity {
public let branch: String
public let projectWCCIdentifier: String
public let wCCName: String
public let projectName: String
public let projectURL: String
public let projectPath: String
public let commitSHA: String?
public let privateSSHKey: String?
public let publicSSHKey: String?
public let sshPassphrase: String?
public var certificateFingerprint: String? = nil
public required init(json: NSDictionary) {
self.wCCName = json.stringForKey(XcodeBlueprintNameKey)
let primaryRepoId = json.stringForKey(XcodeBlueprintPrimaryRemoteRepositoryKey)
self.projectWCCIdentifier = primaryRepoId
let workingCopyPaths = json.dictionaryForKey(XcodeBlueprintWorkingCopyPathsKey)
self.projectName = workingCopyPaths.stringForKey(primaryRepoId)
let repos: [NSDictionary] = json.arrayForKey(XcodeBlueprintRemoteRepositoriesKey)
let primarys: [NSDictionary] = repos.filter {
(item: NSDictionary) -> Bool in
return item.stringForKey(XcodeBlueprintRemoteRepositoryIdentifierKey) == primaryRepoId
}
self.projectPath = json.stringForKey(XcodeBlueprintRelativePathToProjectKey)
let repo = primarys.first!
self.projectURL = repo.stringForKey(XcodeBlueprintRemoteRepositoryURLKey)
self.certificateFingerprint = repo.optionalStringForKey(XcodeBlueprintRemoteRepositoryCertFingerprintKey)
let locations = json.dictionaryForKey(XcodeBlueprintLocationsKey)
let location = locations.dictionaryForKey(primaryRepoId)
self.branch = location.optionalStringForKey(XcodeBranchIdentifierKey) ?? ""
self.commitSHA = location.optionalStringForKey(XcodeLocationRevisionKey)
let authenticationStrategy = json.optionalDictionaryForKey(XcodeRepositoryAuthenticationStrategiesKey)?.optionalDictionaryForKey(primaryRepoId)
self.privateSSHKey = authenticationStrategy?.optionalStringForKey(XcodeRepoAuthenticationStrategiesKey)
self.publicSSHKey = authenticationStrategy?.optionalStringForKey(XcodeRepoPublicKeyDataKey)
self.sshPassphrase = authenticationStrategy?.optionalStringForKey(XcodeRepoPasswordKey)
super.init(json: json)
}
public init(branch: String, projectWCCIdentifier: String, wCCName: String, projectName: String,
projectURL: String, projectPath: String, publicSSHKey: String?, privateSSHKey: String?, sshPassphrase: String?, certificateFingerprint: String? = nil)
{
self.branch = branch
self.projectWCCIdentifier = projectWCCIdentifier
self.wCCName = wCCName
self.projectName = projectName
self.projectURL = projectURL
self.projectPath = projectPath
self.commitSHA = nil
self.publicSSHKey = publicSSHKey
self.privateSSHKey = privateSSHKey
self.sshPassphrase = sshPassphrase
self.certificateFingerprint = certificateFingerprint
super.init()
}
//for credentials verification only
public convenience init(projectURL: String, publicSSHKey: String?, privateSSHKey: String?, sshPassphrase: String?) {
self.init(branch: "", projectWCCIdentifier: "", wCCName: "", projectName: "", projectURL: projectURL, projectPath: "", publicSSHKey: publicSSHKey, privateSSHKey: privateSSHKey, sshPassphrase: sshPassphrase)
}
public func dictionarifyRemoteAndCredentials() -> NSDictionary {
let dictionary = NSMutableDictionary()
let repoId = self.projectWCCIdentifier
let remoteUrl = self.projectURL
let sshPublicKey = self.publicSSHKey?.base64Encoded ?? ""
let sshPrivateKey = self.privateSSHKey?.base64Encoded ?? ""
let sshPassphrase = self.sshPassphrase ?? ""
let certificateFingerprint = self.certificateFingerprint ?? ""
//blueprint is not valid without this magic version
dictionary[XcodeBlueprintVersion] = 203
//now, a repo is defined by its server location. so let's throw that in.
dictionary[XcodeBlueprintRemoteRepositoriesKey] = [
[
XcodeBlueprintRemoteRepositoryURLKey: remoteUrl,
XcodeBlueprintRemoteRepositorySystemKey: "com.apple.dt.Xcode.sourcecontrol.Git", //TODO: add more SCMs
XcodeBlueprintRemoteRepositoryIdentifierKey: repoId,
//new - certificate fingerprint
XcodeBlueprintRemoteRepositoryCertFingerprintKey: certificateFingerprint,
XcodeBlueprintRemoteRepositoryTrustSelfSignedCertKey: true
]
]
//but since there might be multiple repos (think git submodules), we need to declare
//the primary one.
dictionary[XcodeBlueprintPrimaryRemoteRepositoryKey] = repoId
//now, this is enough for a valid blueprint. it might not be too useful, but it's valid.
//to make our supported (git) repos work, we also need some credentials.
//repo authentication
//again, since we can provide information for multiple repos, keep the repo's id close.
dictionary[XcodeRepositoryAuthenticationStrategiesKey] = [
repoId: [
XcodeRepoAuthenticationTypeKey: XcodeRepoSSHKeysAuthenticationStrategy,
XcodeRepoUsernameKey: "git", //TODO: see how to add https support?
XcodeRepoPasswordKey: sshPassphrase,
XcodeRepoAuthenticationStrategiesKey: sshPrivateKey,
XcodeRepoPublicKeyDataKey: sshPublicKey
]
]
//up to this is all we need to verify credentials and fingerprint during preflight
//which is now under /api/scm/branches. all the stuff below is useful for actually *creating*
//a bot.
return dictionary
}
private func dictionarifyForBotCreation() -> NSDictionary {
let dictionary = self.dictionarifyRemoteAndCredentials().mutableCopy() as! NSMutableDictionary
let repoId = self.projectWCCIdentifier
var workingCopyPath = self.projectName
//ensure a trailing slash
if !workingCopyPath.hasSuffix("/") {
workingCopyPath = workingCopyPath + "/"
}
let relativePathToProject = self.projectPath
let blueprintName = self.wCCName
let branch = self.branch
//we're creating a bot now.
//our bot has to know which code to check out - we declare that by giving it a branch to track.
//in our case it can be "master", for instance.
dictionary[XcodeBlueprintLocationsKey] = [
repoId: [
XcodeBranchIdentifierKey: branch,
XcodeBranchOptionsKey: 156, //super magic number
XcodeBlueprintLocationTypeKey: "DVTSourceControlBranch" //TODO: add more types?
]
]
//once XCS checks out your repo, it also needs to know how to get to your working copy, in case
//you have a complicated multiple-folder repo setup. coming from the repo's root, for us it's
//something like "XcodeServerSDK/"
dictionary[XcodeBlueprintWorkingCopyPathsKey] = [
repoId: workingCopyPath
]
//once we're in our working copy, we need to know which Xcode project/workspace to use!
//this is relative to the working copy above. all coming together, huh? here
//it would be "XcodeServerSDK.xcworkspace"
dictionary[XcodeBlueprintRelativePathToProjectKey] = relativePathToProject
//now we've given it all we knew. what else?
//turns out there are a couple more keys that XCS needs to be happy. so let's feed the beast.
//every nice data structure needs a name. so give the blueprint one as well. this is usually
//the same as the name of your project, "XcodeServerSDK" in our case here
dictionary[XcodeBlueprintNameKey] = blueprintName
//just feed the beast, ok? this has probably something to do with working copy state, git magic.
//we pass 0. don't ask.
dictionary[XcodeBlueprintWorkingCopyStatesKey] = [
repoId: 0
]
//and to uniquely identify this beauty, we also need to give it a UUID. well, technically I think
//Xcode generates a hash from the data somehow, but passing in a random UUID works as well, so what the hell.
//if someone figures out how to generate the same ID as Xcode does, I'm all yours.
//TODO: give this a good investigation.
dictionary[XcodeBlueprintIdentifierKey] = NSUUID().UUIDString
//and this is the end of our journey to create a new Blueprint. I hope you enjoyed the ride, please return the 3D glasses to the green bucket on your way out.
return dictionary
}
public override func dictionarify() -> NSDictionary {
return self.dictionarifyForBotCreation()
}
}
|
mit
|
492db99185af71a8de5af7846be1fe84
| 44.234742 | 214 | 0.678983 | 5.163451 | false | false | false | false |
february29/Learning
|
swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observables/Scan.swift
|
130
|
2803
|
//
// Scan.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value.
For aggregation behavior with no intermediate results, see `reduce`.
- seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html)
- parameter seed: The initial accumulator value.
- parameter accumulator: An accumulator function to be invoked on each element.
- returns: An observable sequence containing the accumulated values.
*/
public func scan<A>(_ seed: A, accumulator: @escaping (A, E) throws -> A)
-> Observable<A> {
return Scan(source: self.asObservable(), seed: seed, accumulator: accumulator)
}
}
final fileprivate class ScanSink<ElementType, O: ObserverType> : Sink<O>, ObserverType {
typealias Accumulate = O.E
typealias Parent = Scan<ElementType, Accumulate>
typealias E = ElementType
fileprivate let _parent: Parent
fileprivate var _accumulate: Accumulate
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
_accumulate = parent._seed
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<ElementType>) {
switch event {
case .next(let element):
do {
_accumulate = try _parent._accumulator(_accumulate, element)
forwardOn(.next(_accumulate))
}
catch let error {
forwardOn(.error(error))
dispose()
}
case .error(let error):
forwardOn(.error(error))
dispose()
case .completed:
forwardOn(.completed)
dispose()
}
}
}
final fileprivate class Scan<Element, Accumulate>: Producer<Accumulate> {
typealias Accumulator = (Accumulate, Element) throws -> Accumulate
fileprivate let _source: Observable<Element>
fileprivate let _seed: Accumulate
fileprivate let _accumulator: Accumulator
init(source: Observable<Element>, seed: Accumulate, accumulator: @escaping Accumulator) {
_source = source
_seed = seed
_accumulator = accumulator
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Accumulate {
let sink = ScanSink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
|
mit
|
ba943f872b2ade723ff62a625747d920
| 33.170732 | 169 | 0.640614 | 4.831034 | false | false | false | false |
hgani/ganilib-ios
|
glib/Classes/Screen/UIBarButtonItem+Badge.swift
|
1
|
2799
|
// See https://gist.github.com/freedom27/c709923b163e26405f62b799437243f4
import UIKit
extension CAShapeLayer {
func drawRoundedRect(rect: CGRect, andColor color: UIColor, filled: Bool) {
fillColor = filled ? color.cgColor : UIColor.white.cgColor
strokeColor = color.cgColor
path = UIBezierPath(roundedRect: rect, cornerRadius: 7).cgPath
}
}
private var handle: UInt8 = 0
extension UIBarButtonItem {
private var badgeLayer: CAShapeLayer? {
if let badge: AnyObject = objc_getAssociatedObject(self, &handle) as AnyObject? {
return badge as? CAShapeLayer
} else {
return nil
}
}
func setBadge(text: String?, withOffsetFromTopRight offset: CGPoint = CGPoint.zero, andColor color: UIColor = UIColor.red, andFilled filled: Bool = true, andFontSize _: CGFloat = 11) {
badgeLayer?.removeFromSuperlayer()
if text == nil || text! == "" || Int(text!) == 0 {
return
}
addBadge(text: text!, withOffset: offset, andColor: color, andFilled: filled)
}
private func addBadge(text: String, withOffset offset: CGPoint = CGPoint.zero, andColor color: UIColor = UIColor.red, andFilled filled: Bool = true, andFontSize fontSize: CGFloat = 14) {
guard let view = self.value(forKey: "view") as? UIView else { return }
let font = UIFont.systemFont(ofSize: fontSize)
let badgeSize = text.size(withAttributes: [NSAttributedString.Key.font: font])
// Initialize Badge
let badge = CAShapeLayer()
let height = badgeSize.height
var width = badgeSize.width + 2 /* padding */
// make sure we have at least a circle
if width < height {
width = height
}
// x position is offset from right-hand side
let xPos = view.frame.width - width + offset.x
let badgeFrame = CGRect(origin: CGPoint(x: xPos, y: offset.y), size: CGSize(width: width, height: height))
badge.drawRoundedRect(rect: badgeFrame, andColor: color, filled: filled)
view.layer.addSublayer(badge)
// Initialiaze Badge's label
let label = CATextLayer()
label.string = text
label.alignmentMode = .center
label.font = font
label.fontSize = font.pointSize
label.frame = badgeFrame
label.foregroundColor = filled ? UIColor.white.cgColor : color.cgColor
label.backgroundColor = UIColor.clear.cgColor
label.contentsScale = UIScreen.main.scale
badge.addSublayer(label)
// Save Badge as UIBarButtonItem property
objc_setAssociatedObject(self, &handle, badge, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
private func removeBadge() {
badgeLayer?.removeFromSuperlayer()
}
}
|
mit
|
2379d6b22ab8461631e209c43c32c700
| 34.43038 | 190 | 0.648803 | 4.414826 | false | false | false | false |
KyoheiG3/DynamicBlurView
|
Sources/DynamicBlurView/UIImage+Blur.swift
|
1
|
832
|
//
// UIImage+Blur.swift
// DynamicBlurView
//
// Created by Kyohei Ito on 2017/08/11.
// Copyright © 2017年 kyohei_ito. All rights reserved.
//
import UIKit
public extension UIImage {
func blurred(radius: CGFloat, iterations: Int, ratio: CGFloat, blendColor color: UIColor?, blendMode mode: CGBlendMode) -> UIImage? {
guard let cgImage = cgImage?.arg8888Image() else {
return nil
}
if cgImage.area <= 0 || radius <= 0 {
return self
}
var boxSize = UInt32(radius * scale * ratio)
if boxSize % 2 == 0 {
boxSize += 1
}
return cgImage.blurred(with: boxSize, iterations: iterations, blendColor: color, blendMode: mode).map {
UIImage(cgImage: $0, scale: scale, orientation: imageOrientation)
}
}
}
|
mit
|
80c8299e5cd18d482b744e68238fb592
| 26.633333 | 137 | 0.599517 | 4.186869 | false | false | false | false |
practicalswift/swift
|
stdlib/public/core/StringInterpolation.swift
|
5
|
9906
|
//===--- StringInterpolation.swift - String Interpolation -----------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Represents a string literal with interpolations while it is being built up.
///
/// Do not create an instance of this type directly. It is used by the compiler
/// when you create a string using string interpolation. Instead, use string
/// interpolation to create a new string by including values, literals,
/// variables, or expressions enclosed in parentheses, prefixed by a
/// backslash (`\(`...`)`).
///
/// let price = 2
/// let number = 3
/// let message = """
/// If one cookie costs \(price) dollars, \
/// \(number) cookies cost \(price * number) dollars.
/// """
/// print(message)
/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
///
/// When implementing an `ExpressibleByStringInterpolation` conformance,
/// set the `StringInterpolation` associated type to
/// `DefaultStringInterpolation` to get the same interpolation behavior as
/// Swift's built-in `String` type and construct a `String` with the results.
/// If you don't want the default behavior or don't want to construct a
/// `String`, use a custom type conforming to `StringInterpolationProtocol`
/// instead.
///
/// Extending default string interpolation behavior
/// ===============================================
///
/// Code outside the standard library can extend string interpolation on
/// `String` and many other common types by extending
/// `DefaultStringInterpolation` and adding an `appendInterpolation(...)`
/// method. For example:
///
/// extension DefaultStringInterpolation {
/// fileprivate mutating func appendInterpolation(
/// escaped value: String, asASCII forceASCII: Bool = false) {
/// for char in value.unicodeScalars {
/// appendInterpolation(char.escaped(asASCII: forceASCII)
/// }
/// }
/// }
///
/// print("Escaped string: \(escaped: string)")
///
/// See `StringInterpolationProtocol` for details on `appendInterpolation`
/// methods.
///
/// `DefaultStringInterpolation` extensions should add only `mutating` members
/// and should not copy `self` or capture it in an escaping closure.
@_fixed_layout
public struct DefaultStringInterpolation: StringInterpolationProtocol {
/// The string contents accumulated by this instance.
@usableFromInline
internal var _storage: String
/// Creates a string interpolation with storage pre-sized for a literal
/// with the indicated attributes.
///
/// Do not call this initializer directly. It is used by the compiler when
/// interpreting string interpolations.
@inlinable
public init(literalCapacity: Int, interpolationCount: Int) {
let capacityPerInterpolation = 2
let initialCapacity = literalCapacity +
interpolationCount * capacityPerInterpolation
_storage = String(_StringGuts(_initialCapacity: initialCapacity))
}
/// Appends a literal segment of a string interpolation.
///
/// Do not call this method directly. It is used by the compiler when
/// interpreting string interpolations.
@inlinable
public mutating func appendLiteral(_ literal: String) {
literal.write(to: &self)
}
/// Interpolates the given value's textual representation into the
/// string literal being created.
///
/// Do not call this method directly. It is used by the compiler when
/// interpreting string interpolations. Instead, use string
/// interpolation to create a new string by including values, literals,
/// variables, or expressions enclosed in parentheses, prefixed by a
/// backslash (`\(`...`)`).
///
/// let price = 2
/// let number = 3
/// let message = """
/// If one cookie costs \(price) dollars, \
/// \(number) cookies cost \(price * number) dollars.
/// """
/// print(message)
/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
@inlinable
public mutating func appendInterpolation<T>(_ value: T)
where T: TextOutputStreamable, T: CustomStringConvertible
{
value.write(to: &self)
}
/// Interpolates the given value's textual representation into the
/// string literal being created.
///
/// Do not call this method directly. It is used by the compiler when
/// interpreting string interpolations. Instead, use string
/// interpolation to create a new string by including values, literals,
/// variables, or expressions enclosed in parentheses, prefixed by a
/// backslash (`\(`...`)`).
///
/// let price = 2
/// let number = 3
/// let message = "If one cookie costs \(price) dollars, " +
/// "\(number) cookies cost \(price * number) dollars."
/// print(message)
/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
@inlinable
public mutating func appendInterpolation<T>(_ value: T)
where T: TextOutputStreamable
{
value.write(to: &self)
}
/// Interpolates the given value's textual representation into the
/// string literal being created.
///
/// Do not call this method directly. It is used by the compiler when
/// interpreting string interpolations. Instead, use string
/// interpolation to create a new string by including values, literals,
/// variables, or expressions enclosed in parentheses, prefixed by a
/// backslash (`\(`...`)`).
///
/// let price = 2
/// let number = 3
/// let message = """
/// If one cookie costs \(price) dollars, \
/// \(number) cookies cost \(price * number) dollars.
/// """
/// print(message)
/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
@inlinable
public mutating func appendInterpolation<T>(_ value: T)
where T: CustomStringConvertible
{
value.description.write(to: &self)
}
/// Interpolates the given value's textual representation into the
/// string literal being created.
///
/// Do not call this method directly. It is used by the compiler when
/// interpreting string interpolations. Instead, use string
/// interpolation to create a new string by including values, literals,
/// variables, or expressions enclosed in parentheses, prefixed by a
/// backslash (`\(`...`)`).
///
/// let price = 2
/// let number = 3
/// let message = """
/// If one cookie costs \(price) dollars, \
/// \(number) cookies cost \(price * number) dollars.
/// """
/// print(message)
/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
@inlinable
public mutating func appendInterpolation<T>(_ value: T) {
_print_unlocked(value, &self)
}
/// Creates a string from this instance, consuming the instance in the
/// process.
@inlinable
internal __consuming func make() -> String {
return _storage
}
}
extension DefaultStringInterpolation: CustomStringConvertible {
@inlinable
public var description: String {
return _storage
}
}
extension DefaultStringInterpolation: TextOutputStream {
@inlinable
public mutating func write(_ string: String) {
_storage.append(string)
}
public mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) {
_storage._guts.append(_StringGuts(buffer, isASCII: true))
}
}
// While not strictly necessary, declaring these is faster than using the
// default implementation.
extension String {
/// Creates a new instance from an interpolated string literal.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you create a string using string interpolation. Instead, use string
/// interpolation to create a new string by including values, literals,
/// variables, or expressions enclosed in parentheses, prefixed by a
/// backslash (`\(`...`)`).
///
/// let price = 2
/// let number = 3
/// let message = """
/// If one cookie costs \(price) dollars, \
/// \(number) cookies cost \(price * number) dollars.
/// """
/// print(message)
/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
@inlinable
@_effects(readonly)
public init(stringInterpolation: DefaultStringInterpolation) {
self = stringInterpolation.make()
}
}
extension Substring {
/// Creates a new instance from an interpolated string literal.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you create a string using string interpolation. Instead, use string
/// interpolation to create a new string by including values, literals,
/// variables, or expressions enclosed in parentheses, prefixed by a
/// backslash (`\(`...`)`).
///
/// let price = 2
/// let number = 3
/// let message = """
/// If one cookie costs \(price) dollars, \
/// \(number) cookies cost \(price * number) dollars.
/// """
/// print(message)
/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
@inlinable
@_effects(readonly)
public init(stringInterpolation: DefaultStringInterpolation) {
self.init(stringInterpolation.make())
}
}
|
apache-2.0
|
f3b04ab585b25dc154269a5fd6c501a1
| 37.695313 | 80 | 0.637291 | 4.863034 | false | false | false | false |
huonw/swift
|
test/stdlib/StringCompatibilityDiagnostics4.swift
|
6
|
1785
|
// RUN: %target-swift-frontend -typecheck -swift-version 4 %s -verify
func testPopFirst() {
var str = "abc"
_ = str.popFirst() // expected-error{{'popFirst()' is unavailable: Please use 'first', 'dropFirst()', or 'Substring.popFirst()'}}
_ = str.characters.popFirst() // expected-warning{{'characters' is deprecated: Please use String or Substring directly}}
_ = str.popFirst() // expected-error{{'popFirst()' is unavailable: Please use 'first', 'dropFirst()', or 'Substring.popFirst()'}}
_ = str.unicodeScalars.popFirst() // expected-error{{'popFirst()' is unavailable: Please use 'first', 'dropFirst()', or 'Substring.UnicodeScalarView.popFirst()'}}
var charView: String.CharacterView // expected-warning{{'CharacterView' is deprecated: Please use String or Substring directly}}
charView = str.characters // expected-warning{{'characters' is deprecated: Please use String or Substring directly}}
dump(charView)
var substr = str[...]
_ = substr.popFirst() // ok
_ = substr.characters.popFirst() // expected-warning{{'characters' is deprecated: Please use String or Substring directly}}
_ = substr.unicodeScalars.popFirst() // ok
var charSubView: Substring.CharacterView // expected-warning{{'CharacterView' is deprecated: Please use String or Substring directly}}
charSubView = substr.characters // expected-warning{{'characters' is deprecated: Please use String or Substring directly}}
dump(charSubView)
var _ = String(str.utf8) ?? "" // expected-warning{{left side of nil coalescing operator '??' has non-optional type 'String', so the right side is never used}}
var _: String = String(str.utf8)! // expected-error{{'init' is unavailable: Please use non-failable String.init(_:UTF8View) instead}}
var _: String = String(str.utf8) // ok
}
|
apache-2.0
|
2d2fab3e6429812d66bf78875d5e6322
| 60.551724 | 164 | 0.714846 | 4.311594 | false | false | false | false |
ludoded/ReceiptBot
|
Pods/Material/Sources/iOS/BottomTabBar.swift
|
2
|
4493
|
/*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* 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 CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
extension UITabBarItem {
/// Sets the color of the title color for a state.
public func setTitleColor(color: UIColor, forState state: UIControlState) {
setTitleTextAttributes([NSForegroundColorAttributeName: color], for: state)
}
}
open class BottomTabBar: UITabBar {
open override var intrinsicContentSize: CGSize {
return CGSize(width: width, height: height)
}
/// Automatically aligns the BottomNavigationBar to the superview.
@IBInspectable
open var isAlignedToParentAutomatically = true
/// A property that accesses the backing layer's background
@IBInspectable
open override var backgroundColor: UIColor? {
didSet {
barTintColor = backgroundColor
}
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
super.init(frame: frame)
prepare()
}
/// A convenience initializer.
public convenience init() {
self.init(frame: .zero)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepare()
}
open override func layoutSubviews() {
super.layoutSubviews()
layoutShape()
layoutShadowPath()
if let v = items {
for item in v {
if .phone == Device.userInterfaceIdiom {
if nil == item.title {
let inset: CGFloat = 7
item.imageInsets = UIEdgeInsetsMake(inset, 0, -inset, 0)
} else {
let inset: CGFloat = 6
item.titlePositionAdjustment.vertical = -inset
}
} else if nil == item.title {
let inset: CGFloat = 9
item.imageInsets = UIEdgeInsetsMake(inset, 0, -inset, 0)
} else {
let inset: CGFloat = 3
item.imageInsets = UIEdgeInsetsMake(inset, 0, -inset, 0)
item.titlePositionAdjustment.vertical = -inset
}
}
}
divider.reload()
}
open override func didMoveToSuperview() {
super.didMoveToSuperview()
if isAlignedToParentAutomatically {
if let v = superview {
v.layout(self).bottom().horizontally()
}
}
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
public func prepare() {
heightPreset = .normal
depthPreset = .depth1
dividerAlignment = .top
contentScaleFactor = Screen.scale
backgroundColor = .white
let image = UIImage.image(with: .clear, size: CGSize(width: 1, height: 1))
shadowImage = image
backgroundImage = image
}
}
|
lgpl-3.0
|
bcae53a06bf7ce02c1f423413999bae3
| 32.781955 | 88 | 0.694191 | 4.461768 | false | false | false | false |
maxoly/PulsarKit
|
PulsarKitExample/PulsarKitExample/Cells/MenuItem/MenuItemCollectionViewCell.swift
|
1
|
1209
|
//
// MenuItemCollectionViewCell.swift
// PulsarKitExample
//
// Created by Massimo Oliviero on 27/02/2019.
// Copyright © 2019 Nacoon. All rights reserved.
//
import UIKit
import PulsarKit
class MenuItemCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var lineView: UIView!
@IBOutlet weak var iconImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
titleLabel.textColor = .primary
descriptionLabel.textColor = .secondary
lineView.backgroundColor = .light
iconImageView.tintColor = .primary
backgroundColor = .white
}
}
extension MenuItemCollectionViewCell: Bindable {
func bind(to element: MenuItem) {
titleLabel.text = element.title
descriptionLabel.text = element.description
iconImageView.image = element.icon
}
}
extension MenuItemCollectionViewCell: Groupable {
func groupNotification(sectionPosition: GroupedCollectionPlugin.Position, itemPosition: GroupedCollectionPlugin.Position) {
print("section: \(sectionPosition), item: \(itemPosition)")
}
}
|
mit
|
c63de36ff412d97d30dd02575e6b0203
| 29.2 | 127 | 0.718543 | 4.930612 | false | false | false | false |
RoverPlatform/rover-ios
|
Sources/Location/LocationAssembler.swift
|
1
|
5020
|
//
// LocationAssembler.swift
// RoverLocation
//
// Created by Sean Rucker on 2017-10-24.
// Copyright © 2017 Rover Labs Inc. All rights reserved.
//
import CoreData
import CoreLocation
import os
#if !COCOAPODS
import RoverFoundation
import RoverData
#endif
public class LocationAssembler: Assembler {
let maxGeofenceRegionsToMonitor: Int
let maxBeaconRegionsToMonitor: Int
public init(
maxGeofenceRegionsToMonitor: Int = 20,
maxBeaconRegionsToMonitor: Int = 5
) {
self.maxGeofenceRegionsToMonitor = maxGeofenceRegionsToMonitor
self.maxBeaconRegionsToMonitor = maxBeaconRegionsToMonitor
}
public func assemble(container: Container) {
// MARK: Core Data
container.register(NSManagedObjectContext.self, name: "location.backgroundContext") { resolver in
let container = resolver.resolve(NSPersistentContainer.self, name: "location")!
let context = container.newBackgroundContext()
context.mergePolicy = NSOverwriteMergePolicy
return context
}
container.register(NSManagedObjectContext.self, name: "location.viewContext") { resolver in
let container = resolver.resolve(NSPersistentContainer.self, name: "location")!
return container.viewContext
}
container.register(NSPersistentContainer.self, name: "location") { _ in
#if !COCOAPODS
// for SwiftPM use Bundle.module:
guard let modelURL = Bundle.module.url(forResource: "RoverLocation", withExtension: "momd") else {
fatalError("Core Data model not found for Rover Location module.")
}
guard let model = NSManagedObjectModel(contentsOf: modelURL) else {
fatalError("Core Data model not found for Rover Location module.")
}
// unfortunately the entity names seem to get set to "Rover_RoverLocation.ClassName" rather than "RoverLocation.ClassName" causing a runtime failure. Manually patch it up here.
model.entities.forEach { entity in
switch entity.name {
case "Beacon":
entity.managedObjectClassName = "RoverLocation.Beacon"
case "Geofence":
entity.managedObjectClassName = "RoverLocation.Geofence"
default:
break
}
}
#else
let bundles = [Bundle(for: LocationAssembler.self)]
guard let model = NSManagedObjectModel.mergedModel(from: bundles) else {
fatalError("Core Data model not found for Rover Location module.")
}
#endif
let container = NSPersistentContainer(name: "RoverLocation", managedObjectModel: model)
container.loadPersistentStores { _, error in
if let error = error {
os_log("Core Data store for Rover Location module failed to load, reason: %s", error.logDescription)
assertionFailure("Core Data store for Rover Location module failed to load, reason: \(error.logDescription)")
}
}
return container
}
// MARK: Services
container.register(LocationContextProvider.self) { resolver in
resolver.resolve(LocationManager.self)!
}
container.register(LocationManager.self) { resolver in
LocationManager(
context: resolver.resolve(NSManagedObjectContext.self, name: "location.viewContext")!,
eventQueue: resolver.resolve(EventQueue.self)!,
maxGeofenceRegionsToMonitor: self.maxGeofenceRegionsToMonitor,
maxBeaconRegionsToMonitor: self.maxBeaconRegionsToMonitor
)
}
container.register(RegionManager.self) { resolver in
resolver.resolve(LocationManager.self)!
}
container.register(SyncParticipant.self, name: "location.beacons") { resolver in
BeaconsSyncParticipant(
context: resolver.resolve(NSManagedObjectContext.self, name: "location.backgroundContext")!,
userDefaults: UserDefaults.standard
)
}
container.register(SyncParticipant.self, name: "location.geofences") { resolver in
GeofencesSyncParticipant(
context: resolver.resolve(NSManagedObjectContext.self, name: "location.backgroundContext")!,
userDefaults: UserDefaults.standard
)
}
}
public func containerDidAssemble(resolver: Resolver) {
resolver.resolve(SyncCoordinator.self)!.participants.append(contentsOf: [
resolver.resolve(SyncParticipant.self, name: "location.beacons")!,
resolver.resolve(SyncParticipant.self, name: "location.geofences")!
])
}
}
|
apache-2.0
|
6357353a2c53e27872ee6ed214a9a683
| 40.139344 | 189 | 0.621439 | 5.497262 | false | false | false | false |
seyton/2048
|
NumberTiles/Models/Constants.swift
|
1
|
2133
|
//
// Constants.swift
// NumberTiles
//
// Created by Wesley Matlock on 11/24/15.
// Copyright © 2015 insoc.net. All rights reserved.
//
import Foundation
enum MoveDirection {
case Up, Down, Left, Right
}
enum MoveOrder {
case SingleMoveOrder(source: Int, destination: Int, value: Int, wasMerged: Bool)
case DoubleMoveOrder(firstSource: Int, secondSource: Int, destination: Int, value: Int)
}
enum TileObject {
case Empty
case Tile(Int)
}
enum ActionToken {
case NoAction(source: Int, value: Int)
case Move(source: Int, value: Int)
case SingleCombine(source: Int, value: Int)
case DoubleCombine(firstSource: Int, secondSource: Int, value: Int)
func getValue() -> Int {
switch self {
case let .NoAction(_, v): return v
case let .Move(_, v): return v
case let .SingleCombine(_, v): return v
case let .DoubleCombine(_, _, v): return v
}
}
func getSource() -> Int {
switch self {
case let .NoAction(s, _): return s
case let .Move(s, _): return s
case let .SingleCombine(s, _): return s
case let .DoubleCombine(s, _, _): return s
}
}
}
struct MoveCommand {
let direction: MoveDirection
let completion: (Bool) -> ()
}
struct SquareGameboard<T> {
let dimension: Int
var boardArray: [T]
init(dimension d: Int, initialValue: T) {
dimension = d
boardArray = [T](count: d*d, repeatedValue: initialValue)
}
subscript(row: Int, col: Int) -> T {
get {
assert(row >= 0 && row < dimension)
assert(col >= 0 && col < dimension)
return boardArray[row * dimension + col]
}
set {
assert(row >= 0 && row < dimension)
assert(col >= 0 && col < dimension)
boardArray[row * dimension + col] = newValue
}
}
mutating func setAll(item: T) {
for i in 0..<dimension {
for j in 0..<dimension {
self[i, j] = item
}
}
}
}
|
mit
|
5c5893616ce98db385f93ec56248a658
| 22.966292 | 91 | 0.547373 | 4.037879 | false | false | false | false |
djones6/swift-benchmarks
|
ConvTest.swift
|
1
|
3082
|
//
// ConvTest.swift
// A simple workload to measure the overhead of synchronization in the __CFGetConverter
// Linux Foundation code.
// See: https://github.com/apple/swift-corelibs-foundation/pull/414
//
// Created by David Jones (@djones6) on 02/06/2016
//
import Foundation
import Dispatch
// Determine how many concurrent blocks to schedule (user specified, or 10)
var CONCURRENCY:Int = 10
// Determines how many times to convert a string per block
var EFFORT:Int = 1000
// Determines the length of the payload being converted
var LENGTH:Int = 1000
// Debug
var DEBUG = false
func usage() {
print("Options are:")
print(" -c, --concurrency n: number of concurrent Dispatch blocks")
print(" -e, --effort n: number of times to invoke conversion per block")
print(" -l, --length n: length of String (in chars) to be converted")
print(" -d, --debug: print a lot of debugging output")
exit(1)
}
// Parse an expected int value provided on the command line
func parseInt(param: String, value: String) -> Int {
if let userInput = Int(value) {
return userInput
} else {
print("Invalid value for \(param): '\(value)'")
exit(1)
}
}
// Parse command line options
var param:String? = nil
var remainingArgs = Process.arguments.dropFirst(1)
for arg in remainingArgs {
if let _param = param {
param = nil
switch _param {
case "-c", "--concurrency":
CONCURRENCY = parseInt(param: _param, value: arg)
case "-e", "--effort":
EFFORT = parseInt(param: _param, value: arg)
case "-l", "--length":
LENGTH = parseInt(param: _param, value: arg)
default:
print("Invalid option '\(arg)'")
usage()
}
} else {
switch arg {
case "-c", "--concurrency", "-e", "--effort", "-l", "--length":
param = arg
case "-d", "--debug":
DEBUG = true
case "-?", "-h", "--help", "--?":
usage()
default:
print("Invalid option '\(arg)'")
usage()
}
}
}
if (DEBUG) {
print("Concurrency: \(CONCURRENCY)")
print("Effort: \(EFFORT)")
print("Length: \(LENGTH)")
print("Debug: \(DEBUG)")
}
// The string to convert
let PAYLOAD:String
var _payload = "Houston we have a problem"
while _payload.characters.count < LENGTH {
_payload = _payload + _payload
}
// Surely this isn't the best way to substring? but it works...
PAYLOAD = String(_payload.characters.dropLast(_payload.characters.count - LENGTH))
if DEBUG { print("Payload is \(PAYLOAD.characters.count) chars") }
// Create a queue to run blocks in parallel
let queue = dispatch_queue_create("hello", DISPATCH_QUEUE_CONCURRENT)
// Block to be scheduled
func code(_ instance: String) -> () -> Void {
return {
for _ in 1...EFFORT {
let _ = PAYLOAD.data(using: NSUTF8StringEncoding)
}
if DEBUG { print("\(instance) done") }
// Dispatch a new block to replace this one
dispatch_async(queue, code("\(instance)+"))
}
}
print("Queueing \(CONCURRENCY) blocks")
// Queue the initial blocks
for i in 1...CONCURRENCY {
dispatch_async(queue, code("\(i)"))
}
print("Go!")
// Go
dispatch_main()
|
mit
|
af88182250206535aaa2f479aaedbb1e
| 25.118644 | 88 | 0.646009 | 3.579559 | false | false | false | false |
Appsaurus/Infinity
|
Infinity/controls/snake/SnakeRefreshAnimator.swift
|
1
|
4494
|
//
// SnakeRefreshAnimator.swift
// InfinitySample
//
// Created by Danis on 15/12/26.
// Copyright © 2015年 danis. All rights reserved.
//
import UIKit
open class SnakeRefreshAnimator: UIView, CustomPullToRefreshAnimator {
open var color: UIColor = UIColor.SnakeBlue {
didSet {
snakeLayer.strokeColor = color.cgColor
}
}
var animating = false
fileprivate var snakeLayer = CAShapeLayer()
fileprivate var snakeLengthByCycle:CGFloat = 0 // 显示的长度所占周期数
fileprivate var cycleCount = 1000
fileprivate var pathLength:CGFloat = 0
public override init(frame: CGRect) {
super.init(frame: frame)
let ovalDiametor = frame.width / 4
let lineHeight = frame.height - ovalDiametor
snakeLengthByCycle = 2 - (ovalDiametor/2 * CGFloat(M_PI)) / ((lineHeight + ovalDiametor/2 * CGFloat(M_PI)) * 2)
pathLength = ovalDiametor * 2 * CGFloat(cycleCount)
let snakePath = UIBezierPath()
snakePath.move(to: CGPoint(x: 0, y: frame.height - ovalDiametor/2))
for index in 0...cycleCount {
let cycleStartX = CGFloat(index) * ovalDiametor * 2
snakePath.addLine(to: CGPoint(x: cycleStartX, y: ovalDiametor / 2))
snakePath.addArc(withCenter: CGPoint(x: cycleStartX + ovalDiametor / 2, y: ovalDiametor / 2), radius: ovalDiametor / 2, startAngle: CGFloat(M_PI), endAngle: 0, clockwise: true)
snakePath.addLine(to: CGPoint(x: cycleStartX + ovalDiametor, y: frame.height - ovalDiametor / 2))
snakePath.addArc(withCenter: CGPoint(x: cycleStartX + ovalDiametor / 2 * 3, y: frame.height - ovalDiametor/2), radius: ovalDiametor/2, startAngle: CGFloat(M_PI), endAngle: 0, clockwise: false)
}
snakeLayer.path = snakePath.cgPath
snakeLayer.fillColor = nil
snakeLayer.strokeColor = color.cgColor
snakeLayer.strokeStart = 0
snakeLayer.strokeEnd = snakeLengthByCycle / CGFloat(cycleCount)
snakeLayer.lineWidth = 3
snakeLayer.lineCap = kCALineCapRound
snakeLayer.frame = self.bounds
self.layer.addSublayer(snakeLayer)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func didMoveToWindow() {
super.didMoveToWindow()
if window != nil && animating {
startAnimating()
}
}
open func animateState(_ state: PullToRefreshState) {
switch state {
case .none:
stopAnimating()
case .loading:
startAnimating()
case .releasing(let progress):
updateForProgress(progress)
}
}
func updateForProgress(_ progress: CGFloat) {
snakeLayer.isHidden = false
CATransaction.begin()
CATransaction.setDisableActions(true)
snakeLayer.strokeStart = 0
snakeLayer.strokeEnd = snakeLengthByCycle / CGFloat(cycleCount) * progress
CATransaction.commit()
}
fileprivate let AnimationGroupKey = "SnakePathAnimations"
func startAnimating() {
animating = true
snakeLayer.isHidden = false
snakeLayer.strokeStart = 0
snakeLayer.strokeEnd = snakeLengthByCycle / CGFloat(cycleCount)
let strokeStartAnim = CABasicAnimation(keyPath: "strokeStart")
let strokeEndAnim = CABasicAnimation(keyPath: "strokeEnd")
let moveAnim = CABasicAnimation(keyPath: "position")
strokeStartAnim.toValue = 1 - snakeLengthByCycle/CGFloat(cycleCount)
strokeEndAnim.toValue = 1
moveAnim.toValue = NSValue(cgPoint: CGPoint(x: snakeLayer.position.x - pathLength, y: snakeLayer.position.y))
let animGroup = CAAnimationGroup()
animGroup.animations = [strokeStartAnim,strokeEndAnim,moveAnim]
animGroup.duration = Double(cycleCount) * 0.6
snakeLayer.add(animGroup, forKey: AnimationGroupKey)
}
func stopAnimating() {
animating = false
snakeLayer.isHidden = true
snakeLayer.removeAnimation(forKey: AnimationGroupKey)
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
|
mit
|
879d2ac3272a4fa90a09779f2d248427
| 35.349593 | 204 | 0.639902 | 4.511604 | false | false | false | false |
mleiv/MEGameTracker
|
MEGameTracker/Models/CoreData/CoreDataMigrations/BaseDataImport.swift
|
1
|
18823
|
//
// BaseDataImport.swift
// MEGameTracker
//
// Created by Emily Ivie on 10/1/15.
// Copyright © 2015 Emily Ivie. All rights reserved.
//
import Foundation
import CoreData
public struct BaseDataImport: CoreDataMigrationType {
let progressProcessImportChunk = 40.0
let progressFinalPadding = 20.0
let onProcessMapDataRow = Signal<Bool>()
let onProcessMissionDataRow = Signal<Bool>()
var isTestProject: Bool {
return ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil
}
let manager: CodableCoreDataManageable?
public init(manager: CodableCoreDataManageable? = nil) {
self.manager = manager ?? CoreDataManager.current
}
public func run() throws {
// Don't run base data load twice on same data:
guard !CoreDataMigrationManager.didLoadBaseData else { return }
try addData()
CoreDataMigrationManager.didLoadBaseData = true
print("Installed base data")
}
// Must group these by type
public typealias CoreDataFileImport = (type: BaseDataFileImportType, filename: String, progress: Double)
public let progressFilesEvents: [CoreDataFileImport] = [
(type: .event, filename: "DataEvents_1", progress: 1),
(type: .event, filename: "DataEvents_2", progress: 1),
(type: .event, filename: "DataEvents_3", progress: 1),
]
public let progressFilesOther: [CoreDataFileImport] = [
(type: .decision, filename: "DataDecisions_1", progress: 1),
(type: .decision, filename: "DataDecisions_2", progress: 1),
(type: .decision, filename: "DataDecisions_3", progress: 1),
(type: .person, filename: "DataPersons_1", progress: 1),
(type: .person, filename: "DataPersons_1Others", progress: 3),
(type: .person, filename: "DataPersons_2", progress: 1),
(type: .person, filename: "DataPersons_2Others", progress: 3),
(type: .person, filename: "DataPersons_3", progress: 1),
(type: .person, filename: "DataPersons_3Others", progress: 3),
(type: .map, filename: "DataMaps_Primary", progress: 2),
(type: .map, filename: "DataMaps_TerminusSystems", progress: 5),
(type: .map, filename: "DataMaps_AtticanTraverse", progress: 5),
(type: .map, filename: "DataMaps_InnerCouncil", progress: 5),
(type: .map, filename: "DataMaps_OuterCouncil", progress: 5),
(type: .map, filename: "DataMaps_EarthSystemsAlliance", progress: 5),
(type: .item, filename: "DataItems_1", progress: 1),
(type: .item, filename: "DataItems_1Loot", progress: 1),
(type: .item, filename: "DataItems_1Scans", progress: 1),
(type: .item, filename: "DataItems_2", progress: 1),
(type: .item, filename: "DataItems_2Loot", progress: 1),
(type: .item, filename: "DataItems_3", progress: 1),
(type: .item, filename: "DataItems_3Loot", progress: 1),
(type: .item, filename: "DataItems_3Scans", progress: 1),
(type: .mission, filename: "DataMissions_1", progress: 2),
(type: .mission, filename: "DataMissions_1Assignments", progress: 5),
(type: .mission, filename: "DataMissions_1Convos", progress: 3),
(type: .mission, filename: "DataMissions_1Misc", progress: 3),
(type: .mission, filename: "DataMissions_2", progress: 2),
(type: .mission, filename: "DataMissions_2Assignments", progress: 5),
(type: .mission, filename: "DataMissions_2Convos", progress: 5),
(type: .mission, filename: "DataMissions_2Misc", progress: 5),
(type: .mission, filename: "DataMissions_3", progress: 2),
(type: .mission, filename: "DataMissions_3Assignments", progress: 5),
(type: .mission, filename: "DataMissions_3Convos", progress: 5),
(type: .mission, filename: "DataMissions_3Misc", progress: 5),
]
func fireProgress(progress: Double, progressTotal: Double) {
let progressPercent = progressTotal > 0 ? (progress > 0 ? Int((progress / progressTotal) * 100) : 0) : 1
// print("fireProgress \(progress)/\(progressTotal) \(progressPercent)%")
DispatchQueue.main.async {
CoreDataMigrations.onPercentProgress.fire(progressPercent)
}
}
func addData() throws {
let progressTotal = (progressFilesEvents + progressFilesOther).map { $0.progress }.reduce(0.0, +)
+ (progressProcessImportChunk * 2.0) + progressFinalPadding
try importDataFiles(progress: 0.0, progressTotal: progressTotal)
processImportedData(
progress: progressTotal - (progressProcessImportChunk * 2.0),
progressTotal: progressTotal
)
}
}
extension BaseDataImport {
func importDataFiles(progress: Double, progressTotal: Double) throws {
var progress = progress
fireProgress(progress: progress, progressTotal: progressTotal)
// load up all ids so we know if some have been removed
var deleteOldIds: [BaseDataFileImportType: [String]] = [:]
for type in Array(Set((progressFilesEvents + progressFilesOther).map({ $0.type }))) {
deleteOldIds[type] = self.getAllIds(type: type, with: manager)
}
let queue = DispatchQueue.global(qos: .userInitiated)
let queueGroup = DispatchGroup()
let markIdsImported: (BaseDataFileImportType, [String]) -> Void = { (type, ids) in
deleteOldIds[type] = Array(Set(deleteOldIds[type] ?? []).subtracting(ids))
}
let updateFileProgress: (Double) -> Void = { (batchProgress) in
progress += batchProgress
self.fireProgress(progress: progress, progressTotal: progressTotal)
}
// process all events first
for row in progressFilesEvents {
if isTestProject {
try importFile(fileDefinition: row, markIdsImported: markIdsImported, updateProgress: updateFileProgress)
} else {
queueGroup.enter()
queue.async(group: queueGroup) {
do {
try importFile(fileDefinition: row, markIdsImported: markIdsImported, updateProgress: updateFileProgress)
queueGroup.leave()
} catch {
print("Failed to import", error)
}
}
}
}
// wait for finish
queueGroup.wait()
for row in progressFilesOther {
if isTestProject {
try importFile(fileDefinition: row, markIdsImported: markIdsImported, updateProgress: updateFileProgress)
} else {
queueGroup.enter()
queue.async(group: queueGroup) {
do {
try importFile(fileDefinition: row, markIdsImported: markIdsImported, updateProgress: updateFileProgress)
queueGroup.leave()
} catch let error {
print("Failed to import", error)
}
}
}
}
// wait for finish
queueGroup.wait()
// remove any old entries not included in this update
// (this is unsupported in XCTest inMemoryStore)
if !isTestProject {
for (type, ids) in deleteOldIds {
_ = deleteAllIds(type: type, ids: ids, with: manager)
}
}
}
func processImportedData(progress: Double, progressTotal: Double) {
fireProgress(progress: progress, progressTotal: progressTotal)
let queue = DispatchQueue.global(qos: .userInitiated)
let queueGroup = DispatchGroup()
var tempProgress1 = 0.0
var tempProgress2 = 0.0
let updateProgress1: ((Double, Bool) -> Void) = { (chunkProgress, isCompleted) in
if isCompleted {
tempProgress1 = self.progressProcessImportChunk
self.fireProgress(progress: progress + tempProgress2 + tempProgress1, progressTotal: progressTotal)
} else {
tempProgress1 += chunkProgress
self.fireProgress(
progress: progress + tempProgress2 + tempProgress1,
progressTotal: progressTotal
)
}
}
let updateProgress2: ((Double, Bool) -> Void) = { (chunkProgress, isCompleted) in
if isCompleted {
tempProgress2 = self.progressProcessImportChunk
self.fireProgress(progress: progress + tempProgress2 + tempProgress1, progressTotal: progressTotal)
} else {
tempProgress2 += chunkProgress
self.fireProgress(
progress: progress + tempProgress2 + tempProgress1,
progressTotal: progressTotal
)
}
}
if isTestProject {
// XCTest has some multithreading issues, where the queueGroup wait blocks the Core Data wait.
// So we will run it synchronously.
processImportedMapData(queue: queue, updateProgress: updateProgress1)
processImportedMissionData(queue: queue, updateProgress: updateProgress2)
} else {
// Queue #1
queueGroup.enter()
queue.async(group: queueGroup) {
self.processImportedMapData(queue: queue, updateProgress: updateProgress1)
queueGroup.leave()
}
// Queue #2
queueGroup.enter()
queue.async(group: queueGroup) {
self.processImportedMissionData(queue: queue, updateProgress: updateProgress2)
queueGroup.leave()
}
// wait for finish
queueGroup.wait()
}
// TODO: delete orphan game data?
fireProgress(progress: progressTotal, progressTotal: progressTotal)
}
func importFile(
fileDefinition: CoreDataFileImport,
markIdsImported: @escaping ((BaseDataFileImportType, [String]) -> Void),
updateProgress: @escaping ((Double) -> Void)
) throws {
let type = fileDefinition.type
let filename = fileDefinition.filename
let batchProgress = fileDefinition.progress
do {
if let file = Bundle.main.path(forResource: filename, ofType: "json") {
let data = try Data(contentsOf: URL(fileURLWithPath: file))
let ids = try importData(data, with: manager)
markIdsImported(type, ids)
}
} catch let error {
// failure
print("Failed to load file \(filename)")
if (App.current.isDebug) {
throw error;
}
}
updateProgress(batchProgress)
}
func processImportedMapData(
queue: DispatchQueue,
updateProgress: @escaping ((Double, Bool) -> Void)
) {
let manager = self.manager
let mapsCount = DataMap.getCount(with: manager)
var countProcessed: Int = 0
let chunkSize: Int = 20
let chunkPercentage = Double(chunkSize) / Double(mapsCount)
let chunkProgress = Double(self.progressProcessImportChunk) * chunkPercentage
for map in DataMap.getAll(with: manager, alterFetchRequest: { fetchRequest in
// fetchRequest.predicate = NSPredicate(format: "(inMapId == nil)")
fetchRequest.predicate = NSPredicate(format: "(relatedEvents.@count > 0)")
}) {
self.applyInheritedEvents(
map: map,
inheritableEvents: map.getInheritableEvents(),
runOnEachMapBlock: {
if countProcessed > 0 && countProcessed % chunkSize == 0 {
// notify chunk done
queue.sync {
updateProgress(chunkProgress, false)
}
}
countProcessed += 1
}
)
}
// notify all done
queue.sync {
updateProgress(0, true)
}
}
func processImportedMissionData(
queue: DispatchQueue,
updateProgress: @escaping ((Double, Bool) -> Void)
) {
let manager = self.manager
let missionsCount = DataMission.getCount(with: manager)
var countProcessed: Int = 0
let chunkSize: Int = 20
let chunkPercentage = Double(chunkSize) / Double(missionsCount)
let chunkProgress = Double(self.progressProcessImportChunk) * chunkPercentage
for mission in DataMission.getAll(with: manager, alterFetchRequest: { fetchRequest in
// fetchRequest.predicate = NSPredicate(format: "(inMissionId == nil)")
fetchRequest.predicate = NSPredicate(format: "(relatedEvents.@count > 0)")
}) {
self.applyInheritedEvents(
mission: mission,
inheritableEvents: mission.getInheritableEvents(),
runOnEachMissionBlock: {
if countProcessed > 0 && countProcessed % chunkSize == 0 {
// notify chunk done
queue.sync {
updateProgress(chunkProgress, false)
}
}
countProcessed += 1
}
)
}
// notify all done
queue.sync {
updateProgress(0, true)
}
}
//TODO: Protocol events and generic this function
// Note: items and persons don't inherit, so ignore them here
func applyInheritedEvents(
map: DataMap,
inheritableEvents: [CodableDictionary],
level: Int = 0,
runOnEachMapBlock: @escaping (() -> Void)
) {
guard !inheritableEvents.isEmpty else { return }
var maps: [DataMap] = []
for (var childMap) in DataMap.getAll(with: manager, alterFetchRequest: { fetchRequest in
fetchRequest.predicate = NSPredicate(format: "(inMapId = %@)", map.id)
}) {
var eventData = childMap.rawEventDictionary.map { $0.dictionary }
var isChanged = false
for event in inheritableEvents where !eventData.contains(where: {
$0["id"] as? String == event["id"] as? String && $0["type"] as? String == event["type"] as? String
}) {
eventData.append(event.dictionary)
isChanged = true
}
var childInheritableEvents = inheritableEvents + childMap.getInheritableEvents()
while let index = eventData.firstIndex(where: { $0["eraseParentValue"] as? Bool == true }) {
let event = eventData.remove(at: index)
if let index2 = childInheritableEvents.firstIndex(where: { event["id"] as? String == $0["id"] as? String }) {
childInheritableEvents.remove(at: index2)
}
isChanged = true
}
if isChanged {
childMap.rawEventDictionary = eventData.map { CodableDictionary($0) }
maps.append(childMap)
}
runOnEachMapBlock()
self.applyInheritedEvents(
map: childMap,
inheritableEvents: childInheritableEvents,
level: level + 1,
runOnEachMapBlock: runOnEachMapBlock
)
}
_ = DataMap.saveAll(items: maps, with: manager)
var items: [DataItem] = []
for (var childItem) in DataItem.getAll(with: manager, alterFetchRequest: { fetchRequest in
fetchRequest.predicate = NSPredicate(format: "(inMapId = %@)", map.id)
}) {
var eventData = childItem.rawEventDictionary.map { $0.dictionary }
var isChanged = false
for event in inheritableEvents where !eventData.contains(where: {
$0["id"] as? String == event["id"] as? String && $0["type"] as? String == event["type"] as? String
}) {
eventData.append(event.dictionary)
isChanged = true
}
while let index = eventData.firstIndex(where: { $0["eraseParentValue"] as? Bool == true }) {
eventData.remove(at: index)
isChanged = true
}
if isChanged {
childItem.rawEventDictionary = eventData.map { CodableDictionary($0) }
items.append(childItem)
}
// no child item inheritance
}
_ = DataItem.saveAll(items: items, with: manager)
}
func applyInheritedEvents(
mission: DataMission,
inheritableEvents: [CodableDictionary],
level: Int = 0,
runOnEachMissionBlock: @escaping (() -> Void)
) {
guard !inheritableEvents.isEmpty else { return }
var missions: [DataMission] = []
for (var childMission) in DataMission.getAll(with: manager, alterFetchRequest: { fetchRequest in
fetchRequest.predicate = NSPredicate(format: "(inMissionId = %@)", mission.id)
}) {
var eventData = childMission.rawEventDictionary.map { $0.dictionary }
var isChanged = false
for event in inheritableEvents where !eventData.contains(where: {
$0["id"] as? String == event["id"] as? String && $0["type"] as? String == event["type"] as? String
}) {
eventData.append(event.dictionary)
isChanged = true
}
var childInheritableEvents = inheritableEvents + childMission.getInheritableEvents()
while let index = eventData.firstIndex(where: { $0["eraseParentValue"] as? Bool == true }) {
let event = eventData.remove(at: index)
if let index2 = childInheritableEvents.firstIndex(where: { event["id"] as? String == $0["id"] as? String }) {
childInheritableEvents.remove(at: index2)
}
isChanged = true
}
if isChanged {
childMission.rawEventDictionary = eventData.map { CodableDictionary($0) }
missions.append(childMission)
}
runOnEachMissionBlock()
self.applyInheritedEvents(
mission: childMission,
inheritableEvents: childInheritableEvents,
level: level + 1,
runOnEachMissionBlock: runOnEachMissionBlock
)
}
_ = DataMission.saveAll(items: missions, with: manager)
var items: [DataItem] = []
for (var childItem) in DataItem.getAll(with: manager, alterFetchRequest: { fetchRequest in
fetchRequest.predicate = NSPredicate(format: "(inMissionId = %@)", mission.id)
}) {
var eventData = childItem.rawEventDictionary.map { $0.dictionary }
var isChanged = false
for event in inheritableEvents where !eventData.contains(where: {
$0["id"] as? String == event["id"] as? String && $0["type"] as? String == event["type"] as? String
}) {
eventData.append([
"id": event["id"] as? String,
"type": event["type"] as? String,
"eraseParentValue": event["eraseParentValue"] as? Bool ?? false,
])
isChanged = true
}
while let index = eventData.firstIndex(where: { $0["eraseParentValue"] as? Bool == true }) {
eventData.remove(at: index)
isChanged = true
}
if isChanged {
childItem.rawEventDictionary = eventData.map { CodableDictionary($0) }
items.append(childItem)
}
// no child item inheritance
}
_ = DataItem.saveAll(items: items, with: manager)
}
}
|
mit
|
1eeb36a05dddf49a72db786ffbe869c4
| 39.74026 | 129 | 0.611625 | 4.219233 | false | false | false | false |
mrommel/MiRoRecipeBook
|
MiRoRecipeBook/MiRoRecipeBook/Presentation/Recipes/RecipeDetailTableViewDatasource.swift
|
1
|
3066
|
//
// IngredientsAndStepsTableViewDataSource.swift
// MiRoRecipeBook
//
// Created by Michael Rommel on 15.12.16.
// Copyright © 2016 MiRo Soft. All rights reserved.
//
import UIKit
class RecipeDetailTableViewDatasource: NSObject, UITableViewDataSource {
let recipeManager = RecipeManager()
var recipe: Recipe?
var steps: [RecipeStep]?
var ingredients: [RecipeIngredient]?
var scale: Float = 1.0
init(forRecipe recipe: Recipe?, scale: Float) {
super.init()
self.recipe = recipe
self.steps = recipe?.getSteps()
self.ingredients = recipe?.getRecipeIngredients()
self.scale = scale
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return self.ingredients!.count
} else {
return self.steps!.count
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func getRecipeIngredient(withIndex index: Int) -> RecipeIngredient {
return self.ingredients![index]
}
func getRecipeStepText(withIndex index: Int) -> String {
return self.steps![index].text!
}
func format(_ recipeIngredient: RecipeIngredient?) -> String {
let amount: Float? = recipeIngredient?.quantity
let type: String? = recipeIngredient?.type
let quantity = Quantity.init(withQuantity: amount!, andType: type!)
return quantity.format(withScale: self.scale)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ingredientCell", for: indexPath) as! RecipeTableViewCell
cell.selectionStyle = .none
if indexPath.section == 0 {
let recipeIngredient = self.getRecipeIngredient(withIndex: indexPath.row)
let ingredient = recipeManager.getIngredient(withIdentifier: recipeIngredient.ingredient_identifier)
cell.recipeTitleLabel?.text = ingredient?.name
cell.recipeDescriptionLabel?.text = self.format(recipeIngredient)
cell.recipeDescriptionLabel?.isHidden = false
if ingredient?.getImageUrl() != nil {
cell.imageView?.setImage(with: (ingredient?.getImageUrl())!, placeholder: UIImage(named: "recipe-default-image.png"))
}
} else {
let text = self.getRecipeStepText(withIndex: indexPath.row)
cell.recipeTitleLabel?.text = text
cell.recipeDescriptionLabel?.isHidden = true
cell.imageView?.image = UIImage.init(named: "number\(indexPath.row).png")
/*if ingredient?.getImageUrl() != nil {
cell.imageView?.setImage(withUrl: (ingredient?.getImageUrl())!, placeholder: UIImage(named: "recipe-default-image.png"), crossFadePlaceholder: false, cacheScaled: false)
}*/
}
return cell
}
}
|
gpl-3.0
|
a8e3d988e334271b3e29b54d6a93ae39
| 35.488095 | 182 | 0.634258 | 4.904 | false | false | false | false |
nicolastinkl/swift
|
ListerAProductivityAppBuiltinSwift/Lister/ListViewController.swift
|
1
|
16709
|
/*
Copyright (C) 2014 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Displays the contents of a list document, allows a user to create, update, and delete items, change the color of the list, or delete the list.
*/
import UIKit
import NotificationCenter
import ListerKit
@objc protocol ListViewControllerDelegate {
func listViewControllerDidDeleteList(listViewController: ListViewController)
}
class ListViewController: UITableViewController, UITextFieldDelegate, ListColorCellDelegate, ListDocumentDelegate {
// MARK: Types
struct Notifications {
struct ListColorDidChange {
static let name = "ListDidUpdateColorNotification"
static let colorUserInfoKey = "ListDidUpdateColorUserInfoKey"
static let URLUserInfoKey = "ListDidUpdateURLUserInfoKey"
}
}
struct MainStoryboard {
struct TableViewCellIdentifiers {
static let listItemCell = "listItemCell" // used for normal items and the add item cell
static let listColorCell = "listColorCell" // used in edit mode to allow the user to change colors
}
}
// MARK: Properties
weak var delegate: ListViewControllerDelegate?
var document: ListDocument!
var documentURL: NSURL {
return document.fileURL
}
var list: List {
return document.list
}
// Lazily load and cache the toolbar items since they are used in edit mode (possibly more than once).
@lazy var listToolbarItems: UIBarButtonItem[] = {
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
let title = NSLocalizedString("Delete List", comment: "The title of the button to delete the current list.")
let deleteList = UIBarButtonItem(title: title, style: .Plain, target: self, action: "deleteList:")
return [flexibleSpace, deleteList, flexibleSpace]
}()
var textAttributes: Dictionary<String, AnyObject> = [:] {
didSet {
if isViewLoaded() {
updateInterfaceWithTextAttributes()
}
}
}
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
updateInterfaceWithTextAttributes()
// Use the edit button item provided by the table view controller.
navigationItem.rightBarButtonItem = editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
document.openWithCompletionHandler { success in
if !success {
// In your app you should handle this gracefully.
NSLog("Couldn't open document: \(self.documentURL.absoluteString).")
abort()
}
self.tableView.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleDocumentStateChangedNotification:", name: UIDocumentStateChangedNotification, object: self.document)
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
document.closeWithCompletionHandler(nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDocumentStateChangedNotification, object: document)
// Hide the toolbar so the list can't be edited.
navigationController.setToolbarHidden(true, animated: animated)
}
// MARK: Setup
func configureWithListInfo(listInfo: ListInfo) {
listInfo.fetchInfoWithCompletionHandler { [weak self] in
if let strongSelf = self {
strongSelf.document = ListDocument(fileURL: listInfo.URL)
strongSelf.document.delegate = self
strongSelf.navigationItem.title = listInfo.name
strongSelf.textAttributes = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline),
NSForegroundColorAttributeName: listInfo.color!.colorValue
]
}
}
}
// MARK: Notifications
func handleDocumentStateChangedNotification(_: NSNotification) {
let state = document.documentState
if state & .InConflict {
resolveConflicts()
}
// Passing `tableView.reloadData` passes the table view's reloadData method as a () -> Void closure
// to the dispatch_async method.
dispatch_async(dispatch_get_main_queue(), tableView.reloadData)
}
// MARK: UIViewController Overrides
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
// Prevent navigating back in edit mode.
navigationItem.setHidesBackButton(editing, animated: animated)
// Reload the first row to switch from "Add Item" to "Change Color"
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
// If moving out of edit mode, notify observers about the list color and trigger a save.
if !editing {
// Notify the document of a change.
document.updateChangeCount(.Done)
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.ListColorDidChange.name, object: nil, userInfo: [
Notifications.ListColorDidChange.colorUserInfoKey: list.color.toRaw(),
Notifications.ListColorDidChange.URLUserInfoKey: documentURL
])
triggerNewDataForWidget()
}
navigationController.setToolbarHidden(!editing, animated: animated)
navigationController.toolbar.setItems(listToolbarItems, animated: animated)
}
// MARK: UITableViewDataSource
override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
// Don't show anything if the document hasn't been loaded.
if !document {
return 0
}
// We show the items in a list, plus a separate row that lets users enter a new item.
return list.count + 1
}
override func tableView(_: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 && editing {
let colorCell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.TableViewCellIdentifiers.listColorCell, forIndexPath: indexPath) as ListColorCell
colorCell.configure()
colorCell.delegate = self
return colorCell
}
else {
let itemCell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.TableViewCellIdentifiers.listItemCell, forIndexPath: indexPath) as ListItemCell
configureListItemCell(itemCell, usingColor: list.color, forRow: indexPath.row)
return itemCell
}
}
func configureListItemCell(itemCell: ListItemCell, usingColor color: List.Color, forRow row: Int) {
itemCell.textField.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
itemCell.textField.delegate = self
if row == 0 {
// Configure an "Add Item" list item cell.
itemCell.textField.placeholder = NSLocalizedString("Add Item", comment: "")
itemCell.checkBox.hidden = true
}
else {
let item = list[row - 1]
itemCell.isComplete = item.isComplete
itemCell.textField.text = item.text
}
}
override func tableView(_: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// The initial row is reserved for adding new items so it can't be deleted or edited.
if indexPath.row == 0 {
return false
}
return true
}
override func tableView(_: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// The initial row is reserved for adding new items so it can't be moved.
if indexPath.row == 0 {
return false
}
return true
}
override func tableView(_: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle != .Delete {
return
}
let item = list[indexPath.row - 1]
list.removeItems([item])
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
triggerNewDataForWidget()
// Notify the document of a change.
document.updateChangeCount(.Done)
}
override func tableView(_: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
let item = list[fromIndexPath.row - 1]
list.moveItem(item, toIndex: toIndexPath.row - 1)
// Notify the document of a change.
document.updateChangeCount(.Done)
}
// MARK: UITableViewDelegate
override func tableView(_: UITableView, willBeginEditingRowAtIndexPath: NSIndexPath) {
// When the user swipes to show the delete confirmation, don't enter editing mode.
// UITableViewController enters editing mode by default so we override without calling super.
}
override func tableView(_: UITableView, didEndEditingRowAtIndexPath: NSIndexPath) {
// When the user swipes to hide the delete confirmation, no need to exit edit mode because we didn't enter it.
// UITableViewController enters editing mode by default so we override without calling super.
}
override func tableView(_: UITableView, targetIndexPathForMoveFromRowAtIndexPath fromIndexPath: NSIndexPath, toProposedIndexPath proposedIndexPath: NSIndexPath) -> NSIndexPath {
let item = list[fromIndexPath.row - 1]
if proposedIndexPath.row == 0 {
let row = item.isComplete ? list.indexOfFirstCompletedItem + 1 : 1
return NSIndexPath(forRow: row, inSection: 0)
}
else if list.canMoveItem(item, toIndex: proposedIndexPath.row - 1, inclusive: false) {
return proposedIndexPath
}
else if item.isComplete {
return NSIndexPath(forRow: list.indexOfFirstCompletedItem + 1, inSection: 0)
}
else {
return NSIndexPath(forRow: list.indexOfFirstCompletedItem, inSection: 0)
}
}
// MARK: UITextFieldDelegate
func textFieldDidEndEditing(textField: UITextField) {
let indexPath = indexPathForView(textField)
if indexPath.row > 0 {
// Edit the item in place.
let item = list[indexPath.row - 1]
// If the contents of the text field at the end of editing is the same as it started, don't trigger an update.
if item.text != textField.text {
item.text = textField.text
triggerNewDataForWidget()
// Notify the document of a change.
document.updateChangeCount(.Done)
}
}
else if !textField.text.isEmpty {
// Adds the item to the top of the list.
let item = ListItem(text: textField.text)
let insertedIndex = list.insertItem(item)
// Update the edit row to show the check box.
let itemCell = tableView.cellForRowAtIndexPath(indexPath) as ListItemCell
itemCell.checkBox.hidden = false
// Insert a new add item row into the table view.
tableView.beginUpdates()
let targetIndexPath = NSIndexPath(forRow: insertedIndex, inSection: 0)
tableView.insertRowsAtIndexPaths([targetIndexPath], withRowAnimation: .Automatic)
tableView.endUpdates()
triggerNewDataForWidget()
// Notify the document of a change.
document.updateChangeCount(.Done)
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
let indexPath = indexPathForView(textField)
// An item must have text to dismiss the keyboard.
if !textField.text.isEmpty || indexPath.row == 0 {
textField.resignFirstResponder()
return true
}
return false
}
// MARK: ListColorCellDelegate
func listColorCellDidChangeSelectedColor(listColorCell: ListColorCell) {
list.color = listColorCell.selectedColor
textAttributes = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline),
NSForegroundColorAttributeName: list.color.colorValue
]
let indexPaths = tableView.indexPathsForVisibleRows()
tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: .None)
}
// MARK: IBActions
func deleteList(UIBarButtonItem) {
delegate?.listViewControllerDidDeleteList(self)
if splitViewController?.collapsed {
navigationController?.popViewControllerAnimated(true)
}
}
@IBAction func checkBoxTapped(sender: CheckBox) {
let indexPath = indexPathForView(sender)
// This ~= operator ensures that indexPath.row is found in the range on the right.
if 1...list.count ~= indexPath.row {
let item = list[indexPath.row - 1]
let (fromIndex, toIndex) = list.toggleItem(item)
if fromIndex == toIndex {
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
else {
// Animate the row up or down depending on whether it was complete/incomplete.
let targetRow = NSIndexPath(forRow: toIndex + 1, inSection: 0)
tableView.beginUpdates()
tableView.moveRowAtIndexPath(indexPath, toIndexPath: targetRow)
tableView.endUpdates()
tableView.reloadRowsAtIndexPaths([targetRow], withRowAnimation: .Automatic)
}
triggerNewDataForWidget()
// Notify the document of a change.
document.updateChangeCount(.Done)
}
}
// MARK: ListDocumentDelegate
func listDocumentWasDeleted(listDocument: ListDocument) {
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: Convenience
func triggerNewDataForWidget() {
if document.localizedName == AppConfiguration.localizedTodayDocumentName {
NCWidgetController.widgetController().setHasContent(true, forWidgetWithBundleIdentifier: AppConfiguration.Extensions.widgetBundleIdentifier)
}
}
func updateInterfaceWithTextAttributes() {
navigationController.navigationBar.titleTextAttributes = textAttributes
navigationController.navigationBar.tintColor = textAttributes[NSForegroundColorAttributeName] as UIColor
navigationController.toolbar.tintColor = textAttributes[NSForegroundColorAttributeName] as UIColor
tableView.tintColor = textAttributes[NSForegroundColorAttributeName] as UIColor
}
func resolveConflicts() {
// Any automatic merging logic or presentation of conflict resolution UI should go here.
// For Lister we'll pick the current version and mark the conflict versions as resolved.
NSFileVersion.removeOtherVersionsOfItemAtURL(self.documentURL, error: nil)
let conflictVersions = NSFileVersion.unresolvedConflictVersionsOfItemAtURL(documentURL) as NSFileVersion[]
for fileVersion in conflictVersions {
fileVersion.resolved = true
}
}
func indexPathForView(view: UIView) -> NSIndexPath {
let viewOrigin = view.bounds.origin
let viewLocation = tableView.convertPoint(viewOrigin, fromView: view)
return tableView.indexPathForRowAtPoint(viewLocation)
}
}
|
mit
|
c70e67d3c810056946adfd8bd93cd16d
| 37.318807 | 184 | 0.636619 | 5.895201 | false | false | false | false |
TeamProxima/predictive-fault-tracker
|
mobile/SieHack/Pods/Charts/Source/Charts/Data/Implementations/Standard/PieChartDataSet.swift
|
11
|
3056
|
//
// PieChartDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class PieChartDataSet: ChartDataSet, IPieChartDataSet
{
@objc(PieChartValuePosition)
public enum ValuePosition: Int
{
case insideSlice
case outsideSlice
}
fileprivate func initialize()
{
self.valueTextColor = NSUIColor.white
self.valueFont = NSUIFont.systemFont(ofSize: 13.0)
}
public required init()
{
super.init()
initialize()
}
public override init(values: [ChartDataEntry]?, label: String?)
{
super.init(values: values, label: label)
initialize()
}
internal override func calcMinMax(entry e: ChartDataEntry)
{
calcMinMaxY(entry: e)
}
// MARK: - Styling functions and accessors
fileprivate var _sliceSpace = CGFloat(0.0)
/// the space in pixels between the pie-slices
/// **default**: 0
/// **maximum**: 20
open var sliceSpace: CGFloat
{
get
{
return _sliceSpace
}
set
{
var space = newValue
if space > 20.0
{
space = 20.0
}
if space < 0.0
{
space = 0.0
}
_sliceSpace = space
}
}
/// indicates the selection distance of a pie slice
open var selectionShift = CGFloat(18.0)
open var xValuePosition: ValuePosition = .insideSlice
open var yValuePosition: ValuePosition = .insideSlice
/// When valuePosition is OutsideSlice, indicates line color
open var valueLineColor: NSUIColor? = NSUIColor.black
/// When valuePosition is OutsideSlice, indicates line width
open var valueLineWidth: CGFloat = 1.0
/// When valuePosition is OutsideSlice, indicates offset as percentage out of the slice size
open var valueLinePart1OffsetPercentage: CGFloat = 0.75
/// When valuePosition is OutsideSlice, indicates length of first half of the line
open var valueLinePart1Length: CGFloat = 0.3
/// When valuePosition is OutsideSlice, indicates length of second half of the line
open var valueLinePart2Length: CGFloat = 0.4
/// When valuePosition is OutsideSlice, this allows variable line length
open var valueLineVariableLength: Bool = true
/// the font for the slice-text labels
open var entryLabelFont: NSUIFont? = nil
/// the color for the slice-text labels
open var entryLabelColor: NSUIColor? = nil
// MARK: - NSCopying
open override func copyWithZone(_ zone: NSZone?) -> AnyObject
{
let copy = super.copyWithZone(zone) as! PieChartDataSet
copy._sliceSpace = _sliceSpace
copy.selectionShift = selectionShift
return copy
}
}
|
mit
|
9704a273bc9d5f99a101c5204b96dd48
| 25.807018 | 96 | 0.61911 | 4.805031 | false | false | false | false |
Esri/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Content Display Logic/Controllers/OptionsTableViewController.swift
|
1
|
6602
|
// Copyright 2018 Esri.
//
// 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
/// A basic interface for selecting one options from a list,
/// showing the checkmark accessory for the selected cell.
class OptionsTableViewController: UITableViewController {
struct Option {
let label: String
let image: UIImage?
init(label: String, image: UIImage? = nil) {
self.label = label
self.image = image
}
}
private let options: [Option]
/// The index of the currently selected option or `nil` if no option is
/// selected.
private var selectedIndex: Int?
private let onChange: (Int?) -> Void
private let allowsEmptySelection: Bool
/// Creates a new instance with the options, selected index, empty selection bool, and selection
/// change handler.
/// - Parameters:
/// - options: The options displayed by the view controller.
/// - selectedIndex: The index of the currently selected option or `nil`.
/// - allowsEmptySelection: A bool to determine if empty selection is allowed. Defaulted to false.
/// - onChange: A closure called when the selected option has changed.
init(options: [Option], selectedIndex: Int?, allowsEmptySelection: Bool = false, onChange: @escaping (Int?) -> Void) {
self.options = options
self.selectedIndex = selectedIndex
self.allowsEmptySelection = allowsEmptySelection
self.onChange = onChange
super.init(nibName: nil, bundle: nil)
}
/// Creates a new instance with the options, selected index, empty selection bool, and selection
/// change handler.
/// - Parameters:
/// - options: The options displayed by the view controller.
/// - selectedIndex: The index of the currently selected option or `nil`.
/// - onChange: A closure called when the selected option has changed.
convenience init(options: [Option], selectedIndex: Int, onChange: @escaping (Int) -> Void) {
self.init(options: options, selectedIndex: selectedIndex, allowsEmptySelection: false, onChange: { onChange($0!) })
}
/// Creates a new instance with the given labels, selected index, empty selection bool, and
/// selection change handler.
/// - Parameters:
/// - labels: An array of labels for the options.
/// - selectedIndex: The index of the currently selected option or `nil`.
/// - onChange: A closure called when the selected option has changed.
convenience init(labels: [String], selectedIndex: Int, onChange: @escaping (Int) -> Void) {
let options = labels.map { Option(label: $0) }
self.init(options: options, selectedIndex: selectedIndex, allowsEmptySelection: false, onChange: { onChange($0!) })
}
/// Creates a new instance with the given labels, selected index, empty selection bool, and
/// selection change handler.
/// - Parameters:
/// - labels: An array of labels for the options.
/// - selectedIndex: The index of the currently selected option or `nil`.
/// - onChange: A closure called when the selected option has changed.
convenience init(labels: [String], selectedIndex: Int?, onChange: @escaping (Int) -> Void) {
let options = labels.map { Option(label: $0) }
self.init(options: options, selectedIndex: selectedIndex, allowsEmptySelection: false, onChange: { onChange($0!) })
}
/// Creates a new instance with the given labels, selected index, empty selection bool, and
/// selection change handler.
/// - Parameters:
/// - labels: An array of labels for the options.
/// - selectedIndex: The index of the currently selected option or `nil`.
/// - allowsEmptySelection: A bool that determines whether or not empty selection is allowed.
/// - onChange: A closure called when the selected option has changed.
convenience init(labels: [String], selectedIndex: Int?, allowsEmptySelection: Bool, onChange: @escaping (Int?) -> Void) {
let options = labels.map { Option(label: $0) }
self.init(options: options, selectedIndex: selectedIndex, allowsEmptySelection: allowsEmptySelection, onChange: onChange)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "OptionCell")
}
// UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return options.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "OptionCell", for: indexPath)
let option = options[indexPath.row]
cell.textLabel?.text = option.label
cell.imageView?.image = option.image
cell.accessoryType = indexPath.row == selectedIndex ? .checkmark : .none
return cell
}
// UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexOfSelectedRow = indexPath.row
let indexOfPreviouslySelectedRow = selectedIndex
if indexOfSelectedRow != selectedIndex {
selectedIndex = indexOfSelectedRow
var indexPathsToReload = [indexPath]
if let row = indexOfPreviouslySelectedRow {
indexPathsToReload.append(IndexPath(row: row, section: indexPath.section))
}
tableView.reloadRows(at: indexPathsToReload, with: .automatic)
onChange(indexPath.row)
} else if allowsEmptySelection {
selectedIndex = nil
tableView.reloadRows(at: [indexPath], with: .automatic)
onChange(nil)
} else {
tableView.deselectRow(at: indexPath, animated: true)
}
}
}
|
apache-2.0
|
4944fa348d63bd410d94d0ffacac701a
| 45.492958 | 129 | 0.669191 | 4.861561 | false | false | false | false |
creister/SwiftCharts
|
Examples/MasterViewController.swift
|
3
|
4764
|
//
// MasterViewController.swift
// SwiftCharts
//
// Created by ischuetz on 20/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
enum Example {
case HelloWorld, Bars, StackedBars, BarsPlusMinus, GroupedBars, BarsStackedGrouped, Scatter, Areas, Bubble, Coords, Target, Multival, Notifications, Combination, Scroll, EqualSpacing, Tracker, MultiAxis, MultiAxisInteractive, CandleStick, Cubiclines, NotNumeric, CandleStickInteractive, CustomUnits, Trendline
}
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var examples: [(Example, String)] = [
(.HelloWorld, "Hello World"),
(.Bars, "Bars"),
(.StackedBars, "Stacked bars"),
(.BarsPlusMinus, "+/- bars with dynamic gradient"),
(.GroupedBars, "Grouped bars"),
(.BarsStackedGrouped, "Stacked, grouped bars"),
(.Combination, "+/- bars and line"),
(.Scatter, "Scatter"),
(.Notifications, "Notifications (interactive)"),
(.Target, "Target point animation"),
(.Areas, "Areas, lines, circles (interactive)"),
(.Bubble, "Bubble, gradient bar mapping"),
(.NotNumeric, "Not numeric values"),
(.Scroll, "Multiline, Scroll"),
(.Coords, "Show touch coords (interactive)"),
(.Tracker, "Track touch (interactive)"),
(.EqualSpacing, "Fixed axis spacing"),
(.CustomUnits, "Custom units, rotated labels"),
(.Multival, "Multiple axis labels"),
(.MultiAxis, "Multiple axes"),
(.MultiAxisInteractive, "Multiple axes (interactive)"),
(.CandleStick, "Candlestick"),
(.CandleStickInteractive, "Candlestick (interactive)"),
(.Cubiclines, "Cubic lines"),
(.Trendline, "Trendline")
]
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.titleTextAttributes = ["NSFontAttributeName" : ExamplesDefaults.fontWithSize(22)]
UIBarButtonItem.appearance().setTitleTextAttributes(["NSFontAttributeName" : ExamplesDefaults.fontWithSize(22)], forState: UIControlState.Normal)
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
let example = self.examples[1]
self.detailViewController?.detailItem = example.0
self.detailViewController?.title = example.1
}
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
func showExample(index: Int) {
let example = self.examples[index]
let controller = segue.destinationViewController as! DetailViewController
controller.detailItem = example.0
controller.title = example.1
}
if let indexPath = self.tableView.indexPathForSelectedRow {
showExample(indexPath.row)
} else {
showExample(0)
}
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
let example = self.examples[indexPath.row]
self.detailViewController?.detailItem = example.0
self.detailViewController?.title = example.1
self.splitViewController?.toggleMasterView()
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return examples.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel!.text = examples[indexPath.row].1
cell.textLabel!.font = ExamplesDefaults.fontWithSize(Env.iPad ? 22 : 16)
return cell
}
}
|
apache-2.0
|
45837d6a9173bf748dee02a10bfa1c46
| 38.371901 | 313 | 0.634131 | 5.438356 | false | false | false | false |
maximveksler/Developing-iOS-8-Apps-with-Swift
|
lesson-012/Dropit/Dropit/DropitViewController.swift
|
1
|
5078
|
//
// DropitViewController.swift
// Dropit
//
// Created by Maxim Veksler on 30/09/2015.
// Copyright © 2015 Stanford University. All rights reserved.
//
import UIKit
class DropitViewController: UIViewController, UIDynamicAnimatorDelegate {
@IBOutlet weak var gameView: BezierPathsView!
lazy var animator: UIDynamicAnimator = {
let lezilyCreatedDynamicAnimator = UIDynamicAnimator(referenceView: self.gameView)
lezilyCreatedDynamicAnimator.delegate = self
return lezilyCreatedDynamicAnimator
}()
let dropitBehaviour = DropitBehavior()
var attachment: UIAttachmentBehavior? {
willSet {
if let attachment = attachment {
animator.removeBehavior(attachment)
gameView.setPath(nil, named: PathNames.Attachment)
}
}
didSet {
if let attachment = attachment {
animator.addBehavior(attachment)
attachment.action = { [unowned self] in
if let attachedView = attachment.items.first as? UIView {
let path = UIBezierPath()
path.moveToPoint(attachment.anchorPoint)
path.addLineToPoint(attachedView.center)
self.gameView.setPath(path, named: PathNames.Attachment)
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
animator.addBehavior(dropitBehaviour)
}
struct PathNames {
static let MiddleBarrier = "Middle Barrier"
static let Attachment = "Attachment"
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let barrierSize = dropSize
let barrierOrigin = CGPoint(x: gameView.bounds.midX-barrierSize.width/2, y: gameView.bounds.midY-barrierSize.height/2)
let path = UIBezierPath(ovalInRect: CGRect(origin: barrierOrigin, size: barrierSize))
dropitBehaviour.addBarrier(path, named: PathNames.MiddleBarrier)
gameView.setPath(path, named: PathNames.MiddleBarrier)
}
func dynamicAnimatorDidPause(animator: UIDynamicAnimator) {
removeCompletedRow()
}
var dropsPerRow = 10
var dropSize: CGSize {
let size = gameView.bounds.size.width / CGFloat(dropsPerRow)
return CGSize(width: size, height: size)
}
@IBAction func drop(sender: UITapGestureRecognizer) {
drop()
}
@IBAction func grabDrop(sender: UIPanGestureRecognizer) {
let gesturePoint = sender.locationInView(gameView)
switch sender.state {
case .Began:
if let viewToAttachTo = lastDroppedView {
attachment = UIAttachmentBehavior(item: viewToAttachTo, attachedToAnchor: gesturePoint)
lastDroppedView = nil
}
case .Changed:
attachment?.anchorPoint = gesturePoint
case .Ended:
attachment = nil
default: break
}
}
var lastDroppedView: UIView?
func drop() {
var frame = CGRect(origin: CGPointZero, size: dropSize)
frame.origin.x = CGFloat.random(dropsPerRow) * dropSize.width
let dropView = UIView(frame: frame)
dropView.backgroundColor = UIColor.random
dropitBehaviour.addDrop(dropView)
lastDroppedView = dropView
}
func removeCompletedRow() {
var dropsToRemove = [UIView]()
var dropFrame = CGRect(x:0, y: gameView.frame.maxY, width: dropSize.width, height: dropSize.height)
repeat {
dropFrame.origin.y -= dropSize.height
dropFrame.origin.x = 0
var dropsFound = [UIView]()
var rowIsComplete = true
for _ in 0 ..< dropsPerRow {
if let hitView = gameView.hitTest(CGPoint(x: dropFrame.midX, y: dropFrame.midY), withEvent: nil) {
if hitView.superview == gameView {
dropsFound.append(hitView)
} else {
rowIsComplete = false
}
}
dropFrame.origin.x += dropSize.width
}
if rowIsComplete {
dropsToRemove += dropsFound
}
} while dropsToRemove.count == 0 && dropFrame.origin.y > 0
for drop in dropsToRemove {
dropitBehaviour.removeDrop(drop)
}
}
}
private extension CGFloat {
static func random(max: Int) -> CGFloat {
return CGFloat(arc4random() % UInt32(max))
}
}
private extension UIColor {
class var random: UIColor {
switch arc4random() % 5 {
case 0: return UIColor.greenColor()
case 1: return UIColor.blueColor()
case 2: return UIColor.orangeColor()
case 3: return UIColor.redColor()
case 4: return UIColor.purpleColor()
default: return UIColor.blackColor()
}
}
}
|
apache-2.0
|
cd49247bab6d823bee2a64161c9a131b
| 31.139241 | 126 | 0.58834 | 4.919574 | false | false | false | false |
abelsanchezali/ViewBuilder
|
ViewBuilderDemo/ViewBuilderDemo/ViewControllers/LayoutPerformanceResultView.swift
|
1
|
1512
|
//
// LayoutPerformanceResultView.swift
// ViewBuilderDemo
//
// Created by Abel Sanchez on 9/18/16.
// Copyright © 2016 Abel Sanchez. All rights reserved.
//
import UIKit
import ViewBuilder
public class LayoutPerformanceResultView: StackPanel {
weak var titleLabel: UILabel!
var resultLabels: [UILabel]!
init() {
super.init(frame: CGRect.zero)
self.loadFromDocument(Constants.bundle.path(forResource: "LayoutPerformanceResultView", ofType: "xml")!)
self.titleLabel = self.documentReferences!["titleLabel"] as! UILabel
self.resultLabels = [self.documentReferences!["result0Label"] as! UILabel,
self.documentReferences!["result1Label"] as! UILabel,
self.documentReferences!["result2Label"] as! UILabel]
resetResults()
}
@objc public var title: String? {
didSet {
titleLabel.text = title
}
}
public func resetResults() {
setResultTime(nil, index: 0)
setResultTime(nil, index: 1)
setResultTime(nil, index: 2)
}
public func setResultTime(_ duration: Double?, index: Int) {
guard let duration = duration else {
resultLabels[index].text = "(none)"
return
}
resultLabels[index].text = NSString(format: "%.2lf seconds", duration) as String
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
8fff6548ee861b5522dca2f16c1f8926
| 28.057692 | 112 | 0.62409 | 4.37971 | false | false | false | false |
elfketchup/SporkVN
|
SporkVN/VN Classes/VNScript.swift
|
1
|
91785
|
//
// VNSScript.swift
// EKVN Swift
//
// Created by James on 10/16/14.
// Copyright (c) 2014 James Briones. All rights reserved.
//
import UIKit
/** DEFINITIONS **/
// Items inside of the script
let VNScriptStartingPoint = "start"
let VNScriptActualScriptKey = "actual script"
// Resource Dictionary
let VNScriptVariablesKey = "variables"
let VNScriptSpritesArrayKey = "sprites" // Stores filenames and sprite positions
// Flags for the script's dictionary. These are normally used for passing in dictionary values, and for when
// the script's data is saved to a dictionary (which can be stored as part of a save file... keep in mind
// that when the game is saved, all the game's data is stored in dictionaries).
let VNScriptConversationNameKey = "conversation name"
let VNScriptFilenameKey = "filename"
let VNScriptIndexesDoneKey = "indexes done"
let VNScriptCurrentIndexKey = "current index"
// The command types, in numeric format
let VNScriptCommandSayLine = 100
let VNScriptCommandAddSprite = 101
let VNScriptCommandSetBackground = 102
let VNScriptCommandSetSpeaker = 103
let VNScriptCommandChangeConversation = 104
let VNScriptCommandJumpOnChoice = 105
let VNScriptCommandShowSpeechOrNot = 106
let VNScriptCommandEffectFadeIn = 107
let VNScriptCommandEffectFadeOut = 108
let VNScriptCommandEffectMoveBackground = 109
let VNScriptCommandEffectMoveSprite = 110
let VNScriptCommandSetSpritePosition = 111
let VNScriptCommandPlaySound = 112
let VNScriptCommandPlayMusic = 113
let VNScriptCommandSetFlag = 114
let VNScriptCommandModifyFlagValue = 115 // Add or subtract
let VNScriptCommandIfFlagHasValue = 116 // An "if" command, really
let VNScriptCommandModifyFlagOnChoice = 117 // Choice changes variable
let VNScriptCommandAlignSprite = 118
let VNScriptCommandRemoveSprite = 119
let VNScriptCommandJumpOnFlag = 120 // Change conversation if a certain flag holds a particular value
let VNScriptCommandSystemCall = 121
let VNScriptCommandCallCode = 122
let VNScriptCommandIsFlagMoreThan = 123
let VNScriptCommandIsFlagLessThan = 124
let VNScriptCommandIsFlagBetween = 125
let VNScriptCommandSwitchScript = 126
let VNScriptCommandSetSpeechFont = 127
let VNScriptCommandSetSpeechFontSize = 128
let VNScriptCommandSetSpeakerFont = 129
let VNScriptCommandSetSpeakerFontSize = 130
// 131 was used by the now-obsolete "cinematic text" mode
let VNScriptCommandSetTypewriterText = 132
let VNScriptCommandSetSpeechbox = 133
let VNScriptCommandSetSpriteAlias = 134
let VNScriptCommandFlipSprite = 135
let VNScriptCommandRollDice = 136
let VNScriptCommandModifyChoiceboxOffset = 137
let VNScriptCommandScaleBackground = 138
let VNScriptCommandScaleSprite = 139
let VNScriptCommandAddToChoiceSet = 140
let VNScriptCommandRemoveFromChoiceSet = 141
let VNScriptCommandWipeChoiceSet = 142
let VNScriptCommandShowChoiceSet = 143
// The command strings. Each one starts with a dot (the parser will only check treat a line as a command if it starts
// with a dot), and is followed by some parameters, separated by colons.
let VNScriptStringAddSprite = ".addsprite" // Adds a sprite to the screen (sprite fades in)
let VNScriptStringSetBackground = ".setbackground" // Changes the background of the visual novel scene
let VNScriptStringSetSpeaker = ".setspeaker" // Determines what name shows up when someone speaks
let VNScriptStringChangeConversation = ".setconversation" // Switches to a different section of the script
let VNScriptStringJumpOnChoice = ".jumponchoice" // Switches to different section based on user choice
let VNScriptStringShowSpeechOrNot = ".showspeech" // Determines whether speech text should be shown
let VNScriptStringEffectFadeIn = ".fadein" // Fades in the scene (background + characters)
let VNScriptStringEffectFadeOut = ".fadeout" // The scene fades out to black
let VNScriptStringEffectMoveBackground = ".movebackground" // Moves/pans the background
let VNScriptStringEffectMoveSprite = ".movesprite" // Moves a sprite around the screen
let VNScriptStringSetSpritePosition = ".setspriteposition" // Sets the sprite's exact position
let VNScriptStringPlaySound = ".playsound" // Plays a sound effect once
let VNScriptStringPlayMusic = ".playmusic" // Plays a sound file on infinite loop
let VNScriptStringSetFlag = ".setflag" // Sets a "flag" (numeric value)
let VNScriptStringModifyFlagValue = ".modifyflag" // Modifies the numeric value of a flag
let VNScriptStringIfFlagHasValue = ".isflag" // Executes another command if a flag has a certain value
let VNScriptStringModifyFlagOnChoice = ".modifyflagbychoice" // Modifies a flag's value based on user input
let VNScriptStringAlignSprite = ".alignsprite" // Repositions a sprite (left, center, or right)
let VNScriptStringRemoveSprite = ".removesprite" // Removes a sprite from the screen
let VNScriptStringJumpOnFlag = ".jumponflag" // Changes script section based on flag value
let VNScriptStringSystemCall = ".systemcall" // Calls a predefined function outside the VN system
let VNScriptStringCallCode = ".callcode" // Call any function (from a static object, usually)
let VNScriptStringIsFlagMoreThan = ".isflagmorethan" // Runs another command if flag is more than a certain value
let VNScriptStringIsFlagLessThan = ".isflaglessthan" // Runs a command if a flag is LESS than a certain value
let VNScriptStringIsFlagBetween = ".isflagbetween" // Runs a command if a flag is between two values
let VNScriptStringSwitchScript = ".switchscript" // Changes to another VNScript (stored in a different .plist file)
let VNScriptStringSetSpeechFont = ".setspeechfont" // Changes speech font
let VNScriptStringSetSpeechFontSize = ".setspeechfontsize" // Changes speech font size
let VNScriptStringSetSpeakerFont = ".setspeakerfont" // Changes the font used by the speaker name
let VNScriptStringSetSpeakerFontSize = ".setspeakerfontsize" // Changes font size for speaker
let VNScriptStringSetTypewriterText = ".settypewritertext" // Typewriter text, in which dialogue appears one character at a time
let VNScriptStringSetSpriteAlias = ".setspritealias" // Assigns a filename to a sprite alias
let VNScriptStringSetSpeechbox = ".setspeechbox" // dynamically change speechbox sprite
let VNScriptStringFlipSprite = ".flipsprite" // flips sprite around (left/right or upside-down)
let VNScriptStringRollDice = ".rolldice" // rolls dice, retrieves value and stores in flag
let VNScriptStringModifyChoiceboxOffset = ".modifychoiceboxoffset" // adds X/Y offset to button coordinates during choices (default = 0,0)
let VNScriptStringScaleBackground = ".scalebackground" // changes background scale
let VNScriptStringScaleSprite = ".scalesprite" // changes sprite scale
let VNScriptStringAddToChoiceSet = ".addtochoiceset" // Adds a line of text choice and script section that it will jump to to a "choice set"
let VNScriptStringRemoveFromChoiceSet = ".removefromchoiceset" // Removes a line of text / jump from a choice set
let VNScriptStringWipeChoiceSet = ".wipechoiceset" // Completely removes a Choice Set (this saves memory)
let VNScriptStringShowChoiceSet = ".showchoiceset" // Shows a series of choices from a set that can be dynamically modified
// Script syntax
let VNScriptSeparationString = ":"
let VNScriptNilValue = "nil"
/** CLASSES **/
class VNScript {
var data: NSMutableDictionary?
var conversation: NSArray?
var filename: String?
var conversationName: String?
// Default set
var currentIndex: Int = 0
var indexesDone: Int = 0
var maxIndexes: Int = 0
var isFinished: Bool = false
//init(nameOfFile:String, withConversationNamed:String) {
//}
// Loads the script from a dictionary with a lot of other data (such as specific conversation names, indexes, etc).
init?(info:NSDictionary) {
let filenameValue:NSString? = info.object(forKey: VNScriptFilenameKey) as? NSString
let conversationValue:NSString? = info.object(forKey: VNScriptConversationNameKey) as? NSString
let currentIndexValue:NSNumber? = info.object(forKey: VNScriptCurrentIndexKey) as? NSNumber
let indexesDoneValue:NSNumber? = info.object(forKey: VNScriptIndexesDoneKey) as? NSNumber
if filenameValue == nil || conversationValue == nil {
print("[VNScript] ERROR: Invalid parameters")
return nil
}
let fileLoadResult:Bool = self.didLoadFile(String(filenameValue!), convoName: conversationValue! as String);
if fileLoadResult == false {
print("[VNScript] ERROR: Could not load file.");
return nil
}
// Copy index values
if (currentIndexValue != nil) {
currentIndex = Int(currentIndexValue!.int32Value)
}
if( indexesDoneValue != nil ) {
indexesDone = Int(indexesDoneValue!.int32Value)
}
}
// Load the script from a Property List (.plist) file in the app bundle. Make sure to not include the ".plist" in the file name.
// For example, if the script is stored as "ThisScript.plist" in the bundle, just pass in "ThisScript" as the parameter.
func didLoadFile( _ nameOfFile:String, convoName:String) -> Bool {
let filepath:String? = Bundle.main.path(forResource: nameOfFile, ofType: "plist")
if filepath == nil {
print("[VNScript] ERROR: Cannot load file; filepath was invalid.")
return false
}
let dict:NSDictionary? = NSDictionary(contentsOfFile: filepath!)
if( dict == nil ) {
print("[VNScript] ERROR: Cannot load file; dictionary data is invalid")
return false
}
self.filename = nameOfFile // Copy filename
// Load the data
prepareScript(dict!)
if changeConversationTo(convoName) == false {
print("[VNScript] WARNING: Could not load conversation named: \(convoName)");
}
// Check if no valid data could be loaded from the file
if( self.data == nil ) {
print("[VNScript] ERROR: Could not load data.")
return false
}
return true
}
// This processes the script, converting the data from its original Property List format into something
// that can be used by VNLayer. (This new, converted format is stored in VNScript's "data" dictionary)
func prepareScript(_ dict:NSDictionary) {
let translatedScript:NSMutableDictionary = NSMutableDictionary(capacity: dict.count)
// Go through each NSArray (conversation) in the script and translate each conversation into something that's
// easier for the program to process. This "outer" for loop will get all the conversation names and the loops
// inside this one will translate each conversation.
for conversationKey in dict.allKeys {
//let loadedArray:NSArray = dict.objectForKey(conversationKey) as NSArray
//if let originalArray = loadedArray as? NSArray {
let originalArray:NSArray = dict.object(forKey: conversationKey) as! NSArray
if( originalArray.count > 0 ) {
let translatedArray:NSMutableArray = NSMutableArray(capacity: originalArray.count)
for someIndex in originalArray {
if let line = someIndex as? NSString {
//println("[line:NSString] \(line)");
let commandFromLine = line.components(separatedBy: VNScriptSeparationString) as NSArray
let translatedLine:NSArray? = analyzedCommand( commandFromLine )
if( translatedLine != nil ) {
translatedArray.add(translatedLine!)
//println("[translated line:NSArray] \(translatedLine!)")
}
}
}
let convoKey:NSString = conversationKey as! NSString
translatedScript.setValue(translatedArray, forKey: convoKey as String)
}
}
//println("[TRANSLATED SCRIPT] \(translatedScript)")
//self.data! = NSDictionary(translatedScript)
//var finishedDict:NSDictionary = NSDictionary(translatedScript)
//data = translatedScript.copy() as? NSMutableDictionary
data = translatedScript
if( data == nil ) {
print("[VNScript] ERROR: Data is invalid.")
}
}
func info() -> NSDictionary {
// Store index data
let indexesDoneValue:NSNumber = NSNumber(value: indexesDone)
let currentIndexValue:NSNumber = NSNumber(value: currentIndex)
// Store other data
let conversationValue:NSString = NSString(string: conversationName!)
let filenameValue:NSString = NSString(string: filename!)
/*let dictForScript:NSDictionary = NSDictionary(dictionaryLiteral: indexesDoneValue,VNScriptIndexesDoneKey,
currentIndexValue,VNScriptCurrentIndexKey,
conversationValue,VNScriptConversationNameKey,
filenameValue, VNScriptFilenameKey)*/
let dictForScript = NSDictionary(dictionary: [ VNScriptIndexesDoneKey :indexesDoneValue,
VNScriptCurrentIndexKey :currentIndexValue,
VNScriptConversationNameKey :conversationValue,
VNScriptFilenameKey :filenameValue])
return dictForScript
}
func changeConversationTo(_ nameOfConversation:String) -> Bool {
if( self.data != nil ) {
conversation = data!.object(forKey: nameOfConversation) as? NSArray
if( conversation != nil ) {
self.conversationName = nameOfConversation
self.currentIndex = 0
self.indexesDone = 0
self.maxIndexes = self.conversation!.count
return true
}
}
return false
}
func commandAtLine(_ line:Int) -> NSArray? {
if( conversation != nil ) {
if( line < conversation!.count) {
return conversation!.object(at: line) as? NSArray
}
}
return nil
}
func currentCommand() -> NSArray? {
if( indexesDone > currentIndex ) {
return nil
}
return commandAtLine(self.indexesDone)
}
func lineShouldBeProcessed() -> Bool {
if indexesDone <= currentIndex {
return true
}
return false
}
func advanceLine() {
indexesDone = indexesDone + 1
}
func advanceIndex() {
currentIndex += 1
}
func currentLine() -> NSArray? {
return commandAtLine(currentIndex)
}
/** SCRIPT TRANSLATION **/
// someCommand is an array of strings
func analyzedCommand(_ command:NSArray) -> NSArray? {
var analyzedArray:NSArray? = nil
var type:NSNumber = NSNumber(value: 0)
let firstString:NSString = command.object(at: 0) as! NSString
let thatFirstStr = firstString as String
//let firstCharacter = Array(thatFirstStr.characters)[0]
//let characterArray = Array(thatFirstStr.characters)
//let characterArray = Array(thatFirstStr.ch)
//let firstCharacter = characterArray[0]
//let firstCharacter = thatFirstStr.first as Character! // this works in Swift4
let firstCharacter = SMStringCharacterAtIndex(thatFirstStr, indexPosition: 0)
if command.count < 2 || firstCharacter != "." {
//var fixedString:NSMutableString = NSMutableString("%@", command.objectAtIndex(0))
var fixedString = "\(thatFirstStr)"
if( command.count > 1 ) {
//for var part = 1; part < command.count; part += 1 {
for part in 1 ..< command.count {
let str:NSString = command.object(at: part) as! NSString
let currentPart = str as String
let fixedSubString = ":\(currentPart)"
fixedString += fixedSubString
}
}
type = VNScriptCommandSayLine as NSNumber
analyzedArray = NSArray(objects: type, fixedString)
return analyzedArray // Return at once, instead of doing more processing
}
// Automatically prepare the action and parameter values. After all, pretty much every command has
// an action string and a first parameter. It's only certain commands that have more parameters than that.
let action:NSString = command.object(at: 0) as! NSString
let parameter1:NSString = command.object(at: 1) as! NSString
if( action.caseInsensitiveCompare(VNScriptStringAddSprite) == ComparisonResult.orderedSame ) {
// Function definition
//
// Name: .ADDSPRITE
//
// Uses Cocos2D to add a sprite to the screen. By default, the sprite usually appears right
// at the center of the screen.
//
// Parameters:
//
// #1: Sprite name (string) (example: "girl.png")
// Quite simply, the name of a file where the sprite is. Currently, the VN system doesn't
// support sprite sheets, so it needs to be a single image in a single file.
//
// #2: (OPTIONAL) Sprite appears at once? (Boolean value) (example: "NO") (default is NO)
// If set to YES, the sprite appears immediately (no fade-in). If set to NO, then the
// sprite "gradually" fades in (though the fade-in usually takes a second or less).
//
// Example: .addsprite:girl.png:NO
//
var parameter2:NSString = NSString(string: "NO")
// If an existing command was already provided in the script, then overwrite the default one
// with the value found within the script.
if( command.count > 2 ) {
parameter2 = command.object(at: 2) as! NSString
}
// Convert the second parameter to a Boolean value (stored as a Boolean NSNumber object)
let appearParameter:NSNumber = NSNumber(value: parameter2.boolValue)
type = VNScriptCommandAddSprite as NSNumber
analyzedArray = NSArray(objects: type, parameter1, appearParameter)
} else if action.caseInsensitiveCompare(VNScriptStringAlignSprite) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .ALIGNSPRITE
//
// Aligns a particular sprite in either the center, left, or right ends of the screen. This is done
// by finding the center of the sprite and setting the X coordinate to either 25% of the screen's
// width (on the iPhone 4S, this is 480*0.25 or 120), 50% (the middle), or 75% (the right).
//
// There's also the Far Left (the left border of the screen), Far Right (the right border of the screen),
// and Extreme Left and Extremem Right, which are so far that the sprite is drawn offscreen.
//
// Parameters:
//
// #1: Name of sprite (string) (example: "girl.png")
// This is the name of the sprite to manipulate/align. All sprites currently displayed by the
// VN system are kept track of in the scene, so if the sprite exists onscreen, it'll be found.
//
// #2: Alignment name (string) (example: "left") (default is "center")
// Determines whether to move the sprite to the LEFT, CENTER, or RIGHT of the screen.
// (Other, more unusual values also include FAR LEFT, FAR RIGHT, EXTREME LEFT, EXTREME RIGHT)
// It has to be one of those values; partial/percentage values aren't supported.
//
// #2: (OPTIONAL) Alignment duration in SECONDS (double value) (example: "0.5") (Default is 0.5)
// Determines how long it takes for the sprite to move from its current position to the
// new position. Setting it to zero makes the transition instant. Time is measured in seconds.
//
// Example: .alignsprite:girl.png:center
//
// Set default values
var newAlignment:NSString = NSString(string: "center")
var duration:NSString = NSString(string: "0.5")
// Overwrite any default values with any values that have been explicitly written into the script
if( command.count >= 3 ) {
newAlignment = command.object(at: 2) as! NSString // Parameter 2; should be either "left", "center", or "right"
}
if( command.count >= 4 ) {
duration = command.object(at: 3) as! NSString // Optional, default value is 0.5
}
type = VNScriptCommandAlignSprite as NSNumber
let durationToUse:NSNumber = NSNumber(value: duration.doubleValue) // Convert to NSNumber
analyzedArray = NSArray(objects: type, parameter1, newAlignment, durationToUse)
} else if action.caseInsensitiveCompare(VNScriptStringRemoveSprite) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .REMOVESPRITE
//
// Removes a sprite from the screen, assuming that it's part of the VN system's dictionary of
// existing sprite objects.
//
// Parameters:
//
// #1: Name of sprite (string) (example: "girl.png")
// This is the name of the sprite to manipulate/align. All sprites currently displayed by the
// VN system are kept track of in the scene, so if the sprite exists onscreen, it'll be found.
//
// #2: (OPTIONAL) Sprite appears at once (Boolean value) (example: "NO") (Default is NO)
// Determines whether the sprite disappears from the screen instantly or fades out gradually.
//
// Example: .removesprite:girl.png:NO
//
var parameter2:NSString = NSString(string: "NO") // Default value
if( command.count > 2 ) {
parameter2 = command.object(at: 2) as! NSString // Overwrite default value with user-defined one, if it exists
}
// Convert to Boolean NSNumber object
let vanishAtOnce:Bool = parameter2.boolValue
let vanishParameter:NSNumber = NSNumber(value: vanishAtOnce)
// Example: .removesprite:bob:NO
type = VNScriptCommandRemoveSprite as NSNumber
analyzedArray = NSArray(objects: type, parameter1, vanishParameter)
} else if action.caseInsensitiveCompare(VNScriptStringEffectMoveSprite) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .MOVESPRITE
//
// Uses Cocos2D actions to move a sprite by a certain number of points.
//
// Parameters:
//
// (note that all parameters after the first are TECHNICALLY optional, but if you use one,
// you had better call the ones that come before it!)
//
// #1: The name of the sprite to move (string) (example: "girl.png")
//
// #2: Amount to move sprite by X points (float) (example: 128) (default is ZERO)
//
// #3: Amount to move the sprite by Y points (float) (example: 256) (default is ZERO)
//
// #4: Duration in seconds (float) (example: 0.5) (default is 0.5 seconds)
// This measures how long it takes to move the sprite, in seconds.
//
// Example: .movesprite:girl.png:128:-128:1.0
//
// Set default values for extra parameters
var xParameter:NSString = NSString(string: "0")
var yParameter:NSString = NSString(string: "0")
var durationParameter:NSString = NSString(string: "0.5")
// Overwrite default values with ones that exist in the script (assuming they exist, of course)
if( command.count > 2 ) { xParameter = command.object(at: 2) as! NSString; }
if( command.count > 3 ) { yParameter = command.object(at: 3) as! NSString; }
if( command.count > 4 ) { durationParameter = command.object(at: 4) as! NSString; }
// Convert parameters (which are NSStrings) to NSNumber values
let moveByX:NSNumber = NSNumber(value: xParameter.floatValue);
let moveByY:NSNumber = NSNumber(value: yParameter.floatValue);
let duration:NSNumber = NSNumber(value: durationParameter.doubleValue);
// syntax = command:sprite:xcoord:ycoord:duration
type = VNScriptCommandEffectMoveSprite as NSNumber
analyzedArray = NSArray(objects: type, parameter1, moveByX, moveByY, duration)
} else if action.caseInsensitiveCompare(VNScriptStringEffectMoveBackground) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .MOVEBACKGROUND
//
// Uses Cocos2D actions to move the background by a certain number of points. This is normally used to
// pan the background (along the X-axis), but you can move the background up and down as well. Character
// sprites can also be moved along with the background, though usually at a slightly different rate;
// the rate is referred to as the "parallax factor." A parallax factor of 1.0 means that the character
// sprites move just as quickly as the background does, while a factor 0.0 means that the character
// sprites do not move at all.
//
// Parameters:
//
// #1: Amount to move sprite by X points (float) (example: 128) (default is ZERO)
//
// #2: Amount to move the sprite by Y points (float) (OPTIONAL) (example: 256) (default is ZERO)
//
// #3: Duration in seconds (float) (OPTIONAL) (example: 0.5) (default is 0.5 seconds)
// This measures how long it takes to move the sprite, in seconds.
//
// #4: Parallax factor (float) (OPTIONAL) (example: 0.5) (default is 0.95)
// The rate at which sprites move compared to the background. 1.00 means that the
// sprites move at exactly the same rate as the background, while 0.00 means that
// the sprites do not move at all. You'll probably want to set it something in between.
//
// Example: .movebackground:100:0:1.0
//
/*var xParameter = NSString(string: "0")
var yParameter = NSString(string: "0")
var durationParameter = NSString(string: "0.5")
var parallaxFactor = NSString(string: "0.95")
if( command.count > 1 ) {
xParameter = command.objectAtIndex(1) as NSString
}
if( command.count > 2 ) {
yParameter = command.objectAtIndex(2) as NSString
}
if( command.count > 3 ) {
durationParameter = command.objectAtIndex(3) as NSString
}
if( command.count > 4 ) {
parallaxFactor = command.objectAtIndex(4) as NSString
}
// Convert to NSNumber
var moveByX = NSNumber(float: xParameter.floatValue)
var moveByY = NSNumber(float: yParameter.floatValue)
var duration = NSNumber(double: durationParameter.doubleValue)
var parallaxing = NSNumber(float: parallaxFactor.floatValue)
// Load to array
type = VNScriptCommandEffectMoveBackground
analyzedArray = NSArray(objects: type, moveByX, moveByY, duration, parallaxing)*/
// Set default values for extra parameters
var xParameter:NSString = NSString(string: "0")
var yParameter:NSString = NSString(string: "0")
var durationParameter:NSString = NSString(string: "0.5")
var parallaxFactor:NSString = NSString(string: "0.95")
// Overwrite default values with ones that exist in the script (assuming they exist, of course)
if( command.count > 1 ) { xParameter = command.object(at: 1) as! NSString; }
if( command.count > 2 ) { yParameter = command.object(at: 2) as! NSString; }
if( command.count > 3 ) { durationParameter = command.object(at: 3) as! NSString; }
if( command.count > 4 ) { parallaxFactor = command.object(at: 4) as! NSString; }
// Convert parameters (which are NSStrings) to NSNumber values
let moveByX:NSNumber = NSNumber(value: xParameter.floatValue);
let moveByY:NSNumber = NSNumber(value: yParameter.floatValue);
let duration:NSNumber = NSNumber(value: durationParameter.doubleValue);
let parallaxing:NSNumber = NSNumber(value: parallaxFactor.floatValue);
// syntax = command:xcoord:ycoord:duration:parallaxing
type = VNScriptCommandEffectMoveBackground as NSNumber
analyzedArray = NSArray(objects: type, moveByX, moveByY, duration, parallaxing);
} else if action.caseInsensitiveCompare(VNScriptStringSetSpritePosition) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .SETSPRITEPOSITION
//
// NOTE that unlike .MOVESPRITE, this call is instantaneous. I don't remember why I made it that
// way (probably since sprites usually don't move instantly in most visual novels), but it's probably
// best to keep things simple like that anyways.
//
// Parameters:
//
// #1: The name of the sprite (string) (example: "girl.png")
//
// #2: The sprite's X coordinate, in points (float) (example: 10)
//
// #3: The sprite's Y coordinate, in points (float) (example: 10)
//
// Example: .setspriteposition:girl.png:100:100
//
var xParameter:NSString = NSString(string: "0");
var yParameter:NSString = NSString(string: "0");
if( command.count > 2 ) { xParameter = command.object(at: 2) as! NSString }
if( command.count > 3 ) { yParameter = command.object(at: 3) as! NSString }
let coordinateX:NSNumber = NSNumber(value: xParameter.floatValue);
let coordinateY:NSNumber = NSNumber(value: yParameter.floatValue);
type = VNScriptCommandSetSpritePosition as NSNumber
analyzedArray = NSArray(objects: type, parameter1, coordinateX, coordinateY)
} else if action.caseInsensitiveCompare(VNScriptStringSetBackground) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .SETBACKGROUND
//
// Changes whatever image (if any) is used as the background. You can set this to 'nil' which removes
// the background entirely, and shows whatever is behind. This is useful if you're overlaying the VN
// scene over an existing Cocos2D layer/scene node.
//
// Unlike some of the other image-switching commands, this one is supposed to do the change instantly.
// It might be helpful to fade-out and then fade-in the scene during transistions so that the background
// change isn't too jarring for the person playing the game.
//
// Parameters:
//
// #1: The name of the background image (string) (example: "beach.png")
//
// Example: .setbackground:beach.png
//type = @VNScriptCommandSetBackground;
//analyzedArray = @[type, parameter1];
type = VNScriptCommandSetBackground as NSNumber
analyzedArray = NSArray(objects: type, parameter1)
//} else if ( [action caseInsensitiveCompare:VNScriptStringSetSpeaker] == NSOrderedSame ) {
} else if action.caseInsensitiveCompare(VNScriptStringSetSpeaker) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .SETSPEAKER
//
// The "speaker name" is the title of the person speaking. If you set this to "nil" then it
// removes whatever the previous speaker name was.
//
// Parameters:
//
// #1: The name of the character speaking (string) (example: "Harry Potter")
//
// Example: .setspeaker:John Smith
//
//type = @VNScriptCommandSetSpeaker;
//analyzedArray = @[type, parameter1];
type = VNScriptCommandSetSpeaker as NSNumber
analyzedArray = NSArray(objects: type, parameter1)
//} else if ( [action caseInsensitiveCompare:VNScriptStringChangeConversation] == NSOrderedSame ) {
} else if action.caseInsensitiveCompare(VNScriptStringChangeConversation) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .SETCONVERSATION
//
// This jumps to a new conversation. The beginning conversation name is "start" and the other
// arrays in the script's Property List represent other conversations.
//
// Parameters:
//
// #1: The name of the conversation/array to switch to (string) (example: "flirt sequence")
//
// Example: .setconversation:flirt sequence
//
//type = @VNScriptCommandChangeConversation;
//analyzedArray = @[type, parameter1];
type = VNScriptCommandChangeConversation as NSNumber
analyzedArray = NSArray(objects: type, parameter1)
//} else if ( [action caseInsensitiveCompare:VNScriptStringJumpOnChoice] == NSOrderedSame ) {
} else if action.caseInsensitiveCompare(VNScriptStringJumpOnChoice) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .JUMPONCHOICE
//
// This presents the player with multiple choices. Each choice causes the scene to jump to a different
// "conversation" (or rather, an array in the script dictionary). The function can have multipe parameters,
// but the number should always be even-numbered.
//
// Parameters:
//
// #1: The name of the first action (shows up on button when player decides) (string) (example: "Run away")
//
// #2: The name of the conversation to jump to (string) (example: "fleeing sequence")
//
// ...these variables can be repeated multiple times.
//
// Example: .JUMPONCHOICE:"Hug someone":hug sequence:"Glomp someone":glomp sequence
//
/*
var numberOfChoices = (command.count - 1) / 2
// Check if there's not enough data
if numberOfChoices < 1 || command.count < 3 {
return nil
}
var choiceText = NSMutableArray(capacity: numberOfChoices)
var destinations = NSMutableArray(capacity: numberOfChoices)
for var i = 0; i < numberOfChoices; i++ {
var indexOfChoice = 1 + (2 * i)
choiceText.addObject(command.objectAtIndex(indexOfChoice))
destinations.addObject(command.objectAtIndex(indexOfChoice+1))
}
type = VNScriptCommandJumpOnChoice
analyzedArray = NSArray(objects: type, choiceText, destinations)*/
// Figure out how many choices there are
let numberOfChoices:Int = (command.count - 1) / 2;
// Check if there's not enough data
if( numberOfChoices < 1 || command.count < 3 ) {
return nil;
}
// Create some arrays; one will hold the text that appears to the player, while the other will hold
// the names of the conversations/arrays that the script will switch to depending on the player's choice.
let choiceText:NSMutableArray = NSMutableArray(capacity: numberOfChoices)
let destinations:NSMutableArray = NSMutableArray(capacity: numberOfChoices)
// After determining the number of choices that exist, use a loop to match each choice text with the
// name of the conversation that each choice would correspond to. Then add both to the appropriate arrays.
for i in 0 ..< numberOfChoices { //for( int i = 0; i < numberOfChoices; i++ ) {
// This variable will hold 1 and then every odd number after. It starts at one because index "zero"
// is where the actual .JUMPONCHOICE string is stored.
let indexOfChoice = 1 + (2 * i);
// Add choice data to the two separate arrays
choiceText.add( command.object(at: indexOfChoice) )//[choiceText addObject:[command objectAtIndex:indexOfChoice]];
destinations.add( command.object(at: indexOfChoice+1) )
}
type = VNScriptCommandJumpOnChoice as NSNumber
analyzedArray = NSArray(objects: type, choiceText, destinations)
} else if action.caseInsensitiveCompare(VNScriptStringShowSpeechOrNot) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .SHOWSPEECH
//
// Determines whether or not to show the speech (and accompanying speech-box or speech-area). You
// can set it to NO if you don't want any text to show up.
//
// Parameters:
//
// #1: Whether or not to show the speech box (Boolean)
//
// Example: .SHOWSPEECH:NO
//
// Convert parameter from NSString to a Boolean NSNumber
/*BOOL showParameter = [parameter1 boolValue];
NSNumber* parameterObject = @(showParameter);
type = @VNScriptCommandShowSpeechOrNot;
analyzedArray = @[type, parameterObject];*/
let parameterObject = NSNumber(value: parameter1.boolValue)
type = VNScriptCommandShowSpeechOrNot as NSNumber
analyzedArray = NSArray(objects: type, parameterObject)
} else if action.caseInsensitiveCompare(VNScriptStringEffectFadeIn) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .FADEIN
//
// Uses Cocos2D to fade-out the VN scene's backgrounds and sprites... and nothing else (UI
// elements like speech text are unaffected).
//
// Parameters:
//
// #1: Duration of fade-in sequence, in seconds (double)
//
// Example: .FADEIN:0.5
//
/*
// Convert from NSString to NSNumber
double fadeDuration = [parameter1 doubleValue]; // NSString gets converted to a 'double' by this
NSNumber* durationObject = @(fadeDuration);
type = @VNScriptCommandEffectFadeIn;
analyzedArray = @[type, durationObject];*/
let durationObject = NSNumber(value: parameter1.doubleValue)
type = VNScriptCommandEffectFadeIn as NSNumber
analyzedArray = NSArray(objects: type, durationObject)
} else if action.caseInsensitiveCompare(VNScriptStringEffectFadeOut) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .FADEOUT
//
// Uses Cocos2D to fade-out the VN scene's backgrounds and sprites... and nothing else (UI
// elements like speech text are unaffected).
//
// Parameters:
//
// #1: Duration of fade-out sequence, in seconds (double)
//
// Example: .FADEOUT:1.0
//
/*
double fadeDuration = [parameter1 doubleValue];
NSNumber* durationObject = @(fadeDuration);
type = @VNScriptCommandEffectFadeOut;
analyzedArray = @[type, durationObject];*/
let durationObject = NSNumber(value: parameter1.doubleValue)
type = VNScriptCommandEffectFadeOut as NSNumber
analyzedArray = NSArray(objects: type, durationObject)
} else if action.caseInsensitiveCompare(VNScriptStringPlaySound) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .PLAYSOUND
//
// Plays a sound (any type of sound file supported by Cocos2D/SimpleAudioEngine)
//
// Parameters:
//
// #1: name of sound file (string)
//
// Example: .PLAYSOUND:effect1.caf
//
//type = @VNScriptCommandPlaySound;
//analyzedArray = @[type, parameter1];
type = VNScriptCommandPlaySound as NSNumber
analyzedArray = NSArray(objects: type, parameter1)
} else if action.caseInsensitiveCompare(VNScriptStringPlayMusic) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .PLAYMUSIC
//
// Plays background music. May or may not loop. You can also stop any background music
// by calling this with the parameter set to "nil"
//
// Parameters:
//
// #1: name of music filename (string)
// (you can write "nil" to stop all the music)
//
// #2: (Optional) Should this loop forever? (BOOL value) (default is YES)
//
// Example: .PLAYMUSIC:LevelUpper.mp3:NO
//
var parameter2:NSString = NSString(string: "YES") // Loops forever by default
// Check if there's already a user-specified value, in which case that would override the default value
if( command.count > 2 ) {
parameter2 = command.object(at: 2) as! NSString
}
// Convert the second parameter to a Boolean NSNumber, since it was originally stored as a string
let musicLoopsForever:Bool = parameter2.boolValue
let loopParameter:NSNumber = NSNumber(value: musicLoopsForever)
type = VNScriptCommandPlayMusic as NSNumber
analyzedArray = NSArray(objects: type, parameter1, loopParameter)
} else if action.caseInsensitiveCompare(VNScriptStringSetFlag) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .SETFLAG
//
// Used to manually set a "flag" value in the VN system.
//
// Parameters:
//
// #1: Name of flag (string)
//
// #2: The value to set the flag to (integer)
//
// Example: .SETFLAG:number of friends:12
//
var parameter2:NSString = NSString(string: "0") // Default value
if( command.count > 2 ) {
parameter2 = command.object(at: 2) as! NSString
}
// Convert the second parameter to an NSNumber (it was originally an NSString)
let value:NSNumber = NSNumber(value: parameter2.integerValue)
type = VNScriptCommandSetFlag as NSNumber
analyzedArray = NSArray(objects: type, parameter1, value)
} else if action.caseInsensitiveCompare(VNScriptStringModifyFlagValue) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .MODIFYFLAG
//
// Modifies a flag (which stores a numeric, integer value) by another integer. The catch is,
// the modifying value has to be a "literal" number value, and not another flag/variable.
//
// Parameters:
//
// #1: Name of the flag/variable to modify (string)
//
// #2: The number to modify the flag by (integer)
//
// Example: .MODIFYFLAG:number of friends:1
//
var parameter2 = NSString(string: "0")
if( command.count > 2 ) {
parameter2 = command.object(at: 2) as! NSString
}
let modifyWithValue = NSNumber(value: parameter2.integerValue) // Converts from string to integer NSNumber
type = VNScriptCommandModifyFlagValue as NSNumber
analyzedArray = NSArray(objects: type, parameter1, modifyWithValue)
} else if action.caseInsensitiveCompare(VNScriptStringIfFlagHasValue) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .ISFLAG
//
// Checks if a flag matches a certain value. If it does, then it immediately runs another command.
// In theory, you could probably even nest .ISFLAG commands inside each other, but I've never tried
// this before.
//
// Parameters:
//
// #1: Name of flag (string)
//
// #2: Expected value (integer)
//
// #3: Another command
//
// Example: .ISFLAG:number of friends:1:.SETSPEAKER:That One Friend You Have
//
if( command.count < 4 ) {
return nil;
}
let variableName:NSString? = command.object(at: 1) as? NSString
let expectedValue:NSString? = command.object(at: 2) as? NSString
let extraCount:Int = command.count - 3; // This number = secondary command + secondary command's parameters
if( variableName == nil || expectedValue == nil ) {
print("[VNScript] ERROR: Invalid variable name or value in .ISFLAG command");
return nil;
}
// Convert to numerical types
let expectedValueAsNumber = NSNumber(value: expectedValue!.integerValue)
// Now, here comes the hard part... the 3rd "parameter" (and all that follows) is actually a separate
// command that will get executed IF the variable contains the expected value. At this point, it's necessary to
// translate that extra command so it can be more easily run when the actual script gets run for real.
let extraCommand:NSMutableArray = NSMutableArray(capacity: extraCount)
// This loop starts at the command index where the "secondary command" is and then goes through each
// parameter of the second command.
for i in 3 ..< command.count {
// Extract the secondary/"extra" command and put it in its own array
let partOfCommand:NSString = command.object(at: i) as! NSString // 3rd parameter and everything afterwards
extraCommand.add(partOfCommand) // Add that new data to the "extra command" array
}
// Try to make sense of that secondary command... if it doesn't work out, then just give up on translating this line
let secondaryCommand:NSArray? = analyzedCommand(extraCommand)
if( secondaryCommand == nil ) {
print("[VNScript] ERROR: Could not translate secondary command of .ISFLAG");
return nil;
}
type = VNScriptCommandIfFlagHasValue as NSNumber
//analyzedArray = NSArray(objects: type, variableName!, expectedValue!, secondaryCommand!)
analyzedArray = NSArray(objects: type, variableName!, expectedValueAsNumber, secondaryCommand!)
} else if action.caseInsensitiveCompare(VNScriptStringIsFlagMoreThan) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .ISFLAGMORETHAN
//
// Checks if a flag's value is above a certain number. If it is, then a secondary command is run.
//
// Parameters:
//
// #1: Name of flag (string)
//
// #2: Certain number (integer)
//
// #3: Another command
//
// Example: .ISFLAGMORETHAN:power level:9000:.PLAYSOUND:over nine thousand.mp3
//
if( command.count < 4 ) {
return nil;
}
let variableName:NSString? = command.object(at: 1) as? NSString
let expectedValue:NSString? = command.object(at: 2) as? NSString
let extraCount = command.count - 3; // This number = secondary command + secondary command's parameters
if( variableName == nil || expectedValue == nil ) {
print("[VNScript] ERROR: Invalid variable name or value in .ISFLAGMORETHAN command");
return nil;
}
let extraCommand:NSMutableArray = NSMutableArray(capacity: extraCount)
for i in 3 ..< command.count {
let partOfCommand:NSString = command.object(at: i) as! NSString
extraCommand.add(partOfCommand)
}
let secondaryCommand:NSArray? = analyzedCommand(extraCommand)
if( secondaryCommand == nil ) {
print("[VNScript] ERROR: Could not translate secondary command of .ISFLAGMORETHAN");
return nil;
}
// Convert to numerical types
let expectedValueAsNumber = NSNumber(value: expectedValue!.integerValue)
type = VNScriptCommandIsFlagMoreThan as NSNumber
//analyzedArray = NSArray(objects: type, variableName!, expectedValue!, secondaryCommand!)
analyzedArray = NSArray(objects: type, variableName!, expectedValueAsNumber, secondaryCommand!)
} else if action.caseInsensitiveCompare(VNScriptStringIsFlagLessThan) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .ISFLAGLESSTHAN
//
// Checks if a flag's value is below a certain number. If it is, then a secondary command is run.
//
// Parameters:
//
// #1: Name of flag (string)
//
// #2: Certain number (integer)
//
// #3: Another command
//
// Example: .ISFLAGLESSTHAN:time remaining:0:.PLAYMUSIC:time's up.mp3
//
if( command.count < 4 ) {
return nil;
}
let variableName:NSString? = command.object(at: 1) as? NSString
let expectedValue:NSString? = command.object(at: 2) as? NSString
let extraCount = command.count - 3; // This number = secondary command + secondary command's parameters
if( variableName == nil || expectedValue == nil ) {
print("[VNScript] ERROR: Invalid variable name or value in .ISFLAGLESSTHAN command");
return nil;
}
let extraCommand:NSMutableArray = NSMutableArray(capacity: extraCount)
for i in 3 ..< command.count {
let partOfCommand:NSString = command.object(at: i) as! NSString
extraCommand.add(partOfCommand)
}
let secondaryCommand:NSArray? = analyzedCommand(extraCommand)
if( secondaryCommand == nil ) {
print("[VNScript] ERROR: Could not translate secondary command of .ISFLAGLESSTHAN");
return nil;
}
let expectedValueAsNumber = NSNumber(value: expectedValue!.integerValue)
type = VNScriptCommandIsFlagLessThan as NSNumber
//analyzedArray = NSArray(objects: type, variableName!, expectedValue!, secondaryCommand!)
analyzedArray = NSArray(objects: type, variableName!, expectedValueAsNumber, secondaryCommand!)
} else if action.caseInsensitiveCompare(VNScriptStringIsFlagBetween) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .ISFLAGBETWEEN
//
// Checks if a flag's value is between two numbers, and if it is, this will run another command.
//
// Parameters:
//
// #1: Name of flag (string)
//
// #2: First number (integer)
//
// #3: Second number (integer)
//
// #4: Another command
//
// Example: .ISFLAGBETWEEN:number of cookies:1:3:YOU HAVE EXACTLY TWO COOKIES!
//
if( command.count < 5 ) {
return nil;
}
let variableName:NSString? = command.object(at: 1) as? NSString
let firstValue:NSString? = command.object(at: 2) as? NSString
let secondValue:NSString? = command.object(at: 3) as? NSString
let extraCount = command.count - 4; // This number = secondary command + secondary command's parameters
if( variableName == nil || firstValue == nil || secondValue == nil ) {
print("[VNScript] ERROR: Invalid variable name or value in .ISFLAGBETWEEN command");
return nil;
}
// Figure out which value is the lesser value, and which one is the greater value. By default,
// it's assumed first value is the "lesser" value, and the second ond is the "greater" one
let first:Int = firstValue!.integerValue
let second:Int = secondValue!.integerValue
var lesserValue:Int = first
var greaterValue:Int = second
// Check if the default value assignment is wrong. In this case, the second value is the lesser one,
// and that the first value is the greater one.
if( first > second ) {
// Reassign the values appropriately
greaterValue = first;
lesserValue = second;
}
let extraCommand:NSMutableArray = NSMutableArray(capacity: extraCount)
for i in 4 ..< command.count {
let partOfCommand:NSString = command.object(at: i) as! NSString
extraCommand.add(partOfCommand)
}
let secondaryCommand:NSArray? = analyzedCommand(extraCommand)
if( secondaryCommand == nil ) {
print("[VNScript] ERROR: Could not translate secondary command of .ISFLAGBETWEEN");
return nil;
}
// Convert greater/lesser scalar values back into NSString format for the script
//var lesserValueString:NSString = NSString(string: "\(lesserValue)") //[NSString stringWithFormat:@"%d", lesserValue];
//var greaterValueString:NSString = NSString(string: "\(greaterValue)") //[NSString stringWithFormat:@"%d", greaterValue];
let lesserValueNumber = NSNumber(value: lesserValue)
let greaterValueNumber = NSNumber(value: greaterValue)
type = VNScriptCommandIsFlagBetween as NSNumber
//analyzedArray = NSArray(objects: type, variableName!, lesserValueString, greaterValueString, secondaryCommand!)
analyzedArray = NSArray(objects: type, variableName!, lesserValueNumber, greaterValueNumber, secondaryCommand!)
} else if action.caseInsensitiveCompare(VNScriptStringModifyFlagOnChoice) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .MODIFYFLAGBYCHOICE
//
// This presents a choice menu. Each choice causes a particular flag/variable to be changed
// by a particular integer value.
//
// Parameters:
//
// #1: The text that will appear on the choice (string)
//
// #2: The name of the flag/variable to be modified (string)
//
// #3: The amount to modify the flag/variable by (integer)
//
// ...these variables can be repeated multiple times.
//
// Example: .MODIFYFLAGBYCHOICE:"Be nice":niceness:1:"Be rude":niceness:-1
//
// Since the first item in the command array is the ".MODIFYFLAG" string, we'll just ignore that first index
// when counting the number of choices. Also, since each set of parameters consists of three parts (choice text,
// variable name, and variable value), the number will be divided by three to get the actual number of choices.
let numberOfChoices = (command.count - 1) / 3;
// Create some empty mutable arrays
let choiceText:NSMutableArray = NSMutableArray(capacity: numberOfChoices) //[[NSMutableArray alloc] initWithCapacity:numberOfChoices];
let variableNames:NSMutableArray = NSMutableArray(capacity: numberOfChoices) //[[NSMutableArray alloc] initWithCapacity:numberOfChoices];
let variableValues:NSMutableArray = NSMutableArray(capacity: numberOfChoices) //[[NSMutableArray alloc] initWithCapacity:numberOfChoices];
for i in 0 ..< numberOfChoices {
// This is used as an offset in order to get the right index numbers for the 'command' array.
// It starts at 1 and then jumps to every third number thereafter (from 1 to 4, 7, 10, 13, etc).
let nameIndex = 1 + (i * 3);
// Get the parameters for the command array
let text:NSString = command.object(at: nameIndex) as! NSString // Text to show to player
let name:NSString = command.object(at: nameIndex+1) as! NSString // The name of the flag to modify
let check:NSString = command.object(at: nameIndex+2) as! NSString // The amount to modify the flag by
let convertedToNumber = NSNumber(value: check.integerValue)
// Move each value to the appropriate array
choiceText.add(text)
variableNames.add(name)
//variableValues.addObject(check)
variableValues.add(convertedToNumber)
}
type = VNScriptCommandModifyFlagOnChoice as NSNumber
analyzedArray = NSArray(objects: type, choiceText, variableNames, variableValues)
} else if action.caseInsensitiveCompare(VNScriptStringJumpOnFlag) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .JUMPONFLAG
//
// If a particular flag has a particular value, then this command will jump to a different
// conversation/dialogue-sequence in the script.
//
// Parameters:
//
// #1: The name of the flag to be checked (string)
//
// #2: The expected value of the flag (integer)
//
// #3: The scene to jump to, if the flag's vaue matches the expected value in parameter #2 (string)
//
// Example: .JUMPONFLAG:should jump to beach scene:1:BeachScene
//
if command.count < 4 {
return nil
}
let variableName:NSString? = command.object(at: 1) as? NSString //[command objectAtIndex:1];
let expectedValue:NSString? = command.object(at: 2) as? NSString //[command objectAtIndex:2];
let newLocation:NSString? = command.object(at: 3) as? NSString //[command objectAtIndex:3];
if( variableName == nil || expectedValue == nil || newLocation == nil ) {
print("[VNScript] ERROR: Invalid parameters passed to .JUMPONFLAG command.");
return nil;
}
let expectedValueAsNumber = NSNumber(value: expectedValue!.integerValue)
type = VNScriptCommandJumpOnFlag as NSNumber
//analyzedArray = NSArray(objects: type, variableName!, expectedValue!, newLocation!)
analyzedArray = NSArray(objects: type, variableName!, expectedValueAsNumber, newLocation!)
} else if action.caseInsensitiveCompare(VNScriptStringSystemCall) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .SYSTEMCALL
//
// Used to do a "system call," which is usually game-specific. This command will try to contact the
// VNSystemCall class, and use it to perform some kind of particular task. Some examples of this would
// be starting a mini-game or some other activity that's specific to a particular app.
//
// Parameters:
//
// #1: The "call string" or a string that described what the activity/system-call type will be (string)
//
// #2: (OPTIONAL) The first parameter to pass in to the system call (string?)
//
// ...more parameters can be passed in as necessary
//
// Example: .SYSTEMCALL:start-bullet-hell-minigame:BulletHellLevel01
//
if( command.count < 1 ) {
return nil;
}
let callString:NSString = command.object(at: 1) as! NSString // Extract the call string
//NSMutableArray* extraParameters = [NSMutableArray arrayWithArray:command];
let extraParameters:NSMutableArray = NSMutableArray(array: command)
extraParameters.removeObject(at: 1) // Remove call type
extraParameters.removeObject(at: 0) // Remove command
// Add a dummy parameter just for the heck of it
if( extraParameters.count < 1 ) {
//[extraParameters addObject:@"nil"];
extraParameters.add(NSString(string: "nil"))
}
type = VNScriptCommandSystemCall as NSNumber
analyzedArray = NSArray(objects: type, callString, extraParameters)
} else if action.caseInsensitiveCompare(VNScriptStringCallCode) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .CALLCODE
//
// This action can be used to call functions (usually from static objects). Careful when using it to
// call classes or functions that the VN system doesn't have access to! You may need to include header
// files from certain places if you really want to use certain classes.
//
// Parameters:
//
// #1: The name of the class to call (string)
//
// #2: The name of a static function to call (string)
//
// #3: (OPTIONAL) The name of another function, PRESUMABLY a function that belongs to the class
// instance that was returned by the function called in #2 (string)
//
// #4: (OPTIONAL) A parameter to pass into the function called in #3 (string?)
//
// Example: .CALLCODE:EKRecord:sharedRecord:flagNamed:times played
//
if( command.count < 3 ) {
return nil;
}
// At this point, you'll need an array that has all the things needed to call a particular class,
// as well as class functions. The first string in the array will be the class, the second will be
// a "shared object" static function, and if a third string exists, it will call a particular
// function in that class. If there are any more strings, they will be parameters. For example:
//
// callingArray[0] = EKRecord
// callingArray[1] = sharedRecord
// callingArray[2] = flagNamed
// callingArray[3] = times played
//
// ...which would come out something like --> [[EKRecord sharedRecord] flagNamed:@"times played"];
//
let callingArray:NSMutableArray = NSMutableArray(array: command)
callingArray.removeObject(at: 0) // Removes the string ".callcode"
type = VNScriptCommandCallCode as NSNumber
analyzedArray = NSArray(objects: type, callingArray)
} else if( action.caseInsensitiveCompare(VNScriptStringSwitchScript) == ComparisonResult.orderedSame ) {
// Function definition
//
// Name: .SWITCHSCRIPT
//
// Replaces a scene's script with a script loaded from another .PLIST file. This is useful if you're
// using multiple .PLIST files.
//
// Parameters:
//
// #1: The name of the .PLIST file to load (string)
//
// #2: (OPTIONAL) The name of the "conversation"/array to start at to (string) (default is "start")
//
// Example: .SWITCHSCRIPT:script number 2:Some Random Event
//
if( command.count < 2 ) {
return nil;
}
let scriptName:NSString? = command.object(at: 1) as? NSString
var startingPoint:NSString = VNScriptStartingPoint as NSString; // Default value
// Check if the script name is missing
if( scriptName == nil ) {
return nil;
}
// Load non-default starting point (if it exists)
if( command.count > 2 ) {
startingPoint = command.object(at: 2) as! NSString
}
type = VNScriptCommandSwitchScript as NSNumber
analyzedArray = NSArray(objects: type, scriptName!, startingPoint)
} else if( action.caseInsensitiveCompare(VNScriptStringSetSpeakerFont) == ComparisonResult.orderedSame ) {
// Function definition
//
// Name: .SETSPEAKERFONT
//
// Replaces the current font used by the "speaker name" label with another font.
//
// Parameters:
//
// #1: The name of the font to use (string)
//
// Example: .SETSPEAKERFONT:Helvetica
//
type = VNScriptCommandSetSpeakerFont as NSNumber
analyzedArray = NSArray(objects: type, parameter1)
} else if( action.caseInsensitiveCompare(VNScriptStringSetSpeakerFontSize) == ComparisonResult.orderedSame ) {
// Function definition
//
// Name: .SETSPEAKERFONTSIZE
//
// Changes the font size used by the "speaker name" label.
//
// Parameters:
//
// #1: Font size (float)
//
// Example: .SETSPEAKERFONTSIZE:17.0
//
//let sizeAsNumber = NSNumber( double: parameter1.doubleValue )
type = VNScriptCommandSetSpeakerFontSize as NSNumber
analyzedArray = NSArray(objects: type, parameter1)
//analyzedArray = NSArray(objects: type, sizeAsNumber)
} else if( action.caseInsensitiveCompare(VNScriptStringSetSpeechFont) == ComparisonResult.orderedSame ) {
// Function definition
//
// Name: .SETSPEECHFONT
//
// Replaces the current font used by the speech/dialogue label with another font.
//
// Parameters:
//
// #1: The name of the font to use (string)
//
// Example: .SETSPEECHFONT:Courier New
//
type = VNScriptCommandSetSpeechFont as NSNumber
analyzedArray = NSArray(objects: type, parameter1)
} else if( action.caseInsensitiveCompare(VNScriptStringSetSpeechFontSize) == ComparisonResult.orderedSame ) {
// Function definition
//
// Name: .SETSPEECHFONTSIZE
//
// Changes the speech/dialogue font size.
//
// Parameters:
//
// #1: Font size (float)
//
// Example: .SETSPEECHFONTSIZE:18.0
//
type = VNScriptCommandSetSpeechFontSize as NSNumber
analyzedArray = NSArray(objects: type, parameter1)
} else if action.caseInsensitiveCompare(VNScriptStringSetTypewriterText) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .SETTYPEWRITERTEXT
//
// Sets or disables "typewriter text" mode, in which each character of text/dialogue appears
// one at a time (though usually still very quickly).
//
// Parameters:
//
// #1: How many characters it should print per second (Integer)
// (setting this to zero disables typewriter text mode)
//
// #2: Whether the user can still skip ahead by tapping the screen (BOOL) (default value is NO)
//
// Example: .SETTYPEWRITERTEXT:30:NO
//
let defaultSkipString = NSString(string:"NO")
let textSpeed = parameter1.integerValue
let timeNumber = NSNumber(value: textSpeed)
var canSkip = defaultSkipString.boolValue // use default value first
if( command.count > 2 ) {
let secondParameter = command.object(at: 2) as! NSString
canSkip = secondParameter.boolValue // Use custom value if it exists
}
let skipNumber = NSNumber(value: canSkip)
type = VNScriptCommandSetTypewriterText as NSNumber
analyzedArray = NSArray(objects:type, timeNumber, skipNumber)
} else if action.caseInsensitiveCompare(VNScriptStringSetSpriteAlias) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .SETSPRITEALIAS
//
// Assigns a filename to a particular sprite alias. Creates the that sprite alias if none exists.
//
// Parameters:
//
// #1: The sprite alias. (string)
//
// #2: The filename to use. (string)
//
// Example: .SETSPRITEALIAS:hero:harry.png
//
let aliasParameter = command.object(at: 1) as! NSString
let filenameParameter = command.object(at: 2) as! NSString
type = VNScriptCommandSetSpriteAlias as NSNumber
//analyzedArray = @[type, aliasParameter, filenameParameter];
analyzedArray = NSArray(objects: type, aliasParameter, filenameParameter)
} else if action.caseInsensitiveCompare(VNScriptStringSetSpeechbox) == ComparisonResult.orderedSame {
// Function definition
//
// Name: .SETSPEECHBOX
//
// Dynamically switches to a different speechbox sprite.
//
// Parameters:
//
// #1: Name of speechbox sprite to use (string)
//
// #2: (OPTIONAL) Duration of transition, in seconds) (double)
// (default is 0, which is instant)
//
// Example: .SETSPEECHBOX:alternate_box.png:1.0
//
// Set default values
//NSString* duration = [NSString stringWithFormat:@"0"];
var duration = NSString(string: "0")
// Overwrite any default values with any values that have been explicitly written into the script
if command.count >= 3 {
duration = command.object(at: 2) as! NSString // optional, default value is zero
}
type = VNScriptCommandSetSpeechbox as NSNumber
let durationToUse = NSNumber(value: duration.doubleValue)
analyzedArray = NSArray(objects: type, parameter1, durationToUse)
} else if( action.caseInsensitiveCompare(VNScriptStringFlipSprite) == ComparisonResult.orderedSame ) {
// Function definition
//
// Name: .FLIPSPRITE
//
// Flips the sprite left/right or upside-down/right-side-up.
//
// Parameters:
//
// #1: Name of sprite (string)
//
// #2: (OPTIONAL) Duration in seconds. Duration of zero is instantaneous. (double)
//
// #3: (OPTIONAL) Whether to flip horizontally or not (BOOL)
// (YES means horizontal flip, NO means vertical flip)
//
// Example: .FLIPSPRITE:girl.png:0:YES
//
var duration = NSString(string: "0")
var flipBool = NSString(string: "YES")
// Set default values
//NSString* duration = [NSString stringWithFormat:@"0"];
//NSString* flipBool = [NSString stringWithFormat:@"YES"];
// Overwrite any default values with any values that have been explicitly written into the script
if command.count >= 3 {
duration = command.object(at: 2) as! NSString
}
if command.count >= 4 {
flipBool = command.object(at: 3) as! NSString
}
type = VNScriptCommandFlipSprite as NSNumber
let durationToUse = NSNumber(value: duration.doubleValue)
let numberForFlip = NSNumber(value: flipBool.boolValue)
analyzedArray = NSArray(objects: type, parameter1, durationToUse, numberForFlip)
//type = @VNScriptCommandFlipSprite;
//NSNumber* durationToUse = @([duration doubleValue]);
//NSNumber* numberForFlip = @(flipBool.boolValue);
//analyzedArray = @[type, parameter1, durationToUse, numberForFlip];
} else if( action.caseInsensitiveCompare(VNScriptStringRollDice) == ComparisonResult.orderedSame) {
// Function definition
//
// Name: .ROLLDICE
//
// Rolls dice to get random result, stores value in a flag named DICEROLL
//
// Parameters:
//
// #1: Maximum value of roll; possible results = 1 to (max value) (Integer)
//
// #2: (OPTIONAL) Number of dice, default is zero (Integer)
//
// #3: (OPTIONAL) Name of flag, adds integer value in flag to final result (String)
// (default is ".nil")
//
// Example: .ROLLDICE:20:1:luck_modifier
//
var numberOfDice = NSString(string: "1")
var nameOfFlagModifier = NSString(string: VNScriptNilValue) // ".nil"
if command.count >= 3 {
numberOfDice = command.object(at: 2) as! NSString
}
if command.count >= 4 {
nameOfFlagModifier = command.object(at: 3) as! NSString
}
type = VNScriptCommandRollDice as NSNumber
let maximumValueOfDice = NSNumber(integerLiteral: parameter1.integerValue)
let diceNumberToUse = NSNumber(integerLiteral: numberOfDice.integerValue)
analyzedArray = NSArray(objects: type, maximumValueOfDice, diceNumberToUse, nameOfFlagModifier)
} else if( action.caseInsensitiveCompare(VNScriptStringModifyChoiceboxOffset) == ComparisonResult.orderedSame ) {
// Function definition
//
// Name: .MODIFYCHOICEBOXOFFSET
//
// Modifies button offsets during choices, in case you don't want them to show up in the middle of the screen.
//
// Parameters:
//
// #1: X coordinate (in points) (double)
//
// #2: Y coordinate (in points) (double)
//
// Example: .MODIFYCHOICEBOXOFFSET:10:10
//
// Set default values
var xOffset = NSString(string: "0")
var yOffset = NSString(string: "0")
if command.count >= 2 {
xOffset = command.object(at: 1) as! NSString
}
if command.count >= 2 {
yOffset = command.object(at: 2) as! NSString
}
type = VNScriptCommandModifyChoiceboxOffset as NSNumber
let xAsNumber = NSNumber(value: xOffset.doubleValue);
let yAsNumber = NSNumber(value: yOffset.doubleValue);
analyzedArray = NSArray(objects: type, xAsNumber, yAsNumber)
} else if( action.caseInsensitiveCompare(VNScriptStringScaleBackground) == ComparisonResult.orderedSame ) {
// Function definition
//
// Name: .SCALEBACKGROUND
//
// Changes background scale (1.0 being the "normal" scale)
//
// Parameters:
//
// #1: Scale (double)
//
// #2: (OPTIONAL) Duration in seconds; 0 results in instantaneous scaling (double)
//
// Example: .SCALEBACKGROUND:2.5:1
//
// Set default values
var scaleValue = NSString(string: "1") //[NSString stringWithFormat:@"1"];
var durationValue = NSString(string: "0")
// Overwrite any default values with any values that have been explicitly written into the script
if command.count >= 2 {
scaleValue = command.object(at: 1) as! NSString //[command objectAtIndex:1];
}
if command.count >= 3 {
durationValue = command.object(at: 2) as! NSString //[command objectAtIndex:2];
}
type = VNScriptCommandScaleBackground as NSNumber
let scaleNumber = NSNumber(value: scaleValue.doubleValue)
let durationNumber = NSNumber(value: durationValue.doubleValue)
analyzedArray = NSArray(objects: type, scaleNumber, durationNumber)
} else if( action.caseInsensitiveCompare(VNScriptStringScaleSprite) == ComparisonResult.orderedSame ) {
// Function definition
//
// Name: .SCALESPRITE
//
// Changes sprite scale (1.0 being the "normal" scale)
//
// Parameters:
//
// #1: Name of sprite (string)
//
// #2: Scale (default is 1.0) (double)
//
// #3: (OPTIONAL) Duration in seconds; 0 results in instantaneous scaling (double)
//
// Example: .SCALESPRITE:girl.png:2:1.5
//
// Set default values
var inputScale = NSString(string: "1")
var inputDuration = NSString(string: "0")
// overwrite defaults with any information that's been passed in
if command.count >= 3 {
inputScale = command.object(at: 2) as! NSString
}
if command.count >= 4 {
inputDuration = command.object(at: 3) as! NSString
}
type = VNScriptCommandScaleSprite as NSNumber
let scaleNumber = NSNumber(value: inputScale.doubleValue)
let durationNumber = NSNumber(value: inputDuration.doubleValue)
analyzedArray = NSArray(objects: type, parameter1, scaleNumber, durationNumber);
} else if( action.caseInsensitiveCompare(VNScriptStringAddToChoiceSet) == ComparisonResult.orderedSame) {
// Function definition
//
// Name: .ADDTOCHOICESET
//
// Adds a choice (specifically, a line of dilaogue and a destination to jump to) to a choice set.
//
// Parameters:
//
// #1: The choice set to add to (String)
//
// #2: The destination to jump to (String)
//
// #3: The text to display as a choice (String)
//
// Example: .ADDTOCHOICESET:locations to travel:San Francisco:"I want to go to San Francisco!"
//
if command.count < 4 {
return nil
}
let setName = parameter1
let destinationString = command.object(at: 2) as! NSString
let textToDisplay = command.object(at: 3) as! NSString
type = VNScriptCommandAddToChoiceSet as NSNumber
analyzedArray = NSArray(objects: type, setName, destinationString, textToDisplay)
} else if( action.caseInsensitiveCompare(VNScriptStringRemoveFromChoiceSet) == ComparisonResult.orderedSame) {
// Function definition
//
// Name: .REMOVEFROMCHOICESET
//
// Removes a single location (and the accompanying choice text) from a choice set
//
// Parameters:
//
// #1: The choice set that a choice will be removed from (String)
//
// #2: The destination to remove (String)
//
// Example: .REMOVEFROMCHOICESET:locations to travel:San Francisco
//
if command.count < 3 {
return nil
}
let destinationString = command.object(at: 2) as! String
type = VNScriptCommandRemoveFromChoiceSet as NSNumber
analyzedArray = NSArray(objects: type, parameter1, destinationString)
} else if( action.caseInsensitiveCompare(VNScriptStringWipeChoiceSet) == ComparisonResult.orderedSame) {
// Function definition
//
// Name: .WIPECHOICESET
//
// Removes an entire choice set from memory (both RAM and from SMRecord / device storage)
//
// Parameters:
//
// #1: The name of the choice set to remove from memory (String)
//
// Example: .WIPECHOICESET:locations to travel
//
if command.count < 2 {
return nil
}
type = VNScriptCommandWipeChoiceSet as NSNumber
analyzedArray = NSArray(objects: type, parameter1)
} else if( action.caseInsensitiveCompare(VNScriptStringShowChoiceSet) == ComparisonResult.orderedSame) {
// Function definition
//
// Name: .SHOWCHOICESET
//
// Displays the entire choice set on screen so the player can choose
//
// Parameters:
//
// #1: The name of the choice set to display (String)
//
// Example: .SHOWCHOICESET:locations to travel
//
if command.count < 2 {
return nil
}
type = VNScriptCommandShowChoiceSet as NSNumber
analyzedArray = NSArray(objects: type, parameter1)
}
return analyzedArray
}
}
|
mit
|
2bb31fe1678c78406351ac51d9c7b1ca
| 46.029827 | 156 | 0.544828 | 5.053127 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor
|
TranslationEditor/BookProgressView.swift
|
1
|
5758
|
//
// BookProgressView.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 9.5.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
fileprivate typealias ReduceResult = (mostRecentFilled: Int, mostRecentTotal: Int, historyFilled: Int)
fileprivate func increment(result: inout ReduceResult, filledCountIncrease: Int = 0, totalCountIncrease: Int = 0, isMostRecent: Bool)
{
if isMostRecent
{
result.mostRecentFilled += filledCountIncrease
result.mostRecentTotal += totalCountIncrease
}
else
{
result.historyFilled += filledCountIncrease
}
}
// This view is used for checking the progress of each book
final class BookProgressView: View
{
// TYPES ----------------
typealias Queried = Paragraph
typealias MyQuery = Query<BookProgressView>
// ATTRIBUTES ------------
static let KEY_PROJECT = "project"
static let KEY_BOOK = "book"
static let KEY_CHAPTER = "chapter"
static let KEY_PATH = "path"
static let KEY_MOST_RECENT = "most_recent"
static let keyNames = [KEY_PROJECT, KEY_BOOK, KEY_CHAPTER, KEY_PATH, KEY_MOST_RECENT]
static let instance = BookProgressView()
let view = DATABASE.viewNamed("book_progress_view")
// INIT --------------------
private init()
{
view.setMapBlock(createMapBlock
{
paragraph, emit in
if !paragraph.isDeprecated
{
let key: [Any] = [paragraph.projectId, paragraph.bookId, paragraph.chapterIndex, paragraph.pathId, paragraph.isMostRecent]
// Value is the amount of filled verses + total number of verses
let completion = paragraph.completion
let value = [completion.filledVerses, completion.total]
emit(key, value)
}
}, reduce:
{
keys, values, rereduce in
if rereduce
{
guard let values = values as? [ReduceResult] else
{
print("ERROR: Invalid type in BookProgressView rereduce")
return ReduceResult(0, 0, 0)
}
// Merges the results
return values.reduce(ReduceResult(0, 0, 0)) { ReduceResult(mostRecentFilled: $0.mostRecentFilled + $1.mostRecentFilled, mostRecentTotal: $0.mostRecentTotal + $1.mostRecentTotal, historyFilled: $0.historyFilled + $1.historyFilled) }
}
else
{
guard let keys = keys as? [[Any]] else
{
print("ERROR: Invalid key type in BookProgressView reduce block")
return ReduceResult(0, 0, 0)
}
// Counts together the number of filled and empty verses. A separate count is used for history paragraphs
var result = ReduceResult(0, 0, 0)
for i in 0 ..< keys.count
{
if let isMostRecent = keys[i][4] as? Bool, let counts = values[i] as? [Int], counts.count >= 2
{
increment(result: &result, filledCountIncrease: counts[0], totalCountIncrease: counts[1], isMostRecent: isMostRecent)
}
else
{
print("ERROR: Could not parse key '\(keys[i])' and / or value '\(values[i])' at BookProgressView reduce block")
}
}
return result
}
}, version: "2")
}
// OTHER METHODS ----------------
// Retrieves progress status for a single book
func progressForBook(withId bookId: String) throws -> BookProgressStatus
{
if let result = try createProgressQuery(bookId: bookId).firstResultRow()?.rawValue as? ReduceResult
{
return statusForResult(result)
}
else
{
print("ERROR: No reduce result in BookProgressView query")
return BookProgressStatus(totalElementAmount: 0, filledElementAmount: 0, filledHistoryElementAmount: 0)
}
}
// Retrieves progress status for each of the books in a project
// Resulting dictionary keys are bookIds
func progressForProjectBooks(projectId: String) throws -> [String: BookProgressStatus]
{
return try collectProgressResults(query: createProgressQuery(projectId: projectId), groupByKey: BookProgressView.KEY_BOOK, valueToKey: { $0.string() })
}
// Retrieves progress status for each chapter in a book
// The dictionary keys are the chapter indices
func chapterProgressForBook(withId bookId: String) throws -> [Int: BookProgressStatus]
{
return try collectProgressResults(query: createProgressQuery(bookId: bookId), groupByKey: BookProgressView.KEY_CHAPTER, valueToKey: { $0.int() })
}
// Retrieves progress status for all books
func progressForAllBooks() throws -> [String: BookProgressStatus]
{
return try collectProgressResults(query: createQuery(ofType: .reduce), groupByKey: BookProgressView.KEY_BOOK, valueToKey: { $0.string() })
}
private func collectProgressResults<T>(query: MyQuery, groupByKey: String, valueToKey: (PropertyValue) -> T) throws -> [T: BookProgressStatus]
{
var groupedQuery = query
groupedQuery.groupByKey = groupByKey
var progress = [T: BookProgressStatus]()
try groupedQuery.enumerateResult
{
row in
guard let result = row.rawValue as? ReduceResult else
{
print("ERROR: Couldn't parse reduce result out of \(String(describing: row.rawValue))")
return false
}
progress[valueToKey(row[groupByKey])] = statusForResult(result)
return true
}
return progress
}
private func createProgressQuery(projectId: String, bookId: String? = nil, chapterIndex: Int? = nil) -> MyQuery
{
return createQuery(ofType: .reduce, withKeys: BookProgressView.makeKeys(from: [projectId, bookId, chapterIndex]))
}
private func createProgressQuery(bookId: String, chapterIndex: Int? = nil) -> MyQuery
{
return createProgressQuery(projectId: Book.projectId(fromId: bookId), bookId: bookId, chapterIndex: chapterIndex)
}
private func statusForResult(_ result: ReduceResult) -> BookProgressStatus
{
return BookProgressStatus(totalElementAmount: result.mostRecentTotal, filledElementAmount: result.mostRecentFilled, filledHistoryElementAmount: result.historyFilled)
}
}
|
mit
|
a89ab7a83ccc64a04ae5c36d84e53dad
| 29.951613 | 235 | 0.709224 | 3.718992 | false | false | false | false |
antonio081014/LeetCode-CodeBase
|
Swift/swap-nodes-in-pairs.swift
|
1
|
954
|
/**
* https://leetcode.com/problems/swap-nodes-in-pairs/
*
*
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class Solution {
func swapPairs(_ head: ListNode?) -> ListNode? {
let root = ListNode(0)
root.next = head
var node = root
while let l1 = node.next, let l2 = l1.next {
l1.next = l2.next
l2.next = l1
node.next = l2
node = l1
}
return root.next
}
}
class Solution {
func swapPairs(_ head: ListNode?) -> ListNode? {
guard head != nil && head?.next != nil else { return head }
let next = swapPairs(head?.next?.next)
let first = head?.next
head?.next = next
first?.next = head
return first
}
}
|
mit
|
17cf4e2b28b70f484d211888ac3223c6
| 22.268293 | 67 | 0.51153 | 3.586466 | false | false | false | false |
lieonCX/Uber
|
UberDriver/UberDriver/View/Driver/DriverVC.swift
|
1
|
4664
|
//
// DriverVC.swift
// UberDriver
//
// Created by lieon on 2017/3/24.
// Copyright © 2017年 ChangHongCloudTechService. All rights reserved.
//
import UIKit
import MapKit
class DriverVC: UIViewController {
@IBOutlet weak var acceptUberBtn: UIButton!
@IBOutlet weak var map: MKMapView!
private var authVM: AuthViewModel = AuthViewModel()
fileprivate var locationManager: CLLocationManager = CLLocationManager()
fileprivate var driverVM: DriverViewModel = DriverViewModel()
fileprivate var acceptedUber: Bool = false
fileprivate var driverCancleUber: Bool = false
fileprivate var riderLocation: CLLocationCoordinate2D?
fileprivate var driverLocation: CLLocationCoordinate2D?
fileprivate var timer: Timer = Timer()
@IBAction func cancleUberAction(_ sender: Any) {
if acceptedUber {
driverCancleUber = true
acceptUberBtn.isHidden = true
driverVM.cancleUberForDriver()
timer.invalidate()
}
}
@IBAction func logout(_ sender: Any) {
if authVM.isLogout {
if acceptedUber {
acceptUberBtn.isHidden = true
driverVM.cancleUberForDriver()
timer.invalidate()
}
navigationController?.dismiss(animated: true, completion: nil)
} else {
show(title: "logout faild", message: "logout faild, please try again")
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupMap()
setupDriver()
updateRiderLocation()
}
}
extension DriverVC: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = manager.location?.coordinate {
driverLocation = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
guard let driver = driverLocation else { return }
let region = MKCoordinateRegion(center: driver, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
map.setRegion(region, animated: true)
map.removeAnnotations(map.annotations)
if let rider = riderLocation {
if acceptedUber {
let riverAnnotation = MKPointAnnotation()
riverAnnotation.title = "Rider Annotation"
riverAnnotation.coordinate = rider
map.addAnnotation(riverAnnotation)
}
}
let annotion = MKPointAnnotation()
annotion.coordinate = driver
annotion.title = "Driver Annotation"
map.addAnnotation(annotion)
}
}
}
extension DriverVC {
fileprivate func setupMap() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
fileprivate func setupDriver() {
driverVM.observeMessageForDriver { (latitude, longitude) in
if !self.acceptedUber {
self.show(title: "Uber Request", message: "You have request for an uber request at this location Lat: \(latitude), long: \(longitude)", confirmAction: { _ in
self.acceptedUber = true
self.acceptUberBtn.isHidden = false
self.timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.updateDriverLocation), userInfo: nil, repeats: true)
self.driverVM.acceptUber(lati: latitude, long: longitude)
})
}
}
driverVM.riderCancleAction = {
self.driverVM.cancleUberForDriver()
self.acceptedUber = false
self.acceptUberBtn.isHidden = true
self.show(title: "Uber Cancled", message: "The Uber has cancled ")
}
driverVM.driverCancleAction = {
self.acceptedUber = false
self.acceptUberBtn.isHidden = true
self.timer.invalidate()
}
}
@objc fileprivate func updateDriverLocation() {
guard let location = driverLocation else { return }
driverVM.updateDriverLocation(lati: location.latitude, long: location.longitude)
}
fileprivate func updateRiderLocation() {
driverVM.updateRiderLocation { (lati, long) in
self.riderLocation = CLLocationCoordinate2D(latitude: lati, longitude: long)
self.locationManager.startUpdatingLocation()
}
}
}
|
mit
|
8d927b84090eebf5902ee3ac148fd21b
| 36.58871 | 173 | 0.627977 | 5.060803 | false | false | false | false |
tavultesoft/keymanweb
|
ios/engine/KMEI/KeymanEngine/Classes/Extension/String+Helpers.swift
|
1
|
1250
|
//
// String+Helpers.swift
// KeymanEngine
//
// Created by Gabriel Wong on 2017-10-12.
// Copyright © 2017 SIL International. All rights reserved.
//
import Foundation
extension String {
var hasFontExtension: Bool {
return hasExtension(FileExtensions.trueTypeFont) || hasSuffix(FileExtensions.openTypeFont)
}
var hasJavaScriptExtension: Bool {
return hasExtension(FileExtensions.javaScript)
}
func hasExtension(_ ext: String) -> Bool {
return lowercased().hasSuffix(".\(ext)")
}
/// - Parameter separator: The separator between code units.
/// - Returns: This String interpreted as hex-encoded UTF-16 code units.
func stringFromUTF16CodeUnits(separatedBy separator: String = ",") -> String? {
// TODO: Use one scanner for the whole String instead of splitting by comma first
let hexStrings = components(separatedBy: separator)
var codeUnits: [UInt16] = []
for hexString in hexStrings {
let scanner = Scanner(string: hexString)
var codeUnit: UInt32 = 0
if scanner.scanHexInt32(&codeUnit) && scanner.isAtEnd {
codeUnits.append(UInt16(codeUnit))
} else {
return nil
}
}
return String(utf16CodeUnits: codeUnits, count: codeUnits.count)
}
}
|
apache-2.0
|
7db7c8a8c987fb1a87590d0146aa05ac
| 28.738095 | 94 | 0.692554 | 4.292096 | false | false | false | false |
rshev/Mixpanel
|
Mixpanel/Tests/MixpanelTests.swift
|
1
|
1654
|
//
// MixpanelTests.swift
// MixpanelTests
//
// Created by Sam Soffes on 6/21/15.
// Copyright © 2015 Sam Soffes. All rights reserved.
//
import XCTest
import Mixpanel
import DVR
class DisabledSession: NSURLSession {
override func dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask {
XCTFail("Networking disabled")
return NSURLSessionDataTask()
}
}
class MixpanelTests: XCTestCase {
func testDisabling() {
let expectation = expectationWithDescription("Completion")
var client = Mixpanel(token: "asdf1234", URLSession: DisabledSession())
client.enabled = false
client.track("foo") { success in
XCTAssertFalse(success)
expectation.fulfill()
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func testTracking() {
let expectation = expectationWithDescription("Completion")
let client = Mixpanel(token: "07e60c15c2630d9047d62ac779203cae", URLSession: Session(cassetteName: "tracking"))
client.track("test1", time: NSDate(timeIntervalSince1970: 1434954974)) { success in
XCTAssertTrue(success)
expectation.fulfill()
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func testTrackingWithParameters() {
let expectation = expectationWithDescription("Completion")
let client = Mixpanel(token: "07e60c15c2630d9047d62ac779203cae", URLSession: Session(cassetteName: "tracking-parameters"))
client.track("test2", parameters: ["foo": "bar"], time: NSDate(timeIntervalSince1970: 1434954974)) { success in
XCTAssertTrue(success)
expectation.fulfill()
}
waitForExpectationsWithTimeout(1, handler: nil)
}
}
|
mit
|
43240faab46a03dcc5674e7ae61c5866
| 27.5 | 147 | 0.753176 | 3.889412 | false | true | false | false |
mrdepth/Neocom
|
Legacy/Neocom/Neocom/MailBodyInteractor.swift
|
2
|
1153
|
//
// MailBodyInteractor.swift
// Neocom
//
// Created by Artem Shimanski on 11/2/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import Futures
import CloudData
import EVEAPI
class MailBodyInteractor: ContentProviderInteractor {
typealias Presenter = MailBodyPresenter
typealias Content = ESI.Result<Value>
weak var presenter: Presenter?
struct Value {
var body: ESI.Mail.MailBody
var contacts: [Int64: Contact]
}
required init(presenter: Presenter) {
self.presenter = presenter
}
private var api = Services.api.current
func load(cachePolicy: URLRequest.CachePolicy) -> Future<Content> {
guard let header = presenter?.view?.input, let mailID = header.mailID else { return .init(.failure(NCError.invalidInput(type: type(of: self))))}
var set = Set(header.recipients?.map{Int64($0.recipientID)} ?? [])
if let id = header.from {
set.insert(Int64(id))
}
let api = self.api
return api.mailBody(mailID: Int64(mailID), cachePolicy: cachePolicy).then { body in
api.contacts(with: set).then { contacts in
body.map{ Value(body: $0, contacts: contacts) }
}
}
}
}
|
lgpl-2.1
|
d0015701b01dd05eaf9d1515d60ecc07
| 24.043478 | 146 | 0.710069 | 3.39823 | false | false | false | false |
Dormmate/DORMLibrary
|
Example/DORM/InstagramManager_Example.swift
|
1
|
1723
|
//
// InstagramManager_Example.swift
// DORM
//
// Created by Dormmate on 2017. 5. 4..
// Copyright © 2017 Dormmate. All rights reserved.
//
import UIKit
import DORM
class InstagramManager_Example: UIViewController {
var instaImageView = UIImageView()
var iImage = UIImage(named:"instaImg")
override func viewDidLoad() {
super.viewDidLoad()
instaImageView.rframe(x: 245, y: 309, width: 32, height: 32)
instaImageView.image = UIImage(named:"instaImg")
let instagram = UITapGestureRecognizer(target:self, action:#selector(instaAction1))
instaImageView.isUserInteractionEnabled = true
instaImageView.addGestureRecognizer(instagram)
view.addSubview(instaImageView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func instaAction1(){
//If you want to post by copying item
InstagramManager.sharedManager.postImageToInstagramWithCaption(imageInstagram: iImage!, instagramCaption: "caption", view: self.view)
}
func instaAction2(){
//If you want to save in photoalbum and use photo in instagram
InstagramManager.sharedManager.sendImageDirectlyToInstagram(image: iImage!)
UIImageWriteToSavedPhotosAlbum(iImage!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
InstagramManager.sharedManager.sendImageDirectlyToInstagram(image: image)
}
}
|
mit
|
118da0a43e65630632ff48d845582a4a
| 25.492308 | 141 | 0.648084 | 4.976879 | false | false | false | false |
SergeyVorontsov/SimpleNewsApp
|
SimpleNewsApp/Controller/NewsTableViewController.swift
|
1
|
3345
|
//
// NewsTableViewController.swift
// Simple News
//
// Created by Sergey Vorontsov
// Copyright (c) 2015 Sergey. All rights reserved.
//
import UIKit
class NewsTableViewController: UITableViewController, NewsDataProviderDelegate {
var newsDataProvider:NewsDataProvider!
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "likeChengeNotify:",
name: kLikeChengeNotify,
object: nil)
//configure refresh control
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: "refreshNews", forControlEvents: .ValueChanged)
self.refreshControl = refreshControl
//configure NewsDataProvider
newsDataProvider = NewsDataProvider()
newsDataProvider.delegate = self
newsDataProvider.fetchNews(cachePolicy: .CacheThenNetwork)
//configure tableView
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 134
self.tableView.tableFooterView = UIView()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.hidesBarsOnSwipe = false
}
// MARK: -
func refreshNews(){
newsDataProvider.fetchNews(cachePolicy: .NetworkOnly)
}
func likeChengeNotify(notify:NSNotification){
self.tableView.reloadData()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return newsDataProvider.newsCount()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("NewsCell", forIndexPath: indexPath) as! NewsCell
let newsItem = newsDataProvider.newsAtIndex(indexPath.row)
cell.newsTitleLabel.text = newsItem.title
cell.newsSummaryLabel.text = newsItem.summary
cell.newsSummaryLabel.text = newsItem.summary
cell.newsAgeLabel.text = newsItem.time.description
cell.newsLikeCountLabel.text = "likes: \(newsItem.likeCount)"
cell.newsAgeLabel.text = timeAgoSinceDate(newsItem.time)
cell.setNewsImage(newsItem.imageUrl)
return cell
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showNewsDetails" {
let newsDetailsVC = segue.destinationViewController as! NewsDetailsController
let selectedNewsItemIndex = tableView.indexPathForSelectedRow()?.row ?? 0
let selectedNews = self.newsDataProvider.newsAtIndex(selectedNewsItemIndex)
newsDetailsVC.news = selectedNews
}
}
//MARK: - NewsDataProviderDelegate
func newsDataProviderNewsDidLoad(#dataProvider: NewsDataProvider) {
if self.refreshControl?.refreshing == true {
self.refreshControl?.endRefreshing()
}
self.tableView.reloadData()
}
}
|
mit
|
8512289f914ca2171634b08db98523fe
| 30.857143 | 118 | 0.671151 | 5.377814 | false | false | false | false |
aaronraimist/firefox-ios
|
Storage/SQL/SQLiteLogins.swift
|
2
|
43159
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
import Deferred
private let log = Logger.syncLogger
let TableLoginsMirror = "loginsM"
let TableLoginsLocal = "loginsL"
let IndexLoginsOverrideHostname = "idx_loginsM_is_overridden_hostname"
let IndexLoginsDeletedHostname = "idx_loginsL_is_deleted_hostname"
let AllLoginTables: [String] = [TableLoginsMirror, TableLoginsLocal]
private let OverriddenHostnameIndexQuery =
"CREATE INDEX IF NOT EXISTS \(IndexLoginsOverrideHostname) ON \(TableLoginsMirror) (is_overridden, hostname)"
private let DeletedHostnameIndexQuery =
"CREATE INDEX IF NOT EXISTS \(IndexLoginsDeletedHostname) ON \(TableLoginsLocal) (is_deleted, hostname)"
private class LoginsTable: Table {
var name: String { return "LOGINS" }
var version: Int { return 3 }
func run(db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool {
let err = db.executeChange(sql, withArgs: args)
if err != nil {
log.error("Error running SQL in LoginsTable. \(err?.localizedDescription)")
log.error("SQL was \(sql)")
}
return err == nil
}
// TODO: transaction.
func run(db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql, args: nil) {
return false
}
}
return true
}
func create(db: SQLiteDBConnection) -> Bool {
let common =
"id INTEGER PRIMARY KEY AUTOINCREMENT" +
", hostname TEXT NOT NULL" +
", httpRealm TEXT" +
", formSubmitURL TEXT" +
", usernameField TEXT" +
", passwordField TEXT" +
", timesUsed INTEGER NOT NULL DEFAULT 0" +
", timeCreated INTEGER NOT NULL" +
", timeLastUsed INTEGER" +
", timePasswordChanged INTEGER NOT NULL" +
", username TEXT" +
", password TEXT NOT NULL"
let mirror = "CREATE TABLE IF NOT EXISTS \(TableLoginsMirror) (" +
common +
", guid TEXT NOT NULL UNIQUE" +
", server_modified INTEGER NOT NULL" + // Integer milliseconds.
", is_overridden TINYINT NOT NULL DEFAULT 0" +
")"
let local = "CREATE TABLE IF NOT EXISTS \(TableLoginsLocal) (" +
common +
", guid TEXT NOT NULL UNIQUE " + // Typically overlaps one in the mirror unless locally new.
", local_modified INTEGER" + // Can be null. Client clock. In extremis only.
", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean. Locally deleted.
", sync_status TINYINT " + // SyncStatus enum. Set when changed or created.
"NOT NULL DEFAULT \(SyncStatus.Synced.rawValue)" +
")"
return self.run(db, queries: [mirror, local, OverriddenHostnameIndexQuery, DeletedHostnameIndexQuery])
}
func updateTable(db: SQLiteDBConnection, from: Int) -> Bool {
let to = self.version
if from == to {
log.debug("Skipping update from \(from) to \(to).")
return true
}
if from == 0 {
// This is likely an upgrade from before Bug 1160399.
log.debug("Updating logins tables from zero. Assuming drop and recreate.")
return drop(db) && create(db)
}
if from < 3 && to >= 3 {
log.debug("Updating logins tables to include version 3 indices")
return self.run(db, queries: [OverriddenHostnameIndexQuery, DeletedHostnameIndexQuery])
}
// TODO: real update!
log.debug("Updating logins table from \(from) to \(to).")
return drop(db) && create(db)
}
func exists(db: SQLiteDBConnection) -> Bool {
return db.tablesExist(AllLoginTables)
}
func drop(db: SQLiteDBConnection) -> Bool {
log.debug("Dropping logins table.")
let err = db.executeChange("DROP TABLE IF EXISTS \(name)", withArgs: nil)
return err == nil
}
}
public class SQLiteLogins: BrowserLogins {
private let db: BrowserDB
private static let MainColumns = "guid, username, password, hostname, httpRealm, formSubmitURL, usernameField, passwordField"
private static let MainWithLastUsedColumns = MainColumns + ", timeLastUsed, timesUsed"
private static let LoginColumns = MainColumns + ", timeCreated, timeLastUsed, timePasswordChanged, timesUsed"
public init(db: BrowserDB) {
self.db = db
db.createOrUpdate(LoginsTable())
}
private class func populateLogin(login: Login, row: SDRow) {
login.formSubmitURL = row["formSubmitURL"] as? String
login.usernameField = row["usernameField"] as? String
login.passwordField = row["passwordField"] as? String
login.guid = row["guid"] as! String
if let timeCreated = row.getTimestamp("timeCreated"),
let timeLastUsed = row.getTimestamp("timeLastUsed"),
let timePasswordChanged = row.getTimestamp("timePasswordChanged"),
let timesUsed = row["timesUsed"] as? Int {
login.timeCreated = timeCreated
login.timeLastUsed = timeLastUsed
login.timePasswordChanged = timePasswordChanged
login.timesUsed = timesUsed
}
}
private class func constructLogin<T: Login>(row: SDRow, c: T.Type) -> T {
let credential = NSURLCredential(user: row["username"] as? String ?? "",
password: row["password"] as! String,
persistence: NSURLCredentialPersistence.None)
// There was a bug in previous versions of the app where we saved only the hostname and not the
// scheme and port in the DB. To work with these scheme-less hostnames, we try to extract the scheme and
// hostname by converting to a URL first. If there is no valid hostname or scheme for the URL,
// fallback to returning the raw hostname value from the DB as the host and allow NSURLProtectionSpace
// to use the default (http) scheme. See https://bugzilla.mozilla.org/show_bug.cgi?id=1238103.
let hostnameString = (row["hostname"] as? String) ?? ""
let hostnameURL = hostnameString.asURL
let scheme = hostnameURL?.scheme
let port = hostnameURL?.port?.integerValue ?? 0
// Check for malformed hostname urls in the DB
let host: String
var malformedHostname = false
if let h = hostnameURL?.host {
host = h
} else {
host = hostnameString
malformedHostname = true
}
let protectionSpace = NSURLProtectionSpace(host: host,
port: port,
protocol: scheme,
realm: row["httpRealm"] as? String,
authenticationMethod: nil)
let login = T(credential: credential, protectionSpace: protectionSpace)
self.populateLogin(login, row: row)
login.hasMalformedHostname = malformedHostname
return login
}
class func LocalLoginFactory(row: SDRow) -> LocalLogin {
let login = self.constructLogin(row, c: LocalLogin.self)
login.localModified = row.getTimestamp("local_modified")!
login.isDeleted = row.getBoolean("is_deleted")
login.syncStatus = SyncStatus(rawValue: row["sync_status"] as! Int)!
return login
}
class func MirrorLoginFactory(row: SDRow) -> MirrorLogin {
let login = self.constructLogin(row, c: MirrorLogin.self)
login.serverModified = row.getTimestamp("server_modified")!
login.isOverridden = row.getBoolean("is_overridden")
return login
}
private class func LoginFactory(row: SDRow) -> Login {
return self.constructLogin(row, c: Login.self)
}
private class func LoginDataFactory(row: SDRow) -> LoginData {
return LoginFactory(row) as LoginData
}
private class func LoginUsageDataFactory(row: SDRow) -> LoginUsageData {
return LoginFactory(row) as LoginUsageData
}
func notifyLoginDidChange() {
log.debug("Notifying login did change.")
// For now we don't care about the contents.
// This posts immediately to the shared notification center.
let notification = NSNotification(name: NotificationDataLoginDidChange, object: nil)
NSNotificationCenter.defaultCenter().postNotification(notification)
}
public func getUsageDataForLoginByGUID(guid: GUID) -> Deferred<Maybe<LoginUsageData>> {
let projection = SQLiteLogins.LoginColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND guid = ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND guid = ? " +
"LIMIT 1"
let args: Args = [guid, guid]
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginUsageDataFactory)
>>== { value in
deferMaybe(value[0]!)
}
}
public func getLoginDataForGUID(guid: GUID) -> Deferred<Maybe<Login>> {
let projection = SQLiteLogins.LoginColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND guid = ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overriden IS NOT 1 AND guid = ? " +
"ORDER BY hostname ASC " +
"LIMIT 1"
let args: Args = [guid, guid]
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginFactory)
>>== { value in
if let login = value[0] {
return deferMaybe(login)
} else {
return deferMaybe(LoginDataError(description: "Login not found for GUID \(guid)"))
}
}
}
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? OR hostname IS ?" +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? OR hostname IS ?" +
"ORDER BY timeLastUsed DESC"
// Since we store hostnames as the full scheme/protocol + host, combine the two to look up in our DB.
// In the case of https://bugzilla.mozilla.org/show_bug.cgi?id=1238103, there may be hostnames without
// a scheme. Check for these as well.
let args: Args = [
protectionSpace.urlString(),
protectionSpace.host,
protectionSpace.urlString(),
protectionSpace.host,
]
if Logger.logPII {
log.debug("Looking for login: \(protectionSpace.urlString()) && \(protectionSpace.host)")
}
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
// username is really Either<String, NULL>; we explicitly match no username.
public func getLoginsForProtectionSpace(protectionSpace: NSURLProtectionSpace, withUsername username: String?) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let args: Args
let usernameMatch: String
if let username = username {
args = [
protectionSpace.urlString(), username, protectionSpace.host,
protectionSpace.urlString(), username, protectionSpace.host
]
usernameMatch = "username = ?"
} else {
args = [
protectionSpace.urlString(), protectionSpace.host,
protectionSpace.urlString(), protectionSpace.host
]
usernameMatch = "username IS NULL"
}
if Logger.logPII {
log.debug("Looking for login: \(username), \(args[0])")
}
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? AND \(usernameMatch) OR hostname IS ?" +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? AND \(usernameMatch) OR hostname IS ?" +
"ORDER BY timeLastUsed DESC"
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
public func getAllLogins() -> Deferred<Maybe<Cursor<Login>>> {
return searchLoginsWithQuery(nil)
}
public func searchLoginsWithQuery(query: String?) -> Deferred<Maybe<Cursor<Login>>> {
let projection = SQLiteLogins.LoginColumns
var searchClauses = [String]()
var args: Args? = nil
if let query = query where !query.isEmpty {
// Add wildcards to change query to 'contains in' and add them to args. We need 6 args because
// we include the where clause twice: Once for the local table and another for the remote.
args = (0..<6).map { _ in
return "%\(query)%" as String?
}
searchClauses.append("username LIKE ? ")
searchClauses.append(" password LIKE ? ")
searchClauses.append(" hostname LIKE ?")
}
let whereSearchClause = searchClauses.count > 0 ? "AND (" + searchClauses.joinWithSeparator("OR") + ") " : ""
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 " + whereSearchClause +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 " + whereSearchClause +
"ORDER BY hostname ASC"
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginFactory)
}
public func addLogin(login: LoginData) -> Success {
if let error = login.isValid.failureValue {
return deferMaybe(error)
}
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = NSNumber(unsignedLongLong: nowMicro)
let dateMilli = NSNumber(unsignedLongLong: nowMilli)
let args: Args = [
login.hostname,
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.username,
login.password,
login.guid,
dateMicro, // timeCreated
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
dateMilli, // localModified
]
let sql =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
// Shared fields.
"( hostname" +
", httpRealm" +
", formSubmitURL" +
", usernameField" +
", passwordField" +
", timesUsed" +
", username" +
", password " +
// Local metadata.
", guid " +
", timeCreated" +
", timeLastUsed" +
", timePasswordChanged" +
", local_modified " +
", is_deleted " +
", sync_status " +
") " +
"VALUES (?,?,?,?,?,1,?,?,?,?,?, " +
"?, ?, 0, \(SyncStatus.New.rawValue)" + // Metadata.
")"
return db.run(sql, withArgs: args)
>>> effect(self.notifyLoginDidChange)
}
private func cloneMirrorToOverlay(whereClause whereClause: String?, args: Args?) -> Deferred<Maybe<Int>> {
let shared = "guid, hostname, httpRealm, formSubmitURL, usernameField, passwordField, timeCreated, timeLastUsed, timePasswordChanged, timesUsed, username, password "
let local = ", local_modified, is_deleted, sync_status "
let sql = "INSERT OR IGNORE INTO \(TableLoginsLocal) (\(shared)\(local)) SELECT \(shared), NULL AS local_modified, 0 AS is_deleted, 0 AS sync_status FROM \(TableLoginsMirror) \(whereClause ?? "")"
return self.db.write(sql, withArgs: args)
}
/**
* Returns success if either a local row already existed, or
* one could be copied from the mirror.
*/
private func ensureLocalOverlayExistsForGUID(guid: GUID) -> Success {
let sql = "SELECT guid FROM \(TableLoginsLocal) WHERE guid = ?"
let args: Args = [guid]
let c = db.runQuery(sql, args: args, factory: { row in 1 })
return c >>== { rows in
if rows.count > 0 {
return succeed()
}
log.debug("No overlay; cloning one for GUID \(guid).")
return self.cloneMirrorToOverlay(guid)
>>== { count in
if count > 0 {
return succeed()
}
log.warning("Failed to create local overlay for GUID \(guid).")
return deferMaybe(NoSuchRecordError(guid: guid))
}
}
}
private func cloneMirrorToOverlay(guid: GUID) -> Deferred<Maybe<Int>> {
let whereClause = "WHERE guid = ?"
let args: Args = [guid]
return self.cloneMirrorToOverlay(whereClause: whereClause, args: args)
}
private func markMirrorAsOverridden(guid: GUID) -> Success {
let args: Args = [guid]
let sql =
"UPDATE \(TableLoginsMirror) SET " +
"is_overridden = 1 " +
"WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Replace the local DB row with the provided GUID.
* If no local overlay exists, one is first created.
*
* If `significant` is `true`, the `sync_status` of the row is bumped to at least `Changed`.
* If it's already `New`, it remains marked as `New`.
*
* This flag allows callers to make minor changes (such as incrementing a usage count)
* without triggering an upload or a conflict.
*/
public func updateLoginByGUID(guid: GUID, new: LoginData, significant: Bool) -> Success {
if let error = new.isValid.failureValue {
return deferMaybe(error)
}
// Right now this method is only ever called if the password changes at
// point of use, so we always set `timePasswordChanged` and `timeLastUsed`.
// We can (but don't) also assume that `significant` will always be `true`,
// at least for the time being.
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = NSNumber(unsignedLongLong: nowMicro)
let dateMilli = NSNumber(unsignedLongLong: nowMilli)
let args: Args = [
dateMilli, // local_modified
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
new.httpRealm,
new.formSubmitURL,
new.usernameField,
new.passwordField,
new.password,
new.hostname,
new.username,
guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?, timeLastUsed = ?, timePasswordChanged = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timesUsed = timesUsed + 1" +
", password = ?, hostname = ?, username = ?" +
// We keep rows marked as New in preference to marking them as changed. This allows us to
// delete them immediately if they don't reach the server.
(significant ? ", sync_status = max(sync_status, 1) " : "") +
" WHERE guid = ?"
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(update, withArgs: args) }
>>> effect(self.notifyLoginDidChange)
}
public func addUseOfLoginByGUID(guid: GUID) -> Success {
let sql =
"UPDATE \(TableLoginsLocal) SET " +
"timesUsed = timesUsed + 1, timeLastUsed = ?, local_modified = ? " +
"WHERE guid = ? AND is_deleted = 0"
// For now, mere use is not enough to flip sync_status to Changed.
let nowMicro = NSDate.nowMicroseconds()
let nowMilli = nowMicro / 1000
let args: Args = [NSNumber(unsignedLongLong: nowMicro), NSNumber(unsignedLongLong: nowMilli), guid]
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(sql, withArgs: args) }
}
public func removeLoginByGUID(guid: GUID) -> Success {
return removeLoginsWithGUIDs([guid])
}
private func getDeletionStatementsForGUIDs(guids: ArraySlice<GUID>, nowMillis: Timestamp) -> [(sql: String, args: Args?)] {
let inClause = BrowserDB.varlist(guids.count)
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause) AND sync_status = \(SyncStatus.New.rawValue)"
// Otherwise, mark it as changed.
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = \(nowMillis)" +
", sync_status = \(SyncStatus.Changed.rawValue)" +
", is_deleted = 1" +
", password = ''" +
", hostname = ''" +
", username = ''" +
" WHERE guid IN \(inClause)"
let markMirrorAsOverridden =
"UPDATE \(TableLoginsMirror) SET " +
"is_overridden = 1 " +
"WHERE guid IN \(inClause)"
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
"(guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.Changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror) WHERE guid IN \(inClause)"
let args: Args = guids.map { $0 as AnyObject }
return [
(delete, args),
(update, args),
(markMirrorAsOverridden, args),
(insert, args)
]
}
public func removeLoginsWithGUIDs(guids: [GUID]) -> Success {
let timestamp = NSDate.now()
return db.run(chunk(guids, by: BrowserDB.MaxVariableNumber).flatMap {
self.getDeletionStatementsForGUIDs($0, nowMillis: timestamp)
}) >>> effect(self.notifyLoginDidChange)
}
public func removeAll() -> Success {
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server. If Sync isn't set up, this will be everything.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE sync_status = \(SyncStatus.New.rawValue)"
let nowMillis = NSDate.now()
// Mark anything we haven't already deleted.
let update =
"UPDATE \(TableLoginsLocal) SET local_modified = \(nowMillis), sync_status = \(SyncStatus.Changed.rawValue), is_deleted = 1, password = '', hostname = '', username = '' WHERE is_deleted = 0"
// Copy all the remaining rows from our mirror, marking them as locally deleted. The
// OR IGNORE will cause conflicts due to non-unique guids to be dropped, preserving
// anything we already deleted.
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) (guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.Changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror)"
// After that, we mark all of the mirror rows as overridden.
return self.db.run(delete)
>>> { self.db.run(update) }
>>> { self.db.run("UPDATE \(TableLoginsMirror) SET is_overridden = 1") }
>>> { self.db.run(insert) }
>>> effect(self.notifyLoginDidChange)
}
}
// When a server change is detected (e.g., syncID changes), we should consider shifting the contents
// of the mirror into the local overlay, allowing a content-based reconciliation to occur on the next
// full sync. Or we could flag the mirror as to-clear, download the server records and un-clear, and
// resolve the remainder on completion. This assumes that a fresh start will typically end up with
// the exact same records, so we might as well keep the shared parents around and double-check.
extension SQLiteLogins: SyncableLogins {
/**
* Delete the login with the provided GUID. Succeeds if the GUID is unknown.
*/
public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success {
// Simply ignore the possibility of a conflicting local change for now.
let local = "DELETE FROM \(TableLoginsLocal) WHERE guid = ?"
let remote = "DELETE FROM \(TableLoginsMirror) WHERE guid = ?"
let args: Args = [guid]
return self.db.run(local, withArgs: args) >>> { self.db.run(remote, withArgs: args) }
}
func getExistingMirrorRecordByGUID(guid: GUID) -> Deferred<Maybe<MirrorLogin?>> {
let sql = "SELECT * FROM \(TableLoginsMirror) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.MirrorLoginFactory) >>== { deferMaybe($0[0]) }
}
func getExistingLocalRecordByGUID(guid: GUID) -> Deferred<Maybe<LocalLogin?>> {
let sql = "SELECT * FROM \(TableLoginsLocal) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory) >>== { deferMaybe($0[0]) }
}
private func storeReconciledLogin(login: Login) -> Success {
let dateMilli = NSNumber(unsignedLongLong: NSDate.now())
let args: Args = [
dateMilli, // local_modified
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
NSNumber(unsignedLongLong: login.timeLastUsed),
NSNumber(unsignedLongLong: login.timePasswordChanged),
login.timesUsed,
login.password,
login.hostname,
login.username,
login.guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timeLastUsed = ?, timePasswordChanged = ?, timesUsed = ?" +
", password = ?" +
", hostname = ?, username = ?" +
", sync_status = \(SyncStatus.Changed.rawValue) " +
" WHERE guid = ?"
return self.db.run(update, withArgs: args)
}
public func applyChangedLogin(upstream: ServerLogin) -> Success {
// Our login storage tracks the shared parent from the last sync (the "mirror").
// This allows us to conclusively determine what changed in the case of conflict.
//
// Our first step is to determine whether the record is changed or new: i.e., whether
// or not it's present in the mirror.
//
// TODO: these steps can be done in a single query. Make it work, make it right, make it fast.
// TODO: if there's no mirror record, all incoming records can be applied in one go; the only
// reason we need to fetch first is to establish the shared parent. That would be nice.
let guid = upstream.guid
return self.getExistingMirrorRecordByGUID(guid) >>== { mirror in
return self.getExistingLocalRecordByGUID(guid) >>== { local in
return self.applyChangedLogin(upstream, local: local, mirror: mirror)
}
}
}
private func applyChangedLogin(upstream: ServerLogin, local: LocalLogin?, mirror: MirrorLogin?) -> Success {
// Once we have the server record, the mirror record (if any), and the local overlay (if any),
// we can always know which state a record is in.
// If it's present in the mirror, then we can proceed directly to handling the change;
// we assume that once a record makes it into the mirror, that the local record association
// has already taken place, and we're tracking local changes correctly.
if let mirror = mirror {
log.debug("Mirror record found for changed record \(mirror.guid).")
if let local = local {
log.debug("Changed local overlay found for \(local.guid). Resolving conflict with 3WM.")
// * Changed remotely and locally (conflict). Resolve the conflict using a three-way merge: the
// local mirror is the shared parent of both the local overlay and the new remote record.
// Apply results as in the co-creation case.
return self.resolveConflictBetween(local: local, upstream: upstream, shared: mirror)
}
log.debug("No local overlay found. Updating mirror to upstream.")
// * Changed remotely but not locally. Apply the remote changes to the mirror.
// There is no local overlay to discard or resolve against.
return self.updateMirrorToLogin(upstream, fromPrevious: mirror)
}
// * New both locally and remotely with no shared parent (cocreation).
// Or we matched the GUID, and we're assuming we just forgot the mirror.
//
// Merge and apply the results remotely, writing the result into the mirror and discarding the overlay
// if the upload succeeded. (Doing it in this order allows us to safely replay on failure.)
//
// If the local and remote record are the same, this is trivial.
// At this point we also switch our local GUID to match the remote.
if let local = local {
// We might have randomly computed the same GUID on two devices connected
// to the same Sync account.
// With our 9-byte GUIDs, the chance of that happening is very small, so we
// assume that this device has previously connected to this account, and we
// go right ahead with a merge.
log.debug("Local record with GUID \(local.guid) but no mirror. This is unusual; assuming disconnect-reconnect scenario. Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// If it's not present, we must first check whether we have a local record that's substantially
// the same -- the co-creation or re-sync case.
//
// In this case, we apply the server record to the mirror, change the local record's GUID,
// and proceed to reconcile the change on a content basis.
return self.findLocalRecordByContent(upstream) >>== { local in
if let local = local {
log.debug("Local record \(local.guid) content-matches new remote record \(upstream.guid). Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// * New upstream only; no local overlay, content-based merge,
// or shared parent in the mirror. Insert it in the mirror.
log.debug("Never seen remote record \(upstream.guid). Mirroring.")
return self.insertNewMirror(upstream)
}
}
// N.B., the final guid is sometimes a WHERE and sometimes inserted.
private func mirrorArgs(login: ServerLogin) -> Args {
let args: Args = [
NSNumber(unsignedLongLong: login.serverModified),
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.timesUsed,
NSNumber(unsignedLongLong: login.timeLastUsed),
NSNumber(unsignedLongLong: login.timePasswordChanged),
NSNumber(unsignedLongLong: login.timeCreated),
login.password,
login.hostname,
login.username,
login.guid,
]
return args
}
/**
* Called when we have a changed upstream record and no local changes.
* There's no need to flip the is_overridden flag.
*/
private func updateMirrorToLogin(login: ServerLogin, fromPrevious previous: Login) -> Success {
let args = self.mirrorArgs(login)
let sql =
"UPDATE \(TableLoginsMirror) SET " +
" server_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?" +
// These we need to coalesce, because we might be supplying zeroes if the remote has
// been overwritten by an older client. In this case, preserve the old value in the
// mirror.
", timesUsed = coalesce(nullif(?, 0), timesUsed)" +
", timeLastUsed = coalesce(nullif(?, 0), timeLastUsed)" +
", timePasswordChanged = coalesce(nullif(?, 0), timePasswordChanged)" +
", timeCreated = coalesce(nullif(?, 0), timeCreated)" +
", password = ?, hostname = ?, username = ?" +
" WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Called when we have a completely new record. Naturally the new record
* is marked as non-overridden.
*/
private func insertNewMirror(login: ServerLogin, isOverridden: Int = 0) -> Success {
let args = self.mirrorArgs(login)
let sql =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") VALUES (\(isOverridden), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
return self.db.run(sql, withArgs: args)
}
/**
* We assume a local record matches if it has the same username (password can differ),
* hostname, httpRealm. We also check that the formSubmitURLs are either blank or have the
* same host and port.
*
* This is roughly the same as desktop's .matches():
* <https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginInfo.js#41>
*/
private func findLocalRecordByContent(login: Login) -> Deferred<Maybe<LocalLogin?>> {
let primary =
"SELECT * FROM \(TableLoginsLocal) WHERE " +
"hostname IS ? AND httpRealm IS ? AND username IS ?"
var args: Args = [login.hostname, login.httpRealm, login.username]
let sql: String
if login.formSubmitURL == nil {
sql = primary + " AND formSubmitURL IS NULL"
} else if login.formSubmitURL!.isEmpty {
sql = primary
} else {
if let hostPort = login.formSubmitURL?.asURL?.hostPort {
// Substring check will suffice for now. TODO: proper host/port check after fetching the cursor.
sql = primary + " AND (formSubmitURL = '' OR (instr(formSubmitURL, ?) > 0))"
args.append(hostPort)
} else {
log.warning("Incoming formSubmitURL is non-empty but is not a valid URL with a host. Not matching local.")
return deferMaybe(nil)
}
}
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory)
>>== { cursor in
switch (cursor.count) {
case 0:
return deferMaybe(nil)
case 1:
// Great!
return deferMaybe(cursor[0])
default:
// TODO: join against the mirror table to exclude local logins that
// already match a server record.
// Right now just take the first.
log.warning("Got \(cursor.count) local logins with matching details! This is most unexpected.")
return deferMaybe(cursor[0])
}
}
}
private func resolveConflictBetween(local local: LocalLogin, upstream: ServerLogin, shared: Login) -> Success {
// Attempt to compute two delta sets by comparing each new record to the shared record.
// Then we can merge the two delta sets -- either perfectly or by picking a winner in the case
// of a true conflict -- and produce a resultant record.
let localDeltas = (local.localModified, local.deltas(from: shared))
let upstreamDeltas = (upstream.serverModified, upstream.deltas(from: shared))
let mergedDeltas = Login.mergeDeltas(a: localDeltas, b: upstreamDeltas)
// Not all Sync clients handle the optional timestamp fields introduced in Bug 555755.
// We might get a server record with no timestamps, and it will differ from the original
// mirror!
// We solve that by refusing to generate deltas that discard information. We'll preserve
// the local values -- either from the local record or from the last shared parent that
// still included them -- and propagate them back to the server.
// It's OK for us to reconcile and reupload; it causes extra work for every client, but
// should not cause looping.
let resultant = shared.applyDeltas(mergedDeltas)
// We can immediately write the downloaded upstream record -- the old one -- to
// the mirror store.
// We then apply this record to the local store, and mark it as needing upload.
// When the reconciled record is uploaded, it'll be flushed into the mirror
// with the correct modified time.
return self.updateMirrorToLogin(upstream, fromPrevious: shared)
>>> { self.storeReconciledLogin(resultant) }
}
private func resolveConflictWithoutParentBetween(local local: LocalLogin, upstream: ServerLogin) -> Success {
// Do the best we can. Either the local wins and will be
// uploaded, or the remote wins and we delete our overlay.
if local.timePasswordChanged > upstream.timePasswordChanged {
log.debug("Conflicting records with no shared parent. Using newer local record.")
return self.insertNewMirror(upstream, isOverridden: 1)
}
log.debug("Conflicting records with no shared parent. Using newer remote record.")
let args: Args = [local.guid]
return self.insertNewMirror(upstream, isOverridden: 0)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid = ?", withArgs: args) }
}
public func getModifiedLoginsToUpload() -> Deferred<Maybe<[Login]>> {
let sql =
"SELECT * FROM \(TableLoginsLocal) " +
"WHERE sync_status IS NOT \(SyncStatus.Synced.rawValue) AND is_deleted = 0"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: SQLiteLogins.LoginFactory)
>>== { deferMaybe($0.asArray()) }
}
public func getDeletedLoginsToUpload() -> Deferred<Maybe<[GUID]>> {
// There are no logins that are marked as deleted that were not originally synced --
// others are deleted immediately.
let sql =
"SELECT guid FROM \(TableLoginsLocal) " +
"WHERE is_deleted = 1"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: { return $0["guid"] as! GUID })
>>== { deferMaybe($0.asArray()) }
}
/**
* Chains through the provided timestamp.
*/
public func markAsSynchronized(guids: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> {
// Update the mirror from the local record that we just uploaded.
// sqlite doesn't support UPDATE FROM, so instead of running 10 subqueries * n GUIDs,
// we issue a single DELETE and a single INSERT on the mirror, then throw away the
// local overlay that we just uploaded with another DELETE.
log.debug("Marking \(guids.count) GUIDs as synchronized.")
// TODO: transaction!
let args: Args = guids.map { $0 as AnyObject }
let inClause = BrowserDB.varlist(args.count)
let delMirror = "DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)"
let insMirror =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") SELECT 0, \(modified)" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid " +
"FROM \(TableLoginsLocal) " +
"WHERE guid IN \(inClause)"
let delLocal = "DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)"
return self.db.run(delMirror, withArgs: args)
>>> { self.db.run(insMirror, withArgs: args) }
>>> { self.db.run(delLocal, withArgs: args) }
>>> always(modified)
}
public func markAsDeleted(guids: [GUID]) -> Success {
log.debug("Marking \(guids.count) GUIDs as deleted.")
let args: Args = guids.map { $0 as AnyObject }
let inClause = BrowserDB.varlist(args.count)
return self.db.run("DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)", withArgs: args)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)", withArgs: args) }
}
public func hasSyncedLogins() -> Deferred<Maybe<Bool>> {
let checkLoginsMirror = "SELECT 1 FROM \(TableLoginsMirror)"
let checkLoginsLocal = "SELECT 1 FROM \(TableLoginsLocal) WHERE sync_status IS NOT \(SyncStatus.New.rawValue)"
let sql = "\(checkLoginsMirror) UNION ALL \(checkLoginsLocal)"
return self.db.queryReturnsResults(sql)
}
}
extension SQLiteLogins: ResettableSyncStorage {
/**
* Clean up any metadata.
* TODO: is this safe for a regular reset? It forces a content-based merge.
*/
public func resetClient() -> Success {
// Clone all the mirrors so we don't lose data.
return self.cloneMirrorToOverlay(whereClause: nil, args: nil)
// Drop all of the mirror data.
>>> { self.db.run("DELETE FROM \(TableLoginsMirror)") }
// Mark all of the local data as new.
>>> { self.db.run("UPDATE \(TableLoginsLocal) SET sync_status = \(SyncStatus.New.rawValue)") }
}
}
extension SQLiteLogins: AccountRemovalDelegate {
public func onRemovedAccount() -> Success {
return self.resetClient()
}
}
|
mpl-2.0
|
0db7e7097f67fc5b923392bc05a4c6d7
| 42.245491 | 204 | 0.611553 | 4.82979 | false | false | false | false |
volodg/iAsync.social
|
iAsync.social/Facebook/Errors/JFacebookError.swift
|
1
|
1531
|
import Foundation
import FBSDKCoreKit
import FBSDKLoginKit
import iAsync_utils
public enum FbErrorType {
case RequestLimitReached
case Undefined
}
final public class JFacebookError : JSocialError {
let nativeError: NSError
init(nativeError: NSError) {
self.nativeError = nativeError
super.init(description: "JFacebookError")
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public class func iAsyncErrorsDomain() -> String {
return "com.just_for_fun.facebook.library"
}
public override var localizedDescription: String {
if let descr = self.nativeError.userInfo["NSLocalizedRecoverySuggestion"] as? String {
return descr
}
return nativeError.localizedDescription
}
public lazy var fbErrorType: FbErrorType = { [unowned self] () -> FbErrorType in
if let descr = self.nativeError.userInfo["com.facebook.sdk:FBSDKErrorDeveloperMessageKey"] as? String {
let table: [String:FbErrorType] = [
"(#4) Application request limit reached" : FbErrorType.RequestLimitReached
]
return table[descr] ?? .Undefined
}
return .Undefined
}()
public override var errorLogDescription: String? {
switch fbErrorType {
case .RequestLimitReached:
return nil
case .Undefined:
return super.errorLogDescription
}
}
}
|
mit
|
4ad66f615d9ad9713839c4e96edf1696
| 22.921875 | 111 | 0.649902 | 4.875796 | false | false | false | false |
btanner/Eureka
|
Source/Rows/TriplePickerRow.swift
|
7
|
7127
|
//
// TriplePickerRow.swift
// Eureka
//
// Created by Mathias Claassen on 5/9/18.
// Copyright © 2018 Xmartlabs. All rights reserved.
//
import Foundation
import UIKit
public struct Tuple3<A: Equatable, B: Equatable, C: Equatable> {
public let a: A
public let b: B
public let c: C
public init(a: A, b: B, c: C) {
self.a = a
self.b = b
self.c = c
}
}
extension Tuple3: Equatable {}
public func == <A: Equatable, B: Equatable, C: Equatable>(lhs: Tuple3<A, B, C>, rhs: Tuple3<A, B, C>) -> Bool {
return lhs.a == rhs.a && lhs.b == rhs.b && lhs.c == rhs.c
}
// MARK: MultiplePickerCell
open class TriplePickerCell<A, B, C> : _PickerCell<Tuple3<A, B, C>> where A: Equatable, B: Equatable, C: Equatable {
private var pickerRow: _TriplePickerRow<A, B, C>? { return row as? _TriplePickerRow<A, B, C> }
public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func update() {
super.update()
if let selectedValue = pickerRow?.value, let indexA = pickerRow?.firstOptions().firstIndex(of: selectedValue.a),
let indexB = pickerRow?.secondOptions(selectedValue.a).firstIndex(of: selectedValue.b),
let indexC = pickerRow?.thirdOptions(selectedValue.a, selectedValue.b).firstIndex(of: selectedValue.c) {
picker.selectRow(indexA, inComponent: 0, animated: true)
picker.selectRow(indexB, inComponent: 1, animated: true)
picker.selectRow(indexC, inComponent: 2, animated: true)
}
}
open override func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
open override func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
guard let pickerRow = pickerRow else { return 0 }
if component == 0 {
return pickerRow.firstOptions().count
} else if component == 1 {
return pickerRow.secondOptions(pickerRow.selectedFirst()).count
} else {
return pickerRow.thirdOptions(pickerRow.selectedFirst(), pickerRow.selectedSecond()).count
}
}
open override func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
guard let pickerRow = pickerRow else { return "" }
if component == 0 {
return pickerRow.displayValueForFirstRow(pickerRow.firstOptions()[row])
} else if component == 1 {
return pickerRow.displayValueForSecondRow(pickerRow.secondOptions(pickerRow.selectedFirst())[row])
} else {
return pickerRow.displayValueForThirdRow(pickerRow.thirdOptions(pickerRow.selectedFirst(), pickerRow.selectedSecond())[row])
}
}
open override func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
guard let pickerRow = pickerRow else { return }
if component == 0 {
let a = pickerRow.firstOptions()[row]
if let value = pickerRow.value {
guard value.a != a else {
return
}
let b: B = pickerRow.secondOptions(a).contains(value.b) ? value.b : pickerRow.secondOptions(a)[0]
let c: C = pickerRow.thirdOptions(a, b).contains(value.c) ? value.c : pickerRow.thirdOptions(a, b)[0]
pickerRow.value = Tuple3(a: a, b: b, c: c)
pickerView.reloadComponent(1)
pickerView.reloadComponent(2)
if b != value.b {
pickerView.selectRow(0, inComponent: 1, animated: true)
}
if c != value.c {
pickerView.selectRow(0, inComponent: 2, animated: true)
}
} else {
let b = pickerRow.secondOptions(a)[0]
pickerRow.value = Tuple3(a: a, b: b, c: pickerRow.thirdOptions(a, b)[0])
pickerView.reloadComponent(1)
pickerView.reloadComponent(2)
pickerView.selectRow(0, inComponent: 1, animated: true)
pickerView.selectRow(0, inComponent: 2, animated: true)
}
} else if component == 1 {
let a = pickerRow.selectedFirst()
let b = pickerRow.secondOptions(a)[row]
if let value = pickerRow.value {
guard value.b != b else {
return
}
if pickerRow.thirdOptions(a, b).contains(value.c) {
pickerRow.value = Tuple3(a: a, b: b, c: value.c)
pickerView.reloadComponent(2)
return
} else {
pickerRow.value = Tuple3(a: a, b: b, c: pickerRow.thirdOptions(a, b)[0])
}
} else {
pickerRow.value = Tuple3(a: a, b: b, c: pickerRow.thirdOptions(a, b)[0])
}
pickerView.reloadComponent(2)
pickerView.selectRow(0, inComponent: 2, animated: true)
} else {
let a = pickerRow.selectedFirst()
let b = pickerRow.selectedSecond()
pickerRow.value = Tuple3(a: a, b: b, c: pickerRow.thirdOptions(a, b)[row])
}
}
}
// MARK: PickerRow
open class _TriplePickerRow<A, B, C> : Row<TriplePickerCell<A, B, C>> where A: Equatable, B: Equatable, C: Equatable {
/// Options for first component. Will be called often so should be O(1)
public var firstOptions: (() -> [A]) = {[]}
/// Options for second component given the selected value from the first component. Will be called often so should be O(1)
public var secondOptions: ((A) -> [B]) = {_ in []}
/// Options for third component given the selected value from the first and second components. Will be called often so should be O(1)
public var thirdOptions: ((A, B) -> [C]) = {_, _ in []}
/// Modify the displayed values for the first picker row.
public var displayValueForFirstRow: ((A) -> (String)) = { a in return String(describing: a) }
/// Modify the displayed values for the second picker row.
public var displayValueForSecondRow: ((B) -> (String)) = { b in return String(describing: b) }
/// Modify the displayed values for the third picker row.
public var displayValueForThirdRow: ((C) -> (String)) = { c in return String(describing: c) }
required public init(tag: String?) {
super.init(tag: tag)
}
func selectedFirst() -> A {
return value?.a ?? firstOptions()[0]
}
func selectedSecond() -> B {
return value?.b ?? secondOptions(selectedFirst())[0]
}
}
/// A generic row where the user can pick an option from a picker view
public final class TriplePickerRow<A, B, C>: _TriplePickerRow<A, B, C>, RowType where A: Equatable, B: Equatable, C: Equatable {
required public init(tag: String?) {
super.init(tag: tag)
}
}
|
mit
|
f9d5098f0555e7e19925afbbe3044dc1
| 39.488636 | 137 | 0.599495 | 4.254328 | false | false | false | false |
grpc/grpc-swift
|
Sources/Examples/RouteGuide/Server/RouteGuideProvider.swift
|
1
|
5668
|
/*
* Copyright 2019, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import GRPC
import NIOConcurrencyHelpers
import NIOCore
import RouteGuideModel
#if compiler(>=5.6)
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
internal final class RouteGuideProvider: Routeguide_RouteGuideAsyncProvider {
private let features: [Routeguide_Feature]
private let notes: Notes
internal init(features: [Routeguide_Feature]) {
self.features = features
self.notes = Notes()
}
internal func getFeature(
request point: Routeguide_Point,
context: GRPCAsyncServerCallContext
) async throws -> Routeguide_Feature {
return self.lookupFeature(at: point) ?? .unnamedFeature(at: point)
}
internal func listFeatures(
request: Routeguide_Rectangle,
responseStream: GRPCAsyncResponseStreamWriter<Routeguide_Feature>,
context: GRPCAsyncServerCallContext
) async throws {
let longitudeRange = request.lo.longitude ... request.hi.longitude
let latitudeRange = request.lo.latitude ... request.hi.latitude
for feature in self.features where !feature.name.isEmpty {
if feature.location.isWithin(latitude: latitudeRange, longitude: longitudeRange) {
try await responseStream.send(feature)
}
}
}
internal func recordRoute(
requestStream points: GRPCAsyncRequestStream<Routeguide_Point>,
context: GRPCAsyncServerCallContext
) async throws -> Routeguide_RouteSummary {
var pointCount: Int32 = 0
var featureCount: Int32 = 0
var distance = 0.0
var previousPoint: Routeguide_Point?
let startTimeNanos = DispatchTime.now().uptimeNanoseconds
for try await point in points {
pointCount += 1
if let feature = self.lookupFeature(at: point), !feature.name.isEmpty {
featureCount += 1
}
if let previous = previousPoint {
distance += previous.distance(to: point)
}
previousPoint = point
}
let durationInNanos = DispatchTime.now().uptimeNanoseconds - startTimeNanos
let durationInSeconds = Double(durationInNanos) / 1e9
return .with {
$0.pointCount = pointCount
$0.featureCount = featureCount
$0.elapsedTime = Int32(durationInSeconds)
$0.distance = Int32(distance)
}
}
internal func routeChat(
requestStream: GRPCAsyncRequestStream<Routeguide_RouteNote>,
responseStream: GRPCAsyncResponseStreamWriter<Routeguide_RouteNote>,
context: GRPCAsyncServerCallContext
) async throws {
for try await note in requestStream {
let existingNotes = await self.notes.addNote(note, to: note.location)
// Respond with all existing notes.
for existingNote in existingNotes {
try await responseStream.send(existingNote)
}
}
}
/// Returns a feature at the given location or an unnamed feature if none exist at that location.
private func lookupFeature(at location: Routeguide_Point) -> Routeguide_Feature? {
return self.features.first(where: {
$0.location.latitude == location.latitude && $0.location.longitude == location.longitude
})
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
internal final actor Notes {
private var recordedNotes: [Routeguide_Point: [Routeguide_RouteNote]]
internal init() {
self.recordedNotes = [:]
}
/// Record a note at the given location and return the all notes which were previously recorded
/// at the location.
internal func addNote(
_ note: Routeguide_RouteNote,
to location: Routeguide_Point
) -> ArraySlice<Routeguide_RouteNote> {
self.recordedNotes[location, default: []].append(note)
return self.recordedNotes[location]!.dropLast(1)
}
}
#endif // compiler(>=5.6)
private func degreesToRadians(_ degrees: Double) -> Double {
return degrees * .pi / 180.0
}
extension Routeguide_Point {
fileprivate func distance(to other: Routeguide_Point) -> Double {
// Radius of Earth in meters
let radius = 6_371_000.0
// Points are in the E7 representation (degrees multiplied by 10**7 and rounded to the nearest
// integer). See also `Routeguide_Point`.
let coordinateFactor = 1.0e7
let lat1 = degreesToRadians(Double(self.latitude) / coordinateFactor)
let lat2 = degreesToRadians(Double(other.latitude) / coordinateFactor)
let lon1 = degreesToRadians(Double(self.longitude) / coordinateFactor)
let lon2 = degreesToRadians(Double(other.longitude) / coordinateFactor)
let deltaLat = lat2 - lat1
let deltaLon = lon2 - lon1
let a = sin(deltaLat / 2) * sin(deltaLat / 2)
+ cos(lat1) * cos(lat2) * sin(deltaLon / 2) * sin(deltaLon / 2)
let c = 2 * atan2(sqrt(a), sqrt(1 - a))
return radius * c
}
func isWithin<Range: RangeExpression>(
latitude: Range,
longitude: Range
) -> Bool where Range.Bound == Int32 {
return latitude.contains(self.latitude) && longitude.contains(self.longitude)
}
}
extension Routeguide_Feature {
static func unnamedFeature(at location: Routeguide_Point) -> Routeguide_Feature {
return .with {
$0.name = ""
$0.location = location
}
}
}
|
apache-2.0
|
661fcdc0085e9257e9c9d088477a4539
| 31.022599 | 99 | 0.706069 | 4.025568 | false | false | false | false |
CPRTeam/CCIP-iOS
|
OPass/Tabs/CheckinTab/CheckinViewController.swift
|
1
|
33082
|
//
// CheckinViewController.swift
// OPass
//
// Created by 腹黒い茶 on 2019/6/16.
// 2019 OPass.
//
import Foundation
import UIKit
import AudioToolbox
import MBProgressHUD
import iCarousel
import ScanditBarcodeScanner
@objc enum HideCheckinViewOverlay: Int {
case Guide
case Status
case InvalidNetwork
}
@objc class CheckinViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, StatusViewDelegate, InvalidNetworkRetryDelegate, iCarouselDataSource, iCarouselDelegate, SBSScanDelegate, SBSProcessFrameDelegate {
@objc public var controllerTopStart: CGFloat = 0
@IBOutlet private var cards: iCarousel?
@IBOutlet private var ivRectangle: UIImageView?
@IBOutlet private var ivUserPhoto: UIImageView?
@IBOutlet private var lbHi: UILabel?
@IBOutlet private var lbUserName: UILabel?
private var pageControl: UIPageControl = UIPageControl.init()
private var scanditBarcodePicker: SBSBarcodePicker?
private var qrButtonItem: UIBarButtonItem?
private var guideViewController: GuideViewController?
private var statusViewController: StatusViewController?
private var invalidNetworkMsgViewController: InvalidNetworkMessageViewController?
private var progress: MBProgressHUD?
// MARK: - View Events
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.setBackgroundImage(UIImage.init(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage.init()
self.navigationController?.navigationBar.backgroundColor = .clear
AppDelegate.delegateInstance.checkinView = self
// Init configure pageControl
self.pageControl.numberOfPages = 0
// Init configure carousel
self.cards?.addSubview(self.pageControl)
self.cards?.type = .rotary
self.cards?.isPagingEnabled = true
self.cards?.bounceDistance = 0.3
self.cards?.contentOffset = CGSize(width: 0, height: -5)
Constants.SendFib("CheckinViewController")
let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(navSingleTap))
let isHidden = !Constants.haveAccessToken
self.lbUserName?.text = " "
self.lbUserName?.isUserInteractionEnabled = true
self.lbUserName?.addGestureRecognizer(tapGesture)
self.lbUserName?.isHidden = isHidden
self.lbHi?.isHidden = isHidden
self.ivUserPhoto?.image = Constants.AssertImage(name: "StaffIconDefault", InBundleName: "PassAssets")
self.ivUserPhoto?.isHidden = isHidden
self.ivUserPhoto?.layer.cornerRadius = (self.ivUserPhoto?.frame.size.height ?? 0) / 2
self.ivUserPhoto?.layer.masksToBounds = true
self.ivRectangle?.setGradientColor(from: Constants.appConfigColor.CheckinRectangleLeftColor, to: Constants.appConfigColor.CheckinRectangleRightColor, startPoint: CGPoint(x: -0.4, y: 0.5), toPoint: CGPoint(x: 1, y: 0.5))
NotificationCenter.default.addObserver(self, selector: #selector(appplicationDidBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.controllerTopStart = (self.view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0) + (self.navigationController?.navigationBar.frame.size.height ?? 0)
self.handleQRButton()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.reloadCard()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.hideView(.Guide, nil)
self.hideView(.Status, nil)
self.hideView(.InvalidNetwork, nil)
self.closeBarcodePickerOverlay()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
OPassAPI.scenarios = []
self.cards?.reloadData()
self.lbUserName?.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func appplicationDidBecomeActive(_ notification: NSNotification) {
self.reloadCard()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destination = segue.destination
switch destination.className {
case GuideViewController.className:
self.guideViewController = destination as? GuideViewController
case StatusViewController.className:
self.statusViewController = destination as? StatusViewController
self.statusViewController?.scenario = sender as? Scenario
self.statusViewController?.delegate = self
case InvalidNetworkMessageViewController.className:
if let inmvc = destination as? InvalidNetworkMessageViewController {
inmvc.message = sender as? String ?? ""
inmvc.delegate = self
}
default:
break
}
}
func refresh() {
self.reloadCard()
}
// MARK: - Dev Mode
@objc func navSingleTap() {
struct tap {
static var tapTimes: Int = 0
static var oldTapTime: Date?
static var newTapTime: Date?
}
// NSLog("navSingleTap")
tap.newTapTime = Date.init()
if tap.oldTapTime == nil {
tap.oldTapTime = tap.newTapTime
}
guard let oldTime = tap.oldTapTime else { return }
if Constants.isDevMode {
// NSLog("navSingleTap from MoreTab")
if ((tap.newTapTime?.timeIntervalSince(oldTime)) ?? TimeInterval(0)) <= TimeInterval(0.25) {
tap.tapTimes += 1
if tap.tapTimes >= 10 {
NSLog("-- Success tap 10 times --")
if Constants.haveAccessToken {
NSLog("-- Clearing the Token --")
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
Constants.accessToken = ""
AppDelegate.delegateInstance.checkinView?.reloadCard()
} else {
NSLog("-- Token is already clear --")
}
tap.tapTimes = 1
}
} else {
NSLog("-- Failed, just tap \(tap.tapTimes) times --")
NSLog("-- Not trigger clean token --")
tap.tapTimes = 1
}
tap.oldTapTime = tap.newTapTime
}
}
// MARK: - hide custom view controller method
func hideView(_ viewType: HideCheckinViewOverlay, _ completion: (() -> Void)?) {
let visible = [
HideCheckinViewOverlay.Guide: self.guideViewController?.isVisible,
HideCheckinViewOverlay.Status: self.statusViewController?.isVisible,
HideCheckinViewOverlay.InvalidNetwork: self.invalidNetworkMsgViewController?.isVisible
][viewType] ?? false
let isVisible: Bool = visible ?? false
let _completion = {
if let c = completion { c() }
}
if isVisible {
if let overlay = [
HideCheckinViewOverlay.Guide: {
self.guideViewController?.dismiss(animated: true, completion: {
self.guideViewController = nil
_completion()
})
},
HideCheckinViewOverlay.Status: {
self.statusViewController?.dismiss(animated: true, completion: {
self.statusViewController = nil
_completion()
})
},
HideCheckinViewOverlay.InvalidNetwork: {
self.invalidNetworkMsgViewController?.dismiss(animated: true, completion: {
self.invalidNetworkMsgViewController = nil
_completion()
})
}
][viewType] {
overlay()
}
} else {
_completion()
}
}
// MARK: - cards methods
func goToCard() {
if Constants.haveAccessToken {
let checkinCard = UserDefaults.standard.object(forKey: "CheckinCard") as? NSDictionary
if checkinCard != nil {
let key = checkinCard?.object(forKey: "key") as? String ?? ""
for item in OPassAPI.scenarios {
if item.Id == key {
if let index = OPassAPI.scenarios.firstIndex(of: item) {
NSLog("index: \(index)")
self.cards?.scrollToItem(at: index, animated: true)
}
}
}
UserDefaults.standard.removeObject(forKey: "CheckinCard")
} else {
// force scroll to first selected item at first load
if let cards = self.cards {
if cards.numberOfItems > 0 {
for scenario in OPassAPI.scenarios {
let used = scenario.Used != nil
let disabled = scenario.Disabled != nil
if !used && !disabled {
self.cards?.scrollToItem(at: OPassAPI.scenarios.firstIndex(of: scenario) ?? 0, animated: true)
break
}
}
}
}
}
UserDefaults.standard.synchronize()
}
self.progress?.hide(animated: true)
}
func reloadAndGoToCard() {
self.cards?.reloadData()
self.goToCard()
}
func showGuide() {
if self.scanditBarcodePicker == nil {
if !(self.presentedViewController?.isKind(of: GuideViewController.self) ?? false) {
self.performSegue(withIdentifier: "ShowGuide", sender: self.cards)
}
OPassAPI.scenarios.removeAll()
self.reloadAndGoToCard()
}
}
func processStatus() {
OPassAPI.GetCurrentStatus { success, obj, _ in
if success {
self.hideView(.Guide, nil)
if let userInfo = obj as? ScenarioStatus {
OPassAPI.userInfo = userInfo
OPassAPI.scenarios = OPassAPI.userInfo?.Scenarios ?? []
let isHidden = !Constants.haveAccessToken
self.lbHi?.isHidden = isHidden
self.ivUserPhoto?.isHidden = isHidden
self.lbUserName?.isHidden = isHidden
self.lbUserName?.text = OPassAPI.userInfo?.UserId
AppDelegate.sendTag("\(OPassAPI.userInfo?.EventId ?? "")\(OPassAPI.userInfo?.Role ?? "")", value: OPassAPI.userInfo?.Token ?? "")
if OPassAPI.isLoginSession {
AppDelegate.delegateInstance.displayGreetingsForLogin()
}
if ((OPassAPI.userInfo?.Role ?? "").count > 0) {
if let info = OPassAPI.userInfo {
self.cards?.isHidden = !((OPassAPI.eventInfo?.Features[OPassKnownFeatures.FastPass]?.VisibleRoles?.contains(info.Role)) ?? true)
}
}
OPassAPI.refreshTabBar()
OPassAPI.openFirstAvailableTab()
self.reloadAndGoToCard()
}
} else {
func broken(_ msg: String = "Networking_Broken") {
self.performSegue(withIdentifier: "ShowInvalidNetworkMsg", sender: NSLocalizedString(msg, comment: ""))
}
guard let sr = obj as? OPassNonSuccessDataResponse else {
// broken()
return
}
switch (sr.Response?.statusCode) {
case 200:
broken("Data_Wrong")
case 400:
guard let responseObject = sr.Obj as? NSDictionary else { return }
let msg = responseObject.value(forKeyPath: "json.message") as? String ?? ""
if msg == "invalid token" {
NSLog("\(msg)")
Constants.accessToken = ""
let ac = UIAlertController.alertOfTitle(NSLocalizedString("InvalidTokenAlert", comment: ""), withMessage: NSLocalizedString("InvalidTokenDesc", comment: ""), cancelButtonText: NSLocalizedString("GotIt", comment: ""), cancelStyle: .cancel) { _ in
self.reloadCard()
}
ac.showAlert {
UIImpactFeedback.triggerFeedback(.notificationFeedbackError)
}
}
case 403:
broken("Networking_WrongWiFi")
default:
broken()
}
}
}
}
@objc func reloadCard() {
if self.progress != nil {
self.progress?.hide(animated: true)
}
self.progress = MBProgressHUD.showAdded(to: self.view, animated: true)
self.progress?.mode = .indeterminate
self.handleQRButton()
let isHidden = !Constants.haveAccessToken
self.lbHi?.isHidden = isHidden
self.ivUserPhoto?.isHidden = isHidden
self.lbUserName?.isHidden = isHidden
self.lbUserName?.text = " "
if !Constants.haveAccessToken {
self.showGuide()
} else {
self.processStatus()
}
}
// MARK: - display messages
func showCountdown(_ scenario: Scenario) {
self.lbHi?.isHidden = true
self.lbUserName?.isHidden = true
self.ivUserPhoto?.isHidden = true
NSLog("Show Countdown: \(scenario)")
self.performSegue(withIdentifier: "ShowCountdown", sender: scenario)
}
public func statusViewDisappear() {
let isHidden = !Constants.haveAccessToken
self.lbHi?.isHidden = isHidden
self.ivUserPhoto?.isHidden = isHidden
self.lbUserName?.isHidden = isHidden
}
@objc func showInvalidNetworkMsg(_ msg: String? = nil) {
self.performSegue(withIdentifier: "ShowInvalidNetworkMsg", sender: msg)
}
// MARK: - QR Code Scanner
func handleQRButton() {
if self.qrButtonItem == nil {
self.qrButtonItem = UIBarButtonItem.init(image: Constants.AssertImage(name: "QR_Code", InBundleName: "AssetsUI"), landscapeImagePhone: nil, style: .plain, target: self, action: #selector(callBarcodePickerOverlay))
}
self.navigationItem.rightBarButtonItem = nil
if Constants.isDevMode || !Constants.haveAccessToken {
self.navigationItem.rightBarButtonItem = self.qrButtonItem
}
}
func hideQRButton() {
if !Constants.isDevMode {
self.navigationItem.rightBarButtonItem = nil
}
}
public func barcodePicker(_ barcodePicker: SBSBarcodePicker, didProcessFrame frame: CMSampleBuffer, session: SBSScanSession) {
//
}
//! [SBSBarcodePicker overlayed as a view]
/**
* A simple example of how the barcode picker can be used in a simple view of various dimensions
* and how it can be added to any o ther view. This example scales the view instead of cropping it.
*/
public func barcodePicker(_ picker: SBSBarcodePicker, didScan session: SBSScanSession) {
session.pauseScanning()
let recognized = session.newlyRecognizedCodes
if let code = recognized.first {
// Add your own code to handle the barcode result e.g.
NSLog("scanned \(code.symbologyName) barcode: \(String(describing: code.data))")
OperationQueue.main.addOperation {
OPassAPI.RedeemCode(forEvent: "", withToken: code.data ?? "") { (success, obj, _) in
if success {
self.perform(#selector(self.reloadCard), with: nil, afterDelay: 0.5)
self.perform(#selector(self.closeBarcodePickerOverlay), with: nil, afterDelay: 0.5)
} else {
func broken(_ msg: String = "") {
let ac = UIAlertController.alertOfTitle(NSLocalizedString("GuideViewTokenErrorTitle", comment: ""), withMessage: NSLocalizedString("GuideViewTokenErrorDesc", comment: ""), cancelButtonText: NSLocalizedString("GotIt", comment: ""), cancelStyle: .cancel) { _ in
self.scanditBarcodePicker?.resumeScanning()
}
ac.showAlert {
UIImpactFeedback.triggerFeedback(.notificationFeedbackError)
}
}
guard let sr = obj as? OPassNonSuccessDataResponse else {
return
}
switch (sr.Response?.statusCode) {
case 400:
guard let responseObject = sr.Obj as? NSDictionary else { return }
let msg = responseObject.value(forKeyPath: "json.message") as? String ?? ""
if msg == "invalid token" {
NSLog("\(msg)")
broken()
}
case 403:
broken("Networking_WrongWiFi")
default:
return
}
}
}
}
}
}
@objc func closeBarcodePickerOverlay() {
if self.scanditBarcodePicker != nil {
self.qrButtonItem?.image = Constants.AssertImage(name: "QR_Code", InBundleName: "AssetsUI")
self.scanditBarcodePicker?.removeFromParent()
self.scanditBarcodePicker?.view.removeFromSuperview()
self.scanditBarcodePicker?.didMove(toParent: nil)
self.scanditBarcodePicker = nil
let isHidden = !Constants.haveAccessToken
self.lbHi?.isHidden = isHidden
self.lbUserName?.isHidden = isHidden
self.ivUserPhoto?.isHidden = isHidden
}
}
@objc func callBarcodePickerOverlay() {
self.hideView(.Guide) {
self.showBarcodePickerOverlay()
}
}
func showBarcodePickerOverlay() {
if self.scanditBarcodePicker != nil {
self.closeBarcodePickerOverlay()
if !Constants.haveAccessToken {
self.performSegue(withIdentifier: "ShowGuide", sender: nil)
} else {
self.hideQRButton()
}
} else {
self.lbHi?.isHidden = true
self.ivUserPhoto?.isHidden = true
self.qrButtonItem?.image = Constants.AssertImage(name: "QR_Code_Filled", InBundleName: "AssetsUI")
// Configure the barcode picker through a scan settings instance by defining which
// symbologies should be enabled.
let scanSettings = SBSScanSettings.default()
// prefer backward facing camera over front-facing cameras.
scanSettings.cameraFacingPreference = .back
// Enable symbologies that you want to scan
scanSettings.setSymbology(.qr, enabled: true)
self.scanditBarcodePicker = SBSBarcodePicker.init(settings: scanSettings)
/* Set the delegate to receive callbacks.
* This is commented out here in the demo app since the result view with the scan results
* is not suitable for this overlay view */
self.scanditBarcodePicker?.scanDelegate = self
self.scanditBarcodePicker?.processFrameDelegate = self
// Add a button behind the subview to close it.
// self.backgroundButton.hidden = NO;
if let picker = self.scanditBarcodePicker {
self.addChild(picker)
self.view.addSubview(picker.view)
self.scanditBarcodePicker?.didMove(toParent: self)
}
self.scanditBarcodePicker?.view.translatesAutoresizingMaskIntoConstraints = false
// Add constraints to scale the view and place it in the center of the controller.
self.view.addConstraint(NSLayoutConstraint.init(item: self.scanditBarcodePicker?.view as Any, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint.init(item: self.scanditBarcodePicker?.view as Any, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: self.controllerTopStart))
// Add constraints to set the width to 200 and height to 400. Since this is not the aspect ratio
// of the camera preview some of the camera preview will be cut away on the left and right.
self.view.addConstraint(NSLayoutConstraint.init(item: self.scanditBarcodePicker?.view as Any, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint.init(item: self.scanditBarcodePicker?.view as Any, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: -(self.tabBarController?.tabBar.frame.size.height ?? 0)))
// add "OpenQRCodeFromFile" button
let barcodePickerOverlay = self.scanditBarcodePicker?.overlayController.view
let torchButton = barcodePickerOverlay?.subviews[2]
let button = UIButton.init(type: .roundedRect)
button.layer.masksToBounds = false
button.layer.cornerRadius = (torchButton?.frame.height ?? 2) / 2
button.frame = CGRect(x: (torchButton?.frame.origin.x ?? 0) + (torchButton?.frame.width ?? 0) + 15, y: (torchButton?.frame.origin.y ?? 0) + (self.navigationController?.navigationBar.frame.height ?? 0), width: 80, height: (torchButton?.frame.height ?? 0))
button.backgroundColor = UIColor.white.withAlphaComponent(0.35)
button.setTitle(NSLocalizedString("OpenQRCodeFromFile", comment: ""), for: .normal)
button.tintColor = .black
button.addTarget(self, action: #selector(getImageFromLibrary), for: .touchUpInside)
barcodePickerOverlay?.addSubview(button)
self.scanditBarcodePicker?.startScanning(inPausedState: true, completionHandler: {
self.scanditBarcodePicker?.perform(#selector(SBSBarcodePicker.startScanning as (SBSBarcodePicker) -> () -> Void), with: nil, afterDelay: 0.5)
})
}
}
// MARK: - QR Code from Camera Roll Library
@objc func getImageFromLibrary() {
let imagePicker = UIImagePickerController.init()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
self.present(imagePicker, animated: true, completion: nil)
}
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
let mediaType = info[.mediaType] as? String ?? ""
if mediaType == "public.image" {
guard let srcImage = info[.originalImage] as? UIImage else { return }
guard let detector = CIDetector.init(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]) else { return }
guard let cgImage = srcImage.cgImage else { return }
let image = CIImage.init(cgImage: cgImage)
guard let features = detector.features(in: image) as? [CIQRCodeFeature] else { return }
var ac: UIAlertController? = nil
var noQR = false
if (features.count == 0) {
NSLog("no QR in the image")
noQR = true
} else {
for feature in features {
NSLog("feature: \(String(describing: feature.messageString))")
}
guard let feature = features.first else { return }
let result = feature.messageString
NSLog("QR: \(String(describing: result))")
if result == nil {
noQR = true
} else {
OPassAPI.RedeemCode(forEvent: "", withToken: result ?? "") { (success, _, _) in
if success {
picker.dismiss(animated: true) {
// self.reloadCard()
}
} else {
ac = UIAlertController.alertOfTitle(NSLocalizedString("GuideViewTokenErrorTitle", comment: ""), withMessage: NSLocalizedString("GuideViewTokenErrorDesc", comment: ""), cancelButtonText: NSLocalizedString("GotIt", comment: ""), cancelStyle: .cancel, cancelAction: nil)
ac?.showAlert {
UIImpactFeedback.triggerFeedback(.notificationFeedbackError)
}
}
}
}
}
if (noQR) {
ac = UIAlertController.alertOfTitle(NSLocalizedString("QRFileNotAvailableTitle", comment: ""), withMessage: NSLocalizedString("QRFileNotAvailableDesc", comment: ""), cancelButtonText: NSLocalizedString("GotIt", comment: ""), cancelStyle: .cancel, cancelAction: nil)
ac?.showAlert {
UIImpactFeedback.triggerFeedback(.notificationFeedbackError)
}
}
}
}
// MARK: - iCarousel methods
func carouselCurrentItemIndexDidChange(_ carousel: iCarousel) {
if OPassAPI.scenarios.count > 0 {
self.pageControl.currentPage = carousel.currentItemIndex
}
}
func numberOfItems(in carousel: iCarousel) -> Int {
let count = OPassAPI.scenarios.count
self.pageControl.numberOfPages = count
return count
}
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
struct card {
static var cardRect = CGRect()
}
var view = view
// Init configure pageControl
self.pageControl.isHidden = true // set page control to hidden
if card.cardRect.isEmpty {
let pageControlFrame = self.pageControl.frame
self.pageControl.frame = CGRect(x: self.view.frame.size.width / 2, y: ((self.cards?.frame.size.height ?? 0) + (self.cards?.frame.size.height ?? 0) - (self.pageControl.isHidden ? 0 : 10)) / 2, width: pageControlFrame.size.width, height: pageControlFrame.size.height)
// Init cardRect
// x 0, y 0, left 30, up 40, right 30, bottom 50
// self.cards.contentOffset = CGSizeMake(0, -5.0f); // set in viewDidLoad
// 414 736
card.cardRect = CGRect(x: 0, y: 0, width: (self.cards?.bounds.size.width ?? 0), height: (self.cards?.frame.size.height ?? 0) - (self.pageControl.isHidden ? 0 : 10))
}
// create new view if no view is available for recycling
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let haveScenario = OPassAPI.scenarios.count > 0
if haveScenario {
guard let temp = storyboard.instantiateViewController(withIdentifier: "CheckinCardReuseView") as? CheckinCardViewController else { return UIView.init() }
temp.view.frame = card.cardRect
view = temp.view
let scenario = OPassAPI.scenarios[index]
let id = scenario.Id
let isCheckin = id.contains("checkin")
let isLunch = id.contains("lunch")
let isKit = id.lowercased().contains("kit")
let isVipKit = id.lowercased().contains("vipkit")
let isShirt = id.lowercased().contains("shirt")
let isRadio = id.contains("radio")
let isDisabled = scenario.Disabled != nil
let isUsed = scenario.Used != nil
temp.setId(id)
let dateRange = OPassAPI.ParseScenarioRange(scenario)
let availableRange = "\(dateRange.first ?? "")\n\(dateRange.last ?? "")"
let dd = OPassAPI.ParseScenarioType(id)
let did = dd["did"]
let scenarioType = dd["scenarioType"]
let defaultIcon = Constants.AssertImage(name: "doc", InBundleName: "PassAssets")
let scenarioIcon = Constants.AssertImage(name: (scenarioType as? String) ?? "", InBundleName: "PassAssets") ?? defaultIcon
temp.checkinTitle.textColor = Constants.appConfigColor.CardTextColor
temp.checkinTitle.text = scenario.DisplayText
temp.checkinDate.textColor = Constants.appConfigColor.CardTextColor
temp.checkinDate.text = availableRange
temp.checkinText.textColor = Constants.appConfigColor.CardTextColor
temp.checkinText.text = NSLocalizedString("CheckinNotice", comment: "")
temp.checkinIcon.image = scenarioIcon
if isCheckin {
if let day = did {
temp.checkinIcon.image = Constants.AssertImage(name: "day\(day)", InBundleName: "PassAssets")
temp.checkinText.text = NSLocalizedString("CheckinText", comment: "")
}
}
if isLunch {
// nothing to do
}
if isKit {
// nothing to do
}
if isVipKit {
temp.checkinText.text = NSLocalizedString("CheckinTextVipKit", comment: "")
}
if isShirt {
temp.checkinText.text = NSLocalizedString("CheckinStaffShirtNotice", comment: "")
}
if isRadio {
temp.checkinText.text = NSLocalizedString("CheckinStaffRadioNotice", comment: "")
}
if isDisabled {
temp.setDisabled(scenario.Disabled)
temp.checkinBtn.setTitle("\(scenario.Disabled ?? "")", for: .normal)
temp.checkinBtn.setGradientColor(from: Constants.appConfigColor.DisabledButtonLeftColor, to: Constants.appConfigColor.DisabledButtonRightColor, startPoint: CGPoint(x: 0.2, y: 0.8), toPoint: CGPoint(x: 1, y: 0.5))
} else if isUsed {
temp.setUsed(scenario.Used)
if isCheckin {
temp.checkinBtn.setTitle(NSLocalizedString("CheckinViewButtonPressed", comment: ""), for: .normal)
} else {
temp.checkinBtn.setTitle(NSLocalizedString("UseButtonPressed", comment: ""), for: .normal)
}
temp.checkinBtn.setGradientColor(from: Constants.appConfigColor.UsedButtonLeftColor, to: Constants.appConfigColor.UsedButtonRightColor, startPoint: CGPoint(x: 0.2, y: 0.8), toPoint: CGPoint(x: 1, y: 0.5))
} else {
temp.setUsed(nil)
if isCheckin {
temp.checkinBtn.setTitle(NSLocalizedString("CheckinViewButton", comment: ""), for: .normal)
} else {
temp.checkinBtn.setTitle(NSLocalizedString("UseButton", comment: ""), for: .normal)
}
temp.checkinBtn.setGradientColor(from: Constants.appConfigColor.CheckinButtonLeftColor, to: Constants.appConfigColor.CheckinButtonRightColor, startPoint: CGPoint(x: 0.2, y: 0.8), toPoint: CGPoint(x: 1, y: 0.5))
}
temp.checkinBtn.tintColor = .white
temp.setDelegate(self)
temp.setScenario(scenario)
}
return view ?? UIView.init()
}
func carousel(_ carousel: iCarousel, valueFor option: iCarouselOption, withDefault value: CGFloat) -> CGFloat {
switch (option) {
case .wrap:
//normally you would hard-code this to YES or NO
return 0
case .spacing:
//add a bit of spacing between the item views
return value * 0.9
case .fadeMax:
return 0
case .fadeMin:
return 0
case .fadeMinAlpha:
return 0.65
case .arc:
return value * (CGFloat(carousel.numberOfItems) / 48)
case .radius:
return value
case .showBackfaces, .angle, .tilt, .count, .fadeRange, .offsetMultiplier, .visibleItems:
return value
default:
return value
}
}
}
|
gpl-3.0
|
1bb480afef3b12536b5249b46030665f
| 43.694595 | 295 | 0.581877 | 5.045614 | false | false | false | false |
scoremedia/Fisticuffs
|
Sources/Fisticuffs/BindableProperty.swift
|
1
|
5109
|
// The MIT License (MIT)
//
// Copyright (c) 2015 theScore Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
open class BindableProperty<Control: AnyObject, ValueType> {
public typealias Setter = (Control, ValueType) -> Void
weak var control: Control?
let setter: (Control, ValueType) -> Void
var currentBinding: Disposable?
public init(_ control: Control?, setter: @escaping Setter) {
self.control = control
self.setter = setter
}
deinit {
currentBinding?.dispose()
}
}
public extension BindableProperty {
/// Bind property to subscribable
///
/// - Parameters:
/// - subscribable: The `Subscribable`
/// - receiveOn: The `Scheduler` for the call back. Defaults to `MainThreadScheduler`
func bind(_ subscribable: Subscribable<ValueType>, receiveOn scheduler: Scheduler = MainThreadScheduler()) {
bind(subscribable, receiveOn: scheduler, DefaultBindingHandler())
}
/// Bind property to subscribable
///
/// - Parameters:
/// - subscribable: The `Subscribable`
/// - receiveOn: The `Scheduler` for the call back. Defaults to `MainThreadScheduler`
/// - bindingHandler: The custom `BindingHandler`
func bind<Data>(
_ subscribable: Subscribable<Data>,
receiveOn scheduler: Scheduler = MainThreadScheduler(),
_ bindingHandler: BindingHandler<Control, Data, ValueType>
) {
currentBinding?.dispose()
currentBinding = nil
guard let control = control else { return }
bindingHandler.setup(control, propertySetter: setter, subscribable: subscribable, receiveOn: scheduler)
currentBinding = bindingHandler
}
}
public extension BindableProperty where ValueType: OptionalType {
/// Bind property to subscribable
///
/// - Parameters:
/// - subscribable: The `Subscribable`
/// - receiveOn: The `Scheduler` for the call back. Defaults to `MainThreadScheduler`
func bind(_ subscribable: Subscribable<ValueType.Wrapped>, receiveOn scheduler: Scheduler = MainThreadScheduler()) {
bind(subscribable, DefaultBindingHandler())
}
/// Bind property to subscribable
///
/// - Parameters:
/// - subscribable: The `Subscribable`
/// - receiveOn: The `Scheduler` for the call back. Defaults to `MainThreadScheduler`
/// - bindingHandler: The custom `BindingHandler`
func bind<Data>(
_ subscribable: Subscribable<Data>,
receiveOn scheduler: Scheduler = MainThreadScheduler(),
_ bindingHandler: BindingHandler<Control, Data, ValueType.Wrapped>
) {
currentBinding?.dispose()
currentBinding = nil
guard let control = control else { return }
let outerBindingHandler = OptionalTypeBindingHandler<Control, Data, ValueType>(innerHandler: bindingHandler)
outerBindingHandler.setup(control, propertySetter: setter, subscribable: subscribable, receiveOn: scheduler)
currentBinding = outerBindingHandler
}
}
public extension BindableProperty {
@available(*, deprecated, message: "Use BindableProperty(subscribable, BindingHandlers.transform(...)) instead")
func bind<OtherType>(_ subscribable: Subscribable<OtherType>, transform: @escaping (OtherType) -> ValueType) {
bind(subscribable, BindingHandlers.transform(transform))
}
@available(*, deprecated, message: "Use a Computed in place of the `block`")
func bind(_ block: @escaping () -> ValueType) {
currentBinding?.dispose()
currentBinding = nil
guard let control = control else { return }
var computed: Computed<ValueType>? = Computed<ValueType>(block: block)
let bindingHandler = DefaultBindingHandler<Control, ValueType>()
bindingHandler.setup(control, propertySetter: setter, subscribable: computed!)
currentBinding = DisposableBlock {
computed = nil // keep a strong reference to the Computed
bindingHandler.dispose()
}
}
}
|
mit
|
cda445c695592168e0136339fa5b5e6d
| 38.3 | 120 | 0.687219 | 4.743733 | false | false | false | false |
beeth0ven/BNKit
|
BNKit/Source/Rx+/CLLocationManager+Rx.swift
|
1
|
2762
|
//
// CLLocationManager+Rx.swift
// WorkMap
//
// Created by luojie on 16/10/10.
// Copyright © 2016年 LuoJie. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import MapKit
public class RxLocationManagerDelegateProxy: DelegateProxy, DelegateProxyType, CLLocationManagerDelegate {
typealias HasDelegate = CLLocationManager
typealias Delegate = CLLocationManagerDelegate
public static func currentDelegateFor(_ object: AnyObject) -> AnyObject? {
let hasDelegate = object as! HasDelegate
return hasDelegate.delegate
}
public static func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) {
let hasDelegate = object as! HasDelegate
hasDelegate.delegate = delegate as? Delegate
}
}
extension Reactive where Base: CLLocationManager {
public var delegate: DelegateProxy {
return RxLocationManagerDelegateProxy.proxyForObject(base)
}
public var didUpdateLocations: Observable<[CLLocation]> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didUpdateLocations:)))
.map { params in params[1] as! [CLLocation] }
}
public var didChangeAuthorizationStatus: Observable<CLAuthorizationStatus> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didChangeAuthorization:)))
.map { params in CLAuthorizationStatus(rawValue: (params[1] as! NSNumber).int32Value)! }
}
public var didAuthorize: Observable<Void> {
let status: CLAuthorizationStatus = CLLocationManager.authorizationStatus()
switch status {
case .authorizedAlways, .authorizedWhenInUse:
break
case .restricted:
let alert = UIAlertController(title: "Work Map", message: "Location service is restricted!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
case .denied:
let alert = UIAlertController(title: "Work Map", message: "Location service is denied!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Authorize", style: .default, handler: { _ in UIApplication.shared.openSettings() }))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
case .notDetermined:
self.base.requestWhenInUseAuthorization()
}
return didChangeAuthorizationStatus
.startWith(status)
.filter { (state: CLAuthorizationStatus) in state == .authorizedAlways || state == .authorizedWhenInUse }
.mapToVoid()
}
}
|
mit
|
12d75696f6cd8fd15cad4515b6d31114
| 36.283784 | 134 | 0.674157 | 5.529058 | false | false | false | false |
el-hoshino/NotAutoLayout
|
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/CenterTopHeight.Individual.swift
|
1
|
1294
|
//
// CenterTopHeight.Individual.swift
// NotAutoLayout
//
// Created by 史翔新 on 2017/06/20.
// Copyright © 2017年 史翔新. All rights reserved.
//
import Foundation
extension IndividualProperty {
public struct CenterTopHeight {
let center: LayoutElement.Horizontal
let top: LayoutElement.Vertical
let height: LayoutElement.Length
}
}
// MARK: - Make Frame
extension IndividualProperty.CenterTopHeight {
private func makeFrame(center: Float, top: Float, height: Float, width: Float) -> Rect {
let x = center - width.half
let y = top
let frame = Rect(x: x, y: y, width: width, height: height)
return frame
}
}
// MARK: - Set A Length -
// MARK: Width
extension IndividualProperty.CenterTopHeight: LayoutPropertyCanStoreWidthToEvaluateFrameType {
public func evaluateFrame(width: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect {
let center = self.center.evaluated(from: parameters)
let top = self.top.evaluated(from: parameters)
let height = self.height.evaluated(from: parameters, withTheOtherAxis: .width(0))
let width = width.evaluated(from: parameters, withTheOtherAxis: .height(height))
return self.makeFrame(center: center, top: top, height: height, width: width)
}
}
|
apache-2.0
|
96cbec22d5d671325e7a6985d6c69947
| 22.254545 | 115 | 0.721658 | 3.772861 | false | false | false | false |
FrostDigital/HyperIsland-ios
|
HI-Segue-Demo/HI-Segue-Demo/HIColoredViewController.swift
|
1
|
1037
|
//
// HIColoredViewController.swift
// HI-Segue-Demo
//
// Created by Sergii Nezdolii on 06/03/16.
// Copyright © 2016 HyperIsland. All rights reserved.
//
import UIKit
extension UIColor {
func inverse () -> UIColor {
var r:CGFloat = 0.0; var g:CGFloat = 0.0; var b:CGFloat = 0.0; var a:CGFloat = 0.0;
if self.getRed(&r, green: &g, blue: &b, alpha: &a) {
return UIColor(red: 1.0-r, green: 1.0 - g, blue: 1.0 - b, alpha: a)
}
return self
}
}
class HIColoredViewController: UIViewController {
var shouldInverseColor: Bool?
var baseColor: UIColor?
override func viewDidLoad() {
super.viewDidLoad()
//Need to make sure that baseColor is set, otherwise skip color setup
guard let bgColor = baseColor else {
return
}
if shouldInverseColor == true {
self.view.backgroundColor = bgColor.inverse()
} else {
self.view.backgroundColor = bgColor
}
}
}
|
mit
|
87330fb1c70a678584fb45c529ade85f
| 24.268293 | 91 | 0.578185 | 3.822878 | false | false | false | false |
nikHowlett/Attend-O
|
attendo1/newStudentViewController.swift
|
1
|
2831
|
//
// newStudentViewController.swift
// attendo1
//
// Created by Nik Howlett on 4/10/16.
// Copyright © 2016 NikHowlett. All rights reserved.
//
import UIKit
class newStudentViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var items: [String] = ["CS 1332", "CS 2340", "CS 3750"]
var groups: [String] = ["A1", "F3", "B2"]
var theClass = "CS 1332"
var classes2: [Class]?
var username: String = "George P. Burdell"
@IBOutlet weak var welcomeString: UILabel!
@IBOutlet weak var classTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.classTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "ClassCell")
self.title = "Select a Class"
print(classes2)
print("classes printed")
if classes2?.count > 0 {
var be = 0
items = []
while be < classes2?.count {
items.append("\(classes2![be])")
be = be + 1
}
welcomeString.text! = "Welcome \(username)"
}
//self.classes = TSAuthenticatedReader2.getActiveClasses()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.classTable.dequeueReusableCellWithIdentifier("ClassCell")! as UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
cell.detailTextLabel?.text = self.groups[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
theClass = items[indexPath.row]
self.performSegueWithIdentifier("segueTest", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "segueTest") {
let svc = segue.destinationViewController as! studentCalViewController;
svc.toPass = theClass
}
}
/*
// 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.
}
*/
}
|
mit
|
799b462ccb15f8697dfe65ce0e82d339
| 31.528736 | 117 | 0.634629 | 4.938918 | false | false | false | false |
BenziAhamed/Tracery
|
CommonTesting/Helpers.swift
|
1
|
1590
|
//
// Helpers.swift
// Tracery
//
// Created by Benzi on 11/03/17.
// Copyright © 2017 Benzi Ahamed. All rights reserved.
//
import Foundation
import XCTest
@testable import Tracery
func XCTAssertItemInArray<T: Equatable>(item: T, array: [T]) {
XCTAssert(array.contains(where: { $0 == item }), "\(item) was not found in \(array)")
}
extension Array {
func regexGenerateMatchesAnyItemPattern() -> String {
return "(" + self.map { "\($0)" }.joined(separator: "|") + ")"
}
}
extension Sequence {
func mapDict<Key: Hashable,Value>(_ transform:(Iterator.Element)->(Key, Value)) -> Dictionary<Key, Value> {
var d = Dictionary<Key, Value>()
forEach {
let (k,v) = transform($0)
d[k] = v
}
return d
}
@discardableResult
func scan<T>(_ initial: T, _ combine: (T, Iterator.Element) throws -> T) rethrows -> [T] {
var accu = initial
return try map { e in
accu = try combine(accu, e)
return accu
}
}
}
extension Tracery {
class func hierarchical(rules: ()->[String:Any]) -> Tracery {
let options = TraceryOptions()
options.tagStorageType = .heirarchical
return Tracery.init(options, rules: rules)
}
class func hierarchical() -> Tracery {
return hierarchical {[:]}
}
func expandVerbose(_ text: String) -> String {
Tracery.logLevel = .verbose
defer {
Tracery.logLevel = .errors
}
return self.expand(text)
}
}
|
mit
|
1fdd3278a52494c067ac61e9679bb74f
| 22.367647 | 111 | 0.561359 | 4.032995 | false | false | false | false |
grayunicorn/Quiz
|
Quiz/Teacher/TeacherViewController.swift
|
1
|
6455
|
//
// TeacherViewController.swift
// Quiz
//
// Created by Adam Eberbach on 11/9/17.
// Copyright © 2017 Adam Eberbach. All rights reserved.
//
import Foundation
import UIKit
import CoreData
// the Teacher view controller should present the Teacher's view as a table
// 1. quizzes that this teacher can set answers for (used in automatic grading)
// 2. quizzes that this teacehr needs to manually mark, as written by students (i.e. text questions)
// 3. students that can be viewed (leading to results)
class TeacherViewController: UIViewController {
var me: Teacher?
var moc: NSManagedObjectContext? = nil
var selectedQuizCollection: QuizCollection?
var selectedStudent: Student?
var grading = false
// these two arrays are used for precalculation of table view display
var needGrading: [QuizCollection] = []
var haveResults: [Student] = []
@IBOutlet weak var tableView: UITableView!
let kQuizSection = 0
let kCorrectionSection = 1
let kResultsSection = 2
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let studentResultsVC = segue.destination as? StudentResultsViewController {
studentResultsVC.teacher = me
studentResultsVC.student = selectedStudent
} else if let quizVC = segue.destination as? QuizViewController {
// go and edit a quiz
quizVC.quizCollection = selectedQuizCollection
if grading == true {
quizVC.gradingView = true
}
quizVC.moc = moc!
}
}
// refresh table view whenever this view appears
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
prepareTableView()
}
override func viewDidLoad() {
super.viewDidLoad()
if let me = me, let name = me.login {
self.navigationItem.title = name
}
}
// gather the information to get this table view displayed correctly and reload data
func prepareTableView() {
guard let me = me else { return }
grading = false
// empty the arrays
needGrading = []
haveResults = []
// gather every quiz that is completed by a student and requires Teacher grading
if let students = me.students {
for student in students {
let student = student as! Student
needGrading.append(contentsOf: student.quizzesRequiringGrading())
let completeQuizzes = student.gradeableResults()
if completeQuizzes.count > 0 {
// gather each student that has results that can be viewed
haveResults.append(student)
}
}
}
// cause refresh of the table view
tableView.reloadData()
}
}
// MARK:- UITableViewDelegate
extension TeacherViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let me = me else { return }
if indexPath.section == kQuizSection {
// select the teacher's quiz for this row
if let quizzes = me.quizzes {
if let quizCollection = quizzes[indexPath.row] as? QuizCollection {
// go to the quiz screen where the teacher can edit answers
selectedQuizCollection = quizCollection
performSegue(withIdentifier: "TeacherQuizSegue", sender: self)
}
}
} else if indexPath.section == kCorrectionSection {
// go to the quiz screen where the teacher can edit answers
selectedQuizCollection = needGrading[indexPath.row]
grading = true
performSegue(withIdentifier: "TeacherQuizSegue", sender: self)
} else if indexPath.section == kResultsSection {
selectedStudent = haveResults[indexPath.row]
performSegue(withIdentifier: "TeacherStudentResultsSegue", sender: self)
}
tableView.deselectRow(at: indexPath, animated: true)
}
}
// MARK:- UITableViewDataSource
extension TeacherViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == kQuizSection {
return "My Quizzes"
} else if section == kCorrectionSection {
return "Grading Required"
} else if section == kResultsSection {
return "Results"
}
return nil
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = UITableViewCell()
guard let me = me, let quizzes = me.quizzes, let students = me.students else { return cell }
if indexPath.section == kQuizSection {
// populate the cell with this Teacher's quiz at the index path
if let newCell = tableView.dequeueReusableCell(withIdentifier: "QuizTitleTableViewCell") {
let quiz = quizzes[indexPath.row] as! QuizCollection
newCell.textLabel?.text = quiz.text
cell = newCell
}
} else if indexPath.section == kCorrectionSection {
// populate the cell with the quiz the Teacher should correct at the index path
if let newCell = tableView.dequeueReusableCell(withIdentifier: "QuizTitleTableViewCell") {
let quiz = needGrading[indexPath.row]
newCell.textLabel?.text = quiz.text
cell = newCell
}
} else if indexPath.section == kResultsSection {
// populate the cell with the student whose results can be viewed
if let newCell = tableView.dequeueReusableCell(withIdentifier: "StudentNameTableViewCell") {
let student = haveResults[indexPath.row]
newCell.textLabel?.text = student.login
cell = newCell
}
}
return cell
}
// for each of the possible sections calculate how many rows are required
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let me = me, let quizzes = me.quizzes else { return 0 }
var count = 0
if section == kQuizSection {
// return the count of quizzes for this teacher
count = quizzes.count
} else if section == kCorrectionSection {
count = needGrading.count
} else if section == kResultsSection {
count = haveResults.count
}
return count
}
// what could happen here is for the two section contants to become enums with value equal to the section number,
// with the value returned by this function equal to the number of values in the enum.
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
}
|
bsd-3-clause
|
2780edb31b2dfec19a3517c8e922edf1
| 30.178744 | 115 | 0.678339 | 4.656566 | false | false | false | false |
ambientlight/GithubIssuesExtension
|
GithubIssueEditorExtension/NewIssueCommand.swift
|
1
|
2364
|
//
// NewIssueCommand.swift
// GithubIssuesExtension
//
// Created by Taras Vozniuk on 21/11/2016.
// Copyright © 2016 Ambientlight. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import XcodeKit
import OctoKit
import RequestKit
/// Handles insertion of new issue template into source buffer
class NewIssueCommand: NSObject, XCSourceEditorCommand {
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void {
let (derivedOwnerº, derivedRepositoryº) = GithubIssuesExtension.deriveOwnerAndRepository(fromHeaderIn: invocation.buffer)
let sourceEditSession = SourceEditSession(sourceBuffer: invocation.buffer)
let selection = invocation.buffer.selections.firstObject as! XCSourceTextRange
let newIssueBody = [
"// \(GithubIssuesExtension.Literal.newIssueKey): <#Title#>",
"//",
"// - \(GithubIssuesExtension.Parameter.owner.rawValue): \(derivedOwnerº ?? "<#owner#>")",
"// - \(GithubIssuesExtension.Parameter.repository.rawValue): \(derivedRepositoryº ?? "<#repository#>")",
"// - \(GithubIssuesExtension.Parameter.assignee.rawValue): <#assignee#>",
"//",
"// <#Description#>"
]
let targetError: NSError? = (!sourceEditSession.insert(strings: newIssueBody, withPreservedIndentationAfter: selection.end.line - 1)) ? NSError(domain: GithubIssuesExtension.Literal.errorDomainIdentifier, code: GithubIssuesExtension.ErrorCode.insertionFailed.rawValue, userInfo: [NSLocalizedDescriptionKey: "Couldn't insert. Please submit an issues on https://github.com/ambientlight/GithubIssuesExtension/issues if it is not there already"]) : nil
completionHandler(targetError)
}
}
|
apache-2.0
|
adcadb3e5ba745b42b3b93d5f29395f4
| 46.18 | 456 | 0.713862 | 4.671287 | false | false | false | false |
getsentry/sentry-swift
|
Samples/iOS-Swift/iOS-Swift/Tools/UIAssert.swift
|
1
|
3335
|
import Foundation
import Sentry
import UIKit
class UIAssert {
static let shared = UIAssert()
private let view = AssertView()
private var isFailed = false
var targetView: AssertView?
private init() {
view.translatesAutoresizingMaskIntoConstraints = false
}
func assert(success: Bool, errorMessage: String?) {
if isFailed {
return
}
let assetView = targetView ?? view
assetView.message = success ? "ASSERT: SUCCESS" : "ASSERT: FAIL"
assetView.errorMessage = success ? "" : errorMessage
isFailed = !success
if targetView != nil {
return
}
guard let window = UIApplication.shared.delegate?.window else { return }
guard let target = window else { return }
if view.superview != target {
view.removeFromSuperview()
target.addSubview(view)
let constraints = [
view.leftAnchor.constraint(equalTo: target.leftAnchor, constant: 0),
view.rightAnchor.constraint(equalTo: target.rightAnchor, constant: 0),
view.bottomAnchor.constraint(equalTo: target.bottomAnchor, constant: 0)
]
NSLayoutConstraint.activate(constraints)
}
}
func reset() {
isFailed = false
}
static func isTrue(_ value: Bool, _ errorMessage: String? = nil) {
shared.assert(success: value, errorMessage: errorMessage)
}
static func isFalse(_ value: Bool, _ errorMessage: String? = nil) {
shared.assert(success: !value, errorMessage: errorMessage)
}
static func isEqual<T>(_ first: T, _ second: T, _ errorMessage: String? = nil) where T: Equatable {
shared.assert(success: first == second, errorMessage: errorMessage)
}
static func notNil(_ value: Any?, _ errorMessage: String? = nil) {
shared.assert(success: value != nil, errorMessage: errorMessage)
}
static func isNil(_ value: Any?, _ errorMessage: String? = nil) {
shared.assert(success: value == nil, errorMessage: errorMessage)
}
static func fail(_ errorMessage: String? = nil) {
shared.assert(success: false, errorMessage: errorMessage)
}
static func checkForViewControllerLifeCycle(_ transaction: Span, viewController: String, stepsToCheck: [String]? = nil, checkExcess: Bool = false) {
guard var children = transaction.children() else {
shared.assert(success: false, errorMessage: "\(viewController) span has no children")
return
}
let steps = stepsToCheck ?? ["loadView", "viewDidLoad", "viewWillAppear", "viewDidAppear", "viewAppearing"]
var missing = [String]()
steps.forEach { spanDescription in
let index = children.firstIndex { $0.context.spanDescription == spanDescription }
if let spanIndex = index {
children.remove(at: spanIndex)
} else {
missing.append(spanDescription)
}
}
UIAssert.isEqual(missing.count, 0, "Following spans not found: \(missing.joined(separator: ", "))")
}
}
|
mit
|
ed91853af820f101f9f0717a5cbdf5f9
| 32.35 | 152 | 0.586507 | 5.045386 | false | false | false | false |
Phelthas/LXMWaterfallLayout
|
LXMWaterfallLayout/DemoViewControllers/HeaderFooterViewController.swift
|
1
|
6706
|
//
// HeaderFooterViewController.swift
// LXMWaterfallLayout
//
// Created by luxiaoming on 2017/8/26.
// Copyright © 2017年 duowan. All rights reserved.
//
import UIKit
class HeaderFooterViewController: DemoBaseViewController {
var scrollDirection: UICollectionView.ScrollDirection = .vertical
}
// MARK: - Lifecycle
extension HeaderFooterViewController {
override func viewDidLoad() {
super.viewDidLoad()
// let layout = UICollectionViewFlowLayout()
let layout = LXMHeaderFooterFlowLayout()
layout.minimumInteritemSpacing = 20
layout.minimumLineSpacing = 5
layout.sectionInset = UIEdgeInsets(top: 10, left: 20, bottom: 30, right: 40)
layout.collectionViewHeaderHeight = 200
layout.collectionViewFooterHeight = 300
layout.scrollDirection = self.scrollDirection
self.collectionView.collectionViewLayout = layout
let sectionNib = UINib(nibName: "TestSectionView", bundle: nil)
collectionView.register(sectionNib, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader , withReuseIdentifier: TestSectionViewIdentifier)
collectionView.register(sectionNib, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: TestSectionViewIdentifier)
collectionView.register(sectionNib, forSupplementaryViewOfKind: LXMCollectionElementKindHeader , withReuseIdentifier: TestSectionViewIdentifier)
collectionView.register(sectionNib, forSupplementaryViewOfKind: LXMCollectionElementKindFooter, withReuseIdentifier: TestSectionViewIdentifier)
// collectionView.contentInset = UIEdgeInsets(top: 10, left: 20, bottom: 30, right: 40)
let item = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(changeAlignment))
self.navigationItem.rightBarButtonItem = item
}
@objc func changeAlignment() {
if let layout = self.collectionView.collectionViewLayout as? LXMHeaderFooterFlowLayout {
if self.scrollDirection == .vertical {
if layout.horiziontalAlignment == .left {
layout.horiziontalAlignment = .right
} else if layout.horiziontalAlignment == .right {
layout.horiziontalAlignment = .center
} else if layout.horiziontalAlignment == .center {
layout.horiziontalAlignment = .justified
} else if layout.horiziontalAlignment == .justified {
layout.horiziontalAlignment = .none
} else if layout.horiziontalAlignment == .none {
layout.horiziontalAlignment = .left
}
} else {
if layout.verticalAlignment == .top {
layout.verticalAlignment = .bottom
} else if layout.verticalAlignment == .bottom {
layout.verticalAlignment = .center
} else if layout.verticalAlignment == .center {
layout.verticalAlignment = .justified
} else if layout.verticalAlignment == .justified {
layout.verticalAlignment = .none
} else if layout.verticalAlignment == .none {
layout.verticalAlignment = .top
}
}
self.collectionView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension HeaderFooterViewController {
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionView.elementKindSectionHeader {
let sectionView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: TestSectionViewIdentifier, for: indexPath) as! TestSectionView
sectionView.backgroundColor = UIColor.red
sectionView.nameLabel.text = "sectionHeader \(indexPath.section)"
return sectionView
} else if kind == UICollectionView.elementKindSectionFooter {
let sectionView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: TestSectionViewIdentifier, for: indexPath) as! TestSectionView
sectionView.backgroundColor = UIColor.blue
sectionView.nameLabel.text = "sectionFooter \(indexPath.section)"
return sectionView
} else if kind == LXMCollectionElementKindHeader {
let sectionView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: TestSectionViewIdentifier, for: indexPath) as! TestSectionView
sectionView.backgroundColor = UIColor.yellow
sectionView.nameLabel.text = "collectionViewHeader"
return sectionView
} else if kind == LXMCollectionElementKindFooter {
let sectionView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: TestSectionViewIdentifier, for: indexPath) as! TestSectionView
sectionView.backgroundColor = UIColor.green
sectionView.nameLabel.text = "collectionViewFooter"
return sectionView
} else {
return UICollectionReusableView()
}
}
}
extension HeaderFooterViewController: UICollectionViewDelegateFlowLayout {
// func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// return sizeArray[indexPath.item]
// }
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section == 0 {
return CGSize(width: 100, height: 30)
} else if section == 1 {
return CGSize(width: 100, height: 100)
} else {
return CGSize.zero
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
if section == 0 {
return CGSize(width: 100, height: 30)
} else if section == 1 {
return CGSize(width: 100, height: 50)
} else {
return CGSize.zero
}
}
}
extension HeaderFooterViewController {
}
|
mit
|
7bc0962cacbc94297526cbf0256b6a15
| 44.598639 | 175 | 0.66791 | 5.979483 | false | true | false | false |
vlevschanov/CheckRecognition
|
CheckRecognition/CheckRecognition/UI/ViewControllers/Scanning/PreviewViewController.swift
|
1
|
1644
|
//
// PreviewViewController.swift
// CheckRecognition
//
// Created by Viktor Levshchanov on 30.11.14.
// Copyright (c) 2014 Viktor Levshchanov. All rights reserved.
//
import UIKit
private extension BaseViewController.SegueID {
static let RESULT_SEGUE = "resultSegue"
}
class PreviewViewController: BaseViewController {
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
@IBOutlet weak var photoImageFormattingView: ImageFormattingView!
var photoImage : UIImage?
var recognizedText : String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
override func viewDidAppear(animated: Bool) {
var loaded = self.isLoaded
super.viewDidAppear(animated)
if !loaded {
self.photoImageFormattingView.image = self.photoImage
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch segue.identifier! {
case SegueID.RESULT_SEGUE:
let vc = segue.destinationViewController as! ResultViewController
//vc.text = recognizedText
vc.image = self.photoImageFormattingView.getFormattedImage()
default:
break
}
}
@IBAction func scanButtonDidTap(sender: UIBarButtonItem) {
performSegueWithIdentifier(SegueID.RESULT_SEGUE, sender: self)
}
}
|
apache-2.0
|
836fb2cf2ca6be05f77ff25b64ea2410
| 27.842105 | 81 | 0.670316 | 5.169811 | false | false | false | false |
SergeVKom/RPAgentSwiftXCTest
|
RPAgentSwiftXCTest/RPServices.swift
|
1
|
6546
|
//
// RPServices.swift
// com.oxagile.automation.RPAgentSwiftXCTest
//
// Created by Sergey Komarov on 6/26/17.
// Copyright © 2017 Oxagile. All rights reserved.
//
import Foundation
import XCTest
class RPService: NSObject {
var httpClient = HTTPClient()
var endPoints: RPEndPoints!
var launchID = ""
var launchStatus = TestStatus.passed.rawValue
var testCaseID = ""
var testID = ""
var currentTime: String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter.string(from: Date())
}
let semaphore = DispatchSemaphore(value: 0)
let timeOutForRequestExpectation = 10.0
var currentDevice = UIDevice.current
func startLaunch(_ bundleProperties: [String: Any]) {
endPoints = RPEndPoints (
url: bundleProperties["ReportPortalURL"] as! String,
token: bundleProperties["ReportPortalToken"] as! String
)
var requestData = endPoints.startLaunch
requestData.parameters["name"] = bundleProperties["ReportPortalLaunchName"]
requestData.parameters["start_time"] = currentTime
var customTags: [String] {
var tags = [String]()
if (bundleProperties["ReportPortalTags"] != nil) {
tags = (bundleProperties["ReportPortalTags"] as! String).replacingOccurrences(of: ", ", with: ",").components(separatedBy: ",")
}
return tags
}
requestData.parameters["tags"] = [currentDevice.systemName, currentDevice.systemVersion, currentDevice.modelName, currentDevice.model] + customTags
httpClient.doRequest(data: requestData) { (result: ItemData) in
self.launchID = result.id
self.semaphore.signal()
}
_ = semaphore.wait(timeout: .now() + timeOutForRequestExpectation)
}
func startTestCase(_ testCase: XCTestSuite) {
var requestData = endPoints.startTestCase
var testCaseName: String {
var sentence = ""
for eachCharacter in Array(testCase.name) {
if (eachCharacter >= "A" && eachCharacter <= "Z") == true {
sentence.append(" ")
}
sentence.append(eachCharacter)
}
return sentence.trimmingCharacters(in: .whitespaces)
}
requestData.parameters["launch_id"] = launchID
requestData.parameters["name"] = testCaseName
requestData.parameters["start_time"] = currentTime
httpClient.doRequest(data: requestData) { (result: ItemData) in
self.testCaseID = result.id
self.semaphore.signal()
}
_ = semaphore.wait(timeout: .now() + timeOutForRequestExpectation)
}
func startTest(_ test: XCTestCase) {
var requestData = endPoints.startTest
var testName: String {
let camelStyleName = Array(String(test.name.components(separatedBy: " ")[1]).dropLast())
var sentence = ""
for eachCharacter in camelStyleName {
if (eachCharacter >= "A" && eachCharacter <= "Z") == true {
sentence.append(" ")
}
sentence.append(eachCharacter)
}
var worlds = sentence.trimmingCharacters(in: .whitespaces).lowercased().components(separatedBy: " ")
if worlds.count > 1 {
worlds.remove(at: 0)
}
worlds[0] = worlds[0].capitalized
return worlds.joined(separator: " ")
}
requestData.url = requestData.url.replacingOccurrences(of: "{parentId}", with: testCaseID)
requestData.parameters["launch_id"] = launchID
requestData.parameters["name"] = testName
requestData.parameters["start_time"] = currentTime
httpClient.doRequest(data: requestData) { (result: ItemData) in
self.testID = result.id
self.semaphore.signal()
}
_ = semaphore.wait(timeout: .now() + timeOutForRequestExpectation)
}
func reportError(message: String) {
var requestData = endPoints.postLog
requestData.parameters["item_id"] = self.testID
requestData.parameters["level"] = "error"
requestData.parameters["message"] = message
requestData.parameters["time"] = currentTime
httpClient.doRequest(data: requestData) { (result: ItemData) in
self.semaphore.signal()
}
_ = semaphore.wait(timeout: .now() + timeOutForRequestExpectation)
}
func finishTest(_ test: XCTestCase) {
var requestData = endPoints.finishItem
requestData.url = requestData.url.replacingOccurrences(of: "{itemId}", with: testID)
var issueType = ""
let status = test.testRun!.hasSucceeded ? TestStatus.passed.rawValue : TestStatus.failed.rawValue
if status == TestStatus.failed.rawValue {
issueType = "TO_INVESTIGATE"
launchStatus = TestStatus.failed.rawValue
}
requestData.parameters = [
"end_time": currentTime,
"issue": [
"comment": "",
"issue_type": issueType
],
"status": status
]
httpClient.doRequest(data: requestData) { (result: FinishData) in
self.semaphore.signal()
}
_ = semaphore.wait(timeout: .now() + timeOutForRequestExpectation)
}
func finishTestCase() {
var requestData = endPoints.finishItem
requestData.url = requestData.url.replacingOccurrences(of: "{itemId}", with: testCaseID)
requestData.parameters["end_time"] = currentTime
requestData.parameters["status"] = launchStatus
httpClient.doRequest(data: requestData) { (result: FinishData) in
self.semaphore.signal()
}
_ = semaphore.wait(timeout: .now() + timeOutForRequestExpectation)
}
func finishLaunch() {
var requestData = endPoints.finishLaunch
requestData.url = requestData.url.replacingOccurrences(of: "{launchId}", with: launchID)
requestData.parameters = [
"end_time": currentTime,
"status": launchStatus
]
httpClient.doRequest(data: requestData) { (result: FinishData) in
self.semaphore.signal()
}
_ = semaphore.wait(timeout: .now() + timeOutForRequestExpectation)
}
}
|
mit
|
0cca74886de85673d8fe0d3fdb8cc105
| 38.666667 | 155 | 0.605959 | 4.729046 | false | true | false | false |
vector-im/vector-ios
|
Riot/Modules/TabBar/MainTitleView.swift
|
1
|
1858
|
//
// Copyright 2021 New Vector Ltd
//
// 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
@objcMembers
class MainTitleView: UIStackView, Themable {
// MARK: - Properties
public private(set) var titleLabel: UILabel!
public private(set) var subtitleLabel: UILabel!
// MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
// MARK: - Themable
func update(theme: Theme) {
self.titleLabel.textColor = theme.colors.primaryContent
self.titleLabel.font = theme.fonts.calloutSB
self.subtitleLabel.textColor = theme.colors.tertiaryContent
self.subtitleLabel.font = theme.fonts.footnote
}
// MARK: - Private
private func setupView() {
self.titleLabel = UILabel(frame: .zero)
self.titleLabel.backgroundColor = .clear
self.subtitleLabel = UILabel(frame: .zero)
self.subtitleLabel.backgroundColor = .clear
self.addArrangedSubview(titleLabel)
self.addArrangedSubview(subtitleLabel)
self.distribution = .equalCentering
self.axis = .vertical
self.alignment = .center
self.spacing = 0.5
}
}
|
apache-2.0
|
91869e6a0ee49b8628cd8ac11d9be66d
| 27.584615 | 75 | 0.660926 | 4.553922 | false | false | false | false |
kasei/SwiftRegex
|
SwiftRegex/SwiftRegex.swift
|
1
|
1609
|
//
// SwiftRegex.swift
// SwiftRegex
//
// Created by Gregory Todd Williams on 6/7/14.
// Copyright (c) 2014 Gregory Todd Williams. All rights reserved.
//
import Foundation
infix operator =~
func =~ (value : String, pattern : String) -> RegexMatchResult {
let nsstr = value as NSString // we use this to access the NSString methods like .length and .substringWithRange(NSRange)
let options : NSRegularExpression.Options = []
do {
let re = try NSRegularExpression(pattern: pattern, options: options)
let all = NSRange(location: 0, length: nsstr.length)
var matches : Array<String> = []
re.enumerateMatches(in: value, options: [], range: all) { (result, flags, ptr) -> Void in
guard let result = result else { return }
let string = nsstr.substring(with: result.range)
matches.append(string)
}
return RegexMatchResult(items: matches)
} catch {
return RegexMatchResult(items: [])
}
}
struct RegexMatchCaptureGenerator : IteratorProtocol {
var items: ArraySlice<String>
mutating func next() -> String? {
if items.isEmpty { return nil }
let ret = items[items.startIndex]
items = items[1..<items.count]
return ret
}
}
struct RegexMatchResult : Sequence {
var items: Array<String>
func makeIterator() -> RegexMatchCaptureGenerator {
return RegexMatchCaptureGenerator(items: items[0..<items.count])
}
var boolValue: Bool {
return items.count > 0
}
subscript (i: Int) -> String {
return items[i]
}
}
|
bsd-3-clause
|
431ef6cb31535da3ae81c5e067315415
| 29.942308 | 125 | 0.637042 | 4.201044 | false | false | false | false |
Cloudage/XWebView
|
XWebView/XWVUserScript.swift
|
2
|
2155
|
/*
Copyright 2015 XWebView
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 WebKit
class XWVUserScript {
weak var webView: WKWebView?
let script: WKUserScript
let cleanup: String?
init(webView: WKWebView, script: WKUserScript, cleanup: String? = nil) {
self.webView = webView
self.script = script
self.cleanup = cleanup
inject()
}
convenience init(webView: WKWebView, script: WKUserScript, namespace: String) {
self.init(webView: webView, script: script, cleanup: "delete \(namespace)")
}
deinit {
eject()
}
private func inject() {
guard let webView = webView else { return }
// add to userContentController
webView.configuration.userContentController.addUserScript(script)
// inject into current context
if webView.URL != nil {
webView.evaluateJavaScript(script.source) {
if let error = $1 {
log("!Failed to inject script. \(error)")
}
}
}
}
private func eject() {
guard let webView = webView else { return }
// remove from userContentController
let controller = webView.configuration.userContentController
let userScripts = controller.userScripts
controller.removeAllUserScripts()
userScripts.forEach {
if $0 != self.script { controller.addUserScript($0) }
}
if webView.URL != nil, let cleanup = cleanup {
// clean up in current context
webView.evaluateJavaScript(cleanup, completionHandler: nil)
}
}
}
|
apache-2.0
|
d199617233eab248753ac3d77d52e1e1
| 30.231884 | 83 | 0.647796 | 4.976905 | false | false | false | false |
nameghino/swift-algorithm-club
|
Count Occurrences/CountOccurrences.playground/Contents.swift
|
2
|
1346
|
//: Playground - noun: a place where people can play
func countOccurrencesOfKey(key: Int, inArray a: [Int]) -> Int {
func leftBoundary() -> Int {
var low = 0
var high = a.count
while low < high {
let midIndex = low + (high - low)/2
if a[midIndex] < key {
low = midIndex + 1
} else {
high = midIndex
}
}
return low
}
func rightBoundary() -> Int {
var low = 0
var high = a.count
while low < high {
let midIndex = low + (high - low)/2
if a[midIndex] > key {
high = midIndex
} else {
low = midIndex + 1
}
}
return low
}
return rightBoundary() - leftBoundary()
}
// Simple test
let a = [ 0, 1, 1, 3, 3, 3, 3, 6, 8, 10, 11, 11 ]
countOccurrencesOfKey(3, inArray: a)
// Test with arrays of random size and contents (see debug output)
import Foundation
func createArray() -> [Int] {
var a = [Int]()
for i in 0...5 {
if i != 2 { // don't include the number 2
let count = Int(arc4random_uniform(UInt32(6))) + 1
for _ in 0..<count {
a.append(i)
}
}
}
return a.sort(<)
}
for _ in 0..<10 {
let a = createArray()
print(a)
// Note: we also test -1 and 6 to check the edge cases.
for k in -1...6 {
print("\t\(k): \(countOccurrencesOfKey(k, inArray: a))")
}
}
|
mit
|
dd927c8ac8245c64144af5085c9c852d
| 19.089552 | 66 | 0.538633 | 3.307125 | false | false | false | false |
Acidburn0zzz/firefox-ios
|
Client/Frontend/Widgets/PhotonActionSheet/PhotonActionSheetProtocol.swift
|
1
|
5583
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
protocol PhotonActionSheetProtocol {
var tabManager: TabManager { get }
var profile: Profile { get }
}
private let log = Logger.browserLogger
extension PhotonActionSheetProtocol {
typealias PresentableVC = UIViewController & UIPopoverPresentationControllerDelegate
typealias MenuAction = () -> Void
typealias IsPrivateTab = Bool
typealias URLOpenAction = (URL?, IsPrivateTab) -> Void
func presentSheetWith(title: String? = nil, actions: [[PhotonActionSheetItem]], on viewController: PresentableVC, from view: UIView, closeButtonTitle: String = Strings.CloseButtonTitle, suppressPopover: Bool = false) {
let style: UIModalPresentationStyle = (UIDevice.current.userInterfaceIdiom == .pad && !suppressPopover) ? .popover : .overCurrentContext
let sheet = PhotonActionSheet(title: title, actions: actions, closeButtonTitle: closeButtonTitle, style: style)
sheet.modalPresentationStyle = style
sheet.photonTransitionDelegate = PhotonActionSheetAnimator()
if profile.hasSyncableAccount() {
// the sync manager is only needed when we have a logged in user with sync in a good state
sheet.syncManager = profile.syncManager // the syncmanager is used to display the sync button in the browser menu
}
if let popoverVC = sheet.popoverPresentationController, sheet.modalPresentationStyle == .popover {
popoverVC.delegate = viewController
popoverVC.sourceView = view
popoverVC.sourceRect = CGRect(x: view.frame.width/2, y: view.frame.size.height * 0.75, width: 1, height: 1)
popoverVC.permittedArrowDirections = .up
}
viewController.present(sheet, animated: true, completion: nil)
}
typealias PageOptionsVC = QRCodeViewControllerDelegate & SettingsDelegate & PresentingModalViewControllerDelegate & UIViewController
func fetchBookmarkStatus(for url: String) -> Deferred<Maybe<Bool>> {
return profile.places.isBookmarked(url: url)
}
func fetchPinnedTopSiteStatus(for url: String) -> Deferred<Maybe<Bool>> {
return self.profile.history.isPinnedTopSite(url)
}
func getLongPressLocationBarActions(with urlBar: URLBarView, webViewContainer: UIView) -> [PhotonActionSheetItem] {
let pasteGoAction = PhotonActionSheetItem(title: Strings.PasteAndGoTitle, iconString: "menu-PasteAndGo") { _, _ in
if let pasteboardContents = UIPasteboard.general.string {
urlBar.delegate?.urlBar(urlBar, didSubmitText: pasteboardContents)
}
}
let pasteAction = PhotonActionSheetItem(title: Strings.PasteTitle, iconString: "menu-Paste") { _, _ in
if let pasteboardContents = UIPasteboard.general.string {
urlBar.enterOverlayMode(pasteboardContents, pasted: true, search: true)
}
}
let copyAddressAction = PhotonActionSheetItem(title: Strings.CopyAddressTitle, iconString: "menu-Copy-Link") { _, _ in
if let url = self.tabManager.selectedTab?.canonicalURL?.displayURL ?? urlBar.currentURL {
UIPasteboard.general.url = url
SimpleToast().showAlertWithText(Strings.AppMenuCopyURLConfirmMessage, bottomContainer: webViewContainer)
}
}
if UIPasteboard.general.string != nil {
return [pasteGoAction, pasteAction, copyAddressAction]
} else {
return [copyAddressAction]
}
}
func getRefreshLongPressMenu(for tab: Tab) -> [PhotonActionSheetItem] {
guard tab.webView?.url != nil && (tab.getContentScript(name: ReaderMode.name()) as? ReaderMode)?.state != .active else {
return []
}
let defaultUAisDesktop = UserAgent.isDesktop(ua: UserAgent.getUserAgent())
let toggleActionTitle: String
if defaultUAisDesktop {
toggleActionTitle = tab.changedUserAgent ? Strings.AppMenuViewDesktopSiteTitleString : Strings.AppMenuViewMobileSiteTitleString
} else {
toggleActionTitle = tab.changedUserAgent ? Strings.AppMenuViewMobileSiteTitleString : Strings.AppMenuViewDesktopSiteTitleString
}
let toggleDesktopSite = PhotonActionSheetItem(title: toggleActionTitle, iconString: "menu-RequestDesktopSite") { _, _ in
if let url = tab.url {
tab.toggleChangeUserAgent()
Tab.ChangeUserAgent.updateDomainList(forUrl: url, isChangedUA: tab.changedUserAgent, isPrivate: tab.isPrivate)
}
}
if let url = tab.webView?.url, let helper = tab.contentBlocker, helper.isEnabled, helper.blockingStrengthPref == .strict {
let isSafelisted = helper.status == .safelisted
let title = !isSafelisted ? Strings.TrackingProtectionReloadWithout : Strings.TrackingProtectionReloadWith
let imageName = helper.isEnabled ? "menu-TrackingProtection-Off" : "menu-TrackingProtection"
let toggleTP = PhotonActionSheetItem(title: title, iconString: imageName) { _, _ in
ContentBlocker.shared.safelist(enable: !isSafelisted, url: url) {
tab.reload()
}
}
return [toggleDesktopSite, toggleTP]
} else {
return [toggleDesktopSite]
}
}
}
|
mpl-2.0
|
b2fef98f7c6765bfbaaf56d6cf912aa7
| 48.848214 | 222 | 0.683145 | 5.262017 | false | false | false | false |
nathawes/swift
|
test/SILOptimizer/opt-remark-generator.swift
|
2
|
12314
|
// RUN: %target-swiftc_driver -O -Rpass-missed=sil-opt-remark-gen -Xllvm -sil-disable-pass=FunctionSignatureOpts -emit-sil %s -o /dev/null -Xfrontend -verify
// REQUIRES: optimized_stdlib
// XFAIL: OS=linux-androideabi && CPU=armv7
public class Klass {}
// TODO: Change global related code to be implicit/autogenerated (as
// appropriate) so we don't emit this remark.
public var global = Klass() // expected-remark {{heap allocated ref of type 'Klass'}}
@inline(never)
public func getGlobal() -> Klass {
return global // expected-remark @:5 {{retain of type 'Klass'}}
// expected-note @-5:12 {{of 'global'}}
}
// Make sure that the retain msg is at the beginning of the print and the
// releases are the end of the print.
//
// The heap allocated ref is for the temporary array and the release that is
// unannotated is for that array as well. We make sure that the heap allocated
// ref is on the argument that necessitated its creation.
public func useGlobal() {
let x = getGlobal()
print(x) // expected-remark @:11 {{heap allocated ref of type}}
// expected-remark @-1:5 {{retain of type 'Klass'}}
// expected-note @-3:9 {{of 'x'}}
// expected-remark @-3:12 {{release of type}}
// expected-remark @-4:12 {{release of type 'Klass'}}
// expected-note @-6:9 {{of 'x'}}
}
public enum TrivialState {
case first
case second
case third
}
struct StructWithOwner {
var owner = Klass()
var state = TrivialState.first
}
func printStructWithOwner(x : StructWithOwner) {
print(x) // expected-remark @:11 {{heap allocated ref of type}}
// expected-remark @-1 {{retain of type 'Klass'}}
// expected-note @-3:27 {{of 'x.owner'}}
// expected-remark @-3:12 {{release of type}}
}
func printStructWithOwnerOwner(x : StructWithOwner) {
print(x.owner) // expected-remark @:11 {{heap allocated ref of type}}
// expected-remark @-1 {{retain of type 'Klass'}}
// expected-note @-3:32 {{of 'x.owner'}}
// expected-remark @-3:18 {{release of type}}
}
func returnStructWithOwnerOwner(x: StructWithOwner) -> Klass {
return x.owner // expected-remark {{retain of type 'Klass'}}
// expected-note @-2:33 {{of 'x.owner'}}
}
func callingAnInitializerStructWithOwner(x: Klass) -> StructWithOwner {
return StructWithOwner(owner: x) // expected-remark {{retain of type 'Klass'}}
// expected-note @-2:42 {{of 'x'}}
}
struct KlassPair {
var lhs: Klass
var rhs: Klass
}
func printKlassPair(x : KlassPair) {
// We pattern match columns to ensure we get retain on the p and release on
// the end ')'
print(x) // expected-remark @:11 {{heap allocated ref of type}}
// expected-remark @-1:5 {{retain of type 'Klass'}}
// expected-note @-5:21 {{of 'x.lhs'}}
// expected-remark @-3:5 {{retain of type 'Klass'}}
// expected-note @-7:21 {{of 'x.rhs'}}
// expected-remark @-5:12 {{release of type}}
}
func printKlassPairLHS(x : KlassPair) {
// We print the remarks at the 'p' and at the ending ')'.
print(x.lhs) // expected-remark @:11 {{heap allocated ref of type}}
// expected-remark @-1:5 {{retain of type 'Klass'}}
// expected-note @-4:24 {{of 'x.lhs'}}
// expected-remark @-3:16 {{release of type}}
}
// We put the retain on the return here since it is part of the result
// convention.
func returnKlassPairLHS(x: KlassPair) -> Klass {
return x.lhs // expected-remark @:5 {{retain of type 'Klass'}}
// expected-note @-2:25 {{of 'x.lhs'}}
}
func callingAnInitializerKlassPair(x: Klass, y: Klass) -> KlassPair {
return KlassPair(lhs: x, rhs: y) // expected-remark {{retain of type 'Klass'}}
// expected-note @-2:36 {{of 'x'}}
// expected-remark @-2:5 {{retain of type 'Klass'}}
// expected-note @-4:46 {{of 'y'}}
}
func printKlassTuplePair(x : (Klass, Klass)) {
// We pattern match columns to ensure we get retain on the p and release on
// the end ')'
print(x) // expected-remark @:11 {{heap allocated ref of type}}
// expected-remark @-1:5 {{retain of type 'Klass'}}
// expected-note @-5:26 {{of 'x'}}
// expected-remark @-3:5 {{retain of type 'Klass'}}
// expected-note @-7:26 {{of 'x'}}
// expected-remark @-5:12 {{release of type}}
}
func printKlassTupleLHS(x : (Klass, Klass)) {
// We print the remarks at the 'p' and at the ending ')'.
print(x.0) // expected-remark @:11 {{heap allocated ref of type}}
// expected-remark @-1:5 {{retain of type 'Klass'}}
// expected-note @-4:25 {{of 'x'}}
// Release on Array<Any> for print.
// expected-remark @-4:14 {{release of type}}
}
func returnKlassTupleLHS(x: (Klass, Klass)) -> Klass {
return x.0 // expected-remark @:5 {{retain of type 'Klass'}}
// expected-note @-2:26 {{of 'x'}}
}
func callingAnInitializerKlassTuplePair(x: Klass, y: Klass) -> (Klass, Klass) {
return (x, y) // expected-remark {{retain of type 'Klass'}}
// expected-note @-2:41 {{of 'x'}}
// expected-remark @-2:5 {{retain of type 'Klass'}}
// expected-note @-4:51 {{of 'y'}}
}
public class SubKlass : Klass {
@inline(never)
final func doSomething() {}
}
func lookThroughCast(x: SubKlass) -> Klass {
return x as Klass // expected-remark {{retain of type 'SubKlass'}}
// expected-note @-2:22 {{of 'x'}}
}
func lookThroughRefCast(x: Klass) -> SubKlass {
return x as! SubKlass // expected-remark {{retain of type 'Klass'}}
// expected-note @-2:25 {{of 'x'}}
}
func lookThroughEnum(x: Klass?) -> Klass {
return x! // expected-remark {{retain of type 'Klass'}}
// expected-note @-2:22 {{of 'x.some'}}
}
func castAsQuestion(x: Klass) -> SubKlass? {
x as? SubKlass // expected-remark {{retain of type 'Klass'}}
// expected-note @-2:21 {{of 'x'}}
}
func castAsQuestionDiamond(x: Klass) -> SubKlass? {
guard let y = x as? SubKlass else {
return nil
}
y.doSomething()
return y // expected-remark {{retain of type 'Klass'}}
// expected-note @-7:28 {{of 'x'}}
}
func castAsQuestionDiamondGEP(x: KlassPair) -> SubKlass? {
guard let y = x.lhs as? SubKlass else {
return nil
}
y.doSomething()
// We eliminate the rhs retain/release.
return y // expected-remark {{retain of type 'Klass'}}
// expected-note @-8:31 {{of 'x.lhs'}}
}
// We don't handle this test case as well.
func castAsQuestionDiamondGEP2(x: KlassPair) {
switch (x.lhs as? SubKlass, x.rhs as? SubKlass) { // expected-remark @:19 {{retain of type 'Klass'}}
// expected-note @-2 {{of 'x.lhs'}}
// expected-remark @-2:39 {{retain of type 'Klass'}}
// expected-note @-4 {{of 'x.rhs'}}
case let (.some(x1), .some(x2)):
print(x1, x2) // expected-remark @:15 {{heap allocated ref of type}}
// expected-remark @-1 {{retain of type 'Optional<SubKlass>'}}
// expected-remark @-2 {{retain of type 'Optional<SubKlass>'}}
// expected-remark @-3 {{release of type}}
// expected-remark @-4 {{release of type 'Optional<SubKlass>'}}
// expected-remark @-5 {{release of type 'Optional<SubKlass>'}}
case let (.some(x1), nil):
print(x1) // expected-remark @:15 {{heap allocated ref of type}}
// expected-remark @-1 {{retain of type 'SubKlass'}}
// expected-remark @-2 {{release of type}}
// expected-remark @-3 {{release of type 'Optional<SubKlass>'}}
case let (nil, .some(x2)):
print(x2) // expected-remark @:15 {{heap allocated ref of type}}
// expected-remark @-1 {{retain of type 'SubKlass'}}
// expected-remark @-2 {{release of type}}
// expected-remark @-3 {{release of type 'Optional<SubKlass>'}}
case (nil, nil):
break
}
}
func inoutKlassPairArgument(x: inout KlassPair) -> Klass {
return x.lhs // expected-remark {{retain of type 'Klass'}}
// expected-note @-2 {{of 'x.lhs'}}
}
func inoutKlassTuplePairArgument(x: inout (Klass, Klass)) -> Klass {
return x.0 // expected-remark {{retain of type 'Klass'}}
// expected-note @-2 {{of 'x.0'}}
}
func inoutKlassOptionalArgument(x: inout Klass?) -> Klass {
return x! // expected-remark {{retain of type 'Klass'}}
// expected-note @-2 {{of 'x.some'}}
}
func inoutKlassBangCastArgument(x: inout Klass) -> SubKlass {
return x as! SubKlass // expected-remark {{retain of type 'Klass'}}
// expected-note @-2 {{of 'x'}}
}
func inoutKlassQuestionCastArgument(x: inout Klass) -> SubKlass? {
return x as? SubKlass // expected-remark {{retain of type 'Klass'}}
// expected-note @-2 {{of 'x'}}
}
func inoutKlassBangCastArgument2(x: inout Klass?) -> SubKlass {
return x as! SubKlass // expected-remark {{retain of type 'Klass'}}
// expected-note @-2 {{of 'x.some'}}
}
func inoutKlassQuestionCastArgument2(x: inout Klass?) -> SubKlass? {
return x as? SubKlass // expected-remark {{retain of type 'Klass'}}
// expected-note @-2 {{of 'x.some'}}
}
// We should have 1x rr remark here on calleeX for storing it into the array to
// print. Release is from the array. We don't pattern match it due to the actual
// underlying Array type name changing under the hood in between platforms.
@inline(__always)
func alwaysInlineCallee(_ calleeX: Klass) {
print(calleeX) // expected-remark @:11 {{heap allocated ref of type}}
// expected-remark @-1:5 {{retain of type 'Klass'}}
// expected-note @-3:27 {{of 'calleeX'}}
// expected-remark @-3:18 {{release of type}}
}
// We should have 3x rr remarks here on callerX and none on calleeX. All of the
// releases are for the temporary array that we pass into print.
//
// TODO: Should we print out as notes the whole inlined call stack?
func alwaysInlineCaller(_ callerX: Klass) {
alwaysInlineCallee(callerX) // expected-remark @:5 {{heap allocated ref of type}}
// expected-remark @-1:5 {{retain of type 'Klass'}}
// expected-note @-3:27 {{of 'callerX'}}
// expected-remark @-3:31 {{release of type}}
print(callerX) // expected-remark @:11 {{heap allocated ref of type}}
// expected-remark @-1:5 {{retain of type 'Klass'}}
// expected-note @-7:27 {{of 'callerX'}}
// expected-remark @-3:18 {{release of type}}
alwaysInlineCallee(callerX) // expected-remark @:5 {{heap allocated ref of type}}
// expected-remark @-1:5 {{retain of type 'Klass'}}
// expected-note @-11:27 {{of 'callerX'}}
// expected-remark @-3:31 {{release of type}}
}
func allocateValue() {
// Remark should be on Klass and note should be on k.
let k = Klass() // expected-remark @:13 {{heap allocated ref of type 'Klass'}}
// expected-note @-1:9 {{of 'k'}}
print(k) // expected-remark @:11 {{heap allocated ref of type}}
// expected-remark @-1:5 {{retain of type 'Klass'}}
// expected-note @-4:9 {{of 'k'}}
// expected-remark @-3:12 {{release of type}}
// expected-remark @-4:12 {{release of type 'Klass'}}
// expected-note @-7:9 {{of 'k'}}
}
|
apache-2.0
|
e6ae09329e8b0b0b42ccfc67e035fad8
| 41.756944 | 157 | 0.559445 | 3.94048 | false | false | false | false |
frankrausch/Typographizer
|
Sources/Typographizer.swift
|
1
|
13244
|
//
// Typographizer.swift
// Typographizer
//
// Created by Frank Rausch on 2017-01-02.
// Copyright © 2017 Frank Rausch.
//
import Foundation
struct Typographizer {
var language: String {
didSet {
self.refreshLanguage()
}
}
var text = "" {
didSet {
self.refreshTextIterator()
}
}
private var textIterator: String.UnicodeScalarView.Iterator?
private var bufferedScalar: UnicodeScalar?
private var previousScalar: UnicodeScalar?
var isDebugModeEnabled = false
var isMeasurePerformanceEnabled = false
var isHTML = false
private var openingDoubleQuote: String = "·"
private var closingDoubleQuote: String = "·"
private var openingSingleQuote: String = "·"
private var closingSingleQuote: String = "·"
private let apostrophe: String = "’"
private let enDash: String = "–"
private let tagsToSkip: Set<String> = ["pre", "code", "var", "samp", "kbd", "math", "script", "style"]
private let openingBracketsSet: Set<UnicodeScalar> = ["(", "["]
init(language: String, text: String, isHTML: Bool = false, debug: Bool = false, measurePerformance: Bool = false) {
self.text = text
self.isHTML = isHTML
self.language = language
self.isDebugModeEnabled = debug
self.isMeasurePerformanceEnabled = measurePerformance
self.refreshLanguage()
self.refreshTextIterator()
}
private mutating func refreshLanguage() {
switch self.language {
case "he":
// TODO: Insert proper replacements.
// Fixing dumb quotation marks in Hebrew is tricky,
// because a dumb double quotation mark may also be used for gershayim.
// See https://en.wikipedia.org/wiki/Gershayim
self.openingDoubleQuote = "\""
self.closingDoubleQuote = "\""
self.openingSingleQuote = "\'"
self.closingSingleQuote = "\'"
case "cs",
"da",
"de",
"et",
"is",
"lt",
"lv",
"sk",
"sl":
self.openingDoubleQuote = "„"
self.closingDoubleQuote = "“"
self.openingSingleQuote = "\u{201A}"
self.closingSingleQuote = "‘"
case "de_CH",
"de_LI":
self.openingDoubleQuote = "«"
self.closingDoubleQuote = "»"
self.openingSingleQuote = "‹"
self.closingSingleQuote = "›"
case "bs",
"fi",
"sv":
self.openingDoubleQuote = "”"
self.closingDoubleQuote = "”"
self.openingSingleQuote = "’"
self.closingSingleQuote = "’"
case "fr":
self.openingDoubleQuote = "«\u{00A0}"
self.closingDoubleQuote = "\u{00A0}»"
self.openingSingleQuote = "‹\u{00A0}"
self.closingSingleQuote = "\u{00A0}›"
case "hu",
"pl",
"ro":
self.openingDoubleQuote = "„"
self.closingDoubleQuote = "”"
self.openingSingleQuote = "’"
self.closingSingleQuote = "’"
case "ja":
self.openingDoubleQuote = "「"
self.closingDoubleQuote = "」"
self.openingSingleQuote = "『"
self.closingSingleQuote = "』"
case "ru",
"no",
"nn":
self.openingDoubleQuote = "«"
self.closingDoubleQuote = "»"
self.openingSingleQuote = "’"
self.closingSingleQuote = "’"
case "en",
"nl": // contemporary Dutch style
fallthrough
default:
self.openingDoubleQuote = "“"
self.closingDoubleQuote = "”"
self.openingSingleQuote = "‘"
self.closingSingleQuote = "’"
}
}
mutating func refreshTextIterator() {
self.textIterator = self.text.unicodeScalars.makeIterator()
}
mutating func typographize() -> String {
#if DEBUG
var startTime: Date?
if self.isMeasurePerformanceEnabled {
startTime = Date()
}
#endif
var tokens = [Token]()
do {
while let token = try self.nextToken() {
tokens.append(token)
}
} catch {
if self.isDebugModeEnabled {
#if DEBUG
print("Typographizer iterator triggered an error.")
abort()
#endif
} else {
return self.text // return unchanged text
}
}
let s = tokens.compactMap({$0.text}).joined()
#if DEBUG
if let startTime = startTime {
let endTime = Date().timeIntervalSince(startTime)
print("Typographizing took \(NSString(format:"%.8f", endTime)) seconds")
}
#endif
return s
}
private mutating func nextToken() throws -> Token? {
while let ch = self.nextScalar() {
switch ch {
case "´",
"`":
// FIXME: Replacing a combining accent only works for the very first scalar in a string
return Token(.apostrophe, self.apostrophe)
case "\"",
"'",
"-":
return try self.fixableToken(ch)
case "<" where self.isHTML:
return try self.htmlToken()
default:
return try self.unchangedToken(ch)
}
}
return nil
}
private mutating func nextScalar() -> UnicodeScalar? {
if let next = self.bufferedScalar {
self.bufferedScalar = nil
return next
}
return self.textIterator?.next()
}
// MARK: Tag Token
private mutating func htmlToken() throws -> Token {
var tokenText = "<"
var tagName = ""
var tagNameHasAlreadyBeenDetermined = false
var attributeIsOpen = false
loop: while let ch = nextScalar() {
switch ch {
case " " where self.tagsToSkip.contains(tagName),
">" where self.tagsToSkip.contains(tagName):
tokenText.unicodeScalars.append(ch)
tokenText.append(self.fastForwardToClosingTag(tagName))
break loop
case ">" where !attributeIsOpen:
tokenText.unicodeScalars.append(ch)
break loop
case "\"":
attributeIsOpen.toggle()
tokenText.unicodeScalars.append(ch)
case " ":
tagNameHasAlreadyBeenDetermined = true
tokenText.unicodeScalars.append(ch)
default:
if !tagNameHasAlreadyBeenDetermined {
tagName.unicodeScalars.append(ch)
}
tokenText.unicodeScalars.append(ch)
}
}
return Token(.skipped, tokenText)
}
private mutating func fastForwardToClosingTag(_ tag: String) -> String {
var buffer = ""
loop: while let ch = nextScalar() {
buffer.unicodeScalars.append(ch)
if ch == "<" {
if let ch = nextScalar() {
buffer.unicodeScalars.append(ch)
if ch == "/" {
let (bufferedString, isMatchingTag) = self.checkForMatchingTag(tag)
buffer.append(bufferedString)
if isMatchingTag {
break loop
}
}
}
}
}
return buffer
}
private mutating func checkForMatchingTag(_ tag: String) -> (bufferedString: String, isMatchingTag: Bool) {
var buffer = ""
loop: while let ch = nextScalar() {
buffer.unicodeScalars.append(ch)
if ch == ">" {
break loop
}
}
return (buffer, buffer.hasPrefix(tag))
}
// MARK: Unchanged Token
private mutating func unchangedToken(_ first: UnicodeScalar) throws -> Token {
var tokenText = String(first)
self.previousScalar = first
loop: while let ch = nextScalar() {
switch ch {
case "\"", "'", "<", "-":
self.bufferedScalar = ch
break loop
default:
self.previousScalar = ch
tokenText.unicodeScalars.append(ch)
}
}
return Token(.unchanged, tokenText)
}
// MARK: Fixable Token (quote, apostrophe, hyphen)
private mutating func fixableToken(_ first: UnicodeScalar) throws -> Token {
var tokenText = String(first)
let nextScalar = self.nextScalar()
self.bufferedScalar = nextScalar
var fixingResult: Result = .ignored
switch first {
case "\"":
if let previousScalar = self.previousScalar,
let nextScalar = nextScalar {
if CharacterSet.whitespacesAndNewlines.contains(previousScalar) || self.openingBracketsSet.contains(previousScalar) {
tokenText = self.openingDoubleQuote
fixingResult = .openingDouble
} else if CharacterSet.whitespacesAndNewlines.contains(nextScalar) || CharacterSet.punctuationCharacters.contains(nextScalar) {
tokenText = self.closingDoubleQuote
fixingResult = .closingDouble
} else {
tokenText = self.closingDoubleQuote
fixingResult = .closingDouble
}
} else {
if self.previousScalar == nil {
// The last character of a string:
tokenText = self.openingDoubleQuote
fixingResult = .openingDouble
} else {
// The first character of a string:
tokenText = self.closingDoubleQuote
fixingResult = .closingDouble
}
}
case "'":
if let previousScalar = self.previousScalar,
let nextScalar = nextScalar {
if CharacterSet.whitespacesAndNewlines.contains(previousScalar)
|| CharacterSet.punctuationCharacters.contains(previousScalar) && !CharacterSet.whitespacesAndNewlines.contains(nextScalar) {
tokenText = self.openingSingleQuote
fixingResult = .openingSingle
} else if CharacterSet.whitespacesAndNewlines.contains(nextScalar) || CharacterSet.punctuationCharacters.contains(nextScalar) {
tokenText = self.closingSingleQuote
fixingResult = .closingSingle
} else {
tokenText = self.apostrophe
fixingResult = .apostrophe
}
} else {
if self.previousScalar == nil {
// The first character of a string:
tokenText = self.openingSingleQuote
fixingResult = .openingSingle
} else {
// The last character of a string:
tokenText = self.closingSingleQuote
fixingResult = .closingSingle
}
}
case "-":
if let previousScalar = self.previousScalar,
let nextScalar = nextScalar,
CharacterSet.whitespacesAndNewlines.contains(previousScalar)
&& CharacterSet.whitespacesAndNewlines.contains(nextScalar) {
tokenText = self.enDash
fixingResult = .enDash
}
default: ()
}
self.previousScalar = tokenText.unicodeScalars.last
#if DEBUG
if self.isDebugModeEnabled && self.isHTML {
tokenText = "<span class=\"typographizer-debug typographizer-debug--\(fixingResult.rawValue)\">\(tokenText)</span>"
}
#endif
return Token(fixingResult, tokenText)
}
}
extension Typographizer {
enum Result: String {
case openingSingle = "opening-single"
case closingSingle = "closing-single"
case openingDouble = "opening-double"
case closingDouble = "closing-double"
case apostrophe
case enDash = "en-dash"
// Unchanged text because it doesn’t contain the trigger characters:
case unchanged
// It’s one of the trigger characters but didn’t need changing:
case ignored
// Was skipped because it was either an HTML tag, or a pair of tags with protected text in between:
case skipped
}
struct Token {
let result: Result
let text: String
init(_ result: Result, _ text: String) {
self.result = result
self.text = text
}
}
}
|
mit
|
26758fec7c472a0138928d3286bb5630
| 32.68798 | 145 | 0.525812 | 5.097523 | false | false | false | false |
nakajijapan/Sengiri
|
Sengiri/AppDelegate.swift
|
1
|
11463
|
//
// AppDelegate.swift
// ScreenRecord
//
// Created by nakajijapan on 2016/02/17.
// Copyright © 2016 nakajijapan. All rights reserved.
//
import Cocoa
import AVFoundation
import CoreMedia
import CoreVideo
import QuartzCore
import RegiftOSX
let SengiriHomePath = "\(NSHomeDirectory())/Pictures"
let SengiriSavePath = "\(SengiriHomePath)/\(Bundle.main.bundleIdentifier!)"
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var menu: NSMenu!
@IBOutlet weak var mainMenuItem: NSMenuItem!
var statusItem:NSStatusItem?
var captureController:CaptureWindowController? = nil
var preferenceWindowController:NSWindowController? = nil
// image
var captureSession:AVCaptureSession!
var videoStillImageOutput:AVCaptureStillImageOutput!
// movie
var videoMovieFileOutput:AVCaptureMovieFileOutput!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// create working directory
let fileManager = FileManager.default
do {
try fileManager.createDirectory(atPath: "\(SengiriSavePath)", withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print("failed to make directory. error: \(error.description)")
}
// initialize default setting
NotificationCenter.default.addObserver(
self,
selector: #selector(recordButtonDidClick(_:)),
name: NSNotification.Name(rawValue: "CaptureViewRecordButtonDidClick"),
object: nil
)
let frameCount = UserDefaults.standard.double(forKey: "GifSecondPerFrame")
if frameCount == 0 {
UserDefaults.standard.set(0.1, forKey: "GifSecondPerFrame")
}
let delayTime = UserDefaults.standard.float(forKey: "GifDelayTime")
if delayTime == 0.0 {
UserDefaults.standard.set(0.1, forKey: "GifDelayTime")
}
let compressionRate = UserDefaults.standard.float(forKey: "GifCompressionRate")
if compressionRate == 0.0 {
UserDefaults.standard.set(0.5, forKey: "GifCompressionRate")
}
menu.delegate = self
}
deinit {
NotificationCenter.default.removeObserver(
self,
name: NSNotification.Name(rawValue: "CaptureViewRecordButtonDidClick"),
object: nil
)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
// MARK: - Main Menu Actions
extension AppDelegate {
@IBAction func mainMenuItemDidClick(_ sender: AnyObject) {
menuItemForCropRecordDidClick(NSMenuItem())
}
@IBAction func mainMenuItemForCropWindowToTopWindowDidClic(_ sender: AnyObject) {
if captureController == nil {
let storyBoard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil)
let windowController = storyBoard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "CaptureWindowController")) as! CaptureWindowController
captureController = windowController
}
if let windowInfo = WindowInfoManager.topWindowInfo() {
let frame = windowInfo.frame
captureController?.window?.setFrame(frame, display: true, animate: true)
}
captureController?.showWindow(nil)
captureController?.window?.makeKey()
}
@IBAction func mainMenuForStopDidClick(_ sender: AnyObject) {
menuItemForStopDidClick(NSMenuItem())
}
}
// MARK: - NSMenuDelegate
extension AppDelegate: NSMenuDelegate {
func menuWillOpen(_ menu: NSMenu) {
let progressIndicator = NSProgressIndicator(frame: NSRect(x: 0, y: 0, width: 16, height: 16))
progressIndicator.style = NSProgressIndicator.Style.spinning
progressIndicator.startAnimation(nil)
progressIndicator.controlSize = NSControl.ControlSize.small
progressIndicator.isDisplayedWhenStopped = false
statusItem!.view = progressIndicator
menuItemForStopDidClick(NSMenuItem())
}
}
// MARK: - NSMenu Actions
extension AppDelegate {
func menuItemForCropRecordDidClick(_ sender: NSMenuItem) {
if captureController == nil {
let storyBoard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil)
let windowController = storyBoard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "CaptureWindowController")) as! CaptureWindowController
captureController = windowController
}
captureController!.showWindow(nil)
captureController?.window?.makeKey()
}
func menuItemForStopDidClick(_ sender: NSMenuItem) {
captureController?.window?.close()
captureController?.close()
captureController = nil // assign nil because some capture window opens when capture window open in second time
NotificationCenter.default.post(name: Notification.Name(rawValue: "AppDelegateStopMenuDidClick"), object: self, userInfo:nil)
if videoMovieFileOutput == nil {
return
}
if videoMovieFileOutput.isRecording {
videoMovieFileOutput.stopRecording()
captureSession.stopRunning()
}
}
@IBAction func mainMenuItemForPreferenceDidClick(_ sender: NSMenuItem) {
if preferenceWindowController == nil {
let storyBoard = NSStoryboard(name: NSStoryboard.Name(rawValue: "PreferenceWindowController"), bundle: nil)
let windowController = storyBoard.instantiateInitialController() as! NSWindowController
windowController.showWindow(self)
preferenceWindowController = windowController
}
preferenceWindowController!.showWindow(nil)
preferenceWindowController?.window?.makeKey()
}
}
// MARK: - Notifications
extension AppDelegate {
@objc func recordButtonDidClick(_ button:NSButton) {
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
statusItem!.highlightMode = true
statusItem!.menu = menu
statusItem!.image = NSImage(named: NSImage.Name(rawValue: "icon_stop"))
prapareVideoScreen()
}
var currentDisplayID: CGDirectDisplayID {
guard let screen = captureController?.window?.screen else {
fatalError("Can not find screen info")
}
guard let displayID = screen.deviceDescription[NSDeviceDescriptionKey(rawValue: "NSScreenNumber")] as? CGDirectDisplayID else {
fatalError("Can not find screen device description")
}
return displayID
}
var currentSize: NSSize {
guard let screen = captureController?.window?.screen else {
fatalError("Can not find screen info")
}
guard let size = screen.deviceDescription[NSDeviceDescriptionKey.size] as? NSSize else {
fatalError("Can not find screen device description")
}
return size
}
func prapareVideoScreen() {
videoMovieFileOutput = AVCaptureMovieFileOutput()
let captureInput = AVCaptureScreenInput(displayID: currentDisplayID)
captureSession = AVCaptureSession()
if captureSession.canAddInput(captureInput) {
captureSession.addInput(captureInput)
}
if captureSession.canAddOutput(videoMovieFileOutput) {
captureSession.addOutput(videoMovieFileOutput)
}
// Start running the session
captureSession.startRunning()
// delete file
let fileName = Bundle.main.bundleIdentifier!
let pathString = "\(NSTemporaryDirectory())/\(fileName).mov"
let schemePathString = "file://\(pathString)"
if FileManager.default.fileExists(atPath: pathString) {
try! FileManager.default.removeItem(atPath: pathString)
}
if let frame = captureController?.window?.frame {
let mainDisplayBounds = CGDisplayBounds(CGMainDisplayID())
let quartzScreenFrame = CGDisplayBounds(currentDisplayID)
let x = frame.origin.x - quartzScreenFrame.origin.x
let y = frame.origin.y - (mainDisplayBounds.height - quartzScreenFrame.origin.y - quartzScreenFrame.height)
// cropping
let differencialValue = SengiriCropViewLineWidth
let optimizeFrame = NSRect(
x: x + differencialValue,
y: y + differencialValue,
width: frame.width - differencialValue * 2.0,
height: frame.height - differencialValue * 2.0
)
captureInput.cropRect = optimizeFrame
// start recording
videoMovieFileOutput.startRecording(to: URL(string: schemePathString)!, recordingDelegate: self)
}
}
}
// MARK: - AVCaptureFileOutputRecordingDelegate
extension AppDelegate: AVCaptureFileOutputRecordingDelegate {
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddHHmmss"
let dateString = dateFormatter.string(from: Date())
let pathString = "\(SengiriSavePath)/\(dateString).gif"
let schemePathURL = URL(string: "file://\(pathString)")!
if FileManager.default.fileExists(atPath: pathString) {
try! FileManager.default.removeItem(atPath: pathString)
}
let secondPerFrame = UserDefaults.standard.float(forKey: "GifSecondPerFrame")
let delayTime = UserDefaults.standard.float(forKey: "GifDelayTime")
let compressionRate = CGFloat(UserDefaults.standard.float(forKey: "GifCompressionRate"))
guard let track = AVAsset(url: outputFileURL).tracks(withMediaType: AVMediaType.video).first else { return }
var size = track.naturalSize.applying(track.preferredTransform)
let compressionTargetSide: CGFloat = 1000
if size.width >= compressionTargetSide || size.height >= compressionTargetSide {
size.width = size.width * compressionRate
size.height = size.height * compressionRate
}
let regift = Regift(
sourceFileURL: outputFileURL,
destinationFileURL: schemePathURL,
frameCount: frameCount(outputFileURL, secondPerFrame: secondPerFrame),
delayTime: delayTime,
loopCount: 0,
width: Int(size.width),
height: Int(size.height)
)
_ = regift.createGif()
// hide menu
statusItem!.image = nil
statusItem!.view = nil
NSStatusBar.system.removeStatusItem(statusItem!)
let url = URL(string: "file://\(SengiriSavePath)")!
NSWorkspace.shared.open(url)
}
func frameCount(_ sourceFileURL:URL, secondPerFrame:Float) -> Int {
let asset = AVURLAsset(url: sourceFileURL, options: nil)
let movieLength = Float(asset.duration.value) / Float(asset.duration.timescale)
let frameCount = Int(movieLength / secondPerFrame)
return frameCount
}
}
|
mit
|
11cfb6d7ff5c4671fbd8f221beedd7df
| 34.051988 | 178 | 0.660618 | 5.265044 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.