repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
mono0926/SwiftRecord | Samples/Samples/AppDelegate.swift | 1 | 2148 | //
// AppDelegate.swift
// Samples
//
// Created by mono on 6/16/14.
// Copyright (c) 2014 mono. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> 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:.
}
}
| mit |
astralbodies/CleanRooms | CleanRooms/Services/RoomService.swift | 1 | 2195 | /*
* Copyright (c) 2015 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
import CoreData
public class RoomService {
let managedObjectContext: NSManagedObjectContext
public init(managedObjectContext: NSManagedObjectContext) {
self.managedObjectContext = managedObjectContext
}
public func getAllRooms() -> [Room] {
let fetchRequest = NSFetchRequest(entityName: "Room")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "roomNumber", ascending: true)]
var results: [AnyObject]
do {
try results = managedObjectContext.executeFetchRequest(fetchRequest)
} catch {
print("Error when fetching rooms: \(error)")
return [Room]()
}
return results as! [Room]
}
public func getRoomByID(roomID: String) -> Room? {
let fetchRequest = NSFetchRequest(entityName: "Room")
fetchRequest.predicate = NSPredicate(format: "roomID == %@", roomID)
var results: [AnyObject]
do {
try results = managedObjectContext.executeFetchRequest(fetchRequest)
} catch {
print("Error when fetching Room by ID: \(error)")
return nil
}
return results.first as? Room
}
}
| mit |
SaberVicky/LoveStory | LoveStory/Feature/Profile/LSProfileViewController.swift | 1 | 1438 | //
// LSProfileViewController.swift
// LoveStory
//
// Created by songlong on 2017/1/19.
// Copyright © 2017年 com.Saber. All rights reserved.
//
import UIKit
class LSProfileViewController: UITableViewController {
private let dataList: [[String]] = [["更改头像", "昵称", "性别", "生日"], ["解除关系"]];
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .white
tableView = UITableView(frame: UIScreen.main.bounds, style: .grouped)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "ProfileCell")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return dataList.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataList[section].count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileCell", for: indexPath)
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = dataList[indexPath.section][indexPath.row]
return cell
}
}
| mit |
swift-gtk/SwiftGTK | Sources/UIKit/Misc.swift | 1 | 328 |
public class Misc: Widget {
override class var n_Type: UInt {
return gtk_misc_get_type()
}
// internal init(n_Misc: UnsafeMutablePointer<GtkMisc>) {
// self.n_Misc = n_Misc
// super.init(n_Widget: unsafeBitCast(self.n_Misc, to: UnsafeMutablePointer<GtkWidget>.self))
// }
}
| gpl-2.0 |
biohazardlover/NintendoEverything | NintendoEverything/Router/Routing.swift | 1 | 529 | //
// Routing.swift
// HuaBan-iOS
//
// Created by Leon Li on 30/12/2017.
// Copyright © 2017 Feiguo. All rights reserved.
//
import UIKit
enum RoutingStyle {
case navigation
case presentation
}
protocol RoutingProtocol {
var style: RoutingStyle { get }
var viewController: UIViewController { get }
var animated: Bool { get }
}
protocol Prerouting: RoutingProtocol {
var handler: (@escaping () -> ()) -> () { get }
}
protocol Routing: RoutingProtocol {
var prerouting: Prerouting? { get }
}
| mit |
tkremenek/swift | test/decl/subscript/subscripting.swift | 11 | 14524 | // RUN: %target-typecheck-verify-swift
struct X { } // expected-note * {{did you mean 'X'?}}
// Simple examples
struct X1 {
var stored : Int
subscript (i : Int) -> Int {
get {
return stored
}
mutating
set {
stored = newValue
}
}
}
struct X2 {
var stored : Int
subscript (i : Int) -> Int {
get {
return stored + i
}
set(v) {
stored = v - i
}
}
}
struct X3 {
var stored : Int
subscript (_ : Int) -> Int {
get {
return stored
}
set(v) {
stored = v
}
}
}
struct X4 {
var stored : Int
subscript (i : Int, j : Int) -> Int {
get {
return stored + i + j
}
set(v) {
stored = v + i - j
}
}
}
struct X5 {
static var stored : Int = 1
static subscript (i : Int) -> Int {
get {
return stored + i
}
set {
stored = newValue - i
}
}
}
class X6 {
static var stored : Int = 1
class subscript (i : Int) -> Int {
get {
return stored + i
}
set {
stored = newValue - i
}
}
}
protocol XP1 {
subscript (i : Int) -> Int { get set }
static subscript (i : Int) -> Int { get set }
}
// Semantic errors
struct Y1 {
var x : X
subscript(i: Int) -> Int {
get {
return x // expected-error{{cannot convert return expression of type 'X' to return type 'Int'}}
}
set {
x = newValue // expected-error{{cannot assign value of type 'Int' to type 'X'}}
}
}
}
struct Y2 {
subscript(idx: Int) -> TypoType { // expected-error {{cannot find type 'TypoType' in scope}}
get { repeat {} while true }
set {}
}
}
class Y3 {
subscript(idx: Int) -> TypoType { // expected-error {{cannot find type 'TypoType' in scope}}
get { repeat {} while true }
set {}
}
}
class Y4 {
var x = X()
static subscript(idx: Int) -> X {
get { return x } // expected-error {{instance member 'x' cannot be used on type 'Y4'}}
set {}
}
}
class Y5 {
static var x = X()
subscript(idx: Int) -> X {
get { return x } // expected-error {{static member 'x' cannot be used on instance of type 'Y5'}}
set {}
}
}
protocol ProtocolGetSet0 {
subscript(i: Int) -> Int {} // expected-error {{subscript declarations must have a getter}}
}
protocol ProtocolGetSet1 {
subscript(i: Int) -> Int { get }
}
protocol ProtocolGetSet2 {
subscript(i: Int) -> Int { set } // expected-error {{subscript with a setter must also have a getter}}
}
protocol ProtocolGetSet3 {
subscript(i: Int) -> Int { get set }
}
protocol ProtocolGetSet4 {
subscript(i: Int) -> Int { set get }
}
protocol ProtocolWillSetDidSet1 {
subscript(i: Int) -> Int { willSet } // expected-error {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}}
}
protocol ProtocolWillSetDidSet2 {
subscript(i: Int) -> Int { didSet } // expected-error {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}}
}
protocol ProtocolWillSetDidSet3 {
subscript(i: Int) -> Int { willSet didSet } // expected-error 2 {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}}
}
protocol ProtocolWillSetDidSet4 {
subscript(i: Int) -> Int { didSet willSet } // expected-error 2 {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}}
}
class DidSetInSubscript {
subscript(_: Int) -> Int {
didSet { // expected-error {{'didSet' is not allowed in subscripts}}
print("eek")
}
get {}
}
}
class WillSetInSubscript {
subscript(_: Int) -> Int {
willSet { // expected-error {{'willSet' is not allowed in subscripts}}
print("eek")
}
get {}
}
}
subscript(i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}}
get {}
}
func f() { // expected-note * {{did you mean 'f'?}}
subscript (i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}}
get {}
}
}
struct NoSubscript { }
struct OverloadedSubscript {
subscript(i: Int) -> Int {
get {
return i
}
set {}
}
subscript(i: Int, j: Int) -> Int {
get { return i }
set {}
}
}
struct RetOverloadedSubscript {
subscript(i: Int) -> Int { // expected-note {{found this candidate}}
get { return i }
set {}
}
subscript(i: Int) -> Float { // expected-note {{found this candidate}}
get { return Float(i) }
set {}
}
}
struct MissingGetterSubscript1 {
subscript (i : Int) -> Int {
} // expected-error {{subscript must have accessors specified}}
}
struct MissingGetterSubscript2 {
subscript (i : Int, j : Int) -> Int {
set {} // expected-error{{subscript with a setter must also have a getter}}
}
}
func test_subscript(_ x2: inout X2, i: Int, j: Int, value: inout Int, no: NoSubscript,
ovl: inout OverloadedSubscript, ret: inout RetOverloadedSubscript) {
no[i] = value // expected-error{{value of type 'NoSubscript' has no subscripts}}
value = x2[i]
x2[i] = value
value = ovl[i]
ovl[i] = value
value = ovl[i, j]
ovl[i, j] = value
value = ovl[(i, j, i)] // expected-error{{cannot convert value of type '(Int, Int, Int)' to expected argument type 'Int'}}
ret[i] // expected-error{{ambiguous use of 'subscript(_:)'}}
value = ret[i]
ret[i] = value
X5[i] = value
value = X5[i]
}
func test_proto_static<XP1Type: XP1>(
i: Int, value: inout Int,
existential: inout XP1,
generic: inout XP1Type
) {
existential[i] = value
value = existential[i]
type(of: existential)[i] = value
value = type(of: existential)[i]
generic[i] = value
value = generic[i]
XP1Type[i] = value
value = XP1Type[i]
}
func subscript_rvalue_materialize(_ i: inout Int) {
i = X1(stored: 0)[i]
}
func subscript_coerce(_ fn: ([UnicodeScalar], [UnicodeScalar]) -> Bool) {}
func test_subscript_coerce() {
subscript_coerce({ $0[$0.count-1] < $1[$1.count-1] })
}
struct no_index {
subscript () -> Int { return 42 }
func test() -> Int {
return self[]
}
}
struct tuple_index {
subscript (x : Int, y : Int) -> (Int, Int) { return (x, y) }
func test() -> (Int, Int) {
return self[123, 456]
}
}
struct MutableComputedGetter {
var value: Int
subscript(index: Int) -> Int {
value = 5 // expected-error{{cannot assign to property: 'self' is immutable}}
return 5
}
var getValue : Int {
value = 5 // expected-error {{cannot assign to property: 'self' is immutable}}
return 5
}
}
struct MutableSubscriptInGetter {
var value: Int
subscript(index: Int) -> Int {
get { // expected-note {{mark accessor 'mutating' to make 'self' mutable}}
value = 5 // expected-error{{cannot assign to property: 'self' is immutable}}
return 5
}
}
}
protocol Protocol {}
protocol RefinedProtocol: Protocol {}
class SuperClass {}
class SubClass: SuperClass {}
class SubSubClass: SubClass {}
class ClassConformingToProtocol: Protocol {}
class ClassConformingToRefinedProtocol: RefinedProtocol {}
struct GenSubscriptFixitTest {
subscript<T>(_ arg: T) -> Bool { return true } // expected-note 3 {{declared here}}
// expected-note@-1 2 {{in call to 'subscript(_:)'}}
}
func testGenSubscriptFixit(_ s0: GenSubscriptFixitTest) {
_ = s0.subscript("hello")
// expected-error@-1 {{value of type 'GenSubscriptFixitTest' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{27-28=]}}
}
func testUnresolvedMemberSubscriptFixit(_ s0: GenSubscriptFixitTest) {
_ = s0.subscript
// expected-error@-1 {{value of type 'GenSubscriptFixitTest' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-19=[<#index#>]}}
// expected-error@-2 {{generic parameter 'T' could not be inferred}}
s0.subscript = true
// expected-error@-1 {{value of type 'GenSubscriptFixitTest' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{5-15=[<#index#>]}}
// expected-error@-2 {{generic parameter 'T' could not be inferred}}
}
struct SubscriptTest1 {
subscript(keyword:String) -> Bool { return true }
// expected-note@-1 5 {{found this candidate}} expected-note@-1 {{'subscript(_:)' produces 'Bool', not the expected contextual result type 'Int'}}
subscript(keyword:String) -> String? {return nil }
// expected-note@-1 5 {{found this candidate}} expected-note@-1 {{'subscript(_:)' produces 'String?', not the expected contextual result type 'Int'}}
subscript(arg: SubClass) -> Bool { return true } // expected-note {{declared here}}
// expected-note@-1 2 {{found this candidate}}
subscript(arg: Protocol) -> Bool { return true } // expected-note 2 {{declared here}}
// expected-note@-1 2 {{found this candidate}}
subscript(arg: (foo: Bool, bar: (Int, baz: SubClass)), arg2: String) -> Bool { return true }
// expected-note@-1 3 {{declared here}}
}
func testSubscript1(_ s1 : SubscriptTest1) {
let _ : Int = s1["hello"] // expected-error {{no 'subscript' candidates produce the expected contextual result type 'Int'}}
if s1["hello"] {}
_ = s1.subscript((true, (5, SubClass())), "hello")
// expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{52-53=]}}
_ = s1.subscript((true, (5, baz: SubSubClass())), "hello")
// expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{60-61=]}}
_ = s1.subscript((fo: true, (5, baz: SubClass())), "hello")
// expected-error@-1 {{cannot convert value of type '(fo: Bool, (Int, baz: SubClass))' to expected argument type '(foo: Bool, bar: (Int, baz: SubClass))'}}
// expected-error@-2 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}}
_ = s1.subscript(SubSubClass())
// expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{33-34=]}}
_ = s1.subscript(ClassConformingToProtocol())
// expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{47-48=]}}
_ = s1.subscript(ClassConformingToRefinedProtocol())
// expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{54-55=]}}
_ = s1.subscript(true)
// expected-error@-1 {{no exact matches in call to subscript}}
_ = s1.subscript(SuperClass())
// expected-error@-1 {{no exact matches in call to subscript}}
_ = s1.subscript("hello")
// expected-error@-1 {{no exact matches in call to subscript}}
_ = s1.subscript("hello"
// expected-error@-1 {{no exact matches in call to subscript}}
// expected-note@-2 {{to match this opening '('}}
let _ = s1["hello"]
// expected-error@-1 {{ambiguous use of 'subscript(_:)'}}
// expected-error@-2 {{expected ')' in expression list}}
}
struct SubscriptTest2 {
subscript(a : String, b : Int) -> Int { return 0 } // expected-note {{candidate expects value of type 'Int' for parameter #2}}
// expected-note@-1 2 {{declared here}}
subscript(a : String, b : String) -> Int { return 0 } // expected-note {{candidate expects value of type 'String' for parameter #2}}
}
func testSubscript1(_ s2 : SubscriptTest2) {
_ = s2["foo"] // expected-error {{missing argument for parameter #2 in call}}
let a = s2["foo", 1.0] // expected-error {{no exact matches in call to subscript}}
_ = s2.subscript("hello", 6)
// expected-error@-1 {{value of type 'SubscriptTest2' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{30-31=]}}
let b = s2[1, "foo"] // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
// rdar://problem/27449208
let v: (Int?, [Int]?) = (nil [17]) // expected-error {{cannot subscript a nil literal value}}
}
// sr-114 & rdar://22007370
class Foo {
subscript(key: String) -> String { // expected-note {{'subscript(_:)' previously declared here}}
get { a } // expected-error {{cannot find 'a' in scope}}
set { b } // expected-error {{cannot find 'b' in scope}}
}
subscript(key: String) -> String { // expected-error {{invalid redeclaration of 'subscript(_:)'}}
get { _ = 0; a } // expected-error {{cannot find 'a' in scope}}
set { b } // expected-error {{cannot find 'b' in scope}}
}
}
// <rdar://problem/23952125> QoI: Subscript in protocol with missing {}, better diagnostic please
protocol r23952125 {
associatedtype ItemType
var count: Int { get }
subscript(index: Int) -> ItemType // expected-error {{subscript in protocol must have explicit { get } or { get set } specifier}} {{36-36= { get <#set#> \}}}
var c : Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-14= { get <#set#> \}}}
}
// SR-2575
struct SR2575 {
subscript() -> Int { // expected-note {{declared here}}
return 1
}
}
SR2575().subscript()
// expected-error@-1 {{value of type 'SR2575' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{20-21=]}}
// SR-7890
struct InOutSubscripts {
subscript(x1: inout Int) -> Int { return 0 }
// expected-error@-1 {{'inout' must not be used on subscript parameters}}
subscript(x2: inout Int, y2: inout Int) -> Int { return 0 }
// expected-error@-1 2{{'inout' must not be used on subscript parameters}}
subscript(x3: (inout Int) -> ()) -> Int { return 0 } // ok
subscript(x4: (inout Int, inout Int) -> ()) -> Int { return 0 } // ok
subscript(inout x5: Int) -> Int { return 0 }
// expected-error@-1 {{'inout' before a parameter name is not allowed, place it before the parameter type instead}}
// expected-error@-2 {{'inout' must not be used on subscript parameters}}
}
| apache-2.0 |
mitochrome/complex-gestures-demo | apps/GestureRecognizer/Carthage/Checkouts/RxDataSources/Example/Example4_DifferentSectionAndItemTypes.swift | 3 | 4225 | //
// MultipleSectionModelViewController.swift
// RxDataSources
//
// Created by Segii Shulga on 4/26/16.
// Copyright © 2016 kzaher. All rights reserved.
//
import UIKit
import RxDataSources
import RxCocoa
import RxSwift
// the trick is to just use enum for different section types
class MultipleSectionModelViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let sections: [MultipleSectionModel] = [
.ImageProvidableSection(title: "Section 1",
items: [.ImageSectionItem(image: UIImage(named: "settings")!, title: "General")]),
.ToggleableSection(title: "Section 2",
items: [.ToggleableSectionItem(title: "On", enabled: true)]),
.StepperableSection(title: "Section 3",
items: [.StepperSectionItem(title: "1")])
]
let dataSource = RxTableViewSectionedReloadDataSource<MultipleSectionModel>()
skinTableViewDataSource(dataSource)
Observable.just(sections)
.bind(to: tableView.rx.items(dataSource: dataSource))
.addDisposableTo(disposeBag)
}
func skinTableViewDataSource(_ dataSource: RxTableViewSectionedReloadDataSource<MultipleSectionModel>) {
dataSource.configureCell = { (dataSource, table, idxPath, _) in
switch dataSource[idxPath] {
case let .ImageSectionItem(image, title):
let cell: ImageTitleTableViewCell = table.dequeueReusableCell(forIndexPath: idxPath)
cell.titleLabel.text = title
cell.cellImageView.image = image
return cell
case let .StepperSectionItem(title):
let cell: TitleSteperTableViewCell = table.dequeueReusableCell(forIndexPath: idxPath)
cell.titleLabel.text = title
return cell
case let .ToggleableSectionItem(title, enabled):
let cell: TitleSwitchTableViewCell = table.dequeueReusableCell(forIndexPath: idxPath)
cell.switchControl.isOn = enabled
cell.titleLabel.text = title
return cell
}
}
dataSource.titleForHeaderInSection = { dataSource, index in
let section = dataSource[index]
return section.title
}
}
}
enum MultipleSectionModel {
case ImageProvidableSection(title: String, items: [SectionItem])
case ToggleableSection(title: String, items: [SectionItem])
case StepperableSection(title: String, items: [SectionItem])
}
enum SectionItem {
case ImageSectionItem(image: UIImage, title: String)
case ToggleableSectionItem(title: String, enabled: Bool)
case StepperSectionItem(title: String)
}
extension MultipleSectionModel: SectionModelType {
typealias Item = SectionItem
var items: [SectionItem] {
switch self {
case .ImageProvidableSection(title: _, items: let items):
return items.map {$0}
case .StepperableSection(title: _, items: let items):
return items.map {$0}
case .ToggleableSection(title: _, items: let items):
return items.map {$0}
}
}
init(original: MultipleSectionModel, items: [Item]) {
switch original {
case let .ImageProvidableSection(title: title, items: _):
self = .ImageProvidableSection(title: title, items: items)
case let .StepperableSection(title, _):
self = .StepperableSection(title: title, items: items)
case let .ToggleableSection(title, _):
self = .ToggleableSection(title: title, items: items)
}
}
}
extension MultipleSectionModel {
var title: String {
switch self {
case .ImageProvidableSection(title: let title, items: _):
return title
case .StepperableSection(title: let title, items: _):
return title
case .ToggleableSection(title: let title, items: _):
return title
}
}
}
| mit |
ioscodigo/ICTabFragment | ICTabFragment/ICTabCollectionViewCell.swift | 2 | 2349 | //
// ICTabCollectionViewCell.swift
// ICTabFragment
//
// Created by Digital Khrisna on 6/1/17.
// Copyright © 2017 codigo. All rights reserved.
//
import UIKit
class ICTabCollectionViewCell: UICollectionViewCell {
var tabNameLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor.black
label.font = UIFont.systemFont(ofSize: 12)
label.numberOfLines = 0
label.text = "Label"
label.sizeToFit()
return label
}()
var indicatorView: UIView = {
let view = UIView()
return view
}()
private var indicatorTopSpaceConstraint: NSLayoutConstraint!
private var indicatorHeightConstraint: NSLayoutConstraint!
var indicatorTopSpace: CGFloat = 0 {
didSet {
indicatorTopSpaceConstraint.constant = indicatorTopSpace
}
}
var indicatorHeight: CGFloat = 5 {
didSet {
indicatorHeightConstraint.constant = indicatorHeight
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(tabNameLabel)
tabNameLabel.translatesAutoresizingMaskIntoConstraints = false
tabNameLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0).isActive = true
tabNameLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0).isActive = true
self.addSubview(indicatorView)
indicatorView.translatesAutoresizingMaskIntoConstraints = false
indicatorView.widthAnchor.constraint(equalTo: tabNameLabel.widthAnchor, multiplier: 0.8).isActive = true
indicatorTopSpaceConstraint = indicatorView.topAnchor.constraint(equalTo: tabNameLabel.bottomAnchor, constant: indicatorTopSpace)
indicatorTopSpaceConstraint.isActive = true
indicatorView.centerXAnchor.constraint(equalTo: tabNameLabel.centerXAnchor, constant: 0).isActive = true
indicatorHeightConstraint = indicatorView.heightAnchor.constraint(equalToConstant: indicatorHeight)
indicatorHeightConstraint.isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var reuseIdentifier: String? {
return "ictabcollectionviewcell"
}
}
| mit |
xwu/swift | test/IRGen/async/run-call-nonresilient-classinstance-void-to-void.swift | 1 | 1414 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift-dylib(%t/%target-library-name(NonresilientClass)) %S/Inputs/class_open-1instance-void_to_void.swift -Xfrontend -disable-availability-checking -g -module-name NonresilientClass -emit-module -emit-module-path %t/NonresilientClass.swiftmodule
// RUN: %target-codesign %t/%target-library-name(NonresilientClass)
// RUN: %target-build-swift -Xfrontend -disable-availability-checking -g %S/Inputs/class_open-1instance-void_to_void.swift -emit-ir -I %t -L %t -lNonresilientClass -parse-as-library -module-name main | %FileCheck %S/Inputs/class_open-1instance-void_to_void.swift --check-prefix=CHECK-LL
// RUN: %target-build-swift -Xfrontend -disable-availability-checking -g %s -parse-as-library -module-name main -o %t/main -I %t -L %t -lNonresilientClass %target-rpath(%t)
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main %t/%target-library-name(NonresilientClass) | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: swift_test_mode_optimize_none
// REQUIRES: concurrency
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
// XFAIL: windows
import _Concurrency
import NonresilientClass
class D : C {
}
// CHECK: entering call_f
// CHECK: entering f
// CHECK: D
// CHECK: main.D
// CHECK: exiting f
// CHECK: exiting call_f
@main struct Main {
static func main() async {
let c = D()
await call_f(c)
}
}
| apache-2.0 |
joerocca/GitHawk | Pods/Tabman/Sources/Tabman/TabmanBar/TabmanBar.swift | 1 | 13153 | //
// TabmanBar.swift
// Tabman
//
// Created by Merrick Sapsford on 17/02/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import UIKit
import PureLayout
import Pageboy
public protocol TabmanBarDelegate: class {
/// Whether a bar should select an item at an index.
///
/// - Parameters:
/// - index: The proposed selection index.
/// - Returns: Whether the index should be selected.
func bar(shouldSelectItemAt index: Int) -> Bool
}
/// A bar that displays the current page status of a TabmanViewController.
open class TabmanBar: UIView, TabmanBarLifecycle {
// MARK: Types
/// The height for the bar.
///
/// - auto: Autosize the bar according to its contents.
/// - explicit: Explicit value for the bar height.
public enum Height {
case auto
case explicit(value: CGFloat)
}
// MARK: Properties
/// The items that are displayed in the bar.
internal var items: [TabmanBar.Item]? {
didSet {
self.isHidden = (items?.count ?? 0) == 0
}
}
internal private(set) var currentPosition: CGFloat = 0.0
internal weak var transitionStore: TabmanBarTransitionStore?
internal lazy var behaviorEngine = BarBehaviorEngine(for: self)
/// The object that acts as a responder to the bar.
internal weak var responder: TabmanBarResponder?
/// The object that acts as a data source to the bar.
public weak var dataSource: TabmanBarDataSource? {
didSet {
self.reloadData()
}
}
/// Appearance configuration for the bar.
public var appearance: Appearance = .defaultAppearance {
didSet {
self.updateCore(forAppearance: appearance)
}
}
/// The height for the bar. Default: .auto
public var height: Height = .auto {
didSet {
switch height {
case let .explicit(value) where value == 0:
removeAllSubviews()
default: break
}
self.invalidateIntrinsicContentSize()
self.superview?.setNeedsLayout()
self.superview?.layoutIfNeeded()
}
}
open override var intrinsicContentSize: CGSize {
var autoSize = super.intrinsicContentSize
switch self.height {
case .explicit(let height):
autoSize.height = height
return autoSize
default:
return autoSize
}
}
/// Background view of the bar.
public private(set) var backgroundView: BackgroundView = BackgroundView(forAutoLayout: ())
/// The content view for the bar.
public private(set) var contentView = UIView(forAutoLayout: ())
/// The bottom separator view for the bar.
internal private(set) var bottomSeparator = SeparatorView()
/// Indicator for the bar.
public internal(set) var indicator: TabmanIndicator? {
didSet {
indicator?.delegate = self
self.clear(indicator: oldValue)
}
}
/// Mask view used for indicator.
internal var indicatorMaskView: UIView = {
let maskView = UIView()
maskView.backgroundColor = .black
return maskView
}()
internal var indicatorLeftMargin: NSLayoutConstraint?
internal var indicatorWidth: NSLayoutConstraint?
internal var indicatorIsProgressive: Bool = TabmanBar.Appearance.defaultAppearance.indicator.isProgressive ?? false {
didSet {
guard indicatorIsProgressive != oldValue else {
return
}
UIView.animate(withDuration: 0.3, animations: {
self.updateForCurrentPosition()
})
}
}
internal var indicatorBounces: Bool = TabmanBar.Appearance.defaultAppearance.indicator.bounces ?? false
internal var indicatorCompresses: Bool = TabmanBar.Appearance.defaultAppearance.indicator.compresses ?? false
/// Preferred style for the indicator.
/// Bar conforms at own discretion via usePreferredIndicatorStyle()
public var preferredIndicatorStyle: TabmanIndicator.Style? {
didSet {
self.updateIndicator(forPreferredStyle: preferredIndicatorStyle)
}
}
/// The limit that the bar has for the number of items it can display.
public var itemCountLimit: Int? {
return nil
}
// MARK: Init
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initTabBar(coder: aDecoder)
}
public override init(frame: CGRect) {
super.init(frame: frame)
initTabBar(coder: nil)
}
private func initTabBar(coder aDecoder: NSCoder?) {
self.addSubview(backgroundView)
backgroundView.autoPinEdgesToSuperviewEdges()
bottomSeparator.addAsSubview(to: self)
self.addSubview(contentView)
if #available(iOS 11, *) {
contentView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
contentView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor),
contentView.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor),
contentView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
contentView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor)
])
} else {
contentView.autoPinEdgesToSuperviewEdges()
}
self.indicator = self.create(indicatorForStyle: self.defaultIndicatorStyle())
}
// MARK: Lifecycle
open override func layoutSubviews() {
super.layoutSubviews()
// refresh intrinsic size for indicator
self.indicator?.invalidateIntrinsicContentSize()
}
open override func addSubview(_ view: UIView) {
if view !== self.backgroundView &&
view !== self.contentView &&
view !== self.bottomSeparator {
fatalError("Please add subviews to the contentView rather than directly onto the TabmanBar")
}
super.addSubview(view)
}
/// The default indicator style for the bar.
///
/// - Returns: The default indicator style.
open func defaultIndicatorStyle() -> TabmanIndicator.Style {
print("indicatorStyle() returning default. This should be overridden in subclass")
return .clear
}
/// Whether the bar should use preferredIndicatorStyle if available
///
/// - Returns: Whether to use preferredIndicatorStyle
open func usePreferredIndicatorStyle() -> Bool {
return true
}
/// The type of transition to use for the indicator (Internal use only).
///
/// - Returns: The transition type.
internal func indicatorTransitionType() -> TabmanIndicatorTransition.Type? {
return nil
}
// MARK: Data
/// Reload and reconstruct the contents of the bar.
public func reloadData() {
self.items = self.dataSource?.items(for: self)
self.clearAndConstructBar()
}
// MARK: Updating
internal func updatePosition(_ position: CGFloat,
direction: PageboyViewController.NavigationDirection,
bounds: CGRect? = nil) {
guard let items = self.items else {
return
}
let bounds = bounds ?? self.bounds
self.layoutIfNeeded()
self.currentPosition = position
self.update(forPosition: position,
direction: direction,
indexRange: 0 ..< items.count - 1,
bounds: bounds)
}
internal func updateForCurrentPosition(bounds: CGRect? = nil) {
self.updatePosition(self.currentPosition,
direction: .neutral,
bounds: bounds)
}
// MARK: TabmanBarLifecycle
open func construct(in contentView: UIView,
for items: [TabmanBar.Item]) {
}
open func add(indicator: TabmanIndicator, to contentView: UIView) {
}
open func update(forPosition position: CGFloat,
direction: PageboyViewController.NavigationDirection,
indexRange: Range<Int>,
bounds: CGRect) {
guard self.indicator != nil else {
return
}
let indicatorTransition = self.transitionStore?.indicatorTransition(forBar: self)
indicatorTransition?.transition(withPosition: position,
direction: direction,
indexRange: indexRange,
bounds: bounds)
let itemTransition = self.transitionStore?.itemTransition(forBar: self, indicator: self.indicator!)
itemTransition?.transition(withPosition: position,
direction: direction,
indexRange: indexRange,
bounds: bounds)
}
/// Appearance updates that are core to TabmanBar and must always be evaluated
///
/// - Parameter appearance: The appearance config
internal func updateCore(forAppearance appearance: Appearance) {
let defaultAppearance = Appearance.defaultAppearance
self.preferredIndicatorStyle = appearance.indicator.preferredStyle
let backgroundStyle = appearance.style.background ?? defaultAppearance.style.background!
self.backgroundView.style = backgroundStyle
let height: Height
let hideWhenSingleItem = appearance.state.shouldHideWhenSingleItem ?? defaultAppearance.state.shouldHideWhenSingleItem!
if hideWhenSingleItem && items?.count ?? 0 <= 1 {
height = .explicit(value: 0)
} else {
height = appearance.layout.height ?? .auto
}
self.height = height
let bottomSeparatorColor = appearance.style.bottomSeparatorColor ?? defaultAppearance.style.bottomSeparatorColor!
self.bottomSeparator.color = bottomSeparatorColor
let bottomSeparatorEdgeInsets = appearance.layout.bottomSeparatorEdgeInsets ?? defaultAppearance.layout.bottomSeparatorEdgeInsets!
self.bottomSeparator.edgeInsets = bottomSeparatorEdgeInsets
self.update(forAppearance: appearance,
defaultAppearance: defaultAppearance)
}
open func update(forAppearance appearance: Appearance,
defaultAppearance: Appearance) {
let indicatorIsProgressive = appearance.indicator.isProgressive ?? defaultAppearance.indicator.isProgressive!
self.indicatorIsProgressive = indicatorIsProgressive ? self.indicator?.isProgressiveCapable ?? false : false
let indicatorBounces = appearance.indicator.bounces ?? defaultAppearance.indicator.bounces!
self.indicatorBounces = indicatorBounces
let indicatorCompresses = appearance.indicator.compresses ?? defaultAppearance.indicator.compresses!
self.indicatorCompresses = indicatorBounces ? false : indicatorCompresses // only allow compression if bouncing disabled
let indicatorColor = appearance.indicator.color
self.indicator?.tintColor = indicatorColor ?? defaultAppearance.indicator.color!
let indicatorUsesRoundedCorners = appearance.indicator.useRoundedCorners
let lineIndicator = self.indicator as? TabmanLineIndicator
lineIndicator?.useRoundedCorners = indicatorUsesRoundedCorners ?? defaultAppearance.indicator.useRoundedCorners!
let indicatorWeight = appearance.indicator.lineWeight ?? defaultAppearance.indicator.lineWeight!
if let lineIndicator = self.indicator as? TabmanLineIndicator {
lineIndicator.weight = indicatorWeight
}
}
// MARK: Actions
/// Inform the TabmanViewController that an item in the bar was selected.
///
/// - Parameter index: The index of the selected item.
open func itemSelected(at index: Int) {
responder?.bar(self, didSelectItemAt: index)
}
}
extension TabmanBar: TabmanIndicatorDelegate {
func indicator(requiresLayoutInvalidation indicator: TabmanIndicator) {
self.invalidateIntrinsicContentSize()
self.setNeedsLayout()
self.layoutIfNeeded()
}
}
internal extension TabmanIndicator.Style {
var rawType: TabmanIndicator.Type? {
switch self {
case .line:
return TabmanLineIndicator.self
case .dot:
return TabmanDotIndicator.self
case .chevron:
return TabmanChevronIndicator.self
case .custom(let type):
return type
case .clear:
return TabmanClearIndicator.self
}
}
}
| mit |
aschwaighofer/swift | stdlib/public/Windows/WinSDK.swift | 1 | 6333 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
@_exported import WinSDK // Clang module
// WinBase.h
public let HANDLE_FLAG_INHERIT: DWORD = 0x00000001
// WinBase.h
public let STARTF_USESTDHANDLES: DWORD = 0x00000100
// WinBase.h
public let INFINITE: DWORD = DWORD(bitPattern: -1)
// WinBase.h
public let WAIT_OBJECT_0: DWORD = 0
// WinBase.h
public let STD_INPUT_HANDLE: DWORD = DWORD(bitPattern: -10)
public let STD_OUTPUT_HANDLE: DWORD = DWORD(bitPattern: -11)
public let STD_ERROR_HANDLE: DWORD = DWORD(bitPattern: -12)
// handleapi.h
public let INVALID_HANDLE_VALUE: HANDLE = HANDLE(bitPattern: -1)!
// shellapi.h
public let FOF_NO_UI: FILEOP_FLAGS =
FILEOP_FLAGS(FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR)
// winioctl.h
public let FSCTL_SET_REPARSE_POINT: DWORD = 0x900a4
public let FSCTL_GET_REPARSE_POINT: DWORD = 0x900a8
public let FSCTL_DELETE_REPARSE_POINT: DWORD = 0x900ac
// WinSock2.h
public let INVALID_SOCKET: SOCKET = SOCKET(bitPattern: -1)
public let FIONBIO: Int32 = Int32(bitPattern: 0x8004667e)
// WinUser.h
public let CW_USEDEFAULT: Int32 = Int32(truncatingIfNeeded: 2147483648)
public let WS_OVERLAPPEDWINDOW: UINT =
UINT(WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX)
public let WS_POPUPWINDOW: UINT =
UINT(Int32(WS_POPUP) | WS_BORDER | WS_SYSMENU)
// fileapi.h
public let INVALID_FILE_ATTRIBUTES: DWORD = DWORD(bitPattern: -1)
// CommCtrl.h
public let WC_BUTTONW: [WCHAR] = Array<WCHAR>("Button".utf16)
public let WC_COMBOBOXW: [WCHAR] = Array<WCHAR>("ComboBox".utf16)
public let WC_EDITW: [WCHAR] = Array<WCHAR>("Edit".utf16)
public let WC_HEADERW: [WCHAR] = Array<WCHAR>("SysHeader32".utf16)
public let WC_LISTBOXW: [WCHAR] = Array<WCHAR>("ListBox".utf16)
public let WC_LISTVIEWW: [WCHAR] = Array<WCHAR>("SysListView32".utf16)
public let WC_SCROLLBARW: [WCHAR] = Array<WCHAR>("ScrollBar".utf16)
public let WC_STATICW: [WCHAR] = Array<WCHAR>("Static".utf16)
public let WC_TABCONTROLW: [WCHAR] = Array<WCHAR>("SysTabControl32".utf16)
public let WC_TREEVIEWW: [WCHAR] = Array<WCHAR>("SysTreeView32".utf16)
public let ANIMATE_CLASSW: [WCHAR] = Array<WCHAR>("SysAnimate32".utf16)
public let HOTKEY_CLASSW: [WCHAR] = Array<WCHAR>("msctls_hotkey32".utf16)
public let PROGRESS_CLASSW: [WCHAR] = Array<WCHAR>("msctls_progress32".utf16)
public let STATUSCLASSNAMEW: [WCHAR] = Array<WCHAR>("msctls_statusbar32".utf16)
public let TOOLBARW_CLASSW: [WCHAR] = Array<WCHAR>("ToolbarWindow32".utf16)
public let TRACKBAR_CLASSW: [WCHAR] = Array<WCHAR>("msctls_trackbar32".utf16)
public let UPDOWN_CLASSW: [WCHAR] = Array<WCHAR>("msctls_updown32".utf16)
// consoleapi.h
public let PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE: DWORD_PTR = 0x00020016
// windef.h
public let DPI_AWARENESS_CONTEXT_UNAWARE: DPI_AWARENESS_CONTEXT =
DPI_AWARENESS_CONTEXT(bitPattern: -1)!
public let DPI_AWARENESS_CONTEXT_SYSTEM_AWARE: DPI_AWARENESS_CONTEXT =
DPI_AWARENESS_CONTEXT(bitPattern: -2)!
public let DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE: DPI_AWARENESS_CONTEXT =
DPI_AWARENESS_CONTEXT(bitPattern: -3)!
public let DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2: DPI_AWARENESS_CONTEXT =
DPI_AWARENESS_CONTEXT(bitPattern: -4)!
public let DPI_AWARENESS_CONTEXT_UNAWARE_GDISCALED: DPI_AWARENESS_CONTEXT =
DPI_AWARENESS_CONTEXT(bitPattern: -5)!
// winreg.h
public let HKEY_CLASSES_ROOT: HKEY = HKEY(bitPattern: 0x80000000)!
public let HKEY_CURRENT_USER: HKEY = HKEY(bitPattern: 0x80000001)!
public let HKEY_LOCAL_MACHINE: HKEY = HKEY(bitPattern: 0x80000002)!
public let HKEY_USERS: HKEY = HKEY(bitPattern: 0x80000003)!
public let HKEY_PERFORMANCE_DATA: HKEY = HKEY(bitPattern: 0x80000004)!
public let HKEY_PERFORMANCE_TEXT: HKEY = HKEY(bitPattern: 0x80000050)!
public let HKEY_PERFORMANCE_NLSTEXT: HKEY = HKEY(bitPattern: 0x80000060)!
public let HKEY_CURRENT_CONFIG: HKEY = HKEY(bitPattern: 0x80000005)!
public let HKEY_DYN_DATA: HKEY = HKEY(bitPattern: 0x80000006)!
public let HKEY_CURRENT_USER_LOCAL_SETTINGS: HKEY = HKEY(bitPattern: 0x80000007)!
// Swift Convenience
public extension FILETIME {
var time_t: time_t {
let NTTime: Int64 = Int64(self.dwLowDateTime) | (Int64(self.dwHighDateTime) << 32)
return (NTTime - 116444736000000000) / 10000000
}
init(from time: time_t) {
let UNIXTime: Int64 = ((time * 10000000) + 116444736000000000)
self = FILETIME(dwLowDateTime: DWORD(UNIXTime & 0xffffffff),
dwHighDateTime: DWORD((UNIXTime >> 32) & 0xffffffff))
}
}
// WindowsBool
/// The `BOOL` type declared in WinDefs.h and used throughout WinSDK
///
/// The C type is a typedef for `int`.
@frozen
public struct WindowsBool : ExpressibleByBooleanLiteral {
@usableFromInline
var _value: Int32
/// The value of `self`, expressed as a `Bool`.
@_transparent
public var boolValue: Bool {
return !(_value == 0)
}
@_transparent
public init(booleanLiteral value: Bool) {
self.init(value)
}
/// Create an instance initialized to `value`.
@_transparent
public init(_ value: Bool) {
self._value = value ? 1 : 0
}
}
extension WindowsBool : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: boolValue)
}
}
extension WindowsBool : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return self.boolValue.description
}
}
extension WindowsBool : Equatable {
@_transparent
public static func ==(lhs: WindowsBool, rhs: WindowsBool) -> Bool {
return lhs.boolValue == rhs.boolValue
}
}
@_transparent
public // COMPILER_INTRINSIC
func _convertBoolToWindowsBool(_ b: Bool) -> WindowsBool {
return WindowsBool(b)
}
@_transparent
public // COMPILER_INTRINSIC
func _convertWindowsBoolToBool(_ b: WindowsBool) -> Bool {
return b.boolValue
}
| apache-2.0 |
xwu/swift | validation-test/Sema/SwiftUI/rdar57201781.swift | 11 | 622 | // RUN: %target-typecheck-verify-swift -target x86_64-apple-macosx10.15 -swift-version 5
// REQUIRES: rdar66110075
// REQUIRES: objc_interop
// REQUIRES: OS=macosx
import SwiftUI
struct ContentView : View {
@State var foo: [String] = Array(repeating: "", count: 5)
var body: some View {
VStack { // expected-error{{type of expression is ambiguous without more context}}
HStack {
Text("")
TextFi // expected-error {{cannot find 'TextFi' in scope}}
}
ForEach(0 ... 4, id: \.self) { i in
HStack {
TextField("", text: self.$foo[i])
}
}
}
}
}
| apache-2.0 |
mmoaay/MBNetwork | Bamboots/Classes/Core/Request/Request.swift | 1 | 3877 | //
// Requester.swift
// Pods
//
// Created by Perry on 16/7/6.
//
//
import UIKit
import Alamofire
import AlamofireCodable
public extension Requestable {
/// Creates a `DataRequest` from the specified `form`
///
/// - Parameter form: Object conforms to `RequestFormable` protocol.
/// - Returns: The created `DataRequest`.
@discardableResult
func request(_ form: RequestFormable) -> DataRequest {
return Alamofire.request(
form.url,
method: form.method,
parameters: form.parameters(),
encoding: form.encoding(),
headers: form.headers()
)
}
/// Creates a `DownloadRequest` from the specified `form`
///
/// - Parameter form: Object conforms to `DownloadFormable` protocol.
/// - Returns: The created `DownloadRequest`.
@discardableResult
func download(_ form: DownloadFormable) -> DownloadRequest {
return Alamofire.download(
form.url,
method: form.method,
parameters: form.parameters(),
encoding: form.encoding(),
headers: form.headers(),
to: form.destination
)
}
/// Creates a `DownloadRequest` from the specified `form`
///
/// - Parameter form: Object conforms to `DownloadResumeFormable` protocol.
/// - Returns: The created `DownloadRequest`.
@discardableResult
func download(_ form: DownloadResumeFormable) -> DownloadRequest {
return Alamofire.download(resumingWith: form.resumeData, to: form.destination)
}
/// Creates an `UploadRequest` from the specified `form`
///
/// - Parameter form: Object conforms to `UploadDataFormable` protocol.
/// - Returns: The created `DownloadRequest`.
@discardableResult
func upload(_ form: UploadDataFormable) -> UploadRequest {
return Alamofire.upload(form.data, to: form.url, method: form.method, headers: form.headers())
}
/// Creates an `UploadRequest` from the specified `form`
///
/// - Parameter form: Object conforms to `UploadFileFormable` protocol.
/// - Returns: The created `DownloadRequest`.
@discardableResult
func upload(_ form: UploadFileFormable) -> UploadRequest {
return Alamofire.upload(form.fileURL, to: form.url, method: form.method, headers: form.headers())
}
/// Encodes `form` and calls `completion` with new `UploadRequest` using the `form`
///
/// - Parameters:
/// - form: Object conforms to `UploadMultiFormDataFormable` protocol.
/// - completion: The closure called when the upload is complete
func upload(_ form: UploadMultiFormDataFormable, completion: ((UploadRequest) -> Void)?) {
Alamofire.upload(
multipartFormData: form.multipartFormData,
usingThreshold: form.encodingMemoryThreshold,
to: form.url,
method: form.method,
headers: form.headers(),
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
completion?(upload)
break
case .failure(let encodingError):
print(encodingError)
break
}
}
)
}
/// Creates an `UploadRequest` from the specified `form`
///
/// - Parameter form: Object conforms to `UploadStreamFormable` protocol.
/// - Returns: The created `DownloadRequest`.
@discardableResult
func upload(_ form: UploadStreamFormable) -> UploadRequest {
return Alamofire.upload(form.stream, to: form.url, method: form.method, headers: form.headers())
}
}
/// Network request protocol, object conforms to this protocol can make network request
public protocol Requestable: class {
}
| mit |
brightdigit/speculid | frameworks/speculid/Controllers/Application.swift | 1 | 7860 | import AppKit
import Foundation
import SwiftVer
extension OperatingSystemVersion {
var fullDescription: String {
[majorVersion, minorVersion, patchVersion].map {
String(describing: $0)
}.joined(separator: ".")
}
}
var exceptionHandler: ((NSException) -> Void)?
func exceptionHandlerMethod(exception: NSException) {
if let handler = exceptionHandler {
handler(exception)
}
}
public typealias RegularExpressionArgumentSet = (String, options: NSRegularExpression.Options)
open class Application: NSApplication, ApplicationProtocol {
public func withInstaller(_ completed: (Result<InstallerProtocol>) -> Void) {
installerObjectInterfaceProvider.remoteObjectProxyWithHandler(completed)
}
public func documents(url: URL) throws -> [SpeculidDocumentProtocol] {
var isDirectory: ObjCBool = false
let exists = FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory)
if exists, isDirectory.boolValue == true {
guard let enumerator = FileManager.default.enumerator(at: url, includingPropertiesForKeys: nil) else {
throw InvalidDocumentURL(url: url)
}
return enumerator.compactMap { (item) -> SpeculidDocument? in
guard let url = item as? URL else {
return nil
}
return try? SpeculidDocument(url: url, decoder: jsonDecoder, configuration: configuration)
}
} else {
return [try SpeculidDocument(url: url, decoder: jsonDecoder, configuration: configuration)]
}
}
public static var current: ApplicationProtocol! {
NSApplication.shared as? ApplicationProtocol
}
public static let unknownCommandMessagePrefix = "Unknown Command Arguments"
public static func unknownCommandMessage(fromArguments arguments: [String]) -> String {
"\(unknownCommandMessagePrefix): \(arguments.joined(separator: " "))"
}
public static let helpText: String! = {
guard let url = Application.bundle.url(forResource: "help", withExtension: "txt") else {
return nil
}
guard let format = try? String(contentsOf: url) else {
return nil
}
let text: String
if let sourceApplicationName = ProcessInfo.processInfo.environment["sourceApplicationName"] ?? Bundle.main.executableURL?.lastPathComponent {
text = format.replacingOccurrences(of: "$ speculid", with: "$ " + sourceApplicationName)
} else {
text = format
}
return text
}()
open private(set) var commandLineActivity: CommandLineActivityProtocol?
open private(set) var statusItem: NSStatusItem?
open private(set) var service: ServiceProtocol!
open private(set) var installer: InstallerProtocol!
open private(set) var regularExpressions: RegularExpressionSetProtocol!
open private(set) var tracker: AnalyticsTrackerProtocol!
open private(set) var configuration: SpeculidConfigurationProtocol!
open private(set) var builder: SpeculidBuilderProtocol!
public let statusItemProvider: StatusItemProviderProtocol
public let remoteObjectInterfaceProvider: RemoteObjectInterfaceProviderProtocol
public let installerObjectInterfaceProvider: InstallerObjectInterfaceProviderProtocol
public let regularExpressionBuilder: RegularExpressionSetBuilderProtocol
public let configurationBuilder: SpeculidConfigurationBuilderProtocol
public let jsonDecoder: JSONDecoder
public let imageSpecificationBuilder: SpeculidImageSpecificationBuilderProtocol
open var commandLineRunner: CommandLineRunnerProtocol
public override init() {
statusItemProvider = StatusItemProvider()
remoteObjectInterfaceProvider = RemoteObjectInterfaceProvider()
installerObjectInterfaceProvider = InstallerObjectInterfaceProvider()
regularExpressionBuilder = RegularExpressionSetBuilder()
configurationBuilder = SpeculidConfigurationBuilder()
jsonDecoder = JSONDecoder()
imageSpecificationBuilder = SpeculidImageSpecificationBuilder()
commandLineRunner = CommandLineRunner(
outputStream: FileHandle.standardOutput,
errorStream: FileHandle.standardError
)
super.init()
}
public required init?(coder: NSCoder) {
statusItemProvider = StatusItemProvider()
remoteObjectInterfaceProvider = RemoteObjectInterfaceProvider()
installerObjectInterfaceProvider = InstallerObjectInterfaceProvider()
regularExpressionBuilder = RegularExpressionSetBuilder()
configurationBuilder = SpeculidConfigurationBuilder(coder: coder)
jsonDecoder = JSONDecoder()
imageSpecificationBuilder = SpeculidImageSpecificationBuilder()
commandLineRunner = CommandLineRunner(
outputStream: FileHandle.standardOutput,
errorStream: FileHandle.standardError
)
super.init(coder: coder)
}
open override func finishLaunching() {
super.finishLaunching()
configuration = configurationBuilder.configuration(fromCommandLine: CommandLineArgumentProvider())
let operatingSystem = ProcessInfo.processInfo.operatingSystemVersion.fullDescription
let applicationVersion: String
if let version = self.version {
applicationVersion = (try? version.fullDescription(withLocale: nil)) ?? ""
} else {
applicationVersion = ""
}
let analyticsConfiguration = AnalyticsConfiguration(
trackingIdentifier: "UA-33667276-6",
applicationName: "speculid",
applicationVersion: applicationVersion,
customParameters: [.operatingSystemVersion: operatingSystem, .model: Sysctl.model]
)
remoteObjectInterfaceProvider.remoteObjectProxyWithHandler { result in
switch result {
case let .error(error):
preconditionFailure("Could not connect to XPS Service: \(error)")
case let .success(service):
self.service = service
}
}
builder = SpeculidBuilder(tracker: self.tracker, configuration: configuration, imageSpecificationBuilder: imageSpecificationBuilder)
let tracker = AnalyticsTracker(configuration: analyticsConfiguration, sessionManager: AnalyticsSessionManager())
NSSetUncaughtExceptionHandler(exceptionHandlerMethod)
exceptionHandler = tracker.track
tracker.track(event: AnalyticsEvent(category: "main", action: "launch", label: "application"))
self.tracker = tracker
do {
regularExpressions = try regularExpressionBuilder.buildRegularExpressions(fromDictionary: [
.geometry: ("x?(\\d+)", options: [.caseInsensitive]),
.integer: ("\\d+", options: []),
.scale: ("(\\d+)x", options: []),
.size: ("(\\d+\\.?\\d*)x(\\d+\\.?\\d*)", options: []),
.number: ("\\d", options: [])
])
} catch {
assertionFailure("Failed to parse regular expression: \(error)")
}
if case let .command(arguments) = configuration.mode {
let commandLineActivity = self.commandLineRunner.activity(withArguments: arguments, self.commandLineActivity(_:hasCompletedWithError:))
self.commandLineActivity = commandLineActivity
commandLineActivity.start()
return
}
statusItem = statusItemProvider.statusItem(for: self)
}
public func commandLineActivity(_: CommandLineActivityProtocol, hasCompletedWithError error: Error?) {
if let error = error {
FileHandle.standardError.write(error.localizedDescription)
exit(1)
} else {
exit(0)
}
}
public func quit(_ sender: Any?) {
terminate(sender)
}
public static var author: String {
bundle.bundleIdentifier!.components(separatedBy: "-").first!
}
public static let bundle = Bundle(for: Application.self)
public static let vcs = VersionControlInfo(jsonResource: "autorevision", fromBundle: Application.bundle)
public static let sbd =
Stage.dictionary(fromPlistAtURL: Application.bundle.url(forResource: "versions", withExtension: "plist")!)!
public let version = Version(
bundle: bundle,
dictionary: sbd,
versionControl: vcs
)
}
| mit |
radex/swift-compiler-crashes | crashes-fuzzing/01400-swift-inflightdiagnostic.swift | 11 | 250 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
{
}
let a{
func e{
{
}
return[T->{
{
"""
}
}
}
protocol d{
func b typealias e:b | mit |
prebid/prebid-mobile-ios | PrebidMobileTests/RenderingTests/Tests/Prebid/BidTest.swift | 1 | 1498 | /* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
@testable import PrebidMobile
class BidTest: XCTestCase {
override func tearDown() {
super.tearDown()
Prebid.reset()
}
// Rendering API doesn't require cache id by default.
// But publisher can set useCacheForReportingWithRenderingAPI to true
// in order to add hb_cache_id to winning bid markers.
func testWinningBidRendering() {
let rawBid = RawWinningBidFabricator.makeRawWinningBid(price: 0.75, bidder: "some bidder", cacheID: nil)
let bid = Bid(bid: rawBid)
XCTAssertTrue(bid.isWinning)
}
func testNoWinningBidRendering() {
Prebid.shared.useCacheForReportingWithRenderingAPI = true
let rawBid = RawWinningBidFabricator.makeRawWinningBid(price: 0.75, bidder: "some bidder", cacheID: nil)
let bid = Bid(bid: rawBid)
XCTAssertFalse(bid.isWinning)
}
}
| apache-2.0 |
radex/swift-compiler-crashes | crashes-fuzzing/06975-swift-tupleexpr-create.swift | 11 | 231 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B{
let a=a<b
var b=b<b
protocol A{
typealias e:e
func b | mit |
radex/swift-compiler-crashes | crashes-fuzzing/05536-swift-printingdiagnosticconsumer-handlediagnostic.swift | 11 | 239 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A{
func a(){
class d<T where f:a{
typealias e=e
struct B{
let b{ | mit |
radex/swift-compiler-crashes | crashes-fuzzing/21509-swift-archetypebuilder-resolvearchetype.swift | 11 | 295 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct b<S {
{
}
enum S<d {
struct S<i {
protocol c {
{
}
class B<T where i = T.e {
{
}
}
{
}
{
{
}
}
}
class d<T where i = c
| mit |
acort3255/Emby.ApiClient.Swift | Emby.ApiClient/model/dlna/ResponseProfile.swift | 2 | 724 | //
// ResponseProfile.swift
// EmbyApiClient
//
import Foundation
public struct ResponseProfile {
let container: String?
let audioCodec: String?
let videoCodec: String?
var type = DlnaProfileType.Audio
let orgPn: String?
let mimeType: String?
var conditions = [ProfileCondition]()
var containers: [String] {
get {
return splitToArray(stringToSplit: container, delimiter: ",")
}
}
var audioCodecs: [String] {
get {
return splitToArray(stringToSplit: audioCodec, delimiter: ",")
}
}
var videoCodecs: [String] {
get {
return splitToArray(stringToSplit: videoCodec, delimiter: ",")
}
}
}
| mit |
acort3255/Emby.ApiClient.Swift | Emby.ApiClient/model/PersonsQuery.swift | 1 | 156 | //
// PersonsQuery.swift
// EmbyApiClient
//
//
import Foundation
public class PersonsQuery: ItemsByNameQuery {
public var personTypes: [String]?
}
| mit |
NileshJarad/shopping_cart_ios_swift | ShoppingCartTests/Login/LoginPresenterTest.swift | 1 | 1856 | //
// LoginPresenterTest.swift
// ShoppingCart
//
// Created by Nilesh Jarad on 15/09/16.
// Copyright © 2016 Nilesh Jarad. All rights reserved.
//
import XCTest
@testable import ShoppingCart
class LoginPresenterTest: XCTestCase {
var loginViewMocked : LoginViewMocked!
var loginPresenter : LoginPresenter!
override func setUp() {
super.setUp()
loginViewMocked = LoginViewMocked()
loginPresenter = LoginPresenter(loginView: loginViewMocked)
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testUserNamePasswordWrong() {
loginPresenter.doValidation("N@J", pasword: "J@N")
XCTAssertTrue(loginViewMocked.showErrorMessageCalled)
}
//
func testUserNamePasswordCorrect() {
loginPresenter.doValidation("N@J", pasword: "N@J")
XCTAssertTrue(loginViewMocked.showSuccessMessageCalled)
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
/*
# Mocked View classes
*/
class LoginViewMocked : LoginView{
var showErrorMessageCalled :Bool = false
var showSuccessMessageCalled :Bool = false
func showErrorMessage(errorMessage: String){
self.showErrorMessageCalled = true
}
func showSuccessMessage(success: String){
self.showSuccessMessageCalled = true
}
func intializeViewAndDelegate(){
}
}
}
| lgpl-3.0 |
Mobilette/MobiletteDashboardiOS | MobiletteDashboardIOS/Classes/Modules/Root/RootWireframe.swift | 1 | 1042 | //
// RootWireframe.swift
// MobiletteDashboardIOS
//
// Created by Issouf M'sa Benaly on 9/15/15.
// Copyright (c) 2015 Mobilette. All rights reserved.
//
import UIKit
class RootWireframe
{
// MARK: - Presentation
func presentRootViewController(fromWindow window: UIWindow)
{
// self.present<# Root module name #>ViewController(fromWindow: window)
}
/*
private func present<# Root module name #>ViewController(fromWindow window: UIWindow)
{
let presenter = <# Root module name #>Presenter()
let interactor = <# Root module name #>Interactor()
// let networkController = <# Root module name #>NetworkController()
let wireframe = <# Root module name #>Wireframe()
// interactor.networkController = networkController
interactor.output = presenter
presenter.interactor = interactor
presenter.wireframe = wireframe
wireframe.presenter = presenter
wireframe.presentInterface(fromWindow: window)
}
*/
}
| mit |
xivol/MCS-V3-Mobile | examples/networking/firebase-test/FireAuthWrapper.swift | 1 | 3227 | //
// FireAuthWrapper.swift
// firebase-test
//
// Created by Илья Лошкарёв on 14.11.2017.
// Copyright © 2017 Илья Лошкарёв. All rights reserved.
//
import Firebase
import FirebaseAuthUI
import FirebaseGoogleAuthUI
protocol FireAuthWrapperDelegate: class {
func didChangeAuth(_ auth: FireAuthWrapper, forUser user: User?)
func failed(withError error: Error, onAction action: FireAuthWrapper.Action)
}
class FireAuthWrapper: NSObject, FUIAuthDelegate {
private var didChangeAuthHandle: AuthStateDidChangeListenerHandle!
public weak var delegate: FireAuthWrapperDelegate? {
didSet {
guard let delegate = delegate else {
auth.removeStateDidChangeListener(didChangeAuthHandle)
return
}
didChangeAuthHandle = auth.addStateDidChangeListener {
(auth, user) in
delegate.didChangeAuth(self, forUser: user)
}
}
}
private let auth = Auth.auth()
public let ui = FUIAuth.defaultAuthUI()!
public var signInController: UIViewController {
let authVC = ui.authViewController()
// remove cancel button
authVC.navigationBar.items?[0].leftBarButtonItems = nil
return authVC
}
public var currentUser: User? {
return auth.currentUser
}
public var isSignedIn: Bool {
return currentUser != nil
}
public override init() {
super.init()
ui.providers = [FUIGoogleAuth()]
}
deinit {
if delegate != nil {
auth.removeStateDidChangeListener(didChangeAuthHandle)
}
}
public enum Action: String {
case register, signIn, signOut, passwordReset
}
public func register(withEmail email: String, password: String) {
auth.createUser(withEmail: email, password: password) {
[weak self] (usr, error) in
guard let error = error else {return}
self?.delegate?.failed(withError: error, onAction: .register)
}
}
public func signIn(withEmail email: String, password: String) {
auth.signIn(withEmail: email, password: password) {
[weak self] (usr, error) in
guard let error = error else {return}
self?.delegate?.failed(withError: error, onAction: .signIn)
}
}
public func signOut() {
print("signing out")
do { try auth.signOut() }
catch let error as NSError {
delegate?.failed(withError: error, onAction: .signOut)
}
}
public func passwordReset(forEmail email: String) {
auth.sendPasswordReset(withEmail: email) {
[weak self] (error) in
guard let error = error else {return}
self?.delegate?.failed(withError: error, onAction: .passwordReset)
}
}
func authUI(_ authUI: FUIAuth, didSignInWith user: User?, error: Error?) {
guard let _ = user else {
delegate?.failed(withError: error!, onAction: .signIn)
return
}
//delegate?.didChangeAuth(self, forUser: user)
}
}
| mit |
jwolkovitzs/AMScrollingNavbar | Source/ScrollingNavbar+Sizes.swift | 1 | 2161 | import UIKit
import WebKit
/**
Implements the main functions providing constants values and computed ones
*/
extension ScrollingNavigationController {
// MARK: - View sizing
var fullNavbarHeight: CGFloat {
return navbarHeight + statusBarHeight
}
var navbarHeight: CGFloat {
return navigationBar.frame.size.height
}
var statusBarHeight: CGFloat {
var statusBarHeight = UIApplication.shared.statusBarFrame.size.height
if #available(iOS 11.0, *) {
// Account for the notch when the status bar is hidden
statusBarHeight = max(UIApplication.shared.statusBarFrame.size.height, UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0)
}
return max(statusBarHeight - extendedStatusBarDifference, 0)
}
// Extended status call changes the bounds of the presented view
var extendedStatusBarDifference: CGFloat {
return abs(view.bounds.height - (UIApplication.shared.delegate?.window??.frame.size.height ?? UIScreen.main.bounds.height))
}
var tabBarOffset: CGFloat {
// Only account for the tab bar if a tab bar controller is present and the bar is not translucent
if let tabBarController = tabBarController, !(topViewController?.hidesBottomBarWhenPushed ?? false) {
return tabBarController.tabBar.isTranslucent ? 0 : tabBarController.tabBar.frame.height
}
return 0
}
func scrollView() -> UIScrollView? {
if let webView = self.scrollableView as? UIWebView {
return webView.scrollView
} else if let wkWebView = self.scrollableView as? WKWebView {
return wkWebView.scrollView
} else {
return scrollableView as? UIScrollView
}
}
var contentOffset: CGPoint {
return scrollView()?.contentOffset ?? CGPoint.zero
}
var contentSize: CGSize {
guard let scrollView = scrollView() else {
return CGSize.zero
}
let verticalInset = scrollView.contentInset.top + scrollView.contentInset.bottom
return CGSize(width: scrollView.contentSize.width, height: scrollView.contentSize.height + verticalInset)
}
var navbarFullHeight: CGFloat {
return navbarHeight - statusBarHeight
}
}
| mit |
EZ-NET/CodePiece | XcodeSourceEditorExtension/OpenCodePieceCommand.swift | 1 | 915 | //
// SendToCodePieceCommand.swift
// XcodeSourceEditorExtension
//
// Created by Tomohiro Kumagai on 2020/02/21.
// Copyright © 2020 Tomohiro Kumagai. All rights reserved.
//
import AppKit
import XcodeKit
class OpenCodePieceCommand: NSObject, XCSourceEditorCommand {
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void {
let scheme = CodePieceUrlScheme(method: "open")
guard let url = URL(scheme) else {
completionHandler(NSError(.failedToOpenCodePiece("Failed to create URL scheme for CodePiece.")))
return
}
NSLog("Try opening CodePiece app using URL scheme: %@", url.absoluteString)
switch NSWorkspace.shared.open(url) {
case true:
completionHandler(nil)
case false:
completionHandler(NSError(.failedToOpenCodePiece("Failed to open CodePiece (\(url.absoluteString))")))
}
}
}
| gpl-3.0 |
connienguyen/volunteers-iOS | VOLA/VOLATests/DataManagerUnitTests.swift | 1 | 1778 | //
// DataManagerUnitTests.swift
// VOLA
//
// Created by Connie Nguyen on 6/13/17.
// Copyright © 2017 Systers-Opensource. All rights reserved.
//
import XCTest
@testable import VOLA
class DataManagerUnitTests: XCTestCase {
let user = User(uid: InputConstants.userUID, firstName: SplitNameConstants.standardFirstName, lastName: SplitNameConstants.standardLastName, email: InputConstants.validEmail)
override func setUp() {
super.setUp()
DataManager.shared.setUserUpdateStoredUser(nil)
}
func testSuccessUserSetNilShouldReturnFalse() {
let notLoggedIn = DataManager.shared.isLoggedIn
XCTAssertFalse(notLoggedIn, "Start state: user should not be logged in.")
}
func testSuccessSetUserShouldReturnTrue() {
DataManager.shared.setUserUpdateStoredUser(self.user)
let loggedIn = DataManager.shared.isLoggedIn
XCTAssertTrue(loggedIn, "User should be logged in after setting user.")
}
func testSuccessSetUserShouldReturnMatchingCurrentUser() {
var currentUser = DataManager.shared.currentUser
XCTAssertNil(currentUser, "Start state: no currentUser since no user is logged in.")
DataManager.shared.setUserUpdateStoredUser(self.user)
currentUser = DataManager.shared.currentUser
XCTAssertNotNil(currentUser, "Current user model should be updated to new user.")
XCTAssertEqual(currentUser?.firstName, self.user.firstName)
XCTAssertEqual(currentUser?.lastName, self.user.lastName)
XCTAssertEqual(currentUser?.email, self.user.email)
DataManager.shared.setUserUpdateStoredUser(nil)
currentUser = DataManager.shared.currentUser
XCTAssertNil(currentUser, "Current user should be unset to nil.")
}
}
| gpl-2.0 |
BLVudu/SkyFloatingLabelTextField | SkyFloatingLabelTextField/SkyFloatingLabelTextFieldExample/Example4/IconTextField.swift | 1 | 3277 | // Copyright 2016 Skyscanner 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 UIKit
@IBDesignable
public class IconTextField: SkyFloatingLabelTextField {
public var iconLabel:UILabel!
public var iconWidth:CGFloat = 25.0
@IBInspectable
public var icon:String? {
didSet {
self.iconLabel?.text = icon
}
}
// MARK: Initializers
override public init(frame: CGRect) {
super.init(frame: frame)
self.createIconLabel()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.createIconLabel()
}
// MARK: Creating the icon label
func createIconLabel() {
let iconLabel = UILabel()
iconLabel.backgroundColor = UIColor.clearColor()
iconLabel.textAlignment = .Center
iconLabel.autoresizingMask = [.FlexibleTopMargin, .FlexibleRightMargin]
self.iconLabel = iconLabel
self.addSubview(iconLabel)
self.updateIconLabelColor()
}
// MARK: Handling the icon color
override public func updateColors() {
super.updateColors()
self.updateIconLabelColor()
}
private func updateIconLabelColor() {
if self.hasErrorMessage {
self.iconLabel?.textColor = self.errorColor
} else {
self.iconLabel?.textColor = self.editing ? self.selectedLineColor : self.lineColor
}
}
// MARK: Custom layout overrides
override public func textRectForBounds(bounds: CGRect) -> CGRect {
var rect = super.textRectForBounds(bounds)
if (isLTRLanguage) {
rect.origin.x += iconWidth
} else {
rect.origin.x = 0
}
rect.size.width -= iconWidth
return rect
}
override public func editingRectForBounds(bounds: CGRect) -> CGRect {
var rect = super.textRectForBounds(bounds)
rect.origin.x += iconWidth - iconWidth
rect.size.width -= iconWidth
return rect
}
override public func placeholderRectForBounds(bounds: CGRect) -> CGRect {
var rect = super.placeholderRectForBounds(bounds)
rect.origin.x += iconWidth
rect.size.width -= iconWidth
return rect
}
override public func layoutSubviews() {
super.layoutSubviews()
let textHeight = self.textHeight()
let textWidth:CGFloat = self.bounds.size.width
if (isLTRLanguage) {
self.iconLabel.frame = CGRectMake(0, self.bounds.size.height - textHeight, iconWidth, textHeight)
} else {
self.iconLabel.frame = CGRectMake(textWidth - iconWidth, self.bounds.size.height - textHeight, iconWidth, textHeight)
}
}
}
| apache-2.0 |
victorpimentel/SwiftLint | Source/SwiftLintFramework/Rules/ProtocolPropertyAccessorsOrderRule.swift | 2 | 2523 | //
// ProtocolPropertyAccessorsOrderRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 15/05/17.
// Copyright © 2017 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct ProtocolPropertyAccessorsOrderRule: ConfigurationProviderRule, CorrectableRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "protocol_property_accessors_order",
name: "Protocol Property Accessors Order",
description: "When declaring properties in protocols, the order of accessors should be `get set`.",
nonTriggeringExamples: [
"protocol Foo {\n var bar: String { get set }\n }",
"protocol Foo {\n var bar: String { get }\n }",
"protocol Foo {\n var bar: String { set }\n }"
],
triggeringExamples: [
"protocol Foo {\n var bar: String { ↓set get }\n }"
],
corrections: [
"protocol Foo {\n var bar: String { ↓set get }\n }":
"protocol Foo {\n var bar: String { get set }\n }"
]
)
public func validate(file: File) -> [StyleViolation] {
return violationRanges(file: file).map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
private func violationRanges(file: File) -> [NSRange] {
return file.match(pattern: "\\bset\\s*get\\b", with: [.keyword, .keyword])
}
public func correct(file: File) -> [Correction] {
let violatingRanges = file.ruleEnabled(violatingRanges: violationRanges(file: file), for: self)
var correctedContents = file.contents
var adjustedLocations = [Int]()
for violatingRange in violatingRanges.reversed() {
if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) {
correctedContents = correctedContents
.replacingCharacters(in: indexRange, with: "get set")
adjustedLocations.insert(violatingRange.location, at: 0)
}
}
file.write(correctedContents)
return adjustedLocations.map {
Correction(ruleDescription: type(of: self).description,
location: Location(file: file, characterOffset: $0))
}
}
}
| mit |
githubError/KaraNotes | KaraNotes/KaraNotes/MyArticle/Model/CPFMyArticleModel.swift | 1 | 2726 | //
// CPFMyArticleModel.swift
// KaraNotes
//
// Created by 崔鹏飞 on 2017/4/19.
// Copyright © 2017年 崔鹏飞. All rights reserved.
//
import Foundation
struct CPFMyArticleModel {
var abstract_content:String
var article_attachment:String
var article_create_time:TimeInterval
var article_id:String
var article_show_img:String
var article_title:String
var article_update_time:UInt16
var classify_id:String
var collect_num:Int
var comment_num:Int
var praise_num:Int
var user_id:String
var article_create_formatTime:String {
return timestampToString(timestamp: article_create_time)
}
var article_show_img_URL:URL {
return URL(string: article_show_img)!
}
}
extension CPFMyArticleModel {
static func parse(json: JSONDictionary) -> CPFMyArticleModel {
guard let abstract_content = json["abstract_content"] as? String else {fatalError("解析CPFMyArticleModel出错")}
guard let article_attachment = json["article_attachment"] as? String else {fatalError("解析CPFMyArticleModel出错")}
guard let article_create_time = json["article_create_time"] as? TimeInterval else {fatalError("解析CPFMyArticleModel出错")}
guard let article_id = json["article_id"] as? String else {fatalError("解析CPFMyArticleModel出错")}
guard let article_show_img = json["article_show_img"] as? String else {fatalError("解析CPFMyArticleModel出错")}
guard let article_title = json["article_title"] as? String else {fatalError("解析CPFMyArticleModel出错")}
guard let article_update_time = json["article_update_time"] as? UInt16 else {fatalError("解析CPFMyArticleModel出错")}
guard let classify_id = json["classify_id"] as? String else {fatalError("解析CPFMyArticleModel出错")}
guard let collect_num = json["collect_num"] as? Int else {fatalError("解析CPFMyArticleModel出错")}
guard let comment_num = json["comment_num"] as? Int else {fatalError("解析CPFMyArticleModel出错")}
guard let praise_num = json["praise_num"] as? Int else {fatalError("解析CPFMyArticleModel出错")}
guard let user_id = json["user_id"] as? String else {fatalError("解析CPFMyArticleModel出错")}
return CPFMyArticleModel(abstract_content: abstract_content, article_attachment: article_attachment, article_create_time: article_create_time, article_id: article_id, article_show_img: article_show_img, article_title: article_title, article_update_time: article_update_time, classify_id: classify_id, collect_num: collect_num, comment_num: comment_num, praise_num: praise_num, user_id: user_id)
}
}
| apache-2.0 |
nheagy/WordPress-iOS | WordPress/Classes/System/3DTouch/WP3DTouchShortcutCreator.swift | 1 | 7164 | import UIKit
public class WP3DTouchShortcutCreator: NSObject
{
enum LoggedIn3DTouchShortcutIndex: Int {
case Notifications = 0,
Stats,
NewPhotoPost,
NewPost
}
var application: UIApplication!
var mainContext: NSManagedObjectContext!
var blogService: BlogService!
private let logInShortcutIconImageName = "icon-shortcut-signin"
private let notificationsShortcutIconImageName = "icon-shortcut-notifications"
private let statsShortcutIconImageName = "icon-shortcut-stats"
private let newPhotoPostShortcutIconImageName = "icon-shortcut-new-photo"
private let newPostShortcutIconImageName = "icon-shortcut-new-post"
override public init() {
super.init()
application = UIApplication.sharedApplication()
mainContext = ContextManager.sharedInstance().mainContext
blogService = BlogService(managedObjectContext: mainContext)
}
public func createShortcutsIf3DTouchAvailable(loggedIn: Bool) {
if !is3DTouchAvailable() {
return
}
if loggedIn {
if hasBlog() {
createLoggedInShortcuts()
} else {
clearShortcuts()
}
} else {
createLoggedOutShortcuts()
}
}
private func loggedOutShortcutArray() -> [UIApplicationShortcutItem] {
let logInShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.LogIn.type,
localizedTitle: NSLocalizedString("Sign In", comment: "Sign In 3D Touch Shortcut"),
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: logInShortcutIconImageName),
userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.LogIn.rawValue])
return [logInShortcut]
}
private func loggedInShortcutArray() -> [UIApplicationShortcutItem] {
var defaultBlogName: String?
if blogService.blogCountForAllAccounts() > 1 {
defaultBlogName = blogService.lastUsedOrFirstBlog()?.settings?.name
}
let notificationsShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.Notifications.type,
localizedTitle: NSLocalizedString("Notifications", comment: "Notifications 3D Touch Shortcut"),
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: notificationsShortcutIconImageName),
userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.Notifications.rawValue])
let statsShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.Stats.type,
localizedTitle: NSLocalizedString("Stats", comment: "Stats 3D Touch Shortcut"),
localizedSubtitle: defaultBlogName,
icon: UIApplicationShortcutIcon(templateImageName: statsShortcutIconImageName),
userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.Stats.rawValue])
let newPhotoPostShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPhotoPost.type,
localizedTitle: NSLocalizedString("New Photo Post", comment: "New Photo Post 3D Touch Shortcut"),
localizedSubtitle: defaultBlogName,
icon: UIApplicationShortcutIcon(templateImageName: newPhotoPostShortcutIconImageName),
userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPhotoPost.rawValue])
let newPostShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPost.type,
localizedTitle: NSLocalizedString("New Post", comment: "New Post 3D Touch Shortcut"),
localizedSubtitle: defaultBlogName,
icon: UIApplicationShortcutIcon(templateImageName: newPostShortcutIconImageName),
userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPost.rawValue])
return [notificationsShortcut, statsShortcut, newPhotoPostShortcut, newPostShortcut]
}
private func createLoggedInShortcuts() {
var entireShortcutArray = loggedInShortcutArray()
var visibleShortcutArray = [UIApplicationShortcutItem]()
if hasWordPressComAccount() {
visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.Notifications.rawValue])
}
if doesCurrentBlogSupportStats() {
visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.Stats.rawValue])
}
visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.NewPhotoPost.rawValue])
visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.NewPost.rawValue])
application.shortcutItems = visibleShortcutArray
}
private func clearShortcuts() {
application.shortcutItems = nil
}
private func createLoggedOutShortcuts() {
application.shortcutItems = loggedOutShortcutArray()
}
private func is3DTouchAvailable() -> Bool {
let window = UIApplication.sharedApplication().keyWindow
return window?.traitCollection.forceTouchCapability == .Available
}
private func hasWordPressComAccount() -> Bool {
let accountService = AccountService(managedObjectContext: mainContext)
return accountService.defaultWordPressComAccount() != nil
}
private func doesCurrentBlogSupportStats() -> Bool {
guard let currentBlog = blogService.lastUsedOrFirstBlog() else {
return false
}
return hasWordPressComAccount() && currentBlog.supports(BlogFeature.Stats)
}
private func hasBlog() -> Bool {
return blogService.blogCountForAllAccounts() > 0
}
}
| gpl-2.0 |
kickstarter/ios-oss | KsApi/models/graphql/adapters/Project.Country+CountryFragment.swift | 1 | 1045 | import Prelude
extension Project.Country {
static func country(from countryFragment: GraphAPI.CountryFragment,
minPledge: Int,
maxPledge: Int,
currency: GraphAPI.CurrencyCode) -> Project.Country? {
guard let countryWithCurrencyDefault = Project.Country.all
.first(where: { $0.countryCode == countryFragment.code.rawValue }) else {
return nil
}
var updatedCountryWithProjectCurrency = countryWithCurrencyDefault
|> Project.Country.lens.minPledge .~ minPledge
|> Project.Country.lens.maxPledge .~ maxPledge
|> Project.Country.lens.currencyCode .~ currency.rawValue
if let matchingCurrencySymbol = Project.Country.all
.first(where: { $0.currencyCode.lowercased() == currency.rawValue.lowercased() })?.currencySymbol {
updatedCountryWithProjectCurrency = updatedCountryWithProjectCurrency
|> Project.Country.lens.currencySymbol .~ matchingCurrencySymbol
}
return updatedCountryWithProjectCurrency
}
}
| apache-2.0 |
Tomikes/jetstream-ios | JetstreamTests/SyncFragmentTests.swift | 3 | 7447 | //
// SyncFragmentTests.swift
// Jetstream
//
// Copyright (c) 2014 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
@testable import Jetstream
class SyncFragmentTests: XCTestCase {
var parent = TestModel()
var child = TestModel()
var scope = Scope(name: "Testing")
override func setUp() {
parent = TestModel()
child = TestModel()
parent.childModel = child
scope = Scope(name: "Testing")
parent.setScopeAndMakeRootModel(scope)
}
override func tearDown() {
super.tearDown()
}
func testSerializationFailure() {
let uuid = NSUUID()
var json: [String: AnyObject] = [
"uuid": child.uuid.UUIDString
]
var fragment = SyncFragment.unserialize(json)
XCTAssertNil(fragment , "Fragment with missing type shouldn't be created")
json = [
"type": "remove",
]
fragment = SyncFragment.unserialize(json)
XCTAssertNil(fragment , "Fragment with missing uuid shouldn't be created")
json = [
"type": "add",
"uuid": uuid.UUIDString,
"properties": ["string": "set correctly"],
]
fragment = SyncFragment.unserialize(json)
XCTAssertNil(fragment , "Add fragment with missing cls property shouldn't be created")
}
func testChange() {
let json: [String: AnyObject] = [
"type": "change",
"uuid": child.uuid.UUIDString,
"clsName": "TestModel",
"properties": ["string": "testing", "integer": 20]
]
let fragment = SyncFragment.unserialize(json)
XCTAssertEqual(fragment!.objectUUID, child.uuid , "UUID unserialized")
XCTAssertEqual(fragment!.objectUUID, child.uuid , "UUID unserialized")
XCTAssertEqual(fragment!.properties!.count, 2 , "Properties unserialized")
fragment?.applyChangesToScope(scope)
XCTAssertEqual(parent.childModel!.string!, "testing" , "Properties applied")
XCTAssertEqual(parent.childModel!.integer, 20 , "Properties applied")
}
func testAdd() {
let uuid = NSUUID()
let json: [String: AnyObject] = [
"type": "add",
"uuid": uuid.UUIDString,
"clsName": "TestModel",
"properties": ["string": "set correctly"]
]
let fragment = SyncFragment.unserialize(json)
let json2: [String: AnyObject] = [
"type": "change",
"uuid": child.uuid.UUIDString,
"clsName": "TestModel",
"properties": ["childModel": uuid.UUIDString],
]
let fragment2 = SyncFragment.unserialize(json2)
XCTAssertEqual(fragment!.objectUUID, uuid , "UUID unserialized")
XCTAssertEqual(fragment!.clsName!, "TestModel" , "Class name unserialized")
scope.applySyncFragments([fragment!, fragment2!])
let testModel = child.childModel!
XCTAssertEqual(child.childModel!, testModel, "Child added")
XCTAssertEqual(testModel.parents[0].parent, child , "Child has correct parent")
XCTAssert(testModel.scope === scope , "Scope set correctly")
XCTAssertEqual(testModel.string!, "set correctly" , "Properties set correctly")
XCTAssertEqual(scope.modelObjects.count, 3 , "Scope knows of added model")
}
func testAddToArray() {
let uuid = NSUUID()
let json: [String: AnyObject] = [
"type": "add",
"uuid": uuid.UUIDString,
"clsName": "TestModel",
"properties": ["string": "set correctly"]
]
let fragment = SyncFragment.unserialize(json)
let json2: [String: AnyObject] = [
"type": "change",
"uuid": child.uuid.UUIDString,
"clsName": "TestModel",
"properties": ["array": [uuid.UUIDString]],
]
let fragment2 = SyncFragment.unserialize(json2)
scope.applySyncFragments([fragment!, fragment2!])
let testModel = child.array[0]
XCTAssertEqual(child.array[0], testModel, "Child added")
XCTAssertEqual(testModel.parents[0].parent, child , "Child has correct parent")
XCTAssert(testModel.scope === scope , "Scope set correctly")
XCTAssertEqual(testModel.string!, "set correctly" , "Properties set correctly")
XCTAssertEqual(scope.modelObjects.count, 3 , "Scope knows of added model")
}
func testNullValues() {
let json: [String: AnyObject] = [
"type": "change",
"uuid": child.uuid.UUIDString,
"clsName": "TestModel",
"properties": [
"array": NSNull(),
"string": NSNull(),
"integer": NSNull(),
"float32": NSNull(),
"int32": NSNull()
],
]
let fragment = SyncFragment.unserialize(json)
child.string = "test"
child.integer = 10
child.float32 = 10.0
child.int32 = 10
scope.applySyncFragments([fragment!])
XCTAssertNil(child.string, "String was nilled out")
XCTAssertEqual(child.integer, 10 , "Nill not applied")
XCTAssertEqual(child.float32, Float(10.0) , "Nil not applied")
XCTAssertEqual(child.int32, Int32(10) , "Nil not applied")
}
func testInvalidValues() {
let json: [String: AnyObject] = [
"type": "change",
"uuid": child.uuid.UUIDString,
"clsName": "TestModel",
"properties": [
"string": 10,
"integer": "5",
"float32": "whatever",
"int32": 5.5
],
]
let fragment = SyncFragment.unserialize(json)
child.string = "test"
child.integer = 10
child.float32 = 10.0
child.int32 = 10
scope.applySyncFragments([fragment!])
XCTAssertNil(child.string, "String nilled out")
XCTAssertEqual(child.integer, 10 , "Invalid property not applied")
XCTAssertEqual(child.float32, Float(10.0) , "Invalid property not applied")
XCTAssertEqual(child.int32, Int32(5) , "Int32 converted")
}
}
| mit |
euajudo/ios | euajudo/View/CampaignCell.swift | 1 | 2529 | //
// CampaignCell.swift
// euajudo
//
// Created by Rafael Kellermann Streit on 4/11/15.
// Copyright (c) 2015 euajudo. All rights reserved.
//
import UIKit
class CampaignCell: UICollectionViewCell {
var campaign: Campaign?
var progressView: CampaignGoalView!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var labelDescription: UILabel!
@IBOutlet weak var playImage: UIImageView!
@IBOutlet weak var userName: UILabel!
override func drawRect(rect: CGRect) {
super.drawRect(rect)
progressView = NSBundle.mainBundle().loadNibNamed("CampaignGoalView", owner: self, options: nil)[0] as! CampaignGoalView
self.containerView.addSubview(progressView)
self.containerView.bringSubviewToFront(progressView.progress)
let frameSize = progressView.frame
progressView.frame = CGRectMake(progressView.frame.origin.x, self.frame.size.height - frameSize.height, self.frame.size.width, frameSize.height)
progressView.setNeedsLayout()
progressView.layoutIfNeeded()
progressView.layoutSubviews()
progressView?.campaign = campaign
self.applyCardPattern()
}
override func layoutSubviews() {
super.layoutSubviews()
self.applyCardPattern()
switch self.campaign!.mainMedia.type {
case .Image:
self.playImage.alpha = 0.0
case .Video:
self.playImage.alpha = 1.0
}
}
func applyCardPattern() {
let shadowPath = UIBezierPath(rect: self.containerView.bounds)
self.layer.masksToBounds = false;
self.layer.shadowColor = UIColor.blackColor().CGColor
self.layer.shadowOffset = CGSizeMake(1.0, 1.0);
self.layer.shadowOpacity = 0.2;
self.layer.shadowPath = shadowPath.CGPath;
self.layer.cornerRadius = 3.0;
self.contentView.layer.cornerRadius = 1.5
self.contentView.clipsToBounds = true
}
func updateInformations() {
labelTitle.text = campaign?.name
labelDescription.text = campaign?.description
userName.text = campaign?.user["name"]!
unowned let weakSelf = self
campaign?.mainMedia.image({ (image) -> Void in
weakSelf.imageView.image = image
})
progressView?.campaign = campaign
}
}
| mit |
radvansky-tomas/NutriFacts | nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Renderers/LineChartRenderer.swift | 6 | 25219 | //
// LineChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics.CGBase
import UIKit.UIFont
@objc
public protocol LineChartRendererDelegate
{
func lineChartRendererData(renderer: LineChartRenderer) -> LineChartData!;
func lineChartRenderer(renderer: LineChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer!;
func lineChartRendererFillFormatter(renderer: LineChartRenderer) -> ChartFillFormatter;
func lineChartDefaultRendererValueFormatter(renderer: LineChartRenderer) -> NSNumberFormatter!;
func lineChartRendererChartYMax(renderer: LineChartRenderer) -> Float;
func lineChartRendererChartYMin(renderer: LineChartRenderer) -> Float;
func lineChartRendererChartXMax(renderer: LineChartRenderer) -> Float;
func lineChartRendererChartXMin(renderer: LineChartRenderer) -> Float;
func lineChartRendererMaxVisibleValueCount(renderer: LineChartRenderer) -> Int;
}
public class LineChartRenderer: ChartDataRendererBase
{
public weak var delegate: LineChartRendererDelegate?;
public init(delegate: LineChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler);
self.delegate = delegate;
}
public override func drawData(#context: CGContext)
{
var lineData = delegate!.lineChartRendererData(self);
if (lineData === nil)
{
return;
}
for (var i = 0; i < lineData.dataSetCount; i++)
{
var set = lineData.getDataSetByIndex(i);
if (set !== nil && set!.isVisible)
{
drawDataSet(context: context, dataSet: set as! LineChartDataSet);
}
}
}
internal struct CGCPoint
{
internal var x: CGFloat = 0.0;
internal var y: CGFloat = 0.0;
/// x-axis distance
internal var dx: CGFloat = 0.0;
/// y-axis distance
internal var dy: CGFloat = 0.0;
internal init(x: CGFloat, y: CGFloat)
{
self.x = x;
self.y = y;
}
}
internal func drawDataSet(#context: CGContext, dataSet: LineChartDataSet)
{
var lineData = delegate!.lineChartRendererData(self);
var entries = dataSet.yVals;
if (entries.count < 1)
{
return;
}
CGContextSaveGState(context);
CGContextSetLineWidth(context, dataSet.lineWidth);
if (dataSet.lineDashLengths != nil)
{
CGContextSetLineDash(context, dataSet.lineDashPhase, dataSet.lineDashLengths, dataSet.lineDashLengths.count);
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0);
}
// if drawing cubic lines is enabled
if (dataSet.isDrawCubicEnabled)
{
drawCubic(context: context, dataSet: dataSet, entries: entries);
}
else
{ // draw normal (straight) lines
drawLinear(context: context, dataSet: dataSet, entries: entries);
}
CGContextRestoreGState(context);
}
internal func drawCubic(#context: CGContext, dataSet: LineChartDataSet, entries: [ChartDataEntry])
{
var trans = delegate?.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency);
var entryFrom = dataSet.entryForXIndex(_minX);
var entryTo = dataSet.entryForXIndex(_maxX);
var minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true), 0);
var maxx = min(dataSet.entryIndex(entry: entryTo, isEqual: true) + 1, entries.count);
var phaseX = _animator.phaseX;
var phaseY = _animator.phaseY;
// get the color that is specified for this position from the DataSet
var drawingColor = dataSet.colors.first!;
var intensity = dataSet.cubicIntensity;
// the path for the cubic-spline
var cubicPath = CGPathCreateMutable();
var valueToPixelMatrix = trans!.valueToPixelMatrix;
var size = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx)));
if (size - minx >= 2)
{
var prevDx: CGFloat = 0.0;
var prevDy: CGFloat = 0.0;
var curDx: CGFloat = 0.0;
var curDy: CGFloat = 0.0;
var prevPrev = entries[minx];
var prev = entries[minx];
var cur = entries[minx];
var next = entries[minx + 1];
// let the spline start
CGPathMoveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY);
prevDx = CGFloat(cur.xIndex - prev.xIndex) * intensity;
prevDy = CGFloat(cur.value - prev.value) * intensity;
curDx = CGFloat(next.xIndex - cur.xIndex) * intensity;
curDy = CGFloat(next.value - cur.value) * intensity;
// the first cubic
CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix,
CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY,
CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY,
CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY);
for (var j = minx + 1, count = min(size, entries.count - 1); j < count; j++)
{
prevPrev = entries[j == 1 ? 0 : j - 2];
prev = entries[j - 1];
cur = entries[j];
next = entries[j + 1];
prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity;
prevDy = CGFloat(cur.value - prevPrev.value) * intensity;
curDx = CGFloat(next.xIndex - prev.xIndex) * intensity;
curDy = CGFloat(next.value - prev.value) * intensity;
CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY,
CGFloat(cur.xIndex) - curDx,
(CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY);
}
if (size > entries.count - 1)
{
prevPrev = entries[entries.count - (entries.count >= 3 ? 3 : 2)];
prev = entries[entries.count - 2];
cur = entries[entries.count - 1];
next = cur;
prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity;
prevDy = CGFloat(cur.value - prevPrev.value) * intensity;
curDx = CGFloat(next.xIndex - prev.xIndex) * intensity;
curDy = CGFloat(next.value - prev.value) * intensity;
// the last cubic
CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY,
CGFloat(cur.xIndex) - curDx,
(CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY);
}
}
CGContextSaveGState(context);
if (dataSet.isDrawFilledEnabled)
{
drawCubicFill(context: context, dataSet: dataSet, spline: cubicPath, matrix: valueToPixelMatrix, from: minx, to: size);
}
CGContextBeginPath(context);
CGContextAddPath(context, cubicPath);
CGContextSetStrokeColorWithColor(context, drawingColor.CGColor);
CGContextStrokePath(context);
CGContextRestoreGState(context);
}
internal func drawCubicFill(#context: CGContext, dataSet: LineChartDataSet, spline: CGMutablePath, var matrix: CGAffineTransform, from: Int, to: Int)
{
CGContextSaveGState(context);
var fillMin = delegate!.lineChartRendererFillFormatter(self).getFillLinePosition(
dataSet: dataSet,
data: delegate!.lineChartRendererData(self),
chartMaxY: delegate!.lineChartRendererChartYMax(self),
chartMinY: delegate!.lineChartRendererChartYMin(self));
var pt1 = CGPoint(x: CGFloat(to - 1), y: fillMin);
var pt2 = CGPoint(x: CGFloat(from), y: fillMin);
pt1 = CGPointApplyAffineTransform(pt1, matrix);
pt2 = CGPointApplyAffineTransform(pt2, matrix);
CGContextBeginPath(context);
CGContextAddPath(context, spline);
CGContextAddLineToPoint(context, pt1.x, pt1.y);
CGContextAddLineToPoint(context, pt2.x, pt2.y);
CGContextClosePath(context);
CGContextSetFillColorWithColor(context, dataSet.fillColor.CGColor);
CGContextSetAlpha(context, dataSet.fillAlpha);
CGContextFillPath(context);
CGContextRestoreGState(context);
}
private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint());
internal func drawLinear(#context: CGContext, dataSet: LineChartDataSet, entries: [ChartDataEntry])
{
var lineData = delegate!.lineChartRendererData(self);
var dataSetIndex = lineData.indexOfDataSet(dataSet);
var trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency);
var valueToPixelMatrix = trans.valueToPixelMatrix;
var phaseX = _animator.phaseX;
var phaseY = _animator.phaseY;
var pointBuffer = CGPoint();
CGContextSaveGState(context);
var entryFrom = dataSet.entryForXIndex(_minX);
var entryTo = dataSet.entryForXIndex(_maxX);
var minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true), 0);
var maxx = min(dataSet.entryIndex(entry: entryTo, isEqual: true) + 1, entries.count);
// more than 1 color
if (dataSet.colors.count > 1)
{
if (_lineSegments.count != 2)
{
_lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint());
}
for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++)
{
if (count > 1 && j == count - 1)
{ // Last point, we have already drawn a line to this point
break;
}
var e = entries[j];
_lineSegments[0].x = CGFloat(e.xIndex);
_lineSegments[0].y = CGFloat(e.value) * phaseY;
_lineSegments[0] = CGPointApplyAffineTransform(_lineSegments[0], valueToPixelMatrix);
if (j + 1 < count)
{
e = entries[j + 1];
_lineSegments[1].x = CGFloat(e.xIndex);
_lineSegments[1].y = CGFloat(e.value) * phaseY;
_lineSegments[1] = CGPointApplyAffineTransform(_lineSegments[1], valueToPixelMatrix);
}
else
{
_lineSegments[1] = _lineSegments[0];
}
if (!viewPortHandler.isInBoundsRight(_lineSegments[0].x))
{
break;
}
// make sure the lines don't do shitty things outside bounds
if (!viewPortHandler.isInBoundsLeft(_lineSegments[1].x)
|| (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y))
|| (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y)))
{
continue;
}
// get the color that is set for this line-segment
CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor);
CGContextStrokeLineSegments(context, _lineSegments, 2);
}
}
else
{ // only one color per dataset
var e1: ChartDataEntry!;
var e2: ChartDataEntry!;
if (_lineSegments.count != max((entries.count - 1) * 2, 2))
{
_lineSegments = [CGPoint](count: max((entries.count - 1) * 2, 2), repeatedValue: CGPoint());
}
e1 = entries[minx];
var count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx)));
for (var x = count > 1 ? minx + 1 : minx, j = 0; x < count; x++)
{
e1 = entries[x == 0 ? 0 : (x - 1)];
e2 = entries[x];
_lineSegments[j++] = CGPointApplyAffineTransform(CGPoint(x: CGFloat(e1.xIndex), y: CGFloat(e1.value) * phaseY), valueToPixelMatrix);
_lineSegments[j++] = CGPointApplyAffineTransform(CGPoint(x: CGFloat(e2.xIndex), y: CGFloat(e2.value) * phaseY), valueToPixelMatrix);
}
var size = max((count - minx - 1) * 2, 2)
CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor);
CGContextStrokeLineSegments(context, _lineSegments, size);
}
CGContextRestoreGState(context);
// if drawing filled is enabled
if (dataSet.isDrawFilledEnabled && entries.count > 0)
{
drawLinearFill(context: context, dataSet: dataSet, entries: entries, minx: minx, maxx: maxx, trans: trans);
}
}
internal func drawLinearFill(#context: CGContext, dataSet: LineChartDataSet, entries: [ChartDataEntry], minx: Int, maxx: Int, trans: ChartTransformer)
{
CGContextSaveGState(context);
CGContextSetFillColorWithColor(context, dataSet.fillColor.CGColor);
// filled is usually drawn with less alpha
CGContextSetAlpha(context, dataSet.fillAlpha);
var filled = generateFilledPath(
entries,
fillMin: delegate!.lineChartRendererFillFormatter(self).getFillLinePosition(
dataSet: dataSet,
data: delegate!.lineChartRendererData(self),
chartMaxY: delegate!.lineChartRendererChartYMax(self),
chartMinY: delegate!.lineChartRendererChartYMin(self)),
from: minx,
to: maxx,
matrix: trans.valueToPixelMatrix);
CGContextBeginPath(context);
CGContextAddPath(context, filled);
CGContextFillPath(context);
CGContextRestoreGState(context);
}
/// Generates the path that is used for filled drawing.
private func generateFilledPath(entries: [ChartDataEntry], fillMin: CGFloat, from: Int, to: Int, var matrix: CGAffineTransform) -> CGPath
{
var point = CGPoint();
var phaseX = _animator.phaseX;
var phaseY = _animator.phaseY;
var filled = CGPathCreateMutable();
CGPathMoveToPoint(filled, &matrix, CGFloat(entries[from].xIndex), fillMin);
CGPathAddLineToPoint(filled, &matrix, CGFloat(entries[from].xIndex), CGFloat(entries[from].value) * phaseY);
// create a new path
for (var x = from + 1, count = Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))); x < count; x++)
{
var e = entries[x];
CGPathAddLineToPoint(filled, &matrix, CGFloat(e.xIndex), CGFloat(e.value) * phaseY);
}
// close up
CGPathAddLineToPoint(filled, &matrix, CGFloat(entries[max(min(Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))) - 1, entries.count - 1), 0)].xIndex), fillMin);
CGPathCloseSubpath(filled);
return filled;
}
public override func drawValues(#context: CGContext)
{
var lineData = delegate!.lineChartRendererData(self);
if (lineData === nil)
{
return;
}
var defaultValueFormatter = delegate!.lineChartDefaultRendererValueFormatter(self);
if (CGFloat(lineData.yValCount) < CGFloat(delegate!.lineChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX)
{
var dataSets = lineData.dataSets;
for (var i = 0; i < dataSets.count; i++)
{
var dataSet = dataSets[i] as! LineChartDataSet;
if (!dataSet.isDrawValuesEnabled)
{
continue;
}
var valueFont = dataSet.valueFont;
var valueTextColor = dataSet.valueTextColor;
var formatter = dataSet.valueFormatter;
if (formatter === nil)
{
formatter = defaultValueFormatter;
}
var trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency);
// make sure the values do not interfear with the circles
var valOffset = Int(dataSet.circleRadius * 1.75);
if (!dataSet.isDrawCirclesEnabled)
{
valOffset = valOffset / 2;
}
var entries = dataSet.yVals;
var entryFrom = dataSet.entryForXIndex(_minX);
var entryTo = dataSet.entryForXIndex(_maxX);
var minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true), 0);
var maxx = min(dataSet.entryIndex(entry: entryTo, isEqual: true) + 1, entries.count);
var positions = trans.generateTransformedValuesLine(
entries,
phaseX: _animator.phaseX,
phaseY: _animator.phaseY,
from: minx,
to: maxx);
for (var j = 0, count = positions.count; j < count; j++)
{
if (!viewPortHandler.isInBoundsRight(positions[j].x))
{
break;
}
if (!viewPortHandler.isInBoundsLeft(positions[j].x) || !viewPortHandler.isInBoundsY(positions[j].y))
{
continue;
}
var val = entries[j + minx].value;
ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(val)!, point: CGPoint(x: positions[j].x, y: positions[j].y - CGFloat(valOffset) - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]);
}
}
}
}
public override func drawExtras(#context: CGContext)
{
drawCircles(context: context);
}
private func drawCircles(#context: CGContext)
{
var phaseX = _animator.phaseX;
var phaseY = _animator.phaseY;
var lineData = delegate!.lineChartRendererData(self);
var dataSets = lineData.dataSets;
var pt = CGPoint();
var rect = CGRect();
CGContextSaveGState(context);
for (var i = 0, count = dataSets.count; i < count; i++)
{
var dataSet = lineData.getDataSetByIndex(i) as! LineChartDataSet!;
if (!dataSet.isVisible || !dataSet.isDrawCirclesEnabled)
{
continue;
}
var trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency);
var valueToPixelMatrix = trans.valueToPixelMatrix;
var entries = dataSet.yVals;
var circleRadius = dataSet.circleRadius;
var circleDiameter = circleRadius * 2.0;
var circleHoleDiameter = circleRadius;
var circleHoleRadius = circleHoleDiameter / 2.0;
var isDrawCircleHoleEnabled = dataSet.isDrawCircleHoleEnabled;
var entryFrom = dataSet.entryForXIndex(_minX);
var entryTo = dataSet.entryForXIndex(_maxX);
var minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true), 0);
var maxx = min(dataSet.entryIndex(entry: entryTo, isEqual: true) + 1, entries.count);
for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++)
{
var e = entries[j];
pt.x = CGFloat(e.xIndex);
pt.y = CGFloat(e.value) * phaseY;
pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix);
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break;
}
// make sure the circles don't do shitty things outside bounds
if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))
{
continue;
}
CGContextSetFillColorWithColor(context, dataSet.getCircleColor(j)!.CGColor);
rect.origin.x = pt.x - circleRadius;
rect.origin.y = pt.y - circleRadius;
rect.size.width = circleDiameter;
rect.size.height = circleDiameter;
CGContextFillEllipseInRect(context, rect);
if (isDrawCircleHoleEnabled)
{
CGContextSetFillColorWithColor(context, dataSet.circleHoleColor.CGColor);
rect.origin.x = pt.x - circleHoleRadius;
rect.origin.y = pt.y - circleHoleRadius;
rect.size.width = circleHoleDiameter;
rect.size.height = circleHoleDiameter;
CGContextFillEllipseInRect(context, rect);
}
}
}
CGContextRestoreGState(context);
}
var _highlightPtsBuffer = [CGPoint](count: 4, repeatedValue: CGPoint());
public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight])
{
var lineData = delegate!.lineChartRendererData(self);
var chartXMax = delegate!.lineChartRendererChartXMax(self);
var chartYMax = delegate!.lineChartRendererChartYMax(self);
var chartYMin = delegate!.lineChartRendererChartYMin(self);
CGContextSaveGState(context);
for (var i = 0; i < indices.count; i++)
{
var set = lineData.getDataSetByIndex(indices[i].dataSetIndex) as! LineChartDataSet!;
if (set === nil)
{
continue;
}
CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor);
CGContextSetLineWidth(context, set.highlightLineWidth);
if (set.highlightLineDashLengths != nil)
{
CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count);
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0);
}
var xIndex = indices[i].xIndex; // get the x-position
if (CGFloat(xIndex) > CGFloat(chartXMax) * _animator.phaseX)
{
continue;
}
var y = CGFloat(set.yValForXIndex(xIndex)) * _animator.phaseY; // get the y-position
_highlightPtsBuffer[0] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMax));
_highlightPtsBuffer[1] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMin));
_highlightPtsBuffer[2] = CGPoint(x: CGFloat(delegate!.lineChartRendererChartXMin(self)), y: y);
_highlightPtsBuffer[3] = CGPoint(x: CGFloat(chartXMax), y: y);
var trans = delegate!.lineChartRenderer(self, transformerForAxis: set.axisDependency);
trans.pointValuesToPixel(&_highlightPtsBuffer);
// draw the highlight lines
CGContextStrokeLineSegments(context, _highlightPtsBuffer, 4);
}
CGContextRestoreGState(context);
}
} | gpl-2.0 |
piars777/TheMovieDatabaseSwiftWrapper | Sources/Models/Discover/DiscoverTV.swift | 1 | 6826 | //
// DiscoverTV.swift
// TheMovieDBWrapperSwift
//
// Created by George on 2016-02-05.
// Copyright © 2016 GeorgeKye. All rights reserved.
//
import Foundation
public enum TVGenres: String{
case Action_Adventure = "10759";
case Animation = "16";
case Comedy = "35";
case Documentary = "99";
case Drama = "18";
case Education = "10761";
case Family = "10751";
case Kids = "10762";
case Mystery = "9648";
case News = "10763";
case Reality = "10764";
case ScifiFantasy = "10765";
case Soap = "10766";
case Talk = "10767";
case WarPolitics = "10768";
case Western = "37";
}
public class DiscoverTVMDB: DiscoverMDB {
// ///DiscoverTV query. Language must be an ISO 639-1 code. Page must be greater than one. sort_by expected values can be found in DiscoverSortBy() and DiscoverSortByTV class variables. ALL parameters are optional
public class func discoverTV(api_key: String, language: String?, sort_by: String?, page: Double?, completionHandler: (clientReturn: ClientReturn, data: [TVMDB]?) -> ()) -> (){
Client.discover(api_key, baseURL: "tv", sort_by: sort_by, certification_country: nil, certification: nil, certification_lte: nil, include_adult: nil, include_video: nil, primary_release_year: nil, primary_release_date_gte: nil, primary_release_date_lte: nil, release_date_gte: nil, release_date_lte: nil, air_date_gte: nil, air_date_lte: nil, first_air_date_gte: nil, first_air_date_lte: nil, first_air_date_year: nil, language: language, page: page, timezone: nil, vote_average_gte: nil, vote_average_lte: nil, vote_count_gte: nil, vote_count_lte: nil, with_genres: nil, with_cast: nil, with_crew: nil, with_companies: nil, with_keywords: nil, with_people: nil, with_networks: nil, year: nil, certification_gte: nil){
apiReturn in
var data: [TVMDB]?
if(apiReturn.error == nil){
data = TVMDB.initialize(json: apiReturn.json!["results"])
}
completionHandler(clientReturn: apiReturn, data: data)
}
}
///lte = The minimum. gte = maximum. Expected date format is YYYY-MM-DD. Excpected year format is (####) ie.2010. ALL parameters are optional
public class func discoverTV(api_key: String, first_air_date_year: String?, first_air_date_gte: String?, first_air_date_lte: String?, air_date_gte: String?, air_date_lte: String?, language: String?, sort_by: String?, page: Double?, timezone: String?, completionHandler: (clientReturn: ClientReturn, data: [TVMDB]?) -> ()) -> (){
Client.discover(api_key, baseURL: "tv", sort_by: sort_by, certification_country: nil, certification: nil, certification_lte: nil, include_adult: nil, include_video: nil, primary_release_year: nil, primary_release_date_gte: nil, primary_release_date_lte: nil, release_date_gte: nil, release_date_lte: nil, air_date_gte: air_date_gte, air_date_lte: air_date_lte, first_air_date_gte: first_air_date_gte, first_air_date_lte: first_air_date_lte, first_air_date_year: first_air_date_year, language: language, page: page, timezone: timezone, vote_average_gte: nil, vote_average_lte: nil, vote_count_gte: nil, vote_count_lte: nil, with_genres: nil, with_cast: nil, with_crew: nil, with_companies: nil, with_keywords: nil, with_people: nil, with_networks: nil, year: nil, certification_gte: nil){
apiReturn in
var data: [TVMDB]?
if(apiReturn.error == nil){
data = TVMDB.initialize(json: apiReturn.json!["results"])
}
completionHandler(clientReturn: apiReturn, data: data)
}
}
////DiscoverTV query. Language must be an ISO 639-1 code. Page must be greater than one. sort_by expected values can be found in DiscoverSortBy() and DiscoverSortByTV class variables. lte = The minimum. gte = maximum. Expected date format is YYYY-MM-DD. Excpected year format is (####) ie.2010. ALL parameters are optional
public class func discoverTV(api_key: String, language: String?, sort_by: String?, page: Double?, first_air_date_year: String?, first_air_date_gte: String?, first_air_date_lte: String?, air_date_gte: String?, air_date_lte: String?, timezone: String?, vote_average_gte: Double?, vote_count_gte: Double?, with_genres: String?, with_networks: String?, completionHandler: (clientReturn: ClientReturn, data: [TVMDB]?) -> ()) -> (){
Client.discover(api_key, baseURL: "tv", sort_by: sort_by, certification_country: nil, certification: nil, certification_lte: nil, include_adult: nil, include_video: nil, primary_release_year: nil, primary_release_date_gte: nil, primary_release_date_lte: nil, release_date_gte: nil, release_date_lte: nil, air_date_gte: air_date_gte, air_date_lte: air_date_lte, first_air_date_gte: first_air_date_gte, first_air_date_lte: first_air_date_lte, first_air_date_year: first_air_date_year, language: language, page: page, timezone: timezone, vote_average_gte: vote_average_gte, vote_average_lte: nil, vote_count_gte: vote_count_gte, vote_count_lte: nil, with_genres: with_genres, with_cast: nil, with_crew: nil, with_companies: nil, with_keywords: nil, with_people: nil, with_networks: with_networks, year: nil, certification_gte: nil){
apiReturn in
var data: [TVMDB]?
if(apiReturn.error == nil){
data = TVMDB.initialize(json: apiReturn.json!["results"])
}
completionHandler(clientReturn: apiReturn, data: data)
}
}
//Discover tv shows with
public class func discoverTVWith(api_key: String, with_genres: String?, with_networks: String?, sort_by: String?, language: String?, page: Double?, completionHandler: (clientReturn: ClientReturn, data: [TVMDB]?) -> ()) -> (){
Client.discover(api_key, baseURL: "tv", sort_by: sort_by, certification_country: nil, certification: nil, certification_lte: nil, include_adult: nil, include_video: nil, primary_release_year: nil, primary_release_date_gte: nil, primary_release_date_lte: nil, release_date_gte: nil, release_date_lte: nil, air_date_gte: nil, air_date_lte: nil, first_air_date_gte: nil, first_air_date_lte: nil, first_air_date_year: nil, language: language, page: page, timezone: nil, vote_average_gte: nil, vote_average_lte: nil, vote_count_gte: nil, vote_count_lte: nil, with_genres: with_genres, with_cast: nil, with_crew: nil, with_companies: nil, with_keywords: nil, with_people: nil, with_networks: with_networks, year: nil, certification_gte: nil){
apiReturn in
var data: [TVMDB]?
if(apiReturn.error == nil){
data = TVMDB.initialize(json: apiReturn.json!["results"])
}
completionHandler(clientReturn: apiReturn, data: data)
}
}
} | mit |
glorybird/KeepReading2 | kr/kr/ui/ViewController.swift | 1 | 1486 | //
// ViewController.swift
// kr
//
// Created by FanFamily on 16/1/20.
// Copyright © 2016年 glorybird. All rights reserved.
//
import UIKit
class ViewController: UIViewController, SideMenuBuilderDelegate {
var readListVC:ReadListViewController?
var builder:SideMenuBuilder?
override func viewDidLoad() {
super.viewDidLoad()
let menuVC:MenuViewController = MenuViewController()
readListVC = ReadListViewController()
let menuButton:UIButton = UIButton(type: UIButtonType.System)
menuButton.frame = CGRectMake(0, 0, 50, 50)
menuButton.setTitle("...", forState: UIControlState.Normal)
builder = SideMenuBuilder(containVC: self, leftVC: menuVC, rightVC: readListVC!, menuButton:menuButton)
builder!.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
builder!.build()
}
func willChangeLeftSpace(space: CGFloat) {
if space == 0 {
self.readListVC!.collectionView.frame.size.width = self.readListVC!.view.frame.width
}
}
func didChangeLeftSpace(space: CGFloat) {
if space > 0 {
self.readListVC!.collectionView.frame.size.width = self.readListVC!.view.frame.width - space
}
}
}
| apache-2.0 |
pixel-ink/PIRipple | PIRipple/PIRipple.swift | 1 | 6836 | //---------------------------------------
// https://github.com/pixel-ink/PIRipple
//---------------------------------------
import UIKit
public extension UIView {
public func rippleBorder(location:CGPoint, color:UIColor) {
rippleBorder(location, color: color){}
}
public func rippleBorder(location:CGPoint, color:UIColor, then: ()->() ) {
Ripple.border(self, locationInView: location, color: color, then: then)
}
public func rippleFill(location:CGPoint, color:UIColor) {
rippleFill(location, color: color){}
}
public func rippleFill(location:CGPoint, color:UIColor, then: ()->() ) {
Ripple.fill(self, locationInView: location, color: color, then: then)
}
public func rippleStop() {
Ripple.stop(self)
}
}
public class Ripple {
private static var targetLayer: CALayer?
public struct Option {
public var borderWidth = CGFloat(5.0)
public var radius = CGFloat(30.0)
public var duration = CFTimeInterval(0.4)
public var borderColor = UIColor.whiteColor()
public var fillColor = UIColor.clearColor()
public var scale = CGFloat(3.0)
public var isRunSuperView = true
}
public class func option () -> Option {
return Option()
}
public class func run(view:UIView, locationInView:CGPoint, option:Ripple.Option) {
run(view, locationInView: locationInView, option: option){}
}
public class func run(view:UIView, locationInView:CGPoint, option:Ripple.Option, then: ()->() ) {
prePreform(view, point: locationInView, option: option, isLocationInView: true, then: then)
}
public class func run(view:UIView, absolutePosition:CGPoint, option:Ripple.Option) {
run(view, absolutePosition: absolutePosition, option: option){}
}
public class func run(view:UIView, absolutePosition:CGPoint, option:Ripple.Option, then: ()->() ) {
prePreform(view, point: absolutePosition, option: option, isLocationInView: false, then: then)
}
public class func border(view:UIView, locationInView:CGPoint, color:UIColor) {
border(view, locationInView: locationInView, color: color){}
}
public class func border(view:UIView, locationInView:CGPoint, color:UIColor, then: ()->() ) {
var opt = Ripple.Option()
opt.borderColor = color
prePreform(view, point: locationInView, option: opt, isLocationInView: true, then: then)
}
public class func border(view:UIView, absolutePosition:CGPoint, color:UIColor) {
border(view, absolutePosition: absolutePosition, color: color){}
}
public class func border(view:UIView, absolutePosition:CGPoint, color:UIColor, then: ()->() ) {
var opt = Ripple.Option()
opt.borderColor = color
prePreform(view, point: absolutePosition, option: opt, isLocationInView: false, then: then)
}
public class func fill(view:UIView, locationInView:CGPoint, color:UIColor) {
fill(view, locationInView: locationInView, color: color){}
}
public class func fill(view:UIView, locationInView:CGPoint, color:UIColor, then: ()->() ) {
var opt = Ripple.Option()
opt.borderColor = color
opt.fillColor = color
prePreform(view, point: locationInView, option: opt, isLocationInView: true, then: then)
}
public class func fill(view:UIView, absolutePosition:CGPoint, color:UIColor) {
fill(view, absolutePosition: absolutePosition, color: color){}
}
public class func fill(view:UIView, absolutePosition:CGPoint, color:UIColor, then: ()->() ) {
var opt = Ripple.Option()
opt.borderColor = color
opt.fillColor = color
prePreform(view, point: absolutePosition, option: opt, isLocationInView: false, then: then)
}
private class func prePreform(view:UIView, point:CGPoint, option: Ripple.Option, isLocationInView:Bool, then: ()->() ) {
let p = isLocationInView ? CGPointMake(point.x + view.frame.origin.x, point.y + view.frame.origin.y) : point
if option.isRunSuperView, let superview = view.superview {
prePreform(
superview,
point: p,
option: option,
isLocationInView: isLocationInView,
then: then
)
} else {
perform(
view,
point:p,
option:option,
then: then
)
}
}
private class func perform(view:UIView, point:CGPoint, option: Ripple.Option, then: ()->() ) {
UIGraphicsBeginImageContextWithOptions (
CGSizeMake((option.radius + option.borderWidth) * 2, (option.radius + option.borderWidth) * 2), false, 3.0)
let path = UIBezierPath(
roundedRect: CGRectMake(option.borderWidth, option.borderWidth, option.radius * 2, option.radius * 2),
cornerRadius: option.radius)
option.fillColor.setFill()
path.fill()
option.borderColor.setStroke()
path.lineWidth = option.borderWidth
path.stroke()
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let opacity = CABasicAnimation(keyPath: "opacity")
opacity.autoreverses = false
opacity.fillMode = kCAFillModeForwards
opacity.removedOnCompletion = false
opacity.duration = option.duration
opacity.fromValue = 1.0
opacity.toValue = 0.0
let transform = CABasicAnimation(keyPath: "transform")
transform.autoreverses = false
transform.fillMode = kCAFillModeForwards
transform.removedOnCompletion = false
transform.duration = option.duration
transform.fromValue = NSValue(CATransform3D: CATransform3DMakeScale(1.0 / option.scale, 1.0 / option.scale, 1.0))
transform.toValue = NSValue(CATransform3D: CATransform3DMakeScale(option.scale, option.scale, 1.0))
var rippleLayer:CALayer? = targetLayer
if rippleLayer == nil {
rippleLayer = CALayer()
view.layer.addSublayer(rippleLayer!)
targetLayer = rippleLayer
targetLayer?.addSublayer(CALayer())//Temporary, CALayer.sublayers is Implicitly Unwrapped Optional
}
dispatch_async(dispatch_get_main_queue()) {
[weak rippleLayer] in
if let target = rippleLayer {
let layer = CALayer()
layer.contents = img.CGImage
layer.frame = CGRectMake(point.x - option.radius, point.y - option.radius, option.radius * 2, option.radius * 2)
target.addSublayer(layer)
CATransaction.begin()
CATransaction.setAnimationDuration(option.duration)
CATransaction.setCompletionBlock {
layer.contents = nil
layer.removeAllAnimations()
layer.removeFromSuperlayer()
then()
}
layer.addAnimation(opacity, forKey:nil)
layer.addAnimation(transform, forKey:nil)
CATransaction.commit()
}
}
}
public class func stop(view:UIView) {
guard let sublayers = targetLayer?.sublayers else {
return
}
for layer in sublayers {
layer.removeAllAnimations()
}
}
} | mit |
xiaoleixy/Cocoa_swift | KvcFun/KvcFun/AppDelegate.swift | 1 | 743 | //
// AppDelegate.swift
// KvcFun
//
// Created by michael on 15/2/14.
// Copyright (c) 2015年 michael. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
var fido: Int = 0
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
@IBAction func incrementFido(sender: AnyObject) {
self.willChangeValueForKey("fido")
self.fido = self.fido + 1
self.didChangeValueForKey("fido")
}
}
| mit |
larryhou/swift | fetchQuote/fetchQuote/main.swift | 1 | 5571 | //
// main.swift
// fetchQuote
//
// Created by larryhou on 4/11/15.
// Copyright (c) 2015 larryhou. All rights reserved.
//
import Foundation
var ticket: String = "0700.HK"
var zone: String = "+0800"
var related: NSDate?
var verbose = false
var automated = false
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd Z"
var timeFormatter = NSDateFormatter()
timeFormatter.dateFormat = "YYYY-MM-dd,HH:mm:ss Z"
func judge(@autoclosure condition:() -> Bool, message: String) {
if !condition() {
println("ERR: " + message)
exit(1)
}
}
if Process.arguments.filter({$0 == "-h"}).count == 0 {
let count = Process.arguments.filter({$0 == "-t"}).count
judge(count >= 1, "[-t STOCK_TICKET] MUST be provided")
judge(count == 1, "[-t STOCK_TICKET] has been set \(count) times")
judge(Process.argc >= 3, "Unenough Parameters")
}
var skip: Bool = false
for i in 1..<Int(Process.argc) {
let option = Process.arguments[i]
if skip {
skip = false
continue
}
switch option {
case "-t":
judge(Process.arguments.count > i + 1, "-t lack of parameter")
ticket = Process.arguments[i + 1]
skip = true
break
case "-d":
judge(Process.arguments.count > i + 1, "-d lack of parameter")
related = dateFormatter.dateFromString(Process.arguments[i + 1] + " \(zone)")
judge(related != nil, "Unsupported date format:\(Process.arguments[i + 1]), e.g.2015-04-09")
skip = true
break
case "-z":
judge(Process.arguments.count > i + 1, "-z lack of parameter")
zone = Process.arguments[i + 1]
let regex = NSPredicate(format: "SELF MATCHES %@", "[+-]\\d{4}")
judge(regex.evaluateWithObject(zone), "Unsupported time zone format:\(zone), e.g. +0800")
skip = true
break
case "-v":
verbose = true
break
case "-a":
automated = true
break
case "-h":
let msg = Process.arguments[0] + " -t STOCK_TICKET [-z TIME_ZONE] [-d DATE]"
println(msg)
exit(0)
break
default:
println("Unsupported arguments: " + Process.arguments[i])
exit(2)
}
}
func getQuotesURL(var date: NSDate?) -> NSURL {
if date == nil {
date = NSDate()
}
let text = dateFormatter.stringFromDate(date!).componentsSeparatedByString(" ").first!
date = timeFormatter.dateFromString("\(text),06:00:00 \(zone)")
let refer = timeFormatter.dateFromString("\(text),20:00:00 \(zone)")!
let s = UInt(date!.timeIntervalSince1970)
let e = UInt(refer.timeIntervalSince1970)
let url = "http://finance.yahoo.com/_td_charts_api/resource/charts;comparisonTickers=;events=div%7Csplit%7Cearn;gmtz=8;indicators=quote;period1=\(s);period2=\(e);queryString=%7B%22s%22%3A%22\(ticket)%2BInteractive%22%7D;range=1d;rangeSelected=undefined;ticker=\(ticket);useMock=false?crumb=a6xbm2fVIlt"
return NSURL(string: url)!
}
class QuoteSpliter: Printable {
let date: NSDate
let ratios: [Int]
init(date: NSDate, ratios: [Int]) {
self.date = date
self.ratios = ratios
}
var description: String {
return dateFormatter.stringFromDate(date) + ", " + "/".join(ratios.map({"\($0)"}))
}
}
func formatQuote(value: AnyObject, format: String = "%6.2f") -> String {
return String(format: format, value as! Double)
}
func fetchQuoteOn(date: NSDate?) {
let url = getQuotesURL(date)
if verbose {
println(url)
}
var response: NSURLResponse?
var error: NSError?
var spliters: [QuoteSpliter] = []
let data = NSURLConnection.sendSynchronousRequest(NSURLRequest(URL: url), returningResponse: &response, error: &error)
if data != nil {
error = nil
var result: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &error)
if error == nil {
let json = result as! NSDictionary
let map = json.valueForKeyPath("data.events.splits") as? [String: [String: AnyObject]]
if map != nil {
for (key, item) in map! {
let time = NSString(string: key).integerValue
let date = NSDate(timeIntervalSince1970: NSTimeInterval(time))
let ratios = (item["splitRatio"] as! String).componentsSeparatedByString("/").map({$0.toInt()!})
spliters.append(QuoteSpliter(date: date, ratios: ratios))
}
}
let quotes = (json.valueForKeyPath("data.indicators.quote") as! [[String: [AnyObject]]]).first!
let stamps = json.valueForKeyPath("data.timestamp") as! [UInt]
let OPEN = "open", HIGH = "high", LOW = "low", CLOSE = "close"
let VOLUME = "volume"
var list: [String] = []
for i in 0..<stamps.count {
var item: [String] = []
var date = NSDate(timeIntervalSince1970: NSTimeInterval(stamps[i]))
if quotes[OPEN]![i] is NSNull {
continue
}
item.append(timeFormatter.stringFromDate(date).componentsSeparatedByString(" ").first!)
item.append(formatQuote(quotes[OPEN]![i]))
item.append(formatQuote(quotes[HIGH]![i]))
item.append(formatQuote(quotes[LOW ]![i]))
item.append(formatQuote(quotes[CLOSE]![i]))
item.append("\(quotes[VOLUME]![i])")
list.append(",".join(item))
}
if spliters.count > 0 {
println(spliters)
}
println("\n".join(list))
} else {
if verbose {
println(NSString(data: data!, encoding: NSUTF8StringEncoding)!)
}
}
} else {
if verbose {
if response != nil {
println(response!)
}
println(error!)
}
exit(202)
}
}
if !automated {
fetchQuoteOn(related)
} else {
let DAY: NSTimeInterval = 24 * 3600
related = NSDate(timeIntervalSince1970: NSDate().timeIntervalSince1970 + DAY)
for i in 0...50 {
fetchQuoteOn(NSDate(timeIntervalSince1970: related!.timeIntervalSince1970 - NSTimeInterval(i) * DAY))
}
}
| mit |
bourdakos1/Visual-Recognition-Tool | iOS/Visual Recognition/SnapperViewController.swift | 1 | 4228 | //
// SnapperViewController.swift
// Visual Recognition
//
// Created by Nicholas Bourdakos on 7/14/17.
// Copyright © 2017 Nicholas Bourdakos. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
class SnapperViewController: CameraViewController {
var classifier = PendingClassifier()
var pendingClass = PendingClass()
@IBOutlet var thumbnail: UIView!
@IBOutlet var thumbnailImage: UIImageView!
@IBOutlet weak var width: NSLayoutConstraint!
@IBOutlet weak var height: NSLayoutConstraint!
// MARK: View Controller Life Cycle
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// load the thumbnail of images.
// This needs to happen in view did appear so it loads in the right spot.
let border = UIView()
let frame = CGRect(x: self.thumbnailImage.frame.origin.x - 1.0, y: self.thumbnailImage.frame.origin.y - 1.0, width: self.thumbnailImage.frame.size.height + 2.0, height: self.thumbnailImage.frame.size.height + 2.0)
border.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.25)
border.frame = frame
border.layer.cornerRadius = 7.0
self.view.insertSubview(border, belowSubview: self.thumbnailImage)
}
override func viewDidLoad() {
super.viewDidLoad()
self.thumbnailImage.layer.cornerRadius = 5.0
grabPhoto()
}
func grabPhoto() {
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
// Get the directory contents urls (including subfolders urls)
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl.appendingPathComponent(classifier.id!).appendingPathComponent(pendingClass.name!), includingPropertiesForKeys: nil, options: [])
// if you want to filter the directory contents you can do like this:
let jpgFile = directoryContents.filter{ $0.pathExtension == "jpg" }
.map { url -> (URL, TimeInterval) in
var lastModified = try? url.resourceValues(forKeys: [URLResourceKey.contentModificationDateKey])
return (url, lastModified?.contentModificationDate?.timeIntervalSinceReferenceDate ?? 0)
}
.sorted(by: { $0.1 > $1.1 }) // sort descending modification dates
.map{ $0.0 }.first!
thumbnailImage.image = UIImage(contentsOfFile: jpgFile.path)!
} catch {
print(error.localizedDescription)
}
}
override func captured(image: UIImage) {
DispatchQueue.main.async { [unowned self] in
self.width.constant = 5
self.height.constant = 5
self.thumbnailImage.image = image
self.view.layoutIfNeeded()
self.width.constant = 60
self.height.constant = 60
UIView.animate(withDuration: 0.3, delay: 0.0, options: [.curveEaseOut], animations: { () -> Void in
self.thumbnailImage.alpha = 1.0
}, completion: nil)
UIView.animate(withDuration: 0.3, delay: 0.0, options: [.curveEaseOut], animations: { () -> Void in
self.view.layoutIfNeeded()
}, completion: nil)
}
let reducedImage = image.resized(toWidth: 300)!
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let path = documentsUrl.appendingPathComponent(self.classifier.id!).appendingPathComponent(self.pendingClass.name!)
do {
try FileManager.default.createDirectory(atPath: path.path, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error.localizedDescription)
}
let filename = path.appendingPathComponent("\(NSUUID().uuidString).jpg")
do {
try UIImageJPEGRepresentation(reducedImage, 0.4)!.write(to: filename)
} catch {
print(error.localizedDescription)
}
}
}
| mit |
yoonapps/swift-corelibs-xctest | Tests/Functional/Observation/Selected/main.swift | 1 | 3578 | // RUN: %{swiftc} %s -o %{built_tests_dir}/Selected
// RUN: %{built_tests_dir}/Selected Selected.ExecutedTestCase/test_executed > %t || true
// RUN: %{xctest_checker} %t %s
#if os(Linux) || os(FreeBSD)
import XCTest
import Foundation
#else
import SwiftXCTest
import SwiftFoundation
#endif
// CHECK: Test Suite 'Selected tests' started at \d+:\d+:\d+\.\d+
class Observer: XCTestObservation {
var startedTestSuites = [XCTestSuite]()
var finishedTestSuites = [XCTestSuite]()
func testBundleWillStart(_ testBundle: NSBundle) {}
func testSuiteWillStart(_ testSuite: XCTestSuite) {
startedTestSuites.append(testSuite)
}
func testCaseWillStart(_ testCase: XCTestCase) {}
func testCase(_ testCase: XCTestCase, didFailWithDescription description: String, inFile filePath: String?, atLine lineNumber: UInt) {}
func testCaseDidFinish(_ testCase: XCTestCase) {}
func testSuiteDidFinish(_ testSuite: XCTestSuite) {
print("In \(#function): \(testSuite.name)")
}
func testBundleDidFinish(_ testBundle: NSBundle) {}
}
let observer = Observer()
XCTestObservationCenter.shared().addTestObserver(observer)
class SkippedTestCase: XCTestCase {
static var allTests: [(String, SkippedTestCase -> () throws -> Void)] {
return [
("test_skipped", test_skipped),
]
}
func test_skipped() {
XCTFail("This test case should not be executed.")
}
}
// CHECK: Test Suite 'ExecutedTestCase' started at \d+:\d+:\d+\.\d+
class ExecutedTestCase: XCTestCase {
static var allTests: [(String, ExecutedTestCase -> () throws -> Void)] {
return [
("test_executed", test_executed),
("test_skipped", test_skipped),
]
}
// CHECK: Test Case 'ExecutedTestCase.test_executed' started at \d+:\d+:\d+\.\d+
// CHECK: Test Case 'ExecutedTestCase.test_executed' passed \(\d+\.\d+ seconds\).
func test_executed() {
let suiteNames = observer.startedTestSuites.map { $0.name }
XCTAssertEqual(suiteNames, ["Selected tests", "ExecutedTestCase"])
}
func test_skipped() {
XCTFail("This test case should not be executed.")
}
}
// There's no guarantee as to the order in which these two observers will be
// called, so we match any order here.
// CHECK: (In testSuiteDidFinish: ExecutedTestCase)|(Test Suite 'ExecutedTestCase' passed at \d+:\d+:\d+\.\d+|\t Executed 1 test, with 0 failures \(0 unexpected\) in \d+\.\d+ \(\d+\.\d+\) seconds)
// CHECK: (In testSuiteDidFinish: ExecutedTestCase)|(Test Suite 'ExecutedTestCase' passed at \d+:\d+:\d+\.\d+|\t Executed 1 test, with 0 failures \(0 unexpected\) in \d+\.\d+ \(\d+\.\d+\) seconds)
// CHECK: (In testSuiteDidFinish: ExecutedTestCase)|(Test Suite 'ExecutedTestCase' passed at \d+:\d+:\d+\.\d+|\t Executed 1 test, with 0 failures \(0 unexpected\) in \d+\.\d+ \(\d+\.\d+\) seconds)
XCTMain([
testCase(SkippedTestCase.allTests),
testCase(ExecutedTestCase.allTests),
])
// CHECK: (In testSuiteDidFinish: Selected tests|Test Suite 'Selected tests' passed at \d+:\d+:\d+\.\d+)|(\t Executed 1 test, with 0 failures \(0 unexpected\) in \d+\.\d+ \(\d+\.\d+\) seconds)
// CHECK: (In testSuiteDidFinish: Selected tests|Test Suite 'Selected tests' passed at \d+:\d+:\d+\.\d+)|(\t Executed 1 test, with 0 failures \(0 unexpected\) in \d+\.\d+ \(\d+\.\d+\) seconds)
// CHECK: (In testSuiteDidFinish: Selected tests|Test Suite 'Selected tests' passed at \d+:\d+:\d+\.\d+)|(\t Executed 1 test, with 0 failures \(0 unexpected\) in \d+\.\d+ \(\d+\.\d+\) seconds)
| apache-2.0 |
zhuhaow/NEKit | src/Socket/SocketProtocol.swift | 1 | 4374 | import Foundation
/**
The current connection status of the socket.
- Invalid: The socket is just created but never connects.
- Connecting: The socket is connecting.
- Established: The connection is established.
- Disconnecting: The socket is disconnecting.
- Closed: The socket is closed.
*/
public enum SocketStatus {
/// The socket is just created but never connects.
case invalid,
/// The socket is connecting.
connecting,
/// The connection is established.
established,
/// The socket is disconnecting.
disconnecting,
/// The socket is closed.
closed
}
/// Protocol for socket with various functions.
///
/// Any concrete implementation does not need to be thread-safe.
public protocol SocketProtocol: class {
/// The underlying TCP socket transmitting data.
var socket: RawTCPSocketProtocol! { get }
/// The delegate instance.
var delegate: SocketDelegate? { get set }
/// The current connection status of the socket.
var status: SocketStatus { get }
// /// The description of the currect status.
// var statusDescription: String { get }
/// If the socket is disconnected.
var isDisconnected: Bool { get }
/// The type of the socket.
var typeName: String { get }
var readStatusDescription: String { get }
var writeStatusDescription: String { get }
/**
Read data from the socket.
- warning: This should only be called after the last read is finished, i.e., `delegate?.didReadData()` is called.
*/
func readData()
/**
Send data to remote.
- parameter data: Data to send.
- warning: This should only be called after the last write is finished, i.e., `delegate?.didWriteData()` is called.
*/
func write(data: Data)
/**
Disconnect the socket elegantly.
*/
func disconnect(becauseOf error: Error?)
/**
Disconnect the socket immediately.
*/
func forceDisconnect(becauseOf error: Error?)
}
extension SocketProtocol {
/// If the socket is disconnected.
public var isDisconnected: Bool {
return status == .closed || status == .invalid
}
public var typeName: String {
return String(describing: type(of: self))
}
public var readStatusDescription: String {
return "\(status)"
}
public var writeStatusDescription: String {
return "\(status)"
}
}
/// The delegate protocol to handle the events from a socket.
public protocol SocketDelegate : class {
/**
The socket did connect to remote.
- parameter adapterSocket: The connected socket.
*/
func didConnectWith(adapterSocket: AdapterSocket)
/**
The socket did disconnect.
This should only be called once in the entire lifetime of a socket. After this is called, the delegate will not receive any other events from that socket and the socket should be released.
- parameter socket: The socket which did disconnect.
*/
func didDisconnectWith(socket: SocketProtocol)
/**
The socket did read some data.
- parameter data: The data read from the socket.
- parameter from: The socket where the data is read from.
*/
func didRead(data: Data, from: SocketProtocol)
/**
The socket did send some data.
- parameter data: The data which have been sent to remote (acknowledged). Note this may not be available since the data may be released to save memory.
- parameter by: The socket where the data is sent out.
*/
func didWrite(data: Data?, by: SocketProtocol)
/**
The socket is ready to forward data back and forth.
- parameter socket: The socket which becomes ready to forward data.
*/
func didBecomeReadyToForwardWith(socket: SocketProtocol)
/**
Did receive a `ConnectSession` from local now it is time to connect to remote.
- parameter session: The received `ConnectSession`.
- parameter from: The socket where the `ConnectSession` is received.
*/
func didReceive(session: ConnectSession, from: ProxySocket)
/**
The adapter socket decided to replace itself with a new `AdapterSocket` to connect to remote.
- parameter newAdapter: The new `AdapterSocket` to replace the old one.
*/
func updateAdapterWith(newAdapter: AdapterSocket)
}
| bsd-3-clause |
yeziahehe/Gank | Pods/JTAppleCalendar/Sources/JTAppleCalendarVariables.swift | 1 | 3703 | //
// JTAppleCalendarVariables.swift
//
// Copyright (c) 2016-2017 JTAppleCalendar (https://github.com/patchthecode/JTAppleCalendar)
//
// 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.
//
// Calculated Variables
extension JTAppleCalendarView {
/// Workaround for Xcode bug that prevents you from connecting the delegate in the storyboard.
/// Remove this extra property once Xcode gets fixed.
@IBOutlet public var ibCalendarDelegate: AnyObject? {
get { return calendarDelegate }
set { calendarDelegate = newValue as? JTAppleCalendarViewDelegate }
}
/// Workaround for Xcode bug that prevents you from connecting the delegate in the storyboard.
/// Remove this extra property once Xcode gets fixed.
@IBOutlet public var ibCalendarDataSource: AnyObject? {
get { return calendarDataSource }
set { calendarDataSource = newValue as? JTAppleCalendarViewDataSource }
}
@available(*, unavailable)
/// Will not be used by subclasses
open override var delegate: UICollectionViewDelegate? {
get { return super.delegate }
set { /* Do nothing */ }
}
@available(*, unavailable)
/// Will not be used by subclasses
open override var dataSource: UICollectionViewDataSource? {
get { return super.dataSource }
set {/* Do nothing */ }
}
/// Returns all selected dates
open var selectedDates: [Date] {
return selectedDatesSet.sorted()
}
var selectedDatesSet: Set<Date> {
return Set(selectedCellData.values.map { $0.date })
}
var monthInfo: [Month] {
get { return theData.months }
set { theData.months = monthInfo }
}
var numberOfMonths: Int {
return monthInfo.count
}
var totalDays: Int {
return theData.totalDays
}
var calendarViewLayout: JTAppleCalendarLayout {
guard let layout = collectionViewLayout as? JTAppleCalendarLayout else {
developerError(string: "Calendar layout is not of type JTAppleCalendarLayout.")
return JTAppleCalendarLayout(withDelegate: self)
}
return layout
}
var functionIsUnsafeSafeToRun: Bool {
return !isCalendarLayoutLoaded || isScrollInProgress || isReloadDataInProgress
}
var isCalendarLayoutLoaded: Bool { return calendarViewLayout.isCalendarLayoutLoaded }
var startDateCache: Date { return _cachedConfiguration.startDate }
var endDateCache: Date { return _cachedConfiguration.endDate }
var calendar: Calendar { return _cachedConfiguration.calendar }
}
| gpl-3.0 |
mohamede1945/quran-ios | Quran/AudioQariBarView.swift | 2 | 1516 | //
// AudioQariBarView.swift
// Quran
//
// Created by Mohamed Afifi on 5/8/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// 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.
//
import UIKit
class AudioQariBarView: UIView {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var backgroundButton: BackgroundColorButton!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
private func setUp() {
loadViewFrom(nibName: "AudioQariBarView")
imageView.layer.borderColor = UIColor.lightGray.cgColor
imageView.layer.borderWidth = 0.5
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.layer.cornerRadius = imageView.bounds.width / 2
imageView.layer.masksToBounds = true
}
}
| gpl-3.0 |
xedin/swift | stdlib/public/core/Zip.swift | 1 | 5527 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Creates a sequence of pairs built out of two underlying sequences.
///
/// In the `Zip2Sequence` instance returned by this function, the elements of
/// the *i*th pair are the *i*th elements of each underlying sequence. The
/// following example uses the `zip(_:_:)` function to iterate over an array
/// of strings and a countable range at the same time:
///
/// let words = ["one", "two", "three", "four"]
/// let numbers = 1...4
///
/// for (word, number) in zip(words, numbers) {
/// print("\(word): \(number)")
/// }
/// // Prints "one: 1"
/// // Prints "two: 2
/// // Prints "three: 3"
/// // Prints "four: 4"
///
/// If the two sequences passed to `zip(_:_:)` are different lengths, the
/// resulting sequence is the same length as the shorter sequence. In this
/// example, the resulting array is the same length as `words`:
///
/// let naturalNumbers = 1...Int.max
/// let zipped = Array(zip(words, naturalNumbers))
/// // zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)]
///
/// - Parameters:
/// - sequence1: The first sequence or collection to zip.
/// - sequence2: The second sequence or collection to zip.
/// - Returns: A sequence of tuple pairs, where the elements of each pair are
/// corresponding elements of `sequence1` and `sequence2`.
@inlinable // generic-performance
public func zip<Sequence1, Sequence2>(
_ sequence1: Sequence1, _ sequence2: Sequence2
) -> Zip2Sequence<Sequence1, Sequence2> {
return Zip2Sequence(sequence1, sequence2)
}
/// A sequence of pairs built out of two underlying sequences.
///
/// In a `Zip2Sequence` instance, the elements of the *i*th pair are the *i*th
/// elements of each underlying sequence. To create a `Zip2Sequence` instance,
/// use the `zip(_:_:)` function.
///
/// The following example uses the `zip(_:_:)` function to iterate over an
/// array of strings and a countable range at the same time:
///
/// let words = ["one", "two", "three", "four"]
/// let numbers = 1...4
///
/// for (word, number) in zip(words, numbers) {
/// print("\(word): \(number)")
/// }
/// // Prints "one: 1"
/// // Prints "two: 2
/// // Prints "three: 3"
/// // Prints "four: 4"
@frozen // generic-performance
public struct Zip2Sequence<Sequence1 : Sequence, Sequence2 : Sequence> {
@usableFromInline // generic-performance
internal let _sequence1: Sequence1
@usableFromInline // generic-performance
internal let _sequence2: Sequence2
/// Creates an instance that makes pairs of elements from `sequence1` and
/// `sequence2`.
@inlinable // generic-performance
internal init(_ sequence1: Sequence1, _ sequence2: Sequence2) {
(_sequence1, _sequence2) = (sequence1, sequence2)
}
}
extension Zip2Sequence {
/// An iterator for `Zip2Sequence`.
@frozen // generic-performance
public struct Iterator {
@usableFromInline // generic-performance
internal var _baseStream1: Sequence1.Iterator
@usableFromInline // generic-performance
internal var _baseStream2: Sequence2.Iterator
@usableFromInline // generic-performance
internal var _reachedEnd: Bool = false
/// Creates an instance around a pair of underlying iterators.
@inlinable // generic-performance
internal init(
_ iterator1: Sequence1.Iterator,
_ iterator2: Sequence2.Iterator
) {
(_baseStream1, _baseStream2) = (iterator1, iterator2)
}
}
}
extension Zip2Sequence.Iterator: IteratorProtocol {
/// The type of element returned by `next()`.
public typealias Element = (Sequence1.Element, Sequence2.Element)
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable // generic-performance
public mutating func next() -> Element? {
// The next() function needs to track if it has reached the end. If we
// didn't, and the first sequence is longer than the second, then when we
// have already exhausted the second sequence, on every subsequent call to
// next() we would consume and discard one additional element from the
// first sequence, even though next() had already returned nil.
if _reachedEnd {
return nil
}
guard let element1 = _baseStream1.next(),
let element2 = _baseStream2.next() else {
_reachedEnd = true
return nil
}
return (element1, element2)
}
}
extension Zip2Sequence: Sequence {
public typealias Element = (Sequence1.Element, Sequence2.Element)
/// Returns an iterator over the elements of this sequence.
@inlinable // generic-performance
public __consuming func makeIterator() -> Iterator {
return Iterator(
_sequence1.makeIterator(),
_sequence2.makeIterator())
}
@inlinable // generic-performance
public var underestimatedCount: Int {
return Swift.min(
_sequence1.underestimatedCount,
_sequence2.underestimatedCount
)
}
}
| apache-2.0 |
a1049145827/WebViewTest1 | WebView/AppDelegate.swift | 1 | 2140 | //
// AppDelegate.swift
// WebView
//
// Created by LiuBruce on 15/11/26.
// Copyright © 2015年 LiuBruce. All rights reserved.
//
import UIKit
@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:.
}
}
| mit |
SwiftGen/SwiftGen | Sources/SwiftGenKit/Parsers/Strings/StringsEntry.swift | 1 | 1037 | //
// SwiftGenKit
// Copyright © 2022 SwiftGen
// MIT Licence
//
import Foundation
import PathKit
extension Strings {
struct Entry {
var comment: String?
let key: String
let translation: String
let types: [PlaceholderType]
let keyStructure: [String]
init(key: String, translation: String, types: [PlaceholderType], keyStructureSeparator: String) {
self.key = key
self.translation = translation
self.types = types
self.keyStructure = Self.split(key: key, separator: keyStructureSeparator)
}
init(key: String, translation: String, keyStructureSeparator: String) throws {
let types = try PlaceholderType.placeholderTypes(fromFormat: translation)
self.init(key: key, translation: translation, types: types, keyStructureSeparator: keyStructureSeparator)
}
// MARK: - Structured keys
private static func split(key: String, separator: String) -> [String] {
key
.components(separatedBy: separator)
.filter { !$0.isEmpty }
}
}
}
| mit |
VirgilSecurity/virgil-sdk-keys-x | Source/Cards/CardManager/CardManager+Queries.swift | 2 | 12540 | //
// Copyright (C) 2015-2021 Virgil Security Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// (1) Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// (3) Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>
//
import Foundation
import VirgilCrypto
// MARK: - Extension for primary operations
extension CardManager {
/// Makes CallbackOperation<Card> for getting verified Virgil Card
/// from the Virgil Cards Service with given ID, if exists
///
/// - Parameter cardId: identifier of Virgil Card to find
/// - Returns: CallbackOperation<GetCardResponse> for getting `GetCardResponse` with verified Virgil Card
open func getCard(withId cardId: String) -> GenericOperation<Card> {
return CallbackOperation { _, completion in
do {
let responseModel = try self.cardClient.getCard(withId: cardId)
let card = try self.parseCard(from: responseModel.rawCard)
card.isOutdated = responseModel.isOutdated
guard card.identifier == cardId else {
throw CardManagerError.gotWrongCard
}
guard self.cardVerifier.verifyCard(card) else {
throw CardManagerError.cardIsNotVerified
}
completion(card, nil)
}
catch {
completion(nil, error)
}
}
}
/// Generates self signed RawSignedModel
///
/// - Parameters:
/// - privateKey: VirgilPrivateKey to self sign with
/// - publicKey: Public Key instance
/// - identity: Card's identity
/// - previousCardId: Identifier of Virgil Card with same identity this Card will replace
/// - extraFields: Dictionary with extra data to sign with model. Should be JSON-compatible
/// - Returns: Self signed RawSignedModel
/// - Throws: Rethrows from `VirgilCrypto`, `JSONEncoder`, `JSONSerialization`, `ModelSigner`
@objc open func generateRawCard(privateKey: VirgilPrivateKey, publicKey: VirgilPublicKey,
identity: String, previousCardId: String? = nil,
extraFields: [String: String]? = nil) throws -> RawSignedModel {
return try CardManager.generateRawCard(crypto: self.crypto,
modelSigner: self.modelSigner,
privateKey: privateKey,
publicKey: publicKey,
identity: identity,
previousCardId: previousCardId,
extraFields: extraFields)
}
/// Generates self signed RawSignedModel
///
/// - Parameters:
/// - crypto: VirgilCrypto implementation
/// - modelSigner: ModelSigner implementation
/// - privateKey: VirgilPrivateKey to self sign with
/// - publicKey: Public Key instance
/// - identity: Card's identity
/// - previousCardId: Identifier of Virgil Card with same identity this Card will replace
/// - extraFields: Dictionary with extra data to sign with model. Should be JSON-compatible
/// - Returns: Self signed RawSignedModel
/// - Throws: Rethrows from `VirgilCrypto`, `JSONEncoder`, `JSONSerialization`, `ModelSigner`
@objc open class func generateRawCard(crypto: VirgilCrypto, modelSigner: ModelSigner,
privateKey: VirgilPrivateKey, publicKey: VirgilPublicKey,
identity: String, previousCardId: String? = nil,
extraFields: [String: String]? = nil) throws -> RawSignedModel {
let exportedPubKey = try crypto.exportPublicKey(publicKey)
let cardContent = RawCardContent(identity: identity,
publicKey: exportedPubKey,
previousCardId: previousCardId,
createdAt: Date())
let snapshot = try JSONEncoder().encode(cardContent)
let rawCard = RawSignedModel(contentSnapshot: snapshot)
var data: Data?
if extraFields != nil {
data = try JSONSerialization.data(withJSONObject: extraFields as Any, options: [])
}
else {
data = nil
}
try modelSigner.selfSign(model: rawCard, privateKey: privateKey, additionalData: data)
return rawCard
}
/// Makes CallbackOperation<Card> for creating Virgil Card instance
/// on the Virgil Cards Service and associates it with unique identifier
///
/// - Parameter rawCard: RawSignedModel of Card to create
/// - Returns: CallbackOperation<Card> for creating Virgil Card instance
open func publishCard(rawCard: RawSignedModel) -> GenericOperation<Card> {
return CallbackOperation { _, completion in
do {
let signedRawCard = try CallbackOperation<RawSignedModel> { _, completion in
if let signCallback = self.signCallback {
signCallback(rawCard) { rawCard, error in
completion(rawCard, error)
}
}
else {
completion(rawCard, nil)
}
}.startSync().get()
let responseModel = try self.cardClient.publishCard(model: signedRawCard)
guard responseModel.contentSnapshot == rawCard.contentSnapshot,
let selfSignature = rawCard.signatures
.first(where: { $0.signer == ModelSigner.selfSignerIdentifier }),
let responseSelfSignature = responseModel.signatures
.first(where: { $0.signer == ModelSigner.selfSignerIdentifier }),
selfSignature.snapshot == responseSelfSignature.snapshot else {
throw CardManagerError.gotWrongCard
}
let card = try self.parseCard(from: responseModel)
guard self.cardVerifier.verifyCard(card) else {
throw CardManagerError.cardIsNotVerified
}
completion(card, nil)
}
catch {
completion(nil, error)
}
}
}
/// Makes CallbackOperation<Card> for generating self signed RawSignedModel and
/// creating Virgil Card instance on the Virgil Cards Service
///
/// - Parameters:
/// - privateKey: VirgilPrivateKey to self sign with
/// - publicKey: Public Key instance
/// - identity: Card's identity
/// - previousCardId: Identifier of Virgil Card with same identity this Card will replace
/// - extraFields: Dictionary with extra data to sign with model. Should be JSON-compatible
/// - Returns: CallbackOperation<Card> for generating self signed RawSignedModel and
/// creating Virgil Card instance on the Virgil Cards Service
open func publishCard(privateKey: VirgilPrivateKey, publicKey: VirgilPublicKey,
identity: String, previousCardId: String? = nil,
extraFields: [String: String]? = nil) -> GenericOperation<Card> {
return CallbackOperation { _, completion in
do {
let rawCard = try self.generateRawCard(privateKey: privateKey,
publicKey: publicKey,
identity: identity,
previousCardId: previousCardId,
extraFields: extraFields)
let card = try self.publishCard(rawCard: rawCard).startSync().get()
completion(card, nil)
}
catch {
completion(nil, error)
}
}
}
/// Makes CallbackOperation<[Card]> for performing search of Virgil Cards
/// on the Virgil Cards Service using identities
///
/// - Note: Resulting array will contain only actual cards.
/// Older cards (that were replaced) can be accessed using previousCard property of new cards.
///
/// - Parameter identities: identities of cards to search
/// - Returns: CallbackOperation<[Card]> for performing search of Virgil Cards
open func searchCards(identities: [String]) -> GenericOperation<[Card]> {
return CallbackOperation { _, completion in
do {
let cards = try self.cardClient.searchCards(identities: identities)
.map { rawSignedModel -> Card in
try self.parseCard(from: rawSignedModel)
}
let result = try cards
.compactMap { card -> Card? in
guard identities.contains(card.identity) else {
throw CardManagerError.gotWrongCard
}
if let nextCard = cards.first(where: { $0.previousCardId == card.identifier }) {
nextCard.previousCard = card
card.isOutdated = true
return nil
}
return card
}
guard result.allSatisfy({ self.cardVerifier.verifyCard($0) }) else {
throw CardManagerError.cardIsNotVerified
}
completion(result, nil)
}
catch {
completion(nil, error)
}
}
}
/// Returns list of cards that were replaced with newer ones
///
/// - Parameter cardIds: card ids to check
/// - Returns: GenericOperation<[String]>
open func getOutdated(cardIds: [String]) -> GenericOperation<[String]> {
return CallbackOperation { _, completion in
do {
let cardIds = try self.cardClient.getOutdated(cardIds: cardIds)
completion(cardIds, nil)
}
catch {
completion(nil, error)
}
}
}
/// Makes CallbackOperation<Void> for performing revokation of Virgil Card
///
/// Revoked card gets isOutdated flag to be set to true.
/// Also, such cards could be obtained using get query, but will be absent in search query result.
///
/// - Parameter cardId: identifier of card to revoke
/// - Returns: CallbackOperation<Void>
open func revokeCard(withId cardId: String) -> GenericOperation<Void> {
return CallbackOperation { _, completion in
do {
try self.cardClient.revokeCard(withId: cardId)
completion(Void(), nil)
}
catch {
completion(nil, error)
}
}
}
}
| bsd-3-clause |
talyadev/EdmundsAPI-Swift | EdmundsAPI/AppDelegate.swift | 1 | 2153 | //
// AppDelegate.swift
// EdmundsAPI
//
// Created by Talia DeVault on 1/28/15.
// Copyright (c) 2015 Frames Per Sound. All rights reserved.
//
import UIKit
@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:.
}
}
| mit |
apple/swift-format | Sources/SwiftFormatRules/FileScopedDeclarationPrivacy.swift | 1 | 7063 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftFormatCore
import SwiftSyntax
/// Declarations at file scope with effective private access should be consistently declared as
/// either `fileprivate` or `private`, determined by configuration.
///
/// Lint: If a file-scoped declaration has formal access opposite to the desired access level in the
/// formatter's configuration, a lint error is raised.
///
/// Format: File-scoped declarations that have formal access opposite to the desired access level in
/// the formatter's configuration will have their access level changed.
public final class FileScopedDeclarationPrivacy: SyntaxFormatRule {
public override func visit(_ node: SourceFileSyntax) -> SourceFileSyntax {
let newStatements = rewrittenCodeBlockItems(node.statements)
return node.withStatements(newStatements)
}
/// Returns a list of code block items equivalent to the given list, but where any file-scoped
/// declarations with effective private access have had their formal access level rewritten, if
/// necessary, to be either `private` or `fileprivate`, as determined by the formatter
/// configuration.
///
/// - Parameter codeBlockItems: The list of code block items to rewrite.
/// - Returns: A new `CodeBlockItemListSyntax` that has possibly been rewritten.
private func rewrittenCodeBlockItems(_ codeBlockItems: CodeBlockItemListSyntax)
-> CodeBlockItemListSyntax
{
let newCodeBlockItems = codeBlockItems.map { codeBlockItem -> CodeBlockItemSyntax in
switch codeBlockItem.item {
case .decl(let decl):
return codeBlockItem.withItem(.decl(rewrittenDecl(decl)))
default:
return codeBlockItem
}
}
return CodeBlockItemListSyntax(newCodeBlockItems)
}
private func rewrittenDecl(_ decl: DeclSyntax) -> DeclSyntax {
switch Syntax(decl).as(SyntaxEnum.self) {
case .ifConfigDecl(let ifConfigDecl):
// We need to look through `#if/#elseif/#else` blocks because the decls directly inside
// them are still considered file-scope for our purposes.
return DeclSyntax(rewrittenIfConfigDecl(ifConfigDecl))
case .functionDecl(let functionDecl):
return DeclSyntax(rewrittenDecl(
functionDecl,
modifiers: functionDecl.modifiers,
factory: functionDecl.withModifiers))
case .variableDecl(let variableDecl):
return DeclSyntax(rewrittenDecl(
variableDecl,
modifiers: variableDecl.modifiers,
factory: variableDecl.withModifiers))
case .classDecl(let classDecl):
return DeclSyntax(rewrittenDecl(
classDecl,
modifiers: classDecl.modifiers,
factory: classDecl.withModifiers))
case .structDecl(let structDecl):
return DeclSyntax(rewrittenDecl(
structDecl,
modifiers: structDecl.modifiers,
factory: structDecl.withModifiers))
case .enumDecl(let enumDecl):
return DeclSyntax(rewrittenDecl(
enumDecl,
modifiers: enumDecl.modifiers,
factory: enumDecl.withModifiers))
case .protocolDecl(let protocolDecl):
return DeclSyntax(rewrittenDecl(
protocolDecl,
modifiers: protocolDecl.modifiers,
factory: protocolDecl.withModifiers))
case .typealiasDecl(let typealiasDecl):
return DeclSyntax(rewrittenDecl(
typealiasDecl,
modifiers: typealiasDecl.modifiers,
factory: typealiasDecl.withModifiers))
default:
return decl
}
}
/// Returns a new `IfConfigDeclSyntax` equivalent to the given node, but where any file-scoped
/// declarations with effective private access have had their formal access level rewritten, if
/// necessary, to be either `private` or `fileprivate`, as determined by the formatter
/// configuration.
///
/// - Parameter ifConfigDecl: The `IfConfigDeclSyntax` to rewrite.
/// - Returns: A new `IfConfigDeclSyntax` that has possibly been rewritten.
private func rewrittenIfConfigDecl(_ ifConfigDecl: IfConfigDeclSyntax) -> IfConfigDeclSyntax {
let newClauses = ifConfigDecl.clauses.map { clause -> IfConfigClauseSyntax in
switch clause.elements {
case .statements(let codeBlockItemList)?:
return clause.withElements(.statements(rewrittenCodeBlockItems(codeBlockItemList)))
default:
return clause
}
}
return ifConfigDecl.withClauses(IfConfigClauseListSyntax(newClauses))
}
/// Returns a rewritten version of the given declaration if its modifier list contains `private`
/// that contains `fileprivate` instead.
///
/// If the modifier list is not inconsistent with the configured access level, the original
/// declaration is returned unchanged.
///
/// - Parameters:
/// - decl: The declaration to possibly rewrite.
/// - modifiers: The modifier list of the declaration (i.e., `decl.modifiers`).
/// - factory: A reference to the `decl`'s `withModifiers` instance method that is called to
/// rewrite the node if needed.
/// - Returns: A new node if the modifiers were rewritten, or the original node if not.
private func rewrittenDecl<DeclType: DeclSyntaxProtocol>(
_ decl: DeclType,
modifiers: ModifierListSyntax?,
factory: (ModifierListSyntax?) -> DeclType
) -> DeclType {
let invalidAccess: TokenKind
let validAccess: TokenKind
let diagnostic: Finding.Message
switch context.configuration.fileScopedDeclarationPrivacy.accessLevel {
case .private:
invalidAccess = .fileprivateKeyword
validAccess = .privateKeyword
diagnostic = .replaceFileprivateWithPrivate
case .fileprivate:
invalidAccess = .privateKeyword
validAccess = .fileprivateKeyword
diagnostic = .replacePrivateWithFileprivate
}
guard let modifiers = modifiers, modifiers.has(modifier: invalidAccess) else {
return decl
}
let newModifiers = modifiers.map { modifier -> DeclModifierSyntax in
let name = modifier.name
if name.tokenKind == invalidAccess {
diagnose(diagnostic, on: name)
return modifier.withName(name.withKind(validAccess))
}
return modifier
}
return factory(ModifierListSyntax(newModifiers))
}
}
extension Finding.Message {
public static let replacePrivateWithFileprivate: Finding.Message =
"replace 'private' with 'fileprivate' on file-scoped declarations"
public static let replaceFileprivateWithPrivate: Finding.Message =
"replace 'fileprivate' with 'private' on file-scoped declarations"
}
| apache-2.0 |
practicalswift/swift | validation-test/compiler_crashers_fixed/00664-swift-pattern-operator.swift | 65 | 539 | // 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
// RUN: not %target-swift-frontend %s -typecheck
func q<k:q
ss f<o : h, o : h c o.o> : p {
}
class f<o, o> {
}
protocol h {
}
protocol p {
f q: h -> h = { o
}(k, q)
protocol h : f { func f
| apache-2.0 |
practicalswift/swift | stdlib/public/core/StringUTF8Validation.swift | 2 | 8136 | private func _isUTF8MultiByteLeading(_ x: UInt8) -> Bool {
return (0xC2...0xF4).contains(x)
}
private func _isNotOverlong_F0(_ x: UInt8) -> Bool {
return (0x90...0xBF).contains(x)
}
private func _isNotOverlong_F4(_ x: UInt8) -> Bool {
return _isContinuation(x) && x <= 0x8F
}
private func _isNotOverlong_E0(_ x: UInt8) -> Bool {
return (0xA0...0xBF).contains(x)
}
private func _isNotOverlong_ED(_ x: UInt8) -> Bool {
return _isContinuation(x) && x <= 0x9F
}
private func _isASCII_cmp(_ x: UInt8) -> Bool {
return x <= 0x7F
}
internal struct UTF8ExtraInfo: Equatable {
public var isASCII: Bool
}
internal enum UTF8ValidationResult {
case success(UTF8ExtraInfo)
case error(toBeReplaced: Range<Int>)
}
extension UTF8ValidationResult: Equatable {}
private struct UTF8ValidationError: Error {}
internal func validateUTF8(_ buf: UnsafeBufferPointer<UInt8>) -> UTF8ValidationResult {
if _allASCII(buf) {
return .success(UTF8ExtraInfo(isASCII: true))
}
var iter = buf.makeIterator()
var lastValidIndex = buf.startIndex
@inline(__always) func guaranteeIn(_ f: (UInt8) -> Bool) throws {
guard let cu = iter.next() else { throw UTF8ValidationError() }
guard f(cu) else { throw UTF8ValidationError() }
}
@inline(__always) func guaranteeContinuation() throws {
try guaranteeIn(_isContinuation)
}
func _legacyInvalidLengthCalculation(_ _buffer: (_storage: UInt32, ())) -> Int {
// function body copied from UTF8.ForwardParser._invalidLength
if _buffer._storage & 0b0__1100_0000__1111_0000
== 0b0__1000_0000__1110_0000 {
// 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result
// must be nonzero and not a surrogate
let top5Bits = _buffer._storage & 0b0__0010_0000__0000_1111
if top5Bits != 0 && top5Bits != 0b0__0010_0000__0000_1101 { return 2 }
}
else if _buffer._storage & 0b0__1100_0000__1111_1000
== 0b0__1000_0000__1111_0000
{
// Prefix of 4-byte sequence. The top 5 bits of the decoded result
// must be nonzero and no greater than 0b0__0100_0000
let top5bits = UInt16(_buffer._storage & 0b0__0011_0000__0000_0111)
if top5bits != 0 && top5bits.byteSwapped <= 0b0__0000_0100__0000_0000 {
return _buffer._storage & 0b0__1100_0000__0000_0000__0000_0000
== 0b0__1000_0000__0000_0000__0000_0000 ? 3 : 2
}
}
return 1
}
func _legacyNarrowIllegalRange(buf: Slice<UnsafeBufferPointer<UInt8>>) -> Range<Int> {
var reversePacked: UInt32 = 0
if let third = buf.dropFirst(2).first {
reversePacked |= UInt32(third)
reversePacked <<= 8
}
if let second = buf.dropFirst().first {
reversePacked |= UInt32(second)
reversePacked <<= 8
}
reversePacked |= UInt32(buf.first!)
let _buffer: (_storage: UInt32, x: ()) = (reversePacked, ())
let invalids = _legacyInvalidLengthCalculation(_buffer)
return buf.startIndex ..< buf.startIndex + invalids
}
func findInvalidRange(_ buf: Slice<UnsafeBufferPointer<UInt8>>) -> Range<Int> {
var endIndex = buf.startIndex
var iter = buf.makeIterator()
_ = iter.next()
while let cu = iter.next(), !_isASCII(cu) && !_isUTF8MultiByteLeading(cu) {
endIndex += 1
}
let illegalRange = Range(buf.startIndex...endIndex)
_internalInvariant(illegalRange.clamped(to: (buf.startIndex..<buf.endIndex)) == illegalRange,
"illegal range out of full range")
// FIXME: Remove the call to `_legacyNarrowIllegalRange` and return `illegalRange` directly
return _legacyNarrowIllegalRange(buf: buf[illegalRange])
}
do {
var isASCII = true
while let cu = iter.next() {
if _isASCII(cu) { lastValidIndex &+= 1; continue }
isASCII = false
if _slowPath(!_isUTF8MultiByteLeading(cu)) {
throw UTF8ValidationError()
}
switch cu {
case 0xC2...0xDF:
try guaranteeContinuation()
lastValidIndex &+= 2
case 0xE0:
try guaranteeIn(_isNotOverlong_E0)
try guaranteeContinuation()
lastValidIndex &+= 3
case 0xE1...0xEC:
try guaranteeContinuation()
try guaranteeContinuation()
lastValidIndex &+= 3
case 0xED:
try guaranteeIn(_isNotOverlong_ED)
try guaranteeContinuation()
lastValidIndex &+= 3
case 0xEE...0xEF:
try guaranteeContinuation()
try guaranteeContinuation()
lastValidIndex &+= 3
case 0xF0:
try guaranteeIn(_isNotOverlong_F0)
try guaranteeContinuation()
try guaranteeContinuation()
lastValidIndex &+= 4
case 0xF1...0xF3:
try guaranteeContinuation()
try guaranteeContinuation()
try guaranteeContinuation()
lastValidIndex &+= 4
case 0xF4:
try guaranteeIn(_isNotOverlong_F4)
try guaranteeContinuation()
try guaranteeContinuation()
lastValidIndex &+= 4
default:
Builtin.unreachable()
}
}
return .success(UTF8ExtraInfo(isASCII: isASCII))
} catch {
return .error(toBeReplaced: findInvalidRange(buf[lastValidIndex...]))
}
}
internal func repairUTF8(_ input: UnsafeBufferPointer<UInt8>, firstKnownBrokenRange: Range<Int>) -> String {
_internalInvariant(input.count > 0, "empty input doesn't need to be repaired")
_internalInvariant(firstKnownBrokenRange.clamped(to: input.indices) == firstKnownBrokenRange)
// During this process, `remainingInput` contains the remaining bytes to process. It's split into three
// non-overlapping sub-regions:
//
// 1. `goodChunk` (may be empty) containing bytes that are known good UTF-8 and can be copied into the output String
// 2. `brokenRange` (never empty) the next range of broken bytes,
// 3. the remainder (implicit, will become the next `remainingInput`)
//
// At the beginning of the process, the `goodChunk` starts at the beginning and extends to just before the first
// known broken byte. The known broken bytes are covered in the `brokenRange` and everything following that is
// the remainder.
// We then copy the `goodChunk` into the target buffer and append a UTF8 replacement character. `brokenRange` is
// skipped (replaced by the replacement character) and we restart the same process. This time, `goodChunk` extends
// from the byte after the previous `brokenRange` to the next `brokenRange`.
var result = _StringGuts()
let replacementCharacterCount = Unicode.Scalar._replacementCharacter.withUTF8CodeUnits { $0.count }
result.reserveCapacity(input.count + 5 * replacementCharacterCount) // extra space for some replacement characters
var brokenRange: Range<Int> = firstKnownBrokenRange
var remainingInput = input
repeat {
_internalInvariant(brokenRange.count > 0, "broken range empty")
_internalInvariant(remainingInput.count > 0, "empty remaining input doesn't need to be repaired")
let goodChunk = remainingInput[..<brokenRange.startIndex]
// very likely this capacity reservation does not actually do anything because we reserved space for the entire
// input plus up to five replacement characters up front
result.reserveCapacity(result.count + remainingInput.count + replacementCharacterCount)
// we can now safely append the next known good bytes and a replacement character
result.appendInPlace(UnsafeBufferPointer(rebasing: goodChunk),
isASCII: false /* appending replacement character anyway, so let's not bother */)
Unicode.Scalar._replacementCharacter.withUTF8CodeUnits {
result.appendInPlace($0, isASCII: false)
}
remainingInput = UnsafeBufferPointer(rebasing: remainingInput[brokenRange.endIndex...])
switch validateUTF8(remainingInput) {
case .success:
result.appendInPlace(remainingInput, isASCII: false)
return String(result)
case .error(let newBrokenRange):
brokenRange = newBrokenRange
}
} while remainingInput.count > 0
return String(result)
}
| apache-2.0 |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Sources/FeatureTransactionUI/EnterAmount/AccountAuxiliaryView/AccountAuxiliaryView.swift | 1 | 4839 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import PlatformUIKit
import RxCocoa
import RxSwift
import ToolKit
import UIKit
final class AccountAuxiliaryView: UIView {
// MARK: - Public Properties
var presenter: AccountAuxiliaryViewPresenter! {
willSet {
disposeBag = DisposeBag()
}
didSet {
presenter
.titleLabel
.drive(titleLabel.rx.content)
.disposed(by: disposeBag)
// If there is a badge to be displayed, we hide the subtitle.
// We do this as this views height is hard coded in the
// `EnterAmountViewController`.
Driver.combineLatest(
presenter
.subtitleLabel,
presenter
.badgeViewVisiblity
)
.map { $0.1.isHidden ? $0.0 : .empty }
.drive(subtitleLabel.rx.content)
.disposed(by: disposeBag)
presenter
.badgeViewVisiblity
.map { $0.isHidden ? 0.0 : 24.0 }
.drive(badgeView.rx.rx_heightAnchor)
.disposed(by: disposeBag)
presenter
.badgeViewModel
.drive(badgeView.rx.badgeViewModel)
.disposed(by: disposeBag)
presenter
.badgeViewVisiblity
.map(\.inverted)
.drive(subtitleLabel.rx.visibility)
.disposed(by: disposeBag)
presenter
.badgeImageViewModel
.drive(badgeImageView.rx.viewModel)
.disposed(by: disposeBag)
presenter
.buttonEnabled
.drive(button.rx.isEnabled)
.disposed(by: disposeBag)
presenter.buttonEnabled
.map(Visibility.init(boolValue:))
.drive(disclosureImageView.rx.visibility)
.disposed(by: disposeBag)
button.rx
.controlEvent(.touchUpInside)
.bindAndCatch(to: presenter.tapRelay)
.disposed(by: disposeBag)
}
}
// MARK: - Private Properties
private let button = UIButton()
private let titleLabel = UILabel()
private let badgeView = BadgeView()
private let subtitleLabel = UILabel()
private let stackView = UIStackView()
private let separatorView = UIView()
private let disclosureImageView = UIImageView()
private let tapGestureRecognizer = UITapGestureRecognizer()
private let badgeImageView = BadgeImageView()
private var disposeBag = DisposeBag()
init() {
super.init(frame: UIScreen.main.bounds)
layer.cornerRadius = 16
layer.masksToBounds = true
layer.borderColor = UIColor(Color.semantic.light).cgColor
layer.borderWidth = 1
addSubview(stackView)
stackView.addArrangedSubview(titleLabel)
stackView.addArrangedSubview(subtitleLabel)
stackView.addArrangedSubview(badgeView)
addSubview(badgeImageView)
addSubview(separatorView)
addSubview(disclosureImageView)
addSubview(button)
button.fillSuperview()
badgeImageView.layoutToSuperview(.centerY)
badgeImageView.layout(size: .init(edge: Sizing.badge))
badgeImageView.layoutToSuperview(.leading, offset: Spacing.inner)
disclosureImageView.layoutToSuperview(.trailing, offset: -Spacing.inner)
disclosureImageView.layoutToSuperview(.centerY)
disclosureImageView.layout(size: CGSize(width: 14, height: 24))
disclosureImageView.contentMode = .scaleAspectFit
disclosureImageView.image = Icon.chevronRight.uiImage
stackView.layoutToSuperview(.centerY)
stackView.layout(
edge: .leading,
to: .trailing,
of: badgeImageView,
offset: Spacing.inner
)
stackView.layout(
edge: .trailing,
to: .leading,
of: disclosureImageView,
offset: -Spacing.inner
)
stackView.axis = .vertical
stackView.spacing = 4.0
separatorView.backgroundColor = .lightBorder
separatorView.layoutToSuperview(.leading, .trailing, .top)
separatorView.layout(dimension: .height, to: 1)
button.addTargetForTouchDown(self, selector: #selector(touchDown))
button.addTargetForTouchUp(self, selector: #selector(touchUp))
}
required init?(coder: NSCoder) { unimplemented() }
// MARK: - Private Functions
@objc
private func touchDown() {
backgroundColor = .hightlightedBackground
}
@objc
private func touchUp() {
backgroundColor = .white
}
}
| lgpl-3.0 |
hironytic/Kiretan0 | Kiretan0/View/TextInput/TextInputViewController.swift | 1 | 2355 | //
// TextInputViewController.swift
// Kiretan0
//
// Copyright (c) 2017 Hironori Ichimiya <hiron@hironytic.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import RxSwift
extension DefaultTextInputViewModel: ViewControllerCreatable {
public func createViewController() -> UIViewController {
let alertController = UIAlertController(title: self.title, message: self.detailMessage, preferredStyle: .alert)
alertController.addTextField { textField in
textField.placeholder = self.placeholder
textField.text = self.initialText
}
alertController.addAction(UIAlertAction(title: self.cancelButtonTitle, style: .cancel, handler: { _ in
alertController.dismiss(animated: true, completion: nil)
self.onCancel.onNext(())
self.onDone.onCompleted()
self.onCancel.onCompleted()
}))
alertController.addAction(UIAlertAction(title: self.doneButtonTitle, style: .default, handler: { _ in
let resultText = alertController.textFields![0].text ?? ""
alertController.dismiss(animated: true, completion: nil)
self.onDone.onNext(resultText)
self.onDone.onCompleted()
self.onCancel.onCompleted()
}))
return alertController
}
}
| mit |
Halin-Lee/SwiftTestApp | Library/AppUIKit/Example/AppUIKit/AppDelegate.swift | 1 | 2194 | //
// AppDelegate.swift
// AppUIKit
//
// Created by d.halin.lee@gmail.com on 06/23/2017.
// Copyright (c) 2017 d.halin.lee@gmail.com. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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:.
}
}
| mit |
JaSpa/swift | test/SILOptimizer/specialize_chain.swift | 4 | 2270 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -O -Xllvm -sil-disable-pass="Function Signature Optimization" -emit-sil -primary-file %s | %FileCheck %s
// We can't deserialize apply_inst with subst lists. When radar://14443304
// is fixed then we should convert this test to a SIL test.
struct YYY<T> {
@inline(never)
init(t : T) {m_t = t}
@inline(never) mutating
func AAA9(t t : T) -> Int { return AAA8(t: t) }
@inline(never) mutating
func AAA8(t t : T) -> Int { return AAA7(t: t) }
@inline(never) mutating
func AAA7(t t : T) -> Int { return AAA6(t: t) }
@inline(never) mutating
func AAA6(t t : T) -> Int { return AAA5(t: t) }
@inline(never) mutating
func AAA5(t t : T) -> Int { return AAA4(t: t) }
@inline(never) mutating
func AAA4(t t : T) -> Int { return AAA3(t: t) }
@inline(never) mutating
func AAA3(t t : T) -> Int { return AAA2(t: t) }
@inline(never) mutating
func AAA2(t t : T) -> Int { return AAA1(t: t) }
@inline(never) mutating
func AAA1(t t : T) -> Int { return AAA0(t: t) }
@inline(never) mutating
func AAA0(t t : T) -> Int { return foo(t: t) }
@inline(never) mutating
func foo(t t : T) -> Int { m_t = t; return 4 }
var m_t : T
}
func exp1() {
var II = YYY<Int>(t: 5)
print(II.AAA9(t: 4), terminator: "")
}
//CHECK: sil shared [noinline] @_T016specialize_chain3YYYV4AAA9{{[_0-9a-zA-Z]*}}FSi_Tg5
//CHECK: sil shared [noinline] @_T016specialize_chain3YYYV4AAA8{{[_0-9a-zA-Z]*}}FSi_Tg5
//CHECK: sil shared [noinline] @_T016specialize_chain3YYYV4AAA7{{[_0-9a-zA-Z]*}}FSi_Tg5
//CHECK: sil shared [noinline] @_T016specialize_chain3YYYV4AAA6{{[_0-9a-zA-Z]*}}FSi_Tg5
//CHECK: sil shared [noinline] @_T016specialize_chain3YYYV4AAA5{{[_0-9a-zA-Z]*}}FSi_Tg5
//CHECK: sil shared [noinline] @_T016specialize_chain3YYYV4AAA4{{[_0-9a-zA-Z]*}}FSi_Tg5
//CHECK: sil shared [noinline] @_T016specialize_chain3YYYV4AAA3{{[_0-9a-zA-Z]*}}FSi_Tg5
//CHECK: sil shared [noinline] @_T016specialize_chain3YYYV4AAA2{{[_0-9a-zA-Z]*}}FSi_Tg5
//CHECK: sil shared [noinline] @_T016specialize_chain3YYYV4AAA1{{[_0-9a-zA-Z]*}}FSi_Tg5
//CHECK: exp1
//CHECK: function_ref @_T016specialize_chain3YYYV{{[_0-9a-zA-Z]*}}fCSi_Tg5
//CHECK: function_ref @_T016specialize_chain3YYYV4AAA9{{[_0-9a-zA-Z]*}}FSi_Tg5
//CHECK: return
| apache-2.0 |
MinMao-Hub/MMActionSheet | Sources/MMActionSheet/MMButtonType.swift | 1 | 271 | //
// MMButtonType.swift
// swiftui
//
// Created by JefferDevs on 2021/9/13.
// Copyright © 2021 keeponrunning. All rights reserved.
//
import Foundation
public enum MMButtonType {
/// `default`
case `default`(index: Int)
/// cancel
case cancel
}
| mit |
biohazardlover/ROer | DataImporter/MonsterSpawn.swift | 1 | 4166 |
import Foundation
import CoreData
/// <map name>,<x>,<y>,<xs>,<ys>%TAB%monster%TAB%<monster name>%TAB%<mob id>,<amount>,<delay1>,<delay2>,<event>
///
/// Map name is the name of the map the monsters will spawn on. x,y are the
/// coordinates where the mob should spawn. If xs and ys are non-zero, they
/// specify the diameters of a spawn-rectangle area who's center is x,y.
/// Putting zeros instead of these coordinates will spawn the monsters randomly.
/// Note this is only the initial spawn zone, as mobs random-walk, they are free
/// to move away from their specified spawn region.
///
/// Monster name is the name the monsters will have on screen, and has no relation
/// whatsoever to their names anywhere else. It's the mob id that counts, which
/// identifies monster record in 'mob_db.txt' database of monsters. If the mob name
/// is given as "--ja--", the 'japanese name' field from the monster database is
/// used, (which, in eAthena, actually contains an english name) if it's "--en--",
/// it's the 'english name' from the monster database (which contains an uppercase
/// name used to summon the monster with a GM command).
///
/// If you add 20000 to the monster ID, the monster will be spawned in a 'big
/// version', (monster size class will increase) and if you add 10000, the 'tiny
/// version' of the monster will be created. However, this method is deprecated
/// and not recommended, as the values to add can change at a later time (20000
/// and 10000 actually stand for 2*MAX_MOB_DB and MAX_MOB_DB respectively, which
/// is defined on mob.h, and can change in the future as more mobs are created).
/// The recommended way to change a mob's size is to use the event-field (see
/// below).
///
/// Amount is the amount of monsters that will be spawned when this command is
/// executed, it is affected by spawn rates in 'battle_athena.conf'.
///
/// Delay1 and delay2 are the monster respawn delays - the first one counts the time
/// since a monster defined in this spawn was last respawned and the second one
/// counts the time since the monster of this spawn was last killed. Whichever turns
/// out to be higher will be used. If the resulting number is smaller than a random
/// value between 5 and 10 seconds, this value will be used instead. (Which is
/// normally the case if both delay values are zero.) The times are given in
/// 1/1000ths of a second.
///
/// You can specify a custom level to use for the mob different from the one of
/// the database by adjoining the level after the name with a comma. eg:
/// "Poring,50" for a name will spawn a monster with name Poring and level 50.
///
/// Event is a script event to be executed when the mob is killed. The event must
/// be in the form "NPCName::OnEventName" to execute, and the event name label
/// should start with "On". As with all events, if the NPC is an on-touch npc, the
/// player who triggers the script must be within 'trigger' range for the event to
/// work.
class MonsterSpawn: NSManagedObject {
@NSManaged var mapName: String?
@NSManaged var x: NSNumber?
@NSManaged var y: NSNumber?
@NSManaged var xs: NSNumber?
@NSManaged var ys: NSNumber?
@NSManaged var monsterName: String?
@NSManaged var monsterID: NSNumber?
@NSManaged var amount: NSNumber?
@NSManaged var delay1: NSNumber?
@NSManaged var delay2: NSNumber?
@NSManaged var event: NSNumber?
}
extension MonsterSpawn {
var map: Map? {
guard let mapName = mapName else { return nil }
let fetchRequest = NSFetchRequest<Map>(entityName: "Map")
fetchRequest.predicate = NSPredicate(format: "mapName == %@", mapName)
let maps = try? managedObjectContext?.fetch(fetchRequest)
return maps??.first
}
var monster: Monster? {
guard let monsterID = monsterID else { return nil }
let fetchRequest = NSFetchRequest<Monster>(entityName: "Monster")
fetchRequest.predicate = NSPredicate(format: "id == %@", monsterID)
let monsters = try? managedObjectContext?.fetch(fetchRequest)
return monsters??.first
}
}
| mit |
izeni-team/retrolux | Retrolux/TransformerType.swift | 1 | 420 | //
// TransformerType.swift
// Retrolux
//
// Created by Bryan Henderson on 4/14/17.
// Copyright © 2017 Bryan. All rights reserved.
//
import Foundation
public protocol TransformerType: class {
func supports(propertyType: PropertyType) -> Bool
func set(value: Any?, for property: Property, instance: Reflectable) throws
func value(for property: Property, instance: Reflectable) throws -> Any?
}
| mit |
CCIP-App/CCIP-iOS | OPass/Class+Extension/Collection+Extension.swift | 1 | 308 | //
// Collection+Extension.swift
// OPass
//
// Created by 張智堯 on 2022/8/31.
// 2022 OPass.
//
import Foundation
extension Collection {
/// A Boolean value indicating whether the collection is **not** empty.
/// - Complexity: O(1)
var isNotEmpty: Bool {
!self.isEmpty
}
}
| gpl-3.0 |
biohazardlover/ROer | Roer/StatusCalculatorCheckboxInputElementCell.swift | 1 | 928 |
import UIKit
class StatusCalculatorCheckboxInputElementCell: UICollectionViewCell {
fileprivate var checkboxInputElement: StatusCalculator.CheckboxInputElement!
@IBOutlet var elementDescriptionLabel: UILabel!
@IBOutlet var checkbox: UIButton!
@IBAction func checkboxSelected(_ sender: AnyObject) {
checkbox.isSelected = !checkbox.isSelected
checkboxInputElement.checked = checkbox.isSelected
}
}
extension StatusCalculatorCheckboxInputElementCell: StatusCalculatorElementCell {
func configureWithElement(_ element: AnyObject) {
guard let checkboxInputElement = element as? StatusCalculator.CheckboxInputElement else {
return
}
self.checkboxInputElement = checkboxInputElement
elementDescriptionLabel.text = checkboxInputElement.description
checkbox.isSelected = checkboxInputElement.checked
}
}
| mit |
robrix/Madness | Documentation/Collections.playground/Contents.swift | 1 | 374 | import Madness
import Result
let input = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
typealias Fibonacci = Parser<[Int], [Int]>.Function
func fibonacci(_ x: Int, _ y: Int) -> Fibonacci {
let combined: Fibonacci = %(x + y) >>- { (xy: Int) -> Fibonacci in
{ [ xy ] + $0 } <^> fibonacci(y, xy)
}
return combined <|> pure([])
}
parse(fibonacci(0, 1), input: input).value
| mit |
mendesbarreto/IOS | CollectionViewController/CollectionViewController/Observable.swift | 1 | 469 | //
// Common.swift
// CollectionViewController
//
// Created by Douglas Barreto on 2/19/16.
// Copyright © 2016 Douglas. All rights reserved.
//
import Foundation
public class Observable<T> {
public typealias Observer = T -> Void
public var observer: Observer?
public func observe(observer: Observer?) {
self.observer = observer
observer?(value)
}
public var value: T {
didSet {
observer?(value)
}
}
public init(_ v: T) {
value = v
}
} | mit |
335g/Prelude | Prelude/Curry.swift | 1 | 1312 | // Copyright (c) 2014 Rob Rix. All rights reserved.
// MARK: - Currying
/// Curries a binary function `f`, producing a function which can be partially applied.
public func curry<T, U, V>(f: (T, U) -> V) -> T -> U -> V {
return { x in { f(x, $0) } }
}
/// Curries a ternary function `f`, producing a function which can be partially applied.
public func curry<T, U, V, W>(f: (T, U, V) -> W) -> T -> U -> V -> W {
return { x in curry { f(x, $0, $1) } }
}
/// Curries a quaternary function, `f`, producing a function which can be partially applied.
public func curry<T, U, V, W, X>(f: (T, U, V, W) -> X) -> T -> U -> V -> W -> X {
return { x in curry { f(x, $0, $1, $2) } }
}
// MARK: - Uncurrying
/// Uncurries a curried binary function `f`, producing a function which can be applied to a tuple.
public func uncurry<T, U, V>(f: T -> U -> V) -> (T, U) -> V {
return { f($0)($1) }
}
/// Uncurries a curried ternary function `f`, producing a function which can be applied to a tuple.
public func uncurry<T, U, V, W>(f: T -> U -> V -> W) -> (T, U, V) -> W {
return { f($0)($1)($2) }
}
/// Uncurries a curried quaternary function `f`, producing a function which can be applied to a tuple.
public func uncurry<T, U, V, W, X>(f: T -> U -> V -> W -> X) -> (T, U, V, W) -> X {
return { f($0)($1)($2)($3) }
}
| mit |
cwaffles/Soulcast | Soulcast/HistoryDataSource.swift | 1 | 5385 | //
// HistoryDataSource.swift
// Soulcast
//
// Created by June Kim on 2016-11-19.
// Copyright © 2016 Soulcast-team. All rights reserved.
//
import Foundation
import UIKit
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
protocol HistoryDataSourceDelegate: class {
func willFetch()
func didFetch(_ success:Bool)
func didUpdate(_ soulCount:Int)
func didFinishUpdating(_ soulCount:Int)
func didRequestBlock(_ soul: Soul)
}
class HistoryDataSource: NSObject, SoulCatcherDelegate {
fileprivate var souls = [Soul]()
fileprivate var soulCatchers = Set<SoulCatcher>()
weak var delegate: HistoryDataSourceDelegate?
var updateTimer: Timer = Timer()
func fetch() {
//TODO:
delegate?.willFetch()
ServerFacade.getHistory({ souls in
self.catchSouls(souls)
self.delegate?.didFetch(true)
}, failure: { failureCode in
self.delegate?.didFetch(false)
})
}
func startTimer() {
updateTimer.invalidate()
updateTimer = Timer.scheduledTimer(
timeInterval: 0.25,
target: self,
selector: #selector(timerExpired),
userInfo: nil,
repeats: false)
}
func timerExpired() {
updateTimer.invalidate()
// assertSorted()
delegate?.didFinishUpdating(souls.count)
print("HistoryDataSource timerExpired!!")
}
func assertSorted() {
for soulIndex in 0...(souls.count-1) {
assert(souls[soulIndex].epoch > souls[soulIndex + 1].epoch)
}
}
func soul(forIndex index:Int) -> Soul? {
guard index < souls.count else {
return nil
}
return souls[index]
}
func indexPath(forSoul soul:Soul) -> IndexPath {
if let index = souls.index(of: soul) {
return IndexPath(row: index, section: 0)
}
return IndexPath()
}
func catchSouls(_ souls:[Soul]) {
soulCatchers.removeAll(keepingCapacity: true)
self.souls.removeAll(keepingCapacity: true)
for eachSoul in souls {
let catcher = SoulCatcher(soul: eachSoul)
catcher.delegate = self
soulCatchers.insert(catcher)
}
}
func remove(_ soul:Soul) {
if let index = souls.index(of: soul) {
souls.remove(at: index)
delegate?.didUpdate(souls.count)
}
}
func insertByEpoch(_ soul: Soul) {
var insertionIndex = 0
for eachSoul in souls {
if eachSoul.epoch > soul.epoch {
insertionIndex = indexPath(forSoul: eachSoul).row + 1
}
}
souls.insert(soul, at: insertionIndex)
delegate?.didUpdate(souls.count)
}
func debugEpoch() {
for eachSoul in souls {
print(eachSoul.epoch!)
}
print(" ")
}
//SoulCatcherDelegate
func soulDidStartToDownload(_ catcher: SoulCatcher, soul: Soul) {
//
}
func soulIsDownloading(_ catcher: SoulCatcher, progress: Float) {
//
}
func soulDidFinishDownloading(_ catcher: SoulCatcher, soul: Soul) {
insertByEpoch(soul)
soulCatchers.remove(catcher)
startTimer()
}
func soulDidFailToDownload(_ catcher: SoulCatcher) {
//
soulCatchers.remove(catcher)
}
func soulCount() -> Int {
return souls.count
}
}
extension HistoryDataSource: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return souls.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Recent Souls"
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return ""
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
switch editingStyle {
case .delete:
if let blockingSoul = soul(forIndex: indexPath.row) {
delegate?.didRequestBlock(blockingSoul)
}
case .insert: break
case .none: break
}
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return false
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: String(describing: UITableViewCell()))
if let thisSoul = soul(forIndex: indexPath.row),
let epoch = thisSoul.epoch,
let radius = thisSoul.radius {
cell.textLabel?.text = timeAgo(epoch: epoch)
cell.detailTextLabel?.text = String(round(radius*10)/10) + "km away"
cell.detailTextLabel?.textColor = UIColor.gray
cell.accessoryType = .disclosureIndicator
}
return cell
}
}
| mit |
MaddTheSane/WWDC | WWDC/SlidesDownloader.swift | 1 | 2118 | //
// SlidesDownloader.swift
// WWDC
//
// Created by Guilherme Rambo on 10/3/15.
// Copyright © 2015 Guilherme Rambo. All rights reserved.
//
import Cocoa
import Alamofire
class SlidesDownloader {
private let maxPDFLength = 16*1024*1024
typealias ProgressHandler = (downloaded: Double, total: Double) -> Void
typealias CompletionHandler = (success: Bool, data: NSData?) -> Void
var session: Session
init(session: Session) {
self.session = session
}
func downloadSlides(completionHandler: CompletionHandler, progressHandler: ProgressHandler?) {
guard session.slidesURL != "" else { return completionHandler(success: false, data: nil) }
guard let slidesURL = NSURL(string: session.slidesURL) else { return completionHandler(success: false, data: nil) }
Alamofire.download(Method.GET, slidesURL.absoluteString) { tempURL, response in
if let data = NSData(contentsOfURL: tempURL) {
mainQ {
// this operation can fail if the PDF file is too big, Realm currently supports blobs of up to 16MB
if data.length < self.maxPDFLength {
WWDCDatabase.sharedDatabase.doChanges {
self.session.slidesPDFData = data
}
} else {
print("Error saving slides data to database, the file is too big to be saved")
}
completionHandler(success: true, data: data)
}
} else {
completionHandler(success: false, data: nil)
}
do {
try NSFileManager.defaultManager().removeItemAtURL(tempURL)
} catch {
print("Error removing temporary PDF file")
}
return tempURL
}.progress { _, totalBytesRead, totalBytesExpected in
mainQ { progressHandler?(downloaded: Double(totalBytesRead), total: Double(totalBytesExpected)) }
}
}
} | bsd-2-clause |
dominickhera/Projects | personal/iOU/iOU 4.0/EmailViewController.swift | 2 | 1040 | //
// EmailViewController.swift
// iOU 4.0
//
// Created by Dominick Hera on 2/18/15.
// Copyright (c) 2015 Posa. All rights reserved.
//
import Foundation
import MessageUI
class EmailComposer: NSObject, MFMailComposeViewControllerDelegate {
func canSendMail() -> Bool {
return MFMailComposeViewController.canSendMail()
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["posacorporations@gmail.com"])
mailComposerVC.setSubject("")
mailComposerVC.setMessageBody("", isHTML: false)
return mailComposerVC
}
// MARK: MFMailComposeViewControllerDelegate Method
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
}
| apache-2.0 |
gdfairclough/EmotionalSwift | EmotionalSwift/HTTPMethod.swift | 1 | 290 | //
// HTTPMethod.swift
// EmotionalSwift
//
// Created by Gerald Fairclough, Jr on 2/26/17.
// Copyright © 2017 Faircoder. All rights reserved.
//
import Foundation
///HTTP methods
enum HTTPmethod : String {
case POST = "POST"
case GET = "GET"
case PUT = "PUT"
}
| mit |
Eonil/Monolith.Swift | Text/Sources/Parsing/Stepping.swift | 2 | 8690 | //
// Parsing.swift
// EDXC
//
// Created by Hoon H. on 10/14/14.
// Copyright (c) 2014 Eonil. All rights reserved.
//
import Foundation
extension Parsing {
/// Represents parsing state.
///
/// Parsing state is represneted node-list.
/// Node-list can be empty by a result of successful parsing. (in case
/// of repetition rule)
///
/// If parsing is unsuccessful, the node-list will be `nil`. contain one or more
/// error-node. Upper rule can decide what to do with errors.
/// If parsing is successful, the resulting node list can be empty or
/// If node-list is empty (`count == 0`), it means parser couldn't find
/// any matching, and the composition is ignored to try next pattern.
/// This is a normal pattern matching procedure, and the parser will
/// continue parsing.
///
/// If node-list is non-empty and contains any error-node, it just means
/// *error* state. Error-node must be placed at the end of the node-list.
/// Parser will stop parsing ASAP.
///
/// If node-list is non-empty and contains no error-node, it means *ready*
/// state. Parser found propr matching pattern, and continues parsing.
///
/// If node-list is non-empty and contains some mark-node, it means one
/// or more marker has been found at proper position, and that means
/// current syntax pattern must be satisfied. Parser will force to find
/// current pattern, and will emit an error if current pattern cannot be
/// completed. This marking-effect will be applied only to current rule
/// composition, and disappear when parser switches to another rule.
public struct Stepping : Printable {
public let status:Status
public let location:Cursor
public let nodes:NodeList
init(status:Status, location:Cursor, nodes:NodeList) {
assert(status != Status.Match || nodes.count == 0 || nodes.last!.endCursor <= location)
self.status = status
self.location = location
self.nodes = nodes
}
init(status:Status, location:Cursor, nodes:[Node]) {
self.init(status: status, location: location, nodes: NodeList(nodes))
}
var match:Bool {
get {
return status == Status.Match
}
}
/// Mismatch means the pattern does not fit to the source.
var mismatch:Bool {
get {
return status == Status.Mismatch
}
}
/// Error is defined only when there's some node result.
var error:Bool {
get {
assert(status != Status.Error || nodes.hasAnyError())
return status == Status.Error
}
}
var marking:Bool {
get {
return nodes.hasAnyMarkingAtCurrentLevel()
}
}
func reoriginate(rule r1:Rule) -> Stepping {
precondition(match)
func reoriginateAll(n:Stepping.Node) -> Stepping.Node {
return n.reorigination(rule: r1)
}
let ns2 = nodes.map(reoriginateAll)
return Stepping(status: status, location: location, nodes: ns2)
}
func remark(m:Node.Mark) -> Stepping {
assert(match)
let ns1 = self.nodes
let ns2 = ns1.map({ n in return n.remark(m) }) as NodeList
return Stepping.match(location: self.location, nodes: ns2)
}
static func mismatch(location l1:Cursor) -> Stepping {
return Stepping(status: Status.Mismatch, location: l1, nodes: NodeList())
}
static func match(location l1:Cursor, nodes ns1:NodeList) -> Stepping {
assert(ns1.count == 0 || l1 >= ns1.last!.endCursor)
assert(ns1.hasAnyError() == false)
return Stepping(status: Status.Match, location: l1, nodes: ns1)
}
/// Error status should return some parsed node to provide debugging information to users.
static func error(location l1:Cursor, nodes ns1:NodeList, message m1:String) -> Stepping {
assert(ns1.count == 0 || l1 >= ns1.last!.endCursor)
// assert(ns1.hasAnyError() == false) // Discovered
return Stepping(status: Status.Error, location: l1, nodes: ns1 + NodeList([Node(location: l1, error: m1)]))
}
// static func discover(location l1:Cursor, nodes ns1:NodeList) -> Stepping {
// assert(ns1.count == 0 || l1 >= ns1.last!.endCursor)
//
// if ns1.hasAnyError() {
// return Parsing.error(location: l1, nodes: ns1, message m1:String)
// } else {
// return Parsing.match(location: l1, nodes: ns1)
// }
// }
public enum Status {
case Mismatch ///< No match with no error. Parser will return no result and this status can be ignored safely.
case Match ///< Exact match found. Good result. Parser will return fully established tree.
case Error ///< No match with some error. Parser quit immediately and will return some result containing error information in tree.
}
public struct NodeList : Printable {
init() {
_items = []
}
init(_ ns1:[Node]) {
_items = ns1
}
public var count:Int {
get {
return _items.count
}
}
public var first:Node? {
get {
return _items.first
}
}
public var last:Node? {
get {
return _items.last
}
}
public var description:String {
get {
return "\(_items)"
}
}
public subscript(index:Int) -> Node {
get {
return _items[index]
}
}
public func map(t:Node->Node) -> NodeList {
return NodeList(map(t))
}
public func map<U>(t:Node->U) -> [U] {
return _items.map(t)
}
public func reduce<U>(v:U, combine c:(U,Node)->U) -> U {
return _items.reduce(v, combine: c)
}
public func filter(f:Node->Bool) -> NodeList {
return NodeList(_items.filter(f))
}
////
private let _items:[Node]
private func hasAnyError() -> Bool {
/// TODO: Optimisation.
return _items.reduce(false, combine: { u, n in return u || n.hasAnyError() })
}
private func hasAnyMarkingAtCurrentLevel() -> Bool {
/// TODO: Optimisation.
return _items.reduce(false, combine: { u, n in return u || (n.marking != nil) })
}
}
public struct Node {
var startCursor:Cursor
var endCursor:Cursor
var origin:Rule?
var marking:Mark?
var subnodes:NodeList = NodeList()
let error:String? // Read-only for easier optimization. Once error-node will be eternally an error.
init(start:Cursor, end:Cursor, origin:Rule?, subnodes:NodeList) {
self.init(start: start, end: end, origin: origin, marking: nil, subnodes: subnodes, error: nil)
}
// init(start:Cursor, end:Cursor) {
// self.init(start: start, end: end, origin: nil, marking: nil, subnodes: NodeList())
// }
init(start:Cursor, end:Cursor) {
self.init(start: start, end: end, origin: nil, subnodes: NodeList([]))
}
init(location:Cursor, error:String) {
self.init(start: location, end: location, origin: nil, marking: nil, subnodes: NodeList(), error: error)
}
var content:String {
get {
return startCursor.content(to: endCursor)
}
}
func reorigination(rule r1:Rule) -> Node {
var n2 = self
n2.origin = r1
return n2
}
func remark(m:Mark) -> Node {
var n2 = self
n2.marking = m
return n2
}
/// Rule name will be reported if `expectation` is `nil`.
struct Mark {
let expectation: String?
init(expectation: String?) {
self.expectation = expectation
}
}
// enum Mark {
// case None
// case Flag(expectation:String)
//
// private var none:Bool {
// get {
// switch self {
// case let None: return true
// default: return false
// }
// }
// }
// private var expectation:String? {
// get {
// switch self {
// case let Flag(state): return state.expectation
// default: return nil
// }
// }
// }
// }
////
private var _cache_any_error = false
private init(start:Cursor, end:Cursor, origin:Rule?, marking:Mark?, subnodes:NodeList, error:String?) {
assert(start <= end)
self.startCursor = start
self.endCursor = end
self.origin = origin
self.marking = marking
self.subnodes = subnodes
self.error = error
}
private func hasAnyError() -> Bool {
return (error != nil) || subnodes.hasAnyError()
}
}
// struct Error {
// let message:String
// }
}
}
extension Parsing.Stepping {
public var description:String {
get {
return "Parsing(status: \(status), location: \(location), nodes: \(nodes))"
}
}
}
func + (left:Parsing.Stepping.NodeList, right:Parsing.Stepping.NodeList) -> Parsing.Stepping.NodeList {
return Parsing.Stepping.NodeList(left._items + right._items)
}
func += (inout left:Parsing.Stepping.NodeList, right:Parsing.Stepping.NodeList) {
left = left + right
}
extension Parsing.Stepping.NodeList {
var marking:Bool {
get {
return hasAnyMarkingAtCurrentLevel()
}
}
}
| mit |
ishkawa/APIKit | Demo.playground/Contents.swift | 2 | 1721 | import PlaygroundSupport
import Foundation
import APIKit
PlaygroundPage.current.needsIndefiniteExecution = true
//: Step 1: Define request protocol
protocol GitHubRequest: Request {
}
extension GitHubRequest {
var baseURL: URL {
return URL(string: "https://api.github.com")!
}
}
//: Step 2: Create model object
struct RateLimit {
let count: Int
let resetDate: Date
init?(dictionary: [String: AnyObject]) {
guard let count = dictionary["rate"]?["limit"] as? Int else {
return nil
}
guard let resetDateString = dictionary["rate"]?["reset"] as? TimeInterval else {
return nil
}
self.count = count
self.resetDate = Date(timeIntervalSince1970: resetDateString)
}
}
//: Step 3: Define request type conforming to created request protocol
// https://developer.github.com/v3/rate_limit/
struct GetRateLimitRequest: GitHubRequest {
typealias Response = RateLimit
var method: HTTPMethod {
return .get
}
var path: String {
return "/rate_limit"
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
guard let dictionary = object as? [String: AnyObject],
let rateLimit = RateLimit(dictionary: dictionary) else {
throw ResponseError.unexpectedObject(object)
}
return rateLimit
}
}
//: Step 4: Send request
let request = GetRateLimitRequest()
Session.send(request) { result in
switch result {
case .success(let rateLimit):
print("count: \(rateLimit.count)")
print("reset: \(rateLimit.resetDate)")
case .failure(let error):
print("error: \(error)")
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/04975-swift-sourcemanager-getmessage.swift | 11 | 342 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct S<h : T where S<Int>(v: AnyObject) {
enum S<T where g: a {
func a() {
if true {
class c : a {
{
protocol A : d where g<T where T.E == a(h:as b).E == ")
class
case c,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/16637-no-stacktrace.swift | 11 | 217 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
for b
var {
let h = == {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/27499-llvm-bitstreamcursor-read.swift | 4 | 216 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum S<e{struct A
class A?enum A<e>:d{let f=A{
| mit |
eurofurence/ef-app_ios | Packages/EurofurenceComponents/Tests/ScheduleComponentTests/Presenter Tests/Searching/WhenSceneChangesSearchScopeToAllEvents_SchedulePresenterShould.swift | 1 | 1796 | import EurofurenceModel
import ScheduleComponent
import XCTest
class WhenSceneChangesSearchScopeToAllEvents_SchedulePresenterShould: XCTestCase {
func testTellTheSearchViewModelToFilterToFavourites() {
let searchViewModel = CapturingScheduleSearchViewModel()
let viewModelFactory = FakeScheduleViewModelFactory(searchViewModel: searchViewModel)
let context = SchedulePresenterTestBuilder().with(viewModelFactory).build()
context.simulateSceneDidLoad()
context.scene.delegate?.scheduleSceneDidChangeSearchScopeToAllEvents()
XCTAssertTrue(searchViewModel.didFilterToAllEvents)
}
func testTellTheSearchResultsToHide() {
let context = SchedulePresenterTestBuilder().build()
context.simulateSceneDidLoad()
context.scene.delegate?.scheduleSceneDidChangeSearchScopeToAllEvents()
XCTAssertTrue(context.scene.didHideSearchResults)
}
func testNotHideTheSearchResultsWhenQueryActive() {
let context = SchedulePresenterTestBuilder().build()
context.simulateSceneDidLoad()
context.scene.delegate?.scheduleSceneDidUpdateSearchQuery("Something")
context.scene.delegate?.scheduleSceneDidChangeSearchScopeToAllEvents()
XCTAssertFalse(context.scene.didHideSearchResults)
}
func testNotTellTheSearchResultsToAppearWhenQueryChangesToEmptyString() {
let context = SchedulePresenterTestBuilder().build()
context.simulateSceneDidLoad()
context.scene.delegate?.scheduleSceneDidChangeSearchScopeToFavouriteEvents()
context.scene.delegate?.scheduleSceneDidChangeSearchScopeToAllEvents()
context.scene.delegate?.scheduleSceneDidUpdateSearchQuery("")
XCTAssertEqual(1, context.scene.didShowSearchResultsCount)
}
}
| mit |
mozilla-mobile/focus | XCUITest/QuickAddAutocompleteURLTest.swift | 1 | 1041 | /* 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 XCTest
class QuickAddAutocompleteURLTest: BaseTestCase {
override func setUp() {
super.setUp()
dismissFirstRunUI()
}
override func tearDown() {
app.terminate()
super.tearDown()
}
func testURLContextMenu() {
let urlBarTextField = app.textFields["URLBar.urlText"]
loadWebPage("reddit.com")
urlBarTextField.press(forDuration: 1.0)
waitforHittable(element: app.cells["Add Custom URL"])
app.cells["Add Custom URL"].tap()
waitforHittable(element: app.textFields["URLBar.urlText"])
urlBarTextField.tap()
urlBarTextField.typeText("reddit.c\n")
guard let text = urlBarTextField.value as? String else {
XCTFail()
return
}
XCTAssert(text == "www.reddit.com")
}
}
| mpl-2.0 |
massada/swift-collections | Collections/QueueType.swift | 1 | 1572 | //
// QueueType.swift
// Collections
//
// Copyright (c) 2016 José Massada <jose.massada@gmail.com>
//
// 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.
//
/// A *collection* where elements are kept in order. Supports adding an element
/// to the head and removing the oldest added element from the front.
public protocol QueueType : Sequence, ExpressibleByArrayLiteral {
/// Returns the number of elements.
var count: Int { get }
/// Returns `true` if `self` is empty.
var isEmpty: Bool { get }
/// Clears `self`, removing all elements.
mutating func clear()
/// Enqueues `newElement` to `self`.
mutating func enqueue(_ newElement: Iterator.Element)
/// Dequeues the oldest added element of `self` and returns it.
///
/// - Requires: `self.count > 0`.
mutating func dequeue() -> Iterator.Element
/// Returns the oldest added element of `self`, or `nil` if `self` is
/// empty.
var front: Iterator.Element? { get }
}
// Default implementations
extension QueueType {
public var isEmpty: Bool {
return count == 0
}
}
| apache-2.0 |
yq616775291/DiliDili-Fun | DiliDili/Classes/Home/Model/FQModel.swift | 1 | 252 | //
// FQModel.swift
// DiliDili
//
// Created by yq on 16/3/10.
// Copyright © 2016年 yq. All rights reserved.
//
import UIKit
class FQModel: NSObject {
var moduleImageName:String?
var moduleName:String?
var moduleID:String?
}
| mit |
leonardo-ferreira07/OnTheMap | OnTheMap/OnTheMap/API/Clients/StudentLocationClient.swift | 1 | 2797 | //
// StudentLocationClient.swift
// OnTheMap
//
// Created by Leonardo Vinicius Kaminski Ferreira on 10/10/17.
// Copyright © 2017 Leonardo Ferreira. All rights reserved.
//
import Foundation
import CoreLocation
struct StudentLocationClient {
static fileprivate let headers: [String: String] = ["X-Parse-Application-Id": "QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", "X-Parse-REST-API-Key": "QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY"]
static func getStudentsLocations(_ completion: @escaping (_ success: Bool) -> Void) {
let url = APIClient.buildURL(["limit": "100", "order": "-updatedAt"] as [String: AnyObject], withHost: Constants.apiHostParseClasses, withPathExtension: Constants.apiPathUdacityParseStudentLocations)
_ = APIClient.performRequest(url, headerValues: headers, completion: { (dict, error) in
guard let dict = dict else {
completion(false)
return
}
if let array = dict[StudentLocationKeys.results.rawValue] as? [[String: AnyObject]] {
MemoryStorage.shared.studentsLocations.removeAll()
for object in array {
MemoryStorage.shared.studentsLocations.append(StudentLocation(withDictionary: object))
}
completion(true)
} else {
completion(false)
}
}) {
}
}
static func postStudentLocation(mapString: String, mediaURL: String, coordinate: CLLocationCoordinate2D, completion: @escaping (_ success: Bool) -> Void) {
guard let id = MemoryStorage.shared.session?.account.id, let firstName = MemoryStorage.shared.user?.user.firstName, let lastName = MemoryStorage.shared.user?.user.lastName else {
completion(false)
return
}
let url = APIClient.buildURL(withHost: Constants.apiHostParseClasses, withPathExtension: Constants.apiPathUdacityParseStudentLocations)
let jsonBody = ["uniqueKey": id,
"firstName": firstName,
"lastName": lastName,
"mapString": mapString,
"mediaURL": mediaURL,
"latitude": coordinate.latitude,
"longitude": coordinate.longitude] as [String: AnyObject]
_ = APIClient.performRequest(url, method: .POST, jsonBody: jsonBody, headerValues: headers, completion: { (dict, error) in
guard dict != nil else {
completion(false)
return
}
completion(true)
}) {
}
}
}
| mit |
DarthRumata/EventsTree | EventsTreeiOSExample/Sources/IOSExample/Main/TreeNodeView.swift | 1 | 5380 | //
// TreeNodeView.swift
// EventNodeExample
//
// Created by Rumata on 6/22/17.
// Copyright © 2017 DarthRumata. All rights reserved.
//
import Foundation
import UIKit
import EventsTree
import AMPopTip
extension TreeNodeView {
enum Events {
struct NodeSelected: Event { let view: TreeNodeView? }
struct EventImitationStarted: Event { let sharedTime: SharedTime }
struct UserGeneratedEventRaised: Event {}
}
class SharedTime {
var startTime: DispatchTime = .now()
}
}
@IBDesignable
class TreeNodeView: UIView {
@IBInspectable
var title: String = "" {
didSet {
self.titleLabel.text = title
}
}
var eventNode: EventNode! {
didSet {
addInitialHandlers()
}
}
@IBOutlet fileprivate weak var titleLabel: UILabel!
@IBOutlet fileprivate weak var eventDirectionMarker: UIImageView!
fileprivate var selectedState: SelectedState = .normal {
didSet {
updateBackground()
}
}
fileprivate var highlightedState: HighlightedState = .none {
didSet {
updateIcon()
}
}
fileprivate let popTip = PopTip()
// MARK: Init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let nib = UINib(nibName: String(describing: TreeNodeView.self), bundle: nil)
let content = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
addSubview(content)
content.frame = bounds
}
override func awakeFromNib() {
super.awakeFromNib()
layer.cornerRadius = 5
layer.masksToBounds = true
}
// MARK: Actions
@IBAction func didTapOnView() {
let event = Events.NodeSelected(view: self)
eventNode.raise(event: event)
}
}
fileprivate extension TreeNodeView {
/// TODO: Can be optimized by merging to states in OptionSet
enum SelectedState {
case normal, selected
var color: UIColor {
switch self {
case .normal:
return .lightGray
case .selected:
return .green
}
}
}
enum HighlightedState {
case onPropagate, onRaise, none
var icon: UIImage? {
switch self {
case .onPropagate: return UIImage(named: "arrowDown")
case .onRaise: return UIImage(named: "arrowUp")
case .none: return nil
}
}
}
func addInitialHandlers() {
eventNode.addHandler { [weak self] (event: Events.NodeSelected) in
guard let strongSelf = self else { return }
let newState: SelectedState = event.view == strongSelf ? .selected : .normal
if strongSelf.selectedState != newState {
strongSelf.selectedState = newState
}
}
eventNode.addHandler { [weak self] (event: MainViewController.Events.AddHandler) in
guard let strongSelf = self else { return }
guard strongSelf.selectedState == .selected else { return }
let handlerInfo = event.info
strongSelf.eventNode.addHandler(handlerInfo.handlerMode) { (event: Events.UserGeneratedEventRaised) in
strongSelf.popTip.show(
text: handlerInfo.tipText,
direction: .down,
maxWidth: 150,
in: strongSelf.superview!,
from: strongSelf.frame,
duration: 2
)
}
}
eventNode.addHandler { [weak self] (event: MainViewController.Events.SendTestEvent) in
guard let strongSelf = self else { return }
guard strongSelf.selectedState == .selected else { return }
let flowImitationEvent = Events.EventImitationStarted(sharedTime: SharedTime())
strongSelf.eventNode.raise(event: flowImitationEvent)
let userEvent = Events.UserGeneratedEventRaised()
strongSelf.eventNode.raise(event: userEvent)
}
eventNode.addHandler { [weak self] (event: MainViewController.Events.RemoveHandler) in
guard let strongSelf = self else { return }
guard strongSelf.selectedState == .selected else { return }
strongSelf.eventNode.removeHandlers(for: Events.UserGeneratedEventRaised.self)
}
eventNode.addHandler(.onPropagate) { [weak self] (event: Events.EventImitationStarted) in
guard let strongSelf = self else {
return
}
/// TODO: Need to provide more convient implimentation via separate serial queue
let sharedTime = event.sharedTime
let scheduledTime = sharedTime.startTime
sharedTime.startTime = sharedTime.startTime + 1
DispatchQueue.main.asyncAfter(deadline: scheduledTime) {
strongSelf.highlightedState = .onPropagate
DispatchQueue.main.asyncAfter(deadline: scheduledTime + 1) {
strongSelf.highlightedState = .none
}
}
}
eventNode.addHandler(.onRaise) { [weak self] (event: Events.EventImitationStarted) in
guard let strongSelf = self else {
return
}
let sharedTime = event.sharedTime
let scheduledTime = sharedTime.startTime
sharedTime.startTime = sharedTime.startTime + 1
DispatchQueue.main.asyncAfter(deadline: scheduledTime) {
strongSelf.highlightedState = .onRaise
DispatchQueue.main.asyncAfter(deadline: scheduledTime + 1) {
if strongSelf.highlightedState == .onRaise {
strongSelf.highlightedState = .none
}
}
}
}
}
func updateBackground() {
backgroundColor = selectedState.color
}
func updateIcon() {
eventDirectionMarker.image = highlightedState.icon
}
}
| mit |
scotlandyard/expocity | expocity/View/Chat/DisplayAnnotations/VChatDisplayAnnotations.swift | 1 | 9649 | import UIKit
class VChatDisplayAnnotations:UIView
{
weak var controller:CChatDisplayAnnotations!
weak var shadeTop:VChatDisplayAnnotationsShade!
weak var shadeBottom:VChatDisplayAnnotationsShade!
weak var list:VChatDisplayAnnotationsList!
weak var tutorial:VChatDisplayAnnotationsTutorial!
weak var placer:VChatDisplayAnnotationsPlacer!
weak var editText:VChatDisplayAnnoationsEdit!
weak var layoutShadeTopHeight:NSLayoutConstraint!
weak var layoutShadeBottomHeight:NSLayoutConstraint!
weak var layoutPlacerTop:NSLayoutConstraint!
weak var layoutPlacerHeight:NSLayoutConstraint!
weak var layoutEditTextBottom:NSLayoutConstraint!
private let kEditTextHeight:CGFloat = 45
private let kAnimationDuration:TimeInterval = 0.3
private let kWaitingTime:TimeInterval = 0.1
convenience init(controller:CChatDisplayAnnotations)
{
self.init()
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let shadeTop:VChatDisplayAnnotationsShade = VChatDisplayAnnotationsShade(borderTop:false, borderBottom:true)
self.shadeTop = shadeTop
let shadeBottom:VChatDisplayAnnotationsShade = VChatDisplayAnnotationsShade(borderTop:true, borderBottom:false)
self.shadeBottom = shadeBottom
let list:VChatDisplayAnnotationsList = VChatDisplayAnnotationsList(controller:controller)
self.list = list
let tutorial:VChatDisplayAnnotationsTutorial = VChatDisplayAnnotationsTutorial(controller:controller)
self.tutorial = tutorial
let placer:VChatDisplayAnnotationsPlacer = VChatDisplayAnnotationsPlacer(controller:controller)
self.placer = placer
let editText:VChatDisplayAnnoationsEdit = VChatDisplayAnnoationsEdit(controller:controller)
self.editText = editText
shadeTop.addSubview(list)
shadeTop.addSubview(tutorial)
addSubview(shadeTop)
addSubview(shadeBottom)
addSubview(placer)
addSubview(editText)
let views:[String:UIView] = [
"shadeTop":shadeTop,
"shadeBottom":shadeBottom,
"list":list,
"tutorial":tutorial,
"placer":placer,
"editText":editText]
let metrics:[String:CGFloat] = [
"editTextHeight":kEditTextHeight]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[placer]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[shadeTop]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[shadeBottom]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[list]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[tutorial]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[editText]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[shadeTop]",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:[shadeBottom]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[list]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[tutorial]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:[editText(editTextHeight)]",
options:[],
metrics:metrics,
views:views))
layoutShadeTopHeight = NSLayoutConstraint(
item:shadeTop,
attribute:NSLayoutAttribute.height,
relatedBy:NSLayoutRelation.equal,
toItem:nil,
attribute:NSLayoutAttribute.notAnAttribute,
multiplier:1,
constant:0)
layoutShadeBottomHeight = NSLayoutConstraint(
item:shadeBottom,
attribute:NSLayoutAttribute.height,
relatedBy:NSLayoutRelation.equal,
toItem:nil,
attribute:NSLayoutAttribute.notAnAttribute,
multiplier:1,
constant:0)
layoutPlacerTop = NSLayoutConstraint(
item:placer,
attribute:NSLayoutAttribute.top,
relatedBy:NSLayoutRelation.equal,
toItem:self,
attribute:NSLayoutAttribute.top,
multiplier:1,
constant:0)
layoutPlacerHeight = NSLayoutConstraint(
item:placer,
attribute:NSLayoutAttribute.height,
relatedBy:NSLayoutRelation.equal,
toItem:nil,
attribute:NSLayoutAttribute.notAnAttribute,
multiplier:1,
constant:0)
layoutEditTextBottom = NSLayoutConstraint(
item:editText,
attribute:NSLayoutAttribute.bottom,
relatedBy:NSLayoutRelation.equal,
toItem:self,
attribute:NSLayoutAttribute.bottom,
multiplier:1,
constant:0)
addConstraint(layoutShadeTopHeight)
addConstraint(layoutShadeBottomHeight)
addConstraint(layoutPlacerTop)
addConstraint(layoutPlacerHeight)
addConstraint(layoutEditTextBottom)
layoutShades()
NotificationCenter.default.addObserver(
self,
selector:#selector(notifiedKeyboardChanged(sender:)),
name:NSNotification.Name.UIKeyboardWillChangeFrame,
object:nil)
}
deinit
{
NotificationCenter.default.removeObserver(self)
}
override func layoutSubviews()
{
let delayLayout:TimeInterval = kWaitingTime
DispatchQueue.main.async
{ [weak self] in
self?.shadeTop.alpha = 0
self?.shadeBottom.alpha = 0
DispatchQueue.main.asyncAfter(deadline:DispatchTime.now() + delayLayout)
{ [weak self] in
self?.layoutShades()
self?.animateShades()
}
}
super.layoutSubviews()
}
//MARK: notified
func notifiedKeyboardChanged(sender notification:Notification)
{
let userInfo:[AnyHashable:Any] = notification.userInfo!
let keyboardFrameValue:NSValue = userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue
let keyRect:CGRect = keyboardFrameValue.cgRectValue
let yOrigin = keyRect.origin.y
let screenHeight:CGFloat = UIScreen.main.bounds.size.height
let keyboardHeight:CGFloat
if yOrigin < screenHeight
{
keyboardHeight = screenHeight - yOrigin
}
else
{
keyboardHeight = 0
}
layoutEditTextBottom.constant = -keyboardHeight
UIView.animate(withDuration:kAnimationDuration)
{ [weak self] in
self?.layoutIfNeeded()
}
}
//MARK: private
private func layoutShades()
{
let imageRect:CGRect = controller.controllerChat.displayImageRect()
let screenRect:CGRect = UIScreen.main.bounds
let topHeight:CGFloat = imageRect.minY
let bottomHeight:CGFloat = screenRect.maxY - imageRect.maxY
layoutShadeTopHeight.constant = topHeight
layoutShadeBottomHeight.constant = bottomHeight
layoutPlacerTop.constant = topHeight
layoutPlacerHeight.constant = imageRect.size.height
}
private func modelAtIndex(index:IndexPath) -> MChatDisplayAnnotationsItem
{
let item:MChatDisplayAnnotationsItem = controller.controllerChat.model.annotations.items[index.item]
return item
}
//MARK: public
func animateShades()
{
UIView.animate(withDuration:kAnimationDuration)
{ [weak self] in
self?.shadeTop.alpha = 1
self?.shadeBottom.alpha = 1
}
}
func addAnnotation()
{
list.alpha = 0
tutorial.tutorialPlaceMark()
placer.addAnnotation()
}
func cancelAnnotation()
{
list.alpha = 1
tutorial.closeTutorial()
placer.cancelAnnotation()
}
func confirmAnnotation()
{
tutorial.tutorialText()
editText.beginEditingText()
placer.reloadItems()
}
func confirmTextAnnotation()
{
list.alpha = 1
list.collectionView.reloadData()
tutorial.closeTutorial()
placer.reloadItems()
}
}
| mit |
jsslai/Action | UIButton+Rx.swift | 1 | 3170 | import UIKit
import RxSwift
import RxCocoa
import ObjectiveC
public extension UIButton {
/// Binds enabled state of action to button, and subscribes to rx_tap to execute action.
/// These subscriptions are managed in a private, inaccessible dispose bag. To cancel
/// them, set the rx_action to nil or another action.
public var rx_action: CocoaAction? {
get {
var action: CocoaAction?
doLocked {
action = objc_getAssociatedObject(self, &AssociatedKeys.Action) as? Action
}
return action
}
set {
doLocked {
// Store new value.
objc_setAssociatedObject(self, &AssociatedKeys.Action, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// This effectively disposes of any existing subscriptions.
self.resetActionDisposeBag()
// Set up new bindings, if applicable.
if let action = newValue {
action
.enabled
.bindTo(self.rx.isEnabled)
.addDisposableTo(self.actionDisposeBag)
// Technically, this file is only included on tv/iOS platforms,
// so this optional will never be nil. But let's be safe 😉
let lookupControlEvent: ControlEvent<Void>?
#if os(tvOS)
lookupControlEvent = self.rx.primaryAction
#elseif os(iOS)
lookupControlEvent = self.rx.tap
#endif
guard let controlEvent = lookupControlEvent else {
return
}
controlEvent
.subscribe(onNext: { _ in _ = action.execute()})
.addDisposableTo(self.actionDisposeBag)
}
}
}
}
}
// Note: Actions performed in this extension are _not_ locked
// So be careful!
internal extension NSObject {
internal struct AssociatedKeys {
static var Action = "rx_action"
static var DisposeBag = "rx_disposeBag"
}
// A dispose bag to be used exclusively for the instance's rx_action.
internal var actionDisposeBag: DisposeBag {
var disposeBag: DisposeBag
if let lookup = objc_getAssociatedObject(self, &AssociatedKeys.DisposeBag) as? DisposeBag {
disposeBag = lookup
} else {
disposeBag = DisposeBag()
objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, disposeBag, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return disposeBag
}
// Resets the actionDisposeBag to nil, disposeing of any subscriptions within it.
internal func resetActionDisposeBag() {
objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
// Uses objc_sync on self to perform a locked operation.
internal func doLocked(_ closure: () -> Void) {
objc_sync_enter(self); defer { objc_sync_exit(self) }
closure()
}
}
| mit |
advantys/workflowgen-templates | integration/azure/authentication/azure-v1/auth-code-pkce/WorkflowGenExample/ios/JWT.swift | 1 | 5420 | import Foundation
import CommonCrypto
@objc(JWT)
class JWT : NSObject, RCTBridgeModule {
static func moduleName() -> String! { return "JWT" }
static func requiresMainQueueSetup() -> Bool {
return false
}
@objc(decode:resolve:reject:)
func decode(args: NSDictionary!, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
guard
let header = args["header"] as? String,
let payload = args["payload"] as? String else {
reject(
"jwt_decode_error",
"You must specify the header and the payload.",
NSError(domain: "JWT", code: 1, userInfo: nil)
)
return
}
let decodePart = { (part: String) throws -> NSDictionary in
try JSONSerialization.jsonObject(
with: NSData(base64UrlEncodedString: part)! as Data,
options: []
) as! NSDictionary
}
let decodedHeader: NSDictionary
let decodedPayload: NSDictionary
do {
decodedHeader = try decodePart(header)
decodedPayload = try decodePart(payload)
} catch {
reject(
"jwt_decode_error",
"Could not decode the header or the payload.",
NSError(domain: "JWT", code: 2, userInfo: nil)
)
return
}
resolve([decodedHeader, decodedPayload])
}
@objc(verify:resolve:reject:)
func verify(args: NSDictionary!, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
guard
let header = args["header"] as? String,
let payload = args["payload"] as? String,
let signature = args["signature"] as? String,
var publicKeyArr = args["publicKey"] as? [String] else {
reject(
"jwt_verify_error",
"You must specify the header, payload, signature and public key.",
NSError(domain: "JWT", code: 1, userInfo: nil)
)
return
}
// Convert PEM format to DER
publicKeyArr.removeFirst() // Remove BEGIN header
publicKeyArr.removeLast(2) // Remove END footer and newline
let publicKey = publicKeyArr.joined(separator: "")
let publicKeyDataBase64 = Data(base64Encoded: publicKey)!
let signedPart = [header, payload].joined(separator: ".")
let signatureData = NSData(base64UrlEncodedString: signature)! as Data
let signingInput = signedPart.data(using: .ascii)!
// Represent the certificate with Apple Security Framework
guard let cert = SecCertificateCreateWithData(nil, publicKeyDataBase64 as CFData) else {
reject(
"jwt_verify_error",
"Could not create the Apple Security Framework representation of the PEM certificate.",
NSError(domain: "jwt", code: 3, userInfo: nil)
)
return
}
// Get the public key
guard let key = SecCertificateCopyKey(cert) else {
reject(
"jwt_verify_error",
"Could not retrieve the key (SecKey) from the certificate representation.",
NSError(domain: "jwt", code: 4, userInfo: nil)
)
return
}
var error: Unmanaged<CFError>?
// Verify the signature of the token
let result = SecKeyVerifySignature(
key,
.rsaSignatureMessagePKCS1v15SHA256,
signingInput as CFData,
signatureData as CFData,
&error
)
if let errorPointer = error {
let cfError = errorPointer.takeUnretainedValue()
let description = CFErrorCopyDescription(cfError)
let domain = CFErrorGetDomain(cfError)
let code = CFErrorGetCode(cfError)
let userInfo = CFErrorCopyUserInfo(cfError)
reject(
"jwt_verify_error",
description as String? ?? "An error occured when verifying the token's signature.",
NSError(
domain: domain as String? ?? "jwt",
code: code,
userInfo: userInfo as? [String:Any]
)
)
errorPointer.release()
return
}
resolve(result)
}
@objc(verifyAtHash:accessToken:resolve:reject:)
func verifyAtHash(
value atHash: String,
accessToken components: NSArray!,
resolve: RCTPromiseResolveBlock,
reject: RCTPromiseRejectBlock
) {
let accessToken = components.componentsJoined(by: ".")
let accessTokenData = accessToken.data(using: .ascii)!
var buffer = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
accessTokenData.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
_ = CC_SHA256(bytes.baseAddress, CC_LONG(accessTokenData.count), &buffer)
}
buffer.removeLast(buffer.count / 2)
let accessTokenFirstHalfBase64 = (Data(buffer) as NSData).base64UrlEncodedString()
resolve(accessTokenFirstHalfBase64 == atHash)
}
}
| mit |
bag-umbala/music-umbala | Music-Umbala/Music-Umbala/Controller/PlaylistViewController.swift | 1 | 4215 | //
// PlaylistViewController.swift
// Music-Umbala
//
// Created by Nam Nguyen on 5/19/17.
// Copyright © 2017 Nam Vo. All rights reserved.
//
import UIKit
class PlaylistViewController: UIViewController, UISearchBarDelegate, UISearchResultsUpdating {
// MARK: *** Data model
var modelPlaylist : [Playlist]?
var modelPlaylistSearchResults : [Playlist]?
var searchController: UISearchController = UISearchController(searchResultsController: nil)
// MARK: *** UI Elements
@IBOutlet weak var tableView: UITableView!
// MARK: *** UI events
// MARK: *** Local variables
let didSelectIdPlaylist : Int32 = -1
var didSelectPlaylist : Playlist?
// MARK: *** UIViewController
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
DB.createDBOrGetDBExist()
modelPlaylist = PlaylistManager.all()
NotificationCenter.default.addObserver(self, selector: #selector(loadPlaylistTables), name: NSNotification.Name(rawValue: "loadPlaylistTables"), object: nil)
self.tableView.delegate = self
self.tableView.dataSource = self
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.scopeButtonTitles = ["Name"] //, "ID"
searchController.searchBar.delegate = self
tableView?.tableHeaderView = searchController.searchBar
// definesPresentationContext = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let speciesDetailVC = segue.destination as? PlaylistDetailViewController
{
speciesDetailVC.playlist = didSelectPlaylist
// let indexPath = self.searchDisplayController?.searchResultsTableView.indexPathForSelectedRow
// if indexPath != nil {
// speciesDetailVC.playlist =
// }
}
}
func loadPlaylistTables() {
modelPlaylist = PlaylistManager.all()
self.tableView.reloadData() // Cập nhật giao diện
}
// MARK: Search
func filterContentForSearchText(searchText: String, scope: Int) {
// Filter the array using the filter method
if self.modelPlaylist == nil {
self.modelPlaylistSearchResults = nil
return
}
self.modelPlaylistSearchResults = self.modelPlaylist!.filter({( aPlaylist: Playlist) -> Bool in
var fieldToSearch: String?
switch (scope) {
case (0):
fieldToSearch = aPlaylist.name
// case (1):
// fieldToSearch = "\(aPlaylist.id)"
default:
fieldToSearch = nil
}
if fieldToSearch == nil {
self.modelPlaylistSearchResults = nil
return false
}
return fieldToSearch!.lowercased().range(of: searchText.lowercased()) != nil
})
}
func updateSearchResults(for searchController: UISearchController) {
let selectedIndex = searchController.searchBar.selectedScopeButtonIndex
let searchString = searchController.searchBar.text ?? ""
filterContentForSearchText(searchText: searchString, scope: selectedIndex)
tableView?.reloadData()
}
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
let selectedIndex = searchBar.selectedScopeButtonIndex
let searchString = searchBar.text ?? ""
filterContentForSearchText(searchText: searchString, scope: selectedIndex)
tableView?.reloadData()
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/12904-no-stacktrace.swift | 11 | 214 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
init( = {
class C {
init( ) {
{
class
case ,
| mit |
suosuopuo/SwiftyAlgorithm | SwiftyAlgorithm/Queue.swift | 1 | 2177 | //
// Queue.swift
// SwiftyAlgorithm
//
// Created by suosuopuo on 24/10/2017.
// Copyright © 2017 shellpanic. All rights reserved.
//
import Foundation
public struct Queue<T> {
private var array = [T?]()
private var head = 0
public var isEmpty: Bool {
return count == 0
}
public var count: Int {
return array.count - head
}
public mutating func enqueue(_ element: T) {
array.append(element)
}
public mutating func dequeue() -> T? {
guard head < array.count, let element = array[head] else { return nil }
array[head] = nil
head += 1
let percentage = Double(head)/Double(array.count)
if array.count > 50 && percentage > 0.25 {
array.removeFirst(head)
head = 0
}
return element
}
public var front: T? {
if isEmpty {
return nil
} else {
return array[head]
}
}
}
public struct LinkedQueue<T> {
fileprivate var list = List<T>()
public var count: Int {
return list.count
}
public var isEmpty: Bool {
return list.isEmpty
}
public mutating func enqueue(_ element: T) {
list.append(element)
}
public mutating func dequeue() -> T? {
return list.removeFirst()
}
public var front: T? {
return list.first?.value
}
}
public struct LinkedDeque<T> {
private var list = List<T>()
public var isEmpty: Bool {
return list.isEmpty
}
public var count: Int {
return list.count
}
public mutating func enqueue(_ element: T) {
list.append(element)
}
public mutating func enqueueFront(_ element: T) {
list.prepend(element)
}
public mutating func dequeue() -> T? {
return list.removeFirst()
}
public mutating func dequeueBack() -> T? {
return list.removeLast()
}
public var front: T? {
return list.first?.value
}
public var back: T? {
return list.last?.value
}
}
| mit |
cnoon/swift-compiler-crashes | fixed/00624-swift-constraints-solution-solution.swift | 11 | 201 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
0
protocol b:A{class A:a{}func a | mit |
Djecksan/MobiTask | MobiTask/Models/Fixer.swift | 1 | 508 | //
// Fixer.swift
// MobiTask
//
// Created by Evgenyi Tyulenev on 31.07.15.
// Copyright (c) 2015 VoltMobi. All rights reserved.
//
import ObjectMapper
class Fixer {
var base :String?
var date :String?
var rates :[String:Float]?
}
extension Fixer:Mappable {
class func newInstance() -> Mappable {
return Fixer()
}
// Mappable
func mapping(map: Map) {
base <- map["base"]
date <- map["date"]
rates <- map["rates"]
}
} | mit |
tbkka/swift-protobuf | Sources/SwiftProtobuf/ExtensibleMessage.swift | 3 | 3484 | // Sources/SwiftProtobuf/ExtensibleMessage.swift - Extension support
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Additional capabilities needed by messages that allow extensions.
///
// -----------------------------------------------------------------------------
// Messages that support extensions implement this protocol
public protocol ExtensibleMessage: Message {
var _protobuf_extensionFieldValues: ExtensionFieldValueSet { get set }
}
extension ExtensibleMessage {
public mutating func setExtensionValue<F: ExtensionField>(ext: MessageExtension<F, Self>, value: F.ValueType) {
_protobuf_extensionFieldValues[ext.fieldNumber] = F(protobufExtension: ext, value: value)
}
public func getExtensionValue<F: ExtensionField>(ext: MessageExtension<F, Self>) -> F.ValueType? {
if let fieldValue = _protobuf_extensionFieldValues[ext.fieldNumber] as? F {
return fieldValue.value
}
return nil
}
public func hasExtensionValue<F: ExtensionField>(ext: MessageExtension<F, Self>) -> Bool {
return _protobuf_extensionFieldValues[ext.fieldNumber] is F
}
public mutating func clearExtensionValue<F: ExtensionField>(ext: MessageExtension<F, Self>) {
_protobuf_extensionFieldValues[ext.fieldNumber] = nil
}
}
// Additional specializations for the different types of repeated fields so
// setting them to an empty array clears them from the map.
extension ExtensibleMessage {
public mutating func setExtensionValue<T>(ext: MessageExtension<RepeatedExtensionField<T>, Self>, value: [T.BaseType]) {
_protobuf_extensionFieldValues[ext.fieldNumber] =
value.isEmpty ? nil : RepeatedExtensionField<T>(protobufExtension: ext, value: value)
}
public mutating func setExtensionValue<T>(ext: MessageExtension<PackedExtensionField<T>, Self>, value: [T.BaseType]) {
_protobuf_extensionFieldValues[ext.fieldNumber] =
value.isEmpty ? nil : PackedExtensionField<T>(protobufExtension: ext, value: value)
}
public mutating func setExtensionValue<E>(ext: MessageExtension<RepeatedEnumExtensionField<E>, Self>, value: [E]) {
_protobuf_extensionFieldValues[ext.fieldNumber] =
value.isEmpty ? nil : RepeatedEnumExtensionField<E>(protobufExtension: ext, value: value)
}
public mutating func setExtensionValue<E>(ext: MessageExtension<PackedEnumExtensionField<E>, Self>, value: [E]) {
_protobuf_extensionFieldValues[ext.fieldNumber] =
value.isEmpty ? nil : PackedEnumExtensionField<E>(protobufExtension: ext, value: value)
}
public mutating func setExtensionValue<M>(ext: MessageExtension<RepeatedMessageExtensionField<M>, Self>, value: [M]) {
_protobuf_extensionFieldValues[ext.fieldNumber] =
value.isEmpty ? nil : RepeatedMessageExtensionField<M>(protobufExtension: ext, value: value)
}
public mutating func setExtensionValue<M>(ext: MessageExtension<RepeatedGroupExtensionField<M>, Self>, value: [M]) {
_protobuf_extensionFieldValues[ext.fieldNumber] =
value.isEmpty ? nil : RepeatedGroupExtensionField<M>(protobufExtension: ext, value: value)
}
}
| apache-2.0 |
dclelland/RefreshableViewController | Sources/RefreshableState.swift | 1 | 1360 | //
// RefreshableState.swift
// RefreshableViewController
//
// Created by Daniel Clelland on 30/08/17.
// Copyright © 2017 Daniel Clelland. All rights reserved.
//
import Foundation
import PromiseKit
// MARK: Refreshable state
public enum RefreshableState<Value> {
case ready
case loading
case success(Value)
case failure(Error)
// MARK: Mutable properties
public var value: Value? {
set {
guard let value = newValue else {
if case .success = self {
self = .ready
}
return
}
self = .success(value)
}
get {
guard case .success(let response) = self else {
return nil
}
return response
}
}
public var error: Error? {
set {
guard let error = newValue else {
if case .failure = self {
self = .ready
}
return
}
self = .failure(error)
}
get {
guard case .failure(let error) = self else {
return nil
}
return error
}
}
}
| mit |
agordeev/OverlayViewController | OverlayViewController/AppDelegate.swift | 1 | 2214 | //
// AppDelegate.swift
// OverlayViewController
//
// Created by Andrey Gordeev on 4/17/17.
// Copyright © 2017 Andrey Gordeev (andrew8712@gmail.com). All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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 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:.
}
}
| mit |
drewag/Swiftlier | Sources/Swiftlier/Errors/SwiftlierResult.swift | 1 | 212 | //
// SwiftlierResult.swift
// Swiftlier
//
// Created by Andrew J Wagner on 7/31/19.
//
import Foundation
public enum SwiftlierResult<Success> {
case success(Success)
case failure(SwiftlierError)
}
| mit |
NUKisZ/MyTools | MyTools/MyTools/Class/ThirdVC/BKBK/NUKController/GroupListViewController.swift | 1 | 3585 | //
// GroupListViewController.swift
// NUK
//
// Created by NUK on 16/8/13.
// Copyright © 2016年 NUK. All rights reserved.
//
import UIKit
class GroupListViewController: NUKBaseViewController,ZKDownloaderDelegate {
var id:String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func downloaderData() {
//http://picaman.picacomic.com/api/categories/1/page/1/comics
let urlString = String(format: "http://picaman.picacomic.com/api/categories/%@/page/%d/comics", self.id,self.curPage)
let download = ZKDownloader()
download.getWithUrl(urlString)
download.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension GroupListViewController{
func downloader(_ downloader: ZKDownloader, didFailWithError error: NSError) {
ZKTools.showAlert(error.localizedDescription, onViewController: self)
}
func downloader(_ download: ZKDownloader, didFinishWithData data: Data?) {
let jsonData = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
if (jsonData as AnyObject).isKind(of: NSArray.self){
if self.curPage == 1 {
self.dataArray.removeAllObjects()
}
let array = jsonData as! NSArray
for arr in array{
let dict = arr as! Dictionary<String,AnyObject>
let model = GroupListModel()
model.setValuesForKeys(dict)
self.dataArray.add(model)
}
DispatchQueue.main.async(execute: {
self.tbView?.reloadData()
self.tbView?.headerView?.endRefreshing()
self.tbView?.footerView?.endRefreshing()
})
}
}
}
extension GroupListViewController{
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellId = "groupListCellId"
var cell = tableView.dequeueReusableCell(withIdentifier: cellId)as? GroupListCell
if cell == nil {
cell = Bundle.main.loadNibNamed("GroupListCell", owner: nil, options: nil)?.last as? GroupListCell
}
let model = self.dataArray[(indexPath as NSIndexPath).row]as! GroupListModel
cell?.config(model)
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
let detailCtrl = DetailViewController()
let model = self.dataArray[(indexPath as NSIndexPath).row]as! GroupListModel
detailCtrl.id = "\((model.id)!)"
self.navigationController?.pushViewController(detailCtrl, animated: true)
}
}
| mit |
Electrode-iOS/ELDispatch | ELDispatchTests/NSBundleTests.swift | 2 | 1178 | //
// NSBundleTests.swift
// ELDispatch
//
// Created by Brandon Sneed on 2/16/15.
// Copyright (c) 2015 WalmartLabs. All rights reserved.
//
import UIKit
import XCTest
import ELDispatch
import Foundation
class NSBundleTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testReverseBundleID() {
let id = NSBundle(forClass: ELDispatch.self)
let label = "doofus"
println("reversedID = %@", id.reverseBundleIdentifier()!)
// does this actually work?
let anotherid = (id.reverseBundleIdentifier() ?? "") + "." + label
println("reversedID = %@", anotherid)
// does this actually work?
let nilIdentifier: String? = nil
let yetAnotherid = (nilIdentifier ?? "") + "." + label
println("reversedID = %@", yetAnotherid)
}
}
| mit |
xilosada/BitcoinFinder | BitcoinFinder/CoinDeskAPI.swift | 1 | 1394 | //
// Copyright 2015 (C) Xabier I. Losada (http://www.xilosada.com)
//
// 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 RxCocoa
import RxSwift
public class CoinDeskAPI {
let _url = NSURL(string: "https://api.coindesk.com/v1/bpi/currentprice/EUR.json")!
let dataScheduler: ImmediateSchedulerType!
let URLSession: NSURLSession!
public init(dataScheduler: ImmediateSchedulerType, URLSession: NSURLSession) {
self.dataScheduler = dataScheduler
self.URLSession = URLSession
}
/**
returns the most recent price index from CoinDesk
*/
func getBPI() -> Observable<CoinDeskBPI> {
return self.URLSession.rx_JSON(_url)
.map { json in
return CoinDeskBPI(fromJson: json as! [String : AnyObject])
}.observeOn(self.dataScheduler)
}
} | apache-2.0 |
hooman/swift | test/AutoDiff/stdlib/simd.swift | 1 | 9186 | // RUN: %target-run-simple-swift(-Xfrontend -requirement-machine=off)
// REQUIRES: executable_test
// Would fail due to unavailability of swift_autoDiffCreateLinearMapContext.
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
import _Differentiation
import StdlibUnittest
var SIMDTests = TestSuite("SIMD")
SIMDTests.test("init(repeating:)") {
let g = SIMD4<Float>(1, 1, 1, 1)
func foo1(x: Float) -> SIMD4<Float> {
return SIMD4<Float>(repeating: 2 * x)
}
let (val1, pb1) = valueWithPullback(at: 5, of: foo1)
expectEqual(SIMD4<Float>(10, 10, 10, 10), val1)
expectEqual(8, pb1(g))
}
// FIXME(TF-1103): Derivative registration does not yet support
// `@_alwaysEmitIntoClient` original functions.
/*
SIMDTests.test("Sum") {
let a = SIMD4<Float>(1, 2, 3, 4)
func foo1(x: SIMD4<Float>) -> Float {
return x.sum()
}
let (val1, pb1) = valueWithPullback(at: a, of: foo1)
expectEqual(10, val1)
expectEqual(SIMD4<Float>(3, 3, 3, 3), pb1(3))
}
*/
SIMDTests.test("Identity") {
let a = SIMD4<Float>(1, 2, 3, 4)
let g = SIMD4<Float>(1, 1, 1, 1)
func foo1(x: SIMD4<Float>) -> SIMD4<Float> {
return x
}
let (val1, pb1) = valueWithPullback(at: a, of: foo1)
expectEqual(a, val1)
expectEqual(g, pb1(g))
}
SIMDTests.test("Negate") {
let a = SIMD4<Float>(1, 2, 3, 4)
let g = SIMD4<Float>(1, 1, 1, 1)
func foo1(x: SIMD4<Float>) -> SIMD4<Float> {
return -x
}
let (val1, pb1) = valueWithPullback(at: a, of: foo1)
expectEqual(-a, val1)
expectEqual(-g, pb1(g))
}
SIMDTests.test("Subscript") {
let a = SIMD4<Float>(1, 2, 3, 4)
func foo1(x: SIMD4<Float>) -> Float {
return x[3]
}
let (val1, pb1) = valueWithPullback(at: a, of: foo1)
expectEqual(4, val1)
expectEqual(SIMD4<Float>(0, 0, 0, 7), pb1(7))
}
SIMDTests.test("SubscriptSetter") {
let a = SIMD4<Float>(1, 2, 3, 4)
let ones = SIMD4<Float>(1, 1, 1, 1)
// A wrapper around `subscript(_: Int).set`.
func subscriptSet(
_ simd: SIMD4<Float>, index: Int, newScalar: Float
) -> SIMD4<Float> {
var result = simd
result[index] = newScalar
return result
}
let (val1, pb1) = valueWithPullback(at: a, 5, of: { subscriptSet($0, index: 2, newScalar: $1) })
expectEqual(SIMD4<Float>(1, 2, 5, 4), val1)
expectEqual((SIMD4<Float>(1, 1, 0, 1), 1), pb1(ones))
func doubled(_ x: SIMD4<Float>) -> SIMD4<Float> {
var result = x
for i in withoutDerivative(at: x.indices) {
result[i] = x[i] * 2
}
return result
}
let (val2, pb2) = valueWithPullback(at: a, of: doubled)
expectEqual(SIMD4<Float>(2, 4, 6, 8), val2)
expectEqual(SIMD4<Float>(2, 2, 2, 2), pb2(ones))
}
SIMDTests.test("Addition") {
let a = SIMD4<Float>(1, 2, 3, 4)
let g = SIMD4<Float>(1, 1, 1, 1)
// SIMD + SIMD
func foo1(x: SIMD4<Float>, y: SIMD4<Float>) -> SIMD4<Float> {
return x + y
}
let (val1, pb1) = valueWithPullback(at: a, a, of: foo1)
expectEqual(SIMD4<Float>(2, 4, 6, 8), val1)
expectEqual((g, g), pb1(g))
// SIMD + Scalar
func foo2(x: SIMD4<Float>, y: Float) -> SIMD4<Float> {
return x + y
}
let (val2, pb2) = valueWithPullback(at: a, 5, of: foo2)
expectEqual(SIMD4<Float>(6, 7, 8, 9), val2)
expectEqual((g, 4), pb2(g))
// Scalar + SIMD
func foo3(x: SIMD4<Float>, y: Float) -> SIMD4<Float> {
return y + x
}
let (val3, pb3) = valueWithPullback(at: a, 5, of: foo3)
expectEqual(SIMD4<Float>(6, 7, 8, 9), val3)
expectEqual((g, 4), pb3(g))
}
SIMDTests.test("Subtraction") {
let a = SIMD4<Float>(1, 2, 3, 4)
let g = SIMD4<Float>(1, 1, 1, 1)
// SIMD - SIMD
func foo1(x: SIMD4<Float>, y: SIMD4<Float>) -> SIMD4<Float> {
return x - y
}
let (val1, pb1) = valueWithPullback(at: a, a, of: foo1)
expectEqual(SIMD4<Float>(0, 0, 0, 0), val1)
expectEqual((g, -g), pb1(g))
// SIMD - Scalar
func foo2(x: SIMD4<Float>, y: Float) -> SIMD4<Float> {
return x - y
}
let (val2, pb2) = valueWithPullback(at: a, 5, of: foo2)
expectEqual(SIMD4<Float>(-4, -3, -2, -1), val2)
expectEqual((g, -4), pb2(g))
// Scalar - SIMD
func foo3(x: SIMD4<Float>, y: Float) -> SIMD4<Float> {
return y - x
}
let (val3, pb3) = valueWithPullback(at: a, 5, of: foo3)
expectEqual(SIMD4<Float>(4, 3, 2, 1), val3)
expectEqual((-g, 4), pb3(g))
}
SIMDTests.test("Multiplication") {
let a = SIMD4<Float>(1, 2, 3, 4)
let g = SIMD4<Float>(1, 1, 1, 1)
// SIMD * SIMD
func foo1(x: SIMD4<Float>, y: SIMD4<Float>) -> SIMD4<Float> {
return x * y
}
let (val1, pb1) = valueWithPullback(at: a, a, of: foo1)
expectEqual(a * a, val1)
expectEqual((a, a), pb1(g))
// SIMD * Scalar
func foo2(x: SIMD4<Float>, y: Float) -> SIMD4<Float> {
return x * y
}
let (val2, pb2) = valueWithPullback(at: a, 5, of: foo2)
expectEqual(a * 5, val2)
expectEqual((SIMD4<Float>(5, 5, 5, 5), 10), pb2(g))
// Scalar * SIMD
func foo3(x: SIMD4<Float>, y: Float) -> SIMD4<Float> {
return y * x
}
let (val3, pb3) = valueWithPullback(at: a, 5, of: foo3)
expectEqual(a * 5, val3)
expectEqual((SIMD4<Float>(5, 5, 5, 5), 10), pb3(g))
}
SIMDTests.test("Division") {
let a = SIMD4<Float>(1, 2, 3, 4)
let g = SIMD4<Float>(1, 1, 1, 1)
// SIMD / SIMD
func foo1(x: SIMD4<Float>, y: SIMD4<Float>) -> SIMD4<Float> {
return x / y
}
let dlhs1 = g / a
let drhs1 = -1 / a
let (val1, pb1) = valueWithPullback(at: a, a, of: foo1)
expectEqual(a / a, val1)
expectEqual((dlhs1, drhs1), pb1(g))
// SIMD / Scalar
func foo2(x: SIMD4<Float>, y: Float) -> SIMD4<Float> {
return x / y
}
let dlhs2 = g / 5
let drhs2 = (-a / 25 * g).sum()
let (val2, pb2) = valueWithPullback(at: a, 5, of: foo2)
expectEqual(a / 5, val2)
expectEqual((dlhs2, drhs2), pb2(g))
// Scalar / SIMD
func foo3(x: Float, y: SIMD4<Float>) -> SIMD4<Float> {
return x / y
}
let dlhs3 = (g / a).sum()
let drhs3 = -5 / (a*a) * g
let (val3, pb3) = valueWithPullback(at: 5, a, of: foo3)
expectEqual(5 / a, val3)
expectEqual((dlhs3, drhs3), pb3(g))
}
SIMDTests.test("Generics") {
let a = SIMD3<Double>(1, 2, 3)
let g = SIMD3<Double>(1, 1, 1)
func testInit<Scalar, SIMDType: SIMD>(x: Scalar) -> SIMDType
where SIMDType.Scalar == Scalar,
SIMDType : Differentiable,
Scalar : BinaryFloatingPoint & Differentiable,
SIMDType.TangentVector == SIMDType,
Scalar.TangentVector == Scalar {
return SIMDType.init(repeating: x)
}
func simd3Init(x: Double) -> SIMD3<Double> { testInit(x: x) }
let (val1, pb1) = valueWithPullback(at: 10, of: simd3Init)
expectEqual(SIMD3<Double>(10, 10, 10), val1)
expectEqual(3, pb1(g))
// SIMDType + SIMDType
func testAddition<Scalar, SIMDType: SIMD>(lhs: SIMDType, rhs: SIMDType)
-> SIMDType
where SIMDType.Scalar == Scalar,
SIMDType : Differentiable,
SIMDType.TangentVector : SIMD,
Scalar : BinaryFloatingPoint,
SIMDType.TangentVector.Scalar : BinaryFloatingPoint {
return lhs + rhs
}
func simd3Add(lhs: SIMD3<Double>, rhs: SIMD3<Double>) -> SIMD3<Double> {
return testAddition(lhs: lhs, rhs: rhs)
}
let (val2, pb2) = valueWithPullback(at: a, a, of: simd3Add)
expectEqual(SIMD3<Double>(2, 4, 6), val2)
expectEqual((g, g), pb2(g))
// Scalar - SIMDType
func testSubtraction<Scalar, SIMDType: SIMD>(lhs: Scalar, rhs: SIMDType)
-> SIMDType
where SIMDType.Scalar == Scalar,
SIMDType : Differentiable,
Scalar : BinaryFloatingPoint & Differentiable,
SIMDType.TangentVector == SIMDType,
Scalar.TangentVector == Scalar {
return lhs - rhs
}
func simd3Subtract(lhs: Double, rhs: SIMD3<Double>) -> SIMD3<Double> {
return testSubtraction(lhs: lhs, rhs: rhs)
}
let (val3, pb3) = valueWithPullback(at: 5, a, of: simd3Subtract)
expectEqual(SIMD3<Double>(4, 3, 2), val3)
expectEqual((3, SIMD3<Double>(-1, -1, -1)), pb3(g))
// SIMDType * Scalar
func testMultiplication<Scalar, SIMDType: SIMD>(lhs: SIMDType, rhs: Scalar)
-> SIMDType
where SIMDType.Scalar == Scalar,
SIMDType : Differentiable,
Scalar : BinaryFloatingPoint & Differentiable,
SIMDType.TangentVector == SIMDType,
Scalar.TangentVector == Scalar {
return lhs * rhs
}
func simd3Multiply(lhs: SIMD3<Double>, rhs: Double) -> SIMD3<Double> {
return testMultiplication(lhs: lhs, rhs: rhs)
}
let (val4, pb4) = valueWithPullback(at: a, 5, of: simd3Multiply)
expectEqual(SIMD3<Double>(5, 10, 15), val4)
expectEqual((SIMD3<Double>(5, 5, 5), 6), pb4(g))
// FIXME(TF-1103): Derivative registration does not yet support
// `@_alwaysEmitIntoClient` original functions like `SIMD.sum()`.
/*
func testSum<Scalar, SIMDType: SIMD>(x: SIMDType) -> Scalar
where SIMDType.Scalar == Scalar,
SIMDType : Differentiable,
Scalar : BinaryFloatingPoint & Differentiable,
Scalar.TangentVector : BinaryFloatingPoint,
SIMDType.TangentVector == SIMDType {
return x.sum()
}
func simd3Sum(x: SIMD3<Double>) -> Double { testSum(x: x) }
let (val5, pb5) = valueWithPullback(at: a, of: simd3Sum)
expectEqual(6, val5)
expectEqual(SIMD3<Double>(7, 7, 7), pb5(7))
*/
}
runAllTests()
| apache-2.0 |
herrkaefer/AccelerateWatch | Example/AccelerateWatch/AppDelegate.swift | 1 | 2179 | //
// AppDelegate.swift
// AccelerateWatch
//
// Created by HerrKaefer on 06/23/2017.
// Copyright (c) 2017 HerrKaefer. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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:.
}
}
| mit |
nchitale/em-power | Empower/AppDelegate.swift | 1 | 2135 | //
// AppDelegate.swift
// Empower
//
// Created by Nandini on 7/20/16.
// Copyright © 2016 Empower. All rights reserved.
//
import UIKit
@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:.
}
}
| mit |
Raizlabs/ios-template | {{ cookiecutter.project_name | replace(' ', '') }}/app/{{ cookiecutter.project_name | replace(' ', '') }}/Application/Appearance/Appearance.swift | 1 | 557 | //
// Appearance.swift
// {{ cookiecutter.project_name | replace(' ', '') }}
//
// Created by {{ cookiecutter.lead_dev }} on {% now 'utc', '%D' %}.
// Copyright © {% now 'utc', '%Y' %} {{ cookiecutter.company_name }}. All rights reserved.
//
import UIKit
struct Appearance {
static var shared = Appearance()
func style() {
// Configure UIAppearance proxies
}
}
extension Appearance: AppLifecycle {
func onDidLaunch(application: UIApplication, launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
style()
}
}
| mit |
iamcam/Sinker | Sinker/ViewController.swift | 1 | 5150 | //
// ViewController.swift
// Hook Line and Sinker
//
// Created by Cameron Perry on 12/16/14.
// Copyright (c) 2014 Cameron Perry. All rights reserved.
//
import UIKit
class ViewController: UIViewController, SettingsDelegate {
let kClientAccessIdentifier = CommonSettings().clientAccessIdentifier
var manager: AFOAuth2Manager?
var widgets: NSArray?
var client_id: String { get { return CommonSettings().client_id } }
var client_secret: String { get { return CommonSettings().client_secret } }
var baseURL: NSURL? { get { return NSURL(string: CommonSettings().hostURL) } }
@IBOutlet var pullButton: UIView!
@IBAction func showSettings(sender: UIButton) {
var settings = SettingsViewController(nibName:"SettingsViewController", bundle:nil)
settings.delegate = self
presentViewController(settings, animated: true, completion: nil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
manager = AFOAuth2Manager(baseURL: self.baseURL, clientID: self.client_id, secret: self.client_secret)
}
@IBAction func pushedButton(sender: AnyObject) {
authenticateApp({ (credential) -> () in
println("👍 Credential found: \(credential!)")
}, failure: { (error) -> () in
println("💩 \(error)")
})
}
@IBAction func logOut(sender: AnyObject) {
if( true == AFOAuthCredential.deleteCredentialWithIdentifier(kClientAccessIdentifier) ){
println("'Logged out'")
} else {
println("Could not delete credential")
}
}
@IBAction func fetchWidgets(sender: AnyObject) {
if( credentialIsCurrent()) {
retrieveWidgets()
} else {
authenticateApp({ (credential) -> () in
self.retrieveWidgets()
}, failure: { (error) -> () in
// handle the error
})
}
}
func authenticateApp(success: ((AFOAuthCredential?)->()), failure:((NSError)->())) {
if ( credentialIsCurrent() ) {
success(AFOAuthCredential.retrieveCredentialWithIdentifier(kClientAccessIdentifier))
} else {
manager?.authenticateUsingOAuthWithURLString("/oauth/token", scope: "public", success: { (credential) -> Void in
println("Good job! \(credential)" )
var didSave = AFOAuthCredential.storeCredential(credential, withIdentifier: self.kClientAccessIdentifier)
success(credential);
},
failure: { (error) -> Void in
failure(error)
})
}
}
func credentialIsCurrent() -> Bool{
var isValid = false
if let credential = AFOAuthCredential.retrieveCredentialWithIdentifier(kClientAccessIdentifier){
println("Found credential: \(credential)")
if (credential.expired) {
println("Credential expired")
AFOAuthCredential.deleteCredentialWithIdentifier(kClientAccessIdentifier)
isValid = false
} else {
isValid = true
}
} else {
isValid = false
}
return isValid
}
func retrieveWidgets(){
if let credential = AFOAuthCredential.retrieveCredentialWithIdentifier(kClientAccessIdentifier){
manager?.requestSerializer.setAuthorizationHeaderFieldWithCredential(credential)
manager?.GET("api/v1/widgets.json", parameters: nil, success: { (theOperation, responseObject) -> Void in
println("Working")
self.widgets = responseObject as? NSArray
if (self.widgets != nil && self.widgets!.count > 0){
if let d = self.widgets![0] as? NSDictionary {
println("First Widget: \(d)")
if let uuid = d["uuid"] as? String {
println("UUID is \(uuid)");
}
}
} else {
println("No Widgets Found")
}
}, failure: { (theOperation, error) -> Void in
println("Error \(error)")
})
} else {
authenticateApp({ (credential) -> () in
self.retrieveWidgets()
}, failure: { (error) -> () in
println("Failed authentication. Maybe something is wrong with the client id and secret")
})
}
}
//MARK: - Settings Delegate methods
func apiSettingsChanged() {
println("baseURL: \(self.baseURL), clientID: \(self.client_id), secret: \(self.client_secret)")
manager = AFOAuth2Manager(baseURL: self.baseURL, clientID: self.client_id, secret: self.client_secret)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.