repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
codestergit/swift | stdlib/public/SDK/CoreData/NSManagedObjectContext.swift | 39 | 951 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import CoreData
import Foundation
extension NSManagedObjectContext {
public func fetch<T>(_ request: NSFetchRequest<T>) throws -> [T] {
return try fetch(unsafeDowncast(request, to: NSFetchRequest<NSFetchRequestResult>.self)) as! [T]
}
public func count<T>(for request: NSFetchRequest<T>) throws -> Int {
return try count(for: unsafeDowncast(request, to: NSFetchRequest<NSFetchRequestResult>.self))
}
}
| apache-2.0 | 44b26c66a17f30075f12a19224c330e4 | 38.625 | 100 | 0.616193 | 5.005263 | false | false | false | false |
wenluma/swift | stdlib/public/core/ValidUTF8Buffer.swift | 5 | 5919 | //===--- ValidUTF8Buffer.swift - Bounded Collection of Valid UTF-8 --------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Stores valid UTF8 inside an unsigned integer.
//
// Actually this basic type could be used to store any UInt8s that cannot be
// 0xFF
//
//===----------------------------------------------------------------------===//
@_fixed_layout
public struct _ValidUTF8Buffer<
Storage: UnsignedInteger & FixedWidthInteger
> {
public typealias Element = Unicode.UTF8.CodeUnit
internal typealias _Storage = Storage
@_versioned
internal var _biasedBits: Storage
@_versioned
internal init(_biasedBits: Storage) {
self._biasedBits = _biasedBits
}
@_versioned
internal init(_containing e: Element) {
_sanityCheck(
e != 192 && e != 193 && !(245...255).contains(e), "invalid UTF8 byte")
_biasedBits = Storage(truncatingIfNeeded: e &+ 1)
}
}
extension _ValidUTF8Buffer : Sequence {
public typealias SubSequence = RangeReplaceableRandomAccessSlice<_ValidUTF8Buffer>
public struct Iterator : IteratorProtocol, Sequence {
public init(_ x: _ValidUTF8Buffer) { _biasedBits = x._biasedBits }
public mutating func next() -> Element? {
if _biasedBits == 0 { return nil }
defer { _biasedBits >>= 8 }
return Element(truncatingIfNeeded: _biasedBits) &- 1
}
internal var _biasedBits: Storage
}
public func makeIterator() -> Iterator {
return Iterator(self)
}
}
extension _ValidUTF8Buffer : Collection {
public typealias IndexDistance = Int
public struct Index : Comparable {
@_versioned
internal var _biasedBits: Storage
@_versioned
internal init(_biasedBits: Storage) { self._biasedBits = _biasedBits }
public static func == (lhs: Index, rhs: Index) -> Bool {
return lhs._biasedBits == rhs._biasedBits
}
public static func < (lhs: Index, rhs: Index) -> Bool {
return lhs._biasedBits > rhs._biasedBits
}
}
public var startIndex : Index {
return Index(_biasedBits: _biasedBits)
}
public var endIndex : Index {
return Index(_biasedBits: 0)
}
public var count : IndexDistance {
return Storage.bitWidth &>> 3 &- _biasedBits.leadingZeroBitCount &>> 3
}
public func index(after i: Index) -> Index {
_debugPrecondition(i._biasedBits != 0)
return Index(_biasedBits: i._biasedBits >> 8)
}
public subscript(i: Index) -> Element {
return Element(truncatingIfNeeded: i._biasedBits) &- 1
}
}
extension _ValidUTF8Buffer : BidirectionalCollection {
public func index(before i: Index) -> Index {
let offset = _ValidUTF8Buffer(_biasedBits: i._biasedBits).count
_debugPrecondition(offset != 0)
return Index(_biasedBits: _biasedBits &>> (offset &<< 3 - 8))
}
}
extension _ValidUTF8Buffer : RandomAccessCollection {
public typealias Indices = DefaultRandomAccessIndices<_ValidUTF8Buffer>
@inline(__always)
public func distance(from i: Index, to j: Index) -> IndexDistance {
_debugPrecondition(_isValid(i))
_debugPrecondition(_isValid(j))
return (
i._biasedBits.leadingZeroBitCount - j._biasedBits.leadingZeroBitCount
) &>> 3
}
@inline(__always)
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
let startOffset = distance(from: startIndex, to: i)
let newOffset = startOffset + n
_debugPrecondition(newOffset >= 0)
_debugPrecondition(newOffset <= count)
return Index(_biasedBits: _biasedBits._fullShiftRight(newOffset &<< 3))
}
}
extension _ValidUTF8Buffer : RangeReplaceableCollection {
public init() {
_biasedBits = 0
}
public var capacity: IndexDistance {
return _ValidUTF8Buffer.capacity
}
public static var capacity: IndexDistance {
return Storage.bitWidth / Element.bitWidth
}
@inline(__always)
public mutating func append(_ e: Element) {
_debugPrecondition(count + 1 <= capacity)
_sanityCheck(
e != 192 && e != 193 && !(245...255).contains(e), "invalid UTF8 byte")
_biasedBits |= Storage(e &+ 1) &<< (count &<< 3)
}
@inline(__always)
public mutating func removeFirst() {
_debugPrecondition(!isEmpty)
_biasedBits = _biasedBits._fullShiftRight(8)
}
@_versioned
internal func _isValid(_ i: Index) -> Bool {
return i == endIndex || indices.contains(i)
}
@inline(__always)
public mutating func replaceSubrange<C: Collection>(
_ target: Range<Index>, with replacement: C
) where C.Element == Element {
_debugPrecondition(_isValid(target.lowerBound))
_debugPrecondition(_isValid(target.upperBound))
var r = _ValidUTF8Buffer()
for x in self[..<target.lowerBound] { r.append(x) }
for x in replacement { r.append(x) }
for x in self[target.upperBound...] { r.append(x) }
self = r
}
@inline(__always)
public mutating func append<T>(contentsOf other: _ValidUTF8Buffer<T>) {
_debugPrecondition(count + other.count <= capacity)
_biasedBits |= Storage(
truncatingIfNeeded: other._biasedBits) &<< (count &<< 3)
}
}
extension _ValidUTF8Buffer {
public static var encodedReplacementCharacter : _ValidUTF8Buffer {
return _ValidUTF8Buffer(_biasedBits: 0xBD_BF_EF &+ 0x01_01_01)
}
}
/*
let test = _ValidUTF8Buffer<UInt64>(0..<8)
print(Array(test))
print(test.startIndex)
for (ni, i) in test.indices.enumerated() {
for (nj, j) in test.indices.enumerated() {
assert(test.distance(from: i, to: j) == nj - ni)
assert(test.index(i, offsetBy: nj - ni) == j)
}
}
*/
| mit | 9b07adadd0d2a0c6a3fc5459def66ec0 | 28.595 | 84 | 0.650786 | 4.239971 | false | false | false | false |
xu6148152/binea_project_for_ios | SportDemo/SportDemo/Shared/feature/Account/AccountRegisterProfileViewController.swift | 1 | 2998 | //
// AccountRegisterProfileViewController.swift
// SportDemo
//
// Created by Binea Xu on 8/16/15.
// Copyright (c) 2015 Binea Xu. All rights reserved.
//
import Foundation
import UIKit
class AccountRegisterProfileViewController : BaseTableViewController{
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerNib(UINib(nibName: "ZPTablePhotoSelectedCell", bundle: nil), forCellReuseIdentifier: "ZPTablePhotoSelectedCell")
self.tableView.registerNib(UINib(nibName: "ZPTableViewTextRowCell", bundle: nil), forCellReuseIdentifier: "ZPTableViewTextRowCell")
self.tableView.registerNib(UINib(nibName: "ZPTableViewButtonCell", bundle: nil), forCellReuseIdentifier: "ZPTableViewButtonCell")
self.tableView.dataSource = self
self.tableView.delegate = self
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0{
let cell = self.tableView.dequeueReusableCellWithIdentifier("ZPTablePhotoSelectedCell", forIndexPath: indexPath)
(cell as! ZPTablePhotoSelectedCell).setCurrentViewController(self)
return cell
}else {
if indexPath.section == 2 && indexPath.row == 3{
return self.tableView.dequeueReusableCellWithIdentifier("ZPTableViewButtonCell", forIndexPath: indexPath)
}
return self.tableView.dequeueReusableCellWithIdentifier("ZPTableViewTextRowCell", forIndexPath: indexPath)
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0{
return 1
}else if section == 1{
return 2
}else {
return 4
}
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if(section == 0){
return 0
}
return 45
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
return ZPTablePhotoSelectedCell.rowHeight();
}
return ZPTableViewTextRowCell.rowHeight()
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?{
if section == 1{
return NSLocalizedString("str_my_account_play_info", comment: "str_my_account_play_info")
}else if section == 2{
return NSLocalizedString("str_add_account_sync_account_title", comment: "str_add_account_sync_account_title")
}
return nil
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
}
} | mit | 98e89816cc49d8541a8a382d10b3f44e | 33.872093 | 143 | 0.657438 | 5.411552 | false | false | false | false |
leizh007/HiPDA | HiPDA/HiPDA/General/Models/Account.swift | 1 | 2199 | //
// Account.swift
// HiPDA
//
// Created by leizh007 on 16/7/23.
// Copyright © 2016年 HiPDA. All rights reserved.
//
import Foundation
import Argo
import Runes
import Curry
/// 存取键
private struct AccountKeys {
static let name = "name"
static let uid = "uid"
static let questionid = "questionid"
static let answer = "answer"
static let password = "password"
}
/// APP登录账户
struct Account {
let name: String
let uid: Int
let questionid: Int
let answer: String
let password: String
/// 默认高辨率的头像链接
let avatarImageURL: URL
init(name: String, uid: Int, questionid: Int, answer: String, password: String) {
self.name = name
self.uid = uid
self.questionid = questionid
self.answer = answer
self.password = password
avatarImageURL = URL(string: String(format: "https://img02.hi-pda.com/forum/uc_server/data/avatar/%03ld/%02ld/%02ld/%02ld_avatar_big.jpg", uid/1000000, (uid%1000000)/10000, (uid%10000)/100, uid%100))!
}
}
// MARK: - Serializable
extension Account: Serializable { }
// MARK: - Decodable
extension Account: Decodable {
static func decode(_ json: JSON) -> Decoded<Account> {
return curry(Account.init(name:uid:questionid:answer:password:))
<^> json <| AccountKeys.name
<*> json <| AccountKeys.uid
<*> json <| AccountKeys.questionid
<*> json <| AccountKeys.answer
<*> json <| AccountKeys.password
}
}
// MARK: - Equalable
extension Account: Equatable {
}
func ==(lhs: Account, rhs: Account) -> Bool {
return lhs.name == rhs.name &&
lhs.uid == rhs.uid &&
lhs.questionid == rhs.questionid &&
lhs.answer == rhs.answer &&
lhs.password == rhs.password
}
// MAKR: - Account Lens
extension Account {
static let uidLens: Lens<Account, Int> = Lens(get: { $0.uid },
set: { Account(name: $1.name, uid: $0, questionid: $1.questionid, answer: $1.answer, password: $1.password) })
}
// MARK: - Hashable
extension Account: Hashable {
var hashValue: Int {
return uid
}
}
| mit | fb81da3fd92d7af20d7c9f6451a0fe75 | 23.568182 | 208 | 0.608233 | 3.746967 | false | false | false | false |
Aioria1314/WeiBo | WeiBo/WeiBo/Classes/Views/ZXCEmoticonButton.swift | 1 | 871 | //
// ZXCEmoticonButton.swift
// WeiBo
//
// Created by Aioria on 2017/4/8.
// Copyright © 2017年 Aioria. All rights reserved.
//
import UIKit
class ZXCEmoticonButton: UIButton {
var emoticonModel: ZXCEmoticonModel? {
didSet {
guard let currentEmoticonModel = emoticonModel else {
return
}
self.isHidden = false
if currentEmoticonModel.type == "0" {
self.setImage(UIImage(named: currentEmoticonModel.path!), for: .normal)
self.setTitle(nil, for: .normal)
} else {
let emoji = (currentEmoticonModel.code! as NSString).emoji()
self.setImage(nil, for: .normal)
self.setTitle(emoji, for: .normal)
}
}
}
}
| mit | b915c787cabb4a1a7e4b4e86539431f5 | 24.529412 | 87 | 0.510369 | 4.641711 | false | false | false | false |
zyrx/eidolon | KioskTests/XAppTokenSpec.swift | 8 | 1616 | import Quick
import Nimble
@testable
import Kiosk
class XAppTokenSpec: QuickSpec {
override func spec() {
let defaults = NSUserDefaults()
let token = XAppToken()
it("returns correct data") {
let key = "some key"
let expiry = NSDate(timeIntervalSinceNow: 1000)
setDefaultsKeys(defaults, key: key, expiry: expiry)
expect(token.token).to(equal(key))
expect(token.expiry).to(equal(expiry))
}
it("correctly calculates validity for expired tokens") {
let key = "some key"
let past = NSDate(timeIntervalSinceNow: -1000)
setDefaultsKeys(defaults, key: key, expiry: past)
expect(token.isValid).to(beFalsy())
}
it("correctly calculates validity for non-expired tokens") {
let key = "some key"
let future = NSDate(timeIntervalSinceNow: 1000)
setDefaultsKeys(defaults, key: key, expiry: future)
expect(token.isValid).to(beTruthy())
}
it("correctly calculates validity for empty keys") {
let key = ""
let future = NSDate(timeIntervalSinceNow: 1000)
setDefaultsKeys(defaults, key: key, expiry: future)
expect(token.isValid).to(beFalsy())
}
it("properly calculates validity for missing tokens") {
setDefaultsKeys(defaults, key: nil, expiry: nil)
expect(token.isValid).to(beFalsy())
}
}
}
| mit | 79b67f959bfcad2e53269a6c685fd5f7 | 31.32 | 68 | 0.550124 | 5.179487 | false | false | false | false |
classmere/app | Classmere/Classmere/Service/Store.swift | 1 | 2495 | import Foundation
class Store {
fileprivate let externalFetcher: Provider
fileprivate var _buildings: [Int: Building] = [:]
fileprivate var _courses: [Int: Course] = [:]
var currentCourse: Course?
var currentSection: Section?
fileprivate(set) var buildingSearchResults: [Building] = []
fileprivate(set) var courseSearchResults: [Course] = []
init(provider: Provider) {
externalFetcher = provider
}
}
extension Store {
func get(buildingAbbr: String, completion: @escaping Completion<Building>) {
if let building = _buildings[Building(abbr: buildingAbbr).hashValue] {
completion(.success(building))
} else {
externalFetcher.get(buildingAbbr: buildingAbbr) { result in
switch result {
case .success(let building):
self._buildings[building.hashValue] = building
completion(.success(building))
case .failure(let error): completion(.failure(error))
}
}
}
}
func get(subjectCode: String, courseNumber: Int, completion: @escaping Completion<Course>) {
if let course = _courses[Course(subjectCode: subjectCode, courseNumber: courseNumber).hashValue] {
completion(.success(course))
} else {
externalFetcher.get(subjectCode: subjectCode, courseNumber: courseNumber) { result in
switch result {
case .success(let course):
self._courses[course.hashValue] = course
completion(.success(course))
case .failure(let error): completion(.failure(error))
}
}
}
}
func search(building: String, completion: @escaping Completion<[Building]>) {
externalFetcher.search(building: building) { result in
if case let .success(buildings) = result {
self.buildingSearchResults = buildings
} else {
self.buildingSearchResults = []
}
completion(result)
}
}
func search(course: String, completion: @escaping Completion<[Course]>) {
externalFetcher.search(course: course) { result in
if case let .success(courses) = result {
self.courseSearchResults = courses
} else {
self.courseSearchResults = []
}
completion(result)
}
}
}
| gpl-3.0 | 3dd61ed359934df9c524b447c75f1028 | 34.140845 | 106 | 0.578758 | 5.165631 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/StartUI/StartUI/StartUIInviteActionBar.swift | 1 | 3760 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
final class StartUIInviteActionBar: UIView {
var bottomEdgeConstraint: NSLayoutConstraint!
private(set) var inviteButton: Button!
private let padding: CGFloat = 12
init() {
super.init(frame: .zero)
backgroundColor = SemanticColors.View.backgroundUserCell
createInviteButton()
createConstraints()
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardFrameWillChange(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func createInviteButton() {
inviteButton = Button(style: .accentColorTextButtonStyle,
cornerRadius: 16,
fontSpec: .normalSemiboldFont)
inviteButton.titleEdgeInsets = UIEdgeInsets(top: 2, left: 8, bottom: 3, right: 8)
inviteButton.setTitle(L10n.Localizable.Peoplepicker.inviteMorePeople.capitalized, for: .normal)
addSubview(inviteButton)
}
override var isHidden: Bool {
didSet {
invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: isHidden ? 0 : 56.0)
}
private func createConstraints() {
inviteButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
inviteButton.leadingAnchor.constraint(equalTo: leadingAnchor, constant: padding * 2),
inviteButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -(padding * 2)),
inviteButton.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -(padding + UIScreen.safeArea.bottom)),
inviteButton.topAnchor.constraint(equalTo: topAnchor, constant: padding)
])
bottomEdgeConstraint = inviteButton.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -(padding + UIScreen.safeArea.bottom))
bottomEdgeConstraint.isActive = true
inviteButton.heightAnchor.constraint(equalToConstant: 56).isActive = true
}
// MARK: - UIKeyboard notifications
@objc
private func keyboardFrameWillChange(_ notification: Notification) {
guard let userInfo = notification.userInfo,
let beginOrigin = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.origin.y,
let endOrigin = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.origin.y
else { return }
let diff: CGFloat = beginOrigin - endOrigin
UIView.animate(withKeyboardNotification: notification, in: self, animations: { [weak self] _ in
guard let weakSelf = self else { return }
weakSelf.bottomEdgeConstraint.constant = -weakSelf.padding - (diff > 0 ? 0 : UIScreen.safeArea.bottom)
weakSelf.layoutIfNeeded()
})
}
}
| gpl-3.0 | 3be4642e8a963ce5c924a8275369dfcd | 37.762887 | 175 | 0.693085 | 5.108696 | false | false | false | false |
Trxy/TRX | TRXTests/specs/morphable/Morphable+CATransform3DSpec.swift | 1 | 1517 | import QuartzCore
@testable import TRX
import Quick
import Nimble
class Morphable_CATransform3D: QuickSpec {
override func spec() {
var subject: Tween<CATransform3D>!
var current: CATransform3D?
let start = CATransform3DIdentity
let finalValue = CATransform3DMakeTranslation(10, 20, 30)
beforeEach {
subject = Tween(from: start,
to: finalValue,
time: 1,
ease: Ease.linear,
update: {
current = $0
})
}
describe("CGAffineTransform") {
context("beginning") {
beforeEach() {
subject.seek(offset: 0)
}
it("should have correct value") {
expect(current?.m41) == start.m41
expect(current?.m42) == start.m42
expect(current?.m43) == start.m43
}
}
context("end") {
beforeEach() {
subject.seek(offset: 1)
}
it("should have correct value") {
expect(current?.m41) == finalValue.m41
expect(current?.m42) == finalValue.m42
expect(current?.m43) == finalValue.m43
}
}
context("between") {
beforeEach() {
subject.seek(offset: 0.5)
}
it("should have correct value") {
expect(current?.m41) == 5
expect(current?.m42) == 10
expect(current?.m43) == 15
}
}
}
}
}
| mit | b219fcf06102116747892955e4e4c77c | 19.5 | 61 | 0.491101 | 4.461765 | false | false | false | false |
sora0077/AppleMusicKit | Sources/Request/FetchGenres.swift | 1 | 2687 | //
// FetchGenres.swift
// AppleMusicKit
//
// Created by 林達也 on 2017/07/05.
// Copyright © 2017年 jp.sora0077. All rights reserved.
//
import Foundation
public struct GetTopChartGenres<Genre: GenreDecodable, Storefront: StorefrontDecodable>: PaginatorResourceRequest, InternalPaginatorRequest {
public typealias Resource = AppleMusicKit.Resource<Genre, NoRelationships>
public let path: String
public var parameters: [String: Any]? { return makePaginatorParameters(_parameters, request: self) }
public internal(set) var limit: Int?
public let offset: Int?
private let _parameters: [String: Any]
public init(storefront: Storefront.Identifier, language: Storefront.Language? = nil, limit: Int? = nil, offset: Int? = nil) {
self.init(path: "/v1/catalog/\(storefront)/genres",
parameters: ["l": language?.languageTag, "limit": limit, "offset": offset].cleaned)
}
init(path: String, parameters: [String: Any]) {
self.path = path
_parameters = parameters
(limit, offset) = parsePaginatorParameters(parameters)
}
}
public struct GetGenre<Genre: GenreDecodable, Storefront: StorefrontDecodable>: ResourceRequest {
public typealias Resource = AppleMusicKit.Resource<Genre, NoRelationships>
public var path: String { return "/v1/catalog/\(storefront)/genres/\(id)" }
public let parameters: [String: Any]?
private let storefront: Storefront.Identifier
private let id: Genre.Identifier
public init(storefront: Storefront.Identifier, id: Genre.Identifier, language: Storefront.Language? = nil) {
self.storefront = storefront
self.id = id
self.parameters = ["l": language?.languageTag].cleaned
}
}
public struct GetMultipleGenres<Genre: GenreDecodable, Storefront: StorefrontDecodable>: ResourceRequest {
public typealias Resource = AppleMusicKit.Resource<Genre, NoRelationships>
public var path: String { return "/v1/catalog/\(storefront)/genres" }
public let parameters: [String: Any]?
private let storefront: Storefront.Identifier
public init(storefront: Storefront.Identifier, id: Genre.Identifier, _ additions: Genre.Identifier..., language: Storefront.Language? = nil) {
self.init(storefront: storefront, ids: [id] + additions, language: language)
}
public init<C>(storefront: Storefront.Identifier,
ids: C,
language: Storefront.Language? = nil) where C: Collection, C.Element == Genre.Identifier {
assert(!ids.isEmpty)
self.storefront = storefront
self.parameters = ["ids": makeIds(ids), "l": language?.languageTag].cleaned
}
}
| mit | 046cf497b1204cab15cda577eb849cc6 | 38.382353 | 146 | 0.697909 | 4.382979 | false | false | false | false |
coderZsq/coderZsq.target.swift | StudyNotes/Foundation/Algorithm4Swift/Algorithm4Swift/Algorithm/Raywenderlich/ShellSort.swift | 1 | 796 | //
// ShellSort.swift
// Algorithm
//
// Created by 朱双泉 on 2018/5/24.
// Copyright © 2018 Castie!. All rights reserved.
//
import Foundation
public func insertionSort(_ list: inout [Int], start: Int, gap: Int) {
for i in stride(from: (start + gap), to: list.count, by: gap) {
let currentValue = list[i]
var pos = i
while pos >= gap && list[pos - gap] > currentValue {
list[pos] = list[pos - gap]
pos -= gap
}
list[pos] = currentValue
}
}
public func shellSort(_ list: inout [Int]) {
var sublistCount = list.count / 2
while sublistCount > 0 {
for pos in 0..<sublistCount {
insertionSort(&list, start: pos, gap: sublistCount)
}
sublistCount = sublistCount / 2
}
}
| mit | 95ccfdec8fb9462c00eed67137099bff | 24.451613 | 70 | 0.56654 | 3.739336 | false | false | false | false |
Corey2121/the-oakland-post | The Oakland Post/HighResImageDownloader.swift | 3 | 2387 | //
// HighResImageDownloader.swift
// The Oakland Post
//
// Functions to find and download the high-res photo corresponding to a PhotoCell.
//
// Created by Andrew Clissold on 7/26/14.
// Copyright (c) 2014 Andrew Clissold. All rights reserved.
//
private var downloadOperation: SDWebImageOperation?
private var canceled = false
func downloadHighResImageFromURL(URL: String, forEnlargedPhoto enlargedPhoto: EnlargedPhoto,
#sender: UIButton, #finished: (UIImage, Int) -> ()) {
canceled = false // reset
// Download progressed callback.
func downloadProgressed(receivedSize: Int, expectedSize: Int) {
let progress = Float(receivedSize) / Float(expectedSize)
onMain { SVProgressHUD.showProgress(progress) }
}
// Download finished callback.
// This is a let closure instead of a function because local functions cannot reference
// other local functions. Specifically, finished() can only be called this way.
let downloadFinished: (UIImage?, NSData?, NSError?, Bool) -> Void = { (image, data, error, _) in
onMain {
SVProgressHUD.dismiss()
enlargedPhoto.imageView.image = image
sender.setBackgroundImage(image, forState: .Normal)
finished(image!, sender.tag)
}
}
onMain { SVProgressHUD.showProgress(0) }
onDefault {
// Find the image URL.
let HTMLData = NSData(contentsOfURL: NSURL(string: URL)!)!
let dataString = NSString(data: HTMLData, encoding: NSUTF8StringEncoding)
let hpple = TFHpple(HTMLData: HTMLData)
let XPathQuery = "//meta[@property='og:image']"
let elements = hpple.searchWithXPathQuery(XPathQuery) as! [TFHppleElement]
if elements.count == 0 {
cancelDownloadingHighResImage()
return
}
let imageURL = elements[0].objectForKey("content")
// Download the image at that URL.
let URL = NSURL(string: imageURL)
if !canceled {
downloadOperation = SDWebImageDownloader.sharedDownloader().downloadImageWithURL(
URL, options: SDWebImageDownloaderOptions(rawValue: 0),
progress: downloadProgressed, completed: downloadFinished)
}
}
}
func cancelDownloadingHighResImage() {
onMain { SVProgressHUD.dismiss() }
downloadOperation?.cancel()
canceled = true
}
| bsd-3-clause | ce977e76761b8452c7ea1d1363d6a079 | 34.102941 | 100 | 0.664851 | 4.680392 | false | false | false | false |
karstengresch/rw_studies | CoreData/HitList/HitList/AppDelegate.swift | 1 | 4441 | //
// AppDelegate.swift
// HitList
//
// Created by Karsten Gresch on 31.05.17.
// Copyright © 2017 Closure One. All rights reserved.
//
import UIKit
import CoreData
@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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "HitList")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| unlicense | 9ee96613c0babb560bf7662a473670c2 | 46.741935 | 281 | 0.709234 | 5.656051 | false | false | false | false |
jbsohn/SteelSidekick | macOS/SteelSidekick/SwiftOpenGLView.swift | 1 | 3247 | //
// SwiftOpenGLView.swift
// SteelSidekick
//
// Created by John Sohn on 1/17/17.
// Copyright © 2017 John Sohn. All rights reserved.
//
import Cocoa
class SwiftOpenGLView: NSOpenGLView {
required init?(coder: NSCoder) {
// Allow the super class to initialize it's properties (phase 1 initialization)
super.init(coder: coder)
// Some OpenGL setup
// NSOpenGLPixelFormatAttribute is a typealias for UInt32 in Swift, but the individual
// attributes are Int's. We have initialize them as Int32's to fit them into an array
// of NSOpenGLPixelFormatAttributes
let attrs: [NSOpenGLPixelFormatAttribute] = [
UInt32(NSOpenGLPFAAccelerated), // Use accelerated renderers
UInt32(NSOpenGLPFAColorSize), UInt32(32), // Use 32-bit color
UInt32(NSOpenGLPFAOpenGLProfile), // Use version's >= 3.2 core
UInt32( NSOpenGLProfileVersion3_2Core),
UInt32(0) // C API's expect to end with 0
]
// Create a pixel format using our attributes
guard let pixelFormat = NSOpenGLPixelFormat(attributes: attrs) else {
Swift.print("pixelFormat could not be constructed")
return
}
self.pixelFormat = pixelFormat
// Create a context with our pixel format (we have no other context, so nil)
guard let context = NSOpenGLContext(format: pixelFormat, share: nil) else {
Swift.print("context could not be constructed")
return
}
self.openGLContext = context
}
override func prepareOpenGL() {
// Allow the superclass to perform it's tasks
super.prepareOpenGL()
// Setup OpenGL
// The buffer will clear each pixel to black upon starting the creation of a new frame
//glClearColor(0.0, 0.0, 0.0, 1.0)
/* other setup here, e.g. gelable() calls */
// Run a test render
drawView()
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
// Call our OpenGL rendering code.
drawView()
}
private func drawView() {
// Clear out the context before rendering
// This uses the clear color we set earlier (0.0, 0.0, 0.0, 1.0 or black)
// We're only drawing with colors now, but if we were using a depth or stencil buffer
// we would also want to clear those here separated by "logical or" " | "
// glClear(GLbitfield(GL_COLOR_BUFFER_BIT))
let sguitar = SGuitar.sharedInstance();
let noteWidthHeight = sguitar?.cacluateNoteWidthHeight(Float(self.frame.size.width), height: Float(self.frame.size.height));
sguitar?.initCanvas(Float(self.frame.size.width), height: Float(self.frame.size.height), noteWidthHeight: Float(noteWidthHeight!), borderWidth: 16.0, scale: 1.0, leftSafeArea: 0);
sguitar?.draw();
// Tell OpenGL that you're done rendering and it's time to send the context to the screen
glFlush()
}
}
| gpl-2.0 | c96cb8a5f21950e1be0acb99b901ae32 | 36.744186 | 187 | 0.601664 | 4.392422 | false | false | false | false |
mathewsheets/SwiftLearningAssignments | Todo_Assignment_2.playground/Sources/Functions.swift | 1 | 2411 | import Foundation
// todo functions
public func getTodos(closure: (Todo) -> Bool) -> [Todo]? {
return filter(todos: todos, closure: closure)
}
public func getTodo(id: String) -> Todo? {
guard let index = (indexOf(todos: todos) { $0.0 == id }) else {
return nil
}
return todos[index]
}
public func createTodo(title: String, subtitle: String, description: String) -> Todo {
return (String(todos.count), title, subtitle, description, Status.NotStarted)
}
public func addTodo(todo: Todo) -> Todo {
todos.append(todo)
return todo
}
public func updateTodo(todo: Todo) -> Todo? {
guard let index = (indexOf(todos: todos) { $0.0 == todo.0 }) else {
return nil
}
todos[index] = todo
return todo
}
public func deleteTodo(id: String) -> Todo? {
guard let index = (indexOf(todos: todos) { $0.0 == id }) else {
return nil
}
return todos.remove(at: index)
}
public func description(todo: Todo) -> String {
let (id, title, subtitle, description, status) = todo
return "id: \(id)\n\ttitle: \(title)\n\tsubtitle: \(subtitle)\n\tdescription: \(description)\n\tstatus: \(status.rawValue)"
}
// querying functions
func iterator(todos: [Todo], closure: (Todo) -> Void) {
for index in 0..<todos.count {
closure(todos[index])
}
}
public func each(todos: [Todo], closure: (Todo, Int) -> Void) {
var index = 0;
iterator(todos: todos) {
closure($0, index)
index += 1
}
}
public func pluck(todos: [Todo], closure: (Todo) -> String) -> [String] {
var plucked = [String]()
iterator(todos: todos) { plucked.append(closure($0)) }
return plucked
}
public func indexOf(todos: [Todo], closure: (Todo) -> Bool) -> Int? {
var index = -1
var found = false
iterator(todos: todos) { (todo) -> Void in
if !found {
if closure(todo) {
found = true
}
index += 1
}
}
return index == -1 || !found ? nil : index
}
public func filter(todos: [Todo], closure: (Todo) -> Bool) -> [Todo]? {
var filter = [Todo]()
iterator(todos: todos) { (todo) -> Void in
if closure(todo) {
filter.append(todo)
}
}
return !filter.isEmpty ? filter : nil
}
| mit | 9617161865c438b5ceb57cb5b300a666 | 18.92562 | 127 | 0.553297 | 3.65303 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/InviteLinksController.swift | 1 | 36665 | //
// InviteLinksController.swift
// Telegram
//
// Created by Mikhail Filimonov on 14.01.2021.
// Copyright © 2021 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import TelegramCore
import Postbox
struct _ExportedInvitation : Equatable {
var link: String
var title: String?
var isPermanent: Bool
var requestApproval: Bool
var isRevoked: Bool
var adminId: PeerId
var date: Int32
var startDate: Int32?
var expireDate: Int32?
var usageLimit: Int32?
var count: Int32?
var requestedCount: Int32?
var invitation: ExportedInvitation {
return .link(link: link, title: title, isPermanent: isPermanent, requestApproval: requestApproval, isRevoked: isRevoked, adminId: adminId, date: date, startDate: startDate, expireDate: expireDate, usageLimit: usageLimit, count: count, requestedCount: requestedCount)
}
static func initialize(_ inivitation: ExportedInvitation) -> _ExportedInvitation? {
switch inivitation {
case .link(let link, let title, let isPermanent, let requestApproval, let isRevoked, let adminId, let date, let startDate, let expireDate, let usageLimit, let count, let requestedCount):
return .init(link: link, title: title, isPermanent: isPermanent, requestApproval: requestApproval, isRevoked: isRevoked, adminId: adminId, date: date, startDate: startDate, expireDate: expireDate, usageLimit: usageLimit, count: count, requestedCount: requestedCount)
case .publicJoinRequest:
return nil
}
}
}
extension _ExportedInvitation {
var isExpired: Bool {
if let expiryDate = expireDate {
if expiryDate < Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970) {
return true
}
}
return false
}
var isLimitReached: Bool {
if let usageLimit = usageLimit, let count = count {
if usageLimit == count {
return true
}
}
return false
}
func withUpdatedIsRevoked(_ isRevoked: Bool) -> _ExportedInvitation {
return _ExportedInvitation(link: self.link, title: self.title, isPermanent: self.isPermanent, requestApproval: self.requestApproval, isRevoked: isRevoked, adminId: self.adminId, date: self.date, startDate: self.startDate, expireDate: self.expireDate, usageLimit: self.usageLimit, count: self.count, requestedCount: self.requestedCount)
}
}
extension ExportedInvitation {
var _invitation: _ExportedInvitation? {
return _ExportedInvitation.initialize(self)
}
}
final class InviteLinkPeerManager {
struct State : Equatable {
var list: [_ExportedInvitation]?
var next: _ExportedInvitation?
var creators:[ExportedInvitationCreator]?
var totalCount: Int32
var activeLoaded: Bool
var revokedList: [_ExportedInvitation]?
var nextRevoked: _ExportedInvitation?
var totalRevokedCount: Int32
var revokedLoaded: Bool
var effectiveCount: Int32 {
return totalCount + (self.creators?.reduce(0, { current, value in
return current + value.count
}) ?? 0)
}
static var `default`: State {
return State(list: nil, next: nil, creators: nil, totalCount: 0, activeLoaded: false, revokedList: nil, nextRevoked: nil, totalRevokedCount: 0, revokedLoaded: false)
}
}
let context: AccountContext
let peerId: PeerId
let adminId: PeerId?
private let listDisposable = DisposableDict<Bool>()
private let loadCreatorsDisposable = MetaDisposable()
private let stateValue: Atomic<State> = Atomic(value: State.default)
private let statePromise = ValuePromise(State.default, ignoreRepeated: true)
private func updateState(_ f: (State) -> State) {
statePromise.set(stateValue.modify (f))
}
var state: Signal<State, NoError> {
return self.statePromise.get()
}
deinit {
listDisposable.dispose()
loadCreatorsDisposable.dispose()
updateAdminsDisposable.dispose()
}
private let updateAdminsDisposable = MetaDisposable()
init(context: AccountContext, peerId: PeerId, adminId: PeerId? = nil) {
self.context = context
self.peerId = peerId
self.adminId = adminId
self.loadNext()
self.loadNext(true)
if adminId == nil {
self.loadCreators()
let (disposable, _) = context.peerChannelMemberCategoriesContextsManager.admins(peerId: peerId, updated: { [weak self] _ in
self?.loadCreators()
})
updateAdminsDisposable.set(disposable)
}
}
func createPeerExportedInvitation(title: String?, expireDate: Int32?, usageLimit: Int32?, requestNeeded: Bool? = nil) -> Signal<_ExportedInvitation?, NoError> {
let context = self.context
let peerId = self.peerId
return Signal { [weak self] subscriber in
let signal = context.engine.peers.createPeerExportedInvitation(peerId: peerId, title: title, expireDate: expireDate, usageLimit: usageLimit, requestNeeded: requestNeeded) |> deliverOnMainQueue
let disposable = signal.start(next: { [weak self] value in
self?.updateState { state in
var state = state
state.list = state.list ?? []
if let value = value?._invitation {
state.list?.insert(value, at: 0)
state.totalCount += 1
}
return state
}
subscriber.putNext(value?._invitation)
subscriber.putCompletion()
})
return disposable
}
}
func editPeerExportedInvitation(link: _ExportedInvitation, title: String?, expireDate: Int32?, usageLimit: Int32?, requestNeeded: Bool? = nil) -> Signal<NoValue, EditPeerExportedInvitationError> {
let context = self.context
let peerId = self.peerId
return Signal { [weak self] subscriber in
let signal = context.engine.peers.editPeerExportedInvitation(peerId: peerId, link: link.link, title: title, expireDate: expireDate, usageLimit: usageLimit, requestNeeded: requestNeeded)
let disposable = signal.start(next: { [weak self] value in
self?.updateState { state in
var state = state
state.list = state.list ?? []
if let value = value?._invitation, let index = state.list?.firstIndex(where: { $0.link == value.link }) {
state.list?[index] = value
}
return state
}
subscriber.putCompletion()
}, error: { error in
subscriber.putError(error)
})
return disposable
}
}
func revokePeerExportedInvitation(link: _ExportedInvitation) -> Signal<NoValue, RevokePeerExportedInvitationError> {
let context = self.context
let peerId = self.peerId
return Signal { [weak self] subscriber in
let signal: Signal<RevokeExportedInvitationResult?, RevokePeerExportedInvitationError>
signal = context.engine.peers.revokePeerExportedInvitation(peerId: peerId, link: link.link)
let disposable = signal.start(next: { [weak self] value in
self?.updateState { state in
var state = state
state.list = state.list ?? []
if let value = value {
switch value {
case let .update(link):
if let link = link._invitation {
state.revokedList = state.revokedList ?? []
state.list!.removeAll(where: { $0.link == link.link})
state.revokedList?.append(link)
state.revokedList?.sort(by: { $0.date < $1.date })
state.totalCount -= 1
}
case let .replace(link, new):
if let link = link._invitation, let new = new._invitation {
let link = link.withUpdatedIsRevoked(true)
state.revokedList = state.revokedList ?? []
state.list!.removeAll(where: { $0.link == link.link})
state.list!.insert(new, at: 0)
state.revokedList?.insert(link, at: 0)
state.revokedList?.sort(by: { $0.date > $1.date })
}
}
}
return state
}
subscriber.putCompletion()
}, error: { error in
subscriber.putError(error)
})
return disposable
}
}
func deletePeerExportedInvitation(link: _ExportedInvitation) -> Signal<Never, DeletePeerExportedInvitationError> {
let context = self.context
let peerId = self.peerId
return Signal { [weak self] subscriber in
let signal = context.engine.peers.deletePeerExportedInvitation(peerId: peerId, link: link.link)
let disposable = signal.start(error: { error in
subscriber.putError(error)
}, completed: { [weak self] in
self?.updateState { state in
var state = state
state.revokedList = state.revokedList ?? []
state.revokedList?.removeAll(where: { $0.link == link.link })
state.totalRevokedCount -= 1
return state
}
subscriber.putCompletion()
})
return disposable
}
}
func deleteAllRevokedPeerExportedInvitations() -> Signal<Never, NoError> {
let context = self.context
let peerId = self.peerId
return Signal { [weak self] subscriber in
let signal = context.engine.peers.deleteAllRevokedPeerExportedInvitations(peerId: peerId, adminId: self?.adminId ?? context.peerId)
let disposable = signal.start(completed: {
self?.updateState { state in
var state = state
state.revokedList?.removeAll()
state.totalRevokedCount = 0
state.nextRevoked = nil
state.revokedLoaded = true
return state
}
subscriber.putCompletion()
})
return disposable
}
}
func loadCreators() {
let signal = context.engine.peers.peerExportedInvitationsCreators(peerId: peerId) |> deliverOnMainQueue
loadCreatorsDisposable.set(signal.start(next: { [weak self] creators in
self?.updateState { state in
var state = state
state.creators = creators
return state
}
}))
}
func loadNext(_ forceLoadRevoked: Bool = false) {
let revoked = forceLoadRevoked ? true : stateValue.with { $0.activeLoaded }
if stateValue.with({ revoked ? !$0.revokedLoaded : !$0.activeLoaded }) {
let offsetLink: _ExportedInvitation? = stateValue.with { state in
if revoked {
return state.nextRevoked
} else {
return state.next
}
}
let signal = context.engine.peers.direct_peerExportedInvitations(peerId: peerId, revoked: revoked, adminId: self.adminId, offsetLink: offsetLink?.invitation) |> deliverOnMainQueue
self.listDisposable.set(signal.start(next: { [weak self] list in
self?.updateState { state in
var state = state
if revoked {
state.revokedList = (state.revokedList ?? []) + (list?.list?.compactMap { $0._invitation } ?? [])
state.totalRevokedCount = list?.totalCount ?? 0
state.revokedLoaded = state.revokedList?.count == Int(state.totalRevokedCount)
state.nextRevoked = state.revokedList?.last
} else {
state.list = (state.list ?? []) + (list?.list?.compactMap { $0._invitation } ?? [])
state.totalCount = list?.totalCount ?? 0
state.activeLoaded = state.list?.count == Int(state.totalCount)
state.next = state.list?.last
}
return state
}
}), forKey: revoked)
}
}
private struct CachedKey : Hashable {
let string: String
let requested: Bool
}
private var cachedImporters:[CachedKey : PeerInvitationImportersContext] = [:]
func importer(for link: _ExportedInvitation) -> (joined: PeerInvitationImportersContext, requested: PeerInvitationImportersContext) {
let joined = self.cachedImporters[.init(string: link.link, requested: false)]
let requested = self.cachedImporters[.init(string: link.link, requested: true)]
if let requested = requested, let joined = joined {
return (joined: joined, requested: requested)
} else {
let joined = context.engine.peers.peerInvitationImporters(peerId: peerId, subject: .invite(invite: link.invitation, requested: false))
let requested = context.engine.peers.peerInvitationImporters(peerId: peerId, subject: .invite(invite: link.invitation, requested: true))
self.cachedImporters[.init(string: link.link, requested: false)] = joined
self.cachedImporters[.init(string: link.link, requested: true)] = requested
return (joined: joined, requested: requested)
}
}
}
private final class InviteLinksArguments {
let context: AccountContext
let shareLink: (String)->Void
let copyLink: (String)->Void
let revokeLink: (_ExportedInvitation)->Void
let editLink:(_ExportedInvitation)->Void
let deleteLink:(_ExportedInvitation)->Void
let deleteAll:()->Void
let newLink:()->Void
let open:(_ExportedInvitation)->Void
let openAdminLinks:(ExportedInvitationCreator)->Void
init(context: AccountContext, shareLink: @escaping(String)->Void, copyLink: @escaping(String)->Void, revokeLink: @escaping(_ExportedInvitation)->Void, editLink:@escaping(_ExportedInvitation)->Void, newLink:@escaping()->Void, deleteLink:@escaping(_ExportedInvitation)->Void, deleteAll:@escaping()->Void, open:@escaping(_ExportedInvitation)->Void, openAdminLinks: @escaping(ExportedInvitationCreator)->Void) {
self.context = context
self.shareLink = shareLink
self.copyLink = copyLink
self.revokeLink = revokeLink
self.editLink = editLink
self.newLink = newLink
self.deleteLink = deleteLink
self.deleteAll = deleteAll
self.open = open
self.openAdminLinks = openAdminLinks
}
}
private struct InviteLinksState : Equatable {
var permanent: _ExportedInvitation?
var permanentImporterState: PeerInvitationImportersState?
var list: [_ExportedInvitation]?
var revokedList: [_ExportedInvitation]?
var creators:[ExportedInvitationCreator]?
var isAdmin: Bool
var totalCount: Int
var peer: PeerEquatable?
var adminPeer: PeerEquatable?
}
private let _id_header = InputDataIdentifier("_id_header")
private let _id_permanent = InputDataIdentifier("_id_permanent")
private let _id_add_link = InputDataIdentifier("_id_add_link")
private let _id_loading = InputDataIdentifier("_id_loading")
private let _id_delete_all = InputDataIdentifier("_id_delete_all")
private func _id_links(_ links:[_ExportedInvitation]) -> InputDataIdentifier {
return InputDataIdentifier("active_" + links.reduce("", { current, value in
return current + value.link
}))
}
private func _id_links_revoked(_ links:[_ExportedInvitation]) -> InputDataIdentifier {
return InputDataIdentifier("revoked_" + links.reduce("", { current, value in
return current + value.link
}))
}
private func _id_creator(_ peerId: PeerId) -> InputDataIdentifier {
return InputDataIdentifier("_id_creator_\(peerId.toInt64())")
}
private func entries(_ state: InviteLinksState, arguments: InviteLinksArguments) -> [InputDataEntry] {
var entries: [InputDataEntry] = []
var sectionId: Int32 = 0
var index: Int32 = 0
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
if !state.isAdmin {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_header, equatable: nil, comparable: nil, item: { initialSize, stableId in
let text:String = state.peer?.peer.isChannel == true ? strings().manageLinksHeaderChannelDesc : strings().manageLinksHeaderGroupDesc
return AnimatedStickerHeaderItem(initialSize, stableId: stableId, context: arguments.context, sticker: LocalAnimatedSticker.invitations, text: .initialize(string: text, color: theme.colors.listGrayText, font: .normal(.text)))
}))
index += 1
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
}
// if !state.isAdmin || state.peer?.peer.addressName == nil {
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().manageLinksInviteLink), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
var peers = state.permanentImporterState?.importers.map { $0.peer } ?? []
peers = Array(peers.prefix(3))
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_permanent, equatable: InputDataEquatable(state), comparable: nil, item: { initialSize, stableId in
return ExportedInvitationRowItem(initialSize, stableId: stableId, context: arguments.context, exportedLink: state.permanent, publicAddress: state.isAdmin ? nil : state.peer?.peer.addressName, lastPeers: peers, viewType: .singleItem, menuItems: {
var items:[ContextMenuItem] = []
if let permanent = state.permanent {
items.append(ContextMenuItem(strings().manageLinksContextCopy, handler: {
arguments.copyLink(permanent.link)
}, itemImage: MenuAnimation.menu_copy.value))
if state.adminPeer?.peer.isBot == true {
} else {
if !items.isEmpty {
items.append(ContextSeparatorItem())
}
items.append(ContextMenuItem(strings().manageLinksContextRevoke, handler: {
arguments.revokeLink(permanent)
}, itemMode: .destruct, itemImage: MenuAnimation.menu_delete.value))
}
} else if let addressName = state.peer?.peer.addressName {
items.append(ContextMenuItem(strings().manageLinksContextCopy, handler: {
arguments.copyLink(addressName)
}, itemImage: MenuAnimation.menu_copy.value))
}
return .single(items)
}, share: arguments.shareLink, open: arguments.open, copyLink: arguments.copyLink)
}))
if state.isAdmin, let peer = state.peer, let adminPeer = state.adminPeer {
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().manageLinksAdminPermanentDesc(adminPeer.peer.displayTitle, peer.peer.displayTitle)), data: .init(color: theme.colors.listGrayText, viewType: .textBottomItem)))
index += 1
}
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
// }
if !state.isAdmin || (state.list != nil && !state.list!.isEmpty) {
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().manageLinksAdditionLinks), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
}
struct Tuple : Equatable {
let link: _ExportedInvitation
let viewType: GeneralViewType
}
let viewType: GeneralViewType = state.list == nil || !state.list!.isEmpty ? .firstItem : .singleItem
if !state.isAdmin {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_add_link, equatable: InputDataEquatable(viewType), comparable: nil, item: { initialSize, stableId in
return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().manageLinksCreateNew, nameStyle: blueActionButton, type: .none, viewType: viewType, action: arguments.newLink, drawCustomSeparator: true, thumb: GeneralThumbAdditional(thumb: theme.icons.proxyAddProxy, textInset: 43, thumbInset: 0))
}))
index += 1
// entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_add_link, data: .init(name: strings().manageLinksCreateNew, color: theme.colors.accent, icon: theme.icons.proxyAddProxy, type: .none, viewType: viewType, enabled: true, action: arguments.newLink)))
// index += 1
}
if let list = state.list {
if !list.isEmpty {
for (i, link) in list.enumerated() {
var viewType: GeneralViewType = bestGeneralViewType(list, for: i)
if i == 0, !state.isAdmin {
if list.count == 1 {
viewType = .lastItem
} else {
viewType = .innerItem
}
}
let tuple = Tuple(link: link, viewType: viewType)
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_links([link]), equatable: InputDataEquatable(tuple), comparable: nil, item: { initialSize, stableId in
return InviteLinkRowItem(initialSize, stableId: stableId, viewType: tuple.viewType, link: tuple.link, action: arguments.open, menuItems: { link in
var items:[ContextMenuItem] = []
items.append(ContextMenuItem(strings().manageLinksContextCopy, handler: {
arguments.copyLink(link.link)
}, itemImage: MenuAnimation.menu_copy.value))
if !link.isRevoked {
if !link.isExpired {
items.append(ContextMenuItem(strings().manageLinksContextShare, handler: {
arguments.shareLink(link.link)
}, itemImage: MenuAnimation.menu_share.value))
}
if !link.isPermanent {
items.append(ContextMenuItem(strings().manageLinksContextEdit, handler: {
arguments.editLink(link)
}, itemImage: MenuAnimation.menu_edit.value))
}
if state.adminPeer?.peer.isBot == true {
} else {
if !items.isEmpty {
items.append(ContextSeparatorItem())
}
items.append(ContextMenuItem(strings().manageLinksContextRevoke, handler: {
arguments.revokeLink(link)
}, itemMode: .destruct, itemImage: MenuAnimation.menu_delete.value))
}
}
return .single(items)
})
}))
index += 1
}
} else {
if !state.isAdmin {
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().manageLinksEmptyDesc), data: .init(color: theme.colors.listGrayText, viewType: .textBottomItem)))
index += 1
}
}
if let list = state.revokedList, list.count > 0 {
if state.list?.isEmpty == false || !state.isAdmin {
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
}
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().manageLinksRevokedLinks), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
// if !state.isAdmin {
entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_delete_all, data: .init(name: strings().manageLinksDeleteAll, color: theme.colors.redUI, icon: nil, type: .none, viewType: .firstItem, enabled: true, action: arguments.deleteAll)))
index += 1
// }
for (i, link) in list.enumerated() {
var viewType: GeneralViewType = bestGeneralViewType(list, for: i)
if i == 0 {
if list.count == 1 {
viewType = .lastItem
} else {
viewType = .innerItem
}
}
let tuple = Tuple(link: link, viewType: viewType)
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_links_revoked([link]), equatable: InputDataEquatable(tuple), comparable: nil, item: { initialSize, stableId in
return InviteLinkRowItem(initialSize, stableId: stableId, viewType: tuple.viewType, link: tuple.link, action: arguments.open, menuItems: { link in
var items:[ContextMenuItem] = []
items.append(ContextMenuItem(strings().manageLinksDelete, handler: {
arguments.deleteLink(link)
}))
return .single(items)
})
}))
index += 1
}
}
} else {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_loading, equatable: nil, comparable: nil, item: { initialSize, stableId in
return GeneralLoadingRowItem(initialSize, stableId: stableId, viewType: !state.isAdmin ? .lastItem : .singleItem)
}))
index += 1
}
if let creators = state.creators, !creators.isEmpty {
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().manageLinksOtherAdmins), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
let creators = creators.filter { $0.peer.peer != nil }
for (i, creator) in creators.enumerated() {
let viewType = bestGeneralViewType(creators, for: i)
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_creator(creator.peer.peerId), equatable: InputDataEquatable(creator), comparable: nil, item: { initialSize, stableId in
return ShortPeerRowItem(initialSize, peer: creator.peer.peer!, account: arguments.context.account, context: arguments.context, stableId: stableId, height: 50, photoSize: NSMakeSize(36, 36), status: strings().manageLinksTitleCountCountable(Int(creator.count)), inset: NSEdgeInsets(left: 30, right: 30), viewType: viewType, action: {
arguments.openAdminLinks(creator)
})
}))
}
}
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
return entries
}
func InviteLinksController(context: AccountContext, peerId: PeerId, manager: InviteLinkPeerManager?) -> InputDataController {
let initialState = InviteLinksState(permanent: nil, permanentImporterState: nil, list: nil, creators: nil, isAdmin: manager?.adminId != nil, totalCount: 0)
let statePromise = ValuePromise<InviteLinksState>(ignoreRepeated: true)
let stateValue = Atomic(value: initialState)
let updateState: ((InviteLinksState) -> InviteLinksState) -> Void = { f in
statePromise.set(stateValue.modify (f))
}
let manager = manager ?? InviteLinkPeerManager(context: context, peerId: peerId)
var getController:(()->ViewController?)? = nil
let arguments = InviteLinksArguments(context: context, shareLink: { link in
showModal(with: ShareModalController(ShareLinkObject(context, link: link)), for: context.window)
}, copyLink: { link in
getController?()?.show(toaster: ControllerToaster(text: strings().shareLinkCopied))
copyToClipboard(link)
}, revokeLink: { [weak manager] link in
confirm(for: context.window, header: strings().channelRevokeLinkConfirmHeader, information: strings().channelRevokeLinkConfirmText, okTitle: strings().channelRevokeLinkConfirmOK, cancelTitle: strings().modalCancel, successHandler: { _ in
if let manager = manager {
_ = showModalProgress(signal: manager.revokePeerExportedInvitation(link: link), for: context.window).start(completed:{
_ = showModalSuccess(for: context.window, icon: theme.icons.successModalProgress, delay: 1.5).start()
})
}
})
}, editLink: { [weak manager] link in
showModal(with: ClosureInviteLinkController(context: context, peerId: peerId, mode: .edit(link), save: { [weak manager] updated in
let signal = manager?.editPeerExportedInvitation(link: link, title: updated.title, expireDate: updated.date == .max ? nil : updated.date + Int32(Date().timeIntervalSince1970), usageLimit: updated.count == .max ? nil : updated.count, requestNeeded: updated.requestApproval)
if let signal = signal {
_ = showModalProgress(signal: signal, for: context.window).start(completed:{
_ = showModalSuccess(for: context.window, icon: theme.icons.successModalProgress, delay: 1.5).start()
})
}
}), for: context.window)
}, newLink: { [weak manager] in
showModal(with: ClosureInviteLinkController(context: context, peerId: peerId, mode: .new, save: { [weak manager] link in
let signal = manager?.createPeerExportedInvitation(title: link.title, expireDate: link.date == .max ? nil : link.date + Int32(Date().timeIntervalSince1970), usageLimit: link.count == .max ? nil : link.count, requestNeeded: link.requestApproval)
if let signal = signal {
_ = showModalProgress(signal: signal, for: context.window).start(next: { invitation in
if let invitation = invitation {
copyToClipboard(invitation.link)
showModalText(for: context.window, text: strings().inviteLinkCreateCopied)
}
})
}
}), for: context.window)
}, deleteLink: { [weak manager] link in
if let manager = manager {
_ = showModalProgress(signal: manager.deletePeerExportedInvitation(link: link), for: context.window).start(completed:{
_ = showModalSuccess(for: context.window, icon: theme.icons.successModalProgress, delay: 1.5).start()
})
}
}, deleteAll: { [weak manager] in
confirm(for: context.window, header: strings().manageLinksDeleteAll, information: strings().manageLinksDeleteAllConfirm, okTitle: strings().manageLinksDeleteAll, cancelTitle: strings().modalCancel, successHandler: { [weak manager] _ in
if let manager = manager {
_ = showModalProgress(signal: manager.deleteAllRevokedPeerExportedInvitations(), for: context.window).start(completed:{
_ = showModalSuccess(for: context.window, icon: theme.icons.successModalProgress, delay: 1.5).start()
})
}
})
}, open: { [weak manager] invitation in
if let manager = manager {
showModal(with: ExportedInvitationController(invitation: invitation, peerId: peerId, accountContext: context, manager: manager, context: manager.importer(for: invitation)), for: context.window)
}
}, openAdminLinks: { creator in
let manager = InviteLinkPeerManager(context: context, peerId: peerId, adminId: creator.peer.peerId)
getController?()?.navigationController?.push(InviteLinksController(context: context, peerId: peerId, manager: manager))
})
let actionsDisposable = DisposableSet()
let importers: Signal<(PeerInvitationImportersState?, InviteLinkPeerManager.State), NoError> = manager.state |> deliverOnMainQueue |> mapToSignal { [weak manager] state in
if let permanent = state.list?.first(where: { $0.isPermanent }) {
if let importer = manager?.importer(for: permanent).joined {
return importer.state |> map(Optional.init) |> map { ($0, state) }
} else {
return .single((nil, state))
}
} else {
return .single((nil, state))
}
}
var peers: [Signal<PeerEquatable, NoError>] = []
peers.append(context.account.postbox.loadedPeerWithId(peerId) |> map { PeerEquatable($0) })
if let adminId = manager.adminId {
peers.append(context.account.postbox.loadedPeerWithId(adminId) |> map { PeerEquatable($0) })
}
actionsDisposable.add(combineLatest(manager.state, importers, combineLatest(peers)).start(next: { state, permanentImporterState, peers in
updateState { current in
var current = current
current.peer = peers.first
if peers.count == 2 {
current.adminPeer = peers.last
}
if current.peer?.peer.addressName != nil && !current.isAdmin {
current.permanent = nil
} else {
current.permanent = state.list?.first(where: { $0.isPermanent })
}
current.permanentImporterState = permanentImporterState.0
current.list = state.list?.filter({ $0.link != current.permanent?.link })
current.revokedList = state.revokedList
current.creators = state.creators
current.totalCount = Int(state.totalCount)
return current
}
}))
let signal = statePromise.get() |> map {
return InputDataSignalValue(entries: entries($0, arguments: arguments), animated: true)
}
let controller = InputDataController(dataSignal: signal, title: strings().manageLinksTitleNew, removeAfterDisappear: false, hasDone: false)
controller.onDeinit = {
actionsDisposable.dispose()
}
controller.getTitle = {
let peer = stateValue.with { $0.adminPeer?.peer }
if let peer = peer {
return peer.displayTitle
} else {
return strings().manageLinksTitleNew
}
}
controller.getStatus = {
let isAdmin = stateValue.with { $0.isAdmin }
if isAdmin {
return strings().manageLinksTitleCountCountable(stateValue.with { $0.totalCount })
} else {
return nil
}
}
controller.didLoaded = { [weak manager] controller, _ in
controller.tableView.setScrollHandler { position in
switch position.direction {
case .bottom:
manager?.loadNext()
default:
break
}
}
}
controller.afterTransaction = { controller in
controller.requestUpdateCenterBar()
}
controller.contextObject = manager
getController = { [weak controller] in
return controller
}
return controller
}
| gpl-2.0 | f645dc58e141854ec4cf464bf1d5363a | 45.468948 | 411 | 0.595571 | 5.104274 | false | false | false | false |
cherrythia/FYP | FYP Table/BarViewController_Table.swift | 1 | 8869 | //
// TableViewController.swift
// FYP Table
//
// Created by Chia Wei Zheng Terry on 7/2/15.
// Copyright (c) 2015 Chia Wei Zheng Terry. All rights reserved.
//
import UIKit
import CoreData
class BarViewController_Table: UITableViewController {
@IBOutlet weak var addBarButton: UIBarButtonItem!
var barVar : Array <AnyObject> = []
//These arrays are to be passed to cal function later
var areaArray : [Float] = []
var youngModArray : [Float] = []
var lengthArray : [Float] = []
var forceBarArray : [Float] = []
override func viewDidLoad() {
super.viewDidLoad()
title = "Bars' Variables"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "barCell")
}
override func viewDidAppear(_ animated: Bool) {
let appDel : AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context : NSManagedObjectContext = appDel.managedObjectContext!
let freq = NSFetchRequest<NSFetchRequestResult>(entityName : "BarVariables")
//barVar = context.executeFetchRequest(freq, error: nil)!
do {
try barVar = context.fetch(freq)
} catch {
}
if(isCheckedGlobal == true){
addBarButton.isEnabled = false
}
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override var canBecomeFirstResponder : Bool{
return true
}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if(event?.subtype == UIEventSubtype.motionShake){
let appDel : AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context : NSManagedObjectContext = appDel.managedObjectContext!
var error : NSError?
for object in barVar as! [NSManagedObject] {
context.delete(object)
}
do {
try context.save()
} catch {
print("save failed : \(error)")
}
barVar.removeAll(keepingCapacity: true)
isCheckedGlobal = false
addBarButton.isEnabled = true
self.tableView.reloadData()
self.viewDidLoad()
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerHeight : CGFloat = (tableView.frame.size.height - (CGFloat(barVar.count) * 45.0) - 44.0 - 0.0 - 64.0) //check value if is okay, because SpringViewController - 64.0
let footerCell = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: footerHeight))
/********************************** View of footerCell edit here***********************************/
return footerCell
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let footerHeight : CGFloat = (tableView.frame.size.height - (CGFloat(barVar.count) * 45.0) - 44.0 - 0.0 - 64.0 ) //check value if is okay, because SpringViewController - 64.0
return footerHeight
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "detail", sender: self)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return barVar.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "barCell"
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: cellIdentifier)
var data : NSManagedObject = barVar[indexPath.row] as! NSManagedObject
cell!.textLabel!.text = "Bar \(indexPath.row + 1)"
cell!.textLabel!.font = UIFont.boldSystemFont(ofSize: 17)
var force : Float = data.value(forKey: "force") as! Float
var area : Float = data.value(forKey: "area") as! Float
var length : Float = data.value(forKey: "length") as! Float
var youngMod : Float = data.value(forKey: "youngMod") as! Float
cell!.detailTextLabel!.text = "Force = \(force)\tArea =\(area)\tLength =\(length)\tYoung Mod =\(youngMod)"
cell!.detailTextLabel!.textColor = UIColor.darkGray
cell!.detailTextLabel!.font = UIFont.systemFont(ofSize: 9)
cell!.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
return cell!
}
//Prepare arrays to be passed into calculations
//ForceArray + Negative at the wall for calculation later
func arrayPrepareForCalculation () {
forceBarArray.append(0)
for index in 0..<barVar.count {
let selectedItem : NSManagedObject = barVar[index] as! NSManagedObject
let tempForce : Float = selectedItem.value(forKey: "force") as! Float
let tempArea : Float = selectedItem.value(forKey: "area") as! Float
let tempLength : Float = selectedItem.value(forKey: "length") as! Float
let tempMod : Float = selectedItem.value(forKey: "youngMod") as! Float
forceBarArray.append(tempForce)
areaArray.append(tempArea)
lengthArray.append(tempLength)
youngModArray.append(tempMod)
print(forceBarArray)
print(areaArray)
print(lengthArray)
print(youngModArray)
}
for index in 0 ... (barVar.count){ //Negative Value for forceAtWall here
forceBarArray[0] += forceBarArray[index]
}
forceBarArray[0] = -(forceBarArray[0])
}
@IBAction func addBar(_ sender: AnyObject) {
self.performSegue(withIdentifier: "addBar", sender: sender)
}
@IBAction func solve_PressedBar(_ sender: AnyObject) {
self.performSegue(withIdentifier: "SolveBar", sender: sender)
}
override func prepare ( for segue: UIStoryboardSegue, sender: Any!) {
if (segue.identifier == "addBar"){
let svcBarInsertVariables = segue.destination as! BarInsertVariables
svcBarInsertVariables.tempCount = barVar.count
}
if (segue.identifier == "SolveBar") {
arrayPrepareForCalculation()
let segueToBarResults = segue.destination as! BarViewController_Results
segueToBarResults.forceBarWall2 = forceBarArray
segueToBarResults.length2 = lengthArray
segueToBarResults.youngMod2 = youngModArray
segueToBarResults.diamter2 = areaArray
segueToBarResults.barCount = barVar.count
}
if (segue.identifier == "detail"){
let insertBarVarViewController : BarInsertVariables = segue.destination as! BarInsertVariables
let selectedItem : NSManagedObject = barVar[self.tableView.indexPathForSelectedRow!.row] as! NSManagedObject
let tempForce : Float = selectedItem.value(forKey: "force") as! Float
let tempArea : Float = selectedItem.value(forKey: "area") as! Float
let tempLength : Float = selectedItem.value(forKey: "length") as! Float
let tempMod : Float = selectedItem.value(forKey: "youngMod") as! Float
insertBarVarViewController.tempForce = tempForce
insertBarVarViewController.tempArea = tempArea
insertBarVarViewController.tempLength = tempLength
insertBarVarViewController.tempMod = tempMod
insertBarVarViewController.tempCount = self.tableView.indexPathForSelectedRow!.row
insertBarVarViewController.tempMangObj = selectedItem
if(self.tableView.indexPathForSelectedRow!.row != (barVar.count - 1)){
let tempCanCheckCheckedBox : Bool = false
insertBarVarViewController.tempCanCheckCheckedBox = tempCanCheckCheckedBox
}
else{
let tempCanCheckCheckedBox : Bool = true
insertBarVarViewController.tempCanCheckCheckedBox = tempCanCheckCheckedBox
}
}
}
}
| mit | 2770c1c9ee5e97c83adc70c9b4c99246 | 37.56087 | 184 | 0.613147 | 5.427785 | false | false | false | false |
huonw/swift | test/Interpreter/tuples.swift | 32 | 1043 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
typealias Interval = (lo: Int, hi: Int)
infix operator <+> {}
infix operator <-> {}
infix operator <+>= {}
func <+>(a: Interval, b: Interval) -> Interval {
return (a.lo + b.lo, a.hi + b.hi)
}
func <->(a: Interval, b: Interval) -> Interval {
return (a.lo - b.hi, a.hi - b.lo)
}
func <+>=(a: inout Interval, b: Interval) {
a.lo += b.lo
a.hi += b.hi
}
func print(_ x: Interval) {
print("(lo=\(x.lo), hi=\(x.hi))")
}
// CHECK: (lo=4, hi=6)
print((1,2) <+> (3,4))
// CHECK: (lo=4, hi=6)
print((hi:2,lo:1) <+> (lo:3,hi:4))
// CHECK: (lo=1, hi=3)
print((3,4) <-> (1,2))
func mutate() {
var x:Interval = (1, 2)
x <+>= (3, 4)
// CHECK: (lo=4, hi=6)
print(x)
}
mutate()
func printInts(_ ints: Int...) {
print("\(ints.count) ints: ", terminator: "")
for int in ints {
print("\(int) ", terminator: "")
}
print("\n", terminator: "")
}
// CHECK: 0 ints
printInts()
// CHECK: 1 ints: 1
printInts(1)
// CHECK: 3 ints: 1 2 3
printInts(1,2,3)
| apache-2.0 | c1942fb37163abe331cb57b947d9f17f | 17.963636 | 48 | 0.542665 | 2.471564 | false | false | false | false |
huonw/swift | stdlib/public/SDK/Foundation/NSIndexSet.swift | 29 | 1460 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
// FIXME: move inside NSIndexSet when the compiler supports this.
public struct NSIndexSetIterator : IteratorProtocol {
public typealias Element = Int
internal let _set: NSIndexSet
internal var _first: Bool = true
internal var _current: Int?
internal init(set: NSIndexSet) {
self._set = set
self._current = nil
}
public mutating func next() -> Int? {
if _first {
_current = _set.firstIndex
_first = false
} else if let c = _current {
_current = _set.indexGreaterThanIndex(c)
} else {
// current is already nil
}
if _current == NSNotFound {
_current = nil
}
return _current
}
}
extension NSIndexSet : Sequence {
/// Return an *iterator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func makeIterator() -> NSIndexSetIterator {
return NSIndexSetIterator(set: self)
}
}
| apache-2.0 | e6ba79775c48f9fefe6de8a9ab03046f | 27.627451 | 80 | 0.597945 | 4.649682 | false | false | false | false |
leberwurstsaft/XLForm | Examples/Swift/SwiftExample/SelectorsFormViewController.swift | 5 | 12715 | //
// SelectorsFormViewController.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.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 MapKit
// Mark - NSValueTransformer
class NSArrayValueTrasformer : NSValueTransformer {
override class func transformedValueClass() -> AnyClass {
return NSString.self
}
override class func allowsReverseTransformation() -> Bool {
return false
}
override func transformedValue(value: AnyObject?) -> AnyObject? {
if let arrayValue = value as? Array<AnyObject> {
return String(format: "%d Item%@", arrayValue.count, arrayValue.count > 1 ? "s" : "")
}
else if let stringValue = value as? String {
return String(format: "%@ - ) - Transformed", stringValue)
}
return nil
}
}
class ISOLanguageCodesValueTranformer : NSValueTransformer {
override class func transformedValueClass() -> AnyClass {
return NSString.self
}
override class func allowsReverseTransformation() -> Bool {
return false
}
override func transformedValue(value: AnyObject?) -> AnyObject? {
if let stringValue = value as? String {
return NSLocale.currentLocale().displayNameForKey(NSLocaleLanguageCode, value: stringValue)
}
return nil
}
}
// Mark - SelectorsFormViewController
class SelectorsFormViewController : XLFormViewController {
private struct Tags {
static let Push = "selectorPush"
static let Popover = "selectorPopover"
static let ActionSheet = "selectorActionSheet"
static let AlertView = "selectorAlertView"
static let PickerView = "selectorPickerView"
static let Picker = "selectorPicker"
static let PickerViewInline = "selectorPickerViewInline"
static let MultipleSelector = "multipleSelector"
static let MultipleSelectorPopover = "multipleSelectorPopover"
static let DynamicSelectors = "dynamicSelectors"
static let CustomSelectors = "customSelectors"
static let SelectorWithSegueId = "selectorWithSegueId"
static let SelectorWithSegueClass = "selectorWithSegueClass"
static let SelectorWithNibName = "selectorWithNibName"
static let SelectorWithStoryboardId = "selectorWithStoryboardId"
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initializeForm()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeForm()
}
override func viewDidLoad() {
super.viewDidLoad()
let barButton = UIBarButtonItem(title: "Disable", style: .Plain, target: self, action: "disableEnable:")
barButton.possibleTitles = Set(["Disable", "Enable"])
navigationItem.rightBarButtonItem = barButton
}
func disableEnable(button : UIBarButtonItem)
{
form.disabled = !form.disabled
button.title = form.disabled ? "Enable" : "Disable"
tableView.endEditing(true)
tableView.reloadData()
}
func initializeForm() {
let form : XLFormDescriptor
var section : XLFormSectionDescriptor
var row : XLFormRowDescriptor
form = XLFormDescriptor(title: "Selectors")
section = XLFormSectionDescriptor.formSectionWithTitle("Selectors")
section.footerTitle = "SelectorsFormViewController.swift"
form.addFormSection(section)
// Selector Push
row = XLFormRowDescriptor(tag: Tags.Push, rowType:XLFormRowDescriptorTypeSelectorPush, title:"Push")
row.selectorOptions = [XLFormOptionsObject(value: 0, displayText: "Option 1"),
XLFormOptionsObject(value: 1, displayText:"Option 2"),
XLFormOptionsObject(value: 2, displayText:"Option 3"),
XLFormOptionsObject(value: 3, displayText:"Option 4"),
XLFormOptionsObject(value: 4, displayText:"Option 5")
]
row.value = XLFormOptionsObject(value: 1, displayText:"Option 2")
section.addFormRow(row)
// Selector Popover
if (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad){
row = XLFormRowDescriptor(tag: Tags.Popover, rowType:XLFormRowDescriptorTypeSelectorPopover, title:"PopOver")
row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "Option 6"]
row.value = "Option 2"
section.addFormRow(row)
}
// Selector Action Sheet
row = XLFormRowDescriptor(tag :Tags.ActionSheet, rowType:XLFormRowDescriptorTypeSelectorActionSheet, title:"Sheet")
row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"]
row.value = "Option 3"
section.addFormRow(row)
// Selector Alert View
row = XLFormRowDescriptor(tag: Tags.AlertView, rowType:XLFormRowDescriptorTypeSelectorAlertView, title:"Alert View")
row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"]
row.value = "Option 3"
section.addFormRow(row)
// Selector Picker View
row = XLFormRowDescriptor(tag: Tags.PickerView, rowType:XLFormRowDescriptorTypeSelectorPickerView, title:"Picker View")
row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"]
row.value = "Option 4"
section.addFormRow(row)
// --------- Fixed Controls
section = XLFormSectionDescriptor.formSectionWithTitle("Fixed Controls")
form.addFormSection(section)
row = XLFormRowDescriptor(tag: Tags.Picker, rowType:XLFormRowDescriptorTypePicker)
row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"]
row.value = "Option 1"
section.addFormRow(row)
// --------- Inline Selectors
section = XLFormSectionDescriptor.formSectionWithTitle("Inline Selectors")
form.addFormSection(section)
row = XLFormRowDescriptor(tag: Tags.MultipleSelector, rowType:XLFormRowDescriptorTypeSelectorPickerViewInline, title:"Inline Picker View")
row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "Option 6"]
row.value = "Option 6"
section.addFormRow(row)
// --------- MultipleSelector
section = XLFormSectionDescriptor.formSectionWithTitle("Multiple Selectors")
form.addFormSection(section)
row = XLFormRowDescriptor(tag: Tags.MultipleSelector, rowType:XLFormRowDescriptorTypeMultipleSelector, title:"Multiple Selector")
row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "Option 6"]
row.value = ["Option 1", "Option 3", "Option 4", "Option 5", "Option 6"]
section.addFormRow(row)
// Multiple selector with value tranformer
row = XLFormRowDescriptor(tag: Tags.MultipleSelector, rowType:XLFormRowDescriptorTypeMultipleSelector, title:"Multiple Selector")
row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "Option 6"]
row.value = ["Option 1", "Option 3", "Option 4", "Option 5", "Option 6"]
row.valueTransformer = NSArrayValueTrasformer.self
section.addFormRow(row)
// Language multiple selector
row = XLFormRowDescriptor(tag: Tags.MultipleSelector, rowType:XLFormRowDescriptorTypeMultipleSelector, title:"Multiple Selector")
row.selectorOptions = NSLocale.ISOLanguageCodes()
row.selectorTitle = "Languages"
row.valueTransformer = ISOLanguageCodesValueTranformer.self
row.value = NSLocale.preferredLanguages()
section.addFormRow(row)
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
// Language multiple selector popover
row = XLFormRowDescriptor(tag: Tags.MultipleSelectorPopover, rowType:XLFormRowDescriptorTypeMultipleSelectorPopover, title:"Multiple Selector PopOver")
row.selectorOptions = NSLocale.ISOLanguageCodes()
row.valueTransformer = ISOLanguageCodesValueTranformer.self
row.value = NSLocale.preferredLanguages()
section.addFormRow(row)
}
// --------- Dynamic Selectors
section = XLFormSectionDescriptor.formSectionWithTitle("Dynamic Selectors")
form.addFormSection(section)
row = XLFormRowDescriptor(tag: Tags.DynamicSelectors, rowType:XLFormRowDescriptorTypeButton, title:"Dynamic Selectors")
row.action.viewControllerClass = DynamicSelectorsFormViewController.self
section.addFormRow(row)
// --------- Custom Selectors
section = XLFormSectionDescriptor.formSectionWithTitle("Custom Selectors")
form.addFormSection(section)
row = XLFormRowDescriptor(tag: Tags.CustomSelectors, rowType:XLFormRowDescriptorTypeButton, title:"Custom Selectors")
row.action.viewControllerClass = CustomSelectorsFormViewController.self
section.addFormRow(row)
// --------- Selector definition types
section = XLFormSectionDescriptor.formSectionWithTitle("Selectors")
form.addFormSection(section)
// selector with segue class
row = XLFormRowDescriptor(tag: Tags.SelectorWithSegueClass, rowType: XLFormRowDescriptorTypeSelectorPush, title: "Selector with Segue Class")
row.action.formSegueClass = NSClassFromString("UIStoryboardPushSegue")
row.action.viewControllerClass = MapViewController.self
row.valueTransformer = CLLocationValueTrasformer.self
row.value = CLLocation(latitude: -33, longitude: -56)
section.addFormRow(row)
// selector with SegueId
row = XLFormRowDescriptor(tag: Tags.SelectorWithSegueId, rowType: XLFormRowDescriptorTypeSelectorPush, title: "Selector with Segue Idenfifier")
row.action.formSegueIdenfifier = "MapViewControllerSegue";
row.valueTransformer = CLLocationValueTrasformer.self
row.value = CLLocation(latitude: -33, longitude: -56)
section.addFormRow(row)
// selector using StoryboardId
row = XLFormRowDescriptor(tag: Tags.SelectorWithStoryboardId, rowType: XLFormRowDescriptorTypeSelectorPush, title: "Selector with StoryboardId")
row.action.viewControllerStoryboardId = "MapViewController";
row.valueTransformer = CLLocationValueTrasformer.self
row.value = CLLocation(latitude: -33, longitude: -56)
section.addFormRow(row)
// selector with NibName
row = XLFormRowDescriptor(tag: Tags.SelectorWithNibName, rowType: XLFormRowDescriptorTypeSelectorPush, title: "Selector with NibName")
row.action.viewControllerNibName = "MapViewController"
row.valueTransformer = CLLocationValueTrasformer.self
row.value = CLLocation(latitude: -33, longitude: -56)
section.addFormRow(row)
self.form = form
}
override func storyboardForRow(formRow: XLFormRowDescriptor!) -> UIStoryboard! {
return UIStoryboard(name: "iPhoneStoryboard", bundle:nil)
}
}
| mit | 5b4f316b2eb7fda129ba716624f2d998 | 43.303136 | 163 | 0.667951 | 5.518663 | false | false | false | false |
MartinOSix/DemoKit | dSwift/2048swift/2048swift/AuxiliaryModels.swift | 1 | 6479 | //
// AuxiliaryModels.swift
// 2048swift
//
// Created by runo on 17/3/13.
// Copyright © 2017年 com.runo. All rights reserved.
//
import Foundation
//用于存放数字块的移动状态,是否需要移动以及两个一块喝并移动等等,关键数据是数组中位置以及最新数字快的值
enum ActionToken {
case noAction(source: Int, value: Int)
case move(source: Int, value: Int)
case singleCombine(source: Int, value: Int)
case doubleCombine(source: Int, second: Int, value: Int)
func getValue() -> Int {
switch self {
case let .noAction(_, v): return v
case let .move(_, v): return v
case let .singleCombine(_, v): return v
case let .doubleCombine(_, _, v): return v
}
}
func getSource() -> Int {
switch self {
case let .noAction(s, _): return s
case let .move(s, _): return s
case let .singleCombine(s, _): return s
case let .doubleCombine(s, _, _): return s
}
}
}
//用户操作---- 上下左右
enum MoveDirection {
case up, down, left, right
}
struct MoveCommand {
let direction: MoveDirection
let completion: (Bool) -> ()
}
//最终移动数据封装,标注了所有需要移动的块的原位置及新位置,以及块的最新值
enum MoveOrder {
case singleMoveOrder(source: Int, destination: Int, value: Int, wasMerge: Bool)
case doubleMoveOrder(firstSource: Int, secondSource: Int, destination: Int, value: Int)
}
//数组中存放的枚举,要么为空,要么带值的title
enum TileObject {
case empty
case tile(Int)
}
struct SquareGameboard<T> {
let dimension : Int
//存放实际值的数组
var boarArray : [T]
init(dimension d: Int, initialValue: T) {
dimension = d
boarArray = [T](repeating: initialValue, count: d*d)
}
//通过当前的x,y坐标来计算存储和取出的TileObject枚举
subscript(row: Int, col: Int)-> T {
get{
assert(row >= 0 && row < dimension)
assert(col >= 0 && col < dimension)
return boarArray[row*dimension + col]
}
set {
assert(row >= 0 && row < dimension)
assert(col >= 0 && col < dimension)
boarArray[row*dimension + col] = newValue
}
}
//初始化时使用
mutating func setAll(value : T) {
for i in 0..<dimension {
for j in 0..<dimension {
self[i , j] = value
}
}
}
}
func merge(group :[TileObject]) -> [MoveOrder] {
return [MoveOrder]();
}
//去空, 如 | | |2|2| => |2|2| | |
func condense(group : [TileObject]) -> [ActionToken] {
var buffer = [ActionToken]()
for (index , tile) in group.enumerated(){
switch tile {
case let .tile(value) where buffer.count == index:
buffer.append(ActionToken.noAction(source: index, value: value))
case let .tile(value) :
buffer.append(ActionToken.move(source: index, value: value))
default:break
}
}
return buffer
}
//合并相同的
func collapse(group : [ActionToken]) -> [ActionToken] {
var tokenBuffer = [ActionToken]()
//是否跳过下一个,如果把下一个块合过来则跳过下一个
var skipNext = false
for (idx, token) in group.enumerated(){
if(skipNext){
skipNext = false;
continue
}
switch token {
//当前块和下一个块值相同,且当前块不需要移动,那么要将下一个块合并到当前块中
case let ActionToken.noAction(source: s, value: v) where (idx < group.count-1 && v == group[idx+1].getValue() && GameModel.quiescentTileStillQuiescent(inputPosition: idx, outputLength: tokenBuffer.count, originalPosition: s)):
let next = group[idx + 1]
let nv = v + group[idx + 1].getValue()
skipNext = true
tokenBuffer.append(ActionToken.singleCombine(source: next.getSource(), value: nv))
//当前块和下一块的值相同,且两个块都需要移动,则将两个块移动到新位置
case let t where (idx < group.count - 1 && t.getValue() == group[idx + 1].getValue()):
let next = group[idx + 1]
let nv = t.getValue() + group[idx + 1].getValue()
skipNext = true
tokenBuffer.append(ActionToken.doubleCombine(source: t.getSource(), second: next.getSource(), value: nv))
//上一步判定不要要移动,但是之前的块有合并过,所以需要移动
case let ActionToken.noAction(source: s, value: v) where !GameModel.quiescentTileStillQuiescent(inputPosition: idx, outputLength: tokenBuffer.count, originalPosition: s):
tokenBuffer.append(ActionToken.move(source: s, value: v))
//上一步判定不需要移动,且之前的块也没有合并,则不需要移动
case let ActionToken.noAction(source: s, value: v):
tokenBuffer.append(ActionToken.noAction(source: s, value: v))
//上一步判定需要移动且不符合上面的条件的,则继续保持移动
case let ActionToken.move(source: s, value: v):
tokenBuffer.append(ActionToken.move(source: s, value: v))
default:
break
}
}
return tokenBuffer
}
//转换为 moveOrder
func convert(group : [ActionToken]) -> [MoveOrder] {
var buffer = [MoveOrder]()
for (idx, tileaction) in group.enumerated() {
switch tileaction {
case let ActionToken.move(source: s, value: v):
//单纯将一个块由s位置移动到idx 位置,新值为v
buffer.append(MoveOrder.singleMoveOrder(source: s, destination: idx, value: v, wasMerge: false))
case let ActionToken.singleCombine(source: s, value: v):
//将s和d两个数字块移动到idx位置,且idx位置有数字块,进行合并,新值为v
buffer.append(MoveOrder.singleMoveOrder(source: s, destination: idx, value: v, wasMerge: true))
case let ActionToken.doubleCombine(source: s, second: d, value: v):
//将s和d两个数字块移动到idx位置并进行合并,新值为v
buffer.append(MoveOrder.doubleMoveOrder(firstSource: s, secondSource: d, destination: idx, value: v))
default:
break
}
}
return buffer
}
| apache-2.0 | 200ef3d6bd95174aa1bab64c6a050222 | 27.781726 | 234 | 0.600353 | 3.67466 | false | false | false | false |
cfraz89/RxSwift | RxExample/RxExample/Examples/ImagePicker/ImagePickerController.swift | 1 | 2384 | //
// ImagePickerController.swift
// RxExample
//
// Created by Segii Shulga on 1/5/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class ImagePickerController: ViewController {
@IBOutlet var imageView: UIImageView!
@IBOutlet var cameraButton: UIButton!
@IBOutlet var galleryButton: UIButton!
@IBOutlet var cropButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera)
cameraButton.rx.tap
.flatMapLatest { [weak self] _ in
return UIImagePickerController.rx.createWithParent(self) { picker in
picker.sourceType = .camera
picker.allowsEditing = false
}
.flatMap { $0.rx.didFinishPickingMediaWithInfo }
.take(1)
}
.map { info in
return info[UIImagePickerControllerOriginalImage] as? UIImage
}
.bindTo(imageView.rx.image)
.disposed(by: disposeBag)
galleryButton.rx.tap
.flatMapLatest { [weak self] _ in
return UIImagePickerController.rx.createWithParent(self) { picker in
picker.sourceType = .photoLibrary
picker.allowsEditing = false
}
.flatMap {
$0.rx.didFinishPickingMediaWithInfo
}
.take(1)
}
.map { info in
return info[UIImagePickerControllerOriginalImage] as? UIImage
}
.bindTo(imageView.rx.image)
.disposed(by: disposeBag)
cropButton.rx.tap
.flatMapLatest { [weak self] _ in
return UIImagePickerController.rx.createWithParent(self) { picker in
picker.sourceType = .photoLibrary
picker.allowsEditing = true
}
.flatMap { $0.rx.didFinishPickingMediaWithInfo }
.take(1)
}
.map { info in
return info[UIImagePickerControllerEditedImage] as? UIImage
}
.bindTo(imageView.rx.image)
.disposed(by: disposeBag)
}
}
| mit | 1f6a3ee18f9de4626029fcad2d7aa459 | 30.355263 | 87 | 0.556022 | 5.529002 | false | false | false | false |
ReactiveSprint/ReactiveSprint-Swift | Pod/Classes/FetchedArrayViewModel.swift | 1 | 7678 | //
// FetchedArrayViewModel.Swift
// Pods
//
// Created by Ahmad Baraka on 3/2/16.
// Copyright © 2016 ReactiveSprint. All rights reserved.
//
import ReactiveCocoa
import Result
/// Non-generic FetchedArrayViewModelType used with Cocoa.
public protocol CocoaFetchedArrayViewModelType: CocoaArrayViewModelType
{
/// Whether the ViewModel is refreshing.
var refreshing: AnyProperty<Bool> { get }
/// Whether the ViewModel is fetching next page and is not refreshing.
var fetchingNextPage: AnyProperty<Bool> { get }
/// Whether the ViewModel has next page.
var hasNextPage: AnyProperty<Bool> { get }
var refreshCocoaAction: CocoaAction { get }
var fetchCocoaAction: CocoaAction { get }
var fetchIfNeededCocoaAction: CocoaAction { get }
}
/// ArrayViewModel which its array is lazily fetched, or even paginated.
public protocol FetchedArrayViewModelType: ArrayViewModelType, CocoaFetchedArrayViewModelType
{
associatedtype FetchInput
associatedtype FetchOutput
associatedtype PaginationType
associatedtype FetchError: ViewModelErrorType
/// Next Page
var nextPage: PaginationType? { get }
/// Action which refreshes ViewModels.
var refreshAction: Action<FetchInput, FetchOutput, FetchError> { get }
/// Action which fetches ViewModels.
///
/// If `nextPage` is nil, then this action will refresh, else this action should fetch next page.
var fetchAction: Action<FetchInput, FetchOutput, FetchError> { get }
/// Applies `fetchAction` only if next page is availabe or returns `SignalProducer.empty`
var fetchIfNeededAction: Action<FetchInput, FetchOutput, ActionError<FetchError>> { get }
}
public extension FetchedArrayViewModelType
{
private var willFetchNextPage: Bool {
return nextPage != nil
}
public func fetchIfNeeded(input: FetchInput) -> SignalProducer<FetchOutput, ActionError<FetchError>>
{
if willFetchNextPage && hasNextPage.value
{
return fetchAction.apply(input)
}
return SignalProducer.empty
}
}
public extension FetchedArrayViewModelType
{
public var fetchCocoaAction: CocoaAction { return fetchAction.unsafeCocoaAction }
public var refreshCocoaAction: CocoaAction { return refreshAction.unsafeCocoaAction }
public var fetchIfNeededCocoaAction: CocoaAction { return fetchIfNeededAction.unsafeCocoaAction }
}
/// An implementation of FetchedArrayViewModelType that fetches ViewModels by calling `fetchClosure.`
public class FetchedArrayViewModel<Element: ViewModelType, PaginationType, FetchError: ViewModelErrorType>: ViewModel, FetchedArrayViewModelType
{
private let _viewModels: MutableProperty<[Element]> = MutableProperty([])
public var viewModels: [Element] {
return _viewModels.value
}
private(set) public lazy var count: AnyProperty<Int> = AnyProperty(initialValue: 0, producer: self._viewModels.producer.map { $0.count })
public let localizedEmptyMessage = MutableProperty<String?>(nil)
private let _refreshing = MutableProperty(false)
private(set) public lazy var refreshing: AnyProperty<Bool> = AnyProperty(self._refreshing)
private let _fetchingNextPage = MutableProperty(false)
private(set) public lazy var fetchingNextPage: AnyProperty<Bool> = AnyProperty(self._fetchingNextPage)
private let _hasNextPage = MutableProperty(true)
private(set) public lazy var hasNextPage: AnyProperty<Bool> = AnyProperty(self._hasNextPage)
private(set) public var nextPage: PaginationType? = nil
public let fetchClosure: PaginationType? -> SignalProducer<(PaginationType?, [Element]), FetchError>
private(set) public lazy var refreshAction: Action<(), [Element], FetchError> = self.initRefreshAction()
private(set) public lazy var fetchAction: Action<(), [Element], FetchError> = self.initFetchAction()
private(set) public lazy var fetchIfNeededAction: Action<(), [Element], ActionError<FetchError>> = { _ in
let action = Action<(), [Element], ActionError<FetchError>>(enabledIf: self.enabled) { [unowned self] _ in
return self.fetchIfNeeded()
}
action.unsafeCocoaAction = CocoaAction(action, input: ())
return action
}()
/// Initializes an instance with `fetchClosure`
///
/// - Parameter fetchClosure: A closure which is called each time `refreshAction` or `fetchAction`
/// are called passing latest PaginationType
/// and returns a `SignalProducer` which sends PaginationType and an array of `Element`.
/// If the returned SignalProducer sends nil PaginationType, then no pagination will be handled.
public init(_ fetchClosure: PaginationType? -> SignalProducer<(PaginationType?, [Element]), FetchError>)
{
self.fetchClosure = fetchClosure
super.init()
}
public subscript(index: Int) -> Element {
return _viewModels.value[index]
}
/// Initializes refresh action.
///
/// Default implementation initializes an Action that is enabled when the receiver is,
/// and executes `fetchClosure` with nil page.
///
/// `CocoaAction.unsafeCocoaAction` is set with a safe one ignoring any input.
///
/// The returned action is also bound to the receiver using `bindAction`
public func initRefreshAction() -> Action<(), [Element], FetchError>
{
let action: Action<(), [Element], FetchError> = Action(enabledIf: self.enabled) { [unowned self] _ in
self._refreshing.value = true
return self._fetch(nil)
}
bindAction(action)
action.unsafeCocoaAction = CocoaAction(action, input: ())
return action
}
/// Initializes Fetch action.
///
/// Default implementation initializes an Action that is enabled when the receiver is,
/// and executes `fetchClosure` with `nextPage`.
///
/// `CocoaAction.unsafeCocoaAction` is set with a safe one ignoring any input.
///
/// The returned action is also bound to the receiver using `bindAction`
public func initFetchAction() -> Action<(), [Element], FetchError>
{
let action: Action<(), [Element], FetchError> = Action(enabledIf: self.enabled) { [unowned self] _ in
if self.willFetchNextPage
{
self._fetchingNextPage.value = true
}
else
{
self._refreshing.value = true
}
return self._fetch(self.nextPage)
}
bindAction(action)
action.unsafeCocoaAction = CocoaAction(action, input: ())
return action
}
private func _fetch(page: PaginationType?) -> SignalProducer<[Element], FetchError>
{
return self.fetchClosure(page)
.on(next: { [unowned self] page, viewModels in
if self.refreshing.value
{
self._viewModels.value.removeAll()
}
self._viewModels.value.appendContentsOf(viewModels)
self._hasNextPage.value = viewModels.count > 0
self.nextPage = page
},
terminated: { [unowned self] in
self._refreshing.value = false
self._fetchingNextPage.value = false
})
.map { $0.1 }
}
public func indexOf(predicate: Element -> Bool) -> Int?
{
return viewModels.indexOf(predicate)
}
}
| mit | 0f39ae6eb769c703e693086a7d5d1adb | 35.732057 | 144 | 0.657418 | 5.226004 | false | false | false | false |
danielsaidi/iExtra | iExtra/Files/MainBundleImageFileFinder.swift | 1 | 1440 | //
// MainBundleImageFileFinder.swift
// iExtra
//
// Created by Daniel Saidi on 2015-11-16.
// Copyright © 2018 Daniel Saidi. All rights reserved.
//
/*
This class finds all non-asset images in the app bundle and
removes any retina variations.
*/
import Foundation
public class MainBundleImageFileFinder: MainBundleFileFinder {
public override func findFiles(withPrefix prefix: String) -> [String] {
let rawResult = super.findFiles(withPrefix: prefix)
let result = filter(rawResult)
return result
}
public override func findFiles(withSuffix suffix: String) -> [String] {
let rawResult = super.findFiles(withSuffix: suffix)
let result = filter(rawResult)
return result
}
}
private extension MainBundleImageFileFinder {
func filter(_ rawResult: [String]) -> [String] {
return rawResult.compactMap { getBaseImageName($0) }
}
func getBaseImageName(_ fileName: String) -> String? {
guard isBaseImageName(fileName) else { return nil }
var result = fileName.components(separatedBy: ".").first
result = result?.components(separatedBy: "~").first
return result
}
func isBaseImageName(_ fileName: String) -> Bool {
return !fileName.contains("@")
&& !fileName.contains("_2x")
&& !fileName.contains("_3x")
&& !fileName.contains("~")
}
}
| mit | e9f4c78aa03222526cc108c7dd9fe148 | 26.150943 | 75 | 0.637943 | 4.482866 | false | false | false | false |
tjw/swift | test/Serialization/function.swift | 4 | 5445 |
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_func.swift
// RUN: llvm-bcanalyzer %t/def_func.swiftmodule | %FileCheck %s
// RUN: %target-swift-frontend -module-name function -emit-silgen -I %t %s | %FileCheck %s -check-prefix=SIL
// CHECK-NOT: FALL_BACK_TO_TRANSLATION_UNIT
// CHECK-NOT: UnknownCode
import def_func
func useEq<T: EqualOperator>(_ x: T, y: T) -> Bool {
return x == y
}
// SIL: sil @main
// SIL: [[RAW:%.+]] = global_addr @$S8function3rawSivp : $*Int
// SIL: [[ZERO:%.+]] = function_ref @$S8def_func7getZeroSiyF : $@convention(thin) () -> Int
// SIL: [[RESULT:%.+]] = apply [[ZERO]]() : $@convention(thin) () -> Int
// SIL: store [[RESULT]] to [trivial] [[RAW]] : $*Int
var raw = getZero()
// Check that 'raw' is an Int
var cooked : Int = raw
// SIL: [[GET_INPUT:%.+]] = function_ref @$S8def_func8getInput1xS2i_tF : $@convention(thin) (Int) -> Int
// SIL: {{%.+}} = apply [[GET_INPUT]]({{%.+}}) : $@convention(thin) (Int) -> Int
var raw2 = getInput(x: raw)
// SIL: [[GET_SECOND:%.+]] = function_ref @$S8def_func9getSecond_1yS2i_SitF : $@convention(thin) (Int, Int) -> Int
// SIL: {{%.+}} = apply [[GET_SECOND]]({{%.+}}, {{%.+}}) : $@convention(thin) (Int, Int) -> Int
var raw3 = getSecond(raw, y: raw2)
// SIL: [[USE_NESTED:%.+]] = function_ref @$S8def_func9useNested_1nySi1x_Si1yt_SitF : $@convention(thin) (Int, Int, Int) -> ()
// SIL: {{%.+}} = apply [[USE_NESTED]]({{%.+}}, {{%.+}}, {{%.+}}) : $@convention(thin) (Int, Int, Int) -> ()
useNested((raw, raw2), n: raw3)
// SIL: [[VA_SIZE:%.+]] = integer_literal $Builtin.Word, 2
// SIL: {{%.+}} = apply {{%.*}}<Int>([[VA_SIZE]])
// SIL: [[VARIADIC:%.+]] = function_ref @$S8def_func8variadic1x_ySd_SidtF : $@convention(thin) (Double, @guaranteed Array<Int>) -> ()
// SIL: {{%.+}} = apply [[VARIADIC]]({{%.+}}, {{%.+}}) : $@convention(thin) (Double, @guaranteed Array<Int>) -> ()
variadic(x: 2.5, 4, 5)
// SIL: [[VARIADIC:%.+]] = function_ref @$S8def_func9variadic2_1xySid_SdtF : $@convention(thin) (@guaranteed Array<Int>, Double) -> ()
variadic2(1, 2, 3, x: 5.0)
// SIL: [[SLICE_SIZE:%.+]] = integer_literal $Builtin.Word, 3
// SIL: {{%.+}} = apply {{%.*}}<Int>([[SLICE_SIZE]])
// SIL: [[SLICE:%.+]] = function_ref @$S8def_func5slice1xySaySiG_tF : $@convention(thin) (@guaranteed Array<Int>) -> ()
// SIL: {{%.+}} = apply [[SLICE]]({{%.+}}) : $@convention(thin) (@guaranteed Array<Int>) -> ()
slice(x: [2, 4, 5])
optional(x: .some(23))
optional(x: .none)
// SIL: [[MAKE_PAIR:%.+]] = function_ref @$S8def_func8makePair{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_1) -> (@out τ_0_0, @out τ_0_1)
// SIL: {{%.+}} = apply [[MAKE_PAIR]]<Int, Double>({{%.+}}, {{%.+}})
var pair : (Int, Double) = makePair(a: 1, b: 2.5)
// SIL: [[DIFFERENT_A:%.+]] = function_ref @$S8def_func9different{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool
// SIL: [[DIFFERENT_B:%.+]] = function_ref @$S8def_func9different{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool
_ = different(a: 1, b: 2)
_ = different(a: false, b: false)
// SIL: [[DIFFERENT2_A:%.+]] = function_ref @$S8def_func10different2{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool
// SIL: [[DIFFERENT2_B:%.+]] = function_ref @$S8def_func10different2{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool
_ = different2(a: 1, b: 2)
_ = different2(a: false, b: false)
struct IntWrapper1 : Wrapped {
typealias Value = Int
func getValue() -> Int { return 1 }
}
struct IntWrapper2 : Wrapped {
typealias Value = Int
func getValue() -> Int { return 2 }
}
// SIL: [[DIFFERENT_WRAPPED:%.+]] = function_ref @$S8def_func16differentWrapped1a1bSbx_q_tAA0D0RzAaER_5ValueQy_AFRtzr0_lF : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Wrapped, τ_0_1 : Wrapped, τ_0_0.Value == τ_0_1.Value> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_1) -> Bool
_ = differentWrapped(a: IntWrapper1(), b: IntWrapper2())
// SIL: {{%.+}} = function_ref @$S8def_func10overloaded1xySi_tF : $@convention(thin) (Int) -> ()
// SIL: {{%.+}} = function_ref @$S8def_func10overloaded1xySb_tF : $@convention(thin) (Bool) -> ()
overloaded(x: 1)
overloaded(x: false)
// SIL: {{%.+}} = function_ref @primitive : $@convention(thin) () -> ()
primitive()
if raw == 5 {
testNoReturnAttr()
testNoReturnAttrPoly(x: 5)
}
// SIL: {{%.+}} = function_ref @$S8def_func16testNoReturnAttrs5NeverOyF : $@convention(thin) () -> Never
// SIL: {{%.+}} = function_ref @$S8def_func20testNoReturnAttrPoly{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> Never
// SIL: sil @$S8def_func16testNoReturnAttrs5NeverOyF : $@convention(thin) () -> Never
// SIL: sil @$S8def_func20testNoReturnAttrPoly{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> Never
do {
try throws1()
_ = try throws2(1)
} catch _ {}
// SIL: sil @$S8def_func7throws1yyKF : $@convention(thin) () -> @error Error
// SIL: sil @$S8def_func7throws2{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> (@out τ_0_0, @error Error)
// LLVM: }
| apache-2.0 | ef763449b50f0abf8ef1688fffcd42df | 44.066667 | 279 | 0.593195 | 2.790506 | false | false | false | false |
alexth/SwiftFake | SwiftFake.swift | 1 | 9623 | //
// SwiftFake.swift
//
// Created by Alex Golub on 10/11/16.
// Copyright (c) 2016 Alex Golub. All rights reserved.
//
import UIKit
public struct SwiftFake {
fileprivate let maleFirstNames = ["Victor", "Brian", "Steve", "Marcus", "Stanley", "Jaco", "John", "Avishai", "Richard", "Alex"]
fileprivate let maleLastNames = ["Wooten", "Bromberg", "Bailey", "Miller", "Clarke", "Pastorius", "Patitucci", "Cohen", "Bona", "Webster"]
fileprivate let femaleFirstNames = ["Esperanza", "Suzi", "Carol", "Kim", "Antonella", "Tal", "Divinity", "Manou", "Mohini", "Rhonda"]
fileprivate let femaleLastNames = ["Spalding", "Quatro", "Kaye", "Gordon", "Mazza", "Wilkenfeld", "Roxx", "Gallo", "Dey", "Smith"]
// MARK: Name
/**
Call it when you just want full name, without setting gender
@return full name
*/
public static func fullName() -> String {
if Bool.randomBool() == true {
return SwiftFake.maleFullName()
} else {
return SwiftFake.femaleFullName()
}
}
/**
Male first name
@return male first name
*/
public static func maleFirstName() -> String {
return SwiftFake().maleFirstNames.randomElement()
}
/**
Male last name
@return male last name
*/
public static func maleLastName() -> String {
return SwiftFake().maleLastNames.randomElement()
}
/**
Male full name
@return male full name
*/
public static func maleFullName() -> String {
return maleFirstName() + " " + maleLastName()
}
/**
Female first name
@return female first name
*/
public static func femaleFirstName() -> String {
return SwiftFake().femaleFirstNames.randomElement()
}
/**
Female last name
@return female last name
*/
public static func femaleLastName() -> String {
return SwiftFake().femaleLastNames.randomElement()
}
/**
Female full name
@return female full name
*/
public static func femaleFullName() -> String {
return femaleFirstName() + " " + femaleLastName()
}
// MARK: Contact
/**
Email
@return email
*/
public static func email() -> String {
let namesArray = ["example", "user", "dearuser", "yourfriend", "homer.simpson", "dart.vader", "jack.jones", "batman"]
let domainsArray = ["aaa", "bbb", "uuu", "abc", "ccc", "ddd", "eee", "fff", "ggg"]
let topDomainsArray = ["edu", "co", "com", "br", "io", "net", "org", "ua"]
return namesArray.randomElement() + "@" + domainsArray.randomElement() + "." + topDomainsArray.randomElement()
}
/**
Phone number
@return phone number
*/
public static func phoneNumber() -> String {
let countriesArray = ["27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38"]
let regionsArray = ["000", "111", "222", "333", "444", "555", "666", "777", "888", "999"]
let phonesArray = ["0000000", "1111111", "2222222", "3333333", "4444444", "5555555", "6666666", "7777777", "8888888", "9999999"]
return "+" + countriesArray.randomElement() + regionsArray.randomElement() + phonesArray.randomElement()
}
// MARK: Data
/**
City name.
@return city name
*/
public static func city() -> String {
let prefixes = ["Det", "Ives", "Checo", "Lay", "Rock", "Dale", "Morri", "Park", "Dixie", "Frier", "Bras", "Crow", "Wolf", "Grid", "Rums"]
let postfixes = ["mold", "dale", "tah", "ville", "hill", "york", "son", "way", "land", "ona", "well", "der", "boro", "ley", "town"]
return prefixes.randomElement() + postfixes.randomElement()
}
/**
One of two genders.
@return gender
*/
public static func gender() -> String {
return Bool.randomBool() ? "Male" : "Female"
}
/**
Age in range
@param lower lower bound of generated age
@param higher higher bound of generated age
@return age
*/
public static func ageBetween(lower: Int, higher: Int) -> Int {
return Int.randomInt(from: lower, to: higher)
}
/**
Title
@return title
*/
public static func title() -> String {
let title = ["CEO", "COO", "CTO", "Director", "Head", "President", "Vice President", "Coordinator", "Assistant", "Worker"]
return title.randomElement()
}
// MARK: Date
/**
Birth date for age.
@discussion Month and day will be randomly set, but year will be a current minus age. Time (hours and minutes)
will also be the same as current when called.
@param age for which birth date will be generated
@return birth date
*/
public static func birthDateFor(age: Int) -> Date {
let calendar = NSCalendar.current
let date = Date()
let dateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date as Date)
var newDateComponents = DateComponents()
newDateComponents = dateComponents
let newDay = Int.randomInt(from: 1, to: 30)
let newMonth = Int.randomInt(from: 1, to: 12)
let newYear = dateComponents.year! - age
newDateComponents.day = newDay
newDateComponents.month = newMonth
newDateComponents.year = newYear
return calendar.date(from: newDateComponents)!
}
// MARK: ID
/**
ID in format of uuid : https://en.wikipedia.org/wiki/Universally_unique_identifier
@discussion String description of the UUID, such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
@return uuidID
*/
public static func uuidID() -> String {
return NSUUID().uuidString
}
// MARK: Password
/**
Password.
@discussion Only digits and english alphabet symbols are included
@param length Length for generated password
@return pasword
*/
public static func password(length: Int) -> String {
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString: String = ""
for _ in 0..<length {
let randomValue = arc4random_uniform(UInt32(base.characters.count))
randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
}
return randomString
}
// MARK: Image
/**
Image filled with color.
@discussion Generated image which can be filled with color
@param color for filling image
@return image
*/
public static func image(color: UIColor) -> UIImage {
let imageSize = CGSize(width: 100, height: 100)
UIGraphicsBeginImageContext(imageSize)
color.set()
UIRectFill(CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
/**
Image from for colored squares.
@discussion Generated image which will be filled with for squares of different color
@return image
*/
public static func imageWithColors() -> UIImage {
var colorsArray = [UIColor.black, UIColor.darkGray, UIColor.lightGray, UIColor.white, UIColor.gray, UIColor.red, UIColor.green, UIColor.blue, UIColor.cyan, UIColor.yellow, UIColor.magenta, UIColor.orange, UIColor.purple, UIColor.brown]
var subviewsArray = [UIView]()
for _ in 0..<4 {
let view = UIView()
let colorIndex = Int.randomInt(from: 0, to: colorsArray.count - 1)
view.backgroundColor = colorsArray[colorIndex]
colorsArray.remove(at: colorIndex)
subviewsArray.append(view)
}
let finalView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let leftTopSubview = subviewsArray[0]
leftTopSubview.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
finalView.addSubview(leftTopSubview)
let rightTopSubview = subviewsArray[1]
rightTopSubview.frame = CGRect(x: 50, y: 0, width: 50, height: 50)
finalView.addSubview(rightTopSubview)
let leftBottomSubview = subviewsArray[2]
leftBottomSubview.frame = CGRect(x: 0, y: 50, width: 50, height: 50)
finalView.addSubview(leftBottomSubview)
let rightBottomSubview = subviewsArray[3]
rightBottomSubview.frame = CGRect(x: 50, y: 50, width: 50, height: 50)
finalView.addSubview(rightBottomSubview)
UIGraphicsBeginImageContext(finalView.frame.size)
finalView.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return UIImage(cgImage: image!.cgImage!)
}
}
// Basic types extensions
public extension Bool {
public static func randomBool() -> Bool {
return arc4random_uniform(2) == 0
}
}
public extension Array {
public func randomElement() -> Element {
let arrayCount = UInt32(self.count)
let index = Int(arc4random_uniform(arrayCount))
return self[index]
}
}
public extension Int {
public static func randomInt(from lower: Int, to higher: Int) -> Int {
var safeLower = lower
var safeHigher = higher
if safeLower > safeHigher {
swap(&safeLower, &safeHigher)
}
return Int(arc4random_uniform(UInt32(safeHigher - safeLower + 1))) + safeLower
}
}
| mit | 43f82a33108237d1494ca6e220a22499 | 33.367857 | 243 | 0.604905 | 4.23175 | false | false | false | false |
rsyncOSX/RsyncOSX | RsyncOSX/Setrsyncpath.swift | 1 | 1890 | //
// Rsyncpath.swift
// RsyncOSX
//
// Created by Thomas Evensen on 06/06/2019.
// Copyright © 2019 Thomas Evensen. All rights reserved.
//
import Foundation
struct Setrsyncpath {
weak var setinfoaboutrsyncDelegate: Setinfoaboutrsync?
init() {
setinfoaboutrsyncDelegate = SharedReference.shared.getvcref(viewcontroller: .vcsidebar) as? ViewControllerSideBar
var rsyncpath: String?
// If not in /usr/bin or /usr/local/bin, rsyncPath is set if none of the above
if let pathforrsync = SharedReference.shared.localrsyncpath {
rsyncpath = pathforrsync + SharedReference.shared.rsync
} else if SharedReference.shared.rsyncversion3 {
if SharedReference.shared.macosarm {
rsyncpath = SharedReference.shared.opthomebrewbinrsync
} else {
rsyncpath = SharedReference.shared.usrlocalbinrsync
}
} else {
rsyncpath = SharedReference.shared.usrbinrsync
}
guard SharedReference.shared.rsyncversion3 == true else {
SharedReference.shared.norsync = false
setinfoaboutrsyncDelegate?.setinfoaboutrsync()
return
}
if FileManager.default.isExecutableFile(atPath: rsyncpath ?? "") == false {
SharedReference.shared.norsync = true
} else {
SharedReference.shared.norsync = false
}
setinfoaboutrsyncDelegate?.setinfoaboutrsync()
}
init(path: String) {
var path = path
if path.isEmpty == false {
if path.hasSuffix("/") == false {
path += "/"
SharedReference.shared.localrsyncpath = path
} else {
SharedReference.shared.localrsyncpath = path
}
} else {
SharedReference.shared.localrsyncpath = nil
}
}
}
| mit | 7dcd10fd77ef7b07862a627f0621ad7e | 33.345455 | 121 | 0.613023 | 4.945026 | false | false | false | false |
jkpang/PPBadgeView | PPBadgeView/swift/UIView+PPBadgeView.swift | 1 | 10972 | //
// UIView+PPBadgeView.swift
// PPBadgeViewSwift
//
// Created by AndyPang on 2017/6/19.
// Copyright © 2017年 AndyPang. All rights reserved.
//
/*
*********************************************************************************
*
* Weibo : jkpang-庞 ( http://weibo.com/jkpang )
* Email : [email protected]
* QQ 群 : 323408051
* GitHub: https://github.com/jkpang
*
*********************************************************************************
*/
import UIKit
private var kBadgeView = "kBadgeView"
// MARK: - add Badge
public extension PP where Base: UIView {
var badgeView: PPBadgeControl {
return base.badgeView
}
/// 添加带文本内容的Badge, 默认右上角, 红色, 18pts
///
/// Add Badge with text content, the default upper right corner, red backgroundColor, 18pts
///
/// - Parameter text: 文本字符串
func addBadge(text: String?) {
showBadge()
base.badgeView.text = text
setBadge(flexMode: base.badgeView.flexMode)
if text == nil {
if base.badgeView.widthConstraint()?.relation == .equal { return }
base.badgeView.widthConstraint()?.isActive = false
let constraint = NSLayoutConstraint(item: base.badgeView, attribute: .width, relatedBy: .equal, toItem: base.badgeView, attribute: .height, multiplier: 1.0, constant: 0)
base.badgeView.addConstraint(constraint)
} else {
if base.badgeView.widthConstraint()?.relation == .greaterThanOrEqual { return }
base.badgeView.widthConstraint()?.isActive = false
let constraint = NSLayoutConstraint(item: base.badgeView, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: base.badgeView, attribute: .height, multiplier: 1.0, constant: 0)
base.badgeView.addConstraint(constraint)
}
}
/// 添加带数字的Badge, 默认右上角,红色,18pts
///
/// Add the Badge with numbers, the default upper right corner, red backgroundColor, 18pts
///
/// - Parameter number: 整形数字
func addBadge(number: Int) {
if number <= 0 {
addBadge(text: "0")
hiddenBadge()
return
}
addBadge(text: "\(number)")
}
/// 添加带颜色的小圆点, 默认右上角, 红色, 8pts
///
/// Add small dots with color, the default upper right corner, red backgroundColor, 8pts
///
/// - Parameter color: 颜色
func addDot(color: UIColor? = .red) {
addBadge(text: nil)
setBadge(height: 8.0)
base.badgeView.backgroundColor = color
}
/// 设置Badge的偏移量, Badge中心点默认为其父视图的右上角
///
/// Set Badge offset, Badge center point defaults to the top right corner of its parent view
///
/// - Parameters:
/// - x: X轴偏移量 (x<0: 左移, x>0: 右移) axis offset (x <0: left, x> 0: right)
/// - y: Y轴偏移量 (y<0: 上移, y>0: 下移) axis offset (Y <0: up, y> 0: down)
func moveBadge(x: CGFloat, y: CGFloat) {
base.badgeView.offset = CGPoint(x: x, y: y)
base.centerYConstraint(with: base.badgeView)?.constant = y
let badgeHeight = base.badgeView.heightConstraint()?.constant ?? 0
switch base.badgeView.flexMode {
case .head:
base.centerXConstraint(with: base.badgeView)?.isActive = false
base.leadingConstraint(with: base.badgeView)?.isActive = false
if let constraint = base.trailingConstraint(with: base.badgeView) {
constraint.constant = badgeHeight * 0.5 + x
return
}
let trailingConstraint = NSLayoutConstraint(item: base.badgeView, attribute: .trailing, relatedBy: .equal, toItem: base, attribute: .trailing, multiplier: 1.0, constant: badgeHeight * 0.5 + x)
base.addConstraint(trailingConstraint)
case .tail:
base.centerXConstraint(with: base.badgeView)?.isActive = false
base.trailingConstraint(with: base.badgeView)?.isActive = false
if let constraint = base.leadingConstraint(with: base.badgeView) {
constraint.constant = x - badgeHeight * 0.5
return
}
let leadingConstraint = NSLayoutConstraint(item: base.badgeView, attribute: .leading, relatedBy: .equal, toItem: base, attribute: .trailing, multiplier: 1.0, constant: x - badgeHeight * 0.5)
base.addConstraint(leadingConstraint)
case .middle:
base.leadingConstraint(with: base.badgeView)?.isActive = false
base.trailingConstraint(with: base.badgeView)?.isActive = false
base.centerXConstraint(with: base.badgeView)?.constant = x
if let constraint = base.centerXConstraint(with: base.badgeView) {
constraint.constant = x
return
}
let centerXConstraint = NSLayoutConstraint(item: base.badgeView, attribute: .centerX, relatedBy: .equal, toItem: base, attribute: .centerX, multiplier: 1.0, constant: x)
base.addConstraint(centerXConstraint)
}
}
/// 设置Badge伸缩的方向
///
/// Setting the direction of Badge expansion
///
/// PPBadgeViewFlexModeHead, 左伸缩 Head Flex : <==●
/// PPBadgeViewFlexModeTail, 右伸缩 Tail Flex : ●==>
/// PPBadgeViewFlexModeMiddle 左右伸缩 Middle Flex : <=●=>
/// - Parameter flexMode : Default is PPBadgeViewFlexModeTail
func setBadge(flexMode: PPBadgeViewFlexMode = .tail) {
base.badgeView.flexMode = flexMode
moveBadge(x: base.badgeView.offset.x, y: base.badgeView.offset.y)
}
/// 设置Badge的高度,因为Badge宽度是动态可变的,通过改变Badge高度,其宽度也按比例变化,方便布局
///
/// (注意: 此方法需要将Badge添加到控件上后再调用!!!)
///
/// Set the height of Badge, because the Badge width is dynamically and variable.By changing the Badge height in proportion to facilitate the layout.
///
/// (Note: this method needs to add Badge to the controls and then use it !!!)
///
/// - Parameter height: 高度大小
func setBadge(height: CGFloat) {
base.badgeView.layer.cornerRadius = height * 0.5
base.badgeView.heightConstraint()?.constant = height
moveBadge(x: base.badgeView.offset.x, y: base.badgeView.offset.y)
}
/// 显示Badge
func showBadge() {
base.badgeView.isHidden = false
}
/// 隐藏Badge
func hiddenBadge() {
base.badgeView.isHidden = true
}
// MARK: - 数字增加/减少, 注意:以下方法只适用于Badge内容为纯数字的情况
// MARK: - Digital increase /decrease, note: the following method applies only to cases where the Badge content is purely numeric
/// badge数字加1
func increase() {
increaseBy(number: 1)
}
/// badge数字加number
func increaseBy(number: Int) {
let label = base.badgeView
let result = (Int(label.text ?? "0") ?? 0) + number
if result > 0 {
showBadge()
}
label.text = "\(result)"
}
/// badge数字加1
func decrease() {
decreaseBy(number: 1)
}
/// badge数字减number
func decreaseBy(number: Int) {
let label = base.badgeView
let result = (Int(label.text ?? "0") ?? 0) - number
if (result <= 0) {
hiddenBadge()
label.text = "0"
return
}
label.text = "\(result)"
}
}
extension UIView {
private func addBadgeViewLayoutConstraint() {
badgeView.translatesAutoresizingMaskIntoConstraints = false
let centerXConstraint = NSLayoutConstraint(item: badgeView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0)
let centerYConstraint = NSLayoutConstraint(item: badgeView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0)
let widthConstraint = NSLayoutConstraint(item: badgeView, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: badgeView, attribute: .height, multiplier: 1.0, constant: 0)
let heightConstraint = NSLayoutConstraint(item: badgeView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 18)
addConstraints([centerXConstraint, centerYConstraint])
badgeView.addConstraints([widthConstraint, heightConstraint])
}
}
// MARK: - getter/setter
extension UIView {
public var badgeView: PPBadgeControl {
get {
if let aValue = objc_getAssociatedObject(self, &kBadgeView) as? PPBadgeControl {
return aValue
}
else {
let badgeControl = PPBadgeControl.default()
self.addSubview(badgeControl)
self.bringSubviewToFront(badgeControl)
self.badgeView = badgeControl
self.addBadgeViewLayoutConstraint()
return badgeControl
}
}
set {
objc_setAssociatedObject(self, &kBadgeView, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
internal func topConstraint(with item: AnyObject?) -> NSLayoutConstraint? {
return constraint(with: item, attribute: .top)
}
internal func leadingConstraint(with item: AnyObject?) -> NSLayoutConstraint? {
return constraint(with: item, attribute: .leading)
}
internal func bottomConstraint(with item: AnyObject?) -> NSLayoutConstraint? {
return constraint(with: item, attribute: .bottom)
}
internal func trailingConstraint(with item: AnyObject?) -> NSLayoutConstraint? {
return constraint(with: item, attribute: .trailing)
}
internal func widthConstraint() -> NSLayoutConstraint? {
return constraint(with: self, attribute: .width)
}
internal func heightConstraint() -> NSLayoutConstraint? {
return constraint(with: self, attribute: .height)
}
internal func centerXConstraint(with item: AnyObject?) -> NSLayoutConstraint? {
return constraint(with: item, attribute: .centerX)
}
internal func centerYConstraint(with item: AnyObject?) -> NSLayoutConstraint? {
return constraint(with: item, attribute: .centerY)
}
private func constraint(with item: AnyObject?, attribute: NSLayoutConstraint.Attribute) -> NSLayoutConstraint? {
for constraint in constraints {
if let isSame = constraint.firstItem?.isEqual(item), isSame, constraint.firstAttribute == attribute {
return constraint
}
}
return nil
}
}
| mit | 889b5dcde28f1d8e349d5ce041023943 | 37.768382 | 204 | 0.61413 | 4.508337 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Room/VoiceMessages/VoiceMessageMediaServiceProvider.swift | 1 | 11577 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import MediaPlayer
@objc public class VoiceMessageMediaServiceProvider: NSObject, VoiceMessageAudioPlayerDelegate, VoiceMessageAudioRecorderDelegate {
private enum Constants {
static let roomAvatarImageSize: CGSize = CGSize(width: 600, height: 600)
static let roomAvatarFontSize: CGFloat = 40.0
static let roomAvatarMimetype: String = "image/jpeg"
}
private var roomAvatarLoader: MXMediaLoader?
private let audioPlayers: NSMapTable<NSString, VoiceMessageAudioPlayer>
private let audioRecorders: NSHashTable<VoiceMessageAudioRecorder>
private var displayLink: CADisplayLink!
// Retain active audio players(playing or paused) so it doesn't stop playing on timeline cell reuse
// and we can pause/resume players on switching rooms.
private var activeAudioPlayers: Set<VoiceMessageAudioPlayer>
// Keep reference to currently playing player for remote control.
private var currentlyPlayingAudioPlayer: VoiceMessageAudioPlayer?
@objc public static let sharedProvider = VoiceMessageMediaServiceProvider()
private var roomAvatar: UIImage?
@objc public var currentRoomSummary: MXRoomSummary? {
didSet {
// set avatar placeholder for now
roomAvatar = AvatarGenerator.generateAvatar(forMatrixItem: currentRoomSummary?.roomId,
withDisplayName: currentRoomSummary?.displayname,
size: Constants.roomAvatarImageSize.width,
andFontSize: Constants.roomAvatarFontSize)
guard let avatarUrl = currentRoomSummary?.avatar else {
return
}
if let cachePath = MXMediaManager.thumbnailCachePath(forMatrixContentURI: avatarUrl,
andType: Constants.roomAvatarMimetype,
inFolder: currentRoomSummary?.roomId,
toFitViewSize: Constants.roomAvatarImageSize,
with: MXThumbnailingMethodCrop),
FileManager.default.fileExists(atPath: cachePath) {
// found in the cache, load it
roomAvatar = MXMediaManager.loadThroughCache(withFilePath: cachePath)
} else {
// cancel previous loader first
roomAvatarLoader?.cancel()
roomAvatarLoader = nil
guard let mediaManager = currentRoomSummary?.mxSession.mediaManager else {
return
}
// not found in the cache, download it
roomAvatarLoader = mediaManager.downloadThumbnail(fromMatrixContentURI: avatarUrl,
withType: Constants.roomAvatarMimetype,
inFolder: currentRoomSummary?.roomId,
toFitViewSize: Constants.roomAvatarImageSize,
with: MXThumbnailingMethodCrop,
success: { filePath in
if let filePath = filePath {
self.roomAvatar = MXMediaManager.loadThroughCache(withFilePath: filePath)
}
self.roomAvatarLoader = nil
}, failure: { error in
self.roomAvatarLoader = nil
})
}
}
}
private override init() {
audioPlayers = NSMapTable<NSString, VoiceMessageAudioPlayer>(valueOptions: .weakMemory)
audioRecorders = NSHashTable<VoiceMessageAudioRecorder>(options: .weakMemory)
activeAudioPlayers = Set<VoiceMessageAudioPlayer>()
super.init()
displayLink = CADisplayLink(target: WeakTarget(self, selector: #selector(handleDisplayLinkTick)), selector: WeakTarget.triggerSelector)
displayLink.isPaused = true
displayLink.add(to: .current, forMode: .common)
}
@objc func audioPlayerForIdentifier(_ identifier: String) -> VoiceMessageAudioPlayer {
if let audioPlayer = audioPlayers.object(forKey: identifier as NSString) {
return audioPlayer
}
let audioPlayer = VoiceMessageAudioPlayer()
audioPlayer.registerDelegate(self)
audioPlayers.setObject(audioPlayer, forKey: identifier as NSString)
return audioPlayer
}
@objc func audioRecorder() -> VoiceMessageAudioRecorder {
let audioRecorder = VoiceMessageAudioRecorder()
audioRecorder.registerDelegate(self)
audioRecorders.add(audioRecorder)
return audioRecorder
}
@objc func pauseAllServices() {
pauseAllServicesExcept(nil)
}
// MARK: - VoiceMessageAudioPlayerDelegate
func audioPlayerDidStartPlaying(_ audioPlayer: VoiceMessageAudioPlayer) {
currentlyPlayingAudioPlayer = audioPlayer
activeAudioPlayers.insert(audioPlayer)
setUpRemoteCommandCenter()
pauseAllServicesExcept(audioPlayer)
}
func audioPlayerDidStopPlaying(_ audioPlayer: VoiceMessageAudioPlayer) {
if currentlyPlayingAudioPlayer == audioPlayer {
currentlyPlayingAudioPlayer = nil
tearDownRemoteCommandCenter()
}
activeAudioPlayers.remove(audioPlayer)
}
func audioPlayerDidFinishPlaying(_ audioPlayer: VoiceMessageAudioPlayer) {
if currentlyPlayingAudioPlayer == audioPlayer {
currentlyPlayingAudioPlayer = nil
tearDownRemoteCommandCenter()
}
activeAudioPlayers.remove(audioPlayer)
}
// MARK: - VoiceMessageAudioRecorderDelegate
func audioRecorderDidStartRecording(_ audioRecorder: VoiceMessageAudioRecorder) {
pauseAllServicesExcept(audioRecorder)
}
// MARK: - Private
private func pauseAllServicesExcept(_ service: AnyObject?) {
for audioRecorder in audioRecorders.allObjects {
if audioRecorder === service {
continue
}
audioRecorder.stopRecording()
}
guard let audioPlayersEnumerator = audioPlayers.objectEnumerator() else {
return
}
for case let audioPlayer as VoiceMessageAudioPlayer in audioPlayersEnumerator {
if audioPlayer === service {
continue
}
audioPlayer.pause()
}
}
@objc private func handleDisplayLinkTick() {
updateNowPlayingInfoCenter()
}
private func setUpRemoteCommandCenter() {
displayLink.isPaused = false
UIApplication.shared.beginReceivingRemoteControlEvents()
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.isEnabled = true
commandCenter.playCommand.removeTarget(nil)
commandCenter.playCommand.addTarget { [weak self] event in
guard let audioPlayer = self?.currentlyPlayingAudioPlayer else {
return MPRemoteCommandHandlerStatus.commandFailed
}
audioPlayer.play()
return MPRemoteCommandHandlerStatus.success
}
commandCenter.pauseCommand.isEnabled = true
commandCenter.pauseCommand.removeTarget(nil)
commandCenter.pauseCommand.addTarget { [weak self] event in
guard let audioPlayer = self?.currentlyPlayingAudioPlayer else {
return MPRemoteCommandHandlerStatus.commandFailed
}
audioPlayer.pause()
return MPRemoteCommandHandlerStatus.success
}
commandCenter.skipForwardCommand.isEnabled = true
commandCenter.skipForwardCommand.removeTarget(nil)
commandCenter.skipForwardCommand.addTarget { [weak self] event in
guard let audioPlayer = self?.currentlyPlayingAudioPlayer, let skipEvent = event as? MPSkipIntervalCommandEvent else {
return MPRemoteCommandHandlerStatus.commandFailed
}
audioPlayer.seekToTime(audioPlayer.currentTime + skipEvent.interval)
return MPRemoteCommandHandlerStatus.success
}
commandCenter.skipBackwardCommand.isEnabled = true
commandCenter.skipBackwardCommand.removeTarget(nil)
commandCenter.skipBackwardCommand.addTarget { [weak self] event in
guard let audioPlayer = self?.currentlyPlayingAudioPlayer, let skipEvent = event as? MPSkipIntervalCommandEvent else {
return MPRemoteCommandHandlerStatus.commandFailed
}
audioPlayer.seekToTime(audioPlayer.currentTime - skipEvent.interval)
return MPRemoteCommandHandlerStatus.success
}
}
private func tearDownRemoteCommandCenter() {
displayLink.isPaused = true
UIApplication.shared.endReceivingRemoteControlEvents()
let nowPlayingInfoCenter = MPNowPlayingInfoCenter.default()
nowPlayingInfoCenter.nowPlayingInfo = nil
}
private func updateNowPlayingInfoCenter() {
guard let audioPlayer = currentlyPlayingAudioPlayer else {
return
}
let artwork = MPMediaItemArtwork(boundsSize: Constants.roomAvatarImageSize) { [weak self] size in
return self?.roomAvatar ?? UIImage()
}
let nowPlayingInfoCenter = MPNowPlayingInfoCenter.default()
nowPlayingInfoCenter.nowPlayingInfo = [MPMediaItemPropertyTitle: audioPlayer.displayName ?? VectorL10n.voiceMessageLockScreenPlaceholder,
MPMediaItemPropertyArtist: currentRoomSummary?.displayname as Any,
MPMediaItemPropertyArtwork: artwork,
MPMediaItemPropertyPlaybackDuration: audioPlayer.duration as Any,
MPNowPlayingInfoPropertyElapsedPlaybackTime: audioPlayer.currentTime as Any]
}
}
| apache-2.0 | 3f6db3fb6c70db644ff01539fb835565 | 42.522556 | 145 | 0.5948 | 7.102454 | false | false | false | false |
getsentry/sentry-swift | Tests/SentryTests/Protocol/SentryDebugMetaEquality.swift | 1 | 566 | import Foundation
extension DebugMeta {
open override func isEqual(_ object: Any?) -> Bool {
if let other = object as? DebugMeta {
return uuid == other.uuid &&
type == other.type &&
name == other.name &&
imageSize == other.imageSize &&
imageAddress == other.imageAddress &&
imageVmAddress == other.imageVmAddress
} else {
return false
}
}
override open var description: String {
"\(self.serialize())"
}
}
| mit | e305213329f78cfa38b49cb815103e3f | 27.3 | 56 | 0.507067 | 5.053571 | false | false | false | false |
Shashi717/ImmiGuide | ImmiGuide/ImmiGuide/ReadingWritingLiteracyPrograms.swift | 1 | 1429 | //
// ReadingWritingLiteracyPrograms.swift
// ImmiGuide
//
// Created by Cris on 2/18/17.
// Copyright © 2017 Madushani Lekam Wasam Liyanage. All rights reserved.
//
import Foundation
class ReadingWritingLiteracyPrograms {
var programType: String
var program: String
var agencyName: String
var agencyLocation: Location?
var agencyPhoneNumber: String
var ageGroup: String
init?(programType: String, program: String, agencyName: String, agencyLocation: Location?, agencyPhoneNumber: String, ageGroup: String) {
self.programType = programType
self.program = program
self.agencyName = agencyName
self.agencyLocation = agencyLocation
self.agencyPhoneNumber = agencyPhoneNumber
self.ageGroup = ageGroup
}
convenience init?(fromDict: [String : Any]) {
guard let programType = fromDict["program_type"] as? String,
let program = fromDict["program"] as? String,
let name = fromDict["agency"] as? String,
let phoneNumber = fromDict["contact_number"] as? String,
let ageGroup = fromDict["grade_level_age_group"] as? String else { return nil }
let location = Location(dict: fromDict)
self.init(programType: programType, program: program, agencyName: name, agencyLocation: location, agencyPhoneNumber: phoneNumber, ageGroup: ageGroup)
}
}
| mit | 369a74295a9e7204252ef1e900f58a79 | 34.7 | 157 | 0.670868 | 4.476489 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Binary Search/4_Median of Two Sorted Arrays.swift | 1 | 4431 | // 4_Median of Two Sorted Arrays
// https://leetcode.com/problems/median-of-two-sorted-arrays/
//
// Created by Honghao Zhang on 9/16/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// There are two sorted arrays nums1 and nums2 of size m and n respectively.
//
//Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
//
//You may assume nums1 and nums2 cannot be both empty.
//
//Example 1:
//
//nums1 = [1, 3]
//nums2 = [2]
//
//The median is 2.0
//Example 2:
//
//nums1 = [1, 2]
//nums2 = [3, 4]
//
//The median is (2 + 3)/2 = 2.5
//
// 找出两个sorted array中的median
// 实际上把题目转换成找出两个array的kth largest value
import Foundation
class Num4 {
// MARK: - Find the Kth largest
// https://www.jiuzhang.com/solution/median-of-two-sorted-arrays
// public class Solution {
// public double findMedianSortedArrays(int A[], int B[]) {
// int n = A.length + B.length;
//
// if (n % 2 == 0) {
// return (
// findKth(A, 0, B, 0, n / 2) +
// findKth(A, 0, B, 0, n / 2 + 1)
// ) / 2.0;
// }
//
// return findKth(A, 0, B, 0, n / 2 + 1);
// }
//
// // find kth number of two sorted array
// public static int findKth(int[] A, int startOfA,
// int[] B, int startOfB,
// int k){
// if (startOfA >= A.length) {
// return B[startOfB + k - 1];
// }
// if (startOfB >= B.length) {
// return A[startOfA + k - 1];
// }
//
// if (k == 1) {
// return Math.min(A[startOfA], B[startOfB]);
// }
//
// int halfKthOfA = startOfA + k / 2 - 1 < A.length
// ? A[startOfA + k / 2 - 1]
// : Integer.MAX_VALUE;
// int halfKthOfB = startOfB + k / 2 - 1 < B.length
// ? B[startOfB + k / 2 - 1]
// : Integer.MAX_VALUE;
//
// if (halfKthOfA < halfKthOfB) {
// return findKth(A, startOfA + k / 2, B, startOfB, k - k / 2);
// } else {
// return findKth(A, startOfA, B, startOfB + k / 2, k - k / 2);
// }
// }
// }
// O(lg(m + n) solution: https://medium.com/@hazemu/finding-the-median-of-2-sorted-arrays-in-logarithmic-time-1d3f2ecbeb46
// O(m + n) solution
// Merge two arrays and find the median of the merged array.
func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double {
var nums = [Int]()
var p1 = 0
var p2 = 0
while p1 < nums1.count, p2 < nums2.count {
let num1 = nums1[p1]
let num2 = nums2[p2]
if num1 <= num2 {
nums.append(num1)
p1 += 1
}
else if num1 > num2 {
nums.append(num2)
p2 += 1
}
}
while p1 < nums1.count {
nums.append(nums1[p1])
p1 += 1
}
while p2 < nums2.count {
nums.append(nums2[p2])
p2 += 1
}
guard nums.count > 0 else { return 0 }
// [1, 2, 3, 4]
if nums.count % 2 == 0 {
let mid = nums.count / 2
return (Double(nums[mid]) + Double(nums[mid - 1])) / 2
}
// [1, 2, 3]
else {
return Double(nums[nums.count / 2])
}
}
// MARK: - Find the median number
func medianOfSortedArrays(_ array1: [Int], _ array2: [Int]) -> Int? {
if array1.isEmpty, array2.isEmpty {
return nil
}
else if array1.isEmpty {
return array2[array2.count / 2]
}
else if array2.isEmpty {
return array1[array1.count / 2]
}
var index1 = 0
var index2 = 0
// 1
// 2 3 4
// 4
// 1 3 5 7 9
// 2 4 6 8 // 9 - >4
//
// 1 3 5 7
// 2 4 6 8 // 8 -> 4
var dropCount = (array1.count + array2.count) / 2
while dropCount > 0 {
if array1[index1] < array2[index2] {
index1 += 1
if index1 >= array1.count {
return array2[index2 + dropCount - 1]
}
}
else {
index2 += 1
if index2 >= array2.count {
return array1[index1 + dropCount - 1]
}
}
dropCount -= 1
}
if index1 < array1.count, index2 < array2.count {
return min(array1[index1], array2[index2])
}
else if index1 >= array1.count {
return array2[index2]
}
else {
return array1[index1]
}
}
}
| mit | 61874110182ce166cef87774c7bcb9f9 | 24.523256 | 124 | 0.499089 | 3.098095 | false | false | false | false |
uber/rides-ios-sdk | source/UberRidesTests/ObjectMappingTests.swift | 1 | 38298 | //
// ObjectMappingTests.swift
// UberRidesTests
//
// Copyright © 2015 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import UberCore
@testable import UberRides
class ObjectMappingTests: XCTestCase {
override func setUp() {
super.setUp()
Configuration.restoreDefaults()
Configuration.shared.isSandbox = true
}
override func tearDown() {
Configuration.restoreDefaults()
super.tearDown()
}
/**
Tests mapping result of GET /v1/product/{product_id} endpoint.
*/
func testGetProduct() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getProductID", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let product = try? JSONDecoder.uberDecoder.decode(Product.self, from: jsonData)
XCTAssertNotNil(product)
XCTAssertEqual(product!.productID, "a1111c8c-c720-46c3-8534-2fcdd730040d")
XCTAssertEqual(product!.name, "uberX")
XCTAssertEqual(product!.productDescription, "THE LOW-COST UBER")
XCTAssertEqual(product!.capacity, 4)
XCTAssertEqual(product!.imageURL, URL(string: "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-uberx.png")!)
let priceDetails = product!.priceDetails
XCTAssertNotNil(priceDetails)
XCTAssertEqual(priceDetails!.distanceUnit, "mile")
XCTAssertEqual(priceDetails!.costPerMinute, 0.22)
XCTAssertEqual(priceDetails!.minimumFee, 7.0)
XCTAssertEqual(priceDetails!.costPerDistance, 1.15)
XCTAssertEqual(priceDetails!.baseFee, 2.0)
XCTAssertEqual(priceDetails!.cancellationFee, 5.0)
XCTAssertEqual(priceDetails!.currencyCode, "USD")
let serviceFees = priceDetails!.serviceFees
XCTAssertNotNil(serviceFees)
XCTAssertEqual(serviceFees?.count, 1)
XCTAssertEqual(serviceFees?.first?.name, "Booking fee")
XCTAssertEqual(serviceFees?.first?.fee, 2.0)
}
}
}
/**
Tests mapping of malformed result of GET /v1/products endpoint.
*/
func testGetProductBadJSON() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getProductID", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let JSONString = String(data: jsonData, encoding: String.Encoding.utf8)!
// Represent some bad JSON
let jsonData = JSONString.replacingOccurrences(of: "[", with: "").data(using: .utf8)!
let product = try? JSONDecoder.uberDecoder.decode(UberProducts.self, from: jsonData)
XCTAssertNil(product)
}
}
}
/**
Tests mapping result of GET /v1/products/{product_id} endpoint.
*/
func testGetAllProducts() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getProducts", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let products = try? JSONDecoder.uberDecoder.decode(UberProducts.self, from: jsonData)
XCTAssertNotNil(products)
XCTAssertNotNil(products!.list)
XCTAssertEqual(products!.list!.count, 9)
XCTAssertEqual(products!.list![0].name, "SELECT")
XCTAssertEqual(products!.list![1].name, "uberXL")
XCTAssertEqual(products!.list![2].name, "BLACK")
XCTAssertEqual(products!.list![3].name, "SUV")
XCTAssertEqual(products!.list![4].name, "ASSIST")
XCTAssertEqual(products!.list![5].name, "WAV")
XCTAssertEqual(products!.list![6].name, "POOL")
XCTAssertEqual(products!.list![7].name, "uberX")
XCTAssertEqual(products!.list![8].name, "TAXI")
/// Assert upfront fare product, POOL
let uberPool = products?.list?[6]
XCTAssertEqual(uberPool?.upfrontFareEnabled, true)
XCTAssertEqual(uberPool?.capacity, 2)
XCTAssertEqual(uberPool?.productID, "26546650-e557-4a7b-86e7-6a3942445247")
XCTAssertNil(uberPool?.priceDetails)
XCTAssertEqual(uberPool?.imageURL, URL(string: "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-uberx.png")!)
XCTAssertEqual(uberPool?.cashEnabled, false)
XCTAssertEqual(uberPool?.isShared, true)
XCTAssertEqual(uberPool?.name, "POOL")
XCTAssertEqual(uberPool?.productGroup, ProductGroup.rideshare)
XCTAssertEqual(uberPool?.productDescription, "Share the ride, split the cost.")
/// Assert time+distance product, uberX (pulled from Sydney)
let uberX = products?.list?[7]
XCTAssertEqual(uberX?.upfrontFareEnabled, false)
XCTAssertEqual(uberX?.capacity, 4)
XCTAssertEqual(uberX?.productID, "2d1d002b-d4d0-4411-98e1-673b244878b2")
XCTAssertEqual(uberX?.imageURL, URL(string: "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-uberx.png")!)
XCTAssertEqual(uberX?.cashEnabled, false)
XCTAssertEqual(uberX?.isShared, false)
XCTAssertEqual(uberX?.name, "uberX")
XCTAssertEqual(uberX?.productGroup, ProductGroup.uberX)
XCTAssertEqual(uberX?.productDescription, "Everyday rides that are always smarter than a taxi")
XCTAssertEqual(uberX?.priceDetails?.serviceFees?.first?.fee, 0.55)
XCTAssertEqual(uberX?.priceDetails?.serviceFees?.first?.name, "Booking fee")
XCTAssertEqual(uberX?.priceDetails?.costPerMinute, 0.4)
XCTAssertEqual(uberX?.priceDetails?.distanceUnit, "km")
XCTAssertEqual(uberX?.priceDetails?.minimumFee, 9)
XCTAssertEqual(uberX?.priceDetails?.costPerDistance, 1.45)
XCTAssertEqual(uberX?.priceDetails?.baseFee, 2.5)
XCTAssertEqual(uberX?.priceDetails?.cancellationFee, 10)
XCTAssertEqual(uberX?.priceDetails?.currencyCode, "AUD")
/// Assert hail product, TAXI
let taxi = products?.list?[8]
XCTAssertEqual(taxi?.upfrontFareEnabled, false)
XCTAssertEqual(taxi?.capacity, 4)
XCTAssertEqual(taxi?.productID, "3ab64887-4842-4c8e-9780-ccecd3a0391d")
XCTAssertNil(uberPool?.priceDetails)
XCTAssertEqual(taxi?.imageURL, URL(string: "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-taxi.png")!)
XCTAssertEqual(taxi?.cashEnabled, false)
XCTAssertEqual(taxi?.isShared, false)
XCTAssertEqual(taxi?.name, "TAXI")
XCTAssertEqual(taxi?.productGroup, ProductGroup.taxi)
XCTAssertEqual(taxi?.productDescription, "TAXI WITHOUT THE HASSLE")
}
}
}
/**
Tests mapping of malformed result of GET /v1/products endpoint.
*/
func testGetAllProductsBadJSON() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getProducts", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let JSONString = String(data: jsonData, encoding: String.Encoding.utf8)!
// Represent some bad JSON
let jsonData = JSONString.replacingOccurrences(of: "[", with: "").data(using: .utf8)!
let products = try? JSONDecoder.uberDecoder.decode(UberProducts.self, from: jsonData)
XCTAssertNil(products)
}
}
}
/**
Tests mapping result of GET /v1.2/estimates/time
*/
func testGetTimeEstimates() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getTimeEstimates", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let timeEstimates = try? JSONDecoder.uberDecoder.decode(TimeEstimates.self, from: jsonData)
XCTAssertNotNil(timeEstimates)
XCTAssertNotNil(timeEstimates!.list)
let list = timeEstimates!.list!
XCTAssertEqual(timeEstimates!.list!.count, 4)
XCTAssertEqual(list[0].productID, "5f41547d-805d-4207-a297-51c571cf2a8c")
XCTAssertEqual(list[0].estimate, 410)
XCTAssertEqual(list[0].name, "UberBLACK")
XCTAssertEqual(list[1].name, "UberSUV")
XCTAssertEqual(list[2].name, "uberTAXI")
XCTAssertEqual(list[3].name, "uberX")
}
}
}
/**
Tests mapping of malformed result of GET /v1.2/estimates/time
*/
func testGetTimeEstimatesBadJSON() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getTimeEstimates", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let JSONString = String(data: jsonData, encoding: String.Encoding.utf8)!
// Represent some bad JSON
let jsonData = JSONString.replacingOccurrences(of: "[", with: "").data(using: .utf8)!
let timeEstimates = try? JSONDecoder.uberDecoder.decode(TimeEstimates.self, from: jsonData)
XCTAssertNil(timeEstimates)
}
}
}
/**
Tests mapping result of GET /v1.2/estimates/price endpoint.
*/
func testGetPriceEstimates() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getPriceEstimates", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
var priceEstimates: PriceEstimates?
do {
priceEstimates = try JSONDecoder.uberDecoder.decode(PriceEstimates.self, from: jsonData)
} catch let e {
XCTFail(e.localizedDescription)
}
XCTAssertNotNil(priceEstimates)
XCTAssertNotNil(priceEstimates!.list)
let list = priceEstimates!.list!
XCTAssertEqual(list.count, 4)
XCTAssertEqual(list[0].productID, "08f17084-23fd-4103-aa3e-9b660223934b")
XCTAssertEqual(list[0].currencyCode, "USD")
XCTAssertEqual(list[0].name, "UberBLACK")
XCTAssertEqual(list[0].estimate, "$23-29")
XCTAssertEqual(list[0].lowEstimate, 23)
XCTAssertEqual(list[0].highEstimate, 29)
XCTAssertEqual(list[0].surgeMultiplier, 1)
XCTAssertEqual(list[0].duration, 640)
XCTAssertEqual(list[0].distance, 5.34)
}
}
}
/**
Tests mapping of malformed result of GET /v1.2/estimates/price endpoint.
*/
func testGetPriceEstimatesBadJSON() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getPriceEstimates", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let JSONString = String(data: jsonData, encoding: String.Encoding.utf8)!
// Represent some bad JSON
let jsonData = JSONString.replacingOccurrences(of: "[", with: "").data(using: .utf8)!
let priceEstimates = try? JSONDecoder.uberDecoder.decode(PriceEstimates.self, from: jsonData)
XCTAssertNil(priceEstimates)
}
}
}
/**
Tests mapping result of GET /v1.2/history
*/
func testGetTripHistory() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getHistory", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let userActivity = try? JSONDecoder.uberDecoder.decode(TripHistory.self, from: jsonData)
XCTAssertNotNil(userActivity)
XCTAssertNotNil(userActivity!.history)
XCTAssertEqual(userActivity!.count, 1)
XCTAssertEqual(userActivity!.limit, 5)
XCTAssertEqual(userActivity!.offset, 0)
let history = userActivity!.history
XCTAssertEqual(history.count, 1)
XCTAssertEqual(history[0].status, RideStatus.completed)
XCTAssertEqual(history[0].distance, 1.64691465)
XCTAssertEqual(history[0].requestTime, Date(timeIntervalSince1970: 1428876188))
XCTAssertEqual(history[0].startTime, Date(timeIntervalSince1970: 1428876374))
XCTAssertEqual(history[0].endTime, Date(timeIntervalSince1970: 1428876927))
XCTAssertEqual(history[0].requestID, "37d57a99-2647-4114-9dd2-c43bccf4c30b")
XCTAssertEqual(history[0].productID, "a1111c8c-c720-46c3-8534-2fcdd730040d")
XCTAssertNotNil(history[0].startCity)
let city = history[0].startCity
XCTAssertEqual(city?.name, "San Francisco")
XCTAssertEqual(city?.latitude, 37.7749295)
XCTAssertEqual(city?.longitude, -122.4194155)
}
}
}
/**
Tests mapping of malformed result of GET /v1.2/history endpoint.
*/
func testGetHistoryBadJSON() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getHistory", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let JSONString = String(data: jsonData, encoding: String.Encoding.utf8)!
// Represent some bad JSON
let jsonData = JSONString.replacingOccurrences(of: "[", with: "").data(using: .utf8)!
let userActivity = try? JSONDecoder.uberDecoder.decode(TripHistory.self, from: jsonData)
XCTAssertNil(userActivity)
}
}
}
/**
Tests mapping result of GET /v1/me endpoint.
*/
func testGetUserProfile() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getMe", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let userProfile = try? JSONDecoder.uberDecoder.decode(UserProfile.self, from: jsonData)
XCTAssertNotNil(userProfile)
XCTAssertEqual(userProfile!.firstName, "Uber")
XCTAssertEqual(userProfile!.lastName, "Developer")
XCTAssertEqual(userProfile!.email, "[email protected]")
XCTAssertEqual(userProfile!.picturePath, "https://profile-picture.jpg")
XCTAssertEqual(userProfile!.promoCode, "teypo")
XCTAssertEqual(userProfile!.UUID, "91d81273-45c2-4b57-8124-d0165f8240c0")
XCTAssertEqual(userProfile!.riderID, "kIN8tMqcXMSJt1VC3HWNF0H4VD1JKlJkY==")
}
}
}
/**
Tests mapping of malformed result of GET /v1/me endpoint.
*/
func testGetUserProfileBadJSON() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getMe", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let JSONString = String(data: jsonData, encoding: String.Encoding.utf8)!
let jsonData = JSONString.replacingOccurrences(of: "{", with: "").data(using: .utf8)!
let userProfile = try? JSONDecoder.uberDecoder.decode(UserProfile.self, from: jsonData)
XCTAssertNil(userProfile)
}
}
}
/**
Tests mapping result of POST /v1/requests
*/
func testPostRequest() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "postRequests", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let trip = try? JSONDecoder.uberDecoder.decode(Ride.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertNotNil(trip)
XCTAssertEqual(trip.requestID, "852b8fdd-4369-4659-9628-e122662ad257")
XCTAssertEqual(trip.status, RideStatus.processing)
XCTAssertNil(trip.vehicle)
XCTAssertNil(trip.driver)
XCTAssertNil(trip.driverLocation)
XCTAssertEqual(trip.surgeMultiplier, 1.0)
}
}
}
/**
Tests mapping result of GET /v1/requests/current or /v1/requests/{request_id}
*/
func testGetRequestProcessing() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getRequestProcessing", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let trip = try? JSONDecoder.uberDecoder.decode(Ride.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(trip.requestID, "43faeac4-1634-4a0c-9826-783e3a3d1668")
XCTAssertEqual(trip.productID, "a1111c8c-c720-46c3-8534-2fcdd730040d")
XCTAssertEqual(trip.status, RideStatus.processing)
XCTAssertEqual(trip.isShared, false)
XCTAssertNil(trip.driverLocation)
XCTAssertNil(trip.vehicle)
XCTAssertNil(trip.driver)
XCTAssertNotNil(trip.pickup)
XCTAssertEqual(trip.pickup!.latitude, 37.7759792)
XCTAssertEqual(trip.pickup!.longitude, -122.41823)
XCTAssertNil(trip.pickup!.eta)
XCTAssertNotNil(trip.destination)
XCTAssertEqual(trip.destination!.latitude, 37.7259792)
XCTAssertEqual(trip.destination!.longitude, -122.42823)
XCTAssertNil(trip.destination!.eta)
}
}
}
/**
Tests mapping result of GET /v1/requests/current or /v1/requests/{request_id}
*/
func testGetRequestAccepted() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getRequestAccepted", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let trip = try? JSONDecoder.uberDecoder.decode(Ride.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(trip.requestID, "17cb78a7-b672-4d34-a288-a6c6e44d5315")
XCTAssertEqual(trip.productID, "a1111c8c-c720-46c3-8534-2fcdd730040d")
XCTAssertEqual(trip.status, RideStatus.accepted)
XCTAssertEqual(trip.isShared, false)
XCTAssertEqual(trip.surgeMultiplier, 1.0)
XCTAssertNotNil(trip.driverLocation)
XCTAssertEqual(trip.driverLocation!.latitude, 37.7886532015)
XCTAssertEqual(trip.driverLocation!.longitude, -122.3961987534)
XCTAssertEqual(trip.driverLocation!.bearing, 135)
XCTAssertNotNil(trip.vehicle)
XCTAssertEqual(trip.vehicle!.make, "Bugatti")
XCTAssertEqual(trip.vehicle!.model, "Veyron")
XCTAssertEqual(trip.vehicle!.licensePlate, "I<3Uber")
XCTAssertEqual(trip.vehicle!.pictureURL, URL(string: "https://d1w2poirtb3as9.cloudfront.net/car.jpeg")!)
XCTAssertNotNil(trip.driver)
XCTAssertEqual(trip.driver!.name, "Bob")
XCTAssertEqual(trip.driver!.pictureURL, URL(string: "https://d1w2poirtb3as9.cloudfront.net/img.jpeg")!)
XCTAssertEqual(trip.driver!.phoneNumber, "+14155550000")
XCTAssertEqual(trip.driver!.smsNumber, "+14155550000")
XCTAssertEqual(trip.driver!.rating, 5)
XCTAssertNotNil(trip.pickup)
XCTAssertEqual(trip.pickup!.latitude, 37.7872486012)
XCTAssertEqual(trip.pickup!.longitude, -122.4026315287)
XCTAssertEqual(trip.pickup!.eta, 5)
XCTAssertNotNil(trip.destination)
XCTAssertEqual(trip.destination!.latitude, 37.7766874)
XCTAssertEqual(trip.destination!.longitude, -122.394857)
XCTAssertEqual(trip.destination!.eta, 19)
}
}
}
/**
Tests mapping result of GET /v1/requests/current or /v1/requests/{request_id}
*/
func testGetRequestArriving() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getRequestArriving", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let trip = try? JSONDecoder.uberDecoder.decode(Ride.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(trip.requestID, "a274f565-cdb7-4a64-947d-042dfd185eed")
XCTAssertEqual(trip.productID, "a1111c8c-c720-46c3-8534-2fcdd730040d")
XCTAssertEqual(trip.status, RideStatus.arriving)
XCTAssertEqual(trip.isShared, false)
XCTAssertNotNil(trip.driverLocation)
XCTAssertEqual(trip.driverLocation?.latitude, 37.7751956968)
XCTAssertEqual(trip.driverLocation?.longitude, -122.4174361781)
XCTAssertEqual(trip.driverLocation?.bearing, 310)
XCTAssertNotNil(trip.vehicle)
XCTAssertEqual(trip.vehicle?.make, "Oldsmobile")
XCTAssertNil(trip.vehicle?.pictureURL)
XCTAssertEqual(trip.vehicle?.model, "Alero")
XCTAssertEqual(trip.vehicle?.licensePlate, "123-XYZ")
XCTAssertNotNil(trip.driver)
XCTAssertEqual(trip.driver?.phoneNumber, "+16504886027")
XCTAssertEqual(trip.driver?.rating, 5)
XCTAssertEqual(trip.driver?.pictureURL, URL(string: "https://d1w2poirtb3as9.cloudfront.net/4615701cdfbb033148d4.jpeg")!)
XCTAssertEqual(trip.driver?.name, "Edward")
XCTAssertEqual(trip.driver?.smsNumber, "+16504886027")
XCTAssertNotNil(trip.pickup)
XCTAssertEqual(trip.pickup!.latitude, 37.7759792)
XCTAssertEqual(trip.pickup!.longitude, -122.41823)
XCTAssertEqual(trip.pickup!.eta, 1)
XCTAssertNotNil(trip.destination)
XCTAssertEqual(trip.destination!.latitude, 37.7259792)
XCTAssertEqual(trip.destination!.longitude, -122.42823)
XCTAssertEqual(trip.destination!.eta, 16)
}
}
}
/**
Tests mapping result of GET /v1/requests/current or /v1/requests/{request_id}
*/
func testGetRequestInProgress() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getRequestInProgress", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let trip = try? JSONDecoder.uberDecoder.decode(Ride.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(trip.requestID, "a274f565-cdb7-4a64-947d-042dfd185eed")
XCTAssertEqual(trip.productID, "a1111c8c-c720-46c3-8534-2fcdd730040d")
XCTAssertEqual(trip.status, RideStatus.inProgress)
XCTAssertEqual(trip.isShared, false)
XCTAssertNotNil(trip.driverLocation)
XCTAssertEqual(trip.driverLocation?.latitude, 37.7751956968)
XCTAssertEqual(trip.driverLocation?.longitude, -122.4174361781)
XCTAssertEqual(trip.driverLocation?.bearing, 310)
XCTAssertNotNil(trip.vehicle)
XCTAssertEqual(trip.vehicle?.make, "Oldsmobile")
XCTAssertNil(trip.vehicle?.pictureURL)
XCTAssertEqual(trip.vehicle?.model, "Alero")
XCTAssertEqual(trip.vehicle?.licensePlate, "123-XYZ")
XCTAssertNotNil(trip.driver)
XCTAssertEqual(trip.driver?.phoneNumber, "+16504886027")
XCTAssertEqual(trip.driver?.rating, 5)
XCTAssertEqual(trip.driver?.pictureURL, URL(string: "https://d1w2poirtb3as9.cloudfront.net/4615701cdfbb033148d4.jpeg")!)
XCTAssertEqual(trip.driver?.name, "Edward")
XCTAssertEqual(trip.driver?.smsNumber, "+16504886027")
XCTAssertNotNil(trip.pickup)
XCTAssertEqual(trip.pickup!.latitude, 37.7759792)
XCTAssertEqual(trip.pickup!.longitude, -122.41823)
XCTAssertNil(trip.pickup!.eta)
XCTAssertNotNil(trip.destination)
XCTAssertEqual(trip.destination!.latitude, 37.7259792)
XCTAssertEqual(trip.destination!.longitude, -122.42823)
XCTAssertEqual(trip.destination!.eta, 16)
}
}
}
/**
Tests mapping result of GET /v1/requests/current or /v1/requests/{request_id}
*/
func testGetRequestCompleted() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getRequestCompleted", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let trip = try? JSONDecoder.uberDecoder.decode(Ride.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(trip.requestID, "a274f565-cdb7-4a64-947d-042dfd185eed")
XCTAssertEqual(trip.productID, "a1111c8c-c720-46c3-8534-2fcdd730040d")
XCTAssertEqual(trip.status, RideStatus.completed)
XCTAssertEqual(trip.isShared, false)
XCTAssertNil(trip.driverLocation)
XCTAssertNil(trip.vehicle)
XCTAssertNil(trip.driver)
XCTAssertNil(trip.pickup)
XCTAssertNil(trip.destination)
}
}
}
/**
Tests mapping of POST /v1.2/requests/estimate endpoint.
*/
func testGetRequestEstimate() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "requestEstimate", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
var estimate: RideEstimate?
do {
estimate = try JSONDecoder.uberDecoder.decode(RideEstimate.self, from: jsonData)
}
catch let e {
XCTFail(e.localizedDescription)
}
XCTAssertNotNil(estimate)
XCTAssertEqual(estimate!.pickupEstimate, 2)
XCTAssertNotNil(estimate?.fare)
XCTAssertEqual(estimate?.fare?.breakdown?.first?.name, "Base Fare")
XCTAssertEqual(estimate?.fare?.breakdown?.first?.type, UpfrontFareComponentType.baseFare)
XCTAssertEqual(estimate?.fare?.breakdown?.first?.value, 11.95)
XCTAssertEqual(estimate?.fare?.value, 11.95)
XCTAssertEqual(estimate?.fare?.fareID, "3d957d6ab84e88209b6778d91bd4df3c12d17b60796d89793d6ed01650cbabfe")
XCTAssertEqual(estimate?.fare?.expiresAt, Date(timeIntervalSince1970: 1503702982))
XCTAssertEqual(estimate?.fare?.display, "$11.95")
XCTAssertEqual(estimate?.fare?.currencyCode, "USD")
XCTAssertNotNil(estimate!.distanceEstimate)
XCTAssertEqual(estimate!.distanceEstimate!.distance, 5.35)
XCTAssertEqual(estimate!.distanceEstimate!.duration, 840)
XCTAssertEqual(estimate!.distanceEstimate!.distanceUnit, "mile")
}
}
}
/**
Tests mapping of POST /v1.2/requests/estimate endpoint for a city w/o upfront pricing.
*/
func testGetRequestEstimateNoUpfront() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "requestEstimateNoUpfront", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let estimate = try? JSONDecoder.uberDecoder.decode(RideEstimate.self, from: jsonData)
XCTAssertNotNil(estimate)
XCTAssertEqual(estimate!.pickupEstimate, 2)
XCTAssertNotNil(estimate!.priceEstimate)
XCTAssertEqual(estimate!.priceEstimate?.surgeConfirmationURL, URL(string: "https://api.uber.com/v1/surge-confirmations/7d604f5e"))
XCTAssertEqual(estimate!.priceEstimate?.surgeConfirmationID, "7d604f5e")
XCTAssertNotNil(estimate!.distanceEstimate)
XCTAssertEqual(estimate!.distanceEstimate!.distance, 4.87)
XCTAssertEqual(estimate!.distanceEstimate!.duration, 660)
XCTAssertEqual(estimate!.distanceEstimate!.distanceUnit, "mile")
}
}
}
func testGetRequestEstimateNoCars() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "requestEstimateNoCars", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let estimate = try? JSONDecoder.uberDecoder.decode(RideEstimate.self, from: jsonData)
XCTAssertNotNil(estimate)
XCTAssertNil(estimate!.pickupEstimate)
XCTAssertNotNil(estimate!.priceEstimate)
XCTAssertEqual(estimate!.priceEstimate?.surgeConfirmationURL, URL(string: "https://api.uber.com/v1/surge-confirmations/7d604f5e"))
XCTAssertEqual(estimate!.priceEstimate?.surgeConfirmationID, "7d604f5e")
XCTAssertNotNil(estimate!.distanceEstimate)
XCTAssertEqual(estimate!.distanceEstimate!.distance, 4.87)
XCTAssertEqual(estimate!.distanceEstimate!.duration, 660)
XCTAssertEqual(estimate!.distanceEstimate!.distanceUnit, "mile")
}
}
}
/**
Tests mapping of GET v1/places/{place_id} endpoint
*/
func testGetPlace() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "place", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let place = try? JSONDecoder.uberDecoder.decode(Place.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(place.address, "685 Market St, San Francisco, CA 94103, USA")
return
}
}
XCTAssert(false)
}
/**
Tests mapping of GET /v1/payment-methods endpoint.
*/
func testGetPaymentMethods() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getPaymentMethods", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let paymentMethods = try? JSONDecoder.uberDecoder.decode(PaymentMethods.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(paymentMethods.lastUsed, "f53847de-8113-4587-c307-51c2d13a823c")
guard let payments = paymentMethods.list else {
XCTAssert(false)
return
}
XCTAssertEqual(payments.count, 4)
XCTAssertEqual(payments[0].methodID, "5f384f7d-8323-4207-a297-51c571234a8c")
XCTAssertEqual(payments[1].methodID, "f33847de-8113-4587-c307-51c2d13a823c")
XCTAssertEqual(payments[2].methodID, "f43847de-8113-4587-c307-51c2d13a823c")
XCTAssertEqual(payments[3].methodID, "f53847de-8113-4587-c307-51c2d13a823c")
XCTAssertEqual(payments[0].type, "baidu_wallet")
XCTAssertEqual(payments[1].type, "alipay")
XCTAssertEqual(payments[2].type, "visa")
XCTAssertEqual(payments[3].type, "business_account")
XCTAssertEqual(payments[0].paymentDescription, "***53")
XCTAssertEqual(payments[1].paymentDescription, "ga***@uber.com")
XCTAssertEqual(payments[2].paymentDescription, "***23")
XCTAssertEqual(payments[3].paymentDescription, "Late Night Ride")
return
}
}
XCTAssert(false)
}
/**
Tests mapping of GET /v1/requests/{request_id}/receipt endpoint.
*/
func testGetRideReceipt() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "rideReceipt", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let receipt = try? JSONDecoder.uberDecoder.decode(RideReceipt.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(receipt.requestID, "f590713c-fe6b-438b-9da1-8aeeea430657")
let chargeAdjustments = receipt.chargeAdjustments
XCTAssertEqual(chargeAdjustments?.count, 1)
XCTAssertEqual(chargeAdjustments?.first?.name, "Booking Fee")
XCTAssertEqual(chargeAdjustments?.first?.type, "booking_fee")
XCTAssertEqual(receipt.subtotal, "$12.78")
XCTAssertEqual(receipt.totalCharged, "$5.92")
XCTAssertEqual(receipt.totalFare, "$12.79")
XCTAssertEqual(receipt.totalOwed, 0.0)
XCTAssertEqual(receipt.currencyCode, "USD")
XCTAssertEqual(receipt.duration?.hour, 0)
XCTAssertEqual(receipt.duration?.minute, 11)
XCTAssertEqual(receipt.duration?.second, 32)
XCTAssertEqual(receipt.distance, "1.87")
XCTAssertEqual(receipt.distanceLabel, "miles")
return
}
}
XCTAssert(false)
}
/**
Test bad JSON for GET /v1/reqeuests/{request_id}/receipt
*/
func testGetRideReceiptBadJSON() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "rideReceipt", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let JSONString = String(data: jsonData, encoding: String.Encoding.utf8)!
let jsonData = JSONString.replacingOccurrences(of: "[", with: "").data(using: .utf8)!
let receipt = try? JSONDecoder.uberDecoder.decode(RideReceipt.self, from: jsonData)
XCTAssertNil(receipt)
return
}
}
XCTAssert(false)
}
/**
Tests mapping of GET /v1/requests/{request_id}/map endpoint.
*/
func testGetRideMap() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "rideMap", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let map = try? JSONDecoder.uberDecoder.decode(RideMap.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(map.path, URL(string: "https://trip.uber.com/abc123")!)
XCTAssertEqual(map.requestID, "b5512127-a134-4bf4-b1ba-fe9f48f56d9d")
return
}
}
XCTAssert(false)
}
}
| mit | dd2afa6080785abc088208d3345320a5 | 46.45601 | 146 | 0.599316 | 4.787125 | false | true | false | false |
keyeMyria/edx-app-ios | Source/Stream.swift | 1 | 16706 | //
// Stream.swift
// edX
//
// Created by Akiva Leffert on 6/15/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
// Bookkeeping class for a listener of a stream
private class Listener<A> : Removable, Equatable, Printable {
private var removeAction : (Listener<A> -> Void)?
private var action : (Result<A> -> Void)?
init(action : Result<A> -> Void, removeAction : Listener<A> -> Void) {
self.action = action
self.removeAction = removeAction
}
func remove() {
self.removeAction?(self)
self.removeAction = nil
self.action = nil
}
var description : String {
let address = unsafeBitCast(self, UnsafePointer<Void>.self)
return NSString(format: "<%@: %p>", "\(self.dynamicType)", address) as String
}
}
private func == <A>(lhs : Listener<A>, rhs : Listener<A>) -> Bool {
/// We want to use pointer equality for equality since the main thing
/// we care about for listeners is are they the same instance so we can remove them
return lhs === rhs
}
public protocol StreamDependency : class, Printable {
var active : Bool {get}
}
// MARK: Reading Streams
// This should really be a protocol with Sink a concrete instantiation of that protocol
// But unfortunately Swift doesn't currently support generic protocols
// Revisit this if it ever does
private let backgroundQueue = NSOperationQueue()
/// A stream of values and errors. Note that, like all objects, a stream will get deallocated if it has no references.
public class Stream<A> : StreamDependency {
private let dependencies : [StreamDependency]
private(set) var lastResult : Result<A>?
public var description : String {
let deps = join(", ", self.dependencies.map({ $0.description }))
let ls = join(", ", self.listeners.map({ $0.description }))
let address = unsafeBitCast(self, UnsafePointer<Void>.self)
return NSString(format: "<%@: %p, deps = {%@}, listeners = {%@}>", "\(self.dynamicType)", address, deps, ls) as String
}
private var baseActive : Bool {
return false
}
public var active : Bool {
return reduce(dependencies, baseActive, {$0 || $1.active} )
}
public var value : A? {
return lastResult?.value
}
public var error : NSError? {
return lastResult?.error
}
private var listeners : [Listener<A>] = []
/// Make a new stream.
///
/// :param: dependencies A list of objects that this stream will retain.
/// Typically this is a stream or streams that this object is listening to so that
/// they don't get deallocated.
private init(dependencies : [StreamDependency]) {
self.dependencies = dependencies
}
public convenience init() {
self.init(dependencies : [])
}
/// Seed a new stream with a constant value.
///
/// :param: value The initial value of the stream.
public convenience init(value : A) {
self.init()
self.lastResult = Success(value)
}
/// Seed a new stream with a constant error.
///
/// :param: error The initial error for the stream
public convenience init(error : NSError) {
self.init()
self.lastResult = Failure(error)
}
/// Add a listener to a stream.
///
/// :param: owner The listener will automatically be removed when owner gets deallocated.
/// :param: fireIfLoaded If true then this will fire the listener immediately if the signal has already received a value.
/// :param: action The action to fire when the stream receives a result.
public func listen(owner : NSObject, fireIfAlreadyLoaded : Bool = true, action : Result<A> -> Void) -> Removable {
let listener = Listener(action: action) {[weak self] (listener : Listener<A>) in
if let listeners = self?.listeners, index = find(listeners, listener) {
self?.listeners.removeAtIndex(index)
}
}
listeners.append(listener)
let removable = owner.oex_performActionOnDealloc {
listener.remove()
}
if let value = self.value where fireIfAlreadyLoaded {
action(Success(value))
}
else if let error = self.error where fireIfAlreadyLoaded {
action(Failure(error))
}
return BlockRemovable {
removable.remove()
listener.remove()
}
}
/// Add a listener to a stream.
///
/// :param: owner The listener will automatically be removed when owner gets deallocated.
/// :param: fireIfLoaded If true then this will fire the listener immediately if the signal has already received a value. If false the listener won't fire until a new result is supplied to the stream.
/// :param: success The action to fire when the stream receives a Success result.
/// :param: success The action to fire when the stream receives a Failure result.
public func listen(owner : NSObject, fireIfAlreadyLoaded : Bool = true, success : A -> Void, failure : NSError -> Void) -> Removable {
return listen(owner, fireIfAlreadyLoaded: fireIfAlreadyLoaded) {
switch $0 {
case let .Success(v): success(v.value)
case let .Failure(e): failure(e)
}
}
}
/// Add a listener to a stream. When the listener fires it will be removed automatically.
///
/// :param: owner The listener will automatically be removed when owner gets deallocated.
/// :param: fireIfLoaded If true then this will fire the listener immediately if the signal has already received a value. If false the listener won't fire until a new result is supplied to the stream.
/// :param: success The action to fire when the stream receives a Success result.
/// :param: success The action to fire when the stream receives a Failure result.
public func listenOnce(owner : NSObject, fireIfAlreadyLoaded : Bool = true, success : A -> Void, failure : NSError -> Void) -> Removable {
return listenOnce(owner, fireIfAlreadyLoaded: fireIfAlreadyLoaded, action : {
switch $0 {
case let .Success(box): success(box.value)
case let .Failure(error): failure(error)
}
})
}
public func listenOnce(owner : NSObject, fireIfAlreadyLoaded : Bool = true, action : Result<A> -> Void) -> Removable {
let removable = listen(owner, fireIfAlreadyLoaded: fireIfAlreadyLoaded, action : action)
let followup = listen(owner, fireIfAlreadyLoaded: fireIfAlreadyLoaded,
action: {_ in
removable.remove()
}
)
return BlockRemovable {
removable.remove()
followup.remove()
}
}
/// :returns: A filtered stream based on the receiver that will only fire the first time a success value is sent. Use this if you want to capture a value and *not* update when the next one comes in.
public func firstSuccess() -> Stream<A> {
let sink = Sink<A>(dependencies: [self])
listen(sink.token) {[weak sink] result in
if sink?.lastResult?.isFailure ?? true {
sink?.send(result)
}
}
return sink
}
/// :returns: A filtered stream based on the receiver that won't fire on errors after a value is loaded. It will fire if a new value comes through after a value is already loaded.
public func dropFailuresAfterSuccess() -> Stream<A> {
let sink = Sink<A>(dependencies: [self])
listen(sink.token) {[weak sink] result in
if sink?.lastResult == nil || result.isSuccess {
sink?.send(result)
}
}
return sink
}
/// Transforms a stream into a new stream. Failure results will pass through untouched.
public func map<B>(f : A -> B) -> Stream<B> {
let sink = Sink<B>(dependencies: [self])
listen(sink.token) {[weak sink] result in
sink?.send(result.map(f))
}
return sink
}
/// Transforms a stream into a new stream.
public func flatMap<B>(f : A -> Result<B>) -> Stream<B> {
let sink = Sink<B>(dependencies: [self])
listen(sink.token) {[weak sink] current in
let next = current.flatMap(f)
sink?.send(next)
}
return sink
}
/// :returns: A stream that is automatically backed by a new stream whenever the receiver fires.
public func transform<B>(f : A -> Stream<B>) -> Stream<B> {
let backed = BackedStream<B>(dependencies: [self])
listen(backed.token) {[weak backed] current in
current.ifSuccess {
backed?.backWithStream(f($0))
}
}
return backed
}
/// Stream that calls a cancelation action if the stream gets deallocated.
/// Use if you want to perform an action once no one is listening to a stream
/// for example, an expensive operation or a network request
/// :param: cancel The action to perform when this stream gets deallocated.
public func autoCancel(cancelAction : Removable) -> Stream<A> {
let sink = CancellingSink<A>(dependencies : [self], removable: cancelAction)
listen(sink.token) {[weak sink] current in
sink?.send(current)
}
return sink
}
/// Extends the lifetime of a stream until the first result received.
///
/// :param: completion A completion that fires when the stream fires
public func extendLifetimeUntilFirstResult(completion : Result<A> -> Void) {
backgroundQueue.addOperation(StreamWaitOperation(stream: self, completion: completion))
}
/// Constructs a stream that returns values from the receiver, but will return any values from *stream* until
/// the first value is sent to the receiver. For example, if you're implementing a network cache, you want to
/// return the value saved to disk, but only if the network request hasn't finished yet.
public func cachedByStream(cacheStream : Stream<A>) -> Stream<A> {
let sink = Sink<A>(dependencies: [cacheStream, self])
listen(sink.token) {[weak sink] current in
sink?.send(current)
}
cacheStream.listen(sink.token) {[weak sink, weak self] current in
if self?.lastResult == nil {
sink?.send(current)
}
}
return sink
}
}
// MARK: Writing Streams
/// A writable stream.
/// Sink is a separate type from stream to make it easy to control who can write to the stream.
/// If you need a writeble stream, typically you'll use a Sink internally,
/// but upcast to stream outside of the relevant abstraction boundary
public class Sink<A> : Stream<A> {
// This gives us an NSObject with the same lifetime as our
// sink so that we can associate a removal action for when the sink gets deallocated
private let token = NSObject()
private var open : Bool
override private init(dependencies : [StreamDependency]) {
// Streams with dependencies typically want to use their dependencies' lifetimes exclusively.
// Streams with no dependencies need to manage their own lifetime
open = dependencies.count == 0
super.init(dependencies : dependencies)
}
override private var baseActive : Bool {
return open
}
public func send(value : A) {
send(Success(value))
}
public func send(error : NSError) {
send(Failure(error))
}
public func send(result : Result<A>) {
self.lastResult = result
for listener in listeners {
listener.action?(result)
}
}
// Mark the sink as inactive. Note that closed streams with active dependencies may still be active
public func close() {
open = false
}
}
// Sink that automatically cancels an operation when it deinits.
private class CancellingSink<A> : Sink<A> {
let removable : Removable
init(dependencies : [StreamDependency], removable : Removable) {
self.removable = removable
super.init(dependencies : dependencies)
}
deinit {
removable.remove()
}
}
/// A stream that is rewirable. This is shorthand for the pattern of having a variable
/// representing an optional stream that is imperatively updated.
/// Using a BackedStream lets you set listeners once and always have a
/// non-optional value to pass around that others can receive values from.
public class BackedStream<A> : Stream<A> {
private let token = NSObject()
private var backing : StreamDependency?
private var removeBackingAction : Removable?
override private init(dependencies : [StreamDependency]) {
super.init(dependencies : dependencies)
}
override private var baseActive : Bool {
return backing?.active ?? false
}
/// Removes the old backing and adds a new one. When the backing stream fires so will this one.
/// Think of this as rewiring a pipe from an old source to a new one.
public func backWithStream(backing : Stream<A>) {
removeBacking()
self.backing = backing
self.removeBackingAction = backing.listen(self.token) {[weak self] result in
self?.send(result)
}
}
public func removeBacking() {
removeBackingAction?.remove()
removeBackingAction = nil
backing = nil
}
var hasBacking : Bool {
return backing != nil
}
/// Send a new value to the stream.
private func send(result : Result<A>) {
self.lastResult = result
for listener in listeners {
listener.action?(result)
}
}
}
// MARK: Combining Streams
// This is different from an option, since you can't nest nils,
// so an A?? could resolve to nil and we wouldn't be able to detect that case
private enum Resolution<A> {
case Unresolved
case Resolved(Result<A>)
}
/// Combine a pair of streams into a stream of pairs.
/// The stream will both substreams have fired.
/// After the initial load, the stream will update whenever either of the substreams updates
public func joinStreams<T, U>(t : Stream<T>, u: Stream<U>) -> Stream<(T, U)> {
let sink = Sink<(T, U)>(dependencies: [t, u])
var tBox = MutableBox<Resolution<T>>(.Unresolved)
var uBox = MutableBox<Resolution<U>>(.Unresolved)
t.listen(sink.token) {[weak sink] tValue in
tBox.value = .Resolved(tValue)
switch uBox.value {
case let .Resolved(uValue):
sink?.send(join(tValue, uValue))
case .Unresolved:
break
}
}
u.listen(sink.token) {[weak sink] uValue in
uBox.value = .Resolved(uValue)
switch tBox.value {
case let .Resolved(tValue):
sink?.send(join(tValue, uValue))
case .Unresolved:
break
}
}
return sink
}
/// Combine an array of streams into a stream of arrays.
/// The stream will not fire until all substreams have fired.
/// After the initial load, the stream will update whenever any of the substreams updates.
public func joinStreams<T>(streams : [Stream<T>]) -> Stream<[T]> {
// This should be unnecesary since [Stream<T>] safely upcasts to [StreamDependency]
// but in practice it causes a runtime crash as of Swift 1.2.
// Explicitly mapping it prevents the crash
let dependencies = streams.map {x -> StreamDependency in x }
let sink = Sink<[T]>(dependencies : dependencies)
let pairs = streams.map {(stream : Stream<T>) -> (box : MutableBox<Resolution<T>>, stream : Stream<T>) in
let box = MutableBox<Resolution<T>>(.Unresolved)
return (box : box, stream : stream)
}
let boxes = pairs.map { return $0.box }
for (box, stream) in pairs {
stream.listen(sink.token) {[weak sink] value in
box.value = .Resolved(value)
let results = boxes.mapOrFailIfNil {(box : MutableBox<Resolution<T>>) -> Result<T>? in
switch box.value {
case .Unresolved: return nil
case let .Resolved(v): return v
}
}
if let r = results {
sink?.send(join(r))
}
}
}
if streams.count == 0 {
sink.send(Success([]))
}
return sink
}
| apache-2.0 | 713b974112859f8143d325a2d9f6234f | 35.00431 | 204 | 0.620795 | 4.58704 | false | false | false | false |
kevin-hirsch/DropDown | DropDown/src/DropDown.swift | 2 | 34753 | //
// DropDown.swift
// DropDown
//
// Created by Kevin Hirsch on 28/07/15.
// Copyright (c) 2015 Kevin Hirsch. All rights reserved.
//
#if os(iOS)
import UIKit
public typealias Index = Int
public typealias Closure = () -> Void
public typealias SelectionClosure = (Index, String) -> Void
public typealias MultiSelectionClosure = ([Index], [String]) -> Void
public typealias ConfigurationClosure = (Index, String) -> String
public typealias CellConfigurationClosure = (Index, String, DropDownCell) -> Void
private typealias ComputeLayoutTuple = (x: CGFloat, y: CGFloat, width: CGFloat, offscreenHeight: CGFloat)
/// Can be `UIView` or `UIBarButtonItem`.
@objc
public protocol AnchorView: class {
var plainView: UIView { get }
}
extension UIView: AnchorView {
public var plainView: UIView {
return self
}
}
extension UIBarButtonItem: AnchorView {
public var plainView: UIView {
return value(forKey: "view") as! UIView
}
}
/// A Material Design drop down in replacement for `UIPickerView`.
public final class DropDown: UIView {
//TODO: handle iOS 7 landscape mode
/// The dismiss mode for a drop down.
public enum DismissMode {
/// A tap outside the drop down is required to dismiss.
case onTap
/// No tap is required to dismiss, it will dimiss when interacting with anything else.
case automatic
/// Not dismissable by the user.
case manual
}
/// The direction where the drop down will show from the `anchorView`.
public enum Direction {
/// The drop down will show below the anchor view when possible, otherwise above if there is more place than below.
case any
/// The drop down will show above the anchor view or will not be showed if not enough space.
case top
/// The drop down will show below or will not be showed if not enough space.
case bottom
}
//MARK: - Properties
/// The current visible drop down. There can be only one visible drop down at a time.
public static weak var VisibleDropDown: DropDown?
//MARK: UI
fileprivate let dismissableView = UIView()
fileprivate let tableViewContainer = UIView()
fileprivate let tableView = UITableView()
fileprivate var templateCell: DropDownCell!
fileprivate lazy var arrowIndication: UIImageView = {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 20, height: 10), false, 0)
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 10))
path.addLine(to: CGPoint(x: 20, y: 10))
path.addLine(to: CGPoint(x: 10, y: 0))
path.addLine(to: CGPoint(x: 0, y: 10))
UIColor.black.setFill()
path.fill()
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let tintImg = img?.withRenderingMode(.alwaysTemplate)
let imgv = UIImageView(image: tintImg)
imgv.frame = CGRect(x: 0, y: -10, width: 15, height: 10)
return imgv
}()
/// The view to which the drop down will displayed onto.
public weak var anchorView: AnchorView? {
didSet { setNeedsUpdateConstraints() }
}
/**
The possible directions where the drop down will be showed.
See `Direction` enum for more info.
*/
public var direction = Direction.any
/**
The offset point relative to `anchorView` when the drop down is shown above the anchor view.
By default, the drop down is showed onto the `anchorView` with the top
left corner for its origin, so an offset equal to (0, 0).
You can change here the default drop down origin.
*/
public var topOffset: CGPoint = .zero {
didSet { setNeedsUpdateConstraints() }
}
/**
The offset point relative to `anchorView` when the drop down is shown below the anchor view.
By default, the drop down is showed onto the `anchorView` with the top
left corner for its origin, so an offset equal to (0, 0).
You can change here the default drop down origin.
*/
public var bottomOffset: CGPoint = .zero {
didSet { setNeedsUpdateConstraints() }
}
/**
The offset from the bottom of the window when the drop down is shown below the anchor view.
DropDown applies this offset only if keyboard is hidden.
*/
public var offsetFromWindowBottom = CGFloat(0) {
didSet { setNeedsUpdateConstraints() }
}
/**
The width of the drop down.
Defaults to `anchorView.bounds.width - offset.x`.
*/
public var width: CGFloat? {
didSet { setNeedsUpdateConstraints() }
}
/**
arrowIndication.x
arrowIndication will be add to tableViewContainer when configured
*/
public var arrowIndicationX: CGFloat? {
didSet {
if let arrowIndicationX = arrowIndicationX {
tableViewContainer.addSubview(arrowIndication)
arrowIndication.tintColor = tableViewBackgroundColor
arrowIndication.frame.origin.x = arrowIndicationX
} else {
arrowIndication.removeFromSuperview()
}
}
}
//MARK: Constraints
fileprivate var heightConstraint: NSLayoutConstraint!
fileprivate var widthConstraint: NSLayoutConstraint!
fileprivate var xConstraint: NSLayoutConstraint!
fileprivate var yConstraint: NSLayoutConstraint!
//MARK: Appearance
@objc public dynamic var cellHeight = DPDConstant.UI.RowHeight {
willSet { tableView.rowHeight = newValue }
didSet { reloadAllComponents() }
}
@objc fileprivate dynamic var tableViewBackgroundColor = DPDConstant.UI.BackgroundColor {
willSet {
tableView.backgroundColor = newValue
if arrowIndicationX != nil { arrowIndication.tintColor = newValue }
}
}
public override var backgroundColor: UIColor? {
get { return tableViewBackgroundColor }
set { tableViewBackgroundColor = newValue! }
}
/**
The color of the dimmed background (behind the drop down, covering the entire screen).
*/
public var dimmedBackgroundColor = UIColor.clear {
willSet { super.backgroundColor = newValue }
}
/**
The background color of the selected cell in the drop down.
Changing the background color automatically reloads the drop down.
*/
@objc public dynamic var selectionBackgroundColor = DPDConstant.UI.SelectionBackgroundColor
/**
The separator color between cells.
Changing the separator color automatically reloads the drop down.
*/
@objc public dynamic var separatorColor = DPDConstant.UI.SeparatorColor {
willSet { tableView.separatorColor = newValue }
didSet { reloadAllComponents() }
}
/**
The corner radius of DropDown.
Changing the corner radius automatically reloads the drop down.
*/
@objc public dynamic var cornerRadius = DPDConstant.UI.CornerRadius {
willSet {
tableViewContainer.layer.cornerRadius = newValue
tableView.layer.cornerRadius = newValue
}
didSet { reloadAllComponents() }
}
/**
Alias method for `cornerRadius` variable to avoid ambiguity.
*/
@objc public dynamic func setupCornerRadius(_ radius: CGFloat) {
tableViewContainer.layer.cornerRadius = radius
tableView.layer.cornerRadius = radius
reloadAllComponents()
}
/**
The masked corners of DropDown.
Changing the masked corners automatically reloads the drop down.
*/
@available(iOS 11.0, *)
@objc public dynamic func setupMaskedCorners(_ cornerMask: CACornerMask) {
tableViewContainer.layer.maskedCorners = cornerMask
tableView.layer.maskedCorners = cornerMask
reloadAllComponents()
}
/**
The color of the shadow.
Changing the shadow color automatically reloads the drop down.
*/
@objc public dynamic var shadowColor = DPDConstant.UI.Shadow.Color {
willSet { tableViewContainer.layer.shadowColor = newValue.cgColor }
didSet { reloadAllComponents() }
}
/**
The offset of the shadow.
Changing the shadow color automatically reloads the drop down.
*/
@objc public dynamic var shadowOffset = DPDConstant.UI.Shadow.Offset {
willSet { tableViewContainer.layer.shadowOffset = newValue }
didSet { reloadAllComponents() }
}
/**
The opacity of the shadow.
Changing the shadow opacity automatically reloads the drop down.
*/
@objc public dynamic var shadowOpacity = DPDConstant.UI.Shadow.Opacity {
willSet { tableViewContainer.layer.shadowOpacity = newValue }
didSet { reloadAllComponents() }
}
/**
The radius of the shadow.
Changing the shadow radius automatically reloads the drop down.
*/
@objc public dynamic var shadowRadius = DPDConstant.UI.Shadow.Radius {
willSet { tableViewContainer.layer.shadowRadius = newValue }
didSet { reloadAllComponents() }
}
/**
The duration of the show/hide animation.
*/
@objc public dynamic var animationduration = DPDConstant.Animation.Duration
/**
The option of the show animation. Global change.
*/
public static var animationEntranceOptions = DPDConstant.Animation.EntranceOptions
/**
The option of the hide animation. Global change.
*/
public static var animationExitOptions = DPDConstant.Animation.ExitOptions
/**
The option of the show animation. Only change the caller. To change all drop down's use the static var.
*/
public var animationEntranceOptions: UIView.AnimationOptions = DropDown.animationEntranceOptions
/**
The option of the hide animation. Only change the caller. To change all drop down's use the static var.
*/
public var animationExitOptions: UIView.AnimationOptions = DropDown.animationExitOptions
/**
The downScale transformation of the tableview when the DropDown is appearing
*/
public var downScaleTransform = DPDConstant.Animation.DownScaleTransform {
willSet { tableViewContainer.transform = newValue }
}
/**
The color of the text for each cells of the drop down.
Changing the text color automatically reloads the drop down.
*/
@objc public dynamic var textColor = DPDConstant.UI.TextColor {
didSet { reloadAllComponents() }
}
/**
The color of the text for selected cells of the drop down.
Changing the text color automatically reloads the drop down.
*/
@objc public dynamic var selectedTextColor = DPDConstant.UI.SelectedTextColor {
didSet { reloadAllComponents() }
}
/**
The font of the text for each cells of the drop down.
Changing the text font automatically reloads the drop down.
*/
@objc public dynamic var textFont = DPDConstant.UI.TextFont {
didSet { reloadAllComponents() }
}
/**
The NIB to use for DropDownCells
Changing the cell nib automatically reloads the drop down.
*/
public var cellNib = UINib(nibName: "DropDownCell", bundle: bundle) {
didSet {
tableView.register(cellNib, forCellReuseIdentifier: DPDConstant.ReusableIdentifier.DropDownCell)
templateCell = nil
reloadAllComponents()
}
}
/// Correctly specify Bundle for Swift Packages
fileprivate static var bundle: Bundle {
#if SWIFT_PACKAGE
return Bundle.module
#else
return Bundle(for: DropDownCell.self)
#endif
}
//MARK: Content
/**
The data source for the drop down.
Changing the data source automatically reloads the drop down.
*/
public var dataSource = [String]() {
didSet {
deselectRows(at: selectedRowIndices)
reloadAllComponents()
}
}
/**
The localization keys for the data source for the drop down.
Changing this value automatically reloads the drop down.
This has uses for setting accibility identifiers on the drop down cells (same ones as the localization keys).
*/
public var localizationKeysDataSource = [String]() {
didSet {
dataSource = localizationKeysDataSource.map { NSLocalizedString($0, comment: "") }
}
}
/// The indicies that have been selected
fileprivate var selectedRowIndices = Set<Index>()
/**
The format for the cells' text.
By default, the cell's text takes the plain `dataSource` value.
Changing `cellConfiguration` automatically reloads the drop down.
*/
public var cellConfiguration: ConfigurationClosure? {
didSet { reloadAllComponents() }
}
/**
A advanced formatter for the cells. Allows customization when custom cells are used
Changing `customCellConfiguration` automatically reloads the drop down.
*/
public var customCellConfiguration: CellConfigurationClosure? {
didSet { reloadAllComponents() }
}
/// The action to execute when the user selects a cell.
public var selectionAction: SelectionClosure?
/**
The action to execute when the user selects multiple cells.
Providing an action will turn on multiselection mode.
The single selection action will still be called if provided.
*/
public var multiSelectionAction: MultiSelectionClosure?
/// The action to execute when the drop down will show.
public var willShowAction: Closure?
/// The action to execute when the user cancels/hides the drop down.
public var cancelAction: Closure?
/// The dismiss mode of the drop down. Default is `OnTap`.
public var dismissMode = DismissMode.onTap {
willSet {
if newValue == .onTap {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissableViewTapped))
dismissableView.addGestureRecognizer(gestureRecognizer)
} else if let gestureRecognizer = dismissableView.gestureRecognizers?.first {
dismissableView.removeGestureRecognizer(gestureRecognizer)
}
}
}
fileprivate var minHeight: CGFloat {
return tableView.rowHeight
}
fileprivate var didSetupConstraints = false
//MARK: - Init's
deinit {
stopListeningToNotifications()
}
/**
Creates a new instance of a drop down.
Don't forget to setup the `dataSource`,
the `anchorView` and the `selectionAction`
at least before calling `show()`.
*/
public convenience init() {
self.init(frame: .zero)
}
/**
Creates a new instance of a drop down.
- parameter anchorView: The view to which the drop down will displayed onto.
- parameter selectionAction: The action to execute when the user selects a cell.
- parameter dataSource: The data source for the drop down.
- parameter topOffset: The offset point relative to `anchorView` used when drop down is displayed on above the anchor view.
- parameter bottomOffset: The offset point relative to `anchorView` used when drop down is displayed on below the anchor view.
- parameter cellConfiguration: The format for the cells' text.
- parameter cancelAction: The action to execute when the user cancels/hides the drop down.
- returns: A new instance of a drop down customized with the above parameters.
*/
public convenience init(anchorView: AnchorView, selectionAction: SelectionClosure? = nil, dataSource: [String] = [], topOffset: CGPoint? = nil, bottomOffset: CGPoint? = nil, cellConfiguration: ConfigurationClosure? = nil, cancelAction: Closure? = nil) {
self.init(frame: .zero)
self.anchorView = anchorView
self.selectionAction = selectionAction
self.dataSource = dataSource
self.topOffset = topOffset ?? .zero
self.bottomOffset = bottomOffset ?? .zero
self.cellConfiguration = cellConfiguration
self.cancelAction = cancelAction
}
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
}
//MARK: - Setup
private extension DropDown {
func setup() {
tableView.register(cellNib, forCellReuseIdentifier: DPDConstant.ReusableIdentifier.DropDownCell)
DispatchQueue.main.async {
//HACK: If not done in dispatch_async on main queue `setupUI` will have no effect
self.updateConstraintsIfNeeded()
self.setupUI()
}
tableView.rowHeight = cellHeight
setHiddentState()
isHidden = true
dismissMode = .onTap
tableView.delegate = self
tableView.dataSource = self
startListeningToKeyboard()
accessibilityIdentifier = "drop_down"
}
func setupUI() {
super.backgroundColor = dimmedBackgroundColor
tableViewContainer.layer.masksToBounds = false
tableViewContainer.layer.cornerRadius = cornerRadius
tableViewContainer.layer.shadowColor = shadowColor.cgColor
tableViewContainer.layer.shadowOffset = shadowOffset
tableViewContainer.layer.shadowOpacity = shadowOpacity
tableViewContainer.layer.shadowRadius = shadowRadius
tableView.backgroundColor = tableViewBackgroundColor
tableView.separatorColor = separatorColor
tableView.layer.cornerRadius = cornerRadius
tableView.layer.masksToBounds = true
}
}
//MARK: - UI
extension DropDown {
public override func updateConstraints() {
if !didSetupConstraints {
setupConstraints()
}
didSetupConstraints = true
let layout = computeLayout()
if !layout.canBeDisplayed {
super.updateConstraints()
hide()
return
}
xConstraint.constant = layout.x
yConstraint.constant = layout.y
widthConstraint.constant = layout.width
heightConstraint.constant = layout.visibleHeight
tableView.isScrollEnabled = layout.offscreenHeight > 0
DispatchQueue.main.async { [weak self] in
self?.tableView.flashScrollIndicators()
}
super.updateConstraints()
}
fileprivate func setupConstraints() {
translatesAutoresizingMaskIntoConstraints = false
// Dismissable view
addSubview(dismissableView)
dismissableView.translatesAutoresizingMaskIntoConstraints = false
addUniversalConstraints(format: "|[dismissableView]|", views: ["dismissableView": dismissableView])
// Table view container
addSubview(tableViewContainer)
tableViewContainer.translatesAutoresizingMaskIntoConstraints = false
xConstraint = NSLayoutConstraint(
item: tableViewContainer,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1,
constant: 0)
addConstraint(xConstraint)
yConstraint = NSLayoutConstraint(
item: tableViewContainer,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1,
constant: 0)
addConstraint(yConstraint)
widthConstraint = NSLayoutConstraint(
item: tableViewContainer,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 0)
tableViewContainer.addConstraint(widthConstraint)
heightConstraint = NSLayoutConstraint(
item: tableViewContainer,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 0)
tableViewContainer.addConstraint(heightConstraint)
// Table view
tableViewContainer.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableViewContainer.addUniversalConstraints(format: "|[tableView]|", views: ["tableView": tableView])
}
public override func layoutSubviews() {
super.layoutSubviews()
// When orientation changes, layoutSubviews is called
// We update the constraint to update the position
setNeedsUpdateConstraints()
let shadowPath = UIBezierPath(roundedRect: tableViewContainer.bounds, cornerRadius: cornerRadius)
tableViewContainer.layer.shadowPath = shadowPath.cgPath
}
fileprivate func computeLayout() -> (x: CGFloat, y: CGFloat, width: CGFloat, offscreenHeight: CGFloat, visibleHeight: CGFloat, canBeDisplayed: Bool, Direction: Direction) {
var layout: ComputeLayoutTuple = (0, 0, 0, 0)
var direction = self.direction
guard let window = UIWindow.visibleWindow() else { return (0, 0, 0, 0, 0, false, direction) }
barButtonItemCondition: if let anchorView = anchorView as? UIBarButtonItem {
let isRightBarButtonItem = anchorView.plainView.frame.minX > window.frame.midX
guard isRightBarButtonItem else { break barButtonItemCondition }
let width = self.width ?? fittingWidth()
let anchorViewWidth = anchorView.plainView.frame.width
let x = -(width - anchorViewWidth)
bottomOffset = CGPoint(x: x, y: 0)
}
if anchorView == nil {
layout = computeLayoutBottomDisplay(window: window)
direction = .any
} else {
switch direction {
case .any:
layout = computeLayoutBottomDisplay(window: window)
direction = .bottom
if layout.offscreenHeight > 0 {
let topLayout = computeLayoutForTopDisplay(window: window)
if topLayout.offscreenHeight < layout.offscreenHeight {
layout = topLayout
direction = .top
}
}
case .bottom:
layout = computeLayoutBottomDisplay(window: window)
direction = .bottom
case .top:
layout = computeLayoutForTopDisplay(window: window)
direction = .top
}
}
constraintWidthToFittingSizeIfNecessary(layout: &layout)
constraintWidthToBoundsIfNecessary(layout: &layout, in: window)
let visibleHeight = tableHeight - layout.offscreenHeight
let canBeDisplayed = visibleHeight >= minHeight
return (layout.x, layout.y, layout.width, layout.offscreenHeight, visibleHeight, canBeDisplayed, direction)
}
fileprivate func computeLayoutBottomDisplay(window: UIWindow) -> ComputeLayoutTuple {
var offscreenHeight: CGFloat = 0
let width = self.width ?? (anchorView?.plainView.bounds.width ?? fittingWidth()) - bottomOffset.x
let anchorViewX = anchorView?.plainView.windowFrame?.minX ?? window.frame.midX - (width / 2)
let anchorViewY = anchorView?.plainView.windowFrame?.minY ?? window.frame.midY - (tableHeight / 2)
let x = anchorViewX + bottomOffset.x
let y = anchorViewY + bottomOffset.y
let maxY = y + tableHeight
let windowMaxY = window.bounds.maxY - DPDConstant.UI.HeightPadding - offsetFromWindowBottom
let keyboardListener = KeyboardListener.sharedInstance
let keyboardMinY = keyboardListener.keyboardFrame.minY - DPDConstant.UI.HeightPadding
if keyboardListener.isVisible && maxY > keyboardMinY {
offscreenHeight = abs(maxY - keyboardMinY)
} else if maxY > windowMaxY {
offscreenHeight = abs(maxY - windowMaxY)
}
return (x, y, width, offscreenHeight)
}
fileprivate func computeLayoutForTopDisplay(window: UIWindow) -> ComputeLayoutTuple {
var offscreenHeight: CGFloat = 0
let anchorViewX = anchorView?.plainView.windowFrame?.minX ?? 0
let anchorViewMaxY = anchorView?.plainView.windowFrame?.maxY ?? 0
let x = anchorViewX + topOffset.x
var y = (anchorViewMaxY + topOffset.y) - tableHeight
let windowY = window.bounds.minY + DPDConstant.UI.HeightPadding
if y < windowY {
offscreenHeight = abs(y - windowY)
y = windowY
}
let width = self.width ?? (anchorView?.plainView.bounds.width ?? fittingWidth()) - topOffset.x
return (x, y, width, offscreenHeight)
}
fileprivate func fittingWidth() -> CGFloat {
if templateCell == nil {
templateCell = (cellNib.instantiate(withOwner: nil, options: nil)[0] as! DropDownCell)
}
var maxWidth: CGFloat = 0
for index in 0..<dataSource.count {
configureCell(templateCell, at: index)
templateCell.bounds.size.height = cellHeight
let width = templateCell.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).width
if width > maxWidth {
maxWidth = width
}
}
return maxWidth
}
fileprivate func constraintWidthToBoundsIfNecessary(layout: inout ComputeLayoutTuple, in window: UIWindow) {
let windowMaxX = window.bounds.maxX
let maxX = layout.x + layout.width
if maxX > windowMaxX {
let delta = maxX - windowMaxX
let newOrigin = layout.x - delta
if newOrigin > 0 {
layout.x = newOrigin
} else {
layout.x = 0
layout.width += newOrigin // newOrigin is negative, so this operation is a substraction
}
}
}
fileprivate func constraintWidthToFittingSizeIfNecessary(layout: inout ComputeLayoutTuple) {
guard width == nil else { return }
if layout.width < fittingWidth() {
layout.width = fittingWidth()
}
}
}
//MARK: - Actions
extension DropDown {
/**
An Objective-C alias for the show() method which converts the returned tuple into an NSDictionary.
- returns: An NSDictionary with a value for the "canBeDisplayed" Bool, and possibly for the "offScreenHeight" Optional(CGFloat).
*/
@objc(show)
public func objc_show() -> NSDictionary {
let (canBeDisplayed, offScreenHeight) = show()
var info = [AnyHashable: Any]()
info["canBeDisplayed"] = canBeDisplayed
if let offScreenHeight = offScreenHeight {
info["offScreenHeight"] = offScreenHeight
}
return NSDictionary(dictionary: info)
}
/**
Shows the drop down if enough height.
- returns: Wether it succeed and how much height is needed to display all cells at once.
*/
@discardableResult
public func show(onTopOf window: UIWindow? = nil, beforeTransform transform: CGAffineTransform? = nil, anchorPoint: CGPoint? = nil) -> (canBeDisplayed: Bool, offscreenHeight: CGFloat?) {
if self == DropDown.VisibleDropDown && DropDown.VisibleDropDown?.isHidden == false { // added condition - DropDown.VisibleDropDown?.isHidden == false -> to resolve forever hiding dropdown issue when continuous taping on button - Kartik Patel - 2016-12-29
return (true, 0)
}
if let visibleDropDown = DropDown.VisibleDropDown {
visibleDropDown.cancel()
}
willShowAction?()
DropDown.VisibleDropDown = self
setNeedsUpdateConstraints()
let visibleWindow = window != nil ? window : UIWindow.visibleWindow()
visibleWindow?.addSubview(self)
visibleWindow?.bringSubviewToFront(self)
self.translatesAutoresizingMaskIntoConstraints = false
visibleWindow?.addUniversalConstraints(format: "|[dropDown]|", views: ["dropDown": self])
let layout = computeLayout()
if !layout.canBeDisplayed {
hide()
return (layout.canBeDisplayed, layout.offscreenHeight)
}
isHidden = false
if anchorPoint != nil {
tableViewContainer.layer.anchorPoint = anchorPoint!
}
if transform != nil {
tableViewContainer.transform = transform!
} else {
tableViewContainer.transform = downScaleTransform
}
layoutIfNeeded()
UIView.animate(
withDuration: animationduration,
delay: 0,
options: animationEntranceOptions,
animations: { [weak self] in
self?.setShowedState()
},
completion: nil)
accessibilityViewIsModal = true
UIAccessibility.post(notification: .screenChanged, argument: self)
//deselectRows(at: selectedRowIndices)
selectRows(at: selectedRowIndices)
return (layout.canBeDisplayed, layout.offscreenHeight)
}
public override func accessibilityPerformEscape() -> Bool {
switch dismissMode {
case .automatic, .onTap:
cancel()
return true
case .manual:
return false
}
}
/// Hides the drop down.
public func hide() {
if self == DropDown.VisibleDropDown {
/*
If one drop down is showed and another one is not
but we call `hide()` on the hidden one:
we don't want it to set the `VisibleDropDown` to nil.
*/
DropDown.VisibleDropDown = nil
}
if isHidden {
return
}
UIView.animate(
withDuration: animationduration,
delay: 0,
options: animationExitOptions,
animations: { [weak self] in
self?.setHiddentState()
},
completion: { [weak self] finished in
guard let `self` = self else { return }
self.isHidden = true
self.removeFromSuperview()
UIAccessibility.post(notification: .screenChanged, argument: nil)
})
}
fileprivate func cancel() {
hide()
cancelAction?()
}
fileprivate func setHiddentState() {
alpha = 0
}
fileprivate func setShowedState() {
alpha = 1
tableViewContainer.transform = CGAffineTransform.identity
}
}
//MARK: - UITableView
extension DropDown {
/**
Reloads all the cells.
It should not be necessary in most cases because each change to
`dataSource`, `textColor`, `textFont`, `selectionBackgroundColor`
and `cellConfiguration` implicitly calls `reloadAllComponents()`.
*/
public func reloadAllComponents() {
DispatchQueue.executeOnMainThread {
self.tableView.reloadData()
self.setNeedsUpdateConstraints()
}
}
/// (Pre)selects a row at a certain index.
public func selectRow(at index: Index?, scrollPosition: UITableView.ScrollPosition = .none) {
if let index = index {
tableView.selectRow(
at: IndexPath(row: index, section: 0), animated: true, scrollPosition: scrollPosition
)
selectedRowIndices.insert(index)
} else {
deselectRows(at: selectedRowIndices)
selectedRowIndices.removeAll()
}
}
public func selectRows(at indices: Set<Index>?) {
indices?.forEach {
selectRow(at: $0)
}
// if we are in multi selection mode then reload data so that all selections are shown
if multiSelectionAction != nil {
tableView.reloadData()
}
}
public func deselectRow(at index: Index?) {
guard let index = index
, index >= 0
else { return }
// remove from indices
if let selectedRowIndex = selectedRowIndices.firstIndex(where: { $0 == index }) {
selectedRowIndices.remove(at: selectedRowIndex)
}
tableView.deselectRow(at: IndexPath(row: index, section: 0), animated: true)
}
// de-selects the rows at the indices provided
public func deselectRows(at indices: Set<Index>?) {
indices?.forEach {
deselectRow(at: $0)
}
}
/// Returns the index of the selected row.
public var indexForSelectedRow: Index? {
return (tableView.indexPathForSelectedRow as NSIndexPath?)?.row
}
/// Returns the selected item.
public var selectedItem: String? {
guard let row = (tableView.indexPathForSelectedRow as NSIndexPath?)?.row else { return nil }
return dataSource[row]
}
/// Returns the height needed to display all cells.
fileprivate var tableHeight: CGFloat {
return tableView.rowHeight * CGFloat(dataSource.count)
}
//MARK: Objective-C methods for converting the Swift type Index
@objc public func selectRow(_ index: Int, scrollPosition: UITableView.ScrollPosition = .none) {
self.selectRow(at:Index(index), scrollPosition: scrollPosition)
}
@objc public func clearSelection() {
self.selectRow(at:nil)
}
@objc public func deselectRow(_ index: Int) {
tableView.deselectRow(at: IndexPath(row: Index(index), section: 0), animated: true)
}
@objc public var indexPathForSelectedRow: NSIndexPath? {
return tableView.indexPathForSelectedRow as NSIndexPath?
}
}
//MARK: - UITableViewDataSource - UITableViewDelegate
extension DropDown: UITableViewDataSource, UITableViewDelegate {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: DPDConstant.ReusableIdentifier.DropDownCell, for: indexPath) as! DropDownCell
let index = (indexPath as NSIndexPath).row
configureCell(cell, at: index)
return cell
}
fileprivate func configureCell(_ cell: DropDownCell, at index: Int) {
if index >= 0 && index < localizationKeysDataSource.count {
cell.accessibilityIdentifier = localizationKeysDataSource[index]
}
cell.optionLabel.textColor = textColor
cell.optionLabel.font = textFont
cell.selectedBackgroundColor = selectionBackgroundColor
cell.highlightTextColor = selectedTextColor
cell.normalTextColor = textColor
if let cellConfiguration = cellConfiguration {
cell.optionLabel.text = cellConfiguration(index, dataSource[index])
} else {
cell.optionLabel.text = dataSource[index]
}
customCellConfiguration?(index, dataSource[index], cell)
}
public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.isSelected = selectedRowIndices.first{ $0 == (indexPath as NSIndexPath).row } != nil
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedRowIndex = (indexPath as NSIndexPath).row
// are we in multi-selection mode?
if let multiSelectionCallback = multiSelectionAction {
// if already selected then deselect
if selectedRowIndices.first(where: { $0 == selectedRowIndex}) != nil {
deselectRow(at: selectedRowIndex)
let selectedRowIndicesArray = Array(selectedRowIndices)
let selectedRows = selectedRowIndicesArray.map { dataSource[$0] }
multiSelectionCallback(selectedRowIndicesArray, selectedRows)
return
}
else {
selectedRowIndices.insert(selectedRowIndex)
let selectedRowIndicesArray = Array(selectedRowIndices)
let selectedRows = selectedRowIndicesArray.map { dataSource[$0] }
selectionAction?(selectedRowIndex, dataSource[selectedRowIndex])
multiSelectionCallback(selectedRowIndicesArray, selectedRows)
tableView.reloadData()
return
}
}
// Perform single selection logic
selectedRowIndices.removeAll()
selectedRowIndices.insert(selectedRowIndex)
selectionAction?(selectedRowIndex, dataSource[selectedRowIndex])
if let _ = anchorView as? UIBarButtonItem {
// DropDown's from UIBarButtonItem are menus so we deselect the selected menu right after selection
deselectRow(at: selectedRowIndex)
}
hide()
}
}
//MARK: - Auto dismiss
extension DropDown {
public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let view = super.hitTest(point, with: event)
if dismissMode == .automatic && view === dismissableView {
cancel()
return nil
} else {
return view
}
}
@objc
fileprivate func dismissableViewTapped() {
cancel()
}
}
//MARK: - Keyboard events
extension DropDown {
/**
Starts listening to keyboard events.
Allows the drop down to display correctly when keyboard is showed.
*/
@objc public static func startListeningToKeyboard() {
KeyboardListener.sharedInstance.startListeningToKeyboard()
}
fileprivate func startListeningToKeyboard() {
KeyboardListener.sharedInstance.startListeningToKeyboard()
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardUpdate),
name: UIResponder.keyboardWillShowNotification,
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardUpdate),
name: UIResponder.keyboardWillHideNotification,
object: nil)
}
fileprivate func stopListeningToNotifications() {
NotificationCenter.default.removeObserver(self)
}
@objc
fileprivate func keyboardUpdate() {
self.setNeedsUpdateConstraints()
}
}
private extension DispatchQueue {
static func executeOnMainThread(_ closure: @escaping Closure) {
if Thread.isMainThread {
closure()
} else {
main.async(execute: closure)
}
}
}
#endif
| mit | 7455963462da10c8c0e5c3068da70e94 | 27.745244 | 256 | 0.718039 | 4.406924 | false | false | false | false |
GrafixMafia/SpaceStateBar | spacestate info/StatusHandler.swift | 1 | 2502 | //
// StatusHandler.swift
// MainFrameStatusBar
//
// Created by markus on 05.08.14.
// Copyright (c) 2014 grafixmafia.net. All rights reserved.
//
import Foundation
public class StatusHandler {
init() {
}
public var stateDetails: NSDictionary?
public var status: NSString? {
get {
return self.getStatus()
}
}
func getStatus() -> NSString {
var freshStatus: NSString = ""
let urlPath: String = "http://status.kreativitaet-trifft-technik.de/api/openState"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)
var response: NSURLResponse?
var error: NSError?
var dataVal: NSData?
dataVal = NSURLConnection.sendSynchronousRequest(request1, returningResponse: &response, error: &error)
if let myError = error {
freshStatus = "X"
} else {
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
if(jsonResult.valueForKey("state") as! NSString == "off") {
freshStatus = "C"
} else {
freshStatus = "O"
}
}
return freshStatus
}
func getDetails(urlToSpace : NSString) {
var freshDetails : NSDictionary = NSDictionary()
// var urlPathToSpace: String = "http://status.mainframe.io/api/spaceInfo"
var url: NSURL = NSURL(string: urlToSpace as String)!
var request1: NSURLRequest = NSURLRequest(URL: url)
let queue:NSOperationQueue = NSOperationQueue()
var stateDetails : NSDictionary = NSDictionary()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError?
if let myerror : NSError = error {
self.stateDetails = NSDictionary()
} else {
self.stateDetails = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary
println("Status")
// println(freshDetails)
}
})
}
} | mit | e80a86b967c5bfed9aa17e5569544040 | 31.089744 | 169 | 0.577938 | 5.064777 | false | false | false | false |
thiagolioy/Notes | Sources/DiatonicHarmony.swift | 1 | 1721 | //
// DiatonicHarmony.swift
// Notes
//
// Created by Thiago Lioy on 26/08/17.
// Copyright © 2017 com.tplioy. All rights reserved.
//
import Foundation
public enum DiatonicHarmony {
case major
case minor
func chords(inKey key: Note) -> [Chord] {
switch self {
case .major:
let mode = IonianMode(key: key)
let notes = mode.scaleNotes()
let chordTypes: [Chord.Type] = [
MajorSeventhChord.self,
MinorSeventhChord.self,
MinorSeventhChord.self,
MajorSeventhChord.self,
DominantSeventhChord.self,
MinorSeventhChord.self,
HalfDiminishedSeventhChord.self
]
return chords(from: notes, with: chordTypes)
case .minor:
let mode = AeolianMode(key: key)
let notes = mode.scaleNotes()
let chordTypes: [Chord.Type] = [
MinorSeventhChord.self,
HalfDiminishedSeventhChord.self,
MajorSeventhChord.self,
MinorSeventhChord.self,
MinorSeventhChord.self,
MajorSeventhChord.self,
MajorSeventhChord.self
]
return chords(from: notes, with: chordTypes)
}
}
private func chords(from notes: [Note], with types: [Chord.Type]) -> [Chord] {
var chords: [Chord] = []
for (index, chordType) in types.enumerated() {
let note = notes[index]
let chord: Chord = chordType.init(key: note)
chords.append(chord)
}
return chords
}
}
| mit | 069d5fac4b58b63dcab5c3ffe877b169 | 28.152542 | 82 | 0.526163 | 4.725275 | false | false | false | false |
keithbhunter/KBHDatePicker | KBHDatePicker/KBHDate.swift | 2 | 2552 | //
// KBHDate.swift
// KBHDatePicker
//
// Created by Keith Hunter on 6/15/15.
// Copyright © 2015 Keith Hunter. All rights reserved.
//
import Foundation
public let KBHDaysInAWeek = 7
extension NSDate {
public var isWeekend: Bool { return self.oneLetterWeekday.uppercaseString == "S" }
public var oneLetterWeekday: String { return self.weekdayWithNumberOfChars(1) }
public var threeLetterWeekday: String { return self.weekdayWithNumberOfChars(3) }
public var month: String {
let formatter = NSDateFormatter()
formatter.dateFormat = "MM"
let monthNumber = formatter.stringFromDate(self) as NSString
let months = formatter.standaloneMonthSymbols
return months[monthNumber.intValue - 1]
}
public var day: Int {
let formatter = NSDateFormatter()
formatter.dateFormat = "dd"
let dayNumber = formatter.stringFromDate(self) as NSString
return dayNumber.integerValue
}
// MARK: - Class Methods
public class func dateWithOffset(offsetInDays: Int, fromDate date: NSDate) -> NSDate {
return date.dateByAddingTimeInterval(NSTimeInterval(offsetInDays * 24 * 60 * 60))
}
// MARK: - Instance Methods
public func weekdayWithNumberOfChars(numOfChars: Int) -> String {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .WeekOfMonth, .Weekday], fromDate: self)
let dayNumber = components.weekday
let formatter = NSDateFormatter()
let weekdays = formatter.standaloneWeekdaySymbols
let weekday = weekdays[dayNumber - 1]
return weekday.substringToIndex(advance(weekday.startIndex, numOfChars))
}
public func withoutTime() -> NSDate {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day], fromDate: self)
components.hour = 1
components.minute = 0
components.second = 0
components.nanosecond = 0
return calendar.dateFromComponents(components)!
}
public func earlierSunday() -> NSDate {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .WeekOfMonth, .Weekday], fromDate: self)
let weekday = components.weekday
let daysToSunday = -((weekday - 1) % 7)
return self.dateByAddingTimeInterval(NSTimeInterval(daysToSunday * 60 * 60 * 24))
}
}
| mit | 81dac1397f3a72fc34af3e4dd59ed3bb | 33.013333 | 101 | 0.657389 | 4.886973 | false | false | false | false |
zaneswafford/ProjectEulerSwift | ProjectEuler/Problem19.swift | 1 | 920 | //
// Problem19.swift
// ProjectEuler
//
// Created by Zane Swafford on 7/17/15.
// Copyright (c) 2015 Zane Swafford. All rights reserved.
//
import Foundation
func problem19() -> Int {
var numberOfSundays = 0
var calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
for year in (1901...2000) {
for month in (1...12) {
var firstDayComponents = NSDateComponents()
firstDayComponents.day = 1
firstDayComponents.month = month
firstDayComponents.year = year
var date = calendar.dateFromComponents(firstDayComponents)!
var weekdayComponents = calendar.components(.CalendarUnitWeekday, fromDate:date)
if weekdayComponents.weekday == 1 {
numberOfSundays++
}
}
}
return numberOfSundays
} | bsd-2-clause | 7fb70e738ca96f801cce7c25609066c1 | 25.314286 | 92 | 0.58913 | 5.139665 | false | false | false | false |
yonadev/yona-app-ios | Yona/Yona/MeDashBoard/MeDayDetailViewController.swift | 1 | 23899 |
//
// MeDetailDayViewController.swift
// Yona
//
// Created by Ben Smith on 20/07/16.
// Copyright © 2016 Yona. All rights reserved.
//
import Foundation
import IQKeyboardManagerSwift
enum detailDayRows : Int {
case activity = 0
case spreadCell
case linkCell
}
enum detailDayCommentRows : Int {
case comment = 0
case sendComment
}
enum detailDaySections : Int {
case activity = 0
case comment
}
class MeDayDetailViewController: UIViewController, YonaButtonsTableHeaderViewProtocol {
@IBOutlet weak var tableView : UITableView!
@IBOutlet weak var sendCommentFooter : SendCommentControl?
var correctToday = Date()
var singleDayData : [String: DaySingleActivityDetail] = [:]
var dayData : DaySingleActivityDetail?
var activityGoal : ActivitiesGoal?
var initialObjectLink : String?
var goalName : String?
var goalType : String?
var currentDate : Date = Date()
var currentDay : String?
var nextLink : String?
var prevLink : String?
var hideReplyButton : Bool = false
var moveToBottomRequired : Bool = false
var previousThreadID : String = ""
var page : Int = 1
var size : Int = 4
var animatedCells : [String] = []
var navbarColor1 : UIColor?
var navbarColor : UIColor?
var violationStartTime : Date?
var violationEndTime : Date?
var violationLinkURL : String?
//paging
var totalSize: Int = 0
var totalPages : Int = 0
var comments = [Comment]() {
didSet{
//everytime savedarticles is added to or deleted from table is refreshed
DispatchQueue.main.async {
self.previousThreadID = ""
self.tableView.reloadData()
if self.comments.count > 0 && self.moveToBottomRequired {
self.tableView.scrollToRow(at: IndexPath(row: self.comments.count - 1, section: 1), at: UITableView.ScrollPosition.bottom, animated: false)
}
}
}
}
// MARK: - view life cycle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = goalName?.uppercased()
self.comments = []
if let activityGoal = activityGoal {
initialObjectLink = activityGoal.dayDetailLinks
currentDate = activityGoal.date as Date
goalName = activityGoal.goalName
goalType = activityGoal.goalType
}
registreTableViewCells()
self.sendCommentFooter?.commentControlDelegate = self
self.sendCommentFooter?.alpha = 0
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let tracker = GAI.sharedInstance().defaultTracker
tracker?.set(kGAIScreenName, value: "MeDayDetailViewController")
let builder = GAIDictionaryBuilder.createScreenView()
tracker?.send(builder?.build() as? [AnyHashable: Any])
correctToday = Date().addingTimeInterval(60*60*24)
self.loadData(.own)
}
//MARK: - button action
@IBAction func backAction(_ sender : AnyObject) {
DispatchQueue.main.async(execute: {
weak var tracker = GAI.sharedInstance().defaultTracker
tracker!.send(GAIDictionaryBuilder.createEvent(withCategory: "ui_action", action: "backAction", label: "MeDayDetailViewController", value: nil).build() as? [AnyHashable: Any])
self.navigationController?.popViewController(animated: true)
})
}
fileprivate func shouldAnimate(_ cell : IndexPath) -> Bool {
let txt = "\(cell.section)-\(cell.row)"
if animatedCells.index(of: txt) == nil {
print("Animated \(txt)")
animatedCells.append(txt)
return true
}
print("NO animated \(txt)")
return false
}
func registreTableViewCells () {
var nib = UINib(nibName: "SpreadCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "SpreadCell")
nib = UINib(nibName: "TimeBucketControlCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "TimeBucketControlCell")
nib = UINib(nibName: "NoGoCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "NoGoCell")
nib = UINib(nibName: "TimeZoneControlCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "TimeZoneControlCell")
nib = UINib(nibName: "YonaButtonsTableHeaderView", bundle: nil)
tableView.register(nib, forHeaderFooterViewReuseIdentifier: "YonaButtonsTableHeaderView")
nib = UINib(nibName: "CommentTableHeader", bundle: nil)
tableView.register(nib, forHeaderFooterViewReuseIdentifier: "CommentTableHeader")
nib = UINib(nibName: "CommentControlCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "CommentControlCell")
nib = UINib(nibName: "ReplyToComment", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "ReplyToComment")
nib = UINib(nibName: "DayViewLinkCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "DayViewLinkCell")
}
//MARK: Protocol implementation
func leftButtonPushed(){
self.comments = []
loadData(.prev)
}
func rightButtonPushed() {
self.comments = []
loadData(.next)
}
//MARK: - load data
func loadData (_ typeToLoad : loadType = .own) {
Loader.Show()
if typeToLoad == .own {
loadOwnData()
}
else if typeToLoad == .prev {
loadPreviousData()
}
else if typeToLoad == .next {
loadNextData()
}
Loader.Hide()
self.tableView.reloadData()
}
fileprivate func loadOwnData() {
if let path = initialObjectLink {
ActivitiesRequestManager.sharedInstance.getDayActivityDetails(path, date: currentDate , onCompletion: { (success, serverMessage, serverCode, dayActivity, err) in
if success {
if let data = dayActivity {
self.currentDate = data.date!
self.currentDay = data.dayOfWeek
self.dayData = data
self.goalType = data.goalType
self.navigationItem.title = data.goalName?.uppercased() //only need to do this in the first original data
if let commentsLink = data.messageLink {
self.getComments(commentsLink)
}
//make sure the commentview has the right link to post comments to
if self.dayData?.commentLink != nil {
self.sendCommentFooter!.alpha = self.dayData?.commentLink != nil ? 1 : 0
self.sendCommentFooter!.postCommentLink = self.dayData?.commentLink
}
}
if let _ = self.dayData?.goalType {
self.tableView.reloadData()
} else {
self.noGoalTypeInResponse()
}
}
})
}
}
fileprivate func loadPreviousData() {
if let path = dayData!.prevLink {
ActivitiesRequestManager.sharedInstance.getDayActivityDetails(path, date: currentDate, onCompletion: { (success, serverMessage, serverCode, dayActivity, err) in
if success {
if let data = dayActivity {
self.currentDate = data.date!
self.currentDay = data.dayOfWeek
self.dayData = data
if let commentsLink = data.messageLink {
self.getComments(commentsLink)
}
//make sure the commentview has the right link to post comments to
if self.dayData?.commentLink != nil {
self.sendCommentFooter!.alpha = self.dayData?.commentLink != nil ? 1 : 0
self.sendCommentFooter!.postCommentLink = self.dayData?.commentLink
}
}
self.tableView.reloadData()
}
})
}
}
fileprivate func loadNextData() {
if let path = dayData!.nextLink {
ActivitiesRequestManager.sharedInstance.getDayActivityDetails(path, date: currentDate, onCompletion: { (success, serverMessage, serverCode, dayActivity, err) in
if success {
if let data = dayActivity {
self.currentDate = data.date!
self.currentDay = data.dayOfWeek
self.dayData = data
if let commentsLink = data.messageLink {
self.getComments(commentsLink)
}
//make sure the commentview has the right link to post comments to
if self.dayData?.commentLink != nil {
self.sendCommentFooter!.alpha = self.dayData?.commentLink != nil ? 1 : 0
self.sendCommentFooter!.postCommentLink = self.dayData?.commentLink
}
}
self.tableView.reloadData()
}
})
}
}
func noGoalTypeInResponse() {
let alert = UIAlertController(title: NSLocalizedString("nogo-data-not-found-title", comment: ""),
message: NSLocalizedString("nogo-data-not-found-description", comment: ""),
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("dashboard.error.button", comment: ""), style: .default, handler: { action in
switch action.style {
case .default:
self.navigationController?.popViewController(animated: true)
default:
break
}
}))
self.present(alert, animated: true, completion: nil)
}
// MARK: - UITableviewDelegate Methods
func numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if dayData == nil {
return 0
}
var numberOfRows = 2
if violationLinkURL != nil {
numberOfRows = 3
}
if section == 1 {
numberOfRows = self.comments.count // number of comments
} else if section == 2 {
numberOfRows = 1
}
return numberOfRows
}
func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: IndexPath) -> CGFloat {
var cellHeight = 165
if indexPath.section == detailDaySections.activity.rawValue && indexPath.row == detailDayRows.activity.rawValue {
if indexPath.row == detailDayRows.activity.rawValue {
if goalType == GoalType.BudgetGoalString.rawValue {
cellHeight = 135
} else if goalType == GoalType.NoGoGoalString.rawValue {
cellHeight = 85
} else if goalType == GoalType.TimeZoneGoalString.rawValue {
cellHeight = 135
}
}
if indexPath.row == detailDayRows.spreadCell.rawValue{
cellHeight = 165
}
} else if indexPath.section == detailDaySections.comment.rawValue {
return UITableView.automaticDimension
}
return CGFloat(cellHeight)
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: IndexPath) -> CGFloat {
var cellHeight = 165
if indexPath.section == detailDaySections.activity.rawValue && indexPath.row == detailDayRows.activity.rawValue {
if indexPath.row == detailDayRows.activity.rawValue {
if goalType == GoalType.BudgetGoalString.rawValue {
cellHeight = 135
} else if goalType == GoalType.NoGoGoalString.rawValue {
cellHeight = 85
} else if goalType == GoalType.TimeZoneGoalString.rawValue {
cellHeight = 135
}
}
if indexPath.row == detailDayRows.spreadCell.rawValue{
cellHeight = 165
}
} else if indexPath.section == detailDaySections.comment.rawValue {
cellHeight = 165
}
return CGFloat(cellHeight)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 44.0
} else if section == 1 && self.comments.count > 0{
return 45
}
return 0.0
}
fileprivate func getSpreadCell(_ tableView: UITableView, _ indexPath: IndexPath) -> UITableViewCell {
let cell: SpreadCell = tableView.dequeueReusableCell(withIdentifier: "SpreadCell", for: indexPath) as! SpreadCell
if let data = dayData {
cell.setDayActivityDetailForView(data, animated: shouldAnimate(indexPath))
}
return cell
}
fileprivate func getTimeBucketControlCell(_ tableView: UITableView, _ indexPath: IndexPath) -> UITableViewCell {
let cell: TimeBucketControlCell = tableView.dequeueReusableCell(withIdentifier: "TimeBucketControlCell", for: indexPath) as! TimeBucketControlCell
if let data = dayData {
cell.setDayActivityDetailForView(data, animated: shouldAnimate(indexPath))
}
return cell
}
fileprivate func getTimeZoneControlCell(_ tableView: UITableView, _ indexPath: IndexPath) -> UITableViewCell {
let cell: TimeZoneControlCell = tableView.dequeueReusableCell(withIdentifier: "TimeZoneControlCell", for: indexPath) as! TimeZoneControlCell
if let data = dayData {
cell.setDayActivityDetailForView(data, animated: shouldAnimate(indexPath))
}
return cell
}
fileprivate func getNoGoCell(_ tableView: UITableView, _ indexPath: IndexPath) -> UITableViewCell {
let cell: NoGoCell = tableView.dequeueReusableCell(withIdentifier: "NoGoCell", for: indexPath) as! NoGoCell
if let data = dayData {
cell.setDayActivityDetailForView(data)
}
return cell
}
fileprivate func getDayViewLinkCell(_ tableView: UITableView, _ indexPath: IndexPath) -> UITableViewCell {
let cell: DayViewLinkCell = tableView.dequeueReusableCell(withIdentifier: "DayViewLinkCell", for: indexPath) as! DayViewLinkCell
cell.setData(violationLinkURL!, startDate: violationStartTime!)
return cell
}
fileprivate func getCommentControlCell(_ tableView: UITableView, _ indexPath: IndexPath, _ comment: Comment) -> UITableViewCell {
let cell: CommentControlCell = tableView.dequeueReusableCell(withIdentifier: "CommentControlCell", for: indexPath) as! CommentControlCell
cell.setBuddyCommentData(comment)
cell.indexPath = indexPath
cell.commentDelegate = self
cell.hideShowReplyButton(self.dayData?.commentLink != nil && comment.replyLink == nil)
self.sendCommentFooter!.setLinks(comment.replyLink, commentLink: self.dayData?.commentLink)
return cell
}
fileprivate func getReplyToCommentCell(_ tableView: UITableView, _ indexPath: IndexPath, _ comment: Comment) -> UITableViewCell {
let cell: ReplyToComment = tableView.dequeueReusableCell(withIdentifier: "ReplyToComment", for: indexPath) as! ReplyToComment
cell.setBuddyCommentData(comment)
cell.indexPath = indexPath
cell.commentDelegate = self
cell.hideShowReplyButton(comment.replyLink == nil)
self.sendCommentFooter?.alpha = 0
return cell
}
func getCellForSectionZero(indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == detailDayRows.spreadCell.rawValue {
return getSpreadCell(tableView, indexPath)
}
if indexPath.row == detailDayRows.activity.rawValue {
if goalType == GoalType.BudgetGoalString.rawValue {
return getTimeBucketControlCell(tableView, indexPath)
} else if goalType == GoalType.TimeZoneGoalString.rawValue {
return getTimeZoneControlCell(tableView, indexPath)
} else if goalType == GoalType.NoGoGoalString.rawValue {
return getNoGoCell(tableView, indexPath)
}
}
if indexPath.row == detailDayRows.linkCell.rawValue {
return getDayViewLinkCell(tableView, indexPath)
}
return UITableViewCell(frame: CGRect.zero)
}
fileprivate func getNextCommentThreadId(_ indexPath: IndexPath, _ nextThreadID: inout String, _ previousThreadID: inout String) {
if indexPath.row + 1 < self.comments.count {
if let nextThreadMessageId = self.comments[indexPath.row + 1].threadHeadMessageID {
nextThreadID = nextThreadMessageId
}
} else {
nextThreadID = ""
}
//check for a previous row
if indexPath.row != 0{
// then get the thread id of this row
if let previousThreadMessageId = self.comments[indexPath.row - 1].threadHeadMessageID {
previousThreadID = previousThreadMessageId
}
}
}
func getCellForSectionOne(indexPath: IndexPath) -> UITableViewCell {
let comment = self.comments[indexPath.row]
let currentThreadID = comment.threadHeadMessageID
var previousThreadID = ""
var nextThreadID = ""
getNextCommentThreadId(indexPath, &nextThreadID, &previousThreadID)
if self.dayData?.messageLink != nil && indexPath.section == 1 {
if currentThreadID != previousThreadID { //if we ahve a thread id that is different in the current comment as in the previous one show ccomment control
return getCommentControlCell(tableView, indexPath, comment)
} else { // if the thread id is the same then show the reply to comment cell
return getReplyToCommentCell(tableView, indexPath, comment)
}
}
return UITableViewCell(frame: CGRect.zero)
}
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
return getCellForSectionZero(indexPath: indexPath)
} else if self.dayData?.messageLink != nil && indexPath.section == 1 {
return getCellForSectionOne(indexPath: indexPath)
}
return UITableViewCell(frame: CGRect.zero)
}
fileprivate func headerViewForSectionZero(_ tableView: UITableView) -> UIView? {
let cell : YonaButtonsTableHeaderView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "YonaButtonsTableHeaderView") as! YonaButtonsTableHeaderView
cell.delegate = self
if currentDate.isToday() {
cell.headerTextLabel.text = NSLocalizedString("today", comment: "")
} else if currentDate.isYesterday() {
cell.headerTextLabel.text = NSLocalizedString("yesterday", comment: "")
} else {
cell.headerTextLabel.text = currentDate.fullDayMonthDateString()
}
//if date prievious to that show
if let data = dayData {
var next = false
var prev = false
cell.configureWithNone()
if let _ = data.nextLink {
next = true
cell.configureAsLast()
}
if let _ = data.prevLink {
prev = true
cell.configureAsFirst()
}
if next && prev {
cell.configureWithBoth()
}
}
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
return headerViewForSectionZero(tableView)
} else if section == 1 && self.comments.count > 0{
let cell : CommentTableHeader = tableView.dequeueReusableHeaderFooterView(withIdentifier: "CommentTableHeader") as! CommentTableHeader
return cell
}
return nil
}
func tableView(_ tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: IndexPath) {
if self.comments.count > 0{
if indexPath.section == 1 {
if indexPath.row == page * size - 1 && page < self.totalPages {
page = page + 1
if let commentsLink = self.dayData?.messageLink {
Loader.Show()
CommentRequestManager.sharedInstance.getComments(commentsLink, size: size, page: page) { (success, comment, comments, serverMessage, serverCode) in
Loader.Hide()
if success {
if let comments = comments {
for comment in comments {
self.comments.append(comment)
}
}
}
}
}
}
}
}
}
// MARK: - get comment data
func getComments(_ commentLink: String) {
CommentRequestManager.sharedInstance.getComments(commentLink, size: size, page: page) { (success, comment, comments, serverMessage, serverCode) in
if success {
self.comments = []
if let comments = comments {
self.comments = comments
self.totalPages = comments[0].totalPages!
}
}
}
}
}
// MARK: - CommentCellDelegate
extension MeDayDetailViewController: CommentCellDelegate {
func deleteComment(_ cell: CommentControlCell, comment: Comment){
let aComment = comment as Comment
CommentRequestManager.sharedInstance.deleteComment(aComment, onCompletion: { (success, message, code) in
if success {
self.comments.remove(at: (cell.indexPath?.row)!)
} else {
self.displayAlertMessage(message!, alertDescription: "")
}
})
}
func showSendComment(_ comment: Comment?) {
self.comments = []
if let comment = comment {
self.comments.append(comment)
}
UIView.animate(withDuration: 0.5, animations: {
self.sendCommentFooter!.alpha = 1
})
}
}
// MARK: - SendCommentControlProtocol
extension MeDayDetailViewController: SendCommentControlProtocol {
func textFieldBeginEdit(_ textField: UITextField, commentTextField: UITextField) {
IQKeyboardManager.shared.enableAutoToolbar = false
}
func textFieldEndEdit(_ commentTextField: UITextField, comment: Comment?){
moveToBottomRequired = true
commentTextField.resignFirstResponder()
commentTextField.text = ""
if let commentsLink = self.dayData?.messageLink {
size = 4
page = 1
self.getComments(commentsLink)
}
}
}
| mpl-2.0 | 4a58780eb47a3b596fa3197b0079556f | 40.061856 | 187 | 0.592937 | 5.561555 | false | false | false | false |
cemolcay/CurlUI | Pods/ProgressKit/InDeterminate/RotatingArc.swift | 2 | 2999 | //
// RotatingArc.swift
// ProgressKit
//
// Created by Kauntey Suryawanshi on 26/10/15.
// Copyright © 2015 Kauntey Suryawanshi. All rights reserved.
//
import Foundation
import Cocoa
private let duration = 0.25
@IBDesignable
public class RotatingArc: IndeterminateAnimation {
var backgroundCircle = CAShapeLayer()
var arcLayer = CAShapeLayer()
@IBInspectable var strokeWidth: CGFloat = 5 {
didSet {
notifyViewRedesigned()
}
}
@IBInspectable var arcLength: Int = 35 {
didSet {
notifyViewRedesigned()
}
}
@IBInspectable var clockWise: Bool = true {
didSet {
notifyViewRedesigned()
}
}
var radius: CGFloat {
return (self.frame.width / 2) * CGFloat(0.75)
}
var rotationAnimation: CABasicAnimation = {
var tempRotation = CABasicAnimation(keyPath: "transform.rotation")
tempRotation.repeatCount = Float.infinity
tempRotation.fromValue = 0
tempRotation.toValue = 1
tempRotation.cumulative = true
tempRotation.duration = duration
return tempRotation
}()
override func notifyViewRedesigned() {
super.notifyViewRedesigned()
arcLayer.strokeColor = foreground.CGColor
backgroundCircle.strokeColor = foreground.colorWithAlphaComponent(0.4).CGColor
backgroundCircle.lineWidth = self.strokeWidth
arcLayer.lineWidth = strokeWidth
rotationAnimation.toValue = clockWise ? -1 : 1
let arcPath = NSBezierPath()
let endAngle: CGFloat = CGFloat(-360) * CGFloat(arcLength) / 100
arcPath.appendBezierPathWithArcWithCenter(self.bounds.mid, radius: radius, startAngle: 0, endAngle: endAngle, clockwise: true)
arcLayer.path = arcPath.CGPath
}
override func configureLayers() {
super.configureLayers()
let rect = self.bounds
// Add background Circle
do {
backgroundCircle.frame = rect
backgroundCircle.lineWidth = strokeWidth
backgroundCircle.strokeColor = foreground.colorWithAlphaComponent(0.5).CGColor
backgroundCircle.fillColor = NSColor.clearColor().CGColor
let backgroundPath = NSBezierPath()
backgroundPath.appendBezierPathWithArcWithCenter(rect.mid, radius: radius, startAngle: 0, endAngle: 360)
backgroundCircle.path = backgroundPath.CGPath
self.layer?.addSublayer(backgroundCircle)
}
// Arc Layer
do {
arcLayer.fillColor = NSColor.clearColor().CGColor
arcLayer.lineWidth = strokeWidth
arcLayer.frame = rect
arcLayer.strokeColor = foreground.CGColor
self.layer?.addSublayer(arcLayer)
}
}
override func startAnimation() {
arcLayer.addAnimation(rotationAnimation, forKey: "")
}
override func stopAnimation() {
arcLayer.removeAllAnimations()
}
}
| mit | e6660809ed1f5f007c30eba22f2effab | 27.826923 | 134 | 0.645097 | 5.306195 | false | false | false | false |
radioboo/Migrator | Pod/Classes/Migrator.swift | 1 | 3544 | //
// Migrator.swift
// Pods
//
// Created by 酒井篤 on 2015/09/13.
//
//
import UIKit
import EDSemver
public protocol MigratorProtocol : class {
func didSucceededMigration(migratedVersion: String) -> ()
func didFailedMigration(migratedVersion: String, error: ErrorType) -> ()
func didCompletedAllMigration() -> ()
}
public class Migrator: NSObject {
var migrationHandlers: [MigrationHandler] = []
public var delegate: MigratorProtocol?
let kMigratorLastVersionKey = "com.radioboo.migratorLastVersionKey";
public func migrate() {
if self.migrationHandlers.count == 0 {
print("[Migrator ERROR] Completed Soon, Empty Handlers.");
return;
}
for handler: MigrationHandler in self.migrationHandlers {
migrate(handler)
}
self.delegate?.didCompletedAllMigration()
}
public func registerHandler(targetVersion: String, migration: () throws -> Void) {
let handler: MigrationHandler = MigrationHandler(targetVersion: targetVersion, handler: migration)
registerHandler(handler)
}
public func currentVersion() -> String {
let currentVersion:String = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
return currentVersion;
}
public func lastMigratedVersion() -> String {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
return defaults.stringForKey(kMigratorLastVersionKey) ?? ""
}
public func shouldMigrate() -> Bool {
let last: EDSemver = EDSemver(string: lastMigratedVersion())
let current: EDSemver = EDSemver(string: currentVersion())
if last.isGreaterThan(current) {
return true
}
return false
}
public func reset() {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.removeObjectForKey(kMigratorLastVersionKey)
defaults.synchronize()
}
public func setInitialVersion(version: String) {
self.setInitialVersionIfEmpty(version)
}
// MARK: - Private Methods
private func registerHandler(handler: MigrationHandler) {
migrationHandlers.append(handler)
}
private func setLastMigratedVersion(version: String) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(version, forKey:kMigratorLastVersionKey)
defaults.synchronize()
}
private func setInitialVersionIfEmpty(version: String) {
if self.lastMigratedVersion().isEmpty {
setLastMigratedVersion(version)
}
}
private func migrate(handler: MigrationHandler) {
let targetVersion: EDSemver = EDSemver(string: handler.targetVersion)
let lastMigratedVersion: EDSemver = EDSemver(string: self.lastMigratedVersion())
let currentVersion: EDSemver = EDSemver(string: self.currentVersion())
if targetVersion.isLessThan(lastMigratedVersion)
|| targetVersion.isEqualTo(lastMigratedVersion) {
return
}
if targetVersion.isGreaterThan(currentVersion) {
return
}
do {
try handler.migrate()
} catch let error {
self.delegate?.didFailedMigration(handler.targetVersion, error: error)
}
setLastMigratedVersion(handler.targetVersion)
self.delegate?.didSucceededMigration(handler.targetVersion)
}
}
| mit | 57359752c1a8c47610dd5c10d2cd7de0 | 28.983051 | 125 | 0.667044 | 5.296407 | false | false | false | false |
MrLSPBoy/LSPDouYu | LSPDouYuTV/LSPDouYuTV/Classes/Main/Model/LSAnchorModel.swift | 1 | 831 | //
// LSAnchorModel.swift
// LSPDouYuTV
//
// Created by lishaopeng on 17/3/1.
// Copyright © 2017年 lishaopeng. All rights reserved.
//
import UIKit
class LSAnchorModel: NSObject {
//房间ID
var room_id : Int = 0
//房间图片对应的URLString
var vertical_src : String = ""
///判断是手机直播还是电脑直播
//0:电脑直播(普通房间) 1:手机直播(秀场房间)
var isVertical : Int = 0
/// 房间名称
var room_name : String = ""
/// 主播昵称
var nickname : String = ""
/// 观看人数
var online : Int = 0
/// 所在城市
var anchor_city : String = ""
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| mit | 109d3f61b477c7272e72f9759a202566 | 20.176471 | 73 | 0.572222 | 3.58209 | false | false | false | false |
apple/swift-lldb | packages/Python/lldbsuite/test/lang/swift/generic_class_arg/main.swift | 2 | 621 | protocol P {
func foo() -> Int32
}
public class C: P {
var x: Int32 = 11223344
public func foo() -> Int32 {
return x
}
}
public struct S : P {
var x: Int32 = 44332211
public func foo() -> Int32 {
return x
}
}
func foo<T1: P, T2: P> (_ t1: T1, _ t2: T2) -> Int32 {
return t1.foo() + t2.foo() //% self.expect('frame variable -d run -- t1', substrs=['11223344'])
//% self.expect('frame variable -d run -- t2', substrs=['44332211'])
//% self.expect('expression -d run -- t1', substrs=['11223344'])
//% self.expect('expression -d run -- t2', substrs=['44332211'])
}
print(foo(C(), S()))
| apache-2.0 | 9e0309d25a3072ecc112eab8bf621267 | 22.884615 | 97 | 0.570048 | 2.797297 | false | false | false | false |
bnickel/SEUICollectionViewLayout | Code Survey/Code Survey/SurveyItem.swift | 1 | 3858 | //
// SurveyItem.swift
// Code Survey
//
// Created by Brian Nickel on 10/6/14.
// Copyright (c) 2014 Brian Nickel. All rights reserved.
//
import UIKit
private var SurveyItemContext = 0
enum ItemType: String {
case Checkbox = "checkbox"
case Text = "text"
case BigText = "big-text"
}
class SurveyItem: NSObject {
let identifier:String
let label:String
let type:ItemType
let indent:Int
dynamic var textValue:String = ""
dynamic var hidden:Bool = false
private let dependencies:[String:String]
private var observedItems:[SurveyItem] = []
init(identifier:String, label:String, type:ItemType = .Text, indent:Int = 0, dependencies:[String:String] = [:]) {
self.identifier = identifier
self.label = label
self.type = type
self.indent = indent
self.dependencies = dependencies
super.init()
}
func startObservingWithObservables(observables:[String:SurveyItem]) {
for (identifier, value) in dependencies {
if let item = observables[identifier] {
item.addObserver(self, forKeyPath: "textValue", options: nil, context: &SurveyItemContext)
observedItems.append(item)
if value != item.textValue {
hidden = true
}
}
}
}
func stopObserving() {
for item in observedItems {
item.removeObserver(self, forKeyPath: "textValue", context: &SurveyItemContext)
}
observedItems.removeAll(keepCapacity: true)
hidden = false
}
deinit {
stopObserving()
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if context == &SurveyItemContext {
let item = object as! SurveyItem
if item.textValue != dependencies[item.identifier]! {
hidden = true
return
}
for item in observedItems {
if item.textValue != dependencies[item.identifier]! {
hidden = true
return
}
}
hidden = false
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
// MARK: - JSON Initialization
private class func parseDependencies(items:AnyObject?) -> [String:String] {
var output:[String:String] = [:]
func parseItem(item:String) {
if let range = item.rangeOfString("=", options: nil, range: nil, locale: nil) {
output.updateValue(item.substringFromIndex(range.endIndex), forKey: item.substringToIndex(range.startIndex))
}
}
if let item = items as? String {
parseItem(item)
} else if let itemsAsArray = items as? [String] {
for item in itemsAsArray {
parseItem(item)
}
}
return output
}
convenience init?(dictionary:NSDictionary) {
if let identifier = dictionary["id"] as? String {
if let label = dictionary["label"] as? String {
let type = ItemType(rawValue: (dictionary["type"] as? String) ?? "") ?? .Text
let indent = (dictionary["indent"] as? Int) ?? 0
self.init(identifier:identifier, label:label, type:type, indent:indent, dependencies:SurveyItem.parseDependencies(dictionary["show-if"]))
return
}
}
self.init(identifier:"", label:"")
return nil
}
}
| mit | 53b5c99d5a029da8c0a1d236e49a9222 | 28.906977 | 156 | 0.551322 | 5.016905 | false | false | false | false |
tuanphung/ATSwiftKit | Source/Classes/IBDesignables/ATSView.swift | 1 | 1706 | //
// ATSView.swift
//
// Copyright (c) 2015 PHUNG ANH TUAN. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
@IBDesignable
public class IBDesignableView: UIView {
@IBInspectable
var cornerRadius: CGFloat = 0.0 {
didSet{
layer.cornerRadius = cornerRadius
}
}
@IBInspectable
var borderColor: UIColor = UIColor.blackColor() {
didSet{
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable
var borderWidth: CGFloat = 0.0 {
didSet{
layer.borderWidth = borderWidth
}
}
}
public class ATSView: IBDesignableView { }
| mit | 58d3a31cf1bf68a76ac5647102a8d9ad | 33.12 | 80 | 0.705158 | 4.648501 | false | false | false | false |
loganSims/wsdot-ios-app | wsdot/RouteAlertsViewController.swift | 1 | 6770 | //
// RouteAlertsViewController.swift
// WSDOT
//
// Copyright (c) 2018 Washington State Department of Transportation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
//
import UIKit
import RealmSwift
import SafariServices
class RouteAlertsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, INDLinkLabelDelegate {
@IBOutlet var tableView: UITableView!
let cellIdentifier = "RouteAlerts"
var routeId = 0
var alertItems = [FerryAlertItem]()
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
let refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator.startAnimating()
tableView.rowHeight = UITableView.automaticDimension
// refresh controller
refreshControl.addTarget(self, action: #selector(RouteAlertsViewController.refreshAction(_:)), for: .valueChanged)
tableView.addSubview(refreshControl)
fetchAlerts()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
MyAnalytics.screenView(screenName: "FerryBulletins")
}
@objc func refreshAction(_ refreshControl: UIRefreshControl) {
// showConnectionAlert = true
fetchAlerts()
}
func fetchAlerts() {
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { [weak self] in
FerryRealmStore.updateRouteSchedules(false, completion: { error in
if (error == nil) {
// Reload tableview on UI thread
DispatchQueue.main.async { [weak self] in
if let selfValue = self {
if let routeItem = FerryRealmStore.findSchedule(withId: selfValue.routeId) {
selfValue.title = "\(routeItem.routeDescription) Alerts"
selfValue.alertItems = routeItem.routeAlerts.sorted(by: {$0.publishDate > $1.publishDate})
selfValue.tableView.reloadData()
}
if selfValue.alertItems.count == 0 {
selfValue.title = "No Alerts"
}
selfValue.activityIndicator.stopAnimating()
selfValue.activityIndicator.isHidden = true
selfValue.refreshControl.endRefreshing()
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: selfValue.tableView)
}
}
} else {
DispatchQueue.main.async { [weak self] in
if let selfValue = self{
selfValue.refreshControl.endRefreshing()
AlertMessages.getConnectionAlert(backupURL: WsdotURLS.ferries)
}
}
}
})
}
}
// MARK: tableview
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return alertItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! LinkCell
let htmlStyleString = "<style>body{font-family: '\(cell.linkLabel.font.familyName)'; font-size:\(cell.linkLabel.font.pointSize)px;}</style>"
let htmlString = htmlStyleString + alertItems[indexPath.row].alertFullText
let attrStr = try! NSMutableAttributedString(
data: htmlString.data(using: String.Encoding.unicode, allowLossyConversion: false)!,
options: [ NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil)
var alertPubDate: Date? = nil
if let alertPubDateValue = try? TimeUtils.formatTimeStamp(alertItems[indexPath.row].publishDate, dateFormat: "yyyy-MM-dd HH:mm aa") {
alertPubDate = alertPubDateValue
} else {
alertPubDate = TimeUtils.parseJSONDateToNSDate(alertItems[indexPath.row].publishDate)
}
if let date = alertPubDate {
cell.updateTime.text = TimeUtils.timeAgoSinceDate(date: date, numericDates: false)
} else {
cell.updateTime.text = "unavailable"
}
cell.linkLabel.attributedText = attrStr
cell.linkLabel.delegate = self
if #available(iOS 13, *) {
cell.linkLabel.textColor = UIColor.label
}
return cell
}
// MARK: INDLinkLabelDelegate
func linkLabel(_ label: INDLinkLabel, didLongPressLinkWithURL URL: Foundation.URL) {
let activityController = UIActivityViewController(activityItems: [URL], applicationActivities: nil)
self.present(activityController, animated: true, completion: nil)
}
func linkLabel(_ label: INDLinkLabel, didTapLinkWithURL URL: Foundation.URL) {
let config = SFSafariViewController.Configuration()
config.entersReaderIfAvailable = true
let svc = SFSafariViewController(url: URL, configuration: config)
if #available(iOS 10.0, *) {
svc.preferredControlTintColor = ThemeManager.currentTheme().secondaryColor
svc.preferredBarTintColor = ThemeManager.currentTheme().mainColor
} else {
svc.view.tintColor = ThemeManager.currentTheme().mainColor
}
self.present(svc, animated: true, completion: nil)
}
}
| gpl-3.0 | a49fa2f94aebaa922940e37d71497786 | 38.590643 | 148 | 0.614771 | 5.63228 | false | false | false | false |
ashfurrow/pragma-2015-rx-workshop | Session 4/Signup Demo/Pods/Nimble-Snapshots/PrettySyntax.swift | 29 | 718 | import Nimble
// MARK: - Nicer syntax using == operator
public struct Snapshot {
let name: String?
init(name: String?) {
self.name = name
}
}
public func snapshot(name: String? = nil) -> Snapshot {
return Snapshot(name: name)
}
public func ==(lhs: Expectation<Snapshotable>, rhs: Snapshot) {
if let name = rhs.name {
lhs.to(haveValidSnapshot(named: name))
} else {
lhs.to(haveValidSnapshot())
}
}
// MARK: - Nicer syntax using emoji
public func 📷(snapshottable: Snapshotable) {
expect(snapshottable).to(recordSnapshot())
}
public func 📷(snapshottable: Snapshotable, named name: String) {
expect(snapshottable).to(recordSnapshot(named: name))
}
| mit | 2cb262def5ced09b0e3ce637f4c828f9 | 20.575758 | 64 | 0.658708 | 3.787234 | false | false | false | false |
Knoxantropicen/Focus-iOS | Focus/Style.swift | 1 | 3167 | //
// Style.swift
// Focus
//
// Created by TianKnox on 2017/5/29.
// Copyright © 2017年 TianKnox. All rights reserved.
//
import Foundation
struct Style {
static let lightColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1)
static let darkColor = UIColor(red: 30/255, green: 30/255, blue: 41/255, alpha: 1)
static let dimColor = UIColor(red: 60/255, green: 60/255, blue: 71/255, alpha: 1)
static var mainBackgroundColor = UIColor.white
static var mainTextColor = UIColor.black
static var popBackgroundColor = lightColor
static var cellBackgroundColor = UIColor.white
static var tableBackgroundColor = UIColor.white
// static var pageColor = UIColor.lightGray
// static var currentPageColor = UIColor.darkGray
static var editTextColor = UIColor.white
static var symbolColor = UIColor.red
static var optionAlpha: CGFloat = 0.7
static var settingsIcon = #imageLiteral(resourceName: "settings-light")
static var checkIcon = #imageLiteral(resourceName: "check-light")
static var plusIcon = #imageLiteral(resourceName: "plus-light")
static var deleteIcon = #imageLiteral(resourceName: "delete-light")
static var returnIcon = #imageLiteral(resourceName: "return-light")
static var lightMode = true
static func themeLight() {
mainBackgroundColor = UIColor.white
mainTextColor = UIColor.black
popBackgroundColor = lightColor
cellBackgroundColor = UIColor.white
tableBackgroundColor = UIColor.white
// pageColor = UIColor.lightGray
// currentPageColor = UIColor.darkGray
editTextColor = UIColor.white
symbolColor = UIColor.red
optionAlpha = 0.7
settingsIcon = #imageLiteral(resourceName: "settings-light")
checkIcon = #imageLiteral(resourceName: "check-light")
plusIcon = #imageLiteral(resourceName: "plus-light")
deleteIcon = #imageLiteral(resourceName: "delete-light")
returnIcon = #imageLiteral(resourceName: "return-light")
lightMode = true
UIApplication.shared.statusBarStyle = UIStatusBarStyle.default
UserDefaults.standard.set(true, forKey: "LightMode")
}
static func themeDark() {
mainBackgroundColor = darkColor
mainTextColor = UIColor.lightGray
popBackgroundColor = dimColor
cellBackgroundColor = dimColor
tableBackgroundColor = darkColor
// pageColor = dimColor
// currentPageColor = UIColor.lightGray
editTextColor = dimColor
symbolColor = UIColor.lightGray
optionAlpha = 0.4
settingsIcon = #imageLiteral(resourceName: "settings-dark")
checkIcon = #imageLiteral(resourceName: "check-dark")
plusIcon = #imageLiteral(resourceName: "plus-dark")
deleteIcon = #imageLiteral(resourceName: "delete-dark")
returnIcon = #imageLiteral(resourceName: "return-dark")
lightMode = false
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
UserDefaults.standard.set(false, forKey: "LightMode")
}
}
| mit | e6ae24ce5c10cd9fe190af3b814434ab | 38.061728 | 90 | 0.680468 | 4.76506 | false | false | false | false |
gongmingqm10/DriftBook | DriftReading/DriftReading/LoadingOverlay.swift | 1 | 1284 | //
// LoadingOverlay.swift
// app
//
// Created by Igor de Oliveira Sa on 25/03/15.
// Copyright (c) 2015 Igor de Oliveira Sa. All rights reserved.
//
// Usage:
//
// # Show Overlay
// LoadingOverlay.shared.showOverlay(self.navigationController?.view)
//
// # Hide Overlay
// LoadingOverlay.shared.hideOverlayView()
import UIKit
import Foundation
public class LoadingOverlay{
var overlayView = UIView()
var activityIndicator = UIActivityIndicatorView()
class var shared: LoadingOverlay {
struct Static {
static let instance: LoadingOverlay = LoadingOverlay()
}
return Static.instance
}
public func showOverlay(view: UIView!) {
overlayView = UIView(frame: UIScreen.mainScreen().bounds)
overlayView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
activityIndicator.center = overlayView.center
overlayView.addSubview(activityIndicator)
activityIndicator.startAnimating()
view.addSubview(overlayView)
}
public func hideOverlayView() {
activityIndicator.stopAnimating()
overlayView.removeFromSuperview()
}
} | mit | b0bc980cd7d0996c2177d25b6b0c71fd | 26.934783 | 116 | 0.695483 | 5.015625 | false | false | false | false |
sourcebitsllc/Asset-Generator-Mac | XCAssetGenerator/AssetWindowViewModel.swift | 1 | 3880 | //
// AssetWindowViewModel.swift
// XCAssetGenerator
//
// Created by Bader on 5/26/15.
// Copyright (c) 2015 Bader Alabdulrazzaq. All rights reserved.
//
import ReactiveCocoa
class AssetWindowViewModel {
let statusLabel: MutableProperty<String>
let canGenerate = MutableProperty<Bool>(false)
let generateTitle = MutableProperty<String>("Build")
private let imagesViewModel: ImagesGroupViewModel
private let projectViewModel: ProjectSelectionViewModel
private var progressViewModel: ProgressIndicationViewModel
private let assetGenerator: AssetGenerationController
// RAC3 TODO: Main WindowController Initialization.
init() {
imagesViewModel = ImagesGroupViewModel()
projectViewModel = ProjectSelectionViewModel()
progressViewModel = ProgressIndicationViewModel()
assetGenerator = AssetGenerationController()
statusLabel = MutableProperty<String>("")
let notCurrentlyGenerating: () -> Bool = {
return self.progressViewModel.animating.value == false
}
let inputsSignal = combineLatest(imagesViewModel.selectionSignal, projectViewModel.selectionSignal)
let inputsContentSignal = combineLatest(imagesViewModel.contentSignal, projectViewModel.contentSignal)
statusLabel <~ inputsSignal
|> map { assets, project in
return StatusCrafter.status(assets: assets, target: project)
}
statusLabel <~ inputsContentSignal
|> filter { _ in notCurrentlyGenerating() }
|> map { _ in
let assets = self.imagesViewModel.assetRepresentation()
let catalog = self.projectViewModel.currentCatalog
return StatusCrafter.status(assets: assets, target: catalog)
}
// RAC3 TODO:
canGenerate <~ combineLatest(inputsSignal, assetGenerator.running.producer)
// |> throttle(0.5, onScheduler: QueueScheduler.mainQueueScheduler)
|> map { input, running in
let validSource = AssetGeneratorInputValidator.validateSource(input.0)
let validTarget = AssetGeneratorInputValidator.validateTarget(input.1)
let notRunning = running == false
return validSource && validTarget && notRunning
}
generateTitle <~ combineLatest(inputsSignal, inputsContentSignal)
|> filter { _ in notCurrentlyGenerating() }
|> map { _ in "Build" }
}
func viewModelForImagesGroup() -> ImagesGroupViewModel {
return imagesViewModel
}
func viewModelForSelectedProject() -> ProjectSelectionViewModel {
return projectViewModel
}
func viewModelForProgressIndication() -> ProgressIndicationViewModel {
return progressViewModel
}
func generateAssets() {
// Wut
let assets = imagesViewModel.assetRepresentation()
let catalog = projectViewModel.currentCatalog
// End Wut
assetGenerator.assetGenerationProducer(assets, destination: catalog?.path)
|> startOn(QueueScheduler.mainQueueScheduler)
|> on(started: {
self.progressViewModel.progressStarted()
}, completed: {
self.generateTitle.put("Build Again")
self.progressViewModel.progressFinished()
}, next: { report in
switch report {
case .Progress(let p):
self.progressViewModel.updateProgress(p)
case .Assets(let a):
StatusCrafter.postGeneration(catalog!.title, amount: a) |> self.statusLabel.put
}
})
|> start()
}
}
| mit | 77cae7d35ccbfcd7c3c5ddaac63f3561 | 37.8 | 110 | 0.621134 | 5.639535 | false | false | false | false |
DaveChambers/SuperCrack | SuperCrack!/Setting.swift | 1 | 1619 | //
// Setting.swift
// MastermindJune
//
// Created by Dave Chambers on 25/06/2017.
// Copyright © 2017 Dave Chambers. All rights reserved.
//
import UIKit
class Setting: CustomStringConvertible {
private var name: String
private var value: Int
private var uncommitedValue: Int
private var minValue: Int
private var maxValue: Int
private var position: Int
private var colour: UIColor
private var textColour: UIColor
init(name: String, value: Int, minValue: Int, maxValue: Int, position: Int, colour: UIColor, textColour: UIColor) {
self.name = name
self.value = value
self.uncommitedValue = value
self.minValue = minValue
self.maxValue = maxValue
self.position = position
self.colour = colour
self.textColour = textColour
}
var description: String {
return "Name:\(name) \tValue:\(value)\n"
}
func getName() -> String {
return self.name
}
func getValue() -> Int {
return self.value
}
func setValue(updatedValue: Int) {
self.value = updatedValue
}
func getUncommitedValue() -> Int {
return self.uncommitedValue
}
func setUncommitedValue(updatedValue: Int) {
self.uncommitedValue = updatedValue
}
func getMin() -> Int {
return self.minValue
}
func getMax() -> Int {
return self.maxValue
}
func getPosition() -> Int {
return self.position
}
func getColour() -> UIColor {
return self.colour
}
func getTextColour() -> UIColor {
return self.textColour
}
}
| mit | 373e01241e3b05e3c3002f5d2bc4170b | 20.012987 | 117 | 0.624227 | 4.180879 | false | false | false | false |
fedepo/phoneid_iOS | Pod/Classes/core/PhoneIdServiceError.swift | 2 | 2388 | //
// PhoneIdServiceError.swift
// phoneid_iOS
//
// Copyright 2015 phone.id - 73 knots, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
public enum ErrorCode:Int{
case inappropriateResult = 101
case requestFailed = 102
case invalidParameters = 100
var asInt:Int {
get{ return self.rawValue}
}
}
open class PhoneIdServiceError:NSError{
public init(code:Int, descriptionKey:String, reasonKey:String?){
let description = NSLocalizedString(descriptionKey, bundle: Bundle.phoneIdBundle(), comment:descriptionKey)
var info = [NSLocalizedDescriptionKey:description]
if let reasonKey = reasonKey{
let reason = NSLocalizedString(reasonKey, bundle: Bundle.phoneIdBundle(), comment:reasonKey)
info[NSLocalizedFailureReasonErrorKey] = reason
}
super.init(domain:"com.phoneid.PhoneIdSDK", code: code, userInfo: info)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open class func inappropriateResponseError(_ descriptionKey:String, reasonKey:String?) -> PhoneIdServiceError{
return PhoneIdServiceError(code:ErrorCode.inappropriateResult.asInt, descriptionKey:descriptionKey , reasonKey: reasonKey)
}
open class func requestFailedError(_ descriptionKey:String, reasonKey:String?) -> PhoneIdServiceError{
return PhoneIdServiceError(code:ErrorCode.requestFailed.asInt, descriptionKey: descriptionKey, reasonKey: reasonKey)
}
open class func invalidParameters(_ descriptionKey:String, reasonKey:String?) -> PhoneIdServiceError{
return PhoneIdServiceError(code:ErrorCode.invalidParameters.asInt, descriptionKey:"error.phone.number.validation.failed", reasonKey: reasonKey)
}
}
| apache-2.0 | 9d8e88e5eb31b1585e583ccc9d6ffd55 | 35.738462 | 151 | 0.716499 | 4.795181 | false | false | false | false |
DianQK/rx-sample-code | RxDataSourcesExample/CellButtonClickTableViewController.swift | 1 | 2717 | //
// CellButtonClickTableViewController.swift
// RxDataSourcesExample
//
// Created by DianQK on 04/10/2016.
// Copyright © 2016 T. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import SafariServices
class InfoTableViewCell: UITableViewCell {
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet fileprivate weak var detailButton: UIButton! {
didSet {
detailButton.layer.borderColor = UIColor.black.cgColor
detailButton.layer.borderWidth = 1
detailButton.layer.cornerRadius = 5
detailButton.addTarget(self, action: #selector(_detailButtonTap), for: .touchUpInside)
}
}
var detailButtonTap: (() -> ())?
var title: String? {
get {
return titleLabel.text
}
set(title) {
titleLabel.text = title
}
}
var disposeBag = DisposeBag()
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
}
private dynamic func _detailButtonTap() {
detailButtonTap?()
}
}
class CellButtonClickTableViewController: UITableViewController {
struct Info {
let name: String
let url: URL
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = nil
tableView.delegate = nil
let infoItems = [
Info(name: "Apple Developer", url: URL(string: "https://developer.apple.com/")!),
Info(name: "GitHub", url: URL(string: "https://github.com")!),
Info(name: "Dribbble", url: URL(string: "https://dribbble.com")!)
]
Observable.just(infoItems)
.bindTo(tableView.rx.items(cellIdentifier: "InfoTableViewCell", cellType: InfoTableViewCell.self)) { [unowned self] (row, element, cell) in
cell.title = element.name
// cell.detailButtonTap = {
// let safari = SFSafariViewController(url: element.url)
// safari.preferredControlTintColor = UIColor.black
// self.showDetailViewController(safari, sender: nil)
// }
cell.detailButton.rx.tap
.map { element.url }
.subscribe(onNext: { url in
print("Open :\(url)")
let safari = SFSafariViewController(url: element.url)
safari.preferredControlTintColor = UIColor.black
self.showDetailViewController(safari, sender: nil)
})
.disposed(by: cell.disposeBag)
}
.disposed(by: rx.disposeBag)
}
}
| mit | 638c06e521248421ee4f15a36378648c | 28.846154 | 151 | 0.575847 | 5.01107 | false | false | false | false |
hzy87email/WeixinWalk | 微信运动/微信运动/PageContentViewController.swift | 2 | 1598 | //
// PageContentViewController.swift
// 微信运动
//
// Created by Eular on 9/6/15.
// Copyright © 2015 Eular. All rights reserved.
//
import UIKit
class PageContentViewController: UIViewController {
@IBOutlet weak var headingLabel: UILabel!
@IBOutlet weak var subHeadingLabel: UILabel!
@IBOutlet weak var pageImage: UIImageView!
@IBOutlet weak var StartBtn: UIButton!
var index: Int = 0
var heading: String = ""
var subHeading: String = ""
var img: String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
headingLabel.text = heading
subHeadingLabel.text = subHeading
pageImage.image = UIImage(named: img)
//pageControl.currentPage = index
StartBtn.hidden = ( index == 2 ) ? false : true
StartBtn.layer.borderColor = UIColor.whiteColor().CGColor
StartBtn.layer.borderWidth = 1
StartBtn.layer.cornerRadius = 5
}
@IBAction func close(sender: AnyObject) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(true, forKey: "hasViewedWalkthrough")
let healthManager = HealthManager()
healthManager.authorizeHealthKit() {
(success, error) in
if success {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 47284133cfd26aea01d3d127cbb512d1 | 28.981132 | 73 | 0.637508 | 4.965625 | false | false | false | false |
GreatfeatServices/gf-mobile-app | olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/Window.swift | 57 | 4469 | //
// Window.swift
// RxSwift
//
// Created by Junior B. on 29/10/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class WindowTimeCountSink<Element, O: ObserverType>
: Sink<O>
, ObserverType
, LockOwnerType
, SynchronizedOnType where O.E == Observable<Element> {
typealias Parent = WindowTimeCount<Element>
typealias E = Element
private let _parent: Parent
let _lock = NSRecursiveLock()
private var _subject = PublishSubject<Element>()
private var _count = 0
private var _windowId = 0
private let _timerD = SerialDisposable()
private let _refCountDisposable: RefCountDisposable
private let _groupDisposable = CompositeDisposable()
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
let _ = _groupDisposable.insert(_timerD)
_refCountDisposable = RefCountDisposable(disposable: _groupDisposable)
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
forwardOn(.next(AddRef(source: _subject, refCount: _refCountDisposable).asObservable()))
createTimer(_windowId)
let _ = _groupDisposable.insert(_parent._source.subscribeSafe(self))
return _refCountDisposable
}
func startNewWindowAndCompleteCurrentOne() {
_subject.on(.completed)
_subject = PublishSubject<Element>()
forwardOn(.next(AddRef(source: _subject, refCount: _refCountDisposable).asObservable()))
}
func on(_ event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<E>) {
var newWindow = false
var newId = 0
switch event {
case .next(let element):
_subject.on(.next(element))
do {
let _ = try incrementChecked(&_count)
} catch (let e) {
_subject.on(.error(e as Swift.Error))
dispose()
}
if (_count == _parent._count) {
newWindow = true
_count = 0
_windowId += 1
newId = _windowId
self.startNewWindowAndCompleteCurrentOne()
}
case .error(let error):
_subject.on(.error(error))
forwardOn(.error(error))
dispose()
case .completed:
_subject.on(.completed)
forwardOn(.completed)
dispose()
}
if newWindow {
createTimer(newId)
}
}
func createTimer(_ windowId: Int) {
if _timerD.isDisposed {
return
}
if _windowId != windowId {
return
}
let nextTimer = SingleAssignmentDisposable()
_timerD.disposable = nextTimer
let scheduledRelative = _parent._scheduler.scheduleRelative(windowId, dueTime: _parent._timeSpan) { previousWindowId in
var newId = 0
self._lock.performLocked {
if previousWindowId != self._windowId {
return
}
self._count = 0
self._windowId = self._windowId &+ 1
newId = self._windowId
self.startNewWindowAndCompleteCurrentOne()
}
self.createTimer(newId)
return Disposables.create()
}
nextTimer.setDisposable(scheduledRelative)
}
}
class WindowTimeCount<Element> : Producer<Observable<Element>> {
fileprivate let _timeSpan: RxTimeInterval
fileprivate let _count: Int
fileprivate let _scheduler: SchedulerType
fileprivate let _source: Observable<Element>
init(source: Observable<Element>, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) {
_source = source
_timeSpan = timeSpan
_count = count
_scheduler = scheduler
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Observable<Element> {
let sink = WindowTimeCountSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| apache-2.0 | 1de56b7fefeb68d502ae059fddf739b7 | 28.012987 | 157 | 0.562668 | 5.177289 | false | false | false | false |
linusnyberg/RepoList | Pods/OAuthSwift/Sources/OAuthSwiftError.swift | 1 | 5143 | //
// OAuthSwiftError.swift
// OAuthSwift
//
// Created by phimage on 02/10/16.
// Copyright © 2016 Dongri Jin. All rights reserved.
//
import Foundation
// MARK: - OAuthSwift errors
public enum OAuthSwiftError: Error {
// Configuration problem with oauth provider.
case configurationError(message: String)
// The provided token is expired, retrieve new token by using the refresh token
case tokenExpired(error: Error?)
// State missing from request (you can set allowMissingStateCheck = true to ignore)
case missingState
// Returned state value is wrong
case stateNotEqual(state: String, responseState: String)
// Error from server
case serverError(message: String)
// Failed to create URL \(urlString) not convertible to URL, please encode
case encodingError(urlString: String)
case authorizationPending
// Failed to create request with \(urlString)
case requestCreation(message: String)
// Authentification failed. No token
case missingToken
// Please retain OAuthSwift object or handle
case retain
// Request error
case requestError(error: Error, request: URLRequest)
// Request cancelled
case cancelled
public static let Domain = "OAuthSwiftError"
public static let ResponseDataKey = "OAuthSwiftError.response.data"
public static let ResponseKey = "OAuthSwiftError.response"
fileprivate enum Code : Int {
case configurationError = -1
case tokenExpired = -2
case missingState = -3
case stateNotEqual = -4
case serverError = -5
case encodingError = -6
case authorizationPending = -7
case requestCreation = -8
case missingToken = -9
case retain = -10
case requestError = -11
case cancelled = -12
}
fileprivate var code: Code {
switch self {
case .configurationError: return Code.configurationError
case .tokenExpired: return Code.tokenExpired
case .missingState: return Code.missingState
case .stateNotEqual: return Code.stateNotEqual
case .serverError: return Code.serverError
case .encodingError: return Code.encodingError
case .authorizationPending: return Code.authorizationPending
case .requestCreation: return Code.requestCreation
case .missingToken: return Code.missingToken
case .retain: return Code.retain
case .requestError: return Code.requestError
case .cancelled : return Code.cancelled
}
}
public var underlyingError: Error? {
switch self {
case .tokenExpired(let e): return e
case .requestError(let e, _): return e
default: return nil
}
}
public var underlyingMessage: String? {
switch self {
case .serverError(let m): return m
case .configurationError(let m): return m
case .requestCreation(let m): return m
default: return nil
}
}
}
extension OAuthSwiftError: CustomStringConvertible {
public var description: String {
switch self {
case .configurationError(let m): return "configurationError[\(m)]"
case .tokenExpired(let e): return "tokenExpired[\(String(describing: e))]"
case .missingState: return "missingState"
case .stateNotEqual(let s, let e): return "stateNotEqual[\(s)<>\(e)]"
case .serverError(let m): return "serverError[\(m)]"
case .encodingError(let urlString): return "encodingError[\(urlString)]"
case .authorizationPending: return "authorizationPending"
case .requestCreation(let m): return "requestCreation[\(m)]"
case .missingToken: return "missingToken"
case .retain: return "retain"
case .requestError(let e, _): return "requestError[\(e)]"
case .cancelled : return "cancelled"
}
}
}
extension OAuthSwift {
static func retainError(_ failureHandler: FailureHandler?) {
#if !OAUTH_NO_RETAIN_ERROR
failureHandler?(OAuthSwiftError.retain)
#endif
}
}
// MARK NSError
extension OAuthSwiftError: CustomNSError {
public static var errorDomain: String { return OAuthSwiftError.Domain }
public var errorCode: Int { return self.code.rawValue }
/// The user-info dictionary.
public var errorUserInfo: [String : Any] {
switch self {
case .configurationError(let m): return ["message": m]
case .serverError(let m): return ["message": m]
case .requestCreation(let m): return ["message": m]
case .tokenExpired(let e): return ["error": e as Any]
case .requestError(let e, let request): return ["error": e, "request": request]
case .encodingError(let urlString): return ["url": urlString]
case .stateNotEqual(let s, let e): return ["state": s, "expected": e]
default: return [:]
}
}
public var _code: Int {
return self.code.rawValue
}
public var _domain: String {
return OAuthSwiftError.Domain
}
}
| mit | fdc7cec94834e67fad077f58592f760f | 32.607843 | 87 | 0.647413 | 4.992233 | false | true | false | false |
mlilback/rc2SwiftClient | Networking/AppFile.swift | 1 | 2099 | //
// File.swift
//
// Copyright © 2016 Mark Lilback. This file is licensed under the ISC license.
//
import Foundation
import Model
import ReactiveSwift
public final class AppFile: CustomStringConvertible, Hashable
{
public private(set) var model: File
public var fileId: Int { return model.id }
public var wspaceId: Int { return model.wspaceId }
public var name: String { return model.name }
public var version: Int { return model.version }
public var fileSize: Int { return model.fileSize }
public var dateCreated: Date { return model.dateCreated }
public var lastModified: Date { return model.lastModified }
public var fileType: FileType
static var dateFormatter: ISO8601DateFormatter = {
var df = ISO8601DateFormatter()
df.formatOptions = [.withInternetDateTime]
return df
}()
public init(model: File) {
self.model = model
guard let ft = FileType.fileType(forFileName: model.name) else {
fatalError("asked to create model for unsupported file type \(model.name)")
}
fileType = ft
}
//documentation inherited from protocol
public init(instance: AppFile) {
model = instance.model
fileType = instance.fileType
}
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
public var eTag: String { return "f/\(fileId)/\(version)" }
/// returns the file name w/o a file extension
public var baseName: String {
guard let idx = name.range(of: ".", options: .backwards) else { return name }
return String(name[idx.upperBound...])
}
/// Updates the file to match the current information
///
/// - Parameter to: latest information from the server
internal func update(to model: File) {
assert(fileId == model.id)
guard let ft = FileType.fileType(forFileName: model.name) else {
fatalError("asked to update unsupported file type \(model.name)")
}
self.model = model
fileType = ft
}
public var description: String {
return "<File: \(name) (\(fileId) v\(version))>"
}
public static func == (a: AppFile, b: AppFile) -> Bool {
return a.fileId == b.fileId && a.version == b.version
}
}
| isc | bbd496f187423b3aade39a57855c4826 | 27.351351 | 79 | 0.708294 | 3.706714 | false | false | false | false |
PartiallyFinite/SwiftDataStructures | Tests/Tests.swift | 1 | 6330 | //
// SwiftDataStructuresTests.swift
// SwiftDataStructuresTests
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Greg Omelaenko
//
// 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
import SwiftDataStructures
class SwiftDataStructuresTests: 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 testHeapSort() {
let x = [5, 7, 98, -178, -15, 36]
var a = x, b = x
a.sortInPlace()
b.heapsort(ascending: true)
XCTAssertEqual(a, b)
a = x
b = x
a[2...4].sortInPlace()
b.heapsort(2...4, ascending: true)
XCTAssertEqual(a, b)
}
func testPriorityQueue() {
var q = PriorityQueue<Int>()
q.insert(5)
q.insert(7)
q.insert(2)
XCTAssertEqual(q.remove(), 7)
XCTAssertEqual(q.remove(), 5)
XCTAssertEqual(q.remove(), 2)
XCTAssertEqual(q.pop(), nil)
q.insert(-9)
q.insert(8)
XCTAssertEqual(q.top, 8)
q.insert(17)
q.insert(-4)
XCTAssertEqual(q.remove(), 17)
XCTAssertEqual(q.remove(), 8)
XCTAssertEqual(q.remove(), -4)
XCTAssertEqual(q.remove(), -9)
}
func testRBTree() {
var nums = insertNumbers
var t = _RBTree<Int, ()>()
XCTAssert(t.first == nil)
XCTAssertEqual(t.startIndex, t.endIndex)
for i in nums {
t.insert(i, with: ())
}
nums.sortInPlace()
XCTAssert(t.map({ $0.0 }).elementsEqual(nums))
XCTAssertEqual(t[t.find(3)!].0, 3)
XCTAssertEqual(t.find(-1), nil)
XCTAssertEqual(t[t.lowerBound(-5)].0, 0)
XCTAssertEqual(t[t.lowerBound(32)].0, nums[nums.indexOf({ $0 >= 32 })!])
XCTAssertEqual(t[t.upperBound(3)].0, nums[nums.indexOf({ $0 > 3 })!])
XCTAssertEqual(t[t.upperBound(73)].0, nums[nums.indexOf({ $0 > 73 })!])
XCTAssertEqual(t.upperBound(100), t.endIndex)
XCTAssertEqual(t.lowerBound(101), t.endIndex)
XCTAssertEqual(t.minKey, 0)
XCTAssertEqual(t.maxKey, 100)
for _ in 0..<300 {
t.remove(t.endIndex.predecessor())
}
for n in nums[700..<1000] {
t.insert(n, with: ())
}
XCTAssert(nums.elementsEqual(t.map { $0.0 }))
for i in removeIndices {
let it = t.find(nums[i])!
XCTAssertEqual(t[it].0, nums[i])
t.remove(it)
nums.removeAtIndex(i)
XCTAssertEqual(t.count, nums.count)
XCTAssertEqual(t.last?.0, nums.last)
XCTAssertEqual(t.first?.0, nums.first)
XCTAssert(t.map({ $0.0 }).elementsEqual(nums))
}
}
func testRBTreeIndexing() {
var a = _RBTree<Int, ()>([1, 2, 3, 4, 5].map { ($0, ()) })
let i = a.find(3)!, j = a.find(2)!, k = a.find(5)!
a.remove(i)
XCTAssertEqual(a[j].0, 2)
XCTAssertEqual(a[k].0, 5)
var b = a
XCTAssertEqual(b[j].0, 2)
XCTAssertEqual(b[k].0, 5)
b.remove(j)
XCTAssert(b.elementsEqual([1, 4, 5].map { ($0, ()) }, isEquivalent: { $0.0 == $1.0 }))
}
func testOrderedDictionary() {
var a: OrderedDictionary = [5: "hello", 6: "aoeu", -1: ""]
XCTAssertEqual(a[5], "hello")
XCTAssertEqual(a[6], "aoeu")
XCTAssertEqual(a[-1], "")
a[2] = "htns"
XCTAssertEqual(a[2], "htns")
a[5] = "bye"
XCTAssertEqual(a[5], "bye")
a.removeValueForKey(6)
XCTAssertEqual(a.count, 3)
}
func testLinkedList() {
var a: List<Int> = [1, 2, 4, 8]
a.append(16)
XCTAssertEqual(a.count, 5)
var b = a
a.removeAtIndex(a.startIndex.advancedBy(2))
XCTAssert(a.elementsEqual([1, 2, 8, 16]))
b.insert(20, atIndex: b.startIndex.advancedBy(2))
XCTAssert(b.elementsEqual([1, 2, 20, 4, 8, 16]))
}
func testDequeMisc() {
var a = [1, 2, 3, 4, 5] as Deque<Int>
a.removeLast()
XCTAssert(a.elementsEqual(1...4))
a.prepend(0)
XCTAssert(a.elementsEqual(0...4))
a.append(5)
XCTAssert(a.elementsEqual(0...5))
var b = a
a.removeFirst()
XCTAssert(a.elementsEqual(1...5))
b.replaceRange(2...4, with: 2...82)
b.removeLast()
XCTAssert(b.elementsEqual(0...82))
b.removeAll(keepCapacity: true)
b.prepend(1)
XCTAssert(b.elementsEqual(1...1))
a.removeAll(keepCapacity: false)
a.appendContentsOf([5, 6, 7, 8])
XCTAssert(a.elementsEqual(5...8))
}
func testDequeRangeReplace() {
var d = Deque<Int>()
var a = Array<Int>()
for (_, (s, t, v)) in rangeReplaceInstructions.enumerate() {
a.replaceRange(s..<t, with: v)
d.replaceRange(s..<t, with: v)
if !a.elementsEqual(d) {
XCTFail("\(d) not equal to \(a).")
}
}
}
}
| mit | 0936da09aaf9839a870e28fd12907524 | 31.461538 | 111 | 0.570458 | 3.719154 | false | true | false | false |
ozpopolam/TrivialAsia | TrivialAsia/TriviaPresenter.swift | 1 | 5539 | //
// TriviaPresenter.swift
// TrivialAsia
//
// Created by Anastasia Stepanova-Kolupakhina on 25.05.17.
// Copyright © 2017 Anastasia Kolupakhina. All rights reserved.
//
import Foundation
class TriviaPresenter {
weak private var view: TriviaView?
private let triviaRepositoryService = TriviaRepositoryService()
private let triviaAPIService = TriviaAPIService()
private let amountOfTriviaToUpload = 20
private var triviaIsBeingLoded = false
private var token: TriviaToken?
private var triviaList = [Trivia]()
init() {
token = triviaRepositoryService.getTriviaToken()
}
func attachView(view: TriviaView) {
self.view = view
}
func detachView() {
self.view = nil
}
func getTriviaList() {
guard !triviaIsBeingLoded else { return }
triviaIsBeingLoded = true
view?.showNotification(TriviaViewNotification.isBeingLoaded)
getTriviaList(withAmount: amountOfTriviaToUpload) { triviaCompletion in
self.triviaIsBeingLoded = false
switch triviaCompletion {
case .failure(let triviaError):
switch triviaError {
case .networkTimeout, .noInternetConnection, .network:
self.view?.showNotification(TriviaViewNotification.checkInternetConnection)
case .responseCode:
self.view?.showNotification(TriviaViewNotification.sorryNoTrivia)
default:
break
}
case .success(let triviaList):
let triviaAdaptedList = triviaList.map { TriviaViewAdapted(fromTrivia: $0) }
self.view?.addTriviaAdaptedList(triviaAdaptedList)
}
}
}
func isAnswer(_ answer: String, correctForTriviaWithId triviaId: Int) -> Bool {
guard let trivia = triviaList.first(where: { $0.id == triviaId }) else {
return false
}
return trivia.isAnswerCorrect(answer)
}
func finishWIthTrivia(withId triviaId: Int) {
guard let index = triviaList.index(where: { $0.id == triviaId }) else { return }
let trivia = triviaList[index]
triviaRepositoryService.setAnswered(trivia)
triviaList.remove(at: index)
}
private func getToken(completionHandler: @escaping (TriviaToken?) -> Void) {
if let token = token, token.isValid {
completionHandler(token) // local token is still valid
return
}
triviaAPIService.getToken { triviaCompletion in
switch triviaCompletion {
case .success(let value):
let processedValue = self.processGetTokenSuccessValue(value)
completionHandler(processedValue)
case .failure:
completionHandler(nil)
}
}
}
private func processGetTokenSuccessValue(_ value: TriviaTokenResponse) -> TriviaToken {
token = value.token
triviaRepositoryService.setTriviaToken(value.token)
return value.token
}
private func getTriviaList(withAmount amount: Int, completionHandler: @escaping (TriviaCompletion<[Trivia]>) -> Void) {
getToken { token in
guard let token = token else {
let responseCodeError = TriviaError.responseCode(error: ResponseCode.tokenNotFound)
completionHandler(.failure(responseCodeError))
return
}
self.triviaAPIService.getTriviaList(withAmount: amount, andToken: token.value) { triviaCompletion in
switch triviaCompletion {
case .success(let value):
let processedValue = self.processGetTriviaListSuccessValue(value)
if processedValue.isEmpty {
let responseCodeError = TriviaError.responseCode(error: ResponseCode.noResults)
completionHandler(.failure(responseCodeError))
} else {
completionHandler(.success(processedValue))
}
case .failure(let triviaError):
if case .responseCode(let error) = triviaError, error == .tokenNotFound {
self.token = nil
self.getTriviaList(withAmount: amount, completionHandler: completionHandler)
} else {
completionHandler(.failure(triviaError))
}
}
}
}
}
private func processGetTriviaListSuccessValue(_ value: TriviaListResponse) -> [Trivia] {
let answeredTrivia = triviaRepositoryService.getAnsweredTrivia()
var newTrivia = [Trivia]()
for trivia in value.list {
if !triviaList.contains(where: { $0 == trivia }) && // new trivia shouldn't be in already exesting list
!answeredTrivia.contains(where: { $0 == trivia }) { // neither in answered ones
newTrivia.append(trivia)
}
}
guard newTrivia.count > 0 else { return [] }
triviaList.append(contentsOf: newTrivia)
return newTrivia
}
}
| mit | 5ef39e1275c0e4f1fc1637b284bf2def | 33.185185 | 123 | 0.568978 | 5.622335 | false | false | false | false |
kiliankoe/DVB | Sources/DVB/Models/Route/Request Settings/StandardSettings.swift | 1 | 1875 | extension Route {
public struct StandardSettings: Encodable {
//swiftlint:disable:next nesting
public enum MaxChangeCount: String, Encodable {
/// "Nur Direktverbindungen"
case none = "None"
case one = "One"
case two = "Two"
case unlimited = "Unlimited"
}
let maximumInterchangeCount: MaxChangeCount
//swiftlint:disable:next nesting
public enum WalkingSpeed: String, Encodable {
case verySlow = "VerySlow"
case slow = "Slow"
case normal = "Normal"
case fast = "Fast"
case veryFast = "VeryFast"
}
let walkingSpeed: WalkingSpeed
//swiftlint:disable:next nesting
public enum FootpathDistance: Int, Encodable {
case five = 5
case ten = 10
case fifteen = 15
case twenty = 20
case thirty = 30
}
let footpathDistanceToStop: FootpathDistance
let modes: [Mode]
/// "Nahegelegene Alternativhaltestellen einschließen"
let includeAlternativeStops: Bool
public static var `default`: StandardSettings {
return StandardSettings(maximumInterchangeCount: .unlimited,
walkingSpeed: .normal,
footpathDistanceToStop: .five,
modes: Mode.allRequest,
includeAlternativeStops: true)
}
//swiftlint:disable:next nesting
private enum CodingKeys: String, CodingKey {
case maximumInterchangeCount = "maxChanges"
case walkingSpeed
case footpathDistanceToStop = "footpathToStop"
case modes = "mot"
case includeAlternativeStops
}
}
}
| mit | 8c9b8419bf36a5b09765387d26860114 | 31.877193 | 72 | 0.549093 | 5.323864 | false | false | false | false |
Vienta/kuafu | kuafu/kuafu/src/Controller/KFLisenceViewController.swift | 1 | 2586 | //
// KFLisenceViewController.swift
// kuafu
//
// Created by Vienta on 15/7/18.
// Copyright (c) 2015年 www.vienta.me. All rights reserved.
//
import UIKit
class KFLisenceViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
var lisences: Array<String>!
@IBOutlet weak var tbvLisence: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "KF_SETTINGS_LISENCE".localized
self.lisences = ["FMDB","SnapKit","MGSwipeTableViewCell","CVCalendarKit","JTCalendar","MKEventKit","DAAlertController","DeviceGuru","ZoomTransition","NJKWebViewProgress"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UITableViewDelegate && UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.lisences.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Thanks for your opensource"
}
func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return "Generated by CocoaPods \n http://cocoapods.org"
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier: String = "KFLisenceCellIdentifier"
var lisenceCell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell
if (lisenceCell == nil) {
lisenceCell = UITableViewCell(style: .Value1, reuseIdentifier: cellIdentifier)
lisenceCell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
}
let cellContent: String = self.lisences[indexPath.row]
lisenceCell.textLabel?.text = cellContent
return lisenceCell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let cellContent: String = self.lisences[indexPath.row]
var lisenceDetailViewController: KFLisenceDetailViewController = KFLisenceDetailViewController(nibName: "KFLisenceDetailViewController", bundle: nil)
lisenceDetailViewController.lisenceName = cellContent
self.navigationController?.pushViewController(lisenceDetailViewController, animated: true)
}
}
| mit | 9c7491882e2c7bef5071a79a34c295ed | 38.753846 | 178 | 0.709365 | 5.4862 | false | false | false | false |
liruqi/actor-platform | actor-apps/app-ios/ActorCore/Providers/iOSNotificationProvider.swift | 9 | 3699 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
import AVFoundation
import AudioToolbox.AudioServices
@objc class iOSNotificationProvider: NSObject, ACNotificationProvider {
var internalMessage:SystemSoundID = 0
var sounds: [String: SystemSoundID] = [:]
var lastSoundPlay: Double = 0
override init() {
super.init()
let path = NSBundle.mainBundle().URLForResource("notification", withExtension: "caf");
AudioServicesCreateSystemSoundID(path!, &internalMessage)
}
func onMessageArriveInAppWithMessenger(messenger: ACMessenger!) {
let currentTime = NSDate().timeIntervalSinceReferenceDate
if (currentTime - lastSoundPlay > 0.2) {
AudioServicesPlaySystemSound(internalMessage)
lastSoundPlay = currentTime
}
}
func onNotificationWithMessenger(messenger: ACMessenger!, withTopNotifications topNotifications: JavaUtilList!, withMessagesCount messagesCount: jint, withConversationsCount conversationsCount: jint) {
let n = topNotifications.getWithInt(0) as! ACNotification
messenger.getFormatter().formatNotificationText(n)
var message = messenger.getFormatter().formatNotificationText(n)
if (!messenger.isShowNotificationsText()) {
message = NSLocalizedString("NotificationSecretMessage", comment: "New Message")
}
let senderUser = messenger.getUserWithUid(n.getSender())
var sender = senderUser.getNameModel().get()
let peer = n.getPeer()
if (UInt(peer.getPeerType().ordinal()) == ACPeerType.GROUP.rawValue) {
let group = messenger.getGroupWithGid(n.getPeer().getPeerId())
sender = "\(sender)@\(group.getNameModel().get())"
}
dispatchOnUi { () -> Void in
let localNotification = UILocalNotification ()
localNotification.alertBody = "\(sender): \(message)"
if (messenger.isNotificationSoundEnabled()) {
localNotification.soundName = "\(self.getNotificationSound(messenger)).caf"
}
localNotification.applicationIconBadgeNumber = Actor.getAppState().getGlobalCounter().get().integerValue
UIApplication.sharedApplication().presentLocalNotificationNow(localNotification)
}
}
func onUpdateNotificationWithMessenger(messenger: ACMessenger!, withTopNotifications topNotifications: JavaUtilList!, withMessagesCount messagesCount: jint, withConversationsCount conversationsCount: jint) {
// Not Supported
}
func hideAllNotifications() {
dispatchOnUi { () -> Void in
// Clearing notifications
let number = Actor.getAppState().getGlobalCounter().get().integerValue
UIApplication.sharedApplication().applicationIconBadgeNumber = 0 // If current value will equals to number + 1
UIApplication.sharedApplication().applicationIconBadgeNumber = number + 1
UIApplication.sharedApplication().applicationIconBadgeNumber = number
// Clearing local notifications
UIApplication.sharedApplication().cancelAllLocalNotifications()
}
}
func getNotificationSound(messenger: ACMessenger!) -> String {
if (messenger.getNotificationSound() != nil) {
let path = NSBundle.mainBundle().pathForResource(messenger.getNotificationSound(), ofType: "caf")
if (NSFileManager.defaultManager().fileExistsAtPath(path!)) {
return messenger.getNotificationSound()
}
}
return "iapetus"
}
}
| mit | 142863087f847826809fdf4726baa66c | 42.517647 | 211 | 0.667207 | 5.761682 | false | false | false | false |
auth0/Lock.iOS-OSX | LockTests/Presenters/BannerMessagePresenterSpec.swift | 1 | 2440 | // BannerMessagePresenterSpec.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.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 Quick
import Nimble
@testable import Lock
class BannerMessagePresenterSpec: QuickSpec {
override func spec() {
var root: UIView!
var presenter: BannerMessagePresenter!
beforeEach {
root = UIView(frame: .zero)
presenter = BannerMessagePresenter(root: root, messageView: nil)
}
describe("message presenter") {
it("should show success message") {
let message = "I.O.U. a message"
presenter.showSuccess(message)
expect(presenter.messageView?.message) == message
expect(presenter.messageView?.type) == .success
}
it("should show error message") {
let error = CredentialAuthError.couldNotLogin
presenter.showError(error)
expect(presenter.messageView?.message) == error.localizableMessage
expect(presenter.messageView?.type) == .failure
}
it("should hide message") {
let error = CredentialAuthError.couldNotLogin
presenter.showError(error)
presenter.hideCurrent()
expect(presenter.messageView).toEventually(beNil())
}
}
}
}
| mit | 8be536a09891d1b1e3409b1f462ebe77 | 36.538462 | 82 | 0.661475 | 5.030928 | false | false | false | false |
khizkhiz/swift | benchmark/single-source/unit-tests/StackPromo.swift | 2 | 748 | protocol Proto {
func at() -> Int
}
@inline(never)
func testStackAllocation(p: Proto) -> Int {
var a = [p, p, p]
var b = 0
a.withUnsafeMutableBufferPointer {
let array = $0
for i in 0..<array.count {
b += array[i].at()
}
}
return b
}
class Foo : Proto {
init() {}
func at() -> Int{
return 1
}
}
@inline(never)
func work(f: Foo) -> Int {
var r = 0
for _ in 0..<100_000 {
r += testStackAllocation(f)
}
return r
}
@inline(never)
func hole(use: Int, _ N: Int) {
if (N == 0) {
print("use: \(use)")
}
}
public func run_StackPromo(N: Int) {
let foo = Foo()
var r = 0
for i in 0..<N {
if i % 2 == 0 {
r += work(foo)
} else {
r -= work(foo)
}
}
hole(r, N)
}
| apache-2.0 | 5f1403c44b17a8851275045432c73ff0 | 13.384615 | 43 | 0.505348 | 2.760148 | false | false | false | false |
brl-x/TaskAPIUsingHeroku | Sources/App/Models/Task.swift | 1 | 2197 | //
// Task.swift
// App
//
// Created by Keith Moon on 18/09/2017.
//
import Foundation
import JSON
import FluentProvider
final class Task: JSONConvertible, Model {
// MARK: - Entity Conformance
var storage = Storage()
init(row: Row) throws {
description = try row.get("description")
category = try row.get("category")
}
func makeRow() throws -> Row {
var row = Row()
try row.set("id", id)
try row.set("description", description)
try row.set("category", category)
return row
}
// MARK: -
enum Error: Swift.Error {
case expectedJSONData
}
var description: String
var category: String
init(description: String, category: String) {
self.description = description
self.category = category
}
required init(json: JSON) throws {
guard
let description = json["description"]?.string,
let category = json["category"]?.string else {
throw Error.expectedJSONData
}
self.description = description
self.category = category
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("id", id)
try json.set("description", description)
try json.set("category", category)
return json
}
}
extension Task: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
builder.id()
builder.string("description")
builder.string("category")
}
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
extension Task: Updateable {
public static var updateableKeys: [UpdateableKey<Task>] {
return [UpdateableKey("description", String.self) { (task, description) in
task.description = description
},
UpdateableKey("category", String.self) { (task, category) in
task.category = category
}]
}
}
| mit | 4a0c43f23f95636b148df038ab6e06be | 22.37234 | 82 | 0.549386 | 4.817982 | false | false | false | false |
zane001/ZMTuan | ZMTuan/Controller/Home/DiscountOCViewController.swift | 1 | 3248 | //
// DiscountOCViewController.swift
// ZMTuan
//
// Created by zm on 4/25/16.
// Copyright © 2016 zm. All rights reserved.
//
import UIKit
class DiscountOCViewController: UITableViewController {
var ID: String!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 3fff5aeb654ae075dbcf693739e703fc | 32.474227 | 157 | 0.684324 | 5.531516 | false | false | false | false |
sebcode/SwiftHelperKit | Source/File-SHA256TreeHash.swift | 1 | 2974 | //
// File-SHA256TreeHash.swift
// SwiftHelperKit
//
// Copyright © 2015 Sebastian Volland. All rights reserved.
//
import Foundation
// http://spin.atomicobject.com/2015/02/23/c-libraries-swift/
import CommonCrypto
extension File {
public func getChunkSHA256Hashes(_ chunkSize: Int, progress: ((_ percentDone: Int) -> Bool)? = nil) throws -> [Data] {
let fileSize = size
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
guard fileSize > 0 else {
CC_SHA256(nil, 0, &hash);
let hashData = Data(bytes: hash, count: Int(CC_SHA256_DIGEST_LENGTH))
return [ hashData ]
}
let inputStream = try getInputStream()
var result = [Data]()
var buf = [UInt8](repeating: 0, count: chunkSize)
inputStream.open()
var bytesRead = 0
var totalBytesRead = 0
repeat {
if progress != nil {
let percentDone: Float = (Float(totalBytesRead) / Float(fileSize)) * 100.0
if progress!(Int(percentDone)) == false { return [] }
}
bytesRead = inputStream.read(&buf, maxLength: chunkSize)
if bytesRead < 0 {
throw FileError.fileNotReadable(file: name)
}
totalBytesRead += bytesRead
if bytesRead > 0 {
CC_SHA256(&buf, CC_LONG(bytesRead), &hash)
let hashData = Data(bytes: hash, count: Int(CC_SHA256_DIGEST_LENGTH))
result.append(hashData)
}
} while bytesRead > 0
return result
}
}
open class TreeHash {
open class func computeSHA256TreeHash(_ hashes: [Data]) -> String {
var prevLvlHashes = hashes
while prevLvlHashes.count > 1 {
var len = prevLvlHashes.count / 2
if prevLvlHashes.count % 2 != 0 {
len += 1
}
var currLvlHashes = [Data]()
var j = 0
for i in stride(from: 0, to: prevLvlHashes.count, by: 2) {
if prevLvlHashes.count - i > 1 {
let firstPart = prevLvlHashes[i]
let secondPart = prevLvlHashes[i + 1]
let concatenation = NSMutableData()
concatenation.append(firstPart)
concatenation.append(secondPart)
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
CC_SHA256(concatenation.bytes, CC_LONG(concatenation.length), &hash)
let hashData = Data(bytes: hash, count: Int(CC_SHA256_DIGEST_LENGTH))
currLvlHashes.insert(hashData, at: j)
} else {
currLvlHashes.insert(prevLvlHashes[i], at: j)
}
j += 1
}
prevLvlHashes = currLvlHashes
}
return prevLvlHashes[0].hexString()
}
}
| mit | e2f8b676f337b6249b80fe8ddc5c2b69 | 30.62766 | 122 | 0.534477 | 4.490937 | false | false | false | false |
suragch/Chimee-iOS | Chimee/UIMongolTableView.swift | 1 | 4208 |
import UIKit
@IBDesignable class UIMongolTableView: UIView {
// MARK:- Unique to TableView
// ********* Unique to TableView *********
fileprivate var view = UITableView()
fileprivate let rotationView = UIView()
fileprivate var userInteractionEnabledForSubviews = true
// read only refernce to the underlying tableview
var tableView: UITableView {
get {
return view
}
}
var tableFooterView: UIView? {
get {
return view.tableFooterView
}
set {
view.tableFooterView = newValue
}
}
func setup() {
// do any setup necessary
self.addSubview(rotationView)
rotationView.addSubview(view)
view.backgroundColor = self.backgroundColor
view.layoutMargins = UIEdgeInsets.zero
view.separatorInset = UIEdgeInsets.zero
}
// FIXME: @IBOutlet still can't be set in IB
@IBOutlet weak var delegate: UITableViewDelegate? {
get {
return view.delegate
}
set {
view.delegate = newValue
}
}
// FIXME: @IBOutlet still can't be set in IB
@IBOutlet weak var dataSource: UITableViewDataSource? {
get {
return view.dataSource
}
set {
view.dataSource = newValue
}
}
@IBInspectable var scrollEnabled: Bool {
get {
return view.isScrollEnabled
}
set {
view.isScrollEnabled = newValue
}
}
func scrollToRowAtIndexPath(_ indexPath: IndexPath, atScrollPosition: UITableViewScrollPosition, animated: Bool) {
view.scrollToRow(at: indexPath, at: atScrollPosition, animated: animated)
}
func registerClass(_ cellClass: AnyClass?, forCellReuseIdentifier identifier: String) {
view.register(cellClass, forCellReuseIdentifier: identifier)
}
func dequeueReusableCellWithIdentifier(_ identifier: String) -> UITableViewCell? {
return view.dequeueReusableCell(withIdentifier: identifier)
}
func reloadData() {
view.reloadData()
}
func insertRowsAtIndexPaths(_ indexPaths: [IndexPath], withRowAnimation animation: UITableViewRowAnimation) {
view.insertRows(at: indexPaths, with: animation)
}
func deleteRowsAtIndexPaths(_ indexPaths: [IndexPath], withRowAnimation animation: UITableViewRowAnimation) {
view.deleteRows(at: indexPaths, with: animation)
}
// MARK:- General code for Mongol views
// *******************************************
// ****** General code for Mongol views ******
// *******************************************
// This method gets called if you create the view in the Interface Builder
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// This method gets called if you create the view in code
override init(frame: CGRect){
super.init(frame: frame)
self.setup()
}
override func awakeFromNib() {
super.awakeFromNib()
self.setup()
}
override func layoutSubviews() {
super.layoutSubviews()
rotationView.transform = CGAffineTransform.identity
rotationView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: self.bounds.height, height: self.bounds.width))
rotationView.transform = translateRotateFlip()
view.frame = rotationView.bounds
}
func translateRotateFlip() -> CGAffineTransform {
var transform = CGAffineTransform.identity
// translate to new center
transform = transform.translatedBy(x: (self.bounds.width / 2)-(self.bounds.height / 2), y: (self.bounds.height / 2)-(self.bounds.width / 2))
// rotate counterclockwise around center
transform = transform.rotated(by: CGFloat(-M_PI_2))
// flip vertically
transform = transform.scaledBy(x: -1, y: 1)
return transform
}
}
| mit | dee9eb6e56c717535e39ba6e88bbb91d | 27.241611 | 148 | 0.584601 | 5.595745 | false | false | false | false |
kevin833752/DifferentWaysToPassValueSwift | DifferentWaysToPassValueSwift/DifferentWaysToPassValueSwift/KVOViewController.swift | 1 | 2738 | //
// KVOViewController.swift
// DifferentWaysToPassValueSwift
//
// Created by Linus on 15-9-2.
// Copyright (c) 2015年 Linus. All rights reserved.
//
import UIKit
// 要监听的对象的定义
class kvo: NSObject {
var ptitle : String = ""
// dynamic修饰的即为可支持KVO
dynamic var title : String {
get {
return self.ptitle
}
set {
self.ptitle = newValue
}
}
override init() {
print("init")
}
deinit {
print("deinit")
}
}
class KVOViewController: UIViewController {
var k = kvo() // 监听的对象
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
print("KVOViewController viewDidLoad")
self.view.backgroundColor = UIColor.whiteColor()
let tf:UITextField = UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 20))
tf.backgroundColor = UIColor.lightGrayColor()
tf.text = k.title
tf.tag = 10003
self.view.addSubview(tf)
// k.addObserver(self, forKeyPath: "title", options: NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old, context: nil)
let but:UIButton = UIButton(frame: CGRect(x: 20, y: 140, width: 50, height: 20))
but.setTitle("返回", forState: UIControlState.Normal)
but.backgroundColor = UIColor.lightGrayColor()
self.view.addSubview(but)
but.addTarget(self, action: "back:", forControlEvents: UIControlEvents.TouchUpInside)
}
func back(sender:UIButton) {
let tit = (self.view.viewWithTag(10003) as! UITextField).text
k.title = tit! // 对监听的属性赋值会触发observeValueForKeyPath方法
self.dismissViewControllerAnimated(true, completion: nil)
}
deinit {
// k.removeObserver(self, forKeyPath: "title", context: nil)
}
// override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
// println("observeValueForKeyPath")
// if keyPath == "title" {
// println(change)
// var newvalue: AnyObject? = change["new"]
// println("the new value is \(newvalue)")
// k.title = newvalue as String
// }
// }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.view.endEditing(true)
}
}
| mit | bc9146fdc1642cb55d32d850061a5a90 | 28.910112 | 158 | 0.613824 | 4.392739 | false | false | false | false |
WeltN24/Carlos | Tests/CarlosTests/ConditionedTwoWayTransformationBoxTests.swift | 1 | 21586 | import Foundation
import Nimble
import Quick
import Carlos
import Combine
final class ConditionedTwoWayTransformationBoxTests: QuickSpec {
override func spec() {
describe("Conditioned two-way transformation box") {
var box: ConditionedTwoWayTransformationBox<Int, NSURL, String>!
var error: Error!
var cancellable: AnyCancellable?
afterEach {
cancellable?.cancel()
cancellable = nil
}
context("when created through closures") {
beforeEach {
error = nil
box = ConditionedTwoWayTransformationBox<Int, NSURL, String>(conditionalTransformClosure: { key, value in
if key > 0 {
guard value.scheme == "http", let value = value.absoluteString else {
return Fail(error: TestError.simpleError).eraseToAnyPublisher()
}
return Just(value).setFailureType(to: Error.self).eraseToAnyPublisher()
} else {
return Fail(error: TestError.anotherError).eraseToAnyPublisher()
}
}, conditionalInverseTransformClosure: { key, value in
if key > 0 {
guard let value = NSURL(string: value) else {
return Fail(error: TestError.simpleError).eraseToAnyPublisher()
}
return Just(value).setFailureType(to: Error.self).eraseToAnyPublisher()
} else {
return Fail(error: TestError.anotherError).eraseToAnyPublisher()
}
})
}
context("when calling the conditional transformation") {
var result: String!
beforeEach {
result = nil
}
context("if the transformation is possible") {
let expectedResult = "http://www.google.de?test=1"
beforeEach {
cancellable = box.conditionalTransform(key: 1, value: NSURL(string: expectedResult)!)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should call the success closure") {
expect(result).toEventuallyNot(beNil())
}
it("should not call the failure closure") {
expect(error).toEventually(beNil())
}
it("should return the expected result") {
expect(result).toEventually(equal(expectedResult))
}
}
context("if the transformation is not possible") {
beforeEach {
cancellable = box.conditionalTransform(key: 1, value: NSURL(string: "ftp://google.de/robots.txt")!)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
it("should call the failure closure") {
expect(error).toEventuallyNot(beNil())
}
it("should pass the right error") {
expect(error as? TestError).toEventually(equal(TestError.simpleError))
}
}
context("if the key doesn't satisfy the condition") {
beforeEach {
cancellable = box.conditionalTransform(key: -1, value: NSURL(string: "ftp://google.de/robots.txt")!)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
it("should call the failure closure") {
expect(error).toEventuallyNot(beNil())
}
it("should pass the right error") {
expect(error as? TestError).toEventually(equal(TestError.anotherError))
}
}
}
context("when calling the conditional inverse transformation") {
var result: NSURL!
beforeEach {
result = nil
}
context("if the transformation is possible") {
let usedString = "http://www.google.de?test=1"
beforeEach {
cancellable = box.conditionalInverseTransform(key: 1, value: usedString)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should call the success closure") {
expect(result).toEventuallyNot(beNil())
}
it("should not call the failure closure") {
expect(error).toEventually(beNil())
}
it("should return the expected result") {
expect(result).toEventually(equal(NSURL(string: usedString)!))
}
}
context("if the transformation is not possible") {
beforeEach {
cancellable = box.conditionalInverseTransform(key: 1, value: "this is not a valid URL :'(")
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
it("should call the failure closure") {
expect(error).toEventuallyNot(beNil())
}
it("should pass the right error") {
expect(error as? TestError).toEventually(equal(TestError.simpleError))
}
}
context("if the key doesn't satisfy the condition") {
beforeEach {
cancellable = box.conditionalInverseTransform(key: -1, value: "http://validurl.de")
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
it("should call the failure closure") {
expect(error).toEventuallyNot(beNil())
}
it("should pass the right error") {
expect(error as? TestError).toEventually(equal(TestError.anotherError))
}
}
}
context("when inverting the transformer") {
var invertedBox: ConditionedTwoWayTransformationBox<Int, String, NSURL>!
beforeEach {
invertedBox = box.invert()
}
context("when calling the inverse transformation") {
var result: String!
beforeEach {
result = nil
}
context("if the transformation is possible") {
let expectedResult = "http://www.google.de?test=1"
beforeEach {
cancellable = invertedBox.conditionalInverseTransform(key: 1, value: NSURL(string: expectedResult)!)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should call the success closure") {
expect(result).toEventuallyNot(beNil())
}
it("should not call the failure closure") {
expect(error).toEventually(beNil())
}
it("should return the expected result") {
expect(result).toEventually(equal(expectedResult))
}
}
context("if the transformation is not possible") {
beforeEach {
cancellable = invertedBox.conditionalInverseTransform(key: 1, value: NSURL(string: "ftp://google.de/robots.txt")!)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
it("should call the failure closure") {
expect(error).toEventuallyNot(beNil())
}
it("should pass the right error") {
expect(error as? TestError).toEventually(equal(TestError.simpleError))
}
}
context("if the key doesn't satisfy the condition") {
beforeEach {
cancellable = invertedBox.conditionalInverseTransform(key: -1, value: NSURL(string: "ftp://google.de/robots.txt")!)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
it("should call the failure closure") {
expect(error).toEventuallyNot(beNil())
}
it("should pass the right error") {
expect(error as? TestError).toEventually(equal(TestError.anotherError))
}
}
}
context("when calling the conditional transformation") {
var result: NSURL!
beforeEach {
result = nil
}
context("if the transformation is possible") {
let usedString = "http://www.google.de?test=1"
beforeEach {
cancellable = invertedBox.conditionalTransform(key: 1, value: usedString)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should call the success closure") {
expect(result).toEventuallyNot(beNil())
}
it("should not call the failure closure") {
expect(error).toEventually(beNil())
}
it("should return the expected result") {
expect(result).toEventually(equal(NSURL(string: usedString)!))
}
}
context("if the transformation is not possible") {
beforeEach {
cancellable = invertedBox.conditionalTransform(key: 1, value: "this is not a valid URL :'(")
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
it("should call the failure closure") {
expect(error).toEventuallyNot(beNil())
}
it("should pass the right error") {
expect(error as? TestError).toEventually(equal(TestError.simpleError))
}
}
context("if the key doesn't satisfy the condition") {
beforeEach {
cancellable = invertedBox.conditionalTransform(key: -1, value: "http://validurl.de")
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
it("should call the failure closure") {
expect(error).toEventuallyNot(beNil())
}
it("should pass the right error") {
expect(error as? TestError).toEventually(equal(TestError.anotherError))
}
}
}
}
}
context("when created through a 2-way transformer") {
var originalTransformer: TwoWayTransformationBox<NSURL, String>!
beforeEach {
error = nil
originalTransformer = TwoWayTransformationBox(transform: { value in
guard value.scheme == "http", let value = value.absoluteString else {
return Fail(error: TestError.simpleError).eraseToAnyPublisher()
}
return Just(value).setFailureType(to: Error.self).eraseToAnyPublisher()
}, inverseTransform: { value in
guard let value = NSURL(string: value) else {
return Fail(error: TestError.simpleError).eraseToAnyPublisher()
}
return Just(value).setFailureType(to: Error.self).eraseToAnyPublisher()
})
box = ConditionedTwoWayTransformationBox<Int, NSURL, String>(transformer: originalTransformer)
}
context("when calling the conditional transformation") {
var result: String!
beforeEach {
result = nil
}
context("if the transformation is possible") {
let expectedResult = "http://www.google.de?test=1"
beforeEach {
cancellable = box.conditionalTransform(key: -1, value: NSURL(string: expectedResult)!)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should call the success closure") {
expect(result).toEventuallyNot(beNil())
}
it("should not call the failure closure") {
expect(error).toEventually(beNil())
}
it("should return the expected result") {
expect(result).toEventually(equal(expectedResult))
}
}
context("if the transformation is not possible") {
beforeEach {
cancellable = box.conditionalTransform(key: 1, value: NSURL(string: "ftp://google.de/robots.txt")!)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
it("should call the failure closure") {
expect(error).toEventuallyNot(beNil())
}
it("should pass the right error") {
expect(error as? TestError).toEventually(equal(TestError.simpleError))
}
}
}
context("when calling the conditional inverse transformation") {
var result: NSURL!
beforeEach {
result = nil
}
context("if the transformation is possible") {
let usedString = "http://www.google.de?test=1"
beforeEach {
cancellable = box.conditionalInverseTransform(key: -1, value: usedString)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should call the success closure") {
expect(result).toEventuallyNot(beNil())
}
it("should not call the failure closure") {
expect(error).toEventually(beNil())
}
it("should return the expected result") {
expect(result).toEventually(equal(NSURL(string: usedString)!))
}
}
context("if the transformation is not possible") {
beforeEach {
cancellable = box.conditionalInverseTransform(key: 1, value: "this is not a valid URL :'(")
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
it("should call the failure closure") {
expect(error).toEventuallyNot(beNil())
}
it("should pass the right error") {
expect(error as? TestError).toEventually(equal(TestError.simpleError))
}
}
}
context("when inverting the transformer") {
var invertedBox: ConditionedTwoWayTransformationBox<Int, String, NSURL>!
beforeEach {
invertedBox = box.invert()
}
context("when calling the inverse transformation") {
var result: String!
beforeEach {
result = nil
}
context("if the transformation is possible") {
let expectedResult = "http://www.google.de?test=1"
beforeEach {
cancellable = invertedBox.conditionalInverseTransform(key: 1, value: NSURL(string: expectedResult)!)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should call the success closure") {
expect(result).toEventuallyNot(beNil())
}
it("should not call the failure closure") {
expect(error).toEventually(beNil())
}
it("should return the expected result") {
expect(result).toEventually(equal(expectedResult))
}
}
context("if the transformation is not possible") {
beforeEach {
cancellable = invertedBox.conditionalInverseTransform(key: 1, value: NSURL(string: "ftp://google.de/robots.txt")!)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
it("should call the failure closure") {
expect(error).toEventuallyNot(beNil())
}
it("should pass the right error") {
expect(error as? TestError).toEventually(equal(TestError.simpleError))
}
}
}
context("when calling the conditional transformation") {
var result: NSURL!
beforeEach {
result = nil
}
context("if the transformation is possible") {
let usedString = "http://www.google.de?test=1"
beforeEach {
cancellable = invertedBox.conditionalTransform(key: 1, value: usedString)
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should call the success closure") {
expect(result).toEventuallyNot(beNil())
}
it("should not call the failure closure") {
expect(error).toEventually(beNil())
}
it("should return the expected result") {
expect(result).toEventually(equal(NSURL(string: usedString)!))
}
}
context("if the transformation is not possible") {
beforeEach {
cancellable = invertedBox.conditionalTransform(key: 1, value: "this is not a valid URL :'(")
.sink(receiveCompletion: { completion in
if case let .failure(e) = completion {
error = e
}
}, receiveValue: { result = $0 })
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
it("should call the failure closure") {
expect(error).toEventuallyNot(beNil())
}
it("should pass the right error") {
expect(error as? TestError).toEventually(equal(TestError.simpleError))
}
}
}
}
}
}
}
}
| mit | 54b9bd0ff9bd5d957f35353fa3b35329 | 33.317965 | 131 | 0.502502 | 5.679032 | false | true | false | false |
zhangchn/swelly | swelly/PTY.swift | 1 | 13881 | //
// PTY.swift
// swelly
//
// Created by ZhangChen on 05/10/2016.
//
//
import Foundation
import Darwin
protocol PTYDelegate: NSObjectProtocol {
func ptyWillConnect(_ pty: PTY)
func ptyDidConnect(_ pty: PTY)
func pty(_ pty: PTY, didRecv data: Data)
func pty(_ pty: PTY, willSend data: Data)
func ptyDidClose(_ pty: PTY)
}
func ctrlKey(_ c: String) throws -> UInt8 {
if let c = c.unicodeScalars.first {
if !c.isASCII {
throw NSError(domain: "PTY", code: 1, userInfo: nil)
}
return UInt8(c.value) - UInt8("A".unicodeScalars.first!.value + 1)
} else {
throw NSError(domain: "PTY", code: 2, userInfo: nil)
}
}
func fdZero(_ set: inout fd_set) {
set.fds_bits = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
}
func fdSet(_ fd: Int32, set: inout fd_set) {
let intOffset = Int(fd / 32)
let bitOffset = fd % 32
let mask: __int32_t = 1 << bitOffset
switch intOffset {
case 0: set.fds_bits.0 = set.fds_bits.0 | mask
case 1: set.fds_bits.1 = set.fds_bits.1 | mask
case 2: set.fds_bits.2 = set.fds_bits.2 | mask
case 3: set.fds_bits.3 = set.fds_bits.3 | mask
case 4: set.fds_bits.4 = set.fds_bits.4 | mask
case 5: set.fds_bits.5 = set.fds_bits.5 | mask
case 6: set.fds_bits.6 = set.fds_bits.6 | mask
case 7: set.fds_bits.7 = set.fds_bits.7 | mask
case 8: set.fds_bits.8 = set.fds_bits.8 | mask
case 9: set.fds_bits.9 = set.fds_bits.9 | mask
case 10: set.fds_bits.10 = set.fds_bits.10 | mask
case 11: set.fds_bits.11 = set.fds_bits.11 | mask
case 12: set.fds_bits.12 = set.fds_bits.12 | mask
case 13: set.fds_bits.13 = set.fds_bits.13 | mask
case 14: set.fds_bits.14 = set.fds_bits.14 | mask
case 15: set.fds_bits.15 = set.fds_bits.15 | mask
case 16: set.fds_bits.16 = set.fds_bits.16 | mask
case 17: set.fds_bits.17 = set.fds_bits.17 | mask
case 18: set.fds_bits.18 = set.fds_bits.18 | mask
case 19: set.fds_bits.19 = set.fds_bits.19 | mask
case 20: set.fds_bits.20 = set.fds_bits.20 | mask
case 21: set.fds_bits.21 = set.fds_bits.21 | mask
case 22: set.fds_bits.22 = set.fds_bits.22 | mask
case 23: set.fds_bits.23 = set.fds_bits.23 | mask
case 24: set.fds_bits.24 = set.fds_bits.24 | mask
case 25: set.fds_bits.25 = set.fds_bits.25 | mask
case 26: set.fds_bits.26 = set.fds_bits.26 | mask
case 27: set.fds_bits.27 = set.fds_bits.27 | mask
case 28: set.fds_bits.28 = set.fds_bits.28 | mask
case 29: set.fds_bits.29 = set.fds_bits.29 | mask
case 30: set.fds_bits.30 = set.fds_bits.30 | mask
case 31: set.fds_bits.31 = set.fds_bits.31 | mask
default: break
}
}
func fdIsset(_ fd: Int32, _ set: fd_set) -> Bool {
let a = fd / 32
let mask: Int32 = 1 << (fd % 32)
switch a {
case 0: return (set.fds_bits.0 & mask) != 0
case 1: return (set.fds_bits.1 & mask) != 0
case 2: return (set.fds_bits.2 & mask) != 0
case 3: return (set.fds_bits.3 & mask) != 0
case 4: return (set.fds_bits.4 & mask) != 0
case 5: return (set.fds_bits.5 & mask) != 0
case 6: return (set.fds_bits.6 & mask) != 0
case 7: return (set.fds_bits.7 & mask) != 0
case 8: return (set.fds_bits.8 & mask) != 0
case 9: return (set.fds_bits.9 & mask) != 0
case 10: return (set.fds_bits.10 & mask) != 0
case 11: return (set.fds_bits.11 & mask) != 0
case 12: return (set.fds_bits.12 & mask) != 0
case 13: return (set.fds_bits.13 & mask) != 0
case 14: return (set.fds_bits.14 & mask) != 0
case 15: return (set.fds_bits.15 & mask) != 0
case 16: return (set.fds_bits.16 & mask) != 0
case 17: return (set.fds_bits.17 & mask) != 0
case 18: return (set.fds_bits.18 & mask) != 0
case 19: return (set.fds_bits.19 & mask) != 0
case 20: return (set.fds_bits.20 & mask) != 0
case 21: return (set.fds_bits.21 & mask) != 0
case 22: return (set.fds_bits.22 & mask) != 0
case 23: return (set.fds_bits.23 & mask) != 0
case 24: return (set.fds_bits.24 & mask) != 0
case 25: return (set.fds_bits.25 & mask) != 0
case 26: return (set.fds_bits.26 & mask) != 0
case 27: return (set.fds_bits.27 & mask) != 0
case 28: return (set.fds_bits.28 & mask) != 0
case 29: return (set.fds_bits.29 & mask) != 0
case 30: return (set.fds_bits.30 & mask) != 0
case 31: return (set.fds_bits.31 & mask) != 0
default: break
}
return false
}
class PTY {
weak var delegate: PTYDelegate?
var proxyType: ProxyType
var proxyAddress: String
private var connecting = false
private var fd: Int32 = -1
private var pid: pid_t = 0
init(proxyAddress addr:String, proxyType type: ProxyType) {
proxyType = type
proxyAddress = addr
}
deinit {
close()
}
func close() {
if pid > 0 {
kill(pid, SIGKILL)
pid = 0
}
if fd >= 0 {
_ = Darwin.close(fd)
fd = -1
delegate?.ptyDidClose(self)
}
}
class func parse(addr: String) -> String {
var addr = addr.trimmingCharacters(in: CharacterSet.whitespaces)
if addr.contains(" ") {
return addr;
}
var ssh = false
var port: String? = nil
var fmt: String!
if addr.lowercased().hasPrefix("ssh://") {
ssh = true
let idx = addr.index(addr.startIndex, offsetBy: 6)
addr = String(addr[idx...])
} else {
if let range = addr.range(of: "://") {
addr = String(addr[range.upperBound...])
}
}
if let range = addr.range(of: ":") {
port = String(addr[range.upperBound...])
addr = String(addr[..<range.lowerBound])
}
if ssh {
if port == nil {
port = "22"
}
fmt = "ssh -o Protocol=2,1 -p %2$@ -x %1$@"
} else {
if port == nil {
port = "23"
}
if let range = addr.range(of: "@") {
addr = String(addr[range.upperBound...])
}
fmt = "/usr/bin/telnet -8 %@ -%@"
}
return String.init(format: fmt, addr, port!)
}
func connect(addr: String, connectionProtocol: ConnectionProtocol, userName: String!) -> Bool {
let slaveName = UnsafeMutablePointer<Int8>.allocate(capacity: Int(PATH_MAX))
let iflag = tcflag_t(bitPattern: Int(ICRNL | IXON | IXANY | IMAXBEL | BRKINT))
let oflag = tcflag_t(bitPattern: Int(OPOST | ONLCR))
let cflag = tcflag_t(bitPattern: Int(CREAD | CS8 | HUPCL))
let lflag = tcflag_t(bitPattern: Int(ICANON | ISIG | IEXTEN | ECHO | ECHOE | ECHOK | ECHOKE | ECHOCTL))
let controlCharacters : (cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t) = try! (ctrlKey("D"), 0xff, 0xff, 0x7f, ctrlKey("W"), ctrlKey("U"), ctrlKey("R"), 0, ctrlKey("C"), 0x1c, ctrlKey("Z"), ctrlKey("Y"), ctrlKey("Q"), ctrlKey("S"), 0xff, 0xff, 1, 0, 0xff, 0)
var term = termios(c_iflag: iflag,
c_oflag: oflag,
c_cflag: cflag,
c_lflag: lflag,
c_cc: controlCharacters,
c_ispeed: speed_t(B38400),
c_ospeed: speed_t(B38400))
let ws_col = GlobalConfig.sharedInstance.column
let ws_row = GlobalConfig.sharedInstance.row
var size = winsize(ws_row: UInt16(ws_row), ws_col: UInt16(ws_col), ws_xpixel: 0, ws_ypixel: 0)
//var arguments = PTY.parse(addr: addr).components(separatedBy: " ")
pid = forkpty(&fd, slaveName, &term, &size)
if pid < 0 {
print("Error forking pty: \(errno)")
} else if pid == 0 {
// child process
//kill(0, SIGSTOP)
var arguments: [String]
var hostAndPort = addr.split(separator: ":")
switch connectionProtocol {
case .telnet:
if hostAndPort.count == 2, let _ = Int(hostAndPort[1]) {
arguments = ["/usr/bin/telnet", "-8", String(hostAndPort[0]), String(hostAndPort[1])]
} else {
arguments = ["/usr/bin/telnet", "-8", String(hostAndPort[0])]
}
case .ssh:
if hostAndPort.count == 2 {
if let _ = Int(hostAndPort[1]) {
arguments = ["ssh", "-o", "Protocol=2,1", "-p", String(hostAndPort[1]), "-x", userName! + "@" + String(hostAndPort[0])]
} else {
arguments = ["ssh", "-o", "Protocol=2,1", "-p", "22", "-x", userName! + "@" + String(hostAndPort[0])]
}
} else {
arguments = ["ssh", "-o", "Protocol=2,1", "-p", "22", "-x", userName! + "@" + String(hostAndPort[0])]
}
if let proxyCommand = Proxy.proxyCommand(address: proxyAddress, type: proxyType) {
arguments.append("-o")
arguments.append(proxyCommand)
}
}
let argv = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: arguments.count + 1)
for (idx, arg) in arguments.enumerated() {
argv[idx] = arg.utf8CString.withUnsafeBytes({ (buf) -> UnsafeMutablePointer<Int8> in
let x = UnsafeMutablePointer<Int8>.allocate(capacity: buf.count + 1)
memcpy(x, buf.baseAddress, buf.count)
x[buf.count] = 0
return x
})
}
argv[arguments.count] = nil
execvp(argv[0], argv)
perror(argv[0])
sleep(UINT32_MAX)
} else {
// parent process
var one = 1
let result = ioctl(fd, TIOCPKT, &one)
if result == 0 {
Thread.detachNewThread {
self.readLoop()
}
} else {
print("ioctl failure: erron: \(errno)")
}
}
slaveName.deallocate()
connecting = true
delegate?.ptyWillConnect(self)
return true
}
func recv(data: Data) {
if connecting {
connecting = false
delegate?.ptyDidConnect(self)
}
delegate?.pty(self, didRecv: data)
}
func send(data: Data) {
guard fd >= 0 && !connecting else {
return
}
delegate?.pty(self, willSend: data)
var length = data.count
data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
var writefds = fd_set()
var errorfds = fd_set()
var timeout = timeval()
var chunkSize: Int
var msg = bytes.baseAddress!
while length > 0 {
// bzero(&writefds, MemoryLayout<fd_set>.size)
// bzero(&errorfds, MemoryLayout<fd_set>.size)
fdZero(&writefds)
fdZero(&errorfds)
fdSet(fd, set: &writefds)
fdSet(fd, set: &errorfds)
timeout.tv_sec = 0
timeout.tv_usec = 100000
let result = select(fd + 1, nil, &writefds, &errorfds, &timeout)
if result == 0 {
NSLog("timeout")
break
} else if result < 0 {
self.close()
break
}
if length > 4096 {
chunkSize = 4096
} else {
chunkSize = length
}
let size = write(fd, bytes.baseAddress!, chunkSize)
if size < 0 {
break
}
msg = msg.advanced(by: size)
length -= size
}
}
}
func readLoop() {
var readfds = fd_set()
var errorfds = fd_set()
var exit = false
let buf = UnsafeMutablePointer<Int8>.allocate(capacity: 4096)
var iterationCount = 0
let result = autoreleasepool { () -> Int32 in
var result = Int32(0)
while !exit {
iterationCount += 1
fdZero(&readfds)
fdZero(&errorfds)
fdSet(fd, set: &readfds)
fdSet(fd, set: &errorfds)
result = select(fd.advanced(by: 1), &readfds, nil, &errorfds, nil)
if result < 0 {
print("")
break
} else if fdIsset(fd, errorfds) {
result = Int32(read(fd, buf, 1))
if result == 0 {
exit = true
}
} else if fdIsset(fd, readfds) {
result = Int32(read(fd, buf, 4096))
if result > 1 {
let d = Data(buffer: UnsafeBufferPointer<Int8>(start: buf.advanced(by: 1), count: Int(result)-1))
DispatchQueue.main.async {
self.recv(data: d)
}
} else if result == 0 {
exit = true
}
}
}
return result
}
if result >= 0 {
DispatchQueue.main.async {
self.close()
}
}
buf.deallocate()
}
}
| gpl-2.0 | 6ab3e62ed175d7c0066d979e0c40f3ac | 36.415094 | 340 | 0.493048 | 3.662533 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/CartCustomDiscountAllocation.swift | 1 | 4075 | //
// CartCustomDiscountAllocation.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// The discounts automatically applied to the cart line based on prerequisites
/// that have been met.
open class CartCustomDiscountAllocationQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = CartCustomDiscountAllocation
/// The discounted amount that has been applied to the cart line.
@discardableResult
open func discountedAmount(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> CartCustomDiscountAllocationQuery {
let subquery = MoneyV2Query()
subfields(subquery)
addField(field: "discountedAmount", aliasSuffix: alias, subfields: subquery)
return self
}
/// The title of the allocated discount.
@discardableResult
open func title(alias: String? = nil) -> CartCustomDiscountAllocationQuery {
addField(field: "title", aliasSuffix: alias)
return self
}
}
/// The discounts automatically applied to the cart line based on prerequisites
/// that have been met.
open class CartCustomDiscountAllocation: GraphQL.AbstractResponse, GraphQLObject, CartDiscountAllocation {
public typealias Query = CartCustomDiscountAllocationQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "discountedAmount":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CartCustomDiscountAllocation.self, field: fieldName, value: fieldValue)
}
return try MoneyV2(fields: value)
case "title":
guard let value = value as? String else {
throw SchemaViolationError(type: CartCustomDiscountAllocation.self, field: fieldName, value: fieldValue)
}
return value
default:
throw SchemaViolationError(type: CartCustomDiscountAllocation.self, field: fieldName, value: fieldValue)
}
}
/// The discounted amount that has been applied to the cart line.
open var discountedAmount: Storefront.MoneyV2 {
return internalGetDiscountedAmount()
}
func internalGetDiscountedAmount(alias: String? = nil) -> Storefront.MoneyV2 {
return field(field: "discountedAmount", aliasSuffix: alias) as! Storefront.MoneyV2
}
/// The title of the allocated discount.
open var title: String {
return internalGetTitle()
}
func internalGetTitle(alias: String? = nil) -> String {
return field(field: "title", aliasSuffix: alias) as! String
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "discountedAmount":
response.append(internalGetDiscountedAmount())
response.append(contentsOf: internalGetDiscountedAmount().childResponseObjectMap())
default:
break
}
}
return response
}
}
}
| mit | a34836efdca265ee56328556a9a50ad7 | 35.711712 | 126 | 0.739632 | 4.391164 | false | false | false | false |
hnag409/HIITTimer | HIITimer/UserRoutine.swift | 1 | 626 | //
// UserRoutine.swift
// HIITimer
//
// Created by hannah gaskins on 7/1/16.
// Copyright © 2016 hannah gaskins. All rights reserved.
//
import UIKit
class UserRoutine {
static let shared = UserRoutine() // singleton
var sets = 0
var activeTime = 0
var restTime = 0
init() {}
// sets the UserRoutine variables, and holds object settings no matter where we are in the app
func setUserRoutine(sets: Int, activeTime: Int, restTime: Int) {
self.sets = sets
self.activeTime = activeTime
self.restTime = restTime
}
}
| mit | ab88641f0978ba9dab346e82bf65a4f7 | 18.53125 | 98 | 0.6 | 3.955696 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios | Frameworks/TBAData/Sources/MyTBA/Favorite.swift | 1 | 3269 | import CoreData
import Foundation
import MyTBAKit
@objc(Favorite)
public class Favorite: MyTBAEntity {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Favorite> {
return NSFetchRequest<Favorite>(entityName: Favorite.entityName)
}
}
extension Favorite {
/**
Insert Favorites with values from myTBA Favorite models in to the managed object context.
This method manages deleting old Favorites.
- Parameter favories: The myTBA Favorite representations to set values from.
- Parameter context: The NSManagedContext to insert the Favorite in to.
- Returns: The array of inserted Favorites.
*/
@discardableResult
public static func insert(_ favories: [MyTBAFavorite], in context: NSManagedObjectContext) -> [Favorite] {
// Fetch all of the previous Favorites
let oldFavorites = Favorite.fetch(in: context)
// Insert new Favorites
let favories = favories.map({
return Favorite.insert($0, in: context)
})
// Delete orphaned Favorites
Set(oldFavorites).subtracting(Set(favories)).forEach({
context.delete($0)
})
return favories
}
/**
Insert a Favorite with values from a myTBA Favorite model in to the managed object context.
- Parameter model: The myTBA Favorite representation to set values from.
- Parameter context: The NSManagedContext to insert the Favorite in to.
- Returns: The inserted Favorite.
*/
@discardableResult
public static func insert(_ model: MyTBAFavorite, in context: NSManagedObjectContext) -> Favorite {
return insert(modelKey: model.modelKey, modelType: model.modelType, in: context)
}
@discardableResult
public static func insert(modelKey: String, modelType: MyTBAModelType, in context: NSManagedObjectContext) -> Favorite {
let predicate = favoritePredicate(modelKey: modelKey, modelType: modelType)
return findOrCreate(in: context, matching: predicate) { (favorite) in
// Required: key, type
favorite.modelKeyRaw = modelKey
favorite.modelTypeRaw = NSNumber(value: modelType.rawValue)
}
}
}
extension Favorite {
static func favoritePredicate(modelKey: String, modelType: MyTBAModelType) -> NSPredicate {
return NSPredicate(format: "%K == %@ && %K == %ld",
#keyPath(Favorite.modelKeyRaw), modelKey,
#keyPath(Favorite.modelTypeRaw), modelType.rawValue)
}
public static func fetch(modelKey: String, modelType: MyTBAModelType, in context: NSManagedObjectContext) -> Favorite? {
let predicate = favoritePredicate(modelKey: modelKey, modelType: modelType)
return findOrFetch(in: context, matching: predicate)
}
public static func favoriteTeamKeys(in context: NSManagedObjectContext) -> [String] {
return Favorite.fetch(in: context, configurationBlock: { (fetchRequest) in
fetchRequest.predicate = NSPredicate(format: "%K == %ld",
#keyPath(Favorite.modelTypeRaw), MyTBAModelType.team.rawValue)
}).compactMap({ $0.modelKey })
}
}
extension Favorite: MyTBAManaged {}
| mit | 64f9d971f180972e534d2dc7bf17cadc | 33.776596 | 124 | 0.669012 | 5.148031 | false | false | false | false |
rudedogg/XNeovim | Sources/XNeovim.swift | 1 | 2599 | import AppKit
import SwiftNeoVim
var sharedPlugin: XNeovim?
class XNeovim: NSObject {
var bundle: Bundle
class func pluginDidLoad(_ bundle: Bundle) {
print("🔌XNeovim|✅: pluginDidLoad called.")
guard let bundleIdentifier = Bundle.main.bundleIdentifier else {
print("🔌XNeovim|⛔️: Bundle identifier is nil. Not loading plugin.")
return
}
guard bundleIdentifier == "com.apple.dt.Xcode" else {
print("🔌XNeovim|⛔️: Bundle identifier doesn't match 'com.apple.dt.Xcode'. Not loading plugin.")
return
}
if sharedPlugin == nil {
sharedPlugin = XNeovim(bundle: bundle)
print("🔌XNeovim|✅: Set sharedPlugin variable.")
}
}
init(bundle: Bundle) {
self.bundle = bundle
super.init()
// Add an observer so we get notified when Xcode is actually loaded
NotificationCenter.default.addObserver(self, selector: #selector(self.xcodeDidFinishLaunching), name: NSNotification.Name.NSApplicationDidFinishLaunching, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private dynamic func xcodeDidFinishLaunching() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NSApplicationDidFinishLaunching, object: nil)
initializePlugin()
}
private func initializePlugin() {
configureMenuItems()
let version = bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") ?? "⛔️ Unknown"
print("🔌XNeovim|✅: Plugin initialized!")
print("🔌XNeovim|✅: Plugin Version \(version)")
print("🔌XNeovim|✅: SwiftNeoVim Framework Version \(SwiftNeoVimVersionNumber)")
}
private func configureMenuItems() {
guard let mainMenu = NSApp.mainMenu else { return }
guard let editItem = mainMenu.item(withTitle: "Edit") else { return }
guard let submenu = editItem.submenu else { return }
let pluginMenuItem = NSMenuItem(title:"🔌 XNeovim", action: nil, keyEquivalent:"")
submenu.addItem(pluginMenuItem)
let pluginMenu = NSMenu(title: "🔌 XNeovim")
let aboutMenuItem = NSMenuItem(title: "About", action: #selector(self.aboutMenuAction), keyEquivalent: "")
aboutMenuItem.target = self
pluginMenu.addItem(aboutMenuItem)
submenu.setSubmenu(pluginMenu, for: pluginMenuItem)
}
dynamic private func aboutMenuAction() {
let version = bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") ?? "⛔️ Unknown"
let alert = NSAlert()
alert.messageText = "XNeovim version \(version)"
alert.alertStyle = .informational
alert.runModal()
}
}
| mit | a1bca8106884e920040349f0336a4bf9 | 32.946667 | 171 | 0.711705 | 4.688766 | false | false | false | false |
niceagency/Base | Base/NetworkTransformers.swift | 1 | 1617 | //
// NetworkTransformers.swift
// Base
//
// Created by Tim Searle on 19/02/2018.
// Copyright © 2018 Nice Agency. All rights reserved.
//
import Foundation
public extension URLRequest {
public func appending(headers: [(String, String)]) -> URLRequest {
var copy = self
headers.forEach { header, value in
copy.addValue(value, forHTTPHeaderField: header)
}
return copy
}
public func modifying(cachePolicy: NSURLRequest.CachePolicy) -> URLRequest {
var copy = self
copy.cachePolicy = cachePolicy
return copy
}
}
public extension URLComponents {
public func replacing(queryItems: [URLQueryItem]?) -> URLComponents {
var copy = self
copy.queryItems = queryItems
return copy
}
public func appending(queryItems: [URLQueryItem]) -> URLComponents {
var copy = self
let existingQueryItems = self.queryItems ?? []
copy.queryItems = existingQueryItems + queryItems
return copy
}
public func modifying(scheme: String?) -> URLComponents {
var copy = self
copy.scheme = scheme
return copy
}
public func modifying(port: Int?) -> URLComponents {
var copy = self
copy.port = port
return copy
}
public func modifying(path: String) -> URLComponents {
var copy = self
copy.path = path
return copy
}
public func modifying(host: String?) -> URLComponents {
var copy = self
copy.host = host
return copy
}
}
| mit | 3be936ba359666ccb375ff2620ec6f15 | 23.484848 | 80 | 0.597772 | 4.957055 | false | false | false | false |
zhugejunwei/Algorithms-in-Java-Swift-CPP | Sort algorithms/Insertion Sort.swift | 1 | 383 | import Darwin
func insertionSort(inout arr: [Int]) {
var curV, lastKey: Int
for i in 1..<arr.count {
curV = arr[i]
lastKey = i - 1
while lastKey >= 0 && arr[lastKey] > curV {
arr[lastKey + 1] = arr[lastKey]
lastKey -= 1
}
arr[lastKey + 1] = curV
}
}
var a = [1,4,1,2,5,8,7,0]
insertionSort(&a)
| mit | ac560286f9b49a3199f0b0bdc6db7acc | 18.15 | 51 | 0.48564 | 3.139344 | false | false | false | false |
Urinx/SublimeCode | Sublime/Sublime/SublimeSafari.swift | 1 | 2796 | //
// SublimeSafari.swift
// Sublime
//
// Created by Eular on 4/19/16.
// Copyright © 2016 Eular. All rights reserved.
//
import UIKit
import WebKit
class SublimeSafari: UIViewController, WKNavigationDelegate {
let popupMenu = PopupMenu()
let url: NSURL
var webView: WKWebView!
var progressBar: UIProgressView!
init(URL: NSURL) {
url = URL
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Constant.CapeCod
self.automaticallyAdjustsScrollViewInsets = false
// 设置分享菜单
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Action, target: popupMenu, action: #selector(popupMenu.showUp))
popupMenu.controller = self
popupMenu.itemsToShare = [url]
webView = WKWebView()
webView.frame = CGRectMake(0, 0, view.width, view.height - Constant.NavigationBarOffset)
webView.backgroundColor = UIColor.clearColor()
webView.scrollView.backgroundColor = UIColor.clearColor()
webView.navigationDelegate = self
view.addSubview(webView)
if let host = url.host {
let hostLB = UILabel()
hostLB.frame = CGRectMake(0, 10, view.width, 20)
hostLB.text = "网页由 \(host) 提供"
hostLB.font = hostLB.font.fontWithSize(12)
hostLB.textAlignment = .Center
hostLB.textColor = UIColor.grayColor()
webView.addSubview(hostLB)
webView.sendSubviewToBack(hostLB)
}
progressBar = UIProgressView()
progressBar.frame = CGRectMake(0, 0, view.width, 0)
progressBar.progress = 0
progressBar.progressTintColor = UIColor.greenColor()
progressBar.trackTintColor = UIColor.clearColor()
webView.addSubview(progressBar)
webView.loadRequest(NSURLRequest(URL: url))
webView.allowsBackForwardNavigationGestures = true
}
// 准备加载页面
func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
progressBar.setProgress(0.5, animated: true)
}
// 已开始加载页面
func webView(webView: WKWebView, didCommitNavigation navigation: WKNavigation!) {
progressBar.setProgress(0.9, animated: true)
}
// 页面已全部加载
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
if title == nil {
title = webView.title
}
progressBar.removeFromSuperview()
}
}
| gpl-3.0 | c0d903b0de8b10d357bb1a2671ab23fc | 30.77907 | 145 | 0.635931 | 4.951087 | false | false | false | false |
popwarsweet/MessageDispatcher | MessageDispatcher/Classes/MessageDispatcher.swift | 1 | 3593 | //
// MessageDispatcher.swift
//
//
// Created by Kyle Zaragoza on 2/17/17.
// Copyright © 2017 Kyle Zaragoza. All rights reserved.
//
import Foundation
/// Contains the closure and queue that the message should be dispatched on.
final public class HandlerWrapper<T> {
let handler: ((_ object: T) -> Void)
var queue: DispatchQueue?
init(handler: @escaping ((_ object: T) -> Void), queue: DispatchQueue? = nil) {
self.handler = handler
self.queue = queue
}
}
/// Used for weakly wrapping listeners.
final public class WeakWrapper<T: AnyObject>: Hashable {
weak var value: T?
init (value: T) {
self.value = value
}
public var hashValue: Int {
return ObjectIdentifier(self).hashValue
}
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
public static func ==(lhs: WeakWrapper<T>, rhs: WeakWrapper<T>) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
/// The class for managing event listeners as well as dispatching messages.
final class MessageDispatcher<MessageType> {
typealias ListenerType = WeakWrapper<AnyObject>
typealias MessageHandler<T> = ((_ object: T) -> Void)
/// Dictionary of listeners as keys, and wrapped handlers as their values.
/// - NOTE: Once a listener (key) is released, the table will not immediately be resized. Do not rely on the count of `listeners` to accurately reflect the number of listeners.
private(set) var listeners = [ListenerType: HandlerWrapper<MessageType>]()
/// Removes all keys that have nil values.
func resize() {
let nilListeners = Array(listeners.keys.filter { $0.value == nil })
nilListeners.forEach { self.listeners.removeValue(forKey: $0) }
}
/// Alerts all listeners of the given message.
///
/// - Parameter message: The message to send to the listeners.
func alertListeners(_ message: MessageType) {
var needsResizing = false
// Alert all non-nil listeners.
for (k, v) in listeners {
guard k.value != nil else {
// Flag that listeners needs resizing.
needsResizing = true
continue
}
if let queue = v.queue {
queue.async { v.handler(message) }
} else {
v.handler(message)
}
}
// Resize if need be.
if needsResizing { resize() }
}
/// Adds a closure to be called when messages are dispatched.
///
/// - Parameters:
/// - listener: The object which is listening to messagse, this object is weakly held.
/// - queue: The queue to have the handler called on, specify nil to be called on the calling queue.
/// - handler: The closure to be called when the dispatcher alerts all listeners.
func addEventListener(_ listener: AnyObject, queue: DispatchQueue?, handler: @escaping MessageHandler<MessageType>) {
// wrap in a class so we can store it in a MapTable
let handlerWrapper = HandlerWrapper<MessageType>(handler: handler, queue: queue)
let weakListener = WeakWrapper(value: listener)
listeners[weakListener] = handlerWrapper
}
/// Removes a listener from the dispatcher
///
/// - Parameter listener: This object to be removed.
func removeEventListener(_ listener: AnyObject) {
listeners.keys.filter {
$0.value === listener
}.forEach {
listeners[$0] = nil
}
}
}
| mit | 99a5dda01120a02df4ba3d08ed35f131 | 34.215686 | 180 | 0.624443 | 4.558376 | false | false | false | false |
liwenban/uploadDemo | uploadDemo/Pods/Alamofire/Source/NetworkReachabilityManager.swift | 117 | 9068 | //
// NetworkReachabilityManager.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if !os(watchOS)
import Foundation
import SystemConfiguration
/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and
/// WiFi network interfaces.
///
/// Reachability can be used to determine background information about why a network operation failed, or to retry
/// network requests when a connection is established. It should not be used to prevent a user from initiating a network
/// request, as it's possible that an initial request may be required to establish reachability.
public class NetworkReachabilityManager {
/// Defines the various states of network reachability.
///
/// - unknown: It is unknown whether the network is reachable.
/// - notReachable: The network is not reachable.
/// - reachable: The network is reachable.
public enum NetworkReachabilityStatus {
case unknown
case notReachable
case reachable(ConnectionType)
}
/// Defines the various connection types detected by reachability flags.
///
/// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi.
/// - wwan: The connection type is a WWAN connection.
public enum ConnectionType {
case ethernetOrWiFi
case wwan
}
/// A closure executed when the network reachability status changes. The closure takes a single argument: the
/// network reachability status.
public typealias Listener = (NetworkReachabilityStatus) -> Void
// MARK: - Properties
/// Whether the network is currently reachable.
public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
/// Whether the network is currently reachable over the WWAN interface.
public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) }
/// Whether the network is currently reachable over Ethernet or WiFi interface.
public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) }
/// The current network reachability status.
public var networkReachabilityStatus: NetworkReachabilityStatus {
guard let flags = self.flags else { return .unknown }
return networkReachabilityStatusForFlags(flags)
}
/// The dispatch queue to execute the `listener` closure on.
public var listenerQueue: DispatchQueue = DispatchQueue.main
/// A closure executed when the network reachability status changes.
public var listener: Listener?
private var flags: SCNetworkReachabilityFlags? {
var flags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(reachability, &flags) {
return flags
}
return nil
}
private let reachability: SCNetworkReachability
private var previousFlags: SCNetworkReachabilityFlags
// MARK: - Initialization
/// Creates a `NetworkReachabilityManager` instance with the specified host.
///
/// - parameter host: The host used to evaluate network reachability.
///
/// - returns: The new `NetworkReachabilityManager` instance.
public convenience init?(host: String) {
guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
self.init(reachability: reachability)
}
/// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0.
///
/// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
/// status of the device, both IPv4 and IPv6.
///
/// - returns: The new `NetworkReachabilityManager` instance.
public convenience init?() {
var address = sockaddr_in()
address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
address.sin_family = sa_family_t(AF_INET)
guard let reachability = withUnsafePointer(to: &address, { pointer in
return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size) {
return SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else { return nil }
self.init(reachability: reachability)
}
private init(reachability: SCNetworkReachability) {
self.reachability = reachability
self.previousFlags = SCNetworkReachabilityFlags()
}
deinit {
stopListening()
}
// MARK: - Listening
/// Starts listening for changes in network reachability status.
///
/// - returns: `true` if listening was started successfully, `false` otherwise.
@discardableResult
public func startListening() -> Bool {
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = Unmanaged.passUnretained(self).toOpaque()
let callbackEnabled = SCNetworkReachabilitySetCallback(
reachability,
{ (_, flags, info) in
let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(info!).takeUnretainedValue()
reachability.notifyListener(flags)
},
&context
)
let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
listenerQueue.async {
self.previousFlags = SCNetworkReachabilityFlags()
self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
}
return callbackEnabled && queueEnabled
}
/// Stops listening for changes in network reachability status.
public func stopListening() {
SCNetworkReachabilitySetCallback(reachability, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachability, nil)
}
// MARK: - Internal - Listener Notification
func notifyListener(_ flags: SCNetworkReachabilityFlags) {
guard previousFlags != flags else { return }
previousFlags = flags
listener?(networkReachabilityStatusForFlags(flags))
}
// MARK: - Internal - Network Reachability Status
func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
guard isNetworkReachable(with: flags) else { return .notReachable }
var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi)
#if os(iOS)
if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) }
#endif
return networkStatus
}
func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool {
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic)
let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired)
return isReachable && (!needsConnection || canConnectWithoutUserInteraction)
}
}
// MARK: -
extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
/// Returns whether the two network reachability status values are equal.
///
/// - parameter lhs: The left-hand side value to compare.
/// - parameter rhs: The right-hand side value to compare.
///
/// - returns: `true` if the two values are equal, `false` otherwise.
public func ==(
lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
-> Bool
{
switch (lhs, rhs) {
case (.unknown, .unknown):
return true
case (.notReachable, .notReachable):
return true
case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)):
return lhsConnectionType == rhsConnectionType
default:
return false
}
}
#endif
| apache-2.0 | 8fc1b534e195729240881cf42b13b47e | 37.918455 | 122 | 0.70644 | 5.416965 | false | false | false | false |
Webtrekk/webtrekk-ios-sdk | Source/Internal/Utility/Migration.swift | 1 | 7207 | import Foundation
internal struct Migration {
internal let appVersion: String?
internal let everId: String
internal let isOptedOut: Bool?
internal let isSampling: Bool?
internal let requestQueue: [URL]?
internal let samplingRate: Int?
internal static func migrateFromLibraryV3(webtrekkId: String) -> Migration? {
#if os(iOS)
let fileManager = FileManager.default
let userDefaults = Foundation.UserDefaults.standard
let cachesDirectory = try? fileManager.url(for: .cachesDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
let documentDirectory = try? fileManager.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
let libraryDirectory = try? fileManager.url(for: .libraryDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
let everIdFileV2 = documentDirectory?.appendingPathComponent("webtrekk-id")
let everIdFileV3 = libraryDirectory?.appendingPathComponent("webtrekk-id")
let requestQueueFileV2 = cachesDirectory?.appendingPathComponent("webtrekk-\(webtrekkId)")
let requestQueueFileV3 = cachesDirectory?.appendingPathComponent("webtrekk-queue")
let samplingFileV2 = documentDirectory?.appendingPathComponent("webtrekk-sampling")
let samplingFileV3 = libraryDirectory?.appendingPathComponent("webtrekk-sampling")
let appVersionFileV2 = documentDirectory?.appendingPathComponent("webtrekk-app-version")
let appVersionFileV3 = libraryDirectory?.appendingPathComponent("webtrekk-app-version")
defer {
let files = [everIdFileV2,
everIdFileV3,
requestQueueFileV2,
requestQueueFileV3,
samplingFileV2,
samplingFileV3,
appVersionFileV2,
appVersionFileV3].filterNonNil()
for file in files where fileManager.itemExistsAtURL(file) {
do {
try fileManager.removeItem(at: file)
} catch let error {
logWarning("Cannot remove \(file) of previous Webtrekk Library version: \(error)")
}
}
userDefaults.removeObject(forKey: "Webtrekk.optedOut")
}
let everId: String
var encoding = String.Encoding.utf8
if let file = everIdFileV3, let _everId = (try? String(contentsOf: file,
usedEncoding: &encoding))?.nonEmpty {
everId = _everId
} else if let file = everIdFileV2, let _everId = (try? String(contentsOf: file,
usedEncoding: &encoding))?.nonEmpty {
everId = _everId
} else {
return nil
}
let requestQueue: [URL]?
if let file = requestQueueFileV3, let _requestQueue = NSKeyedUnarchiver.unarchive(file: file) as? [String] {
requestQueue = _requestQueue.map({ URL(string: $0) }).filterNonNil()
} else if let file = requestQueueFileV2, let _requestQueue = NSKeyedUnarchiver.unarchive(file: file) as? [String] {
requestQueue = _requestQueue.map({ URL(string: $0) }).filterNonNil()
} else {
requestQueue = nil
}
let isSampling: Bool?
let samplingRate: Int?
if let file = samplingFileV3,
let string = try? String(contentsOf: file, usedEncoding: &encoding),
let (_isSampling, _samplingRate) = parseSampling(string) {
isSampling = _isSampling
samplingRate = _samplingRate
} else if let file = samplingFileV2,
let string = try? String(contentsOf: file, usedEncoding: &encoding),
let (_isSampling, _samplingRate) = parseSampling(string) {
isSampling = _isSampling
samplingRate = _samplingRate
} else {
isSampling = nil
samplingRate = nil
}
let appVersion: String?
if let file = appVersionFileV3,
let _appVersion = (try? String(contentsOf: file, usedEncoding: &encoding))?.nonEmpty {
appVersion = _appVersion
} else if let file = appVersionFileV2,
let _appVersion = (try? String(contentsOf: file, usedEncoding: &encoding))?.nonEmpty {
appVersion = _appVersion
} else {
appVersion = nil
}
let isOptedOut = userDefaults.object(forKey: "Webtrekk.optedOut") as? Bool
return Migration(
appVersion: appVersion,
everId: everId,
isOptedOut: isOptedOut,
isSampling: isSampling,
requestQueue: requestQueue,
samplingRate: samplingRate
)
#else
return nil
#endif
}
fileprivate static func parseSampling(_ string: String) -> (isSampling: Bool, samplingRate: Int)? {
let components = string.components(separatedBy: "|")
guard components.count == 2 else {
return nil
}
guard let isSampling = Int(components[0]),
let samplingRate = Int(components[1]), isSampling == 1 || isSampling == 0 else {
return nil
}
return (isSampling: isSampling == 1, samplingRate: samplingRate)
}
}
extension Migration: CustomStringConvertible {
internal var description: String {
return "Migration(\n"
+ "\teverId: \(everId.simpleDescription)\n"
+ "\tappVersion: \(appVersion.simpleDescription)\n"
+ "\tisOptedOut: \(isOptedOut.simpleDescription)\n"
+ "\tisSampling: \(isSampling.simpleDescription)\n"
+ "\trequestQueueSize: \((requestQueue?.count).simpleDescription)\n"
+ "\tsamplingRate: \(samplingRate.simpleDescription)\n"
+ ")"
}
}
extension NSKeyedUnarchiver {
static func unarchive(file: URL) -> AnyObject? {
guard let data = try? Data(contentsOf: file) else {
return nil
}
return unarchive(data: data)
}
static func unarchive(data: Data) -> AnyObject? {
return unarchiveObject(with: data) as AnyObject?
}
}
| mit | 32f904eba76f2daee0b2c6b3253c7af8 | 41.394118 | 127 | 0.527543 | 6.046141 | false | false | false | false |
bigxodus/candlelight | candlelight/screen/main/model/Community.swift | 1 | 1854 |
import Foundation
enum Community: Int {
case CLIEN
case DDANZI
case TODAY_HUMOR
case PPOMPPU
case INVEN
case RULIWEB
case MLBPARK
case TOTAL_COUNT
}
func name(_ community: Community?) -> String {
let sites = [
"클리앙",
"딴지일보",
"오늘의유머",
"뽐뿌",
"인벤",
"루리웹",
"엠팍"
]
let idx = community?.rawValue ?? -1
if (0 > idx || sites.count <= idx) {
return "UNKNOWN"
}
return sites[idx]
}
func boardCrawler(_ community: Community?) -> BoardCrawler {
let crawlers: [() -> BoardCrawler] = [
{() in return ClienParkBoardCrawler()},
{() in return DdanziBoardCrawler()},
{() in return TodayHumorBoardCrawler()},
{() in return PpomppuBoardCrawler()},
{() in return InvenBoardCrawler()},
{() in return RuliwebBoardCrawler()},
{() in return MlbparkBoardCrawler()}
]
let idx = community?.rawValue ?? -1
if (0 > idx || crawlers.count <= idx) {
return ClienParkBoardCrawler()
}
return crawlers[idx]()
}
//community
func articleCrawler(_ community: Community?, _ url: String) -> ArticleCrawler {
let crawlers: [(String) -> ArticleCrawler] = [
{(url) in return ClienParkArticleCrawler(url)},
{(url) in return DdanziArticleCrawler(url)},
{(url) in return TodayHumorArticleCrawler(url)},
{(url) in return PpomppuArticleCrawler(url)},
{(url) in return InvenArticleCrawler(url)},
{(url) in return RuliwebArticleCrawler(url)},
{(url) in return MlbparkArticleCrawler(url)}
]
let idx = community?.rawValue ?? -1
if (0 > idx || crawlers.count <= idx) {
return ClienParkArticleCrawler(url)
}
return crawlers[idx](url)
}
| apache-2.0 | 7f346f67752bfc3105d95ec422cc3442 | 26.044776 | 79 | 0.577263 | 3.814737 | false | false | false | false |
VidyasagarMSC/NearBY | openWhiskAction/SendLocationUpdate.swift | 1 | 576 | func main(args: [String:Any]) -> [String:Any] {
let deviceAarray = args["deviceIds"] as? String;
let location = args["location"] as? String;
let appID = args["appID"] as? String;
let appSecret = args["appSecret"] as? String;
let message = "Reached \(location!). Lets check the best Restaurants."
let devArray = [deviceAarray!]
let result = Whisk.invoke(actionNamed:"/whisk.system/pushnotifications/sendMessage",withParameters:["appSecret":appSecret!,"appId":appID!,"text":message,"deviceIds":devArray])
return [ "Result" : result ]
}
| apache-2.0 | de53f60568a63d4290d39bd78d6a1fb0 | 47 | 179 | 0.673611 | 3.865772 | false | false | false | false |
iOSTestApps/PhoneBattery | PhoneBattery WatchKit Extension/InterfaceController.swift | 1 | 3415 | //
// InterfaceController.swift
// PhoneBattery WatchKit Extension
//
// Created by Marcel Voss on 19.06.15.
// Copyright (c) 2015 Marcel Voss. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
let device = UIDevice.currentDevice()
var batteryLevel : Float?
var batteryState : UIDeviceBatteryState!
@IBOutlet weak var percentageLabel: WKInterfaceLabel!
@IBOutlet weak var statusLabel: WKInterfaceLabel!
@IBOutlet weak var groupItem: WKInterfaceGroup!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
device.batteryMonitoringEnabled = true
batteryLevel = device.batteryLevel
batteryState = device.batteryState
groupItem.setBackgroundImageNamed("frame-")
let level = batteryLevel! * 100
if level > 0 {
groupItem.startAnimatingWithImagesInRange(NSMakeRange(0, Int(level)+1), duration: 1, repeatCount: 1)
} else {
groupItem.startAnimatingWithImagesInRange(NSMakeRange(0, Int(level)), duration: 1, repeatCount: 1)
}
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
self.setTitle(NSLocalizedString("Battery", comment: ""))
device.batteryMonitoringEnabled = true
batteryLevel = device.batteryLevel
batteryState = device.batteryState
// KVO for oberserving battery level and state
NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryLevelChanged:", name: UIDeviceBatteryLevelDidChangeNotification, object: device)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "batteryStateChanged:", name: UIDeviceBatteryStateDidChangeNotification, object: device)
percentageLabel.setText(String(format: "%.f%%", batteryLevel! * 100))
statusLabel.setText(self.stringForBatteryState(batteryState))
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
func stringForBatteryState(batteryState: UIDeviceBatteryState) -> String {
if batteryState == UIDeviceBatteryState.Full {
return NSLocalizedString("FULL", comment: "")
} else if batteryState == UIDeviceBatteryState.Charging {
return NSLocalizedString("CHARGING", comment: "")
} else if batteryState == UIDeviceBatteryState.Unplugged {
return NSLocalizedString("REMAINING", comment: "")
} else {
// State is unknown
return NSLocalizedString("UNKNOWN", comment: "")
}
}
func batteryLevelChanged(notification: NSNotification) {
batteryLevel = device.batteryLevel
let level = Int(batteryLevel!) * 100
percentageLabel.setText(String(format: "%.f%%", batteryLevel! * 100))
groupItem.startAnimatingWithImagesInRange(NSRange(location: 0, length: level), duration: 1, repeatCount: 1)
}
func batteryStateChanged(notification: NSNotification) {
batteryState = device.batteryState
stringForBatteryState(batteryState)
}
}
| mit | 48a26297d96c2f03b956d89a8465b734 | 36.527473 | 161 | 0.674671 | 5.758853 | false | false | false | false |
fulldecent/FSLineChart | Sources/FSLineChart/BoundsCalculator.swift | 1 | 3231 | //
// BoundsCalculator.swift
// FSLineChart
//
// Created by Yaroslav Zhurakovskiy on 25.11.2019.
// Copyright © 2019 William Entriken. All rights reserved.
//
import CoreGraphics
import Foundation
class BoundsCalculator {
private(set) var min: Double = Double.greatestFiniteMagnitude
private(set) var max: Double = -Double.greatestFiniteMagnitude
func computeBounds(data: [Double], verticalGridStep: Int) {
min = Double.greatestFiniteMagnitude
max = -Double.greatestFiniteMagnitude
for number in data {
if number < min {
min = number
}
if number > max {
max = number
}
}
// The idea is to adjust the minimun and the maximum value to display the whole chart in the view, and if possible with nice "round" steps.
max = getUpperRoundNumber(max, forGridStep: verticalGridStep)
if min < 0 {
// If the minimum is negative then we want to have one of the step to be zero so that the chart is displayed nicely and more comprehensively
var step: Double
if verticalGridStep > 3 {
step = abs(max - min) / Double(verticalGridStep - 1)
} else {
step = Swift.max(abs(max - min) / 2, Swift.max(abs(min), abs(max)))
}
step = getUpperRoundNumber(step, forGridStep: verticalGridStep)
var newMin: Double
var newMax: Double
if abs(min) > abs(max) {
let m = ceil(abs(min) / step)
newMin = step * Double(m) * (min > 0 ? 1 : -1)
newMax = step * (Double(verticalGridStep) - m) * (max > 0 ? 1 : -1)
} else {
let m = ceil(abs(max) / step)
newMax = step * Double(m) * (max > 0 ? 1 : -1)
newMin = step * (Double(verticalGridStep) - m) * (min > 0 ? 1 : -1)
}
if min < newMin {
newMin -= step
newMax -= step
}
if max > newMax + step {
newMin += step
newMax += step
}
min = newMin
max = newMax
if max < min {
// TODO: use swap
let tmp = max
max = min
min = tmp
}
}
// No data
if max.isNaN {
max = 1
}
}
func getUpperRoundNumber(
_ value: Double,
forGridStep gridStep: Int
) -> Double {
guard value > 0 else {
return 0
}
// We consider a round number the following by 0.5 step instead of true round number (with step of 1)
let logValue = log10(value);
let scale = pow(10, floor(logValue));
var n = ceil(value / scale * 4);
let tmp = Int(n) % gridStep;
if tmp != 0 {
n += Double(gridStep - tmp)
}
return n * scale / 4.0
}
}
extension BoundsCalculator {
var minVerticalBound: CGFloat {
return CGFloat(Swift.min(min, 0))
}
var maxVerticalBound: CGFloat {
return CGFloat(Swift.max(max, 0))
}
}
| apache-2.0 | 917475dca369aecc022136a0bb958d43 | 26.372881 | 151 | 0.508978 | 4.376694 | false | false | false | false |
Johennes/firefox-ios | Utils/DynamicFontHelper.swift | 1 | 5718 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
let NotificationDynamicFontChanged: String = "NotificationDynamicFontChanged"
private let iPadFactor: CGFloat = 1.06
private let iPhoneFactor: CGFloat = 0.88
class DynamicFontHelper: NSObject {
static var defaultHelper: DynamicFontHelper {
struct Singleton {
static let instance = DynamicFontHelper()
}
return Singleton.instance
}
override init() {
defaultStandardFontSize = UIFontDescriptor.preferredFontDescriptorWithTextStyle(UIFontTextStyleBody).pointSize // 14pt -> 17pt -> 23pt
deviceFontSize = defaultStandardFontSize * (UIDevice.currentDevice().userInterfaceIdiom == .Pad ? iPadFactor : iPhoneFactor)
defaultMediumFontSize = UIFontDescriptor.preferredFontDescriptorWithTextStyle(UIFontTextStyleFootnote).pointSize // 12pt -> 13pt -> 19pt
defaultSmallFontSize = UIFontDescriptor.preferredFontDescriptorWithTextStyle(UIFontTextStyleCaption2).pointSize // 11pt -> 11pt -> 17pt
super.init()
}
/**
* Starts monitoring the ContentSizeCategory chantes
*/
func startObserving() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(DynamicFontHelper.SELcontentSizeCategoryDidChange(_:)), name: UIContentSizeCategoryDidChangeNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/**
* Device specific
*/
private var deviceFontSize: CGFloat
var DeviceFontSize: CGFloat {
return deviceFontSize
}
var DeviceFont: UIFont {
return UIFont.systemFontOfSize(deviceFontSize, weight: UIFontWeightMedium)
}
var DeviceFontLight: UIFont {
return UIFont.systemFontOfSize(deviceFontSize, weight: UIFontWeightLight)
}
var DeviceFontSmall: UIFont {
return UIFont.systemFontOfSize(deviceFontSize - 1, weight: UIFontWeightMedium)
}
var DeviceFontSmallLight: UIFont {
return UIFont.systemFontOfSize(deviceFontSize - 1, weight: UIFontWeightLight)
}
var DeviceFontSmallHistoryPanel: UIFont {
return UIFont.systemFontOfSize(deviceFontSize - 3, weight: UIFontWeightLight)
}
var DeviceFontHistoryPanel: UIFont {
return UIFont.systemFontOfSize(deviceFontSize)
}
var DeviceFontSmallBold: UIFont {
return UIFont.boldSystemFontOfSize(deviceFontSize - 1)
}
var DeviceFontMedium: UIFont {
return UIFont.systemFontOfSize(deviceFontSize + 1)
}
var DeviceFontMediumBold: UIFont {
return UIFont.boldSystemFontOfSize(deviceFontSize + 1)
}
var DeviceFontMediumBoldActivityStream: UIFont {
return UIFont.systemFontOfSize(deviceFontSize + 2, weight: UIFontWeightHeavy)
}
var DeviceFontSmallActivityStream: UIFont {
return UIFont.systemFontOfSize(deviceFontSize - 2, weight: UIFontWeightMedium)
}
var DeviceFontDescriptionActivityStream: UIFont {
return UIFont.systemFontOfSize(deviceFontSize - 2, weight: UIFontWeightRegular)
}
/**
* Small
*/
private var defaultSmallFontSize: CGFloat
var DefaultSmallFontSize: CGFloat {
return defaultSmallFontSize
}
var DefaultSmallFont: UIFont {
return UIFont.systemFontOfSize(defaultSmallFontSize, weight: UIFontWeightRegular)
}
var DefaultSmallFontBold: UIFont {
return UIFont.boldSystemFontOfSize(defaultSmallFontSize)
}
/**
* Medium
*/
private var defaultMediumFontSize: CGFloat
var DefaultMediumFontSize: CGFloat {
return defaultMediumFontSize
}
var DefaultMediumFont: UIFont {
return UIFont.systemFontOfSize(defaultMediumFontSize, weight: UIFontWeightRegular)
}
var DefaultMediumBoldFont: UIFont {
return UIFont.boldSystemFontOfSize(defaultMediumFontSize)
}
/**
* Standard
*/
private var defaultStandardFontSize: CGFloat
var DefaultStandardFontSize: CGFloat {
return defaultStandardFontSize
}
var DefaultStandardFont: UIFont {
return UIFont.systemFontOfSize(defaultStandardFontSize, weight: UIFontWeightRegular)
}
var DefaultStandardFontBold: UIFont {
return UIFont.boldSystemFontOfSize(defaultStandardFontSize)
}
/**
* Reader mode
*/
var ReaderStandardFontSize: CGFloat {
return defaultStandardFontSize - 2
}
var ReaderBigFontSize: CGFloat {
return defaultStandardFontSize + 5
}
/**
* Intro mode
*/
var IntroStandardFontSize: CGFloat {
return defaultStandardFontSize - 1
}
var IntroBigFontSize: CGFloat {
return defaultStandardFontSize + 1
}
func refreshFonts() {
defaultStandardFontSize = UIFontDescriptor.preferredFontDescriptorWithTextStyle(UIFontTextStyleBody).pointSize
deviceFontSize = defaultStandardFontSize * (UIDevice.currentDevice().userInterfaceIdiom == .Pad ? iPadFactor : iPhoneFactor)
defaultMediumFontSize = UIFontDescriptor.preferredFontDescriptorWithTextStyle(UIFontTextStyleFootnote).pointSize
defaultSmallFontSize = UIFontDescriptor.preferredFontDescriptorWithTextStyle(UIFontTextStyleCaption2).pointSize
}
func SELcontentSizeCategoryDidChange(notification: NSNotification) {
refreshFonts()
let notification = NSNotification(name: NotificationDynamicFontChanged, object: nil)
NSNotificationCenter.defaultCenter().postNotification(notification)
}
}
| mpl-2.0 | bdbc0155d131d9866d5e6ab95aac001c | 34.7375 | 201 | 0.721231 | 6.108974 | false | false | false | false |
finder39/Swignals | Source/Swignal2Args.swift | 1 | 1426 | //
// Swignal2Args.swift
// Plug
//
// Created by Joseph Neuman on 7/3/16.
// Copyright © 2016 Plug. All rights reserved.
//
import Foundation
open class Swignal2Args<A,B>: SwignalBase {
public override init() {
}
open func addObserver<L: AnyObject>(_ observer: L, callback: @escaping (_ observer: L, _ arg1: A, _ arg2: B) -> ()) {
let observer = Observer2Args(swignal: self, observer: observer, callback: callback)
addSwignalObserver(observer)
}
open func fire(_ arg1: A, arg2: B) {
synced(self) {
for watcher in self.swignalObservers {
watcher.fire(arg1, arg2)
}
}
}
}
private class Observer2Args<L: AnyObject,A,B>: ObserverGenericBase<L> {
let callback: (_ observer: L, _ arg1: A, _ arg2: B) -> ()
init(swignal: SwignalBase, observer: L, callback: @escaping (_ observer: L, _ arg1: A, _ arg2: B) -> ()) {
self.callback = callback
super.init(swignal: swignal, observer: observer)
}
override func fire(_ args: Any...) {
if let arg1 = args[0] as? A,
let arg2 = args[1] as? B {
fire(arg1: arg1, arg2: arg2)
} else {
assert(false, "Types incorrect")
}
}
fileprivate func fire(arg1: A, arg2: B) {
if let observer = observer {
callback(observer, arg1, arg2)
}
}
}
| mit | 12ecdbc8d38aca51239112ed9a19e1f9 | 26.403846 | 121 | 0.553684 | 3.47561 | false | false | false | false |
kumabook/StickyNotesiOS | StickyNotes/PageStickyTableViewCell.swift | 1 | 2407 | //
// PageStickyTableViewCell.swift
// StickyNotes
//
// Created by Hiroki Kumamoto on 8/13/16.
// Copyright © 2016 kumabook. All rights reserved.
//
import UIKit
class PageStickyTableViewCell: UITableViewCell {
@IBOutlet weak var editButton: UIButton!
@IBOutlet weak var contentTextView: UITextView!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
weak var delegate: PageStickyTableViewController?
var sticky: StickyEntity?
var tagLabels: [UILabel] = []
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
@IBAction func editButtonTapped(_ sender: AnyObject) {
guard let sticky = sticky else { return }
delegate?.editButtonTapped(sticky)
}
func updateView(_ sticky: StickyEntity) {
self.sticky = sticky
separatorInset = UIEdgeInsets.zero
preservesSuperviewLayoutMargins = false
layoutMargins = UIEdgeInsets.zero
contentTextView.text = sticky.content.characters.count > 0 ? sticky.content : "No content".localize()
contentTextView.textContainerInset = UIEdgeInsets.zero
contentTextView.textContainer.lineFragmentPadding = 0
contentTextView.isUserInteractionEnabled = false
locationLabel.text = "position: (\(sticky.left),\(sticky.top))"
locationLabel.textColor = UIColor.themeColor
dateLabel.text = sticky.updatedAt.passedTime
dateLabel.textColor = UIColor.themeColor
tagLabels.forEach { $0.removeFromSuperview() }
tagLabels.removeAll()
// editButton.titleLabel?.text = "Edit".localize()
let margins = layoutMarginsGuide
let _ = sticky.tags.reduce((anchor: layoutMarginsGuide.leadingAnchor, margin: 14.0 as CGFloat)) { (prev, tag) in
let label = TagLabel()
label.text = tag.name
label.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(label)
self.tagLabels.append(label)
label.leadingAnchor.constraint(equalTo: prev.anchor, constant: prev.margin).isActive = true
label.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true
return (anchor: label.trailingAnchor, margin: 8.0)
}
}
}
| mit | ff20743e8a13e8789b677452ce2dfa4a | 36.015385 | 120 | 0.681214 | 5.002079 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/Views/MemberLlistView.swift | 1 | 7967 | //
// MemberLlistView.swift
// Habitica
//
// Created by Phillip Thelen on 02.05.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import PinLayout
class MemberListView: UIView {
var viewTapped: (() -> Void)?
var moreButtonTapped: (() -> Void)?
let avatarView: AvatarView = AvatarView()
let displayNameLabel: UsernameLabel = UsernameLabel()
let sublineLabel: UILabel = {
let view = UILabel()
view.font = UIFont.systemFont(ofSize: 12)
view.textColor = ThemeService.shared.theme.ternaryTextColor
return view
}()
let healthBar: ProgressBar = {
let view = ProgressBar()
if ThemeService.shared.theme.isDark {
view.barColor = UIColor.red50
} else {
view.barColor = UIColor.red100
}
return view
}()
let healthLabel: UILabel = {
let view = UILabel()
view.font = UIFont.systemFont(ofSize: 12)
view.textColor = ThemeService.shared.theme.ternaryTextColor
return view
}()
let experienceBar: ProgressBar = {
let view = ProgressBar()
if ThemeService.shared.theme.isDark {
view.barColor = UIColor.yellow10
} else {
view.barColor = UIColor.yellow50
}
return view
}()
let experienceLabel: UILabel = {
let view = UILabel()
view.font = UIFont.systemFont(ofSize: 12)
view.textColor = ThemeService.shared.theme.ternaryTextColor
return view
}()
let manaBar: ProgressBar = {
let view = ProgressBar()
if ThemeService.shared.theme.isDark {
view.barColor = UIColor.blue50
} else {
view.barColor = UIColor.blue100
}
return view
}()
let manaLabel: UILabel = {
let view = UILabel()
view.font = UIFont.systemFont(ofSize: 12)
view.textColor = ThemeService.shared.theme.ternaryTextColor
return view
}()
let classIconView = UIImageView()
let buffIconView = UIImageView(image: HabiticaIcons.imageOfBuffIcon)
let leaderView: UILabel = {
let view = UILabel()
view.font = UIFont.systemFont(ofSize: 12)
view.textColor = ThemeService.shared.theme.dimmedTextColor
view.backgroundColor = ThemeService.shared.theme.offsetBackgroundColor
view.cornerRadius = 10
view.textAlignment = .center
view.text = L10n.leader
return view
}()
let moreButton: UIButton = {
let button = UIButton()
button.backgroundColor = .clear
button.setImage(Asset.moreInteractionsIcon.image, for: .normal)
button.tintColor = ThemeService.shared.theme.tintColor
button.addTarget(self, action: #selector(onMoreButtonTapped), for: .touchUpInside)
return button
}()
func configure(member: MemberProtocol, isLeader: Bool) {
avatarView.avatar = AvatarViewModel(avatar: member)
displayNameLabel.text = member.profile?.name
displayNameLabel.contributorLevel = member.contributor?.level ?? 0
leaderView.isHidden = !isLeader
if let stats = member.stats {
healthBar.maxValue = CGFloat(stats.maxHealth)
healthBar.value = CGFloat(stats.health)
healthLabel.text = "\(Int(stats.health)) / \(Int(stats.maxHealth))"
experienceBar.maxValue = CGFloat(stats.toNextLevel)
experienceBar.value = CGFloat(stats.experience)
experienceLabel.text = "\(Int(stats.experience)) / \(Int(stats.toNextLevel))"
manaBar.maxValue = CGFloat(stats.maxMana)
manaBar.value = CGFloat(stats.mana)
manaLabel.text = "\(Int(stats.mana)) / \(Int(stats.maxMana))"
if member.hasHabiticaClass, let habiticaClass = HabiticaClass(rawValue: stats.habitClass ?? "") {
switch habiticaClass {
case .warrior:
classIconView.image = HabiticaIcons.imageOfWarriorLightBg
case .mage:
classIconView.image = HabiticaIcons.imageOfMageLightBg
case .healer:
classIconView.image = HabiticaIcons.imageOfHealerLightBg
case .rogue:
classIconView.image = HabiticaIcons.imageOfRogueLightBg
}
}
if let username = member.username {
sublineLabel.text = "@\(username) · Lvl \(stats.level)"
} else {
sublineLabel.text = "Lvl \(stats.level)"
}
buffIconView.isHidden = stats.buffs?.isBuffed != true
}
setNeedsLayout()
}
init() {
super.init(frame: CGRect.zero)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
addSubview(avatarView)
addSubview(displayNameLabel)
addSubview(leaderView)
addSubview(sublineLabel)
addSubview(healthBar)
addSubview(healthLabel)
addSubview(experienceBar)
addSubview(experienceLabel)
addSubview(manaBar)
addSubview(manaLabel)
addSubview(classIconView)
addSubview(buffIconView)
addSubview(moreButton)
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapView)))
}
override func layoutSubviews() {
super.layoutSubviews()
layout()
}
func layout() {
avatarView.pin.start().width(97).height(99).vCenter()
displayNameLabel.pin.top(14).after(of: avatarView).marginStart(16).height(21).sizeToFit(.height)
moreButton.pin.top(to: displayNameLabel.edge.top).height(20).sizeToFit(.height)
moreButton.pin.end()
leaderView.pin.top(to: displayNameLabel.edge.top).height(20).sizeToFit(.height)
leaderView.pin.width(leaderView.bounds.size.width + 16).before(of: moreButton).marginEnd(4)
sublineLabel.pin.after(of: avatarView).marginStart(16).below(of: displayNameLabel).marginTop(4).height(18).sizeToFit(.height)
healthLabel.pin.below(of: sublineLabel).height(16).sizeToFit(.height)
experienceLabel.pin.below(of: healthLabel).marginTop(3).height(16).sizeToFit(.height)
manaLabel.pin.below(of: experienceLabel).marginTop(3).height(16).sizeToFit(.height)
let labelWidth = max(healthLabel.bounds.size.width, experienceLabel.bounds.size.width, manaLabel.bounds.size.width)
healthLabel.pin.end().width(labelWidth)
experienceLabel.pin.end().width(labelWidth)
manaLabel.pin.end().width(labelWidth)
healthBar.pin.after(of: avatarView).marginStart(16).below(of: sublineLabel).marginTop(4).height(8).before(of: healthLabel).marginEnd(12)
experienceBar.pin.after(of: avatarView).marginStart(16).below(of: healthBar).marginTop(11).height(8).before(of: healthLabel).marginEnd(12)
manaBar.pin.after(of: avatarView).marginStart(16).below(of: experienceBar).marginTop(11).height(8).before(of: healthLabel).marginEnd(12)
buffIconView.pin.size(15).after(of: displayNameLabel).top(to: displayNameLabel.edge.top).marginStart(6).marginTop(4)
classIconView.pin.size(15).top(to: displayNameLabel.edge.top).marginStart(4).marginTop(4)
if buffIconView.isHidden {
classIconView.pin.after(of: displayNameLabel)
} else {
classIconView.pin.after(of: buffIconView)
}
}
override var intrinsicContentSize: CGSize {
return CGSize(width: bounds.size.width, height: 127)
}
@objc
private func tapView() {
if let action = viewTapped {
action()
}
}
@objc
private func onMoreButtonTapped() {
if let action = moreButtonTapped {
action()
}
}
}
| gpl-3.0 | a58dc23e8f6ca05f5c7cb09a926a7e30 | 35.875 | 146 | 0.629504 | 4.56447 | false | false | false | false |
Sajjon/ViewComposer | Example/Source/Views/Protocols/SingleSubviewOwner.swift | 1 | 1295 | //
// StackViewOwner.swift
// Example
//
// Created by Alexander Cyon on 2017-06-11.
// Copyright © 2017 Alexander Cyon. All rights reserved.
//
import UIKit
import ViewComposer
protocol SingleSubviewOwner {
associatedtype SubviewType: UIView
var subview: SubviewType { get }
var parentView: UIView { get }
func specialConfig()
}
extension SingleSubviewOwner {
func specialConfig() {}
}
extension SingleSubviewOwner where Self: UIViewController {
var parentView: UIView { return self.view }
func specialConfig() {
view.backgroundColor = .white
edgesForExtendedLayout = []
automaticallyAdjustsScrollViewInsets = false
}
}
extension SingleSubviewOwner {
func setupViews() {
parentView.addSubview(subview)
parentView.addConstraint(subview.topAnchor.constraint(equalTo: parentView.topAnchor))
parentView.addConstraint(subview.leadingAnchor.constraint(equalTo: parentView.leadingAnchor))
parentView.addConstraint(subview.trailingAnchor.constraint(equalTo: parentView.trailingAnchor))
let bottom = subview.bottomAnchor.constraint(equalTo: parentView.bottomAnchor)
bottom.priority = .defaultHigh
parentView.addConstraint(bottom)
specialConfig()
}
}
| mit | a6b5ea702591249bd86c1a99a7518bf4 | 27.130435 | 103 | 0.717156 | 5.015504 | false | true | false | false |
Chris-Perkins/Lifting-Buddy | Lifting Buddy/HelperFunctions.swift | 1 | 22849 | //
// HelperFunctions.swift
// Lifting Buddy
//
// Created by Christopher Perkins on 7/16/17.
// Copyright © 2017 Christopher Perkins. All rights reserved.
//
/// Functions to help make the application more readable.
/// Application defaults are stored here.
import UIKit
import RealmSwift
import Realm
import SwiftCharts
import CDAlertView
// Time amount values (used in graphing)
public enum TimeAmount: String {
case month = "MONTH"
case year = "YEAR"
case alltime = "ALL-TIME"
}
// Used in getting user defined color scheme from userdefaults
public let colorSchemeKey = "colorScheme"
public enum ColorScheme: Int {
case light = 0
case dark = 1
}
public var activeColorScheme: ColorScheme {
guard let storedValue = UserDefaults.standard.value(forKey: colorSchemeKey) as? Int,
let colorScheme = ColorScheme(rawValue: storedValue) else {
fatalError("Could not retrieve the active color scheme")
}
return colorScheme
}
public func setNewColorScheme(_ scheme: ColorScheme) {
let userDefaults = UserDefaults.standard
userDefaults.set(scheme.rawValue, forKey: colorSchemeKey)
}
// An associated array for easy parsing
public let TimeAmountArray = [TimeAmount.month, TimeAmount.year, TimeAmount.alltime]
public let daysOfTheWeekChars = ["S", "M", "T", "W", "T", "F", "S"]
// Returns the height of the status bar (battery view, etc)
var statusBarHeight: CGFloat {
let statusBarSize = UIApplication.shared.statusBarFrame.size
return Swift.min(statusBarSize.width, statusBarSize.height)
}
// MARK: Operators
// let's us do pow function easier.
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Int, power: Int) -> Int {
return Int(pow(Double(radix), Double(power)))
}
// MARK: Global functions
// Gets the colors associated with an index
func getColorsForIndex(_ passedIndex: Int) -> [UIColor] {
var colors = [UIColor]()
let modCount = 10
// Lets us modify the index that was passed in
var index = passedIndex
// + 1 so index starting at 0 is given a color
index += 1
var i = 0
var previousColor = -1
while index > 0 {
var color: UIColor?
var colorIndex = mod(x: index, m: modCount)
if colorIndex == previousColor {
colorIndex = mod(x: colorIndex + 1, m: modCount)
}
switch (colorIndex) {
case 0:
color = .niceRed
case 1:
color = .niceBlue
case 2:
color = .niceGreen
case 3:
color = .niceYellow
case 4:
color = .niceCyan
case 5:
color = .niceBrown
case 6:
color = .nicePurple
case 7:
color = .niceMediterranean
case 8:
color = .niceMaroon
case 9:
color = .niceOrange
default:
fatalError("Modulo returned OOB value. Check case amount in ExerciseChartCreator -> GetLineColor Method")
}
i += 1
// Up this based on mod count. Should be the ceil of closest 10 to modCount
// Ex: modCount 9 -> 10, modCount 11 -> 100
index = index / 10^^i
previousColor = colorIndex
colors.append(color!)
}
return colors
}
// Just mods a number so it doesn't return -1
func mod(x: Int, m: Int) -> Int {
let r = x % m
return r < 0 ? r + m : r
}
func mod(x: Float, m: Float) -> Float {
let r = x.truncatingRemainder(dividingBy: m)
return r < 0 ? r + m : r
}
// MARK: Extensions
extension BetterTextField {
public static var defaultHeight: CGFloat {
return 50
}
}
extension Chart {
public static var defaultHeight: CGFloat {
return 300
}
}
extension ChartSettings {
// Default chart settings for this project
public static func getDefaultSettings() -> ChartSettings {
var chartSettings = ChartSettings()
chartSettings.leading = 10
chartSettings.top = 10
chartSettings.trailing = 15
chartSettings.bottom = 10
chartSettings.labelsToAxisSpacingX = 5
chartSettings.labelsToAxisSpacingY = 5
chartSettings.axisTitleLabelsToLabelsSpacing = 4
chartSettings.axisStrokeWidth = 0.2
chartSettings.spacingBetweenAxesX = 8
chartSettings.spacingBetweenAxesY = 8
chartSettings.labelsSpacing = 0
return chartSettings
}
}
extension NSDate {
// Returns the default date formatter for this project
public static func getDateFormatter() -> DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM yyyy"
return formatter
}
// Get the current day of the week (in string format) ex: "Monday"
public func dayOfTheWeek() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: self as Date)
}
// Gets the day of the week as a string
public func getDayOfWeek(_ fromDate: String, formatter: DateFormatter = NSDate.getDateFormatter()) -> Int? {
guard let date = formatter.date(from: fromDate) else { return nil }
let myCalendar = Calendar(identifier: .gregorian)
let weekDay = myCalendar.component(.weekday, from: date)
return weekDay
}
}
extension Date {
private static let daysOfTheWeek =
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
/// Returns the amount of seconds from another date
func seconds(from date: Date) -> Int {
return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0
}
public static func getDaysOfTheWeekStrings() -> [String] {
return daysOfTheWeek;
}
/**
Attempts to convert an index into the correspondent weekday string; 0-indexed.
- Parameter index: the index of the date (0 is Sunday, 6 is Saturday)
- Returns: A String representing the name of the weekday if the index is valid; nil otherwise.
*/
public static func convertDayIndexToWeekdayName(dayIndex index: Int) -> String? {
if (index < 0 || index >= daysOfTheWeek.count) {
return nil
}
return daysOfTheWeek[index]
}
/**
Attempts to convert a String into the index of the day of the week it's related to; 0-indexed.
- Parameter weekdayName: The String that represents a weekday name
- Returns: The index of the weekday (0-indexed) if it could be found; nil otherwise.
*/
public static func convertWeekdayNameToIndex(weekdayName: String) -> Int? {
if (daysOfTheWeek.contains(weekdayName)) {
return daysOfTheWeek.index(of: weekdayName)
} else {
return nil
}
}
/**
Attempts to get the day of the week for the Date instance; 0-indexed.
- Returns: The index of the day of the week this date is; 0-indexed.
*/
public func getDayOfTheWeekIndex() -> Int {
let date = Date()
let myCalendar = Calendar(identifier: .gregorian)
let weekDay = myCalendar.component(.weekday, from: date)
return weekDay - 1
}
}
extension Int {
public func modulo(_ moduloNumber: Int) -> Int {
let moduloValue = self % moduloNumber
return moduloValue < 0 ? moduloValue + moduloNumber : moduloValue
}
}
extension NSLayoutConstraint {
// Clings a view to the entirety of toView
public static func clingViewToView(view: UIView,
toView: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: view,
withCopyView: toView,
attribute: .right).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: view,
withCopyView: toView,
attribute: .left).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: view,
withCopyView: toView,
attribute: .top).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: view,
withCopyView: toView,
attribute: .bottom).isActive = true
}
// Return a constraint that will place a view below's top a view with padding
public static func createViewBelowViewConstraint(view: UIView,
belowView: UIView,
withPadding: CGFloat = 0) -> NSLayoutConstraint {
return NSLayoutConstraint(item: belowView,
attribute: .bottom,
relatedBy: .equal,
toItem: view,
attribute: .top,
multiplier: 1,
constant: -withPadding)
}
// Return a constraint that will create a width constraint for the given view
public static func createWidthConstraintForView(view: UIView,
width: CGFloat) -> NSLayoutConstraint {
return NSLayoutConstraint(item: view,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: width)
}
// Return a constraint that will create a height constraint for the given view
public static func createHeightConstraintForView(view: UIView,
height: CGFloat) -> NSLayoutConstraint {
return NSLayoutConstraint(item: view,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: height)
}
// Just a faster way to create a layout constraint copy. The original way is waaaay too long.
public static func createViewAttributeCopyConstraint(view: UIView,
withCopyView: UIView,
attribute: NSLayoutConstraint.Attribute,
multiplier: CGFloat = 1.0,
plusConstant: CGFloat = 0.0) -> NSLayoutConstraint {
return NSLayoutConstraint(item: withCopyView,
attribute: attribute,
relatedBy: .equal,
toItem: view,
attribute: attribute,
multiplier: (1/multiplier),
constant: -plusConstant)
}
}
extension PrettyButton {
public static var defaultHeight: CGFloat {
return 50
}
override func setDefaultProperties() {
backgroundColor = .niceBlue
setOverlayColor(color: .niceYellow)
setOverlayStyle(style: .fade)
cornerRadius = 0
}
}
extension PrettySegmentedControl {
public static var defaultHeight: CGFloat {
return 30
}
}
extension String {
var floatValue: Float? {
return Float(self)
}
}
extension UIColor {
public static var primaryBlackWhiteColor: UIColor {
switch(activeColorScheme) {
case .light:
return .white
case .dark:
return .niceBlack
}
}
public static var lightBlackWhiteColor: UIColor {
switch(activeColorScheme) {
case .light:
return .niceLightGray
case .dark:
return .niceDarkestGray
}
}
public static var lightestBlackWhiteColor: UIColor {
switch(activeColorScheme) {
case .light:
return .niceLightestGray
case .dark:
return .niceDarkGray
}
}
public static var oppositeBlackWhiteColor: UIColor {
switch(activeColorScheme) {
case .light:
return .niceBlack
case .dark:
return .white
}
}
public static var niceBlack: UIColor {
return UIColor(hue: 0, saturation: 0, brightness: 0.075, alpha: 1.0)
}
public static var niceBlue: UIColor {
switch(activeColorScheme) {
case .light:
return UIColor(red: 0.291269, green: 0.459894, blue: 0.909866, alpha: 1)
case .dark:
return UIColor(red: 0.4196, green: 0.6196, blue: 0.909866, alpha: 1.0)
}
}
public static var niceBrown: UIColor {
return UIColor(red: 0.6471, green: 0.3647, blue: 0.149, alpha: 1.0)
}
public static var niceCyan: UIColor {
return UIColor(red: 0.149, green: 0.651, blue: 0.6588, alpha: 1.0)
}
public static var niceDarkGray: UIColor {
return UIColor(hue: 0, saturation: 0, brightness: 0.225, alpha: 1.0)
}
public static var niceDarkestGray: UIColor {
return UIColor(hue: 0, saturation: 0, brightness: 0.15, alpha: 1.0)
}
public static var niceGreen: UIColor {
return UIColor(red: 0.27, green: 0.66, blue: 0.3, alpha: 1)
}
public static var niceLabelBlue: UIColor {
return UIColor(red: 0.44, green: 0.56, blue: 0.86, alpha: 1)
}
public static var niceLightBlue: UIColor {
return UIColor(red: 0.8, green: 0.78, blue: 0.96, alpha: 1)
}
public static var niceLightGray: UIColor {
return UIColor(hue: 0, saturation: 0, brightness: 0.895, alpha: 1.0)
}
public static var niceLightestGray: UIColor {
return UIColor(hue: 0, saturation: 0, brightness: 0.95, alpha: 1.0)
}
public static var niceLightGreen: UIColor {
switch(activeColorScheme) {
case .light:
return UIColor(red: 0.85, green: 0.95, blue: 0.85, alpha: 1)
case .dark:
return UIColor(red: 0.1176, green: 0.2667, blue: 0.1176, alpha: 1.0)
}
}
public static var niceLightRed: UIColor {
return UIColor(red: 0.9686, green: 0.5176, blue: 0.3647, alpha: 1.0)
}
public static var niceMaroon: UIColor {
return UIColor(red: 0.349, green: 0.0784, blue: 0.0784, alpha: 1.0)
}
public static var niceMediterranean: UIColor {
return UIColor(red: 0.0745, green: 0.2235, blue: 0.3373, alpha: 1.0)
}
public static var niceOrange: UIColor {
return UIColor(red: 1, green: 0.4118, blue: 0.1569, alpha: 1.0)
}
public static var nicePurple: UIColor {
return UIColor(red: 0.5882, green: 0.1451, blue: 0.6392, alpha: 1.0)
}
public static var niceRed: UIColor {
return UIColor(red: 1.0, green: 0.5, blue: 0.5, alpha: 1)
}
public static var niceYellow: UIColor {
return UIColor(red: 0.90, green: 0.70, blue: 0.16, alpha: 1)
}
}
extension UIImage {
public func rotateNinetyDegreesClockwise() -> UIImage {
return UIImage(cgImage: cgImage!, scale: 1, orientation: UIImage.Orientation.right)
}
public func rotateNinetyDegreesCounterClockwise() -> UIImage {
return UIImage(cgImage: cgImage!, scale: 1, orientation: UIImage.Orientation.left)
}
}
extension UILabel {
public static var titleLabelTextColor: UIColor {
return .niceBlue
}
public static var titleLabelBackgroundColor: UIColor {
return .lightestBlackWhiteColor
}
public static var titleLabelHeight: CGFloat {
return 50.0
}
override func setDefaultProperties() {
font = UIFont.boldSystemFont(ofSize: 18.0)
textAlignment = .center
textColor = .niceBlue
}
}
extension UITableView {
// Returns all cells in a uitableview
public func getAllCells() -> [UITableViewCell] {
var cells = [UITableViewCell]()
for i in 0...numberOfSections - 1 {
for j in 0...numberOfRows(inSection: i) {
if let cell = cellForRow(at: IndexPath(row: j, section: i)) {
cells.append(cell)
}
}
}
return cells
}
}
extension UITableViewCell {
public static var defaultHeight: CGFloat {
return 50
}
}
extension UITextField {
var isNumeric: Bool {
if let text = text {
if text.count == 0 { return true }
let setNums: Set<Character> = Set(arrayLiteral: "1", "2", "3", "4",
"5", "6", "7", "8",
"9", "0")
return Set(text).isSubset(of: setNums)
} else {
return false
}
}
override func setDefaultProperties() {
// View select / deselect events
addTarget(self, action: #selector(textfieldSelected(sender:)), for: .editingDidBegin)
addTarget(self, action: #selector(textfieldDeselected(sender:)), for: .editingDidEnd)
// View prettiness
textAlignment = .center
}
// MARK: Textfield events
@objc func textfieldSelected(sender: UITextField) {
UIView.animate(withDuration: 0.1, animations: {
sender.backgroundColor = .niceYellow
sender.textColor = .white
})
}
@objc func textfieldDeselected(sender: UITextField) {
UIView.animate(withDuration: 0.1, animations: {
sender.backgroundColor = .primaryBlackWhiteColor
sender.textColor = .oppositeBlackWhiteColor
})
}
@objc public func setPlaceholderString(_ placeholder: String?) {
if let placeholder = placeholder {
let attributedText = NSAttributedString(string: placeholder,
attributes: [NSAttributedString.Key.foregroundColor:
UIColor.oppositeBlackWhiteColor.withAlphaComponent(
0.25)])
attributedPlaceholder = attributedText
} else {
attributedPlaceholder = nil
}
}
@objc public func getPlaceholderString() -> String? {
return attributedPlaceholder?.string
}
public func resetColors() {
setPlaceholderString(getPlaceholderString())
textfieldDeselected(sender: self)
}
}
extension UIView {
// Shows a view over this view using constraints
static func slideView(_ coveringView: UIView, overView inView: UIView) {
// Don't want user interacting with the view if it shouldn't be interactable at this time.
inView.isUserInteractionEnabled = false
inView.addSubview(coveringView)
// Constraints take up the whole view. Start above the view (not visible)
coveringView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: coveringView,
withCopyView: inView,
attribute: .left).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: coveringView,
withCopyView: inView,
attribute: .width).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: coveringView,
withCopyView: inView,
attribute: .height).isActive = true
/*
We can use the inView's height as the basis for "above this view" since
coveringView's height is equal to the height of the inView
*/
let heightConstraint = NSLayoutConstraint.createViewAttributeCopyConstraint(
view: coveringView,
withCopyView: inView,
attribute: .top,
plusConstant: -inView.frame.height)
heightConstraint.isActive = true
// Activate these constraints
inView.layoutIfNeeded()
// Moves the view to the bottom upon calling layout if needed
heightConstraint.constant = 0
// Animate the transition between top to bottom to slide down
UIView.animate(withDuration: 0.2, animations: {
inView.layoutIfNeeded()
}, completion: {Bool in
inView.isUserInteractionEnabled = true
})
}
// Calls layoutSubviews on ALL subviews recursively
func layoutAllSubviews() {
for subview in subviews {
(subview as? UITextField)?.resetColors()
subview.layoutAllSubviews()
}
layoutSubviews()
}
@objc func setDefaultProperties() {
// Override me!
}
// Removes all subviews from a given view
func removeAllSubviews() {
for subview in subviews {
subview.removeFromSuperview()
}
}
// Removes itself from this superview by sliding up and fading out
func removeSelfNicelyWithAnimation() {
// Prevent user interaction with all subviews
for subview in subviews {
subview.isUserInteractionEnabled = false
}
// Slide up, then remove from view
UIView.animate(withDuration: 0.2, animations: {
self.frame = CGRect(x: 0,
y: -self.frame.height,
width: self.frame.width,
height: self.frame.height)
}, completion: { (finished:Bool) -> Void in
self.removeFromSuperview()
})
}
}
| mit | 7f78d822cafe45925075779bcf3d75f3 | 33 | 117 | 0.564951 | 5.154072 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard | GCBUtilities/Extensions/NSDate.swift | 2 | 724 | //
//
// Created by Krzysztof Werys on 09/03/16.
// Copyright © 2016 Krzysztof Werys. All rights reserved.
//
import Foundation
extension NSDate: Comparable { }
public func == (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs === rhs || lhs.compare(rhs) == .OrderedSame
}
public func < (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedAscending
}
public func > (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedDescending
}
public func <= (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs == rhs || lhs.compare(rhs) == .OrderedAscending
}
public func >= (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs == rhs || lhs.compare(rhs) == .OrderedDescending
}
| gpl-3.0 | d23fbea7dae5cf429fca806ef1b59fe9 | 23.931034 | 63 | 0.644537 | 3.42654 | false | false | false | false |
iosprogrammingwithswift/iosprogrammingwithswift | 04_Swift2015_Final.playground/Pages/01_The Basics.xcplaygroundpage/Contents.swift | 1 | 4361 | //: [Previous](@previous) | [Next](@next)
print("Hallo Würzburg 🌟")
// DAs ist ein Kommentar
/*
* Das auch!
*/
//MARK: Das ist meine Wichtige Section
//: ## Simple Values
//:
//: Use `let` to make a constant and `var` to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.
//:
var myVariable = 42
myVariable = 50
let myConstant = 42
//myConstant = 32
//: A constant or variable must have the same type as the value you want to assign to it. However, you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type. In the example above, the compiler infers that `myVariable` is an integer because its initial value is an integer.
//:
//: If the initial value doesn’t provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by a colon.
//:
let implicitInteger = 70
let implicitDouble = 70.0
let explicitInt:Int = 70
let explicitDouble: Double = 70
//: > **Experiment**:
//: > Create a constant with an explicit type of `Float` and a value of `4`.
//:
//: Values are never implicitly converted to another type. If you need to convert a value to a different type, explicitly make an instance of the desired type.
//:
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
//: > **Experiment**:
//: > Try removing the conversion to `String` from the last line. What error do you get?
//:
//: There’s an even simpler way to include values in strings: Write the value in parentheses, and write a backslash (`\`) before the parentheses. For example:
//:
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
//: > **Experiment**:
//: > Use `\()` to include a floating-point calculation in a string and to include someone’s name in a greeting.
//:
let maximumNumberOfLogins:Int = 10
var currentLoginCount:Int = 0
currentLoginCount += 4
currentLoginCount += 4
let a = 10, b = 20, c = 33
var aa = 10, bb = 20, cc = 33
let π = 3.14159
let 你好 = "你好世界"
let 🐶🐮 = "dogcow🐶🐮"
let someInt = 1234
let otherValue = 3.22
//: Type Annotations
let otherFloat:Float = 3.33
let someBool:Bool = true
let aString:String = "Hallo"
let val1 = 17
let binary = 0b10001 //17 in binär
let octal = 0o21
let hex = 0x11
//: Printing Constants and Variables
print("Hallo \(implicitInteger) \(🐶🐮)")
print("Hallo \(implicitInteger + val1)")
//: semicolon
let 👍 = "thumb"; print(👍)
👍
//MARK: syntax sugar
let doubleVal = 12345.567
let paddedval = 00012345.567
let oneMillion = 1_000_000
let oneMillionWithRest = 1_000_000.000_1
//: Bounds
UInt8.min
UInt8.max
UInt16.min
UInt16.max
UInt32.min
UInt32.max
//: Tuples
// Constructing a simple tuple
let tp1 = (2, 3)
let tp2 = (2, 3, 4)
// Constructing a named tuple
let tp3 = (x: 5, y: 3)
// Different types
let tp4 = (name: "Carl", age: 78, pets: ["Bonny", "Houdon", "Miki"])
// Accessing tuple elements
let tp5 = (13, 21)
tp5.0 // 13
tp5.1 // 21
let tp6 = (x: 21, y: 33)
tp6.x // 21
tp6.y // 33
let (name, age, pets) = tp4
print("Name: \(name)")
print("Age \(age)")
print("Pets: \(pets)")
//: Ignoring Values During Decomposition
let (_, realAlter, _) = tp4
print("Das Alter \(realAlter)")
//:Named Tuples
//: das Json des kleinen Mannes
let anotherItem = (shape: "Square", color: "Red", coordinate:(1.0, 2.0, 1.5))
print("The shape is \(anotherItem.shape)") // prints "The shape is Square"
print("The color is \(anotherItem.color)") // prints "The color is Red"
//: Tuples in methods
func origin() -> (Double, Double, Double)
{
//...
return (1.0, 2.0, 1.5)
}
/*:
largely Based of [Apple's Swift Language Guide: The Basics](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309 ) & [Apple's A Swift Tour](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1 )
*/
//: [Previous](@previous) | [Next](@next)
| mit | 157751b258e2a847507b43981977cedc | 24.784431 | 395 | 0.692058 | 3.29709 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/Notifications/NotificationsTableViewCell.swift | 1 | 2692 | //
// NotificationsTableViewCell.swift
// PennMobile
//
// Created by Dominic Holmes on 12/27/19.
// Copyright © 2019 PennLabs. All rights reserved.
//
import UIKit
class NotificationTableViewCell: UITableViewCell {
static let identifier = "notificationCell"
weak var delegate: NotificationViewControllerChangedPreference!
fileprivate var option: NotificationOption!
fileprivate var label: UILabel!
fileprivate var optionSwitch: UISwitch!
fileprivate var buildingImageLeftConstraint: NSLayoutConstraint!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.prepareUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(with option: NotificationOption, isEnabled: Bool) {
self.option = option
self.label.text = option.cellTitle
self.optionSwitch.setOn(isEnabled, animated: false)
}
}
// MARK: - Prepare UI
extension NotificationTableViewCell {
@objc func didToggle(_ sender: UISwitch) {
if delegate.allowChange() {
delegate.changed(option: option, toValue: sender.isOn)
} else {
delegate.requestChange(option: option, toValue: sender.isOn)
}
}
fileprivate func prepareUI() {
prepareSwitch()
prepareLabel()
}
fileprivate func prepareSwitch() {
optionSwitch = UISwitch()
optionSwitch.tintColor = UIColor.purpleLight
optionSwitch.translatesAutoresizingMaskIntoConstraints = false
addSubview(optionSwitch)
optionSwitch.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
optionSwitch.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -14).isActive = true
optionSwitch.addTarget(self, action: #selector(didToggle(_:)), for: .primaryActionTriggered)
}
fileprivate func prepareLabel() {
label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
addSubview(label)
label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 14.0).isActive = true
label.widthAnchor.constraint(equalTo: widthAnchor, constant: -90.0).isActive = true
label.topAnchor.constraint(equalTo: topAnchor, constant: 7.0).isActive = true
label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -7.0).isActive = true
label.font = UIFont.systemFont(ofSize: 17, weight: .medium)
label.numberOfLines = 0
label.minimumScaleFactor = 0.7
label.adjustsFontSizeToFitWidth = true
}
}
| mit | c71a5087d174c9d2e7fe4f1e55f8656f | 31.817073 | 102 | 0.697139 | 5.058271 | false | false | false | false |
Authman2/Pix | Pix/PostDetailPage.swift | 1 | 10895 | //
// PostDetailPage.swift
// Pix
//
// Created by Adeola Uthman on 12/24/16.
// Copyright © 2016 Adeola Uthman. All rights reserved.
//
import UIKit
import SnapKit
import Neon
import Firebase
import OneSignal
import Presentr
import Hero
import ChameleonFramework
import DynamicColor
import Spring
class PostDetailPage: UIViewController, UIScrollViewDelegate {
/********************************
*
* VARIABLES
*
********************************/
/* A Post object for data grabbing. */
var post: Post!
static let backgroundColor = UIColor.flatForestGreen.lighten(byPercentage: 0.35);
let back: UIButton = {
let a = UIButton(type: UIButtonType.custom);
a.setImage(UIImage(named: "[email protected]"), for: .normal);
a.transform = a.transform.rotated(by: CGFloat(M_PI_2));
a.transform = a.transform.rotated(by: CGFloat(M_PI_2));
a.transform = a.transform.rotated(by: CGFloat(M_PI_2));
a.setTitleColor(.white, for: .normal);
a.tintColor = .white;
return a;
}();
var scrollView: UIScrollView!;
/* The image view. */
let imageView: UIImageView = {
var imageView = UIImageView();
imageView.translatesAutoresizingMaskIntoConstraints = false;
imageView.backgroundColor = .clear;
imageView.clipsToBounds = false;
imageView.contentMode = .scaleToFill;
return imageView;
}();
/* The label that displays the caption. */
let captionLabel: UILabel = {
let c = UILabel();
c.translatesAutoresizingMaskIntoConstraints = false;
c.textColor = .white;
c.backgroundColor = .clear;
c.numberOfLines = 0;
c.font = UIFont(name: c.font.fontName, size: 15);
return c;
}();
/* The label that shows the number of likes. */
let likesLabel: UILabel = {
let l = UILabel();
l.translatesAutoresizingMaskIntoConstraints = false;
l.textColor = .white;
l.backgroundColor = .clear;
l.font = UIFont(name: l.font.fontName, size: 15);
return l;
}();
/* The label that shows the name of the person who uploaded the photo. */
let uploaderLabel: UILabel = {
let l = UILabel();
l.translatesAutoresizingMaskIntoConstraints = false;
l.textColor = .white;
l.backgroundColor = .clear;
l.font = UIFont(name: l.font.fontName, size: 15);
return l;
}();
/* The button to open the comments page. */
let commentsBtn: SpringButton = {
let a = SpringButton();
a.setTitle("Comments", for: .normal);
a.backgroundColor = PostDetailPage.backgroundColor?.darkened();
a.titleLabel?.font = UIFont(name: (a.titleLabel?.font.fontName)!, size: 15);
return a;
}();
/* Firebase database reference. */
let fireRef: FIRDatabaseReference = FIRDatabase.database().reference();
/********************************
*
* METHODS
*
********************************/
override func viewDidLoad() {
super.viewDidLoad();
self.view.backgroundColor = PostDetailPage.backgroundColor;
self.configureGestures();
scrollView = UIScrollView(frame: view.bounds);
scrollView.backgroundColor = PostDetailPage.backgroundColor;
scrollView.translatesAutoresizingMaskIntoConstraints = false;
scrollView.alwaysBounceVertical = true;
scrollView.alwaysBounceHorizontal = false;
imageView.frame = scrollView.frame;
scrollView.delegate = self;
// Get the important info.
imageView.image = post.photo;
captionLabel.text = "\(post.caption!)";
likesLabel.text = "Likes: \(post.likes)";
uploaderLabel.text = "\(post.uploader.firstName) \(post.uploader.lastName)";
scrollView.contentSize = CGSize(width: view.width, height: view.height * 1.2);
/* Layout the components. */
scrollView.addSubview(back);
scrollView.addSubview(imageView);
scrollView.addSubview(captionLabel);
scrollView.addSubview(likesLabel);
scrollView.addSubview(uploaderLabel);
scrollView.addSubview(commentsBtn);
scrollView.bringSubview(toFront: back);
view.addSubview(scrollView);
/* Layout with Snapkit */
scrollView.snp.makeConstraints { (maker: ConstraintMaker) in
maker.top.equalTo(view.snp.top);
maker.bottom.equalTo(view.snp.bottom);
maker.left.equalTo(view.snp.left);
maker.right.equalTo(view.snp.right);
}
imageView.snp.makeConstraints { (maker: ConstraintMaker) in
maker.left.equalTo(scrollView.snp.left);
maker.right.equalTo(view.snp.right);
maker.top.equalTo(scrollView.snp.top).offset(-20);
maker.height.equalTo(500);
}
uploaderLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.left.equalTo(5);
maker.top.equalTo(imageView.snp.bottom).offset(10);
maker.width.equalTo(view.width);
maker.height.equalTo(30);
}
likesLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.left.equalTo(5);
maker.top.equalTo(uploaderLabel.snp.bottom);
maker.width.equalTo(100);
maker.height.equalTo(30);
}
captionLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.top.equalTo(likesLabel.snp.bottom);
maker.left.equalTo(5);
maker.right.equalTo(view.snp.right).offset(10);
}
back.snp.makeConstraints { (maker: ConstraintMaker) in
maker.left.equalTo(5);
maker.top.equalTo(10);
maker.width.equalTo(50);
maker.height.equalTo(50);
}
commentsBtn.snp.makeConstraints { (maker: ConstraintMaker) in
maker.left.equalTo(scrollView.snp.left);
maker.top.equalTo(captionLabel.snp.bottom).offset(30);
maker.right.equalTo(view.snp.right);
maker.height.equalTo(35);
}
} // End of setup method.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated);
}
@objc func goBack() {
UIView.animate(withDuration: 0.4, delay: 0, options: [], animations: {
self.navigationController?.navigationBar.isHidden = false;
self.navigationController?.navigationBar.alpha = 1;
lastProfile.navigationItem.titleView?.isHidden = false;
lastProfile.navigationItem.titleView?.alpha = 1;
}, completion: { (finished: Bool) in
lastProfile.navigationItem.title = lastProfile.viewcontrollerName;
});
Hero.shared.setDefaultAnimationForNextTransition(animations[1]);
Hero.shared.setContainerColorForNextTransition(view.backgroundColor);
hero_replaceViewController(with: lastProfile);
}
func configureGestures() {
// Tap gesture
let tap = UITapGestureRecognizer(target: self, action: #selector(likePhoto));
tap.numberOfTapsRequired = 2;
imageView.addGestureRecognizer(tap);
view.addGestureRecognizer(tap);
// Long press
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(openActionSheet));
imageView.addGestureRecognizer(longPress);
view.addGestureRecognizer(longPress);
back.addTarget(self, action: #selector(goBack), for: .touchUpInside);
commentsBtn.addTarget(self, action: #selector(goToComments), for: .touchUpInside);
}
@objc func goToComments() {
commentsBtn.animateButtonClick();
let presenter: Presentr = {
let pres = Presentr(presentationType: .bottomHalf);
pres.dismissOnSwipe = true;
pres.dismissAnimated = true;
pres.backgroundOpacity = 0.7;
return pres;
}();
let commVC = CommentsPage(post: self.post);
customPresentViewController(presenter, viewController: commVC, animated: true, completion: nil);
}
@objc func likePhoto() {
if let cUser = Networking.currentUser {
// If the id for this photo is not already in the current user's list of liked photos, then add it and update firebase.
// Otherwise, unlike it.
if !cUser.likedPhotos.containsUsername(username: "\(self.post.uploader.uid) \(self.post.id!)") {
cUser.likedPhotos.append("\(self.post!.uploader!.uid) \(self.post!.id!)");
post.likes += 1;
Networking.updateCurrentUserInFirebase();
fireRef.child("Photos").child(post.uploader.uid).child(post.id!).setValue(post.toDictionary());
// Send notification.
if(self.post.uploader.notification_ID != cUser.notification_ID) {
OneSignal.postNotification(["contents": ["en": "\(cUser.username) liked your photo!"], "include_player_ids": ["\(self.post.uploader.notification_ID)"]], onSuccess: { (dict: [AnyHashable : Any]?) in
self.debug(message: "Follow notification was sent!");
}, onFailure: { (error: Error?) in
self.debug(message: "There was an error sending the notification.");
});
}
} else {
if cUser.likedPhotos.count > 0 {
cUser.likedPhotos.removeItem(item: self.post.id!);
post.likes -= 1;
Networking.updateCurrentUserInFirebase();
fireRef.child("Photos").child(post.uploader.uid).child(post.id!).setValue(post.toDictionary());
}
}
}
likesLabel.text = "Likes: \(post.likes)";
}
@objc func openActionSheet() {
let presenter: Presentr = {
let pres = Presentr(presentationType: .bottomHalf);
pres.dismissOnSwipe = true;
pres.dismissAnimated = true;
pres.backgroundOpacity = 0.7;
return pres;
}();
let detailView = ActionSheet();
detailView.post = self.post;
customPresentViewController(presenter, viewController: detailView, animated: true, completion: nil);
}
}
| gpl-3.0 | 8251b0584a0a082c1a3e6b5bcc9e8a11 | 33.584127 | 217 | 0.577382 | 4.95858 | false | false | false | false |
pavankataria/ChopChop | Src/PKImageUtil.swift | 2 | 4240 | //
// ChopChop.swift
// ChopChop
//
// Created by Pavan Kataria on 10/01/2016.
// Copyright © 2016 Pavan Kataria. All rights reserved.
//
/*
The MIT License (MIT)
Copyright (c) [2016] [Pavan Kataria]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
import UIKit
protocol ChopChopProtocol {
func cropToSquare() -> UIImage
func cropWithMatrix(matrix: (rows: Int, cols: Int)) -> [UIImage]
}
extension UIImage: ChopChopProtocol {
func cropToSquare() -> UIImage
{
return ChopChop.cropToSquare(image: self)
}
func cropWithMatrix(matrix: (rows: Int, cols: Int)) -> [UIImage]
{
return ChopChop.cropImage(image: self, toMatrix: (rows: 2, cols: 2))
}
}
class ChopChop: NSObject {
// Crops to square based on the shortest length
static func cropToSquare(image originalImage: UIImage) -> UIImage {
let imageSize: CGSize = originalImage.size
let posX: CGFloat
let posY: CGFloat
let width: CGFloat
let height: CGFloat
if imageSize.width > imageSize.height {
posX = ((imageSize.width - imageSize.height) / 2)
posY = 0
width = imageSize.height
height = imageSize.height
} else {
posX = 0
posY = ((imageSize.height - imageSize.width) / 2)
width = imageSize.width
height = imageSize.width
}
let rect: CGRect = CGRectMake(posX, posY, width, height)
return self.crop(image: originalImage, cropRect: rect)
}
// A matrix cropper
static func cropImage(image originalImage: UIImage, toMatrix matrix: (rows: Int, cols: Int)) -> [UIImage]{
//TODO:
/* guard originalSquareImage.size.width % matrix.rows == 0 &&
originalSquareImage.size.height % matrix.cols == 0 else {
assertionFailure("For now, the square image needs to divide exactly by the matrix provided, at least until this package is further developed to handle odd image sized edge cases.")
}
*/
var images = [UIImage]()
let quadrantSize: CGSize = CGSize(width: CGFloat(Int(originalImage.size.width) / matrix.rows), height: CGFloat(Int(originalImage.size.height) / matrix.cols))
for rowPosition in 0 ..< matrix.rows {
for colPosition in 0 ..< matrix.cols {
let x: CGFloat = CGFloat(rowPosition * Int(quadrantSize.width))
let y: CGFloat = CGFloat(colPosition * Int(quadrantSize.height))
let rect = CGRect(x: x, y: y, width: quadrantSize.width, height: quadrantSize.height)
images.append(self.crop(image: originalImage, cropRect: rect))
}
}
return images
}
// Crops image to specified rect
static func crop(image originalImage: UIImage, cropRect originalCropRect: CGRect) -> UIImage{
let contextImage: UIImage = UIImage(CGImage: originalImage.CGImage!)
let imageRef: CGImageRef = CGImageCreateWithImageInRect(contextImage.CGImage, originalCropRect)!
let image: UIImage = UIImage(CGImage: imageRef, scale: originalImage.scale, orientation: originalImage.imageOrientation)
return image
}
}
| mit | baa33fd12d8af9475d1d2c2406adac6e | 39.371429 | 188 | 0.672564 | 4.509574 | false | false | false | false |
eofster/Telephone | UseCases/SystemDefaultingSoundIO.swift | 1 | 1369 | //
// SystemDefaultingSoundIO.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone 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.
//
// Telephone 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 Domain
public struct SystemDefaultingSoundIO {
public let input: Item
public let output: Item
public let ringtoneOutput: Item
public init(input: Item, output: Item, ringtoneOutput: Item) {
self.input = input
self.output = output
self.ringtoneOutput = ringtoneOutput
}
public init(_ soundIO: SoundIO) {
input = Item(soundIO.input)
output = Item(soundIO.output)
ringtoneOutput = Item(soundIO.ringtoneOutput)
}
public enum Item {
case systemDefault
case device(name: String)
init(_ device: SystemAudioDevice) {
self = device.isNil ? .systemDefault : .device(name: device.name)
}
}
}
| gpl-3.0 | d2c55bfeb26eb66354524b5c02fb1b86 | 28.717391 | 77 | 0.680322 | 4.46732 | false | false | false | false |
tomboates/BrilliantSDK | Pod/Classes/NPSScoreViewController.swift | 1 | 6216 | //
// NSPScoreViewController.swift
// Pods
//
// Created by Phillip Connaughton on 1/24/16.
//
//
import Foundation
protocol NPSScoreViewControllerDelegate: class{
func closePressed(_ state: SurveyViewControllerState)
func npsScorePressed(_ npsScore: Int)
}
class NPSScoreViewController : UIViewController
{
@IBOutlet var closeButton: UIButton!
@IBOutlet var questionLabel: UILabel!
@IBOutlet var button0: UIButton!
@IBOutlet var button1: UIButton!
@IBOutlet var button2: UIButton!
@IBOutlet var button3: UIButton!
@IBOutlet var button4: UIButton!
@IBOutlet var button5: UIButton!
@IBOutlet var button6: UIButton!
@IBOutlet var button7: UIButton!
@IBOutlet var button8: UIButton!
@IBOutlet var button9: UIButton!
@IBOutlet var button10: UIButton!
@IBOutlet weak var notLikelyBtn: UILabel!
@IBOutlet weak var likelyBtn: UILabel!
@IBOutlet var labelWidthConstraint: NSLayoutConstraint!
internal weak var delegate : NPSScoreViewControllerDelegate?
override func viewDidLoad() {
let image = UIImage(named: "brilliant-icon-close", in:Brilliant.imageBundle(), compatibleWith: nil)
self.closeButton.setImage(image, for: UIControlState())
self.closeButton.imageEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 25, right: 25)
self.questionLabel.textColor = Brilliant.sharedInstance().mainLabelColor()
self.questionLabel.font = Brilliant.sharedInstance().mainLabelFont()
if (Brilliant.sharedInstance().appName != nil)
{
self.questionLabel.text = String(format: "How likely is it that you will recommend %@ to a friend or colleague?", Brilliant.sharedInstance().appName!)
}
else
{
self.questionLabel.text = "How likely is it that you will recommend this app to a friend or colleague?"
}
self.button0.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button1.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button2.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button3.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button4.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button5.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button6.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button7.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button8.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button9.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button10.tintColor = Brilliant.sharedInstance().npsButtonColor()
self.button0.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button1.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button2.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button3.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button4.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button5.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button6.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button7.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button8.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button9.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.button10.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont()
self.notLikelyBtn.font = Brilliant.sharedInstance().levelLabelFont()
self.likelyBtn.font = Brilliant.sharedInstance().levelLabelFont()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// self.updateConstraints()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: nil) { (completion) in
// self.updateConstraints()
}
}
func updateConstraints() {
let size = UIDeviceHelper.deviceWidth()
switch size
{
case .small:
self.labelWidthConstraint.constant = 280
break
case .medium:
self.labelWidthConstraint.constant = 300
break
case .large:
self.labelWidthConstraint.constant = 420
break
}
}
@IBAction func closePressed(_ sender: AnyObject) {
Brilliant.sharedInstance().completedSurvey!.dismissAction = "x_npsscreen"
self.delegate?.closePressed(.ratingScreen)
}
@IBAction func zeroPressed(_ sender: AnyObject) {
self.npsNumberResponse(0)
}
@IBAction func onePressed(_ sender: AnyObject) {
self.npsNumberResponse(1)
}
@IBAction func twoPressed(_ sender: AnyObject) {
self.npsNumberResponse(2)
}
@IBAction func threePressed(_ sender: AnyObject) {
self.npsNumberResponse(3)
}
@IBAction func fourPressed(_ sender: AnyObject) {
self.npsNumberResponse(4)
}
@IBAction func fivePressed(_ sender: AnyObject) {
self.npsNumberResponse(5)
}
@IBAction func sixPressed(_ sender: AnyObject) {
self.npsNumberResponse(6)
}
@IBAction func sevenPressed(_ sender: AnyObject) {
self.npsNumberResponse(7)
}
@IBAction func eightPressed(_ sender: AnyObject) {
self.npsNumberResponse(8)
}
@IBAction func ninePressed(_ sender: AnyObject) {
self.npsNumberResponse(9)
}
@IBAction func tenPressed(_ sender: AnyObject) {
self.npsNumberResponse(10)
}
func npsNumberResponse(_ npsNumber: Int)
{
Brilliant.sharedInstance().completedSurvey!.npsRating = npsNumber
self.delegate?.npsScorePressed(npsNumber)
}
}
| mit | 9f8df59c99410f5d9017bc129212b310 | 35.350877 | 162 | 0.670367 | 4.9728 | false | false | false | false |
tecgirl/firefox-ios | Client/Frontend/Browser/SwipeAnimator.swift | 1 | 5939 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
struct SwipeAnimationParameters {
let totalRotationInDegrees: Double
let deleteThreshold: CGFloat
let totalScale: CGFloat
let totalAlpha: CGFloat
let minExitVelocity: CGFloat
let recenterAnimationDuration: TimeInterval
}
private let DefaultParameters =
SwipeAnimationParameters(
totalRotationInDegrees: 10,
deleteThreshold: 80,
totalScale: 0.9,
totalAlpha: 0,
minExitVelocity: 800,
recenterAnimationDuration: 0.15)
protocol SwipeAnimatorDelegate: AnyObject {
func swipeAnimator(_ animator: SwipeAnimator, viewWillExitContainerBounds: UIView)
}
class SwipeAnimator: NSObject {
weak var delegate: SwipeAnimatorDelegate?
weak var animatingView: UIView?
fileprivate var prevOffset: CGPoint?
fileprivate let params: SwipeAnimationParameters
fileprivate var panGestureRecogniser: UIPanGestureRecognizer!
var containerCenter: CGPoint {
guard let animatingView = self.animatingView else {
return .zero
}
return CGPoint(x: animatingView.frame.width / 2, y: animatingView.frame.height / 2)
}
init(animatingView: UIView, params: SwipeAnimationParameters = DefaultParameters) {
self.animatingView = animatingView
self.params = params
super.init()
self.panGestureRecogniser = UIPanGestureRecognizer(target: self, action: #selector(didPan))
animatingView.addGestureRecognizer(self.panGestureRecogniser)
self.panGestureRecogniser.delegate = self
}
func cancelExistingGestures() {
self.panGestureRecogniser.isEnabled = false
self.panGestureRecogniser.isEnabled = true
}
}
//MARK: Private Helpers
extension SwipeAnimator {
fileprivate func animateBackToCenter() {
UIView.animate(withDuration: params.recenterAnimationDuration, animations: {
self.animatingView?.transform = .identity
self.animatingView?.alpha = 1
})
}
fileprivate func animateAwayWithVelocity(_ velocity: CGPoint, speed: CGFloat) {
guard let animatingView = self.animatingView else {
return
}
// Calculate the edge to calculate distance from
let translation = velocity.x >= 0 ? animatingView.frame.width : -animatingView.frame.width
let timeStep = TimeInterval(abs(translation) / speed)
self.delegate?.swipeAnimator(self, viewWillExitContainerBounds: animatingView)
UIView.animate(withDuration: timeStep, animations: {
animatingView.transform = self.transformForTranslation(translation)
animatingView.alpha = self.alphaForDistanceFromCenter(abs(translation))
}, completion: { finished in
if finished {
animatingView.alpha = 0
}
})
}
fileprivate func transformForTranslation(_ translation: CGFloat) -> CGAffineTransform {
let swipeWidth = animatingView?.frame.size.width ?? 1
let totalRotationInRadians = CGFloat(params.totalRotationInDegrees / 180.0 * Double.pi)
// Determine rotation / scaling amounts by the distance to the edge
let rotation = (translation / swipeWidth) * totalRotationInRadians
let scale = 1 - (abs(translation) / swipeWidth) * (1 - params.totalScale)
let rotationTransform = CGAffineTransform(rotationAngle: rotation)
let scaleTransform = CGAffineTransform(scaleX: scale, y: scale)
let translateTransform = CGAffineTransform(translationX: translation, y: 0)
return rotationTransform.concatenating(scaleTransform).concatenating(translateTransform)
}
fileprivate func alphaForDistanceFromCenter(_ distance: CGFloat) -> CGFloat {
let swipeWidth = animatingView?.frame.size.width ?? 1
return 1 - (distance / swipeWidth) * (1 - params.totalAlpha)
}
}
//MARK: Selectors
extension SwipeAnimator {
@objc func didPan(_ recognizer: UIPanGestureRecognizer!) {
let translation = recognizer.translation(in: animatingView)
switch recognizer.state {
case .began:
prevOffset = containerCenter
case .changed:
animatingView?.transform = transformForTranslation(translation.x)
animatingView?.alpha = alphaForDistanceFromCenter(abs(translation.x))
prevOffset = CGPoint(x: translation.x, y: 0)
case .cancelled:
animateBackToCenter()
case .ended:
let velocity = recognizer.velocity(in: animatingView)
// Bounce back if the velocity is too low or if we have not reached the threshold yet
let speed = max(abs(velocity.x), params.minExitVelocity)
if speed < params.minExitVelocity || abs(prevOffset?.x ?? 0) < params.deleteThreshold {
animateBackToCenter()
} else {
animateAwayWithVelocity(velocity, speed: speed)
}
default:
break
}
}
func close(right: Bool) {
let direction = CGFloat(right ? -1 : 1)
animateAwayWithVelocity(CGPoint(x: -direction * params.minExitVelocity, y: 0), speed: direction * params.minExitVelocity)
}
@discardableResult @objc func closeWithoutGesture() -> Bool {
close(right: false)
return true
}
}
extension SwipeAnimator: UIGestureRecognizerDelegate {
@objc func gestureRecognizerShouldBegin(_ recognizer: UIGestureRecognizer) -> Bool {
let cellView = recognizer.view as UIView!
let panGesture = recognizer as! UIPanGestureRecognizer
let translation = panGesture.translation(in: cellView?.superview)
return fabs(translation.x) > fabs(translation.y)
}
}
| mpl-2.0 | d1dac65a0834f08c7d5a6d9981d032d4 | 37.070513 | 129 | 0.681596 | 5.302679 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.