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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
alblue/swift
|
stdlib/public/core/SmallBuffer.swift
|
1
|
2876
|
//===--- SmallBuffer.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// A specialized type which is a buffer of trivial values utilizing in-line
// storage
//
internal struct _SmallBuffer<T: FixedWidthInteger> {
// FIXME(rdar://45443666): The storage is currently set at 64 bytes, which
// actually hides a normalization bug in validation-test/stdlib/String.swift,
// where exceedingly long segments may compare only the first `n` code units
// worth of a given segment before moving on to the next segment. We'd also
// like to make this be 32-bytes, as commented out below. Adjusting the size
// here was simpler than XFAILing the test, but when fixed, restore size to 32
// bytes.
//
// private var _inlineStorage: (UInt64, UInt64, UInt64, UInt64) = (0,0,0,0)
//
private var _inlineStorage: (
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64
) = (0,0,0,0,0,0,0,0)
internal init() {
_invariantCheck()
}
}
extension _SmallBuffer {
private var stride: Int { return MemoryLayout<T>.stride }
}
extension _SmallBuffer {
private var byteCapacity: Int {
return MemoryLayout.stride(ofValue: _inlineStorage)
}
internal var capacity: Int { return byteCapacity / stride }
internal subscript(i: Int) -> T {
get {
_sanityCheck(i >= 0 && i < capacity)
let capacity = self.capacity
return withUnsafeBytes(of: _inlineStorage) {
let rawPtr = $0.baseAddress._unsafelyUnwrappedUnchecked
let bufPtr = UnsafeBufferPointer(
start: rawPtr.assumingMemoryBound(to: T.self), count: capacity)
return bufPtr[i]
}
}
set {
_sanityCheck(i >= 0 && i < capacity)
let capacity = self.capacity
withUnsafeMutableBytes(of: &_inlineStorage) {
let rawPtr = $0.baseAddress._unsafelyUnwrappedUnchecked
let bufPtr = UnsafeMutableBufferPointer(
start: rawPtr.assumingMemoryBound(to: T.self), count: capacity)
bufPtr[i] = newValue
}
}
}
}
extension _SmallBuffer {
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal mutating func _invariantCheck() {
_sanityCheck(MemoryLayout<_SmallBuffer<Int>>.stride == byteCapacity)
_sanityCheck(capacity * stride == byteCapacity)
_sanityCheck(_isPOD(T.self))
}
#endif // INTERNAL_CHECKS_ENABLED
}
|
apache-2.0
|
57ff8f89d9354fd9f369690bc3377ee7
| 34.073171 | 80 | 0.658206 | 4.174165 | false | false | false | false |
garricn/secret
|
Pods/Cartography/Cartography/Distribute.swift
|
8
|
2384
|
//
// Distribute.swift
// Cartography
//
// Created by Robert Böhnke on 17/02/15.
// Copyright (c) 2015 Robert Böhnke. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
typealias Accumulator = ([NSLayoutConstraint], LayoutProxy)
private func reduce(first: LayoutProxy, rest: [LayoutProxy], combine: (LayoutProxy, LayoutProxy) -> NSLayoutConstraint) -> [NSLayoutConstraint] {
rest.last?.view.car_translatesAutoresizingMaskIntoConstraints = false
return rest.reduce(([], first)) { (acc, current) -> Accumulator in
let (constraints, previous) = acc
return (constraints + [ combine(previous, current) ], current)
}.0
}
/// Distributes multiple views horizontally.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter amount: The distance between the views.
/// - parameter views: The views to distribute.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
public func distribute(by amount: CGFloat, horizontally first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return reduce(first, rest: rest) { $0.trailing == $1.leading - amount }
}
/// Distributes multiple views horizontally from left to right.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter amount: The distance between the views.
/// - parameter views: The views to distribute.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
public func distribute(by amount: CGFloat, leftToRight first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return reduce(first, rest: rest) { $0.right == $1.left - amount }
}
/// Distributes multiple views vertically.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter amount: The distance between the views.
/// - parameter views: The views to distribute.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
public func distribute(by amount: CGFloat, vertically first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return reduce(first, rest: rest) { $0.bottom == $1.top - amount }
}
|
mit
|
5a855361b4a06eacdaabb7c2ad6358fd
| 34.552239 | 145 | 0.70529 | 4.276481 | false | false | false | false |
PokeMapCommunity/PokeMap-iOS
|
Pods/Permission/Source/PermissionTypes/LocationAlways.swift
|
1
|
2252
|
//
// LocationAlways.swift
//
// Copyright (c) 2015-2016 Damien (http://delba.io)
//
// 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 CoreLocation
internal extension Permission {
var statusLocationAlways: PermissionStatus {
guard CLLocationManager.locationServicesEnabled() else { return .Disabled }
let status = CLLocationManager.authorizationStatus()
switch status {
case .AuthorizedAlways: return .Authorized
case .AuthorizedWhenInUse:
return Defaults.requestedLocationAlwaysWithWhenInUse ? .Denied : .NotDetermined
case .NotDetermined: return .NotDetermined
case .Restricted, .Denied: return .Denied
}
}
func requestLocationAlways(callback: Callback) {
guard let _ = NSBundle.mainBundle().objectForInfoDictionaryKey(.nsLocationAlwaysUsageDescription) else {
print("WARNING: \(.nsLocationAlwaysUsageDescription) not found in Info.plist")
return
}
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
Defaults.requestedLocationAlwaysWithWhenInUse = true
}
LocationManager.request(self)
}
}
|
mit
|
08ec8131991ba0a546b16f07cc0f2515
| 40.703704 | 112 | 0.714476 | 5.225058 | false | false | false | false |
salemoh/GoldenQuraniOS
|
GoldenQuranSwift/GoldenQuranSwift/SettingsPageColorTableViewCell.swift
|
1
|
3620
|
//
// SettingsPageColorTableViewCell.swift
// GoldenQuranSwift
//
// Created by Omar Fraiwan on 4/4/17.
// Copyright © 2017 Omar Fraiwan. All rights reserved.
//
import UIKit
class SettingsPageColorTableViewCell: UITableViewCell {
@IBOutlet weak var lblTitle: GQLabel!
@IBOutlet weak var btnColorYellow: UIButton!
@IBOutlet weak var btnColorGreen: UIButton!
@IBOutlet weak var btnColorBlue: UIButton!
@IBOutlet weak var btnColorWhite: UIButton!
@IBOutlet weak var btnColorRed: UIButton!
@IBOutlet weak var btnColorNight: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
refreshSelectedColor()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func sendChangeColorNotifier(){
NotificationCenter.default.post(name: Notification.Name(rawValue: Constants.notifiers.pageColorChanged), object: nil)
}
@IBAction func nighPressed(_ sender: UIButton) {
UserDefaults.standard.set(MushafPageColor.night.rawValue, forKey: Constants.userDefaultsKeys.preferedPageBackgroundColor)
UserDefaults.standard.synchronize()
refreshSelectedColor()
sendChangeColorNotifier()
}
@IBAction func redPressed(_ sender: UIButton) {
UserDefaults.standard.set(MushafPageColor.red.rawValue, forKey: Constants.userDefaultsKeys.preferedPageBackgroundColor)
UserDefaults.standard.synchronize()
refreshSelectedColor()
sendChangeColorNotifier()
}
@IBAction func whitePressed(_ sender: UIButton) {
UserDefaults.standard.set(MushafPageColor.white.rawValue, forKey: Constants.userDefaultsKeys.preferedPageBackgroundColor)
UserDefaults.standard.synchronize()
refreshSelectedColor()
sendChangeColorNotifier()
}
@IBAction func bluePressed(_ sender: UIButton) {
UserDefaults.standard.set(MushafPageColor.blue.rawValue, forKey: Constants.userDefaultsKeys.preferedPageBackgroundColor)
UserDefaults.standard.synchronize()
refreshSelectedColor()
sendChangeColorNotifier()
}
@IBAction func greenPressed(_ sender: UIButton) {
UserDefaults.standard.set(MushafPageColor.green.rawValue, forKey: Constants.userDefaultsKeys.preferedPageBackgroundColor)
UserDefaults.standard.synchronize()
refreshSelectedColor()
sendChangeColorNotifier()
}
@IBAction func yellowPressed(_ sender: UIButton) {
UserDefaults.standard.set(MushafPageColor.yellow.rawValue, forKey: Constants.userDefaultsKeys.preferedPageBackgroundColor)
UserDefaults.standard.synchronize()
refreshSelectedColor()
sendChangeColorNotifier()
}
func refreshSelectedColor() {
for btn in [btnColorRed , btnColorBlue , btnColorGreen , btnColorNight , btnColorWhite , btnColorYellow] {
btn?.shadowColor = UIColor.darkGray
}
switch MushafPageColorManager.currentColor {
case .blue:
btnColorBlue.shadowColor = UIColor.orange
case .red:
btnColorRed.shadowColor = UIColor.orange
case .green:
btnColorGreen.shadowColor = UIColor.orange
case .white:
btnColorWhite.shadowColor = UIColor.orange
case .night:
btnColorNight.shadowColor = UIColor.orange
default:
btnColorYellow.shadowColor = UIColor.orange
}
}
}
|
mit
|
8240048fc86b1649d44b74e6ec8bee78
| 35.19 | 130 | 0.695772 | 4.903794 | false | false | false | false |
remobjects/Marzipan
|
CodeGen4/CGObjectiveCHCodeGenerator.swift
|
1
|
4169
|
public class CGObjectiveCHCodeGenerator : CGObjectiveCCodeGenerator {
public override var defaultFileExtension: String { return "h" }
override func generateForwards() {
for t in currentUnit.Types {
if let type = t as? CGClassTypeDefinition {
Append("@class ")
generateIdentifier(type.Name)
AppendLine(";")
} else if let type = t as? CGInterfaceTypeDefinition {
Append("@protocol ")
generateIdentifier(type.Name)
AppendLine(";")
}
}
}
override func generateImport(_ imp: CGImport) {
AppendLine("#import <\(imp.Name)/\(imp.Name).h>")
}
override func generateFileImport(_ imp: CGImport) {
AppendLine("#import \"\(imp.Name).h\"")
}
//
// Types
//
override func generateAliasType(_ type: CGTypeAliasDefinition) {
}
override func generateBlockType(_ type: CGBlockTypeDefinition) {
}
override func generateEnumType(_ type: CGEnumTypeDefinition) {
Append("typedef NS_ENUM(")
if let baseType = type.BaseType {
generateTypeReference(baseType, ignoreNullability: true)
} else {
Append("NSUInteger")
}
Append(", ")
generateIdentifier(type.Name)
AppendLine(")")
AppendLine("{")
incIndent()
helpGenerateCommaSeparatedList(type.Members) { m in
if let member = m as? CGEnumValueDefinition {
self.generateIdentifier(type.Name+"_"+member.Name) // Obj-C enums must be unique
if let value = member.Value {
self.Append(" = ")
self.generateExpression(value)
}
}
}
AppendLine()
decIndent()
AppendLine("};")
}
override func generateClassTypeStart(_ type: CGClassTypeDefinition) {
Append("@interface ")
generateIdentifier(type.Name)
objcGenerateAncestorList(type)
AppendLine()
// 32-bit OS X Objective-C needs fields declared in @interface, not @implementation
objcGenerateFields(type)
AppendLine()
}
/*override func generateClassTypeEnd(_ type: CGClassTypeDefinition) {
decIndent()
AppendLine(@"end")
}*/
override func generateStructTypeStart(_ type: CGStructTypeDefinition) {
}
override func generateStructTypeEnd(_ type: CGStructTypeDefinition) {
}
override func generateInterfaceTypeStart(_ type: CGInterfaceTypeDefinition) {
Append("@protocol ")
generateIdentifier(type.Name)
objcGenerateAncestorList(type)
AppendLine()
AppendLine()
}
override func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) {
AppendLine()
AppendLine("@end")
}
//
// Type Members
//
override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) {
generateMethodDefinitionHeader(method, type: type)
AppendLine(";")
}
override func generateConstructorDefinition(_ ctor: CGConstructorDefinition, type: CGTypeDefinition) {
generateMethodDefinitionHeader(ctor, type: type)
AppendLine(";")
}
override func generatePropertyDefinition(_ property: CGPropertyDefinition, type: CGTypeDefinition) {
if property.Static {
Append("+ (")
if let type = property.`Type` {
objcGenerateStorageModifierPrefixIfNeeded(property.StorageModifier)
generateTypeReference(type)
if !objcTypeRefereneIsPointer(type) {
Append(" ")
}
} else {
Append("id ")
}
Append(")")
generateIdentifier(property.Name)
AppendLine(";")
} else {
if property.Virtuality == CGMemberVirtualityKind.Override || property.Virtuality == CGMemberVirtualityKind.Final {
Append("// overriden ") // we don't need to re-emit overriden properties in header?
}
Append("@property ")
Append("(")
if property.Atomic {
Append("atomic")
} else {
Append("nonatomic")
}
if let type = property.`Type` {
if type.IsClassType {
//switch type.StorageModifier {
//case .Strong: Append(", strong")
//case .Weak: Append(", weak")
//case .Unretained: Append(", unsafe_unretained")
//}
} else {
//todo?
}
}
if property.ReadOnly {
Append(", readonly")
}
Append(") ")
if let type = property.`Type` {
generateTypeReference(type)
if !objcTypeRefereneIsPointer(type) {
Append(" ")
}
} else {
Append("id ")
}
generateIdentifier(property.Name)
AppendLine(";")
}
}
}
|
bsd-3-clause
|
d108586bb8a3f2a044f47a8f6d4bd335
| 23.232558 | 117 | 0.684905 | 3.632956 | false | false | false | false |
ArnavChawla/InteliChat
|
Carthage/Checkouts/swift-sdk/Source/ConversationV1/Models/WorkspaceExport.swift
|
2
|
2761
|
/**
* Copyright IBM Corporation 2018
*
* 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
/** WorkspaceExport. */
public struct WorkspaceExport: Decodable {
/// The current status of the workspace.
public enum Status: String {
case nonExistent = "Non Existent"
case training = "Training"
case failed = "Failed"
case available = "Available"
case unavailable = "Unavailable"
}
/// The name of the workspace.
public var name: String
/// The description of the workspace.
public var description: String
/// The language of the workspace.
public var language: String
/// Any metadata that is required by the workspace.
public var metadata: [String: JSON]
/// The timestamp for creation of the workspace.
public var created: String?
/// The timestamp for the last update to the workspace.
public var updated: String?
/// The workspace ID.
public var workspaceID: String
/// The current status of the workspace.
public var status: String
/// Whether training data from the workspace can be used by IBM for general service improvements. `true` indicates that workspace training data is not to be used.
public var learningOptOut: Bool
/// An array of intents.
public var intents: [IntentExport]?
/// An array of entities.
public var entities: [EntityExport]?
/// An array of counterexamples.
public var counterexamples: [Counterexample]?
/// An array of objects describing the dialog nodes in the workspace.
public var dialogNodes: [DialogNode]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case name = "name"
case description = "description"
case language = "language"
case metadata = "metadata"
case created = "created"
case updated = "updated"
case workspaceID = "workspace_id"
case status = "status"
case learningOptOut = "learning_opt_out"
case intents = "intents"
case entities = "entities"
case counterexamples = "counterexamples"
case dialogNodes = "dialog_nodes"
}
}
|
mit
|
c93625285c970467c31d9c24d6008823
| 30.735632 | 166 | 0.676929 | 4.703578 | false | false | false | false |
objective-audio/au_v3_sample
|
AudioUnitV3Sample/AudioUnitV3Sample/GeneratorViewController.swift
|
1
|
2863
|
//
// ViewController.swift
// AudioUnitV3Sample
//
// Created by 八十嶋祐樹 on 2015/11/23.
// Copyright © 2015年 Yuki Yasoshima. All rights reserved.
//
import UIKit
import AVFoundation
class GeneratorViewController: UIViewController {
var audioEngine: AVAudioEngine?
override func viewDidLoad() {
super.viewDidLoad()
setupGeneratorAudioUnit()
}
func setupGeneratorAudioUnit() {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch {
print(error)
return
}
// エンジンの生成
let engine = AVAudioEngine()
self.audioEngine = engine
AudioUnitGeneratorSample.registerSubclassOnce
// AVAudioUnitをインスタンス化する。生成処理が終わるとcompletionHandlerが呼ばれる
AVAudioUnit.instantiate(with: AudioUnitGeneratorSample.audioComponentDescription, options: AudioComponentInstantiationOptions(rawValue: 0)) { (audioUnitNode: AVAudioUnit?, err: Error?) -> Void in
guard let audioUnitNode = audioUnitNode else {
if let err = err {
print(err)
}
return
}
// Generatorの処理。サイン波を鳴らす
let generatorUnit = audioUnitNode.auAudioUnit as! AudioUnitGeneratorSample
var phase: Float64 = 0.0
generatorUnit.kernelRenderBlock = { buffer in
// このブロックの中はオーディオのスレッドから呼ばれる
let format = buffer.format
let currentPhase: Float64 = phase
let phasePerFrame: Float64 = 1000.0 / format.sampleRate * 2.0 * Double.pi;
for ch in 0..<format.channelCount {
if let channelData = buffer.floatChannelData {
phase = fillSine(channelData[Int(ch)], length: buffer.frameLength, startPhase: currentPhase, phasePerFrame: phasePerFrame)
}
}
}
// ノードを追加
engine.attach(audioUnitNode)
let sampleRate: Double = AVAudioSession.sharedInstance().sampleRate
let format: AVAudioFormat = AVAudioFormat(standardFormatWithSampleRate: sampleRate, channels: 2)!
// 接続
engine.connect(audioUnitNode, to: engine.mainMixerNode, format: format)
do {
// スタート
try AVAudioSession.sharedInstance().setActive(true)
try engine.start()
} catch {
print(error)
return
}
}
}
}
|
mit
|
73e3cbb61d8b432a7fdfb777f829a383
| 32.185185 | 203 | 0.561012 | 5.149425 | false | false | false | false |
OpenKitten/Meow
|
Sources/Meow/Updatable.swift
|
1
|
4000
|
import Foundation
import NIO
enum KeyPathUpdateError: Error {
case invalidRootOrValue
}
public struct DecoderExtractor: Decodable {
public let decoder: Decoder
public init(from decoder: Decoder) throws {
self.decoder = decoder
}
}
public struct UpdateCodingKey: CodingKey {
public var stringValue: String
public init?(stringValue: String) {
self.stringValue = stringValue
}
public init(_ value: String) {
self.stringValue = value
}
public var intValue: Int?
public init?(intValue: Int) {
return nil
}
}
public protocol MeowWritableKeyPath {
func write<T: KeyPathQueryable>(to: inout T, from container: KeyedDecodingContainer<UpdateCodingKey>) throws -> Bool
}
extension WritableKeyPath: MeowWritableKeyPath where Root: KeyPathQueryable, Value: Decodable {
/// - returns: `true` if the value was changed
public func write<T: KeyPathQueryable>(to: inout T, from container: KeyedDecodingContainer<UpdateCodingKey>) throws -> Bool {
var didUpdate = false
guard var root = to as? Root else {
throw KeyPathUpdateError.invalidRootOrValue
}
let keyString = try Root.makeQueryPath(for: self)
let key = UpdateCodingKey(keyString)
if let newValue = try container.decodeIfPresent(Value.self, forKey: key) {
root[keyPath: self] = newValue
didUpdate = true
} else if let optionalKeyPath = self as? OptionalKeyPath, let isNull = try? container.decodeNil(forKey: key), isNull {
try optionalKeyPath.writeNil(to: &root)
}
// TODO: decode null
// root is converted from T above so this does not fail
// swiftlint:disable force_cast
to = root as! T
return didUpdate
}
}
fileprivate protocol OptionalKeyPath {
func writeNil<T>(to: inout T) throws
}
extension WritableKeyPath: OptionalKeyPath where Value: ExpressibleByNilLiteral {
func writeNil<T>(to: inout T) throws {
guard var root = to as? Root else {
throw KeyPathUpdateError.invalidRootOrValue
}
root[keyPath: self] = nil
to = root as! T
}
}
public extension Decoder {
/// - returns: An array containing the key paths that were updated
public func update<T: KeyPathQueryable>(_ instance: T, withAllowedKeyPaths keyPaths: [MeowWritableKeyPath]) throws -> [PartialKeyPath<T>] {
let container = try self.container(keyedBy: UpdateCodingKey.self)
// must pass as inout to the KeyPath, hence the var
// models are always classes
var instance = instance
var updatedKeyPaths = [PartialKeyPath<T>]()
for keyPath in keyPaths {
let didUpdate = try keyPath.write(to: &instance, from: container)
if didUpdate {
// this should never fail, it would make no sense
// swiftlint:disable force_cast
updatedKeyPaths.append(keyPath as! PartialKeyPath<T>)
}
}
return updatedKeyPaths
}
}
public extension JSONDecoder {
func decoder(from data: Data) throws -> Decoder {
return try self.decode(DecoderExtractor.self, from: data).decoder
}
/// - returns: An array containing the key paths that were updated
public func update<T: QueryableModel>(_ instance: T, from data: Data, withAllowedKeyPaths keyPaths: [MeowWritableKeyPath]) throws -> [PartialKeyPath<T>] {
// It seems not ideal that MeowWritableKeyPath currently is not restricted to Root == T
assert(keyPaths.allSatisfy { $0 as? PartialKeyPath<T> != nil }, "Calling update for a certain model with allowed key paths of a different type does not make sense")
let decoder = try self.decoder(from: data)
return try decoder.update(instance, withAllowedKeyPaths: keyPaths)
}
}
|
mit
|
bd2207e218aaab963d961a68ee630c8f
| 32.898305 | 172 | 0.645 | 4.854369 | false | false | false | false |
ipmobiletech/firefox-ios
|
ClientTests/RelativeDatesTests.swift
|
57
|
2473
|
/* 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 XCTest
class RelativeDatesTests: XCTestCase {
func testRelativeDates() {
let dateOrig = NSDate()
var date = NSDate(timeInterval: 0, sinceDate: dateOrig)
XCTAssertTrue(date.toRelativeTimeString() == "just now")
date = NSDate(timeInterval: 0, sinceDate: dateOrig)
date = date.dateByAddingTimeInterval(-10)
XCTAssertTrue(date.toRelativeTimeString() == "just now")
date = NSDate(timeInterval: 0, sinceDate: dateOrig)
date = date.dateByAddingTimeInterval(-60)
XCTAssertTrue(date.toRelativeTimeString() == ("today at " + NSDateFormatter.localizedStringFromDate(date, dateStyle: NSDateFormatterStyle.NoStyle, timeStyle: NSDateFormatterStyle.ShortStyle)))
date = NSDate(timeInterval: 0, sinceDate: dateOrig)
date = date.dateByAddingTimeInterval(-60 * 60 * 24)
XCTAssertTrue(date.toRelativeTimeString() == "yesterday")
date = NSDate(timeInterval: 0, sinceDate: dateOrig)
date = date.dateByAddingTimeInterval(-60 * 60 * 24 * 2)
XCTAssertTrue(date.toRelativeTimeString() == "this week")
date = NSDate(timeInterval: 0, sinceDate: dateOrig)
date = date.dateByAddingTimeInterval(-60 * 60 * 24 * 7)
XCTAssertTrue(date.toRelativeTimeString() == "more than a week ago")
date = NSDate(timeInterval: 0, sinceDate: dateOrig)
date = date.dateByAddingTimeInterval(-60 * 60 * 24 * 7 * 5)
XCTAssertTrue(date.toRelativeTimeString() == "more than a month ago")
date = NSDate(timeInterval: 0, sinceDate: dateOrig)
date = date.dateByAddingTimeInterval(-60 * 60 * 24 * 7 * 5 * 2)
XCTAssertTrue(date.toRelativeTimeString() == NSDateFormatter.localizedStringFromDate(date, dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.ShortStyle))
date = NSDate(timeInterval: 0, sinceDate: dateOrig)
date = date.dateByAddingTimeInterval(-60 * 60 * 24 * 7 * 5 * 12 * 2)
XCTAssertTrue(date.toRelativeTimeString() == NSDateFormatter.localizedStringFromDate(date, dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.ShortStyle))
}
}
|
mpl-2.0
|
5c1570f75cee21edbdaa0b8638f69e3a
| 51.617021 | 200 | 0.677719 | 4.86811 | false | true | false | false |
laonayt/NewFreshBeen-Swift
|
WEFreshBeen/Classes/Base/Controller/GuidViewController.swift
|
1
|
1660
|
//
// GuidViewController.swift
// WEFreshBeen
//
// Created by WE on 16/5/27.
// Copyright © 2016年 马玮. All rights reserved.
//
import UIKit
class GuidViewController: UIViewController {
var scrollView : UIScrollView?
override func viewDidLoad() {
super.viewDidLoad()
initScrollView()
}
/**
初始化ScrollView
*/
func initScrollView() {
scrollView = UIScrollView(frame: self.view.frame)
scrollView?.contentSize = CGSizeMake(ScreenW * 4, ScreenH)
scrollView?.pagingEnabled = true
self.view.addSubview(scrollView!)
for var i = 0; i < 4; i++ {
let image = UIImage(named: String(format:"guide_35_%d", i + 1))
let imageView = UIImageView(frame: CGRectMake(ScreenW * CGFloat(i), 0, ScreenW, ScreenH))
imageView.image = image
scrollView?.addSubview(imageView)
if i == 3 {
let btn = UIButton(frame: CGRectMake((ScreenW - 80)/2,ScreenH - 100,80,40))
btn.setTitle("立即体验", forState: UIControlState.Normal)
btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
btn.backgroundColor = UIColor.yellowColor()
btn.addTarget(self, action:"btnClick" , forControlEvents: UIControlEvents.TouchUpInside)
imageView.addSubview(btn)
}
}
func btnClick() {
UIApplication.sharedApplication().keyWindow?.rootViewController = WETabBarViewController()
}
}
}
|
apache-2.0
|
5937cfdfbf692125686aa55f442e405f
| 26.779661 | 104 | 0.5723 | 4.951662 | false | false | false | false |
aiaio/DesignStudioExpress
|
DesignStudioExpress/ViewModels/ChallengesViewModel.swift
|
1
|
5718
|
//
// ChallengesViewModel.swift
// DesignStudioExpress
//
// Created by Kristijan Perusko on 11/19/15.
// Copyright © 2015 Alexander Interactive. All rights reserved.
//
import Foundation
import RealmSwift
class ChallengesViewModel {
lazy var realm = try! Realm()
private var designStudio: DesignStudio!
private var data: List<Challenge>!
let buttonLabelTimer = "SHOW TIMER"
let buttonLabelFinished = "ALL DONE. LAUNCH GALLERY"
let buttonLabelBeginDS = "BEGIN DESIGN STUDIO"
let anotherStudioRunningMessageText = "Nice try on multi-tasking, but %@ design studio is already running."
let invalidDesignStudioMessageText = "Your design studio needs at least one challenge (each with at least one activity) before you can start it."
func setDesignStudio(newDesignStudio: DesignStudio) {
if (self.designStudio?.id != newDesignStudio.id) {
self.designStudio = newDesignStudio
self.data = newDesignStudio.challenges
}
}
// +1 because the last row is a button
var totalRows: Int {
get { return data.count + 1 }
}
// 'new' ds has no challenges
var isNewDesignStudio: Bool {
get { return data.count == 0 }
}
var isAnotherStudioRunning: Bool {
get {
if !AppDelegate.designStudio.isDesignStudioRunning {
return false
}
if let runningDSId = AppDelegate.designStudio.currentDesignStudio?.id {
return runningDSId != self.designStudio.id
}
return false
}
}
var beginDesignStudioButtonEnabled: Bool {
return !isNewDesignStudio
}
var beginDesignStudioButtonText: String {
if self.designStudio.finished {
return self.buttonLabelFinished
} else if AppDelegate.designStudio.isDesignStudioRunning && !self.isAnotherStudioRunning {
return self.buttonLabelTimer
}
return self.buttonLabelBeginDS
}
var designStudioTitle: String {
get { return self.designStudio.title }
}
var editingEnabled: Bool {
get { return !self.designStudio.started && !self.designStudio.finished && !self.locked }
}
var locked: Bool {
return self.designStudio.template
}
func canDeleteChallenge(indexPath: NSIndexPath) -> Bool {
let idx = indexPath.row
guard self.data.count > idx && self.editingEnabled else {
return false
}
if let challenge: Challenge = self.data[idx] {
if !challenge.finished && AppDelegate.designStudio.currentChallenge?.id != challenge.id {
return true
}
}
return false
}
func isRowEditable(indexPath: NSIndexPath) -> Bool {
return indexPath.row < data.count
}
func reorderRows(sourceRow: NSIndexPath, destinationRow: NSIndexPath) {
try! realm.write {
self.data.move(from: sourceRow.row, to: destinationRow.row)
}
}
// handler for Delete button
func deleteChallenge(indexPath: NSIndexPath) -> Bool {
let idx = indexPath.row
var success = false
try! self.realm.write {
self.realm.delete(self.data[idx])
success = true
}
return success
}
func getTitle(indexPath: NSIndexPath) -> String {
if self.isRowEditable(indexPath) {
return data[indexPath.row].title
}
return ""
}
func getActivities(indexPath: NSIndexPath) -> String {
if self.isRowEditable(indexPath) {
let activityCount = data[indexPath.row].activities.count
var activityLabel = "Activities"
if (activityCount == 1) {
activityLabel = "Activity"
}
return "\(activityCount) \(activityLabel)"
}
return ""
}
func getDuration(indexPath: NSIndexPath) -> String {
if self.isRowEditable(indexPath) {
let formatter = NSNumberFormatter()
formatter.minimumIntegerDigits = 2
return formatter.stringFromNumber(data[indexPath.row].duration) ?? ""
}
return ""
}
func getChallengesData(indexPath: NSIndexPath?) -> Challenge {
if indexPath != nil && self.isRowEditable(indexPath!) {
return data[indexPath!.row]
}
return createNewChallenge()
}
// if there's an error, return an error message
// otherwise return nil
func actionButtonTouched() -> String? {
if self.isAnotherStudioRunning {
return String(format: self.anotherStudioRunningMessageText, AppDelegate.designStudio.currentDesignStudio?.title ?? "")
}
if !challengesAreValid() {
return self.invalidDesignStudioMessageText
}
AppDelegate.designStudio.challengesScreenActionButton(self.designStudio)
return nil
}
func challengesAreValid() -> Bool {
if self.data.count < 1 {
return false
}
for item in self.data {
if item.activities.count < 1 {
return false
}
}
return true
}
private func createNewChallenge() -> Challenge {
let challenge = Challenge()
let activity = Activity.createDefaultActivity()
challenge.activities.append(activity)
try! realm.write {
self.designStudio.challenges.append(challenge)
}
return challenge
}
}
|
mit
|
5f34cef4f919e1c20b67003e211782f8
| 28.776042 | 149 | 0.596117 | 4.828547 | false | false | false | false |
alienorb/Vectorized
|
Vectorized/Views/SVGView.swift
|
1
|
3939
|
//---------------------------------------------------------------------------------------
// The MIT License (MIT)
//
// Created by Austin Fitzpatrick on 3/18/15 (the "SwiftVG" project)
// Modified by Brian Christensen <[email protected]>
//
// Copyright (c) 2015 Seedling
// Copyright (c) 2016 Alien Orb Software LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//---------------------------------------------------------------------------------------
#if os(OSX)
import AppKit
public typealias BaseView = NSView
#else
import UIKit
public typealias BaseView = UIView
#endif
/// An SVGView provides a way to display SVGGraphics to the screen respecting the contentMode property.
@IBDesignable public class SVGView: BaseView {
@IBInspectable var vectorGraphicName: String? {
didSet {
svgNameChanged()
}
}
#if os(OSX)
public var contentMode: SVGContentMode = .Center {
didSet {
setNeedsDisplay()
}
}
#endif
public var vectorGraphic: SVGGraphic? {
didSet {
setNeedsDisplay()
}
}
public convenience init(vectorGraphic: SVGGraphic?) {
self.init(frame: CGRect(x: 0, y: 0, width: vectorGraphic?.size.width ?? 0, height: vectorGraphic?.size.height ?? 0))
self.vectorGraphic = vectorGraphic
}
/// When the SVG's name changes we'll reparse the new file
private func svgNameChanged() {
guard vectorGraphicName != nil else {
vectorGraphic = nil
return
}
#if !TARGET_INTERFACE_BUILDER
let bundle = NSBundle.mainBundle()
#else
let bundle = NSBundle(forClass: self.dynamicType)
#endif
if let path = bundle.pathForResource(vectorGraphicName, ofType: "svg"), parser = SVGParser(path: path) {
do {
vectorGraphic = try parser.parse()
} catch {
Swift.print("\(self): The SVG parser encountered an error: \(error)")
vectorGraphic = nil
}
} else {
Swift.print("\(self): SVG resource named '\(vectorGraphicName!)' was not found!")
vectorGraphic = nil
}
}
/// Draw the SVGVectorImage to the screen - respecting the contentMode property
override public func drawRect(rect: CGRect) {
super.drawRect(rect)
if let vectorGraphic = vectorGraphic {
if let context = SVGGraphicsGetCurrentContext() {
let translation = vectorGraphic.translationWithTargetSize(rect.size, contentMode: contentMode)
let scale = vectorGraphic.scaleWithTargetSize(rect.size, contentMode: contentMode)
#if os(OSX)
let flipVertical = CGAffineTransform(a: 1.0, b: 0.0, c: 0.0, d: -1.0, tx: 0.0, ty: rect.size.height)
CGContextConcatCTM(context, flipVertical)
#endif
CGContextScaleCTM(context, scale.width, scale.height)
CGContextTranslateCTM(context, translation.x / scale.width, translation.y / scale.height)
vectorGraphic.draw()
}
}
}
/// Interface builder drawing code
#if TARGET_INTERFACE_BUILDER
override func prepareForInterfaceBuilder() {
svgNameChanged()
}
#endif
}
|
mit
|
de03db51f9bdcd81577a255a35d7a93f
| 31.553719 | 118 | 0.690277 | 3.927218 | false | false | false | false |
master-nevi/UPnAtom
|
Source/Management/UPnPEventSubscriptionManager.swift
|
1
|
27151
|
//
// UPnPEventSubscriptionManager.swift
//
// Copyright (c) 2015 David Robles
//
// 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 AFNetworking
import GCDWebServer
protocol UPnPEventSubscriber: class {
func handleEvent(eventSubscriptionManager: UPnPEventSubscriptionManager, eventXML: NSData)
func subscriptionDidFail(eventSubscriptionManager: UPnPEventSubscriptionManager)
}
class UPnPEventSubscriptionManager {
// Subclasses NSObject in order to filter collections of this class using NSPredicate
class Subscription: NSObject {
private(set) var subscriptionID: String
private(set) var expiration: NSDate
weak var subscriber: UPnPEventSubscriber?
let eventURLString: String
private unowned let _manager: UPnPEventSubscriptionManager
private var _renewDate: NSDate {
return expiration.dateByAddingTimeInterval(-30) // attempt renewal 30 seconds before expiration
}
private var _renewWarningTimer: NSTimer?
private var _expirationTimer: NSTimer?
init(subscriptionID: String, expiration: NSDate, subscriber: UPnPEventSubscriber, eventURLString: String, manager: UPnPEventSubscriptionManager) {
self.subscriptionID = subscriptionID
self.expiration = expiration
self.subscriber = subscriber
self.eventURLString = eventURLString
_manager = manager
super.init()
updateTimers()
}
func invalidate() {
_renewWarningTimer?.invalidate()
_expirationTimer?.invalidate()
}
func update(subscriptionID: String, expiration: NSDate) {
self.invalidate()
self.subscriptionID = subscriptionID
self.expiration = expiration
updateTimers()
}
private func updateTimers() {
let renewDate = _renewDate
let expiration = self.expiration
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self._renewWarningTimer = NSTimer.scheduledTimerWithTimeInterval(renewDate.timeIntervalSinceNow, repeats: false, closure: { [weak self] () -> Void in
if let strongSelf = self {
strongSelf._manager.subscriptionNeedsRenewal(strongSelf)
}
})
self._expirationTimer = NSTimer.scheduledTimerWithTimeInterval(expiration.timeIntervalSinceNow, repeats: false, closure: { [weak self] () -> Void in
if let strongSelf = self {
strongSelf._manager.subscriptionDidExpire(strongSelf)
}
})
})
}
}
// internal
static let sharedInstance = UPnPEventSubscriptionManager()
// private
/// Must be accessed within dispatch_sync() or dispatch_async() and updated within dispatch_barrier_async() to the concurrent queue
private var _subscriptions = [String: Subscription]() /* [eventURLString: Subscription] */
private let _concurrentSubscriptionQueue = dispatch_queue_create("com.upnatom.upnp-event-subscription-manager.subscription-queue", DISPATCH_QUEUE_CONCURRENT)
/// Must be accessed within the subscription manager's concurrent queue
private var _httpServer: GCDWebServer! // TODO: Should ideally be a constant, non-optional, see Github issue #10
private let _httpServerPort: UInt = 52808
private let _subscribeSessionManager = AFHTTPSessionManager()
private let _renewSubscriptionSessionManager = AFHTTPSessionManager()
private let _unsubscribeSessionManager = AFHTTPSessionManager()
private let _defaultSubscriptionTimeout: Int = 1800
private let _eventCallBackPath = "/Event/\(NSUUID().dashlessUUIDString)"
init() {
_subscribeSessionManager.requestSerializer = UPnPEventSubscribeRequestSerializer()
_subscribeSessionManager.responseSerializer = UPnPEventSubscribeResponseSerializer()
_renewSubscriptionSessionManager.requestSerializer = UPnPEventRenewSubscriptionRequestSerializer()
_renewSubscriptionSessionManager.responseSerializer = UPnPEventRenewSubscriptionResponseSerializer()
_unsubscribeSessionManager.requestSerializer = UPnPEventUnsubscribeRequestSerializer()
_unsubscribeSessionManager.responseSerializer = UPnPEventUnsubscribeResponseSerializer()
#if os(iOS)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidEnterBackground:", name: UIApplicationDidEnterBackgroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationWillEnterForeground:", name: UIApplicationWillEnterForegroundNotification, object: nil)
#endif
/// GCDWebServer must be initialized on the main thread. In order to guarantee this, it's initialization is dispatched on the main queue. To prevent critical sections from accessing it before it is initialized, the dispatch is synchronized within a dispatch barrier to the subscription manager's critical section queue.
dispatch_barrier_async(_concurrentSubscriptionQueue, { () -> Void in
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
self._httpServer = GCDWebServer()
GCDWebServer.setLogLevel(Int32(3))
self._httpServer.addHandlerForMethod("NOTIFY", path: self._eventCallBackPath, requestClass: GCDWebServerDataRequest.self) { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in
if let dataRequest = request as? GCDWebServerDataRequest,
headers = dataRequest.headers as? [String: AnyObject],
sid = headers["SID"] as? String,
data = dataRequest.data {
LogVerbose("NOTIFY request: Final body with size: \(data.length)\nAll headers: \(headers)")
self.handleIncomingEvent(subscriptionID: sid, eventData: data)
}
return GCDWebServerResponse()
}
})
})
}
/// Subscribers should hold on to a weak reference of the subscription object returned. It's ok to call subscribe for a subscription that already exists, the subscription will simply be looked up and returned.
func subscribe(subscriber: UPnPEventSubscriber, eventURL: NSURL, completion: ((result: Result<AnyObject>) -> Void)? = nil) {
let failureClosure = { (error: NSError) -> Void in
if let completion = completion {
completion(result: .Failure(error))
}
}
guard let eventURLString: String! = eventURL.absoluteString else {
failureClosure(createError("Event URL does not exist"))
return
}
// check if subscription for event URL already exists
subscriptions { [unowned self] (subscriptions: [String: Subscription]) -> Void in
if let subscription = subscriptions[eventURLString] {
if let completion = completion {
completion(result: Result.Success(subscription))
}
return
}
self.eventCallBackURL({ [unowned self] (eventCallBackURL: NSURL?) -> Void in
guard let eventCallBackURL: NSURL = eventCallBackURL else {
failureClosure(createError("Event call back URL could not be created"))
return
}
LogInfo("event callback url: \(eventCallBackURL)")
let parameters = UPnPEventSubscribeRequestSerializer.Parameters(callBack: eventCallBackURL, timeout: self._defaultSubscriptionTimeout)
self._subscribeSessionManager.SUBSCRIBE(eventURL.absoluteString, parameters: parameters, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
guard let response: UPnPEventSubscribeResponseSerializer.Response = responseObject as? UPnPEventSubscribeResponseSerializer.Response else {
failureClosure(createError("Failure serializing event subscribe response"))
return
}
let now = NSDate()
let expiration = now.dateByAddingTimeInterval(NSTimeInterval(response.timeout))
let subscription = Subscription(subscriptionID: response.subscriptionID, expiration: expiration, subscriber: subscriber, eventURLString: eventURL.absoluteString, manager: self)
LogInfo("Successfully subscribed with timeout: \(response.timeout/60) mins: \(subscription)")
self.add(subscription: subscription, completion: { () -> Void in
if let completion = completion {
completion(result: Result.Success(subscription))
}
})
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
LogError("Failed to subscribe to event URL: \(eventURL.absoluteString)\nerror: \(error)")
failureClosure(error)
})
})
}
}
func unsubscribe(subscription: AnyObject, completion: ((result: EmptyResult) -> Void)? = nil) {
guard let subscription: Subscription = subscription as? Subscription else {
if let completion = completion {
completion(result: .Failure(createError("Failure using subscription object passed in")))
}
return
}
// remove local version of subscription immediately to prevent any race conditions
self.remove(subscription: subscription, completion: { [unowned self] () -> Void in
let parameters = UPnPEventUnsubscribeRequestSerializer.Parameters(subscriptionID: subscription.subscriptionID)
self._unsubscribeSessionManager.UNSUBSCRIBE(subscription.eventURLString, parameters: parameters, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
LogInfo("Successfully unsubscribed: \(subscription)")
if let completion = completion {
completion(result: .Success)
}
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
LogError("Failed to unsubscribe: \(subscription)\nerror: \(error)")
if let completion = completion {
completion(result: .Failure(error))
}
})
})
}
private func handleIncomingEvent(subscriptionID subscriptionID: String, eventData: NSData) {
subscriptions { (subscriptions: [String: Subscription]) -> Void in
if let subscription: Subscription = (Array(subscriptions.values) as NSArray).firstUsingPredicate(NSPredicate(format: "subscriptionID = %@", subscriptionID)) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
subscription.subscriber?.handleEvent(self, eventXML: eventData)
return
})
}
}
}
@objc private func applicationDidEnterBackground(notification: NSNotification) {
// GCDWebServer handles stopping and restarting itself as appropriate during application life cycle events. Invalidating the timers is all that's necessary here :)
subscriptions { (subscriptions: [String: Subscription]) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// invalidate all timers before being backgrounded as the will be trashed upon foregrounding anyways
for (_, subscription) in subscriptions {
subscription.invalidate()
}
})
}
}
@objc private func applicationWillEnterForeground(notification: NSNotification) {
subscriptions { [unowned self] (subscriptions: [String: Subscription]) -> Void in
// unsubscribe and re-subscribe for all event subscriptions
for (_, subscription) in subscriptions {
self.unsubscribe(subscription, completion: { (result) -> Void in
self.resubscribe(subscription, completion: {
if let errorDescription = $0.error?.localizedDescriptionOrNil {
LogError("\(errorDescription)")
}
})
})
}
}
}
private func add(subscription subscription: Subscription, completion: (() -> Void)? = nil) {
dispatch_barrier_async(self._concurrentSubscriptionQueue, { () -> Void in
self._subscriptions[subscription.eventURLString] = subscription
self.startStopHTTPServerIfNeeded(self._subscriptions.count)
if let completion = completion {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
completion()
})
}
})
}
private func remove(subscription subscription: Subscription, completion: (() -> Void)? = nil) {
dispatch_barrier_async(self._concurrentSubscriptionQueue, { () -> Void in
self._subscriptions.removeValueForKey(subscription.eventURLString)?.invalidate()
self.startStopHTTPServerIfNeeded(self._subscriptions.count)
if let completion = completion {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
completion()
})
}
})
}
private func eventCallBackURL(closure: (eventCallBackURL: NSURL?) -> Void) {
// only reading subscriptions, so distpach_async is appropriate to allow for concurrent reads
dispatch_async(self._concurrentSubscriptionQueue, { () -> Void in
// needs to be running in order to get server url for the subscription message
let httpServer = self._httpServer
var serverURL: NSURL? = httpServer.serverURL
// most likely nil if the http server is stopped
if serverURL == nil && !httpServer.running {
// Start http server
if self.startHTTPServer() {
// Grab server url
serverURL = httpServer.serverURL
// Stop http server if it's not needed further
self.startStopHTTPServerIfNeeded(self._subscriptions.count)
} else {
LogError("Error starting HTTP server")
}
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
serverURL != nil ? closure(eventCallBackURL: NSURL(string: self._eventCallBackPath, relativeToURL: serverURL)!) : closure(eventCallBackURL: nil)
})
})
}
/// Safe to call from any queue and closure is called on callback queue
private func subscriptions(closure: (subscriptions: [String: Subscription]) -> Void) {
// only reading subscriptions, so distpach_async is appropriate to allow for concurrent reads
dispatch_async(self._concurrentSubscriptionQueue, { () -> Void in
let subscriptions = self._subscriptions
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
closure(subscriptions: subscriptions)
})
})
}
/// Must be called with the most up to date knowledge of the subscription count so should be called withing the subscription queue.
// TODO: consider putting entire method inside a dispatch_barrier_async to subscription queue
private func startStopHTTPServerIfNeeded(subscriptionCount: Int) {
let httpServer = self._httpServer
if subscriptionCount == 0 && httpServer.running {
if !stopHTTPServer() {
LogError("Error stopping HTTP server")
}
} else if subscriptionCount > 0 && !httpServer.running {
if !startHTTPServer() {
LogError("Error starting HTTP server")
}
}
}
private func renewSubscription(subscription: Subscription, completion: ((result: Result<AnyObject>) -> Void)? = nil) {
guard subscription.subscriber != nil else {
if let completion = completion {
completion(result: .Failure(createError("Subscriber doesn't exist anymore")))
}
return
}
let parameters = UPnPEventRenewSubscriptionRequestSerializer.Parameters(subscriptionID: subscription.subscriptionID, timeout: _defaultSubscriptionTimeout)
_renewSubscriptionSessionManager.SUBSCRIBE(subscription.eventURLString, parameters: parameters, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
guard let response: UPnPEventRenewSubscriptionResponseSerializer.Response = responseObject as? UPnPEventRenewSubscriptionResponseSerializer.Response else {
if let completion = completion {
completion(result: .Failure(createError("Failure serializing event subscribe response")))
}
return
}
let now = NSDate()
let expiration = now.dateByAddingTimeInterval(NSTimeInterval(response.timeout))
subscription.update(response.subscriptionID, expiration: expiration)
LogInfo("Successfully renewed subscription with timeout: \(response.timeout/60) mins: \(subscription)")
// read just in case it was removed
self.add(subscription: subscription, completion: { () -> Void in
if let completion = completion {
completion(result: Result.Success(subscription))
}
})
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
LogError("Failed to renew subscription: \(subscription)\nerror: \(error)")
if let completion = completion {
completion(result: .Failure(error))
}
})
}
private func resubscribe(subscription: Subscription, completion: ((result: Result<AnyObject>) -> Void)? = nil) {
// remove, just in case resubscription fails
remove(subscription: subscription)
let failureClosure = { (error: NSError) -> Void in
subscription.subscriber?.subscriptionDidFail(self)
if let completion = completion {
completion(result: .Failure(error))
}
}
// re-subscribe only if subscriber still exists
guard subscription.subscriber != nil else {
failureClosure(createError("Subscriber doesn't exist anymore"))
return
}
self.eventCallBackURL({ [unowned self] (eventCallBackURL: NSURL?) -> Void in
guard let eventCallBackURL: NSURL = eventCallBackURL else {
failureClosure(createError("Event call back URL could not be created"))
return
}
let parameters = UPnPEventSubscribeRequestSerializer.Parameters(callBack: eventCallBackURL, timeout: self._defaultSubscriptionTimeout)
self._subscribeSessionManager.SUBSCRIBE(subscription.eventURLString, parameters: parameters, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
guard let response: UPnPEventSubscribeResponseSerializer.Response = responseObject as? UPnPEventSubscribeResponseSerializer.Response else {
failureClosure(createError("Failure serializing event subscribe response"))
return
}
let now = NSDate()
let expiration = now.dateByAddingTimeInterval(NSTimeInterval(response.timeout))
subscription.update(response.subscriptionID, expiration: expiration)
LogInfo("Successfully re-subscribed with timeout: \(response.timeout/60) mins: \(subscription)")
self.add(subscription: subscription, completion: { () -> Void in
if let completion = completion {
completion(result: Result.Success(subscription))
}
})
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
LogError("Failed to re-subscribe: \(subscription)\nerror: \(error)")
failureClosure(error)
})
})
}
private func subscriptionNeedsRenewal(subscription: Subscription) {
renewSubscription(subscription)
}
private func subscriptionDidExpire(subscription: Subscription) {
resubscribe(subscription, completion: {
if let errorDescription = $0.error?.localizedDescriptionOrNil {
LogError("\(errorDescription)")
}
})
}
private func startHTTPServer() -> Bool {
if _httpServer.safeToStart {
return _httpServer.startWithPort(_httpServerPort, bonjourName: nil)
}
return false
}
private func stopHTTPServer() -> Bool {
if _httpServer.safeToStop {
_httpServer.stop()
return true
}
return false
}
}
internal func ==(lhs: UPnPEventSubscriptionManager.Subscription, rhs: UPnPEventSubscriptionManager.Subscription) -> Bool {
return lhs.subscriptionID == rhs.subscriptionID
}
extension UPnPEventSubscriptionManager.Subscription: ExtendedPrintable {
#if os(iOS)
var className: String { return "Subscription" }
#elseif os(OSX) // NSObject.className actually exists on OSX! Who knew.
override var className: String { return "Subscription" }
#endif
override var description: String {
var properties = PropertyPrinter()
properties.add("subscriptionID", property: subscriptionID)
properties.add("expiration", property: expiration)
properties.add("eventURLString", property: eventURLString)
return properties.description
}
}
extension AFHTTPSessionManager {
func SUBSCRIBE(URLString: String, parameters: AnyObject, success: ((task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void)?, failure: ((task: NSURLSessionDataTask?, error: NSError) -> Void)?) -> NSURLSessionDataTask? {
let dataTask = self.dataTask("SUBSCRIBE", URLString: URLString, parameters: parameters, success: success, failure: failure)
dataTask?.resume()
return dataTask
}
func UNSUBSCRIBE(URLString: String, parameters: AnyObject, success: ((task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void)?, failure: ((task: NSURLSessionDataTask?, error: NSError) -> Void)?) -> NSURLSessionDataTask? {
let dataTask = self.dataTask("UNSUBSCRIBE", URLString: URLString, parameters: parameters, success: success, failure: failure)
dataTask?.resume()
return dataTask
}
private func dataTask(method: String, URLString: String, parameters: AnyObject, success: ((task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void)?, failure: ((task: NSURLSessionDataTask?, error: NSError) -> Void)?) -> NSURLSessionDataTask? {
let request: NSURLRequest!
var serializationError: NSError?
request = try self.requestSerializer.requestWithMethod(method, URLString: NSURL(string: URLString, relativeToURL: self.baseURL)!.absoluteString, parameters: parameters, error: &serializationError)
if let serializationError = serializationError {
if let failure = failure {
dispatch_async(self.completionQueue != nil ? self.completionQueue : dispatch_get_main_queue(), { () -> Void in
failure(task: nil, error: serializationError)
})
}
return nil
}
var dataTask: NSURLSessionDataTask!
dataTask = self.dataTaskWithRequest(request, completionHandler: { (response: NSURLResponse, responseObject: AnyObject?, error: NSError?) -> Void in
if let error = error {
if let failure = failure {
failure(task: dataTask, error: error)
}
} else {
if let success = success {
success(task: dataTask, responseObject: responseObject)
}
}
})
return dataTask
}
}
extension GCDWebServer {
var safeToStart: Bool {
// prevents a crash where although the http server reports running is false, attempting to start while GCDWebServer->_source4 is not null causes abort() to be called which kills the app. GCDWebServer.serverURL == nil is equivalent to GCDWebServer->_source4 == NULL.
return !running && serverURL == nil
}
var safeToStop: Bool {
// prevents a crash where http server must actually be running to stop it or abort() is called which kills the app.
return running
}
}
|
mit
|
29504b99bc7e70888ef514b8f3e9c896
| 49.001842 | 327 | 0.621487 | 5.774351 | false | false | false | false |
suzp1984/IOS-ApiDemo
|
ApiDemo-Swift/ApiDemo-Swift/ImageRenderModeViewController.swift
|
1
|
1822
|
//
// ImageRenderModeViewController.swift
// ApiDemo-Swift
//
// Created by Jacob su on 8/20/16.
// Copyright © 2016 [email protected]. All rights reserved.
//
import UIKit
class ImageRenderModeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.white
let iv = UIImageView()
if let image = UIImage(named: "SmileyTemplate") {
image.withRenderingMode(.automatic)
iv.tintColor = UIColor.red
iv.image = image
}
self.view.addSubview(iv)
iv.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
iv.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
iv.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
iv.widthAnchor.constraint(equalToConstant: 50),
iv.heightAnchor.constraint(equalToConstant: 50)
])
let ib = UIButton()
ib.tintColor = UIColor.red
if let image = UIImage(named: "SmileyVector") {
image.withRenderingMode(.alwaysTemplate)
ib.setBackgroundImage(image, for: UIControlState())
}
self.view.addSubview(ib)
ib.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
ib.topAnchor.constraint(equalTo: iv.bottomAnchor, constant: 10),
ib.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
apache-2.0
|
2a32d4213ae979efed84d0efdc613299
| 30.947368 | 80 | 0.622186 | 5.263006 | false | false | false | false |
Davidde94/StemCode_iOS
|
StemCode/StemProjectKitTests/StemGroupTests.swift
|
1
|
3322
|
//
// StemGroupTests.swift
// StemCodeTests
//
// Created by David Evans on 12/08/2018.
// Copyright © 2018 BlackPoint LTD. All rights reserved.
//
import XCTest
@testable import StemProjectKit
class StemGroupTests: XCTestCase {
func testStemGroupDecodable() {
let testData = """
{
"identifier" : "abc123",
"name" : "Name",
"isFolder" : true,
"childGroups" : [
{
"identifier" : "def456",
"name" : "Second Name",
"isFolder" : false,
"childGroups" : [],
"childFiles" : []
}
],
"childFiles" : ["childFile"],
}
""".data(using: .utf8)!
do {
let codable = try JSONDecoder().decode(StemGroupCodable.self, from: testData)
XCTAssertEqual(codable.identifier, "abc123")
XCTAssertEqual(codable.name, "Name")
XCTAssertEqual(codable.isFolder, true)
XCTAssertEqual(codable.childGroups.count, 1)
XCTAssertEqual(codable.childGroups.first?.identifier, "def456")
XCTAssertEqual(codable.childGroups.first?.name, "Second Name")
XCTAssertEqual(codable.childGroups.first?.isFolder, false)
XCTAssertEqual(codable.childGroups.first?.childGroups.count, 0)
XCTAssertEqual(codable.childGroups.first?.childFiles.count, 0)
XCTAssertEqual(codable.childFiles.count, 1)
XCTAssertEqual(codable.childFiles.first, "childFile")
} catch {
XCTFail(error.localizedDescription)
}
}
func testEncoding() {
let project = Stem(name: "Test", image: nil)
let group = StemGroup(project: project, name: "Test Group", isFolder: true)
let file = StemFile(parentProject: project, name: "Test File", type: .Auto)
group.addChild(file)
let group2 = StemGroup(project: project, name: "Test Group 2", isFolder: true)
group.addChild(group2)
do {
let encoded = try JSONEncoder().encode(group)
let dictionary = try JSONSerialization.jsonObject(with: encoded, options: .allowFragments) as? [AnyHashable : Any]
XCTAssertEqual(dictionary?["identifier"] as? String, group.identifier)
XCTAssertEqual(dictionary?["name"] as? String, group.name)
XCTAssertEqual(dictionary?["isFolder"] as? Bool, group.isFolder)
XCTAssertEqual((dictionary?["childFiles"] as? [String])?.first, file.identifier)
let childGroups = dictionary?["childGroups"] as? [[String : Any]]
XCTAssertEqual(childGroups?.count, 1)
let child = childGroups?.first
XCTAssertEqual(child?["identifier"] as? String, group2.identifier)
XCTAssertEqual(child?["name"] as? String, group2.name)
XCTAssertEqual(child?["isFolder"] as? Bool, group2.isFolder)
XCTAssertEqual((child?["childFiles"] as? [Any])?.count, group2.childFiles.count)
XCTAssertEqual((child?["childGroups"] as? [Any])?.count, group2.childGroups.count)
} catch {
XCTFail(error.localizedDescription)
}
}
func testRemoveFromGroup() {
let project = Stem(name: "Test", image: nil)
let testGroup = StemGroup(project: project, name: "Test Group 1", isFolder: true)
let group = StemGroup(project: project, name: "Test Group 2", isFolder: true)
XCTAssertNil(testGroup.parentGroup)
XCTAssertEqual(group.childGroups.count, 0)
group.addChild(testGroup)
XCTAssertEqual(testGroup.parentGroup, group)
XCTAssertEqual(group.childGroups.count, 1)
testGroup.removeFromParentGroup()
XCTAssertNil(testGroup.parentGroup)
XCTAssertEqual(group.childGroups.count, 0)
}
}
|
mit
|
b7e3f1b52bbbece85079732f154ead3b
| 30.330189 | 117 | 0.711232 | 3.641447 | false | true | false | false |
pennlabs/penn-mobile-ios
|
PennMobile/Laundry/Model/LaundryNotificationCenter.swift
|
1
|
3183
|
//
// LaundryNotificationCenter.swift
// PennMobile
//
// Created by Josh Doman on 11/16/17.
// Copyright © 2017 PennLabs. All rights reserved.
//
import Foundation
import UserNotifications
class LaundryNotificationCenter {
static let shared = LaundryNotificationCenter()
private var identifiers = [LaundryMachine: String]()
func prepare() {
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}
func notifyWithMessage(for machine: LaundryMachine, title: String?, message: String?, completion: @escaping (_ success: Bool) -> Void) {
let center = UNUserNotificationCenter.current()
let minutes = machine.timeRemaining
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
if error != nil {
completion(false)
return
}
if granted {
let content = UNMutableNotificationContent()
if let title = title {
content.title = NSString.localizedUserNotificationString(forKey:
title, arguments: nil)
}
if let message = message {
content.body = NSString.localizedUserNotificationString(forKey:
message, arguments: nil)
}
// Deliver the notification when minutes expire.
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(60 * minutes),
repeats: false)
// Schedule the notification.
let identifier = "\(machine.hashValue)-\(Date().timeIntervalSince1970)"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request, withCompletionHandler: nil)
self.identifiers[machine] = identifier
}
completion(granted)
}
}
func updateForExpiredNotifications(_ completion: @escaping () -> Void) {
UNUserNotificationCenter.current().getPendingNotificationRequests { (requests) in
var newIdentifiers = [LaundryMachine: String]()
for (machine, identifier) in self.identifiers {
if requests.contains(where: { (request) -> Bool in
request.identifier == identifier
}) {
newIdentifiers[machine] = identifier
}
}
self.identifiers = newIdentifiers
completion()
}
}
func removeOutstandingNotification(for machine: LaundryMachine) {
guard let identifier = identifiers[machine] else { return }
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier])
identifiers.removeValue(forKey: machine)
}
func isUnderNotification(for machine: LaundryMachine) -> Bool {
return identifiers[machine] != nil
}
}
|
mit
|
ec8b70233285bfd97593be80feef0113
| 36.880952 | 140 | 0.600251 | 5.881701 | false | false | false | false |
NoryCao/zhuishushenqi
|
zhuishushenqi/TXTReader/BookDetail/Models/QSBook.swift
|
1
|
1708
|
//
// QSBook.swift
// TXTReader
//
// Created by Nory Cao on 2017/4/14.
// Copyright © 2017年 masterY. All rights reserved.
//
import UIKit
/*
暂时不需要这个类,考虑废弃掉
*/
class QSBook: NSObject,NSCoding {
// 只在内存中使用,释放后不保存
var localChapters:[QSChapter] = []
var chapters:[QSChapter] = []
var totalChapters:Int = 1
var bookID:String = "" //bookID为在追书中的ID
var bookName:String = ""
var resources:[ResourceModel]?//书籍来源,这里面有所有的来源id
var curRes:Int = 0 //dhqm选择来源
required init?(coder aDecoder: NSCoder) {
self.localChapters = aDecoder.decodeObject(forKey: "localChapters") as? [QSChapter] ?? []
self.chapters = aDecoder.decodeObject(forKey: "chapters") as! [QSChapter]
self.totalChapters = aDecoder.decodeInteger(forKey: "totalChapters")
self.bookID = aDecoder.decodeObject(forKey: "bookID") as? String ?? ""
self.bookName = aDecoder.decodeObject(forKey: "bookName") as? String ?? ""
self.resources = aDecoder.decodeObject(forKey: "resources") as? [ResourceModel]
self.curRes = aDecoder.decodeInteger(forKey: "curRes")
}
override init() {
}
func encode(with aCoder: NSCoder) {
aCoder.encode(localChapters, forKey: "localChapters")
aCoder.encode(chapters, forKey: "chapters")
aCoder.encode(totalChapters, forKey: "totalChapters")
aCoder.encode(bookID, forKey: "bookID")
aCoder.encode(bookName, forKey: "bookName")
aCoder.encode(resources, forKey: "resources")
aCoder.encode(curRes, forKey: "curRes")
}
}
|
mit
|
fe367b90844cce4a397200c4eb9a1667
| 31.02 | 97 | 0.645222 | 3.68894 | false | false | false | false |
huangboju/Moots
|
算法学习/LeetCode/LeetCode/kthSmallest.swift
|
1
|
1405
|
//
// kthSmallest.swift
// LeetCode
//
// Created by 黄伯驹 on 2019/6/4.
// Copyright © 2019 伯驹 黄. All rights reserved.
//
import Foundation
// https://leetcode-cn.com/explore/interview/card/top-interview-quesitons-in-2018/266/heap-stack-queue/1156/
//有序矩阵中第K小的元素
//给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。
//请注意,它是排序后的第k小元素,而不是第k个元素。
//
//示例:
//
//matrix = [
//[ 1, 5, 9],
//[10, 11, 13],
//[12, 13, 15]
//],
//k = 8,
//
//返回 13。
//说明:
//你可以假设 k 的值永远是有效的, 1 ≤ k ≤ n2 。
func kthSmallest(_ matrix: [[Int]], _ k: Int) -> Int {
if matrix.count == 1 {
return matrix[0][k-1]
}
var result = matrix[0]
for arr in matrix.dropFirst() {
result = mergeSortArr(result, arr)
}
return result[k-1]
}
func mergeSortArr(_ arr1: [Int], _ arr2: [Int]) -> [Int] {
var result = Array(repeating: 0, count: arr1.count + arr2.count)
var i = arr1.count - 1, j = arr2.count - 1
result.replaceSubrange(0...i, with: arr1)
while i >= 0 || j >= 0 {
if j < 0 || (i >= 0 && result[i] > arr2[j]) {
result[i + j + 1] = result[i]
i -= 1
} else {
result[i + j + 1] = arr2[j]
j -= 1
}
}
return result
}
|
mit
|
b28f9d4ba55848a2f3c832d4333decb3
| 21.036364 | 108 | 0.535479 | 2.525 | false | false | false | false |
Jordan150513/DDSwift3Demos
|
DDSwiftDemo2/DDSwiftDemo2/ViewController.swift
|
1
|
22615
|
//
// ViewController.swift
// DDSwiftDemo2
//
// Created by 乔丹丹 on 16/9/20.
// Copyright © 2016年 Fang. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var checkImageView : UIImageView!
var usernameTextField : UITextField!
var passwordTextField : UITextField!
var usernamePasswordDict : NSMutableDictionary!
var userNamesTableView : UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: false)
self.title = "Swift Demo2 - login"
//创建UI
createUI()
}
//创建UI
func createUI() {
//背景图片
let backGroundImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
backGroundImageView.image = UIImage(named: "IOS背景图片")
backGroundImageView.isUserInteractionEnabled = true
self.view.addSubview(backGroundImageView)
let logoImageView = UIImageView(image: UIImage(named:"登录logo370x150"))
//遗漏了这个
logoImageView.translatesAutoresizingMaskIntoConstraints = false
logoImageView.contentMode = .scaleAspectFill
backGroundImageView.addSubview(logoImageView)
/*
let top = NSLayoutConstraint(item: logoImageView, attribute: .top, relatedBy: .equal, toItem: backGroundImageView, attribute: .top, multiplier: 1.0, constant: 100)
backGroundImageView.addConstraint(top)
let leading = NSLayoutConstraint(item: logoImageView, attribute: .leading, relatedBy: .equal, toItem: backGroundImageView, attribute: .leading, multiplier: 1.0, constant: 100)
backGroundImageView.addConstraint(leading)
let trailing = NSLayoutConstraint(item: logoImageView, attribute: .trailing, relatedBy: .equal, toItem: backGroundImageView, attribute: .trailing, multiplier: 1.0, constant: -100)
backGroundImageView.addConstraint(trailing)
let height = NSLayoutConstraint(item: logoImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 80)
logoImageView.addConstraint(height)
*/
//还可以用VFL(Visual Format Language)语法布局--------
let dict = ["logoImageView": logoImageView]
let logoImageView_Constraint_H = NSLayoutConstraint.constraints(withVisualFormat: "H:|-100-[logoImageView]-100-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
let logoImageView_Constraint_V = NSLayoutConstraint.constraints(withVisualFormat: "V:|-100-[logoImageView(\(80))]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
backGroundImageView.addConstraints(logoImageView_Constraint_V)
backGroundImageView.addConstraints(logoImageView_Constraint_H)
//用户名输入框背景
let userNameBGView = UIView()
userNameBGView.backgroundColor = UIColor.white
userNameBGView.layer.cornerRadius = 3
userNameBGView.layer.masksToBounds = true
userNameBGView.isUserInteractionEnabled = true
userNameBGView.translatesAutoresizingMaskIntoConstraints = false
backGroundImageView.addSubview(userNameBGView)
let userNameBGView_leading = NSLayoutConstraint(item: userNameBGView, attribute: .leading, relatedBy: .equal, toItem: backGroundImageView, attribute: .leading, multiplier: 1.0, constant: 40)
backGroundImageView.addConstraint(userNameBGView_leading)
let userNameBGView_top = NSLayoutConstraint(item: userNameBGView, attribute: .top, relatedBy: .equal, toItem: logoImageView, attribute: .bottom, multiplier: 1.0, constant: 30)
backGroundImageView.addConstraint(userNameBGView_top)
let userNameBGView_trailing = NSLayoutConstraint(item: userNameBGView, attribute: .trailing, relatedBy: .equal, toItem: backGroundImageView, attribute: .trailing, multiplier: 1.0, constant: -40)
backGroundImageView.addConstraint(userNameBGView_trailing)
let userNameBGView_height = NSLayoutConstraint(item: userNameBGView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 40)
userNameBGView.addConstraint(userNameBGView_height)
//密码框输入背景
let passwordBGView = UIView()
passwordBGView.backgroundColor = UIColor.white
passwordBGView.layer.cornerRadius = 3
passwordBGView.layer.masksToBounds = true
passwordBGView.isUserInteractionEnabled = true
passwordBGView.translatesAutoresizingMaskIntoConstraints = false
backGroundImageView.addSubview(passwordBGView)
let passwordBGView_leading = NSLayoutConstraint(item: passwordBGView, attribute: .leading, relatedBy: .equal, toItem: backGroundImageView, attribute: .leading, multiplier: 1.0, constant: 40)
backGroundImageView.addConstraint(passwordBGView_leading)
let passwordBGView_top = NSLayoutConstraint(item: passwordBGView, attribute: .top, relatedBy: .equal, toItem: userNameBGView, attribute: .bottom, multiplier: 1.0, constant: 20)
backGroundImageView.addConstraint(passwordBGView_top)
let passwordBGView_trailing = NSLayoutConstraint(item: passwordBGView, attribute: .trailing, relatedBy: .equal, toItem: backGroundImageView, attribute: .trailing, multiplier: 1.0, constant: -40)
backGroundImageView.addConstraint(passwordBGView_trailing)
let passwordBGView_height = NSLayoutConstraint(item: passwordBGView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 40)
passwordBGView.addConstraint(passwordBGView_height)
//用户名icon
let userNameIconimageV = UIImageView(image: UIImage(named: "IOS用户图标"))
userNameIconimageV.contentMode = .scaleAspectFit
userNameBGView.addSubview(userNameIconimageV)
userNameIconimageV.translatesAutoresizingMaskIntoConstraints = false
userNameBGView.addSubview(userNameIconimageV)
let userNameIconimageV_leading = NSLayoutConstraint(item: userNameIconimageV, attribute: .leading, relatedBy: .equal, toItem: userNameBGView, attribute: .leading, multiplier: 1.0, constant: 5)
backGroundImageView.addConstraint(userNameIconimageV_leading)
let userNameIconimageV_top = NSLayoutConstraint(item: userNameIconimageV, attribute: .top, relatedBy: .equal, toItem: userNameBGView, attribute: .top, multiplier: 1.0, constant: 12)
backGroundImageView.addConstraint(userNameIconimageV_top)
let userNameIconimageV_bottom = NSLayoutConstraint(item: userNameIconimageV, attribute: .bottom, relatedBy: .equal, toItem: userNameBGView, attribute: .bottom, multiplier: 1.0, constant: -12)
backGroundImageView.addConstraint(userNameIconimageV_bottom)
let userNameIconimageV_width = NSLayoutConstraint(item: userNameIconimageV, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 14)
backGroundImageView.addConstraint(userNameIconimageV_width)
//密码icon
let passwordIconimageV = UIImageView(image: UIImage(named: "密码锁"))
passwordIconimageV.contentMode = .scaleAspectFit
passwordBGView.addSubview(passwordIconimageV)
passwordIconimageV.translatesAutoresizingMaskIntoConstraints = false
passwordBGView.addSubview(passwordIconimageV)
let passwordIconimageV_leading = NSLayoutConstraint(item: passwordIconimageV, attribute: .leading, relatedBy: .equal, toItem: passwordBGView, attribute: .leading, multiplier: 1.0, constant: 5)
backGroundImageView.addConstraint(passwordIconimageV_leading)
let passwordIconimageV_top = NSLayoutConstraint(item: passwordIconimageV, attribute: .top, relatedBy: .equal, toItem: passwordBGView, attribute: .top, multiplier: 1.0, constant: 12)
backGroundImageView.addConstraint(passwordIconimageV_top)
let passwordIconimageV_bottom = NSLayoutConstraint(item: passwordIconimageV, attribute: .bottom, relatedBy: .equal, toItem: passwordBGView, attribute: .bottom, multiplier: 1.0, constant: -12)
backGroundImageView.addConstraint(passwordIconimageV_bottom)
let passwordIconimageV_width = NSLayoutConstraint(item: passwordIconimageV, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 14)
backGroundImageView.addConstraint(passwordIconimageV_width)
//用户名输入textfield
usernameTextField = UITextField()
usernameTextField.placeholder = "请输入用户名"
// usernameTextField.backgroundColor = UIColor.green
usernameTextField.translatesAutoresizingMaskIntoConstraints = false
usernameTextField.clearButtonMode = .whileEditing
userNameBGView.addSubview(usernameTextField)
let usernameTextField_leading = NSLayoutConstraint(item: usernameTextField, attribute: .leading, relatedBy: .equal, toItem: userNameIconimageV, attribute: .trailing, multiplier: 1.0, constant: 5)
userNameBGView.addConstraint(usernameTextField_leading)
let usernameTextField_top = NSLayoutConstraint(item: usernameTextField, attribute: .top, relatedBy: .equal, toItem: userNameBGView, attribute: .top, multiplier: 1.0, constant: 0)
backGroundImageView.addConstraint(usernameTextField_top)
let usernameTextField_bottom = NSLayoutConstraint(item: usernameTextField, attribute: .bottom, relatedBy: .equal, toItem: userNameBGView, attribute: .bottom, multiplier: 1.0, constant: 0)
backGroundImageView.addConstraint(usernameTextField_bottom)
let usernameTextField_trailing = NSLayoutConstraint(item: usernameTextField, attribute: .trailing, relatedBy: .equal, toItem: userNameBGView, attribute: .trailing, multiplier: 1.0, constant: -30)
backGroundImageView.addConstraint(usernameTextField_trailing)
// //用户名下拉三角
// let arrowImageView = UIImageView(image: UIImage(named: "arrow_shu"))
// arrowImageView.translatesAutoresizingMaskIntoConstraints = false
// arrowImageView.isUserInteractionEnabled = true
// arrowImageView.contentMode = .scaleAspectFit
// userNameBGView.addSubview(arrowImageView)
// let arrowImageView_leading = NSLayoutConstraint(item: arrowImageView, attribute: .leading, relatedBy: .equal, toItem: usernameTextField, attribute: .trailing, multiplier: 1.0, constant: 10)
// userNameBGView.addConstraint(arrowImageView_leading)
//
// let arrowImageView_top = NSLayoutConstraint(item: arrowImageView, attribute: .top, relatedBy: .equal, toItem: userNameBGView, attribute: .top, multiplier: 1.0, constant: 17)
// backGroundImageView.addConstraint(arrowImageView_top)
//
// let arrowImageView_trailing = NSLayoutConstraint(item: arrowImageView, attribute: .trailing, relatedBy: .equal, toItem: userNameBGView, attribute: .trailing, multiplier: 1.0, constant: -10)
// backGroundImageView.addConstraint(arrowImageView_trailing)
//
// let arrowImageView_bottom = NSLayoutConstraint(item: arrowImageView, attribute: .bottom, relatedBy: .equal, toItem: userNameBGView, attribute: .bottom, multiplier: 1.0, constant: -17)
// backGroundImageView.addConstraint(arrowImageView_bottom)
//用户名下拉三角Btn
let arrowBtn = UIButton(type: .custom)
arrowBtn.setImage(UIImage(named: "arrow_shu"), for: .normal)
arrowBtn.imageView?.contentMode = .scaleAspectFit
userNameBGView.addSubview(arrowBtn)
//总是忘记这个,不加上这个就不会出现布局效果
arrowBtn.translatesAutoresizingMaskIntoConstraints = false
let arrowBtn_leading = NSLayoutConstraint(item: arrowBtn, attribute: .leading, relatedBy: .equal, toItem: usernameTextField, attribute: .trailing, multiplier: 1.0, constant: 0)
userNameBGView.addConstraint(arrowBtn_leading)
let arrowBtn_top = NSLayoutConstraint(item: arrowBtn, attribute: .top, relatedBy: .equal, toItem: userNameBGView, attribute: .top, multiplier: 1.0, constant: 0)
backGroundImageView.addConstraint(arrowBtn_top)
let arrowBtn_trailing = NSLayoutConstraint(item: arrowBtn, attribute: .trailing, relatedBy: .equal, toItem: userNameBGView, attribute: .trailing, multiplier: 1.0, constant: 0)
backGroundImageView.addConstraint(arrowBtn_trailing)
let arrowBtn_bottom = NSLayoutConstraint(item: arrowBtn, attribute: .bottom, relatedBy: .equal, toItem: userNameBGView, attribute: .bottom, multiplier: 1.0, constant: 0)
backGroundImageView.addConstraint(arrowBtn_bottom)
arrowBtn.addTarget(self, action: #selector(ViewController.arrowBtnClicked), for: UIControlEvents.touchUpInside)
//密码输入textfield
passwordTextField = UITextField()
passwordTextField.placeholder = "请输入密码"
// passwordTextField.backgroundColor = UIColor.green
passwordTextField.translatesAutoresizingMaskIntoConstraints = false
passwordBGView.addSubview(passwordTextField)
let passwordTextField_leading = NSLayoutConstraint(item: passwordTextField, attribute: .leading, relatedBy: .equal, toItem: passwordIconimageV, attribute: .trailing, multiplier: 1.0, constant: 5)
passwordBGView.addConstraint(passwordTextField_leading)
let passwordTextField_top = NSLayoutConstraint(item: passwordTextField, attribute: .top, relatedBy: .equal, toItem: passwordBGView, attribute: .top, multiplier: 1.0, constant: 0)
backGroundImageView.addConstraint(passwordTextField_top)
let passwordTextField_bottom = NSLayoutConstraint(item: passwordTextField, attribute: .bottom, relatedBy: .equal, toItem: passwordBGView, attribute: .bottom, multiplier: 1.0, constant: 0)
backGroundImageView.addConstraint(passwordTextField_bottom)
let passwordTextField_trailing = NSLayoutConstraint(item: passwordTextField, attribute: .trailing, relatedBy: .equal, toItem: passwordBGView, attribute: .trailing, multiplier: 1.0, constant: -30)
backGroundImageView.addConstraint(passwordTextField_trailing)
//登陆按钮
let loginBtn = UIButton(type: .custom)
loginBtn.setTitle("登录", for: .normal)
loginBtn.backgroundColor = UIColor.blue
loginBtn.layer.cornerRadius = 20
loginBtn.layer.masksToBounds = true
loginBtn.translatesAutoresizingMaskIntoConstraints = false
backGroundImageView.addSubview(loginBtn)
let loginBtn_leading = NSLayoutConstraint(item: loginBtn, attribute: .leading, relatedBy: .equal, toItem: backGroundImageView, attribute: .leading, multiplier: 1.0, constant: 30)
self.view.addConstraint(loginBtn_leading)
let loginBtn_top = NSLayoutConstraint(item: loginBtn, attribute: .top, relatedBy: .equal, toItem: passwordBGView, attribute: .bottom, multiplier: 1.0, constant: 60)
self.view.addConstraint(loginBtn_top)
let loginBtn_trailing = NSLayoutConstraint(item: loginBtn, attribute: .trailing, relatedBy: .equal, toItem: backGroundImageView, attribute: .trailing, multiplier: 1.0, constant: -30)
self.view.addConstraint(loginBtn_trailing)
let loginBtn_height = NSLayoutConstraint(item: loginBtn, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 40)
loginBtn.addConstraint(loginBtn_height)
loginBtn.addTarget(self, action: #selector(ViewController.loginBtnClicked), for: .touchUpInside)
//记住密码按钮
let rememberPasswordBtn = UIButton(type: .custom)
rememberPasswordBtn.setTitle("记住密码", for: .normal)
rememberPasswordBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
rememberPasswordBtn.translatesAutoresizingMaskIntoConstraints = false
rememberPasswordBtn.titleLabel?.textAlignment = .left
backGroundImageView.addSubview(rememberPasswordBtn)
let rememberPasswordBtn_top = NSLayoutConstraint(item: rememberPasswordBtn, attribute: .top, relatedBy: .equal, toItem: passwordBGView, attribute: .bottom, multiplier: 1.0, constant: 10)
backGroundImageView.addConstraint(rememberPasswordBtn_top)
let rememberPasswordBtn_trailing = NSLayoutConstraint(item: rememberPasswordBtn, attribute: .trailing, relatedBy: .equal, toItem: passwordBGView, attribute: .trailing, multiplier: 1.0, constant: 0)
backGroundImageView.addConstraint(rememberPasswordBtn_trailing)
let rememberPasswordBtn_height = NSLayoutConstraint(item: rememberPasswordBtn, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 30)
rememberPasswordBtn.addConstraint(rememberPasswordBtn_height)
rememberPasswordBtn.addTarget(self, action: #selector(ViewController.rememberBtnClicked), for: .touchUpInside)
let rememberBoxBtn = UIButton(type: .custom)
rememberBoxBtn.setImage(UIImage(named: "记住密码9603.9.0"), for: .normal)
rememberBoxBtn.translatesAutoresizingMaskIntoConstraints = false
rememberBoxBtn.imageView?.contentMode = .scaleAspectFit
rememberBoxBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)
rememberBoxBtn.layoutIfNeeded()
backGroundImageView.addSubview(rememberBoxBtn)
let rememberBoxBtn_top = NSLayoutConstraint(item: rememberBoxBtn, attribute: .top, relatedBy: .equal, toItem: rememberPasswordBtn, attribute: .top, multiplier: 1.0, constant: 10)
backGroundImageView.addConstraint(rememberBoxBtn_top)
let rememberBoxBtn_trailing = NSLayoutConstraint(item: rememberBoxBtn, attribute: .trailing, relatedBy: .equal, toItem: rememberPasswordBtn, attribute: .leading, multiplier: 1.0, constant: 0)
backGroundImageView.addConstraint(rememberBoxBtn_trailing)
let rememberBoxBtn_height = NSLayoutConstraint(item: rememberBoxBtn, attribute: .height, relatedBy: .equal, toItem: rememberPasswordBtn, attribute: .height, multiplier: 1.0, constant: -20)
backGroundImageView.addConstraint(rememberBoxBtn_height)
let rememberBoxBtn_width = NSLayoutConstraint(item: rememberBoxBtn, attribute: .width, relatedBy: .equal, toItem: rememberBoxBtn, attribute: .height, multiplier: 1.0, constant: 0)
backGroundImageView.addConstraint(rememberBoxBtn_width)
// rememberBoxBtn.addTarget(self, action: #selector(ViewController.rememberBtnClicked), for: .touchUpInside)
checkImageView = UIImageView(image: UIImage(named: "对勾9603.9.0"))
checkImageView.contentMode = .scaleAspectFit
checkImageView.translatesAutoresizingMaskIntoConstraints = false
checkImageView.backgroundColor = UIColor.clear
rememberBoxBtn.addSubview(checkImageView)
let checkImageView_leading = NSLayoutConstraint(item: checkImageView, attribute: .leading, relatedBy: .equal, toItem: rememberBoxBtn, attribute: .leading, multiplier: 1.0, constant: 0)
backGroundImageView.addConstraint(checkImageView_leading)
let checkImageView_top = NSLayoutConstraint(item: checkImageView, attribute: .top, relatedBy: .equal, toItem: rememberBoxBtn, attribute: .top, multiplier: 1.0, constant: 0)
backGroundImageView.addConstraint(checkImageView_top)
let checkImageView_trailing = NSLayoutConstraint(item: checkImageView, attribute: .trailing, relatedBy: .equal, toItem: rememberBoxBtn, attribute: .trailing, multiplier: 1.0, constant: 0)
backGroundImageView.addConstraint(checkImageView_trailing)
let checkImageView_bottom = NSLayoutConstraint(item: checkImageView, attribute: .bottom, relatedBy: .equal, toItem: rememberBoxBtn, attribute: .bottom, multiplier: 1.0, constant: 0)
backGroundImageView.addConstraint(checkImageView_bottom)
checkImageView.isHidden = true
//用户名的tableView下拉tableView
userNamesTableView = UITableView(frame: CGRect.zero, style: .plain)
userNamesTableView.translatesAutoresizingMaskIntoConstraints = false
backGroundImageView.addSubview(userNamesTableView)
userNamesTableView.delegate = self
userNamesTableView.dataSource = self
}
//table的数据源
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
// func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//
// }
//tableView代理方法
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
//记住按钮的点击事件
func rememberBtnClicked() {
checkImageView.isHidden = !checkImageView.isHidden
}
//登录按钮的点击事件
func loginBtnClicked() {
if (usernameTextField.text?.isEmpty)!||usernameTextField.text==nil {
print("请输入用户名")
}else if (passwordTextField.text?.isEmpty)!||passwordTextField.text == nil{
print("请输入密码")
}else{
loginAndRemeberUsers()
}
}
//进行登陆操作和记住密码
func loginAndRemeberUsers() {
if !checkImageView.isHidden {
//需要记住密码
usernamePasswordDict = NSMutableDictionary(capacity: 10)
usernamePasswordDict.setValue(passwordTextField.text, forKey: usernameTextField.text!)
}
}
//用户名下拉箭头按钮的点击事件
func arrowBtnClicked() {
if usernamePasswordDict.count>0 {
//让用户名的tableview显示出来
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
bf2e2ef0638c5d9ad9d4a5ae8adc6a74
| 61.948864 | 205 | 0.723215 | 4.968161 | false | false | false | false |
Eonil/Editor
|
Editor4/MainMenuPalette.swift
|
1
|
5604
|
//
// MainMenuPalette.swift
// Editor4
//
// Created by Hoon H. on 2016/04/30.
// Copyright © 2016 Eonil. All rights reserved.
//
import AppKit
struct MainMenuPalette {
// Keep menu item identifier length < 64.
let file = submenuContainerWithTitle(.File)
let fileNew = submenuContainerWithTitle(.FileNew)
let fileNewWorkspace = menuItemWithAction(.FileNewWorkspace)
let fileNewFolder = menuItemWithAction(.FileNewFolder)
let fileNewFile = menuItemWithAction(.FileNewFile)
let fileOpen = submenuContainerWithTitle(.FileOpen)
let fileOpenWorkspace = menuItemWithAction(.FileOpenWorkspace)
let fileOpenClearWorkspaceHistory = menuItemWithAction(.FileOpenClearWorkspaceHistory)
let fileCloseFile = menuItemWithAction(.FileCloseFile)
let fileCloseWorkspace = menuItemWithAction(.FileCloseWorkspace)
let fileDelete = menuItemWithAction(.FileDelete)
let fileShowInFinder = menuItemWithAction(.FileShowInFinder)
let fileShowInTerminal = menuItemWithAction(.FileShowInTerminal)
let view = submenuContainerWithTitle(.View)
let viewEditor = menuItemWithAction(.ViewEditor)
let viewNavigators = submenuContainerWithTitle(.ViewShowNavigator)
let viewShowProjectNavigator = menuItemWithAction(.ViewShowProjectNavigator)
let viewShowIssueNavigator = menuItemWithAction(.ViewShowIssueNavigator)
let viewShowDebugNavigator = menuItemWithAction(.ViewShowDebugNavigator)
let viewHideNavigator = menuItemWithAction(.ViewHideNavigator)
let viewConsole = menuItemWithAction(.ViewConsole)
let viewFullScreen = menuItemWithAction(.ViewFullScreen)
let editor = submenuContainerWithTitle(.Editor)
let editorShowCompletions = menuItemWithAction(.EditorShowCompletions)
let product = submenuContainerWithTitle(.Product)
let productRun = menuItemWithAction(.ProductRun)
let productBuild = menuItemWithAction(.ProductBuild)
let productClean = menuItemWithAction(.ProductClean)
let productStop = menuItemWithAction(.ProductStop)
let debug = submenuContainerWithTitle(.Debug)
let debugPause = menuItemWithAction(.DebugPause)
let debugResume = menuItemWithAction(.DebugResume)
let debugHalt = menuItemWithAction(.DebugHalt)
let debugStepInto = menuItemWithAction(.DebugStepInto)
let debugStepOut = menuItemWithAction(.DebugStepOut)
let debugStepOver = menuItemWithAction(.DebugStepOver)
let debugClearConsole = menuItemWithAction(.DebugClearConsole)
init() {
file.subcontrollers = ([
fileNew,
fileOpen,
separator(),
fileCloseFile,
fileCloseWorkspace,
separator(),
fileDelete,
fileShowInFinder,
fileShowInTerminal,
])
fileNew.subcontrollers = ([
fileNewWorkspace,
fileNewFile,
fileNewFolder,
])
fileOpen.subcontrollers = ([
fileOpenWorkspace,
fileOpenClearWorkspaceHistory,
])
view.subcontrollers = ([
viewEditor,
viewNavigators,
viewConsole,
separator(),
viewFullScreen,
])
viewNavigators.subcontrollers = ([
viewShowProjectNavigator,
viewShowIssueNavigator,
viewShowDebugNavigator,
separator(),
viewHideNavigator,
])
editor.subcontrollers = ([
editorShowCompletions,
])
product.subcontrollers = ([
productRun,
productBuild,
productClean,
separator(),
productStop,
])
debug.subcontrollers = ([
debugPause,
debugResume,
debugHalt,
separator(),
debugStepInto,
debugStepOut,
debugStepOver,
separator(),
debugClearConsole,
])
}
func topLevelMenuItemControllers() -> [MenuItemController] {
return [file, view, editor, product, debug]
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private func separator() -> MenuItemController {
return MenuItemController(type: .Separator)
}
private func submenuContainerWithTitle(mainMenuSubmenuID: MainMenuSubmenuID) -> MenuItemController {
let submenuID = MenuSubmenuID.Main(mainMenuSubmenuID)
return MenuItemController(type: .Submenu(submenuID))
}
private func menuItemWithAction(mainMenuCommand: MainMenuCommand) -> MenuItemController {
let command = MenuCommand.main(mainMenuCommand)
return MenuItemController(type: .MenuItem(command))
}
|
mit
|
09ad8d1a3cfbe82e8133a8f20d59fc18
| 31.387283 | 128 | 0.562556 | 5.547525 | false | false | false | false |
breadwallet/breadwallet-ios
|
breadwallet/src/Views/EnterPhraseCell.swift
|
1
|
7565
|
//
// EnterPhraseCell.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-02-24.
// Copyright © 2017-2019 Breadwinner AG. All rights reserved.
//
import UIKit
class EnterPhraseCell: UICollectionViewCell {
// MARK: - Public
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
private func cellPlaceHolder(_ index: Int) -> NSAttributedString {
return NSAttributedString(string: "\(index + 1)", attributes: [NSAttributedString.Key.foregroundColor: Theme.tertiaryText])
}
func updatePlaceholder() {
if let text = textField.text, text.isEmpty, let index = self.index, !textField.isFirstResponder {
textField.attributedPlaceholder = self.cellPlaceHolder(index)
} else {
textField.attributedPlaceholder = nil
}
}
var index: Int? {
didSet {
updatePlaceholder()
}
}
private(set) var text: String?
var didTapPrevious: (() -> Void)? {
didSet {
previousField.tap = didTapPrevious
}
}
var didTapNext: (() -> Void)? {
didSet {
nextField.tap = didTapNext
}
}
var didTapDone: (() -> Void)? {
didSet {
done.tap = {
self.textField.resignFirstResponder()
self.didTapDone?()
}
}
}
var didEnterSpace: (() -> Void)?
var isWordValid: ((String) -> Bool)?
var didPasteWords: (([String]) -> Bool)?
func disablePreviousButton() {
previousField.tintColor = .secondaryShadow
previousField.isEnabled = false
}
func disableNextButton() {
nextField.tintColor = .secondaryShadow
nextField.isEnabled = false
}
// MARK: - Private
let textField = UITextField()
private let nextField = UIButton.icon(image: #imageLiteral(resourceName: "RightArrow"), accessibilityLabel: S.RecoverWallet.rightArrow)
private let previousField = UIButton.icon(image: #imageLiteral(resourceName: "LeftArrow"), accessibilityLabel: S.RecoverWallet.leftArrow)
private let done = UIButton(type: .system)
fileprivate let focusBar = UIView(color: Theme.accent)
fileprivate var hasDisplayedInvalidState = false
private func setup() {
backgroundColor = Theme.tertiaryBackground
contentView.backgroundColor = Theme.tertiaryBackground
contentView.layer.cornerRadius = 2.0
contentView.layer.masksToBounds = true
contentView.addSubview(textField)
contentView.addSubview(focusBar)
textField.constrain([
textField.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
textField.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
textField.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
])
focusBar.constrain([
focusBar.leftAnchor.constraint(equalTo: contentView.leftAnchor),
focusBar.rightAnchor.constraint(equalTo: contentView.rightAnchor),
focusBar.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
focusBar.heightAnchor.constraint(equalToConstant: 2)
])
hideFocusBar()
setData()
}
private func showFocusBar() {
focusBar.isHidden = false
}
private func hideFocusBar() {
focusBar.isHidden = true
}
private func setData() {
textField.textColor = .white
textField.inputAccessoryView = accessoryView
textField.autocorrectionType = .no
textField.textAlignment = .center
textField.autocapitalizationType = .none
textField.font = E.isSmallScreen ? Theme.body2 : Theme.body1
textField.delegate = self
textField.addTarget(self, action: #selector(EnterPhraseCell.textChanged(textField:)), for: .editingChanged)
previousField.tintColor = .secondaryGrayText
nextField.tintColor = .secondaryGrayText
done.setTitle(S.RecoverWallet.done, for: .normal)
}
private var accessoryView: UIView {
let view = UIView(color: .secondaryButton)
view.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)
let topBorder = UIView(color: .secondaryShadow)
view.addSubview(topBorder)
view.addSubview(previousField)
view.addSubview(nextField)
view.addSubview(done)
topBorder.constrainTopCorners(height: 1.0)
previousField.constrain([
previousField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: C.padding[2]),
previousField.topAnchor.constraint(equalTo: view.topAnchor),
previousField.bottomAnchor.constraint(equalTo: view.bottomAnchor),
previousField.widthAnchor.constraint(equalToConstant: 44.0) ])
nextField.constrain([
nextField.leadingAnchor.constraint(equalTo: previousField.trailingAnchor),
nextField.topAnchor.constraint(equalTo: view.topAnchor),
nextField.bottomAnchor.constraint(equalTo: view.bottomAnchor),
nextField.widthAnchor.constraint(equalToConstant: 44.0) ])
done.constrain([
done.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -C.padding[2]),
done.topAnchor.constraint(equalTo: view.topAnchor),
done.bottomAnchor.constraint(equalTo: view.bottomAnchor)])
return view
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension EnterPhraseCell: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
setColors(textField: textField)
if let text = textField.text, let isValid = isWordValid, (isValid(text) || text.isEmpty) {
hideFocusBar()
}
updatePlaceholder()
}
func textFieldDidBeginEditing(_ textField: UITextField) {
showFocusBar()
updatePlaceholder()
}
@objc func textChanged(textField: UITextField) {
if let text = textField.text {
if text.last == " " {
textField.text = text.replacingOccurrences(of: " ", with: "")
didEnterSpace?()
}
}
if hasDisplayedInvalidState {
setColors(textField: textField)
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard E.isDebug || E.isTestFlight else { return true }
if string.count == UIPasteboard.general.string?.count,
let didPasteWords = didPasteWords,
string == UIPasteboard.general.string?.replacingOccurrences(of: "\n", with: " ") {
let words = string.components(separatedBy: " ")
if didPasteWords(words) {
return false
}
}
return true
}
private func setColors(textField: UITextField) {
guard let isWordValid = isWordValid else { return }
guard let word = textField.text else { return }
if isWordValid(word) || word.isEmpty {
textField.textColor = Theme.primaryText
focusBar.backgroundColor = Theme.accent
} else {
textField.textColor = Theme.error
focusBar.backgroundColor = Theme.error
hasDisplayedInvalidState = true
}
}
}
|
mit
|
54ab5ad8e78f74a5c060ebdff1d183c6
| 32.919283 | 141 | 0.631148 | 5.042667 | false | false | false | false |
netguru/inbbbox-ios
|
Inbbbox/Source Files/ViewModels/BucketsViewModel.swift
|
1
|
5846
|
//
// BucketsViewModel.swift
// Inbbbox
//
// Created by Aleksander Popko on 24.02.2016.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
import PromiseKit
class BucketsViewModel: BaseCollectionViewViewModel {
weak var delegate: BaseCollectionViewViewModelDelegate?
let title = Localized("CenterButtonTabBar.Buckets", comment:"Main view, bottom bar & view title")
var buckets = [BucketType]()
var bucketsIndexedShots = [Int: [ShotType]]()
fileprivate let bucketsProvider = BucketsProvider()
fileprivate let bucketsRequester = BucketsRequester()
fileprivate let shotsProvider = ShotsProvider()
fileprivate var userMode: UserMode
var itemsCount: Int {
return buckets.count
}
init() {
userMode = UserStorage.isUserSignedIn ? .loggedUser : .demoUser
}
func downloadInitialItems() {
firstly {
bucketsProvider.provideMyBuckets()
}.then {
buckets -> Void in
var bucketsShouldBeReloaded = true
if let buckets = buckets {
if buckets == self.buckets && buckets.count != 0 {
bucketsShouldBeReloaded = false
}
self.buckets = buckets
self.downloadShots(buckets)
}
if bucketsShouldBeReloaded {
self.delegate?.viewModelDidLoadInitialItems()
}
}.catch {
error in
self.delegate?.viewModelDidFailToLoadInitialItems(error)
}
}
func downloadItemsForNextPage() {
guard UserStorage.isUserSignedIn else {
return
}
firstly {
bucketsProvider.nextPage()
}.then {
buckets -> Void in
if let buckets = buckets, buckets.count > 0 {
let indexes = buckets.enumerated().map {
index, _ in
return index + self.buckets.count
}
self.buckets.append(contentsOf: buckets)
let indexPaths = indexes.map {
IndexPath(row: ($0), section: 0)
}
self.delegate?.viewModel(self, didLoadItemsAtIndexPaths: indexPaths)
}
}.catch { error in
self.notifyDelegateAboutFailure(error)
}
}
func downloadItem(at index: Int) { /* empty */ }
func downloadShots(_ buckets: [BucketType]) {
for bucket in buckets {
firstly {
shotsProvider.provideShotsForBucket(bucket)
}.then {
shots -> Void in
var bucketShotsShouldBeReloaded = true
var indexOfBucket: Int?
for (index, item) in self.buckets.enumerated() {
if item.identifier == bucket.identifier {
indexOfBucket = index
break
}
}
guard let index = indexOfBucket else {
return
}
if let oldShots = self.bucketsIndexedShots[index], let newShots = shots {
bucketShotsShouldBeReloaded = oldShots != newShots
}
if let shots = shots {
self.bucketsIndexedShots[index] = shots
} else {
self.bucketsIndexedShots[index] = [ShotType]()
}
if bucketShotsShouldBeReloaded {
let indexPath = IndexPath(row: index, section: 0)
self.delegate?.viewModel(self, didLoadShotsForItemAtIndexPath: indexPath)
}
}.catch { error in
self.notifyDelegateAboutFailure(error)
}
}
}
func createBucket(_ name: String, description: NSAttributedString? = nil) -> Promise<Void> {
return Promise<Void> {
fulfill, reject in
firstly {
bucketsRequester.postBucket(name, description: description)
}.then {
bucket in
self.buckets.append(bucket)
}.then(execute: fulfill).catch(execute: reject)
}
}
func bucketCollectionViewCellViewData(_ indexPath: IndexPath) -> BucketCollectionViewCellViewData {
return BucketCollectionViewCellViewData(bucket: buckets[indexPath.row],
shots: bucketsIndexedShots[indexPath.row])
}
func clearViewModelIfNeeded() {
let currentUserMode = UserStorage.isUserSignedIn ? UserMode.loggedUser : .demoUser
if userMode != currentUserMode {
buckets = []
userMode = currentUserMode
delegate?.viewModelDidLoadInitialItems()
}
}
}
extension BucketsViewModel {
struct BucketCollectionViewCellViewData {
let name: String
let numberOfShots: String
let shotsImagesURLs: [URL]?
init(bucket: BucketType, shots: [ShotType]?) {
self.name = bucket.name
self.numberOfShots = String.localizedStringWithFormat(Localized("%d shots",
comment: "How many shots in collection?"), bucket.shotsCount)
if let shots = shots, shots.count > 0 {
let allShotsImagesURLs = shots.map {
$0.shotImage.teaserURL
}
if allShotsImagesURLs.count >= 4 {
self.shotsImagesURLs = Array(allShotsImagesURLs.prefix(4))
} else {
let repeatedValues = Array(repeating: allShotsImagesURLs, count: 4).flatMap{$0}
self.shotsImagesURLs = Array(repeatedValues.prefix(4))
}
} else {
self.shotsImagesURLs = nil
}
}
}
}
|
gpl-3.0
|
6f443f05f53b6b521cbfb68158bd727e
| 32.786127 | 103 | 0.551411 | 5.30881 | false | false | false | false |
i-miss-you/Nuke
|
Pod/Classes/Core/ImageRequest.swift
|
1
|
805
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Alexander Grebenyuk (github.com/kean).
import UIKit
public struct ImageRequest {
public var URL: NSURL
/** Image target size in pixels.
*/
public var targetSize: CGSize = ImageMaximumSize
public var contentMode: ImageContentMode = .AspectFill
public var shouldDecompressImage = true
/** Filters to be applied to image. Use ImageProcessorComposition to compose multiple filters.
*/
public var processor: ImageProcessing?
public var userInfo: Any?
public init(URL: NSURL, targetSize: CGSize, contentMode: ImageContentMode) {
self.URL = URL
self.targetSize = targetSize
self.contentMode = contentMode
}
public init(URL: NSURL) {
self.URL = URL
}
}
|
mit
|
b561083bb2e501583faaa21dc80293d7
| 25.833333 | 98 | 0.665839 | 4.763314 | false | false | false | false |
jedisct1/swift-sodium
|
Sodium/SecretStream.swift
|
2
|
5802
|
import Foundation
import Clibsodium
public struct SecretStream {
public let xchacha20poly1305 = XChaCha20Poly1305()
}
extension SecretStream {
public struct XChaCha20Poly1305 {
public static let ABytes = Int(crypto_secretstream_xchacha20poly1305_abytes())
public static let HeaderBytes = Int(crypto_secretstream_xchacha20poly1305_headerbytes())
public static let KeyBytes = Int(crypto_secretstream_xchacha20poly1305_keybytes())
public typealias Header = Bytes
}
}
extension SecretStream.XChaCha20Poly1305 {
public enum Tag: UInt8 {
case MESSAGE = 0x00
case PUSH = 0x01
case REKEY = 0x02
case FINAL = 0x03
}
}
extension SecretStream.XChaCha20Poly1305 {
public class PushStream {
private var state: crypto_secretstream_xchacha20poly1305_state
private var _header: Header
init?(secretKey: Key) {
guard secretKey.count == KeyBytes else { return nil }
state = crypto_secretstream_xchacha20poly1305_state()
_header = Bytes(count: HeaderBytes)
guard .SUCCESS == crypto_secretstream_xchacha20poly1305_init_push(
&state,
&_header,
secretKey
).exitCode else { return nil }
}
}
}
extension SecretStream.XChaCha20Poly1305 {
public class PullStream {
private var state: crypto_secretstream_xchacha20poly1305_state
init?(secretKey: Key, header: Header) {
guard header.count == HeaderBytes, secretKey.count == KeyBytes else {
return nil
}
state = crypto_secretstream_xchacha20poly1305_state()
guard .SUCCESS == crypto_secretstream_xchacha20poly1305_init_pull(
&state,
header,
secretKey
).exitCode else { return nil }
}
}
}
extension SecretStream.XChaCha20Poly1305 {
/**
Creates a new stream using the secret key `secretKey`
- Parameter secretKey: The secret key.
- Returns: A `PushStreamObject`. The stream header can be obtained by
calling the `header()` method of that returned object.
*/
public func initPush(secretKey: Key) -> PushStream? {
return PushStream(secretKey: secretKey)
}
/**
Starts reading a stream, whose header is `header`.
- Parameter secretKey: The secret key.
- Parameter header: The header.
- Returns: The stream to decrypt messages from.
*/
public func initPull(secretKey: Key, header: Header) -> PullStream? {
return PullStream(secretKey: secretKey, header: header)
}
}
extension SecretStream.XChaCha20Poly1305.PushStream {
public typealias Header = SecretStream.XChaCha20Poly1305.Header
/**
The header of the stream, required to decrypt it.
- Returns: The stream header.
*/
public func header() -> Header {
return _header
}
}
extension SecretStream.XChaCha20Poly1305.PushStream {
public typealias Tag = SecretStream.XChaCha20Poly1305.Tag
typealias XChaCha20Poly1305 = SecretStream.XChaCha20Poly1305
/**
Encrypts and authenticate a new message. Optionally also authenticate `ad`.
- Parameter message: The message to encrypt.
- Parameter tag: The tag to attach to the message. By default `.MESSAGE`.
You may want to use `.FINAL` for the last message of the stream instead.
- Parameter ad: Optional additional data to authenticate.
- Returns: The ciphertext.
*/
public func push(message: Bytes, tag: Tag = .MESSAGE, ad: Bytes? = nil) -> Bytes? {
let _ad = ad ?? Bytes(count: 0)
var cipherText = Bytes(count: message.count + XChaCha20Poly1305.ABytes)
guard .SUCCESS == crypto_secretstream_xchacha20poly1305_push(
&state,
&cipherText,
nil,
message, UInt64(message.count),
_ad, UInt64(_ad.count),
tag.rawValue
).exitCode else { return nil }
return cipherText
}
/**
Performs an explicit key rotation.
*/
public func rekey() {
crypto_secretstream_xchacha20poly1305_rekey(&state)
}
}
extension SecretStream.XChaCha20Poly1305.PullStream {
public typealias Tag = SecretStream.XChaCha20Poly1305.Tag
typealias XChaCha20Poly1305 = SecretStream.XChaCha20Poly1305
/**
Decrypts a new message off the stream.
- Parameter cipherText: The encrypted message.
- Parameter ad: Optional additional data to authenticate.
- Returns: The decrypted message, as well as the tag attached to it.
*/
public func pull(cipherText: Bytes, ad: Bytes? = nil) -> (Bytes, Tag)? {
guard cipherText.count >= XChaCha20Poly1305.ABytes else { return nil }
var message = Bytes(count: cipherText.count - XChaCha20Poly1305.ABytes)
let _ad = ad ?? Bytes(count: 0)
var _tag: UInt8 = 0
let result = crypto_secretstream_xchacha20poly1305_pull(
&state,
&message,
nil,
&_tag,
cipherText, UInt64(cipherText.count),
_ad, UInt64(_ad.count)
).exitCode
guard result == .SUCCESS, let tag = Tag(rawValue: _tag) else {
return nil
}
return (message, tag)
}
/**
Performs an explicit key rotation.
*/
public func rekey() {
crypto_secretstream_xchacha20poly1305_rekey(&state)
}
}
extension SecretStream.XChaCha20Poly1305: SecretKeyGenerator {
public var KeyBytes: Int { return SecretStream.XChaCha20Poly1305.KeyBytes }
public typealias Key = Bytes
public static var keygen: (UnsafeMutablePointer<UInt8>) -> Void = crypto_secretstream_xchacha20poly1305_keygen
}
|
isc
|
c45c9c0481d710c8cef41719fd6d9907
| 29.21875 | 114 | 0.642709 | 4.213508 | false | false | false | false |
HabitRPG/habitrpg-ios
|
HabitRPG/UI/User/ClassSelectionViewController.swift
|
1
|
9171
|
//
// ClassSelectionViewController.swift
// Habitica
//
// Created by Phillip Thelen on 26.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import ReactiveSwift
import PinLayout
class ClassSelectionViewController: UIViewController {
@IBOutlet weak var bottomView: UIView!
@IBOutlet weak var titleView: UILabel!
@IBOutlet weak var selectionButton: UIButton!
@IBOutlet weak var descriptionView: UITextView!
@IBOutlet weak var warriorOptionView: ClassSelectionOptionView!
@IBOutlet weak var mageOptionView: ClassSelectionOptionView!
@IBOutlet weak var healerOptionView: ClassSelectionOptionView!
@IBOutlet weak var rogueOptionView: ClassSelectionOptionView!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
private let userRepository = UserRepository()
private let disposable = ScopedDisposable(CompositeDisposable())
private var selectedClass: HabiticaClass?
private var isSelecting = false
private var showBottomView = false
private var selectedView: UIView?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = L10n.Titles.selectClass
configure(view: warriorOptionView, class: .warrior)
configure(view: mageOptionView, class: .mage)
configure(view: healerOptionView, class: .healer)
configure(view: rogueOptionView, class: .rogue)
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.isTranslucent = true
navigationController?.view.backgroundColor = .clear
navigationController?.navigationBar.backgroundColor = .clear
disposable.inner.add(userRepository.getUser()
.take(first: 1)
.filter({ user in !user.canChooseClassForFree })
.flatMap(.latest) { _ in
return self.userRepository.selectClass()
}.start())
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.view.alpha = 0
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
showView()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
layout()
}
private func showView() {
UIView.animate(withDuration: 0.4, animations: {[weak self] in
self?.navigationController?.view.alpha = 1
}, completion: {[weak self] (_) in
self?.set(class: .warrior)
UIView.animate(withDuration: 0.6) {[weak self] in
self?.bottomView.pin.top(58%)
}
UIView.animate(withDuration: 0.2, delay: 0.5, options: [], animations: {[weak self] in
self?.titleView.alpha = 1
self?.descriptionView.alpha = 1
self?.selectionButton.alpha = 1
}, completion: nil)
})
}
private func layout() {
let itemWidth = (view.bounds.size.width - 50) / 2
let itemHeight = ((view.bounds.size.height * 0.575) - (view.pin.safeArea.top + 50)) / 2
if let selectedView = self.selectedView {
selectedView.pin.vCenter().hCenter()
loadingIndicator.pin.below(of: selectedView).marginTop(12).hCenter()
} else {
healerOptionView.pin.left(25).top(view.pin.safeArea.top+10).width(itemWidth).height(itemHeight)
mageOptionView.pin.right(of: healerOptionView).top(view.pin.safeArea.top+10).width(itemWidth).height(itemHeight)
rogueOptionView.pin.below(of: healerOptionView).marginTop(6).left(25).width(itemWidth).height(itemHeight)
warriorOptionView.pin.below(of: mageOptionView).marginTop(6).right(of: rogueOptionView).width(itemWidth).height(itemHeight)
}
if showBottomView {
bottomView.pin.left().right().height(42.5%).top(57.5%)
} else {
bottomView.pin.left().right().height(42.5%).top(100%)
}
titleView.pin.top(20).left(16).right(16).height(28)
selectionButton.pin.bottom(28).left(16).right(16).height(43)
descriptionView.pin.above(of: selectionButton).marginBottom(12).below(of: titleView).left(16).right(16)
}
private func configure(view: ClassSelectionOptionView, class habiticaClass: HabiticaClass) {
view.configure(habiticaClass: habiticaClass) {
self.set(class: habiticaClass)
}
disposable.inner.add(userRepository.getUserStyleWithOutfitFor(class: habiticaClass).on(value: { userStyle in
view.userStyle = userStyle
}).start())
}
private func set(class habiticaClass: HabiticaClass) {
self.selectedClass = habiticaClass
switch habiticaClass {
case .warrior:
configure(className: L10n.Classes.warrior, description: L10n.Classes.warriorDescription, textColor: .white, backgroundColor: UIColor.red50, buttonColor: UIColor(white: 0.1, alpha: 0.2))
case .mage:
configure(className: L10n.Classes.mage, description: L10n.Classes.mageDescription, textColor: .white, backgroundColor: UIColor.blue50, buttonColor: UIColor(white: 0.1, alpha: 0.2))
case .healer:
configure(className: L10n.Classes.healer, description: L10n.Classes.healerDescription, textColor: UIColor.gray50, backgroundColor: UIColor.yellow100, buttonColor: UIColor.yellow10)
case .rogue:
configure(className: L10n.Classes.rogue, description: L10n.Classes.rogueDescription, textColor: .white, backgroundColor: UIColor.purple300, buttonColor: UIColor.purple100)
}
warriorOptionView.isSelected = habiticaClass == .warrior
mageOptionView.isSelected = habiticaClass == .mage
healerOptionView.isSelected = habiticaClass == .healer
rogueOptionView.isSelected = habiticaClass == .rogue
}
private func configure(className: String, description: String, textColor: UIColor, backgroundColor: UIColor, buttonColor: UIColor) {
UIView.animate(withDuration: 0.3) {[weak self] in
self?.titleView.text = L10n.Classes.classHeader(className)
self?.titleView.textColor = textColor
self?.descriptionView.text = description
self?.descriptionView.textColor = textColor
self?.bottomView.backgroundColor = backgroundColor
self?.selectionButton.backgroundColor = buttonColor
self?.selectionButton.setTitle(L10n.Classes.becomeAClass(className), for: .normal)
}
}
@IBAction func selectClass(_ sender: Any) {
if isSelecting {
return
}
isSelecting = true
if let selectedClass = self.selectedClass {
switch selectedClass {
case .warrior:
selectedView = warriorOptionView
case .mage:
selectedView = mageOptionView
case .healer:
selectedView = healerOptionView
case .rogue:
selectedView = rogueOptionView
}
showLoadingSelection()
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {[weak self] in
self?.userRepository.selectClass(selectedClass)
.on(failed: {[weak self] _ in
self?.isSelecting = false
})
.observeCompleted {
self?.dismiss(animated: true, completion: nil)
}
}
}
}
private func showLoadingSelection() {
loadingIndicator.startAnimating()
if let selectedView = selectedView {
showBottomView = false
UIView.animate(withDuration: 0.3) {[weak self] in
self?.navigationController?.navigationBar.alpha = 0
self?.hideView(self?.warriorOptionView)
self?.hideView(self?.mageOptionView)
self?.hideView(self?.healerOptionView)
self?.hideView(self?.rogueOptionView)
}
UIView.animate(withDuration: 0.6, animations: {[weak self] in
selectedView.pin.vCenter().hCenter()
self?.bottomView.pin.top(100%)
}, completion: {[weak self] (_) in
self?.loadingIndicator.pin.below(of: selectedView).marginTop(12).hCenter()
UIView.animate(withDuration: 0.3, animations: {[weak self] in
self?.loadingIndicator.alpha = 1
})
})
}
}
private func hideView(_ view: UIView?) {
if selectedView != view {
view?.alpha = 0
}
}
@IBAction func cancelButtonTapped(_ sender: Any) {
if !isSelecting {
self.userRepository.disableClassSystem().observeCompleted {}
}
dismiss(animated: true, completion: nil)
}
}
|
gpl-3.0
|
761ee1112449b936ec63b8228041da04
| 41.06422 | 197 | 0.628899 | 4.776042 | false | true | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformUIKit/Components/RadioCell/RadioAccountSelectionTableViewCell/RadioAccountCellPresenter.swift
|
1
|
1635
|
import PlatformKit
import RxCocoa
import RxDataSources
import RxSwift
public final class RadioAccountCellPresenter: IdentifiableType {
// MARK: - Public Properties
/// Streams the image content
public let imageContent: Driver<ImageViewContent>
// MARK: - RxDataSources
public let identity: AnyHashable
// MARK: - Internal
/// The `viewModel` for the `WalletView`
let viewModel: Driver<WalletViewViewModel>
// MARK: - Init
public init(
interactor: RadioAccountCellInteractor,
accessibilityPrefix: String = ""
) {
let model = WalletViewViewModel(
account: interactor.account,
descriptor: .init(
accessibilityPrefix: accessibilityPrefix
)
)
viewModel = .just(model)
identity = model.identifier
imageContent = interactor
.isSelected
.map { $0 ? "checkbox-selected" : "checkbox-empty" }
.asDriver(onErrorJustReturn: nil)
.compactMap { name -> ImageViewContent? in
guard let name = name else {
return nil
}
return ImageViewContent(
imageResource: .local(name: name, bundle: .platformUIKit),
accessibility: .id("\(accessibilityPrefix)\(name)"),
renderingMode: .normal
)
}
}
}
extension RadioAccountCellPresenter: Equatable {
public static func == (lhs: RadioAccountCellPresenter, rhs: RadioAccountCellPresenter) -> Bool {
lhs.identity == rhs.identity
}
}
|
lgpl-3.0
|
1a49d74b63428212b495b7496bcc62a9
| 27.189655 | 100 | 0.592049 | 5.413907 | false | false | false | false |
yarshure/Surf
|
Surf-Mac/ViewController.swift
|
1
|
5995
|
//
// ViewController.swift
// Surf-Mac
//
// Created by yarshure on 15/12/22.
// Copyright © 2015年 yarshure. All rights reserved.
//
import Cocoa
import NetworkExtension
import AppKit
import SFSocket
import Xcon
import XRuler
//import SFSocket
func SSLog<T>(_ object: T, _ file: String = #file, _ function: String = #function, _ line: Int = #line) {
//let fn = file.split { $0 == "/" }.last
let fn = file.split { $0 == "/" }.map(String.init).last
if let f = fn {
let info = "\(f).\(function)[\(line)]:\(object)"
NSLog(info)
}
}
class MainViewController: NSViewController {
@IBOutlet weak var hostField: NSTextField!
@IBOutlet weak var portField: NSTextField!
@IBOutlet weak var method: NSTextField!
@IBOutlet weak var password: NSSecureTextField!
@IBOutlet weak var actionButton: NSButton!
@IBOutlet weak var statusView: NSImageView!
var targetManager : NEVPNManager?
//var proxy:SFProxy = SFProxy.init(name: "Proxy", type: .SS, address: "", port: "" , passwd:"", method: "", tls: false)
@IBAction func saveServer(_ sender: AnyObject) {
if let proxy = SFProxy.create(name: "server", type: .SS, address:self.hostField.stringValue, port: self.portField.stringValue, passwd: self.password.stringValue, method: self.method.stringValue, tls: false) {
_ = ProxyGroupSettings.share.addProxy(proxy)
do {
try ProxyGroupSettings.share.save()
}catch let e {
print("\(e.localizedDescription)")
}
}else {
//todo
}
}
var logUrl:NSURL = {
let url = fm.containerURL(forSecurityApplicationGroupIdentifier: groupIdentifier)!
return url.appendingPathComponent("Log") as NSURL
}()
/// A list of NEVPNManager objects for the packet tunnel configurations.
var managers = [NEVPNManager]()
override func viewDidLoad() {
super.viewDidLoad()
reloadManagers()
// Do any additional setup after loading the view.
}
@IBAction func showLog(_ sender: AnyObject) {
NSWorkspace.shared.open(logUrl as URL)
}
@IBAction func showLogUseTerminal(_ sender: AnyObject) {
if NSWorkspace.shared.openFile(logUrl.path!, withApplication:"Terminal") {
}else {
SSLog("can't open")
}
}
@IBAction func showAppDir(_ sender: AnyObject) {
//let urls = FileManager.default.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let url = Bundle.main.bundleURL
if NSWorkspace.shared.openFile(url.path, withApplication:"Terminal") {
}else {
//SSLog("can't open")
}
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func reloadManagers() {
SFVPNManager.shared.loadManager {[weak self] (m, error) in
if let _ = m {
SFVPNManager.shared.xpc()
if let ss = self {
ss.observeStatus()
ss.actionButton.isEnabled = true
}
}
}
}
func readImage(name:String) ->NSImage?{
guard let p = Bundle.main.path(forResource:name, ofType: "png")else {
return nil
}
return NSImage(contentsOfFile: p)
}
func refreshProfile(){
}
func showStatus(_ status:NEVPNStatus){
switch status{
case .disconnected:
statusView.image = NSImage.init(named:"GrayDot")
SSLog("Disconnected")
case .invalid:
statusView.image = NSImage.init(named: "RedDot")
SSLog("Invalid")
case .connected:
statusView.image = NSImage.init(named:"GreenDot")
SSLog("Connected")
case .connecting:
statusView.image = NSImage.init(named:"GreenDot")
SSLog("Connecting")
case .disconnecting:
statusView.image = NSImage.init(named:"RedDot")
SSLog("Disconnecting")
case .reasserting:
statusView.image = NSImage.init(named:"RedDot")
SSLog("Reasserting")
@unknown default:
statusView.image = NSImage.init(named:"RedDot")
}
}
/// Register for configuration change notifications.
func observeStatus() {
if let m = SFVPNManager.shared.manager{
NotificationCenter.default.addObserver(forName: NSNotification.Name.NEVPNStatusDidChange, object: m.connection, queue: OperationQueue.main, using: { [weak self ] notification in
//self.tableView.reloadRowsAtIndexPaths([ NSIndexPath(forRow: index, inSection: 0) ], withRowAnimation: .Fade)
print(index)
if let s = self{
s.showStatus(m.connection.status)
}
print(m.connection.status)
})
}
}
/// De-register for configuration change notifications.
func stopObservingStatus() {
if let m = SFVPNManager.shared.manager {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NEVPNStatusDidChange, object: m.connection)
}
}
@IBAction func connectVPN(_ sender: AnyObject){
do {
_ = try SFVPNManager.shared.startStopToggled("")
}catch _ {
}
}
@IBAction func addVPN(_ sender: AnyObject) {
_ = SFVPNManager.shared.loadManager { [weak self](manager, error) in
if let strong = self, let manager = manager {
strong.test(manager)
}
}
}
func test(_ mangaer:NETunnelProviderManager){
}
}
|
bsd-3-clause
|
35dd71ab8d2f2675efe0ccf411d74dcf
| 30.208333 | 216 | 0.567757 | 4.652174 | false | false | false | false |
zs40x/PairProgrammingTimer
|
PairProgrammingTimerTests/Session/ProgrammingSessionTests_Delegate.swift
|
1
|
1874
|
//
// ProgrammingSessionTests_Delegate.swift
// PairProgrammingTimer
//
// Created by Stefan Mehnert on 31/01/2017.
// Copyright © 2017 Stefan Mehnert. All rights reserved.
//
import XCTest
@testable import PairProgrammingTimer
class ProgrammingSessionDelegateTests: ProgrammingSessionTests {
func testDelegateCalledWhenDeveloperWasChanged() {
_ = testInstance?.changeDevelopers()
XCTAssertEqual(true, fakeSessionDelegate?.developerChangedWasCalled)
}
func testDelegateCalledWhenSessionStarted() {
_ = testInstance?.toggleState()
XCTAssertEqual(true, fakeSessionDelegate?.sessionStartedWasCalled)
}
func testDelegateCalledWhenSessionStartWithEndDateTime() {
_ = testInstance?.toggleState()
XCTAssertNotNil(fakeSessionDelegate?.sessionStartedWasCalledWithEndDateTime)
XCTAssertEqual(fakeSessionDelegate?.sessionStartedWasCalledWithEndDateTime, startedOnDate.addingTimeInterval(sessionDuration.TotalMinutes * 60))
}
func testDelegateCalledWhenSessionStartedWithDeveloper() {
_ = testInstance?.toggleState().changeDevelopers()
XCTAssertNotNil(fakeSessionDelegate?.sessionStartedForDeveloper)
XCTAssertEqual(Developer.right, fakeSessionDelegate?.sessionStartedForDeveloper)
}
func testDelegateCalledWhenSessionEnded() {
_ = testInstance?.toggleState().toggleState()
XCTAssertEqual(true, fakeSessionDelegate?.sessionEndedWasCalled)
}
func testDelegateCalledWhenTimerExpired() {
// simulate that the timer expired after the countdown interval
_ = testInstance?.toggleState()
fakeTimer?.expire()
XCTAssertEqual(true, fakeSessionDelegate?.countdownExpiredWasCalled)
}
}
|
mit
|
f596fde15efe7e402a831e81f689bca0
| 31.293103 | 152 | 0.703684 | 5.727829 | false | true | false | false |
lorentey/swift
|
stdlib/public/Darwin/Accelerate/vImage_CGImageFormat.swift
|
8
|
3124
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// vImage_CGImageFormat
//
//===----------------------------------------------------------------------===//
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension vImage_CGImageFormat {
/// Initializes an image format from a Core Graphics image.
///
/// - Parameter cgImage: The image from which to derive the image format.
///
/// - Returns: An initialized `vImage_CGImageFormat`.
public init?(cgImage: CGImage) {
guard
let colorSpace = cgImage.colorSpace else {
return nil
}
self = vImage_CGImageFormat(
bitsPerComponent: UInt32(cgImage.bitsPerComponent),
bitsPerPixel: UInt32(cgImage.bitsPerPixel),
colorSpace: Unmanaged.passRetained(colorSpace),
bitmapInfo: cgImage.bitmapInfo,
version: 0,
decode: nil,
renderingIntent: cgImage.renderingIntent)
}
/// Initializes an image format.
///
/// - Parameter bitsPerComponent: The number of bits needed to represent one
/// channel of data in one pixel.
/// - Parameter bitsPerPixel: The number of bits needed to represent one pixel.
/// - Parameter colorSpace: The color space for the format.
/// - Parameter bitmapInfo: The component information describing the color channels.
/// - Parameter renderingIntent: A rendering intent constant that specifies how
/// Core Graphics should handle colors that are not located within the gamut of the
/// destination color space of a graphics context.
///
/// - Returns: An initialized `vImage_CGImageFormat`.
public init?(bitsPerComponent: Int,
bitsPerPixel: Int,
colorSpace: CGColorSpace,
bitmapInfo: CGBitmapInfo,
renderingIntent: CGColorRenderingIntent = .defaultIntent) {
if bitsPerComponent < 1 || bitsPerPixel < 0 {
return nil
}
self = vImage_CGImageFormat(
bitsPerComponent: UInt32(bitsPerComponent),
bitsPerPixel: UInt32(bitsPerPixel),
colorSpace: Unmanaged.passRetained(colorSpace),
bitmapInfo: bitmapInfo,
version: 0,
decode: nil,
renderingIntent: renderingIntent)
}
/// The number of color channels.
public var componentCount: Int {
var mutableSelf = self
return Int(vImageCGImageFormat_GetComponentCount(&mutableSelf))
}
}
|
apache-2.0
|
b4c074739f55d4c2431999c365925474
| 37.567901 | 88 | 0.570423 | 5.628829 | false | false | false | false |
fs/ios-base-swift
|
Swift-Base/Tools/ViewControllers/LoggedTabBarController.swift
|
1
|
1742
|
//
// LoggedTabBarController.swift
// Tools
//
// Created by Almaz Ibragimov on 01.01.2018.
// Copyright © 2018 Flatstack. All rights reserved.
//
import UIKit
public class LoggedTabBarController: UITabBarController {
// MARK: - Instance Properties
public fileprivate(set) final var isViewAppeared = false
// MARK: - Initializers
deinit {
Log.i("deinit", sender: self)
}
// MARK: - Instance Methods
public override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
Log.i("didReceiveMemoryWarning()", sender: self)
}
public override func viewDidLoad() {
super.viewDidLoad()
Log.i("viewDidLoad()", sender: self)
self.isViewAppeared = false
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Log.i("viewWillAppear()", sender: self)
self.isViewAppeared = false
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Log.i("viewDidAppear()", sender: self)
self.isViewAppeared = true
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
Log.i("viewWillDisappear()", sender: self)
}
public override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
Log.i("viewDidDisappear()", sender: self)
self.isViewAppeared = false
}
// MARK: -
public override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
Log.i("prepare(for: \(String(describing: segue.identifier)))", sender: self)
}
}
|
mit
|
5bf5459747326b9b1195f07bc46a227b
| 21.907895 | 84 | 0.643883 | 4.743869 | false | false | false | false |
muyang00/YEDouYuTV
|
YEDouYuZB/YEDouYuZB/Home/Views/AmuseHeadView.swift
|
1
|
2680
|
//
// AmuseHeadView.swift
// YEDouYuZB
//
// Created by yongen on 17/4/1.
// Copyright © 2017年 yongen. All rights reserved.
//
import UIKit
let kAmuseViewID = "kAmuseViewID"
class AmuseHeadView: UIView {
var groups : [AnchorGroup]? {
didSet{
collectionView.reloadData()
}
}
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
override func awakeFromNib() {
super.awakeFromNib()
autoresizingMask = UIViewAutoresizing()
collectionView.register(UINib(nibName: "CollectionAmuseHeadCell", bundle: nil), forCellWithReuseIdentifier: kAmuseViewID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
}
}
extension AmuseHeadView {
class func amuseHeadView () -> AmuseHeadView{
return Bundle.main.loadNibNamed("AmuseHeadView", owner: nil, options: nil)?.first as! AmuseHeadView
}
}
extension AmuseHeadView : UICollectionViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetX = scrollView.contentOffset.x
let pageNum = offsetX / scrollView.bounds.width
pageControl.currentPage = Int(pageNum)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("AmuseHeadView -----AmuseHeadView")
}
}
extension AmuseHeadView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if groups?.count == nil { return 0 }
let pageNum = (groups!.count - 1) / 8 + 1
pageControl.numberOfPages = pageNum
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kAmuseViewID, for: indexPath) as! CollectionAmuseHeadCell
setupCellDataWithCell(cell: cell, indexPath: indexPath)
return cell
}
private func setupCellDataWithCell(cell : CollectionAmuseHeadCell, indexPath : IndexPath){
// 0页 : 0 ~ 7
// 1页 : 8 ~ 15
// 2页 : 16 ~ 23
let startIndex = indexPath.item * 8
var endIndex = (indexPath.item + 1) * 8 - 1
if endIndex > groups!.count - 1 {
endIndex = groups!.count - 1
}
cell.groups = Array(groups![startIndex...endIndex])
}
}
|
apache-2.0
|
dc3ffa0679abdc6546f8e5c4c22a502c
| 30.797619 | 132 | 0.662673 | 5.011257 | false | false | false | false |
IAskWind/IAWExtensionTool
|
IAWExtensionTool/IAWExtensionTool/Classes/Tool/IAW_AppTool.swift
|
1
|
1199
|
//
// IAWAppTool.swift
// IAWExtensionTool
//
// Created by winston on 16/11/16.
// Copyright © 2016年 winston. All rights reserved.
//
import Foundation
open class IAW_AppTool{
/**
*注意:用在AppDelegate的rootVC //并且返回的UIWindow要赋值给AppDelegate声明的
*
*/
open class func rootVC(vc:UIViewController) -> UIWindow {
let window = UIWindow(frame: UIScreen.main.bounds)
window.makeKeyAndVisible()
window.rootViewController = vc
return window
}
open class func rootVC(mWindow:UIWindow,vc:UIViewController){
mWindow.makeKeyAndVisible()
mWindow.rootViewController = vc
}
open class func getVersionName() -> String{
let infoDictionary = Bundle.main.infoDictionary
let versionName = infoDictionary?["CFBundleShortVersionString"]as? String ?? ""//主程序版本号 versionName
return versionName
}
open class func getVersionCode() -> Int{
let infoDictionary = Bundle.main.infoDictionary
let versionCode = infoDictionary?["CFBundleVersion"]as? Int ?? 0//主程序版本号 versionCode
return versionCode
}
}
|
mit
|
78ed097f2a9b8c082e1d0838b5951a9c
| 28.128205 | 108 | 0.663732 | 4.655738 | false | false | false | false |
mannd/QTc
|
CommonTests/QTc_iOSTests.swift
|
1
|
65210
|
//
// QTc_iOSTests.swift
// QTc_iOSTests
//
// Created by David Mann on 9/2/17.
// Copyright © 2017, 2018 EP Studios. All rights reserved.
//
import XCTest
@testable import QTc
class QTc_iOSTests: XCTestCase {
// Add formulas to these arrays as they are created
let qtcFormulas: [Formula] = [.qtcBzt, .qtcArr, .qtcDmt,
.qtcFrd, .qtcFrm, .qtcHdg,
.qtcKwt, .qtcMyd, .qtcYos,
.qtcRtha, .qtcRthb, .qtcArr,
.qtcKwt, .qtcDmt,
.qtcAdm, .qtcGot, .qtcRbk]
let qtpFormulas: [Formula] = [.qtpArr, .qtpBzt, .qtpFrd, .qtpBdl,
.qtpAsh, .qtpHdg, .qtpMyd, .qtpKrj,
.qtpSch, .qtpAdm, .qtpSmn, .qtpKwt,
.qtpScl,.qtpMrr, .qtpHgg, .qtpGot,
.qtpKlg, .qtpShp, .qtpWhl, .qtpSrm,
.qtpLcc, .qtpRbk]
// Accuracy for all non-integral measurements
let delta = 0.0000001
let roughDelta = 0.1
let veryRoughDelta = 0.5 // accurate to nearest half integer
let veryVeryRoughDelta = 1.0 // accurate to 1 integer
// source: https://link.springer.com/content/pdf/bfm%3A978-3-642-58810-5%2F1.pdf
// Note this table is not accurate within 0.5 bpm when converting back from interval to rate
let rateIntervalTable: [(rate: Double, interval: Double)] = [(20, 3000), (25, 2400),
(30, 2000), (35, 1714), (40, 1500),
(45, 1333), (50, 1200), (55, 1091),
(60, 1000), (65, 923), (70, 857), (75, 800),
(80, 750), (85, 706), (90, 667), (95, 632),
(100, 600), (105, 571), (110, 545), (115, 522),
(120, 500), (125, 480), (130, 462), (135, 444),
(140, 429), (145, 414), (150, 400), (155, 387),
(160, 375), (165, 364), (170, 353), (175, 343),
(180, 333), (185, 324), (190, 316), (195, 308),
(200, 300), (205, 293), (210, 286), (215, 279),
(220, 273), (225, 267), (230, 261), (235, 255),
(240, 250), (245, 245), (250, 240), (255, 235),
(260, 231), (265, 226), (270, 222), (275, 218),
(280, 214), (285, 211), (290, 207), (295, 203),
(300, 200), (305, 197), (310, 194), (315, 190),
(320, 188), (325, 185), (330, 182), (335, 179),
(340, 176), (345, 174), (350, 171), (355, 169),
(360, 167), (365, 164), (370, 162), (375, 160),
(380, 158), (385, 156), (390, 154), (395, 152),
(400, 150)]
// uses online QTc calculator: http://www.medcalc.com/qtc.html, random values
let qtcBztTable: [(qt: Double, interval: Double, qtc: Double)] = [(318, 1345, 274), (451, 878, 481), (333, 451, 496)]
// TODO: Add other hand calculated tables for each formula
// table of calculated QTc from
let qtcMultipleTable: [(rate: Double, rrInSec: Double, rrInMsec: Double, qtInMsec: Double,
qtcBzt: Double, qtcFrd: Double, qtcFrm: Double, qtcHDG: Double)] =
[(88, 0.682, 681.8, 278, 336.7, 315.9, 327.0, 327.0), (112, 0.536, 535.7, 334, 456.3, 411.2, 405.5, 425.0),
(47, 1.2766, 1276.6, 402, 355.8, 370.6, 359.4, 379.3), (132, 0.4545, 454.5, 219, 324.8, 284.8, 303, 345)]
// TODO: Add new formulae here
let qtcRandomTable: [(qtInSec: Double, rrInSec: Double, qtcMyd: Double, qtcRtha: Double,
qtcArr: Double, qtcKwt: Double, qtcDmt: Double)] = [(0.217, 1.228, 0.191683142324075,
0.20357003257329, 0.188180853891965, 0.206138989195107, 0.199352096980993),
(0.617, 1.873, 0.422349852160997, 0.521139348638548,
0.540226253226725,0.527412865616186 , 0.476131661614717),
(0.441, 0.024, 4.19557027148694, 6.419, 0.744999998985912,
1.12043270968093, 2.05783877711859),
(0.626, 1.938, 0.419771215123981, 0.525004471964224,
0.545939267391605, 0.530561692609049, 0.47631825370458),
(0.594, 1.693, 0.432192914133319, 0.512952155936208,
0.527461134835087, 0.520741518839723, 0.477915505801712),
(0.522, 0.670, 0.664846401046771, 0.607701492537313,
0.585658505426308, 0.576968100296572, 0.615887811579245),
(0.162, 0.238, 0.385533865286431, 0.334890756302521,
0.400524764066341, 0.231937395103792, 0.29308171977912),
(0.449, 0.738, 0.539436462235939, 0.50213369467028,
0.496257865770434, 0.484431360905827, 0.509024942553452),
(0.364, 0.720, 0.443887132523326, 0.411185185185185,
0.415398777435965, 0.395155707875796, 0.416891521344714),
(0.279, 0.013, 3.84399149834848, 7.33984615384616,
0.583, 0.826263113547243, 1.67704840828666),
(0.184, 0.384, 0.328005981451736, 0.282388888888889,
0.347039639944786, 0.233741064151123, 0.27320524164178)]
// QTp random test intervals
let qtIntervals =
[0.587, 0.628, 0.774, 0.44, 0.61, 0.564, 0.322, 0.652, 0.611, 0.771, 0.522, 0.282, 0.255, 0.542, 0.4, 0.706, 0.301, 0.389, 0.486, 0.499]
let rrIntervals =
[1.04, 1.741, 0.803, 0.744, 0.462, 1.741, 0.814, 1.492, 1.217, 1.316, 1.072, 1.729, 1.631, 0.876, 0.738, 1.325, 1.066, 0.57, 0.603, 0.821]
let qtpBztMaleResults =
[0.377327444005866, 0.488203748449354, 0.331557988894854, 0.319145108062148, 0.251491152925903, 0.488203748449354, 0.333821209631743, 0.451945571944233, 0.40817557496744, 0.42445305983112, 0.383088501524126, 0.486518344977864, 0.472529258353385, 0.346301025121209, 0.317855627604735, 0.425901984029189, 0.382014921174553, 0.279343874105018, 0.287316376143094, 0.335253486186199]
let qtpBztFemaleResults = [0.407921561087423, 0.527787836161464, 0.358441069075518, 0.345021738445565, 0.271882327487463, 0.527787836161464, 0.360887794196479, 0.488589807507279, 0.441270891856692, 0.4588681727904, 0.414149731377433, 0.525965778354448, 0.510842441463119, 0.374379486617523, 0.343627705518633, 0.460434577328854, 0.41298910397249, 0.30199337741083, 0.310612298533075, 0.362436201282377]
let qtpFrdResults =
[0.386559422661292, 0.458991603861966, 0.354631247099717, 0.345723947150657, 0.294952767914911, 0.458991603861966, 0.356243229467337, 0.435974838280842, 0.407350896973457, 0.41810989654274, 0.390484152137325, 0.457934624637034, 0.449113873741475, 0.365067512187644, 0.344792072153498, 0.41906087001553, 0.389754273515837, 0.316346792990953, 0.322337565550937, 0.357261488417636]
let qtpHdgResults = [0.395038461538462, 0.435689833429064, 0.365240348692403, 0.354870967741935, 0.268727272727273, 0.435689833429064, 0.367007371007371, 0.425624664879357, 0.409722267871816, 0.416212765957447, 0.39805223880597, 0.435271255060729, 0.431622317596566, 0.37613698630137, 0.353723577235772, 0.416754716981132, 0.397500938086304, 0.311789473684211, 0.321870646766169, 0.3681071863581]
let qtcRthbMaleResults = [0.581343039402066, 0.539876501292278, 0.804174636591087, 0.480109064822965, 0.706177170185111, 0.475876501292278, 0.35037381620353, 0.59024899978608, 0.581832195881668, 0.729613630344318, 0.511915407946455, 0.195090829692423, 0.178212616137001, 0.560500006698053, 0.441146783627781, 0.663531970103914, 0.291739182875841, 0.46167084747726, 0.55205665809079, 0.526235809548196]
let qtcRthbFemaleResults = [0.580695812286438, 0.52926765756804, 0.807541128337159, 0.484551008433048, 0.716354877945081, 0.465267657568039, 0.353543571822623, 0.582928175464681, 0.57844314285625, 0.724767662325179, 0.510758174544893, 0.184635377981728, 0.169028318291773, 0.562581497625133, 0.44570009096784, 0.658556002180993, 0.29067706412139, 0.469515787318061, 0.559226003573487, 0.529280960371902]
let qtpMydResults = [0.425497173513281, 0.580832622192216, 0.363962577477372, 0.347567048264256, 0.260646739027945, 0.580832622192216, 0.366965877563262, 0.529133078075342, 0.467868764175226, 0.490500099361997, 0.433357376010936, 0.578411232930745, 0.558381132281235, 0.383602141228905, 0.345871346870654, 0.49252347281055, 0.43189074158302, 0.29590816947795, 0.30614008546182, 0.368868703669459]
// QTpKRJ is rate dependent
let qtpKrjSlowResults = [0.39764, 0.478956, 0.370148, 0.363304, 0.330592, 0.478956, 0.371424, 0.450072, 0.418172, 0.429656, 0.401352, 0.477564, 0.466196, 0.378616, 0.362608, 0.4307, 0.400656, 0.34312, 0.346948, 0.372236]
let qtpKrjFastResults = [0.49836, 0.767544, 0.407352, 0.384696, 0.276408, 0.767544, 0.411576, 0.671928, 0.566328, 0.604344, 0.510648, 0.762936, 0.725304, 0.435384, 0.382392, 0.6078, 0.508344, 0.31788, 0.330552, 0.414264]
let qtpKrjMediumResults = [0.39824, 0.507596, 0.361268, 0.352064, 0.308072, 0.507596, 0.362984, 0.468752, 0.425852, 0.441296, 0.403232, 0.505724, 0.490436, 0.372656, 0.351128, 0.4427, 0.402296, 0.32492, 0.330068, 0.364076]
let qtpSchResults = [0.3802, 0.523905, 0.331615, 0.31952, 0.26171, 0.523905, 0.33387, 0.47286, 0.416485, 0.43678, 0.38676, 0.521445, 0.501355, 0.34658, 0.31829, 0.438625, 0.38553, 0.28385, 0.290615, 0.335305]
let qtpAdmMenResults = [0.405944, 0.5136176, 0.3695408, 0.3604784, 0.3171632, 0.5136176, 0.3712304, 0.4753712, 0.4331312, 0.4483376, 0.4108592, 0.5117744, 0.4967216, 0.3807536, 0.3595568, 0.44972, 0.4099376, 0.333752, 0.3388208, 0.3723056]
let qtpAdmWomenResults = [0.409836, 0.4980919, 0.3799977, 0.3725696, 0.3370658, 0.4980919, 0.3813826, 0.4667428, 0.4321203, 0.4445844, 0.4138648, 0.4965811, 0.4842429, 0.3891884, 0.3718142, 0.4457175, 0.4131094, 0.350663, 0.3548177, 0.3822639]
let qtpAdmCombinedResults = [0.409456, 0.5120824, 0.3747592, 0.3661216, 0.3248368, 0.5120824, 0.3763696, 0.4756288, 0.4353688, 0.4498624, 0.4141408, 0.5103256, 0.4959784, 0.3854464, 0.3652432, 0.45118, 0.4132624, 0.340648, 0.3454792, 0.3773944]
let ages = [45, 43, 36, 49, 32, 57, 23, 45, 26, 31, 54, 45, 50, 49, 29, 26, 42, 47, 36, 42]
let qtpSmnResults = [0.4014, 0.49894, 0.36552, 0.36116, 0.31658, 0.50314, 0.36316, 0.46468, 0.42048, 0.43584, 0.40858, 0.49786, 0.48564, 0.37964, 0.35432, 0.4356, 0.40414, 0.3362, 0.33752, 0.36984]
let qtpKwtResults = [0.454434032947036, 0.516906753734889, 0.425982148944625, 0.417932117799132, 0.370999229501259, 0.516906753734889, 0.427433557189848, 0.497341522548198, 0.472645098358642, 0.481977190824566, 0.457890053953813, 0.516013735565187, 0.508541036683082, 0.43534999150123, 0.417086952467717, 0.482799135016553, 0.457248000417796, 0.391004024677794, 0.396544418864229, 0.428349538226906]
let qtpScl20to40Results = [0.3738622153476, 0.443915237311756, 0.342982775479653, 0.334368051076366, 0.285264538311867, 0.443915237311756, 0.34454180952133, 0.421654496877457, 0.393970758021775, 0.404376359794986, 0.377658030351792, 0.442892976382533, 0.434361958180625, 0.353076243539145, 0.33346678511196, 0.405296096912831, 0.376952125845609, 0.305955839936506, 0.311749835295614, 0.345526622009758]
let qtpScl40to60Results = [0.377154083910409, 0.447823924935884, 0.346002749603373, 0.337312172280812, 0.287776301542286, 0.447823924935884, 0.347575510988814, 0.425367177982039, 0.397439682935174, 0.407936906359218, 0.380983321185079, 0.446792662967033, 0.438186528881586, 0.356185090966534, 0.336402970641248, 0.408864741791309, 0.38027120116752, 0.3086497907284, 0.314494802398846, 0.348568994782171]
let qtpScl60to70Results = [0.383267554098483, 0.455082916237838, 0.351611272975997, 0.342779825946212, 0.292441004684493, 0.455082916237838, 0.353209527999854, 0.432262157176261, 0.403881972060058, 0.414549349978507, 0.387158861304039, 0.454034938052534, 0.445289303040515, 0.361958664760256, 0.341855886624211, 0.415492225137053, 0.386435198193926, 0.31365284219906, 0.319592598447705, 0.354219115645224]
let qtpSclOver70Results = [0.388440490411469, 0.461225139647183, 0.356356946598986, 0.347406302124627, 0.296388061189437, 0.461225139647183, 0.357976773163043, 0.438096370340604, 0.409333139781115, 0.420144494579444, 0.392384318327774, 0.460163016971034, 0.451299342713454, 0.366843996431866, 0.346469892455949, 0.421100095660375, 0.391650887985501, 0.317886193443464, 0.323906118181355, 0.35899998714473]
let qtpMrrCombinedResults = [0.413821771693228, 0.508533430672105, 0.373152381869917, 0.361933826377932, 0.29912780919351, 0.508533430672105, 0.375188710548383, 0.478087654563197, 0.440672786059032, 0.454676340321416, 0.41886870507502, 0.507128475779878, 0.495429182453337, 0.386368438266048, 0.36076346102693, 0.455917593187799, 0.417929359993219, 0.325349349141896, 0.332756789013529, 0.37647597165676]
let qtpMrrMaleResults = [0.424125777984843, 0.532048789322944, 0.378507805564762, 0.366009275588722, 0.29678535674638, 0.532048789322944, 0.380780533626931, 0.497116618990778, 0.454493686215864, 0.470405717058715, 0.429819095149359, 0.530432098509776, 0.516987143164534, 0.393279950653825, 0.364707587991336, 0.471818522676574, 0.428758921733536, 0.325525441425888, 0.333687253469035, 0.382217871036895]
let qtpMrrFemaleResults = [0.43332459094498, 0.532499872895024, 0.390738511829181, 0.37899124210563, 0.313225268522446, 0.532499872895024, 0.392870809721618, 0.500619231563821, 0.461441054631539, 0.47610457607386, 0.438609378969167, 0.531028704518649, 0.518778040484407, 0.404577421774221, 0.377765719134946, 0.4774043273856, 0.437625763917541, 0.340682591576259, 0.348439133333816, 0.394218737576994]
let qtcYosResults = [0.579906218804505, 0.528825056770059, 0.828474492438624, 0.48224203851013, 0.774980584992121, 0.474932057354002, 0.343211875252954, 0.575942676843373, 0.574911678752592, 0.70808444229737, 0.510869669852896, 0.237975725997005, 0.219118704977358, 0.564706795107062, 0.439503683395084, 0.647020109439033, 0.295094939615308, 0.463050541134329, 0.568509730648057, 0.530461863859337]
let qtpHggResults = [0.397723522060237, 0.514593140257427, 0.34948004234863, 0.336396194984426, 0.265085269300276, 0.514593140257427, 0.351865599341567, 0.476375062319597, 0.430239119560274, 0.44739646847064, 0.403795988092997, 0.512816633895587, 0.498071380426541, 0.365019999452085, 0.335037012880667, 0.448923712895632, 0.402664376373178, 0.294443542975559, 0.302846991069748, 0.353375296250318]
let qtcGotResults = [0.579203844535374, 0.519841973412787, 0.834110198571954, 0.486668752869248, 0.793694526906362, 0.466864447459891, 0.345401335203816, 0.568865772485733, 0.571433440838143, 0.702101733629883, 0.509773318369705, 0.233983264079855, 0.215831398660427, 0.567021643889854, 0.443649072162604, 0.641418243478878, 0.294512725299276, 0.471163742780999, 0.577465572639112, 0.533704621330601]
let qtpGotResults = [0.44085515386182, 0.525505853647332, 0.403651700430511, 0.393285985326909, 0.334322577521446, 0.525505853647332, 0.405528252857931, 0.498571040336432, 0.465119786497204, 0.477687183972686, 0.445433277532429, 0.524268265435149, 0.513942830785809, 0.41580423347261, 0.392201879633879, 0.478798355242157, 0.444581808364807, 0.359142660259095, 0.366099746923131, 0.406713735134663]
let qtpKlgResults = [0.404846153846154, 0.435508902929351, 0.382369863013699, 0.374548387096774, 0.309571428571429, 0.435508902929351, 0.383702702702703, 0.427916890080429, 0.415921939194741, 0.420817629179331, 0.407119402985075, 0.435193175245807, 0.432440833844267, 0.39058904109589, 0.373682926829268, 0.42122641509434, 0.406703564727955, 0.342052631578947, 0.34965671641791, 0.38453227771011]
let qtpShpMaleResults = [0.404862149379267, 0.523829427390253, 0.355752761057451, 0.342434075407223, 0.269843210031307, 0.523829427390253, 0.358181135740005, 0.484925383950975, 0.437961360167766, 0.455426661494472, 0.411043608392102, 0.522021035016789, 0.507011123152145, 0.371571640467891, 0.341050497727243, 0.456981317998887, 0.409891685692696, 0.299728427080249, 0.308282706294077, 0.35971792977276]
let qtpShpFemaleResults = [0.423218619628201, 0.547579880017518, 0.37188260916585, 0.357960053637274, 0.282077914768243, 0.547579880017518, 0.374421086478847, 0.506911925288802, 0.457818550301318, 0.47607572927004, 0.429680346304087, 0.545689495042739, 0.529999033017986, 0.38841871736568, 0.356513744475581, 0.477700873978685, 0.428476195371458, 0.313318129063736, 0.322260259728065, 0.376027558830467]
let qtpWhlResults = [0.388038461538462, 0.416610568638713, 0.367094645080946, 0.359806451612903, 0.29925974025974, 0.416610568638713, 0.368336609336609, 0.409536193029491, 0.398359079704191, 0.402920972644377, 0.39015671641791, 0.416316367842684, 0.413751686082158, 0.374753424657534, 0.359, 0.403301886792453, 0.389769230769231, 0.329526315789474, 0.336611940298507, 0.369109622411693]
let qtpAshChildrenResults = [0.391996117044997, 0.471719418867772, 0.352880341389589, 0.34148415183345, 0.272216862110643, 0.471719418867772, 0.354919599379902, 0.447630386077981, 0.416091955089145, 0.428161211353421, 0.396624788966186, 0.470636686254582, 0.461514117604713, 0.365959176150672, 0.34027926029047, 0.429215327853606, 0.395766874265625, 0.302317490243958, 0.310505649083991, 0.356204139013828]
let qtpAshWomen40Results = [0.405585315769223, 0.488072358721855, 0.365113526557761, 0.35332226909701, 0.281653713330479, 0.488072358721855, 0.367223478825072, 0.463148239462017, 0.430516476198902, 0.443004133347006, 0.410374448317014, 0.486952091378074, 0.477513273681677, 0.378645760923896, 0.352075607980539, 0.444094792552531, 0.4094867925735, 0.312797829905748, 0.321269844918903, 0.368552549166307]
let qtpAshOldMenResults = [0.39722273193893, 0.478009011119342, 0.357585412608116, 0.346037273857897, 0.275846420272118, 0.478009011119342, 0.359651860704968, 0.453598791225687, 0.421639847823667, 0.433870027504799, 0.401913119485735, 0.476911842071309, 0.467667639172776, 0.370838631832681, 0.344816317094343, 0.434938198891654, 0.4010437659225, 0.306348390113877, 0.314645724405111, 0.360953527534012]
let qtpAshOldWomenResults = [0.407675961726796, 0.490588195622483, 0.366995555045172, 0.355143517906788, 0.283105536595069, 0.490588195622483, 0.369116383355099, 0.4655356015211, 0.432735633292711, 0.445287659807557, 0.412489780524833, 0.489462153704765, 0.479974682308902, 0.380597543196699, 0.353890430702089, 0.44638394096775, 0.41159754923625, 0.314410189853716, 0.322925875047351, 0.370452304574381]
let qtpSrmResults = [0.467943852816009, 0.501964962009996, 0.432041878958843, 0.418924693761001, 0.317265549437452, 0.501964962009996, 0.434264663415656, 0.496178946347809, 0.483161815926127, 0.488987775833421, 0.471259409594866, 0.501766224618623, 0.499877953540303, 0.445630139774855, 0.417469921964094, 0.489444204809106, 0.470659364790308, 0.365508528402883, 0.377655343054707, 0.435645174354612]
let qtpLccResults = [0.410586099174599, 0.423922662115945, 0.390357090382849, 0.381905599234239, 0.302661343013188, 0.423922662115945, 0.391738749324714, 0.422293129755823, 0.417512064869254, 0.41980865364909, 0.412195546039764, 0.423873750511202, 0.423381510873599, 0.39855695761056, 0.380938205193939, 0.419978678851639, 0.411908108409114, 0.342961136833629, 0.352390695407995, 0.392589155420387]
// mocks for testing formula sources
class TestQtcFormulas: QTcFormulaSource {
static func qtcCalculator(formula: Formula) -> QTcCalculator {
return QTcCalculator(formula: formula, longName: "TestLongName", shortName: "TestShortName", reference: "TestReference", equation: "TestEquation", baseEquation: { x, y, sex, age in x + y}, classification: .other, publicationDate: "1901")
}
}
class TestQtpFormulas: QTpFormulaSource {
static func qtpCalculator(formula: Formula) -> QTpCalculator {
return QTpCalculator(formula: formula, longName: "TestLongName", shortName: "TestShortName", reference: "TestReference", equation: "TestEquation", baseEquation: {x, sex, age in pow(x, 2.0)}, classification: .other)
}
}
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 testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
func testConversions() {
// sec <-> msec conversions
XCTAssertEqual(QTc.secToMsec(1), 1000)
XCTAssertEqual(QTc.secToMsec(2), 2000)
XCTAssertEqual(QTc.msecToSec(1000), 1)
XCTAssertEqual(QTc.msecToSec(2000), 2)
XCTAssertEqual(QTc.msecToSec(0), 0)
XCTAssertEqual(QTc.secToMsec(0), 0)
XCTAssertEqual(QTc.msecToSec(2000), 2)
XCTAssertEqual(QTc.msecToSec(1117), 1.117, accuracy: delta)
// bpm <-> sec conversions
XCTAssertEqual(QTc.bpmToSec(1), 60)
// Swift divide by zero doesn't throw
XCTAssertNoThrow(QTc.bpmToSec(0))
XCTAssert(QTc.bpmToSec(0).isInfinite)
XCTAssertEqual(QTc.bpmToSec(0), Double.infinity)
XCTAssertEqual(QTc.bpmToSec(0.333), 180.18018018018, accuracy: delta)
// bpm <-> msec conversions
// we'll check published conversion table with rough accuracy
// source: https://link.springer.com/content/pdf/bfm%3A978-3-642-58810-5%2F1.pdf
XCTAssertEqual(QTc.bpmToMsec(215), 279, accuracy: veryRoughDelta)
for (rate, interval) in rateIntervalTable {
XCTAssertEqual(QTc.bpmToMsec(rate), interval, accuracy: veryRoughDelta)
XCTAssertEqual(QTc.msecToBpm(interval), rate, accuracy: veryVeryRoughDelta)
}
}
func testQTcFunctions() {
// QTcBZT (Bazett)
let qtcBzt = QTc.qtcCalculator(formula: .qtcBzt)
XCTAssertEqual(try! qtcBzt.calculate(qtInSec:0.3, rrInSec:1.0), 0.3, accuracy: delta)
XCTAssertEqual(try! qtcBzt.calculate(qtInMsec:300, rrInMsec:1000), 300, accuracy:delta)
XCTAssertEqual(try! qtcBzt.calculate(qtInSec: 0.3, rate: 60), 0.3, accuracy: delta)
XCTAssertEqual(try! qtcBzt.calculate(qtInMsec: 300, rate: 60), 300, accuracy: delta)
for (qt, interval, qtc) in qtcBztTable {
XCTAssertEqual(try! qtcBzt.calculate(qtInMsec: qt, rrInMsec: interval), qtc, accuracy: veryRoughDelta)
}
XCTAssertEqual(try! qtcBzt.calculate(qtInMsec: 456, rate: 77), 516.6, accuracy: roughDelta)
XCTAssertEqual(try! qtcBzt.calculate(qtInMsec: 369, rrInMsec: 600), 476.4, accuracy: roughDelta)
XCTAssertEqual(try! qtcBzt.calculate(qtInSec: 2.78, rate: 88), 3.3667, accuracy: roughDelta)
XCTAssertEqual(try! qtcBzt.calculate(qtInSec: 2.78, rrInSec: QTc.bpmToSec(88)), 3.3667, accuracy: roughDelta)
XCTAssertEqual(try! qtcBzt.calculate(qtInSec: 5.0, rrInSec: 0), Double.infinity)
XCTAssertEqual(try! qtcBzt.calculate(qtInSec: 5.0, rrInSec: 0), Double.infinity)
// QTcFRD (Fridericia)
let qtcFrd = QTc.qtcCalculator(formula: .qtcFrd)
XCTAssertEqual(try! qtcFrd.calculate(qtInMsec: 456, rate: 77), 495.5, accuracy: roughDelta)
XCTAssertEqual(try! qtcFrd.calculate(qtInMsec: 369, rrInMsec: 600), 437.5, accuracy: roughDelta)
XCTAssertEqual(try! qtcFrd.calculate(qtInSec: 2.78, rate: 88), 3.1586, accuracy: roughDelta)
XCTAssertEqual(try! qtcFrd.calculate(qtInSec: 2.78, rrInSec: QTc.bpmToSec(88)), 3.1586, accuracy: roughDelta)
// run through multiple QTcs
let qtcFrm = QTc.qtcCalculator(formula: .qtcFrm)
let qtcHdg = QTc.qtcCalculator(formula: .qtcHdg)
for (rate, rrInSec, rrInMsec, qtInMsec, qtcBztResult, qtcFrdResult, qtcFrmResult, qtcHdgResult) in qtcMultipleTable {
// all 4 forms of QTc calculation are tested for each calculation
// QTcBZT
XCTAssertEqual(try! qtcBzt.calculate(qtInMsec: qtInMsec, rate: rate), qtcBztResult, accuracy: roughDelta)
XCTAssertEqual(try! qtcBzt.calculate(qtInSec: QTc.msecToSec(qtInMsec), rrInSec: rrInSec), QTc.msecToSec(qtcBztResult), accuracy: roughDelta)
XCTAssertEqual(try! qtcBzt.calculate(qtInMsec: qtInMsec, rrInMsec: rrInMsec), qtcBztResult, accuracy: roughDelta)
XCTAssertEqual(try! qtcBzt.calculate(qtInSec: QTc.msecToSec(qtInMsec), rate: rate), QTc.msecToSec(qtcBztResult), accuracy: roughDelta)
// QTcFRD
XCTAssertEqual(try! qtcFrd.calculate(qtInMsec: qtInMsec, rate: rate), qtcFrdResult, accuracy: roughDelta)
XCTAssertEqual(try! qtcFrd.calculate(qtInSec: QTc.msecToSec(qtInMsec), rrInSec: rrInSec), QTc.msecToSec(qtcFrdResult), accuracy: roughDelta)
XCTAssertEqual(try! qtcFrd.calculate(qtInMsec: qtInMsec, rrInMsec: rrInMsec), qtcFrdResult, accuracy: roughDelta)
XCTAssertEqual(try! qtcFrd.calculate(qtInSec: QTc.msecToSec(qtInMsec), rate: rate), QTc.msecToSec(qtcFrdResult), accuracy: roughDelta)
// QTcFRM
XCTAssertEqual(try! qtcFrm.calculate(qtInMsec: qtInMsec, rate: rate), qtcFrmResult, accuracy: roughDelta)
XCTAssertEqual(try! qtcFrm.calculate(qtInSec: QTc.msecToSec(qtInMsec), rrInSec: rrInSec), QTc.msecToSec(qtcFrmResult), accuracy: roughDelta)
XCTAssertEqual(try! qtcFrm.calculate(qtInMsec: qtInMsec, rrInMsec: rrInMsec), qtcFrmResult, accuracy: roughDelta)
XCTAssertEqual(try! qtcFrm.calculate(qtInSec: QTc.msecToSec(qtInMsec), rate: rate), QTc.msecToSec(qtcFrmResult), accuracy: roughDelta)
// QTcHDG
XCTAssertEqual(try! qtcHdg.calculate(qtInMsec: qtInMsec, rate: rate), qtcHdgResult, accuracy: roughDelta)
XCTAssertEqual(try! qtcHdg.calculate(qtInSec: QTc.msecToSec(qtInMsec), rrInSec: rrInSec), QTc.msecToSec(qtcHdgResult), accuracy: roughDelta)
XCTAssertEqual(try! qtcHdg.calculate(qtInMsec: qtInMsec, rrInMsec: rrInMsec), qtcHdgResult, accuracy: roughDelta)
XCTAssertEqual(try! qtcHdg.calculate(qtInSec: QTc.msecToSec(qtInMsec), rate: rate), QTc.msecToSec(qtcHdgResult), accuracy: roughDelta)
}
// handle zero RR
XCTAssertEqual(try! qtcBzt.calculate(qtInSec: 300, rrInSec: 0), Double.infinity)
XCTAssertEqual(try! qtcFrd.calculate(qtInSec: 300, rrInSec: 0), Double.infinity)
// handle zero QT and RR
XCTAssert(try! qtcFrd.calculate(qtInMsec: 0, rrInMsec: 0).isNaN)
// handle negative RR
XCTAssert(try! qtcBzt.calculate(qtInMsec: 300, rrInMsec: -100).isNaN)
// QTcRTHa
let qtcRtha = QTc.qtcCalculator(formula: .qtcRtha)
XCTAssertEqual(try! qtcRtha.calculate(qtInSec: 0.444, rate: 58.123), 0.43937, accuracy: delta)
// QTcMyd
let qtcMyd = QTc.qtcCalculator(formula: .qtcMyd)
XCTAssertEqual(try! qtcMyd.calculate(qtInSec: 0.399, rrInSec: 0.788), 0.46075606, accuracy: delta)
// QTcArr
let qtcArr = QTc.qtcCalculator(formula: .qtcArr)
XCTAssertEqual(try! qtcArr.calculate(qtInSec: 0.275, rate: 69), 0.295707844, accuracy: delta)
// Run through more multiple QTcs
let qtcKwt = QTc.qtcCalculator(formula: .qtcKwt)
let qtcDmt = QTc.qtcCalculator(formula: .qtcDmt)
for (qtInSec, rrInSec, qtcMydResult, qtcRthaResult, qtcArrResult, qtcKwtResult, qtcDmtResult) in qtcRandomTable {
XCTAssertEqual(try! qtcMyd.calculate(qtInSec: qtInSec, rrInSec: rrInSec), qtcMydResult, accuracy: delta)
XCTAssertEqual(try! qtcRtha.calculate(qtInSec: qtInSec, rrInSec: rrInSec), qtcRthaResult, accuracy: delta)
XCTAssertEqual(try! qtcArr.calculate(qtInSec: qtInSec, rrInSec: rrInSec), qtcArrResult, accuracy: delta)
XCTAssertEqual(try! qtcKwt.calculate(qtInSec: qtInSec, rrInSec: rrInSec), qtcKwtResult, accuracy: delta)
XCTAssertEqual(try! qtcDmt.calculate(qtInSec: qtInSec, rrInSec: rrInSec), qtcDmtResult, accuracy: delta)
}
}
// Most QTc functions will have QTc == QT at HR 60 (RR 1000 msec)
func testEquipose() {
let sampleQTs = [0.345, 1.0, 0.555, 0.114, 0, 0.888]
// Subset of QTc formulae, only including non-exponential formulas
let formulas: [Formula] = [.qtcBzt, .qtcFrd, .qtcHdg, .qtcFrm, .qtcMyd, .qtcRtha]
for formula in formulas {
let qtc = QTc.qtcCalculator(formula: formula)
for qt in sampleQTs {
XCTAssertEqual(try! qtc.calculate(qtInSec: qt, rrInSec: 1.0), qt)
}
}
}
func testNewFormulas() {
let qtcYos = QTc.qtcCalculator(formula: .qtcYos)
// QTcYOS is pediatric formula and throws if age not given or age is adult
XCTAssertEqual(try! qtcYos.calculate(qtInSec: 0.421, rrInSec: 1.34, age: 14), 0.384485183352,
accuracy: delta)
XCTAssertThrowsError(try qtcYos.calculate(qtInSec: 0.421, rate: 1.34))
XCTAssertThrowsError(try qtcYos.calculate(qtInSec: 0.421, rate: 1.34, age: 21))
}
func testNewQTpFormulas() {
let qtpBdl = QTc.qtpCalculator(formula: .qtpBdl)
XCTAssertEqual(try! qtpBdl.calculate(rate: 60, sex: .male), 0.401, accuracy: delta)
XCTAssertEqual(try! qtpBdl.calculate(rate: 99, sex: .female), 0.3328, accuracy: delta)
let qtpAsh = QTc.qtpCalculator(formula: .qtpAsh)
XCTAssertEqual(try! qtpAsh.calculate(rate: 60, sex: .female, age: 20), 0.396312754411, accuracy: delta)
XCTAssertThrowsError(try qtpAsh.calculate(rrInSec: 0.8))
XCTAssertThrowsError(try qtpAsh.calculate(rrInSec: 0.8, sex: .male))
XCTAssertThrowsError(try qtpAsh.calculate(rrInSec: 0.8, age: 55))
}
func testQTcConvert() {
let qtcBzt = QTc.qtcCalculator(formula: .qtcBzt)
let qtcHdg = QTc.qtcCalculator(formula: .qtcHdg)
let qtcRtha = QTc.qtcCalculator(formula: .qtcRtha)
let qtcFrm = QTc.qtcCalculator(formula: .qtcFrm)
XCTAssertEqual(try! qtcBzt.calculate(qtInMsec: 356.89, rrInMsec: 891.32), QTc.secToMsec(try! qtcBzt.calculate(qtInSec: 0.35689, rrInSec: 0.89132)))
XCTAssertEqual(try! qtcHdg.calculate(qtInSec: 0.299, rrInSec: 0.5), QTc.msecToSec(try! qtcHdg.calculate(qtInMsec: 299, rate: 120)))
XCTAssertEqual(try! qtcRtha.calculate(qtInSec: 0.489, rate: 78.9), QTc.msecToSec(try! qtcRtha.calculate(qtInMsec: 489, rate: 78.9)))
XCTAssertEqual(try! qtcFrm.calculate(qtInMsec: 843, rrInMsec: 300), try! qtcFrm.calculate(qtInMsec: 843, rate: 200))
}
func testQTpConvert() {
let qtpArr = QTc.qtpCalculator(formula: .qtpArr)
XCTAssertEqual(try! qtpArr.calculate(rrInSec: 0.253), QTc.msecToSec(try! qtpArr.calculate(rrInMsec: 253)))
XCTAssertEqual(try! qtpArr.calculate(rrInSec: 0.500), try! qtpArr.calculate(rate: 120))
}
func testMockSourceFormulas() {
let qtcTest = QTc.qtcCalculator(formulaSource: TestQtcFormulas.self, formula: .qtcBzt)
XCTAssertEqual(qtcTest.formula, .qtcBzt)
XCTAssertEqual(qtcTest.longName, "TestLongName")
XCTAssertEqual(qtcTest.shortName, "TestShortName")
XCTAssertEqual(qtcTest.reference, "TestReference")
XCTAssertEqual(qtcTest.equation, "TestEquation")
XCTAssertEqual(qtcTest.publicationDate, "1901")
XCTAssertEqual(try! qtcTest.calculate(qtInSec: 5, rrInSec: 7), 12)
let qtpTest = QTc.qtpCalculator(formulaSource: TestQtpFormulas.self, formula: .qtpArr)
XCTAssertEqual(qtpTest.formula, .qtpArr)
XCTAssertEqual(qtpTest.longName, "TestLongName")
XCTAssertEqual(qtpTest.shortName, "TestShortName")
XCTAssertEqual(qtpTest.reference, "TestReference")
XCTAssertEqual(qtpTest.equation, "TestEquation")
XCTAssertEqual(qtpTest.publicationDate, nil)
XCTAssertEqual(try! qtpTest.calculate(rrInSec: 5), 25)
}
func testSexFormulas() {
let calculator = QTc.qtcCalculator(formula: .qtcAdm)
let qt = 0.888
let rr = 0.678
let qtcUnspecifiedSex = try! calculator.calculate(qtInSec: qt, rrInSec: rr, sex: .unspecified, age: 55)
let qtcMale = try! calculator.calculate(qtInSec: qt, rrInSec: rr, sex: .male, age: 60)
let qtcFemale = try! calculator.calculate(qtInSec: 0.888, rrInSec: rr, sex: .female, age: 99)
XCTAssertEqual(qtcUnspecifiedSex, 0.9351408, accuracy: delta)
XCTAssertEqual(qtcMale, 0.9374592, accuracy: delta)
XCTAssertEqual(qtcFemale, 0.9285398, accuracy: delta)
}
func testClassification() {
let qtcBzt = QTc.qtcCalculator(formula: .qtcBzt)
XCTAssertEqual(qtcBzt.classification, .power)
let qtcFrm = QTc.qtcCalculator(formula: .qtcFrm)
XCTAssertEqual(qtcFrm.classification, .linear)
}
func testNewCalculate() {
let qtcBzt = QTc.calculator(formula: .qtcBzt, formulaType: .qtc)
var qtMeasurement = QtMeasurement(qt: 370.0, intervalRate: 1000, units: .msec, intervalRateType: .interval, sex: .unspecified, age: nil)
XCTAssertEqual(try? qtcBzt.calculate(qtMeasurement: qtMeasurement), 370.0)
let qtpBzt = QTc.calculator(formula: .qtpBzt, formulaType: .qtp)
qtMeasurement = QtMeasurement(qt: 370.0, intervalRate: 1000, units: .msec, intervalRateType: .interval, sex: .female, age: nil)
XCTAssertEqual(try? qtpBzt.calculate(qtMeasurement: qtMeasurement), 400.0)
let qtcFrd = QTc.calculator(formula: .qtcFrd)
XCTAssertEqual(try? qtcFrd.calculate(qtMeasurement: qtMeasurement), 370.0)
}
func testFormulaTypes() {
let qtcBzt = QTc.calculator(formula: .qtcBzt, formulaType: .qtc)
XCTAssert(qtcBzt.formula == .qtcBzt)
XCTAssert(qtcBzt.formula.formulaType() == .qtc)
// .qtcTest not member of QTc or QTp set of formulas
// However can't test this, as it leads to assertionFailure and program halt
//let qtcTst = QTc.calculator(formula: .qtcTest, formulaType: .qtc)
//XCTAssertThrowsError(qtcTst.formula?.formulaType())
}
func testAbnormalQTc() {
var qtcTest = QTcTest(value: 440, units: .msec, valueComparison: .greaterThan)
var measurement = QTcMeasurement(qtc: 441, units: .msec)
XCTAssertTrue(qtcTest.isAbnormal(qtcMeasurement: measurement))
measurement = QTcMeasurement(qtc: 439, units: .msec)
XCTAssertFalse(qtcTest.isAbnormal(qtcMeasurement: measurement))
measurement = QTcMeasurement(qtc: 440, units: .msec)
XCTAssertFalse(qtcTest.isAbnormal(qtcMeasurement: measurement))
measurement = QTcMeasurement(qtc: 0.439, units: .sec)
XCTAssertFalse(qtcTest.isAbnormal(qtcMeasurement: measurement))
measurement = QTcMeasurement(qtc: 0.441, units: .sec)
XCTAssertTrue(qtcTest.isAbnormal(qtcMeasurement: measurement))
qtcTest = QTcTest(value: 440, units: .msec, valueComparison: .greaterThanOrEqual)
measurement = QTcMeasurement(qtc: 440, units: .msec)
XCTAssertTrue(qtcTest.isAbnormal(qtcMeasurement: measurement))
qtcTest = QTcTest(value: 350, units: .msec, valueComparison: .lessThanOrEqual)
measurement = QTcMeasurement(qtc: 350, units: .msec)
XCTAssertTrue(qtcTest.isAbnormal(qtcMeasurement: measurement))
measurement = QTcMeasurement(qtc: 351, units: .msec)
XCTAssertFalse(qtcTest.isAbnormal(qtcMeasurement: measurement))
qtcTest = QTcTest(value: 350, units: .msec, valueComparison: .lessThanOrEqual, sex: .female)
measurement = QTcMeasurement(qtc: 311, units: .msec)
XCTAssertFalse(qtcTest.isAbnormal(qtcMeasurement: measurement))
measurement = QTcMeasurement(qtc: 311, units: .msec, sex: .male)
XCTAssertFalse(qtcTest.isAbnormal(qtcMeasurement: measurement))
measurement = QTcMeasurement(qtc: 311, units: .msec, sex: .female)
XCTAssertTrue(qtcTest.isAbnormal(qtcMeasurement: measurement))
qtcTest = QTcTest(value: 350, units: .msec, valueComparison: .lessThanOrEqual, sex: .female, age: 18, ageComparison: .lessThan)
measurement = QTcMeasurement(qtc: 311, units: .msec, sex: .female)
XCTAssertFalse(qtcTest.isAbnormal(qtcMeasurement: measurement))
measurement = QTcMeasurement(qtc: 311, units: .msec, sex: .female, age: 15)
XCTAssertTrue(qtcTest.isAbnormal(qtcMeasurement: measurement))
var testSuite = QTcTestSuite(name: "test", qtcTests: [qtcTest], reference: "test", description: "test")
var result = testSuite.abnormalQTcTests(qtcMeasurement: measurement)
XCTAssertEqual(result.count, 1)
XCTAssertTrue(result[0].severity == .abnormal)
XCTAssertEqual(testSuite.severity(measurement: measurement), .abnormal)
measurement = QTcMeasurement(qtc: 355, units: .msec, sex: .female, age: 15)
result = testSuite.abnormalQTcTests(qtcMeasurement: measurement)
XCTAssertEqual(result.count, 0)
XCTAssertEqual(testSuite.severity(measurement: measurement), .normal)
let qtcTest2 = QTcTest(value: 440, units: .msec, valueComparison: .greaterThan, severity: .moderate)
testSuite = QTcTestSuite(name: "test2", qtcTests: [qtcTest, qtcTest2], reference: "test", description: "test")
measurement = QTcMeasurement(qtc: 500, units: .msec)
XCTAssertEqual(testSuite.severity(measurement: measurement), .moderate)
}
func testAbnormalQTcCriteria() {
if let testSuite = AbnormalQTc.qtcTestSuite(criterion: .schwartz1985) {
var measurement = QTcMeasurement(qtc: 445, units: .msec)
XCTAssertEqual(testSuite.severity(measurement: measurement), .abnormal)
XCTAssert(testSuite.severity(measurement: measurement).isAbnormal())
measurement = QTcMeasurement(qtc: 0.439, units: .sec)
XCTAssertFalse(testSuite.severity(measurement: measurement).isAbnormal())
}
if let testSuite = AbnormalQTc.qtcTestSuite(criterion: .fda2005) {
var measurement = QTcMeasurement(qtc: 455, units: .msec)
XCTAssertEqual(testSuite.severity(measurement: measurement), .mild)
measurement = QTcMeasurement(qtc: 485, units: .msec)
XCTAssertEqual(testSuite.severity(measurement: measurement), .moderate)
measurement = QTcMeasurement(qtc: 600, units: .msec)
XCTAssertEqual(testSuite.severity(measurement: measurement), .severe)
measurement = QTcMeasurement(qtc: 450, units: .msec)
XCTAssertEqual(testSuite.severity(measurement: measurement), .normal)
}
if let testSuite = AbnormalQTc.qtcTestSuite(criterion: .aha2009) {
var measurement = QTcMeasurement(qtc: 450, units: .msec, sex: .male)
XCTAssertEqual(testSuite.severity(measurement: measurement), .abnormal)
measurement = QTcMeasurement(qtc: 460, units: .msec, sex: .female)
XCTAssertEqual(testSuite.severity(measurement: measurement), .abnormal)
// we leave out the sex here to get undefined value
measurement = QTcMeasurement(qtc: 460, units: .msec)
XCTAssertEqual(testSuite.severity(measurement: measurement), .undefined)
measurement = QTcMeasurement(qtc: 459, units: .msec, sex: .female)
XCTAssertEqual(testSuite.severity(measurement: measurement), .normal)
measurement = QTcMeasurement(qtc: 390, units: .msec)
XCTAssertEqual(testSuite.severity(measurement: measurement), .undefined)
}
if let testSuite = AbnormalQTc.qtcTestSuite(criterion: .esc2005) {
var measurement = QTcMeasurement(qtc: 450, units: .msec, sex: .male)
XCTAssertEqual(testSuite.severity(measurement: measurement), .abnormal)
measurement = QTcMeasurement(qtc: 460, units: .msec, sex: .female)
XCTAssertEqual(testSuite.severity(measurement: measurement), .normal)
measurement = QTcMeasurement(qtc: 461, units: .msec, sex: .female)
XCTAssertEqual(testSuite.severity(measurement: measurement), .abnormal)
// we leave out the sex here to make sure we get an undefined value
measurement = QTcMeasurement(qtc: 461, units: .msec)
XCTAssertEqual(testSuite.severity(measurement: measurement), .undefined)
measurement = QTcMeasurement(qtc: 459, units: .msec, sex: .female)
XCTAssertEqual(testSuite.severity(measurement: measurement), .normal)
measurement = QTcMeasurement(qtc: 290, units: .msec)
XCTAssertEqual(testSuite.severity(measurement: measurement), .undefined)
}
if let testSuite = AbnormalQTc.qtcTestSuite(criterion: .goldenberg2006) {
var m = QTcMeasurement(qtc: 445, units: .msec) // requires age and sex
XCTAssertEqual(testSuite.severity(measurement: m), .undefined)
m = QTcMeasurement(qtc: 445, units: .msec, sex: .male)
XCTAssertEqual(testSuite.severity(measurement: m), .undefined)
m = QTcMeasurement(qtc: 445, units: .msec, sex: .male, age: 20)
XCTAssertEqual(testSuite.severity(measurement: m), .borderline)
m = QTcMeasurement(qtc: 461, units: .msec, sex: .female, age: 10)
XCTAssertEqual(testSuite.severity(measurement: m), .abnormal)
m = QTcMeasurement(qtc: 461, units: .msec, sex: .female, age: 16)
XCTAssertEqual(testSuite.severity(measurement: m), .borderline)
m = QTcMeasurement(qtc: 461, units: .msec, sex: .male, age: 16)
XCTAssertEqual(testSuite.severity(measurement: m), .abnormal)
}
if let testSuite = AbnormalQTc.qtcTestSuite(criterion: .schwartz1993) {
var m = QTcMeasurement(qtc: 445, units: .msec) // requires sex
XCTAssertEqual(testSuite.severity(measurement: m), .undefined)
m = QTcMeasurement(qtc: 445, units: .msec, sex: .male)
XCTAssertEqual(testSuite.severity(measurement: m), .normal)
m = QTcMeasurement(qtc: 445, units: .msec, sex: .male, age: 20)
XCTAssertEqual(testSuite.severity(measurement: m), .normal)
m = QTcMeasurement(qtc: 461, units: .msec, sex: .female, age: 10)
XCTAssertEqual(testSuite.severity(measurement: m), .moderate)
m = QTcMeasurement(qtc: 461, units: .msec, sex: .female, age: 16)
XCTAssertEqual(testSuite.severity(measurement: m), .moderate)
m = QTcMeasurement(qtc: 451, units: .msec, sex: .male, age: 16)
XCTAssertEqual(testSuite.severity(measurement: m), .mild)
m = QTcMeasurement(qtc: 451, units: .msec, sex: .female, age: 16)
XCTAssertEqual(testSuite.severity(measurement: m), .normal)
}
// test short QTc
if let testSuite = AbnormalQTc.qtcTestSuite(criterion: .gollob2011) {
var m = QTcMeasurement(qtc: 0.345, units: .sec)
XCTAssertEqual(testSuite.severity(measurement: m), .moderate)
m = QTcMeasurement(qtc: 315, units: .msec)
XCTAssertEqual(testSuite.severity(measurement: m), .severe)
m = QTcMeasurement(qtc: 370, units: .msec)
XCTAssertEqual(testSuite.severity(measurement: m), .normal)
m = QTcMeasurement(qtc: 369.99999, units: .msec)
XCTAssertEqual(testSuite.severity(measurement: m), .mild)
}
if let testSuite = AbnormalQTc.qtcTestSuite(criterion: .mazzanti2014) {
var m = QTcMeasurement(qtc: 360, units: .msec)
XCTAssertEqual(testSuite.severity(measurement: m), .borderline)
m = QTcMeasurement(qtc: 335, units: .msec)
XCTAssertEqual(testSuite.severity(measurement: m), .abnormal)
}
}
// TODO: test new QTc and QTp formulas
func testQTp() {
var calculator: QTpCalculator = QTc.qtpCalculator(formula: .qtpBzt)
var i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .male), qtpBztMaleResults[i], accuracy: delta)
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .female), qtpBztFemaleResults[i], accuracy: delta)
i += 1
}
calculator = QTc.qtpCalculator(formula: .qtpFrd)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval), qtpFrdResults[i], accuracy: delta)
i += 1
}
calculator = QTc.qtpCalculator(formula: .qtpHdg)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval), qtpHdgResults[i], accuracy: delta)
i += 1
}
calculator = QTc.qtpCalculator(formula: .qtpMyd)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval), qtpMydResults[i], accuracy: delta)
i += 1
}
calculator = QTc.qtpCalculator(formula: .qtpKrj)
i = 0
for interval in rrIntervals {
if interval > 1.0 {
XCTAssertEqual(qtpKrjSlowResults[i], try calculator.calculate(rrInSec: interval), accuracy: delta)
}
else if interval <= 0.6 {
XCTAssertEqual(qtpKrjFastResults[i], try calculator.calculate(rrInSec: interval), accuracy: delta)
}
else {
XCTAssertEqual(qtpKrjMediumResults[i], try calculator.calculate(rrInSec: interval), accuracy: delta)
}
i += 1
}
calculator = QTc.qtpCalculator(formula: .qtpSch)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval), qtpSchResults[i], accuracy: delta)
i += 1
}
calculator = QTc.qtpCalculator(formula: .qtpAdm)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .male), qtpAdmMenResults[i], accuracy: delta)
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .female), qtpAdmWomenResults[i], accuracy: delta)
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .unspecified), qtpAdmCombinedResults[i], accuracy: delta)
i += 1
}
calculator = QTc.qtpCalculator(formula: .qtpSmn)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval, age: ages[i]), qtpSmnResults[i], accuracy: delta)
i += 1
}
// make sure QTpSMN throws if no age given
XCTAssertThrowsError(try calculator.calculate(rrInSec: 0.4))
calculator = QTc.qtpCalculator(formula: .qtpKwt)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval, age: ages[i]), qtpKwtResults[i], accuracy: delta)
i += 1
}
// NB: in between ages with extrapolated constants not tested here, but are tested in the Rabkin tests.
calculator = QTc.qtpCalculator(formula: .qtpScl)
i = 0
for interval in rrIntervals {
if ages[i] < 20 {
i += 1
continue
}
if ages[i] < 30 {
XCTAssertEqual(try calculator.calculate(rrInSec: interval, age: ages[i]), qtpScl20to40Results[i], accuracy: delta)
}
else if ages[i] < 50 && ages[i] > 40 {
XCTAssertEqual(try calculator.calculate(rrInSec: interval, age: ages[i]), qtpScl40to60Results[i], accuracy: delta)
}
else if ages[i] < 70 && ages[i] > 60 {
XCTAssertEqual(try calculator.calculate(rrInSec: interval, age: ages[i]), qtpScl60to70Results[i], accuracy: delta)
}
else if ages[i] > 70 {
XCTAssertEqual(try calculator.calculate(rrInSec: interval, age: ages[i]), qtpSclOver70Results[i], accuracy: delta)
}
i += 1
}
XCTAssertThrowsError(try calculator.calculate(rate: 60))
XCTAssertThrowsError(try calculator.calculate(rate: 60, age: 15))
calculator = QTc.qtpCalculator(formula: .qtpMrr)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval), qtpMrrCombinedResults[i], accuracy: delta)
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .male), qtpMrrMaleResults[i], accuracy: delta)
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .female), qtpMrrFemaleResults[i], accuracy: delta)
i += 1
}
calculator = QTc.qtpCalculator(formula: .qtpHgg)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval), qtpHggResults[i], accuracy: delta)
i += 1
}
calculator = QTc.qtpCalculator(formula: .qtpGot)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval), qtpGotResults[i], accuracy: delta)
i += 1
}
calculator = QTc.qtpCalculator(formula: .qtpKlg)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval), qtpKlgResults[i], accuracy: delta)
i += 1
}
calculator = QTc.qtpCalculator(formula: .qtpShp)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .male), qtpShpMaleResults[i], accuracy: delta)
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .female), qtpShpFemaleResults[i], accuracy: delta)
i += 1
}
XCTAssertThrowsError(try calculator.calculate(rrInSec: 0.4))
calculator = QTc.qtpCalculator(formula: .qtpWhl)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .female), qtpWhlResults[i], accuracy: delta)
i += 1
}
calculator = QTc.qtpCalculator(formula: .qtpAsh)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .female, age: 12), qtpAshChildrenResults[i], accuracy: delta)
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .female, age: 40), qtpAshWomen40Results[i], accuracy: delta)
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .female, age: 77), qtpAshOldWomenResults[i], accuracy: delta)
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .male, age: 46), qtpAshOldMenResults[i], accuracy: delta)
i += 1
}
calculator = QTc.qtpCalculator(formula: .qtpSrm)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .female), qtpSrmResults[i], accuracy: delta)
i += 1
}
calculator = QTc.qtpCalculator(formula: .qtpLcc)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try calculator.calculate(rrInSec: interval, sex: .female), qtpLccResults[i], accuracy: delta)
i += 1
}
}
func testQTc() {
var qtcCalculator = QTc.qtcCalculator(formula: .qtcRthb)
var i = 0
for interval in rrIntervals {
XCTAssertEqual(try qtcCalculator.calculate(qtInSec: qtIntervals[i], rrInSec: interval, sex: .male, age: nil), qtcRthbMaleResults[i], accuracy: delta)
XCTAssertEqual(try qtcCalculator.calculate(qtInSec: qtIntervals[i], rrInSec: interval, sex: .female, age: nil), qtcRthbFemaleResults[i], accuracy: delta)
i += 1
}
qtcCalculator = QTc.qtcCalculator(formula: .qtcYos)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try qtcCalculator.calculate(qtInSec: qtIntervals[i], rrInSec: interval, age: 15), qtcYosResults[i], accuracy: delta)
i += 1
}
qtcCalculator = QTc.qtcCalculator(formula: .qtcGot)
i = 0
for interval in rrIntervals {
XCTAssertEqual(try qtcCalculator.calculate(qtInSec: qtIntervals[i], rrInSec: interval), qtcGotResults[i], accuracy: delta)
i += 1
}
}
func testCutoffs() {
let test = AbnormalQTc.qtcTestSuite(criterion: .schwartz1985)
let cutoffs = test?.cutoffs(units: .sec)
XCTAssertEqual(cutoffs![0].value, 0.44)
let cutoffsMsec = test?.cutoffs(units: .msec)
XCTAssertEqual(cutoffsMsec![0].value, 440.0)
}
typealias formulaTest = (formula: Formula, result: Double)
typealias formulaTests = [formulaTest]
private func rabkinTest(results: formulaTests, qtMeasurement: QtMeasurement, accuracy: Double = 0.1) {
for result in results {
print(QTc.calculator(formula: result.formula).shortName + " ," + String((try!QTc.calculator(formula: result.formula).calculate(qtMeasurement: qtMeasurement))) + ", " + String(result.result))
XCTAssertEqual(round(try! QTc.calculator(formula: result.formula).calculate(qtMeasurement: qtMeasurement)), result.result, accuracy: accuracy)
}
}
func testRabkinResults() {
// Note that the QTcDMT in Rabkin appears to use a formula with a typo: the exponent he uses in 0.473 rather than 0.413. So we have corrected his result for QTcDMT here. Rabkin has 437 for QTcDMT. It should be 438.
let results1: formulaTests = [(.qtcFrm, 439.0), (.qtcHdg, 441.0), (.qtcRtha, 439.0), (.qtcBzt, 437.0), (.qtcFrd, 439.0), (.qtcMyd, 435.0), (.qtcKwt, 440.0), (.qtcDmt, 438.0), (.qtcGot, 439.0), (.qtcRthb, 439.0)]
let qtMeasurement = QtMeasurement(qt: 444.0, intervalRate: 58, units: .msec, intervalRateType: .rate, sex: .male, age: 71)
rabkinTest(results: results1, qtMeasurement: qtMeasurement)
let results2: formulaTests = [(.qtpAdm, 405), (.qtpSch, 379), (.qtpKrj, 397), (.qtpSmn, 408), (.qtpBdl, 405), (.qtpHdg, 395), (.qtpWhl, 388), (.qtpKlg, 404), (.qtpBzt, 376), (.qtpFrd, 386), (.qtpMyd, 424), (.qtpScl, 388), (.qtpShp, 404), (.qtpHgg, 397), (.qtpKwt, 454), (.qtpGot, 440), (.qtpAsh, 396), (.qtpMrr, 423), (.qtpSrm, 467), (.qtpLcc, 410), (.qtpArr, 425)]
rabkinTest(results: results2, qtMeasurement: qtMeasurement)
let qtMeasurement2 = QtMeasurement(qt: 354, intervalRate: 107, units: .msec, intervalRateType: .rate, sex: .male, age: 53)
let results3: formulaTests = [(.qtcFrm, 422), (.qtcHdg, 436), (.qtcRtha, 446), (.qtcBzt, 473), (.qtcFrd, 429), (.qtcMyd, 502), (.qtcKwt, 409), (.qtcDmt, 450), (.qtcGot, 431), (.qtcRthb, 429)]
rabkinTest(results: results3, qtMeasurement: qtMeasurement2)
let results4: formulaTests = [(.qtpAdm, 332), (.qtpSch, 282), (.qtpKrj, 314), (.qtpSmn, 337), (.qtpBdl, 307), (.qtpHdg, 309), (.qtpWhl, 327), (.qtpKlg, 340), (.qtpBzt, 277), (.qtpFrd, 315), (.qtpMyd, 293), (.qtpScl, 309), (.qtpShp, 297), (.qtpHgg, 292), (.qtpKwt, 389), (.qtpGot, 357), (.qtpAsh, 304), (.qtpMrr, 323), (.qtpSrm, 362), (.qtpLcc, 340), (.qtpArr, 325)]
rabkinTest(results: results4, qtMeasurement: qtMeasurement2)
let qtMeasurment3 = QtMeasurement(qt: 384, intervalRate: 89, units: .msec, intervalRateType: .rate, sex: .female, age: 53)
let results5: formulaTests = [(.qtcFrm, 434), (.qtcHdg, 435), (.qtcRtha, 446), (.qtcBzt, 468), (.qtcFrd, 438), (.qtcMyd, 487), (.qtcKwt, 424), (.qtcDmt, 452), (.qtcGot, 439), (.qtcRthb, 442)]
rabkinTest(results: results5, qtMeasurement: qtMeasurment3)
let results6: formulaTests = [(.qtpAdm, 364), (.qtpSch, 305), (.qtpKrj, 341), (.qtpSmn,353), (.qtpBdl, 351), (.qtpHdg, 340), (.qtpWhl, 350), (.qtpKlg, 364), (.qtpBzt, 328), (.qtpFrd, 335), (.qtpMyd, 327), (.qtpScl, 329), (.qtpShp, 341), (.qtpHgg, 320), (.qtpKwt, 408), (.qtpGot, 380), (.qtpAsh, 340), (.qtpMrr, 364), (.qtpSrm, 400), (.qtpLcc, 369), (.qtpArr, 357)]
rabkinTest(results: results6, qtMeasurement: qtMeasurment3)
// Simonson tests
let qtMesaurement4 = QtMeasurement(qt: 430, intervalRate: 1180, units: .msec, intervalRateType: .interval, sex: .male, age: 55)
let results7: formulaTests = [(.qtpBzt, 400), (.qtpShp, 430), (.qtpScl, 400), (.qtpAsh, 420), (.qtpSch, 410), (.qtpMyd, 450), (.qtpSmn, 420)]
rabkinTest(results: results7, qtMeasurement: qtMesaurement4, accuracy: 10.0)
let qtMesaurement5 = QtMeasurement(qt: 340, intervalRate: 660, units: .msec, intervalRateType: .interval, sex: .male, age: 45)
let results8: formulaTests = [(.qtpBzt, 300), (.qtpShp, 320), (.qtpScl, 320), (.qtpAsh, 330), (.qtpSch, 310), (.qtpMyd, 320), (.qtpSmn, 350)]
rabkinTest(results: results8, qtMeasurement: qtMesaurement5, accuracy: 10.0)
let qtMesaurement6 = QtMeasurement(qt: 370, intervalRate: 840, units: .msec, intervalRateType: .interval, sex: .male, age: 25)
let results9: formulaTests = [(.qtpBzt, 340), (.qtpShp, 360), (.qtpScl, 350), (.qtpAsh, 350), (.qtpSch, 340), (.qtpMyd, 370), (.qtpSmn, 370)]
rabkinTest(results: results9, qtMeasurement: qtMesaurement6, accuracy: 10.0)
}
func testRound() {
print(QtcRbk.r(15.783353333))
}
func testQtcRbk() {
XCTAssertEqual(QtcRbk.b1(60), 0.05552338, accuracy: delta)
XCTAssertEqual(QtcRbk.b1(80), 0)
XCTAssertEqual(QtcRbk.b2(60), 0.4502079, accuracy: delta)
XCTAssertEqual(QtcRbk.b2(80), 0)
XCTAssertEqual(QtcRbk.b3(60), 0.4942118, accuracy: delta)
XCTAssertEqual(QtcRbk.b3(80), 0.0004464286, accuracy: delta)
XCTAssertEqual(QtcRbk.b4(60), 0, accuracy: delta)
XCTAssertEqual(QtcRbk.b4(80), 0.7917742, accuracy: delta)
XCTAssertEqual(QtcRbk.b5(60), 0, accuracy: delta)
XCTAssertEqual(QtcRbk.b5(80), 0.2015557, accuracy: delta)
XCTAssertEqual(QtcRbk.b6(60), 0, accuracy: delta)
XCTAssertEqual(QtcRbk.b6(80), 0.00622369, accuracy: delta)
XCTAssertEqual(QtcRbk.b7(60), 0, accuracy: delta)
XCTAssertEqual(QtcRbk.b7(80), 0, accuracy: delta)
// The calculations in Rabkin seem to be off by a few hundreths msec, thus the rough rounding here.
// Change accuracy to delta to see the difference between Rabkin results and hand calculated results.
XCTAssertEqual(QtcRbk.qtpRbkR(hr: 60, isFemale: false, age: 50.3), 417.7246, accuracy: veryRoughDelta)
XCTAssertEqual(QtcRbk.qtpRbkR(hr: 80, isFemale: true, age: 70), 389.5633, accuracy: veryRoughDelta)
XCTAssertEqual(QtcRbk.qtcRbk(qt: 405, hr: 80, isFemale: true, age: 70), 433.1613, accuracy: veryRoughDelta)
// test Table 1 in https://www.sciencedirect.com/science/article/pii/S2405500X16305199?via%3Dihub#bib9
XCTAssertEqual(QtcRbk.qtcRbk(qt: 340, hr: 114, isFemale: true, age: 72), 419, accuracy: veryRoughDelta)
XCTAssertEqual(QtcRbk.qtcRbk(qt: 340, hr: 114, isFemale: true), 423, accuracy: veryRoughDelta)
var calculator = QTc.calculator(formula: .qtcBzt)
XCTAssertEqual(try calculator.calculate(qtMeasurement: QtMeasurement(qt: 340, intervalRate: 114, units: .msec, intervalRateType: .rate, sex: .female, age: 72)), 469, accuracy: veryRoughDelta)
calculator = QTc.calculator(formula: .qtcDmt)
XCTAssertEqual(try calculator.calculate(qtMeasurement: QtMeasurement(qt: 340, intervalRate: 114, units: .msec, intervalRateType: .rate, sex: .female, age: 72)), 443, accuracy: veryRoughDelta)
calculator = QTc.calculator(formula: .qtcFrd)
XCTAssertEqual(try calculator.calculate(qtMeasurement: QtMeasurement(qt: 340, intervalRate: 114, units: .msec, intervalRateType: .rate, sex: .female, age: 72)), 421, accuracy: veryRoughDelta)
calculator = QTc.calculator(formula: .qtcFrm)
XCTAssertEqual(try calculator.calculate(qtMeasurement: QtMeasurement(qt: 340, intervalRate: 114, units: .msec, intervalRateType: .rate, sex: .female, age: 72)), 413, accuracy: veryRoughDelta)
calculator = QTc.calculator(formula: .qtcHdg)
XCTAssertEqual(try calculator.calculate(qtMeasurement: QtMeasurement(qt: 340, intervalRate: 114, units: .msec, intervalRateType: .rate, sex: .female, age: 72)), 434, accuracy: veryRoughDelta)
calculator = QTc.calculator(formula: .qtcRtha)
XCTAssertEqual(try calculator.calculate(qtMeasurement: QtMeasurement(qt: 340, intervalRate: 114, units: .msec, intervalRateType: .rate, sex: .female, age: 72)), 442, accuracy: veryRoughDelta)
calculator = QTc.calculator(formula: .qtcRthb)
XCTAssertEqual(try calculator.calculate(qtMeasurement: QtMeasurement(qt: 340, intervalRate: 114, units: .msec, intervalRateType: .rate, sex: .female, age: 72)), 431, accuracy: veryRoughDelta)
// rates < 35 should be constant
XCTAssertEqual(QtcRbk.qtpRbk(hr: 34, isFemale: false), QtcRbk.qtpRbk(hr: 23, isFemale: false))
// rates > 156 should be constant
XCTAssertEqual(QtcRbk.qtpRbk(hr: 158, isFemale: true), QtcRbk.qtpRbk(hr: 177, isFemale: true))
// test formula
calculator = QTc.calculator(formula: .qtcRbk)
XCTAssertEqual(try calculator.calculate(qtMeasurement: QtMeasurement(qt: 340, intervalRate: 114, units: .msec, intervalRateType: .rate, sex: .female, age: 72)), 419, accuracy: veryRoughDelta)
XCTAssertEqual(try calculator.calculate(qtMeasurement: QtMeasurement(qt: 340, intervalRate: 114, units: .msec, intervalRateType: .rate, sex: .female)), 423, accuracy: veryRoughDelta)
XCTAssertThrowsError(try calculator.calculate(qtMeasurement: QtMeasurement(qt: 340, intervalRate: 114, units: .msec, intervalRateType: .rate)))
calculator = QTc.calculator(formula: .qtpRbk)
XCTAssertEqual(try calculator.calculate(qtMeasurement: QtMeasurement(qt: nil, intervalRate: 60, units: .msec, intervalRateType: .rate, sex: .male, age: 50)), 418, accuracy: veryRoughDelta)
XCTAssertEqual(try calculator.calculate(qtMeasurement: QtMeasurement(qt: nil, intervalRate: 80, units: .msec, intervalRateType: .rate, sex: .female, age: 70)), 389, accuracy: veryRoughDelta)
}
func testShortNames() {
for formula in qtcFormulas {
XCTAssertEqual(QTc.qtcCalculator(formula: formula).shortName.prefix(3), "QTc")
}
for formula in qtpFormulas {
XCTAssertEqual(QTc.qtpCalculator(formula: formula).shortName.prefix(3), "QTp")
}
}
}
|
apache-2.0
|
3b676f905489b2e73cfab5707cf9e039
| 75.897406 | 410 | 0.660476 | 3.212741 | false | true | false | false |
stephencelis/SQLite.swift
|
Tests/SQLiteTests/Typed/SelectTests.swift
|
1
|
1191
|
import XCTest
@testable import SQLite
class SelectTests: SQLiteTestCase {
override func setUpWithError() throws {
try super.setUpWithError()
try createUsersTable()
try createUsersDataTable()
}
func createUsersDataTable() throws {
try db.execute("""
CREATE TABLE users_name (
id INTEGER,
user_id INTEGER REFERENCES users(id),
name TEXT
)
"""
)
}
func test_select_columns_from_multiple_tables() throws {
let usersData = Table("users_name")
let users = Table("users")
let name = Expression<String>("name")
let id = Expression<Int64>("id")
let userID = Expression<Int64>("user_id")
let email = Expression<String>("email")
try insertUser("Joey")
try db.run(usersData.insert(
id <- 1,
userID <- 1,
name <- "Joey"
))
try db.prepare(users.select(name, email).join(usersData, on: userID == users[id])).forEach {
XCTAssertEqual($0[name], "Joey")
XCTAssertEqual($0[email], "[email protected]")
}
}
}
|
mit
|
d9c0c0e6e2a5eddac88e65d8007406b2
| 26.068182 | 100 | 0.542401 | 4.460674 | false | true | false | false |
austinzmchen/guildOfWarWorldBosses
|
GoWWorldBosses/ViewControllers/Storage/WBStorageMainViewController.swift
|
1
|
2282
|
//
// WBStorageMainViewController.swift
// GoWWorldBosses
//
// Created by Austin Chen on 2016-11-28.
// Copyright © 2016 Austin Chen. All rights reserved.
//
import UIKit
class WBStorageMainViewController: UIViewController, WBDrawerItemViewControllerType {
@IBAction func leftBarButtonTapped(_ sender: Any) {
viewDelegate?.didTriggerToggleButton()
}
@IBOutlet weak var segmentControl: UISegmentedControl!
@IBAction func segmentControlValueChanged(_ sender: UISegmentedControl) {
guard self.storagePageVC?.pageIndex() != sender.selectedSegmentIndex else {
return
}
self.storagePageVC?.scrollToViewController(index: sender.selectedSegmentIndex)
// switch sender.selectedSegmentIndex {
// case 0:
// self.storagePageVC?.scrollToViewController(index: 0)
// break
// case 1:
// break
// default:
// break
// }
}
weak var viewDelegate: WBDrawerMasterViewControllerDelegate?
var storagePageVC: WBStoragePageViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let leftBarButtonItem = UIBarButtonItem.barButtonItem(withImageName:"icBurger",
title: "Storage",
forTarget: self,
action: #selector(leftBarButtonTapped(_:)) )
self.navigationItem.setLeftBarButton(leftBarButtonItem, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "containedStorageVCSegue" {
self.storagePageVC = segue.destination as! WBStoragePageViewController
self.storagePageVC?.wbDelegate = self
}
}
}
extension WBStorageMainViewController: WBStoragePageViewControllerDelegate {
func didUpdate(pageIndex: Int, viewController: WBStoragePageViewController) {
self.segmentControl.selectedSegmentIndex = pageIndex
}
func didUpdate(pageCount: Int, viewController: WBStoragePageViewController) {
}
}
|
mit
|
f5d3030f404d8fead764a88b6af94f75
| 33.044776 | 106 | 0.62911 | 5.577017 | false | false | false | false |
austinzmchen/guildOfWarWorldBosses
|
GoWWorldBosses/ViewControllers/WBLoaderViewController.swift
|
1
|
1847
|
//
// WBLoaderViewController.swift
// GoWWorldBosses
//
// Created by Austin Chen on 2016-12-04.
// Copyright © 2016 Austin Chen. All rights reserved.
//
import UIKit
enum WBLoaderStatus {
case loading
case loaded
}
class WBLoaderViewController: UIViewController {
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
@IBOutlet weak var spinner: UIImageView!
static var sharedInstance: WBLoaderViewController? = nil
static func instantiate() -> WBLoaderViewController {
let loaderVC = WBStoryboardFactory.utilityStoryboard.instantiateViewController(withIdentifier: "loaderVC") as! WBLoaderViewController
loaderVC.modalTransitionStyle = .crossDissolve
loaderVC.modalPresentationStyle = .overCurrentContext
return loaderVC
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//loadingIndicator.startAnimating()
self.resetLoader()
}
deinit {
//loadingIndicator.stopAnimating()
self.status = .loaded
}
// MARK: instance methods
var status: WBLoaderStatus = .loading
@objc fileprivate func startLoader() {
switch self.status {
case .loading:
UIView.animate(withDuration: 0.6, delay: 0, options: .curveLinear, animations: { [weak self] in
if let iv = self?.spinner {
iv.transform = iv.transform.rotated(by: -CGFloat(M_PI_2))
}
}) { [weak self] (finished) -> () in
_ = self?.perform(#selector(self?.startLoader))
}
break
default:
break
}
}
func resetLoader() {
self.status = .loading
self.startLoader()
}
}
|
mit
|
e0bd1f53b1d50c487c4028a401ded6b8
| 26.147059 | 141 | 0.611593 | 4.883598 | false | false | false | false |
Harry-L/5-3-1
|
ios-charts-master/Charts/Classes/Renderers/ChartYAxisRendererRadarChart.swift
|
4
|
8132
|
//
// ChartYAxisRendererRadarChart.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class ChartYAxisRendererRadarChart: ChartYAxisRenderer
{
private weak var chart: RadarChartView?
public init(viewPortHandler: ChartViewPortHandler, yAxis: ChartYAxis, chart: RadarChartView)
{
super.init(viewPortHandler: viewPortHandler, yAxis: yAxis, transformer: nil)
self.chart = chart
}
public override func computeAxis(yMin yMin: Double, yMax: Double)
{
computeAxisValues(min: yMin, max: yMax)
}
public override func computeAxisValues(min yMin: Double, max yMax: Double)
{
guard let yAxis = yAxis else { return }
let labelCount = yAxis.labelCount
let range = abs(yMax - yMin)
if (labelCount == 0 || range <= 0)
{
yAxis.entries = [Double]()
return
}
let rawInterval = range / Double(labelCount)
var interval = ChartUtils.roundToNextSignificant(number: Double(rawInterval))
let intervalMagnitude = pow(10.0, round(log10(interval)))
let intervalSigDigit = Int(interval / intervalMagnitude)
if (intervalSigDigit > 5)
{
// Use one order of magnitude higher, to avoid intervals like 0.9 or
// 90
interval = floor(10 * intervalMagnitude)
}
// force label count
if yAxis.isForceLabelsEnabled
{
let step = Double(range) / Double(labelCount - 1)
if yAxis.entries.count < labelCount
{
// Ensure stops contains at least numStops elements.
yAxis.entries.removeAll(keepCapacity: true)
}
else
{
yAxis.entries = [Double]()
yAxis.entries.reserveCapacity(labelCount)
}
var v = yMin
for (var i = 0; i < labelCount; i++)
{
yAxis.entries.append(v)
v += step
}
}
else
{
// no forced count
// clean old values
if (yAxis.entries.count > 0)
{
yAxis.entries.removeAll(keepCapacity: false)
}
// if the labels should only show min and max
if (yAxis.isShowOnlyMinMaxEnabled)
{
yAxis.entries = [Double]()
yAxis.entries.append(yMin)
yAxis.entries.append(yMax)
}
else
{
let rawCount = Double(yMin) / interval
var first = rawCount < 0.0 ? floor(rawCount) * interval : ceil(rawCount) * interval;
if (first < yMin && yAxis.isStartAtZeroEnabled)
{ // Force the first label to be at the 0 (or smallest negative value)
first = yMin
}
if (first == 0.0)
{ // Fix for IEEE negative zero case (Where value == -0.0, and 0.0 == -0.0)
first = 0.0
}
let last = ChartUtils.nextUp(floor(Double(yMax) / interval) * interval)
var f: Double
var i: Int
var n = 0
for (f = first; f <= last; f += interval)
{
++n
}
if (isnan(yAxis.customAxisMax))
{
n += 1
}
if (yAxis.entries.count < n)
{
// Ensure stops contains at least numStops elements.
yAxis.entries = [Double](count: n, repeatedValue: 0.0)
}
for (f = first, i = 0; i < n; f += interval, ++i)
{
yAxis.entries[i] = Double(f)
}
}
}
if !yAxis.isStartAtZeroEnabled && yAxis.entries[0] < yMin
{
// If startAtZero is disabled, and the first label is lower that the axis minimum,
// Then adjust the axis minimum
yAxis.axisMinimum = yAxis.entries[0]
}
yAxis.axisMaximum = yAxis.entries[yAxis.entryCount - 1]
yAxis.axisRange = abs(yAxis.axisMaximum - yAxis.axisMinimum)
}
public override func renderAxisLabels(context context: CGContext)
{
guard let
yAxis = yAxis,
chart = chart
else { return }
if (!yAxis.isEnabled || !yAxis.isDrawLabelsEnabled)
{
return
}
let labelFont = yAxis.labelFont
let labelTextColor = yAxis.labelTextColor
let center = chart.centerOffsets
let factor = chart.factor
let labelCount = yAxis.entryCount
let labelLineHeight = yAxis.labelFont.lineHeight
for (var j = 0; j < labelCount; j++)
{
if (j == labelCount - 1 && yAxis.isDrawTopYLabelEntryEnabled == false)
{
break
}
let r = CGFloat(yAxis.entries[j] - yAxis.axisMinimum) * factor
let p = ChartUtils.getPosition(center: center, dist: r, angle: chart.rotationAngle)
let label = yAxis.getFormattedLabel(j)
ChartUtils.drawText(context: context, text: label, point: CGPoint(x: p.x + 10.0, y: p.y - labelLineHeight), align: .Left, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor])
}
}
public override func renderLimitLines(context context: CGContext)
{
guard let
yAxis = yAxis,
chart = chart
else { return }
var limitLines = yAxis.limitLines
if (limitLines.count == 0)
{
return
}
CGContextSaveGState(context)
let sliceangle = chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = chart.factor
let center = chart.centerOffsets
for (var i = 0; i < limitLines.count; i++)
{
let l = limitLines[i]
if !l.isEnabled
{
continue
}
CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor)
CGContextSetLineWidth(context, l.lineWidth)
if (l.lineDashLengths != nil)
{
CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
let r = CGFloat(l.limit - chart.chartYMin) * factor
CGContextBeginPath(context)
for (var j = 0, count = chart.data!.xValCount; j < count; j++)
{
let p = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(j) + chart.rotationAngle)
if (j == 0)
{
CGContextMoveToPoint(context, p.x, p.y)
}
else
{
CGContextAddLineToPoint(context, p.x, p.y)
}
}
CGContextClosePath(context)
CGContextStrokePath(context)
}
CGContextRestoreGState(context)
}
}
|
mit
|
e2f8e42423662897d763674fc915987b
| 30.16092 | 227 | 0.489179 | 5.396151 | false | false | false | false |
chandler14362/antlr4
|
runtime/Swift/Antlr4/org/antlr/v4/runtime/DefaultErrorStrategy.swift
|
1
|
31654
|
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
/**
* This is the default implementation of {@link org.antlr.v4.runtime.ANTLRErrorStrategy} used for
* error reporting and recovery in ANTLR parsers.
*/
import Foundation
public class DefaultErrorStrategy: ANTLRErrorStrategy {
/**
* Indicates whether the error strategy is currently "recovering from an
* error". This is used to suppress reporting multiple error messages while
* attempting to recover from a detected syntax error.
*
* @see #inErrorRecoveryMode
*/
internal var errorRecoveryMode: Bool = false
/** The index into the input stream where the last error occurred.
* This is used to prevent infinite loops where an error is found
* but no token is consumed during recovery...another error is found,
* ad nauseum. This is a failsafe mechanism to guarantee that at least
* one token/tree node is consumed for two errors.
*/
internal var lastErrorIndex: Int = -1
internal var lastErrorStates: IntervalSet?
/**
* {@inheritDoc}
*
* <p>The default implementation simply calls {@link #endErrorCondition} to
* ensure that the handler is not in error recovery mode.</p>
*/
public func reset(_ recognizer: Parser) {
endErrorCondition(recognizer)
}
/**
* This method is called to enter error recovery mode when a recognition
* exception is reported.
*
* @param recognizer the parser instance
*/
internal func beginErrorCondition(_ recognizer: Parser) {
errorRecoveryMode = true
}
/**
* {@inheritDoc}
*/
public func inErrorRecoveryMode(_ recognizer: Parser) -> Bool {
return errorRecoveryMode
}
/**
* This method is called to leave error recovery mode after recovering from
* a recognition exception.
*
* @param recognizer
*/
internal func endErrorCondition(_ recognizer: Parser) {
errorRecoveryMode = false
lastErrorStates = nil
lastErrorIndex = -1
}
/**
* {@inheritDoc}
*
* <p>The default implementation simply calls {@link #endErrorCondition}.</p>
*/
public func reportMatch(_ recognizer: Parser) {
endErrorCondition(recognizer)
}
/**
* {@inheritDoc}
*
* <p>The default implementation returns immediately if the handler is already
* in error recovery mode. Otherwise, it calls {@link #beginErrorCondition}
* and dispatches the reporting task based on the runtime type of {@code e}
* according to the following table.</p>
*
* <ul>
* <li>{@link org.antlr.v4.runtime.NoViableAltException}: Dispatches the call to
* {@link #reportNoViableAlternative}</li>
* <li>{@link org.antlr.v4.runtime.InputMismatchException}: Dispatches the call to
* {@link #reportInputMismatch}</li>
* <li>{@link org.antlr.v4.runtime.FailedPredicateException}: Dispatches the call to
* {@link #reportFailedPredicate}</li>
* <li>All other types: calls {@link org.antlr.v4.runtime.Parser#notifyErrorListeners} to report
* the exception</li>
* </ul>
*/
public func reportError(_ recognizer: Parser,
_ e: AnyObject) {
// if we've already reported an error and have not matched a token
// yet successfully, don't report any errors.
if inErrorRecoveryMode(recognizer) {
return // don't report spurious errors
}
beginErrorCondition(recognizer)
//TODO: exception handler
if (e is NoViableAltException) {
try! reportNoViableAlternative(recognizer, e as! NoViableAltException);
} else {
if (e is InputMismatchException) {
reportInputMismatch(recognizer, e as! InputMismatchException);
} else {
if (e is FailedPredicateException) {
reportFailedPredicate(recognizer, e as! FailedPredicateException);
} else {
errPrint("unknown recognition error type: " + String(describing: type(of: e)));
let re = (e as! RecognitionException<ParserATNSimulator>)
recognizer.notifyErrorListeners(re.getOffendingToken(), re.message ?? "", e);
}
}
}
}
/**
* {@inheritDoc}
*
* <p>The default implementation resynchronizes the parser by consuming tokens
* until we find one in the resynchronization set--loosely the set of tokens
* that can follow the current rule.</p>
*/
public func recover(_ recognizer: Parser, _ e: AnyObject) throws {
// print("recover in "+recognizer.getRuleInvocationStack()+
// " index="+getTokenStream(recognizer).index()+
// ", lastErrorIndex="+
// lastErrorIndex+
// ", states="+lastErrorStates);
if let lastErrorStates = lastErrorStates ,
lastErrorIndex == getTokenStream(recognizer).index() &&
lastErrorStates.contains(recognizer.getState()) {
// uh oh, another error at same token index and previously-visited
// state in ATN; must be a case where LT(1) is in the recovery
// token set so nothing got consumed. Consume a single token
// at least to prevent an infinite loop; this is a failsafe.
// errPrint("seen error condition before index="+
// lastErrorIndex+", states="+lastErrorStates);
// errPrint("FAILSAFE consumes "+recognizer.getTokenNames()[getTokenStream(recognizer).LA(1)]);
try recognizer.consume()
}
lastErrorIndex = getTokenStream(recognizer).index()
if lastErrorStates == nil {
lastErrorStates = try IntervalSet()
}
try lastErrorStates!.add(recognizer.getState())
let followSet: IntervalSet = try getErrorRecoverySet(recognizer)
try consumeUntil(recognizer, followSet)
}
/**
* The default implementation of {@link org.antlr.v4.runtime.ANTLRErrorStrategy#sync} makes sure
* that the current lookahead symbol is consistent with what were expecting
* at this point in the ATN. You can call this anytime but ANTLR only
* generates code to check before subrules/loops and each iteration.
*
* <p>Implements Jim Idle's magic sync mechanism in closures and optional
* subrules. E.g.,</p>
*
* <pre>
* a : sync ( stuff sync )* ;
* sync : {consume to what can follow sync} ;
* </pre>
*
* At the start of a sub rule upon error, {@link #sync} performs single
* token deletion, if possible. If it can't do that, it bails on the current
* rule and uses the default error recovery, which consumes until the
* resynchronization set of the current rule.
*
* <p>If the sub rule is optional ({@code (...)?}, {@code (...)*}, or block
* with an empty alternative), then the expected set includes what follows
* the subrule.</p>
*
* <p>During loop iteration, it consumes until it sees a token that can start a
* sub rule or what follows loop. Yes, that is pretty aggressive. We opt to
* stay in the loop as long as possible.</p>
*
* <p><strong>ORIGINS</strong></p>
*
* <p>Previous versions of ANTLR did a poor job of their recovery within loops.
* A single mismatch token or missing token would force the parser to bail
* out of the entire rules surrounding the loop. So, for rule</p>
*
* <pre>
* classDef : 'class' ID '{' member* '}'
* </pre>
*
* input with an extra token between members would force the parser to
* consume until it found the next class definition rather than the next
* member definition of the current class.
*
* <p>This functionality cost a little bit of effort because the parser has to
* compare token set at the start of the loop and at each iteration. If for
* some reason speed is suffering for you, you can turn off this
* functionality by simply overriding this method as a blank { }.</p>
*/
public func sync(_ recognizer: Parser) throws {
let s: ATNState = recognizer.getInterpreter().atn.states[recognizer.getState()]!
// errPrint("sync @ "+s.stateNumber+"="+s.getClass().getSimpleName());
// If already recovering, don't try to sync
if inErrorRecoveryMode(recognizer) {
return
}
let tokens: TokenStream = getTokenStream(recognizer)
let la: Int = try tokens.LA(1)
// try cheaper subset first; might get lucky. seems to shave a wee bit off
//let set : IntervalSet = recognizer.getATN().nextTokens(s)
if try recognizer.getATN().nextTokens(s).contains(la) || la == CommonToken.EOF {
return
}
// Return but don't end recovery. only do that upon valid token match
if try recognizer.isExpectedToken(la) {
return
}
switch s.getStateType() {
case ATNState.BLOCK_START: fallthrough
case ATNState.STAR_BLOCK_START: fallthrough
case ATNState.PLUS_BLOCK_START: fallthrough
case ATNState.STAR_LOOP_ENTRY:
// report error and recover if possible
if try singleTokenDeletion(recognizer) != nil {
return
}
throw try ANTLRException.recognition(e: InputMismatchException(recognizer))
case ATNState.PLUS_LOOP_BACK: fallthrough
case ATNState.STAR_LOOP_BACK:
// errPrint("at loop back: "+s.getClass().getSimpleName());
try reportUnwantedToken(recognizer)
let expecting: IntervalSet = try recognizer.getExpectedTokens()
let whatFollowsLoopIterationOrRule: IntervalSet =
try expecting.or(try getErrorRecoverySet(recognizer)) as! IntervalSet
try consumeUntil(recognizer, whatFollowsLoopIterationOrRule)
break
default:
// do nothing if we can't identify the exact kind of ATN state
break
}
}
/**
* This is called by {@link #reportError} when the exception is a
* {@link org.antlr.v4.runtime.NoViableAltException}.
*
* @see #reportError
*
* @param recognizer the parser instance
* @param e the recognition exception
*/
internal func reportNoViableAlternative(_ recognizer: Parser,
_ e: NoViableAltException) throws {
let tokens: TokenStream? = getTokenStream(recognizer)
var input: String
if let tokens = tokens {
if e.getStartToken().getType() == CommonToken.EOF {
input = "<EOF>"
} else {
input = try tokens.getText(e.getStartToken(), e.getOffendingToken())
}
} else {
input = "<unknown input>"
}
let msg: String = "no viable alternative at input " + escapeWSAndQuote(input)
recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e)
}
/**
* This is called by {@link #reportError} when the exception is an
* {@link org.antlr.v4.runtime.InputMismatchException}.
*
* @see #reportError
*
* @param recognizer the parser instance
* @param e the recognition exception
*/
internal func reportInputMismatch(_ recognizer: Parser,
_ e: InputMismatchException) {
let msg: String = "mismatched input " + getTokenErrorDisplay(e.getOffendingToken()) +
" expecting " + e.getExpectedTokens()!.toString(recognizer.getVocabulary())
recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e)
}
/**
* This is called by {@link #reportError} when the exception is a
* {@link org.antlr.v4.runtime.FailedPredicateException}.
*
* @see #reportError
*
* @param recognizer the parser instance
* @param e the recognition exception
*/
internal func reportFailedPredicate(_ recognizer: Parser,
_ e: FailedPredicateException) {
let ruleName: String = recognizer.getRuleNames()[recognizer._ctx!.getRuleIndex()]
let msg: String = "rule " + ruleName + " " + e.message! // e.getMessage()
recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e)
}
/**
* This method is called to report a syntax error which requires the removal
* of a token from the input stream. At the time this method is called, the
* erroneous symbol is current {@code LT(1)} symbol and has not yet been
* removed from the input stream. When this method returns,
* {@code recognizer} is in error recovery mode.
*
* <p>This method is called when {@link #singleTokenDeletion} identifies
* single-token deletion as a viable recovery strategy for a mismatched
* input error.</p>
*
* <p>The default implementation simply returns if the handler is already in
* error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to
* enter error recovery mode, followed by calling
* {@link org.antlr.v4.runtime.Parser#notifyErrorListeners}.</p>
*
* @param recognizer the parser instance
*/
internal func reportUnwantedToken(_ recognizer: Parser) throws {
if inErrorRecoveryMode(recognizer) {
return
}
beginErrorCondition(recognizer)
let t: Token = try recognizer.getCurrentToken()
let tokenName: String = getTokenErrorDisplay(t)
let expecting: IntervalSet = try getExpectedTokens(recognizer)
let msg: String = "extraneous input " + tokenName + " expecting " +
expecting.toString(recognizer.getVocabulary())
recognizer.notifyErrorListeners(t, msg, nil)
}
/**
* This method is called to report a syntax error which requires the
* insertion of a missing token into the input stream. At the time this
* method is called, the missing token has not yet been inserted. When this
* method returns, {@code recognizer} is in error recovery mode.
*
* <p>This method is called when {@link #singleTokenInsertion} identifies
* single-token insertion as a viable recovery strategy for a mismatched
* input error.</p>
*
* <p>The default implementation simply returns if the handler is already in
* error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to
* enter error recovery mode, followed by calling
* {@link org.antlr.v4.runtime.Parser#notifyErrorListeners}.</p>
*
* @param recognizer the parser instance
*/
internal func reportMissingToken(_ recognizer: Parser) throws {
if inErrorRecoveryMode(recognizer) {
return
}
beginErrorCondition(recognizer)
let t: Token = try recognizer.getCurrentToken()
let expecting: IntervalSet = try getExpectedTokens(recognizer)
let msg: String = "missing " + expecting.toString(recognizer.getVocabulary()) +
" at " + getTokenErrorDisplay(t)
recognizer.notifyErrorListeners(t, msg, nil)
}
/**
* {@inheritDoc}
*
* <p>The default implementation attempts to recover from the mismatched input
* by using single token insertion and deletion as described below. If the
* recovery attempt fails, this method throws an
* {@link org.antlr.v4.runtime.InputMismatchException}.</p>
*
* <p><strong>EXTRA TOKEN</strong> (single token deletion)</p>
*
* <p>{@code LA(1)} is not what we are looking for. If {@code LA(2)} has the
* right token, however, then assume {@code LA(1)} is some extra spurious
* token and delete it. Then consume and return the next token (which was
* the {@code LA(2)} token) as the successful result of the match operation.</p>
*
* <p>This recovery strategy is implemented by {@link #singleTokenDeletion}.</p>
*
* <p><strong>MISSING TOKEN</strong> (single token insertion)</p>
*
* <p>If current token (at {@code LA(1)}) is consistent with what could come
* after the expected {@code LA(1)} token, then assume the token is missing
* and use the parser's {@link org.antlr.v4.runtime.TokenFactory} to create it on the fly. The
* "insertion" is performed by returning the created token as the successful
* result of the match operation.</p>
*
* <p>This recovery strategy is implemented by {@link #singleTokenInsertion}.</p>
*
* <p><strong>EXAMPLE</strong></p>
*
* <p>For example, Input {@code i=(3;} is clearly missing the {@code ')'}. When
* the parser returns from the nested call to {@code expr}, it will have
* call chain:</p>
*
* <pre>
* stat → expr → atom
* </pre>
*
* and it will be trying to match the {@code ')'} at this point in the
* derivation:
*
* <pre>
* => ID '=' '(' INT ')' ('+' atom)* ';'
* ^
* </pre>
*
* The attempt to match {@code ')'} will fail when it sees {@code ';'} and
* call {@link #recoverInline}. To recover, it sees that {@code LA(1)==';'}
* is in the set of tokens that can follow the {@code ')'} token reference
* in rule {@code atom}. It can assume that you forgot the {@code ')'}.
*/
public func recoverInline(_ recognizer: Parser) throws -> Token {
// SINGLE TOKEN DELETION
let matchedSymbol: Token? = try singleTokenDeletion(recognizer)
if matchedSymbol != nil {
// we have deleted the extra token.
// now, move past ttype token as if all were ok
try recognizer.consume()
return matchedSymbol!
}
// SINGLE TOKEN INSERTION
if try singleTokenInsertion(recognizer) {
return try getMissingSymbol(recognizer)
}
throw try ANTLRException.recognition(e: InputMismatchException(recognizer))
// throw try ANTLRException.InputMismatch(e: InputMismatchException(recognizer) )
//RuntimeException("InputMismatchException")
// even that didn't work; must throw the exception
//throwException() /* throw InputMismatchException(recognizer); */
}
/**
* This method implements the single-token insertion inline error recovery
* strategy. It is called by {@link #recoverInline} if the single-token
* deletion strategy fails to recover from the mismatched input. If this
* method returns {@code true}, {@code recognizer} will be in error recovery
* mode.
*
* <p>This method determines whether or not single-token insertion is viable by
* checking if the {@code LA(1)} input symbol could be successfully matched
* if it were instead the {@code LA(2)} symbol. If this method returns
* {@code true}, the caller is responsible for creating and inserting a
* token with the correct type to produce this behavior.</p>
*
* @param recognizer the parser instance
* @return {@code true} if single-token insertion is a viable recovery
* strategy for the current mismatched input, otherwise {@code false}
*/
internal func singleTokenInsertion(_ recognizer: Parser) throws -> Bool {
let currentSymbolType: Int = try getTokenStream(recognizer).LA(1)
// if current token is consistent with what could come after current
// ATN state, then we know we're missing a token; error recovery
// is free to conjure up and insert the missing token
let currentState: ATNState = recognizer.getInterpreter().atn.states[recognizer.getState()]!
let next: ATNState = currentState.transition(0).target
let atn: ATN = recognizer.getInterpreter().atn
let expectingAtLL2: IntervalSet = try atn.nextTokens(next, recognizer._ctx)
// print("LT(2) set="+expectingAtLL2.toString(recognizer.getTokenNames()));
if expectingAtLL2.contains(currentSymbolType) {
try reportMissingToken(recognizer)
return true
}
return false
}
/**
* This method implements the single-token deletion inline error recovery
* strategy. It is called by {@link #recoverInline} to attempt to recover
* from mismatched input. If this method returns null, the parser and error
* handler state will not have changed. If this method returns non-null,
* {@code recognizer} will <em>not</em> be in error recovery mode since the
* returned token was a successful match.
*
* <p>If the single-token deletion is successful, this method calls
* {@link #reportUnwantedToken} to report the error, followed by
* {@link org.antlr.v4.runtime.Parser#consume} to actually "delete" the extraneous token. Then,
* before returning {@link #reportMatch} is called to signal a successful
* match.</p>
*
* @param recognizer the parser instance
* @return the successfully matched {@link org.antlr.v4.runtime.Token} instance if single-token
* deletion successfully recovers from the mismatched input, otherwise
* {@code null}
*/
internal func singleTokenDeletion(_ recognizer: Parser) throws -> Token? {
let nextTokenType: Int = try getTokenStream(recognizer).LA(2)
let expecting: IntervalSet = try getExpectedTokens(recognizer)
if expecting.contains(nextTokenType) {
try reportUnwantedToken(recognizer)
/*
errPrint("recoverFromMismatchedToken deleting "+
((TokenStream)getTokenStream(recognizer)).LT(1)+
" since "+((TokenStream)getTokenStream(recognizer)).LT(2)+
" is what we want");
*/
try recognizer.consume() // simply delete extra token
// we want to return the token we're actually matching
let matchedSymbol: Token = try recognizer.getCurrentToken()
reportMatch(recognizer) // we know current token is correct
return matchedSymbol
}
return nil
}
/** Conjure up a missing token during error recovery.
*
* The recognizer attempts to recover from single missing
* symbols. But, actions might refer to that missing symbol.
* For example, x=ID {f($x);}. The action clearly assumes
* that there has been an identifier matched previously and that
* $x points at that token. If that token is missing, but
* the next token in the stream is what we want we assume that
* this token is missing and we keep going. Because we
* have to return some token to replace the missing token,
* we have to conjure one up. This method gives the user control
* over the tokens returned for missing tokens. Mostly,
* you will want to create something special for identifier
* tokens. For literals such as '{' and ',', the default
* action in the parser or tree parser works. It simply creates
* a CommonToken of the appropriate type. The text will be the token.
* If you change what tokens must be created by the lexer,
* override this method to create the appropriate tokens.
*/
internal func getTokenStream(_ recognizer: Parser) -> TokenStream {
return recognizer.getInputStream() as! TokenStream
}
internal func getMissingSymbol(_ recognizer: Parser) throws -> Token {
let currentSymbol: Token = try recognizer.getCurrentToken()
let expecting: IntervalSet = try getExpectedTokens(recognizer)
let expectedTokenType: Int = expecting.getMinElement() // get any element
var tokenText: String
if expectedTokenType == CommonToken.EOF {
tokenText = "<missing EOF>"
} else {
tokenText = "<missing " + recognizer.getVocabulary().getDisplayName(expectedTokenType) + ">"
}
var current: Token = currentSymbol
let lookback: Token? = try getTokenStream(recognizer).LT(-1)
if current.getType() == CommonToken.EOF && lookback != nil {
current = lookback!
}
let token = recognizer.getTokenFactory().create((current.getTokenSource(), current.getTokenSource()!.getInputStream()), expectedTokenType, tokenText,
CommonToken.DEFAULT_CHANNEL,
-1, -1,
current.getLine(), current.getCharPositionInLine())
return token
}
internal func getExpectedTokens(_ recognizer: Parser) throws -> IntervalSet {
return try recognizer.getExpectedTokens()
}
/** How should a token be displayed in an error message? The default
* is to display just the text, but during development you might
* want to have a lot of information spit out. Override in that case
* to use t.toString() (which, for CommonToken, dumps everything about
* the token). This is better than forcing you to override a method in
* your token objects because you don't have to go modify your lexer
* so that it creates a new Java type.
*/
internal func getTokenErrorDisplay(_ t: Token?) -> String {
if t == nil {
return "<no token>"
}
var s: String? = getSymbolText(t!)
if s == nil {
if getSymbolType(t!) == CommonToken.EOF {
s = "<EOF>"
} else {
s = "<\(getSymbolType(t!))>"
}
}
return escapeWSAndQuote(s!)
}
internal func getSymbolText(_ symbol: Token) -> String {
return symbol.getText()!
}
internal func getSymbolType(_ symbol: Token) -> Int {
return symbol.getType()
}
internal func escapeWSAndQuote(_ s: String) -> String {
var s = s
s = s.replaceAll("\n", replacement: "\\n")
s = s.replaceAll("\r", replacement: "\\r")
s = s.replaceAll("\t", replacement: "\\t")
return "'" + s + "'"
}
/* Compute the error recovery set for the current rule. During
* rule invocation, the parser pushes the set of tokens that can
* follow that rule reference on the stack; this amounts to
* computing FIRST of what follows the rule reference in the
* enclosing rule. See LinearApproximator.FIRST().
* This local follow set only includes tokens
* from within the rule; i.e., the FIRST computation done by
* ANTLR stops at the end of a rule.
*
* EXAMPLE
*
* When you find a "no viable alt exception", the input is not
* consistent with any of the alternatives for rule r. The best
* thing to do is to consume tokens until you see something that
* can legally follow a call to r *or* any rule that called r.
* You don't want the exact set of viable next tokens because the
* input might just be missing a token--you might consume the
* rest of the input looking for one of the missing tokens.
*
* Consider grammar:
*
* a : '[' b ']'
* | '(' b ')'
* ;
* b : c '^' INT ;
* c : ID
* | INT
* ;
*
* At each rule invocation, the set of tokens that could follow
* that rule is pushed on a stack. Here are the various
* context-sensitive follow sets:
*
* FOLLOW(b1_in_a) = FIRST(']') = ']'
* FOLLOW(b2_in_a) = FIRST(')') = ')'
* FOLLOW(c_in_b) = FIRST('^') = '^'
*
* Upon erroneous input "[]", the call chain is
*
* a -> b -> c
*
* and, hence, the follow context stack is:
*
* depth follow set start of rule execution
* 0 <EOF> a (from main())
* 1 ']' b
* 2 '^' c
*
* Notice that ')' is not included, because b would have to have
* been called from a different context in rule a for ')' to be
* included.
*
* For error recovery, we cannot consider FOLLOW(c)
* (context-sensitive or otherwise). We need the combined set of
* all context-sensitive FOLLOW sets--the set of all tokens that
* could follow any reference in the call chain. We need to
* resync to one of those tokens. Note that FOLLOW(c)='^' and if
* we resync'd to that token, we'd consume until EOF. We need to
* sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}.
* In this case, for input "[]", LA(1) is ']' and in the set, so we would
* not consume anything. After printing an error, rule c would
* return normally. Rule b would not find the required '^' though.
* At this point, it gets a mismatched token error and throws an
* exception (since LA(1) is not in the viable following token
* set). The rule exception handler tries to recover, but finds
* the same recovery set and doesn't consume anything. Rule b
* exits normally returning to rule a. Now it finds the ']' (and
* with the successful match exits errorRecovery mode).
*
* So, you can see that the parser walks up the call chain looking
* for the token that was a member of the recovery set.
*
* Errors are not generated in errorRecovery mode.
*
* ANTLR's error recovery mechanism is based upon original ideas:
*
* "Algorithms + Data Structures = Programs" by Niklaus Wirth
*
* and
*
* "A note on error recovery in recursive descent parsers":
* http://portal.acm.org/citation.cfm?id=947902.947905
*
* Later, Josef Grosch had some good ideas:
*
* "Efficient and Comfortable Error Recovery in Recursive Descent
* Parsers":
* ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip
*
* Like Grosch I implement context-sensitive FOLLOW sets that are combined
* at run-time upon error to avoid overhead during parsing.
*/
internal func getErrorRecoverySet(_ recognizer: Parser) throws -> IntervalSet {
let atn: ATN = recognizer.getInterpreter().atn
var ctx: RuleContext? = recognizer._ctx
let recoverSet: IntervalSet = try IntervalSet()
while let ctxWrap = ctx , ctxWrap.invokingState >= 0 {
// compute what follows who invoked us
let invokingState: ATNState = atn.states[ctxWrap.invokingState]!
let rt: RuleTransition = invokingState.transition(0) as! RuleTransition
let follow: IntervalSet = try atn.nextTokens(rt.followState)
try recoverSet.addAll(follow)
ctx = ctxWrap.parent
}
try recoverSet.remove(CommonToken.EPSILON)
// print("recover set "+recoverSet.toString(recognizer.getTokenNames()));
return recoverSet
}
/** Consume tokens until one matches the given token set. */
internal func consumeUntil(_ recognizer: Parser, _ set: IntervalSet) throws {
// errPrint("consumeUntil("+set.toString(recognizer.getTokenNames())+")");
var ttype: Int = try getTokenStream(recognizer).LA(1)
while ttype != CommonToken.EOF && !set.contains(ttype) {
//print("consume during recover LA(1)="+getTokenNames()[input.LA(1)]);
// getTokenStream(recognizer).consume();
try recognizer.consume()
ttype = try getTokenStream(recognizer).LA(1)
}
}
}
|
bsd-3-clause
|
f782d405b9df246c21245fcd523ff777
| 41.431635 | 157 | 0.630916 | 4.427133 | false | false | false | false |
DrGo/LearningSwift
|
PLAYGROUNDS/LSB_D009_DeMorgansLaw.playground/section-2.swift
|
2
|
2702
|
import UIKit
/*
// DeMorgan's Law
//
// Based on: Brandon Williams' "Proof in Functions"
// http://www.fewbutripe.com/swift/math/2015/01/06/proof-in-functions.html
//
// For any propositions P and Q, the following holds true:
// ¬(P∨Q)⇔¬P∧¬Q
//
// "You can think of this as ¬ distributing over ∨
// but at the cost of switching ∨ to ∧."
//
/============================================================*/
/*------------------------------------------------------/
// Negation: ¬
/------------------------------------------------------*/
enum Nothing {
// no cases
}
struct Not <A> {
let not: A -> Nothing
}
/*------------------------------------------------------/
// Box, by Rob Rix
// https://github.com/robrix/Box
//
// The blog post uses the @autoclosure, but that seems
// to be out of fashion since Swift 1.2:
// http://mazur.me/SwiftInFlux/docs/6.3-beta1.pdf
/------------------------------------------------------*/
public protocol BoxType {
/// The type of the wrapped value.
typealias Value
/// Initializes an intance of the type with a value.
init(_ value: Value)
/// The wrapped value.
var value: Value { get }
}
class Box<T>: BoxType, Printable {
/// Initializes a `Box` with the given value.
required init(_ value: T) {
self.value = value
}
/// The (immutable) value wrapped by the receiver.
let value: T
/// Constructs a new Box by transforming `value` by `f`.
func map<U>(f: T -> U) -> Box<U> {
return Box<U>(f(value))
}
// MARK: Printable
var description: String {
return toString(value)
}
}
/*------------------------------------------------------/
// Or: ∨
/------------------------------------------------------*/
enum Or <A, B> {
case left(Box<A>)
case right(Box<B>)
}
struct And <A, B> {
let left: A
let right: B
init (_ left: A, _ right: B) {
self.left = left
self.right = right
}
}
/*------------------------------------------------------/
// ¬(P∨Q) ⇔ ¬P∧¬Q
/------------------------------------------------------*/
func deMorgan <A, B> (f: Not<Or<A, B>>) -> And<Not<A>, Not<B>> {
return And<Not<A>, Not<B>>(
Not<A> {a in f.not(.left(Box(a)))},
Not<B> {b in f.not(.right(Box(b)))}
)
}
/*------------------------------------------------------/
// And, the converse...
// ¬P∧¬Q ⇔ ¬(P∨Q)
/------------------------------------------------------*/
func deMorgan <A, B> (f: And<Not<A>, Not<B>>) -> Not<Or<A, B>> {
return Not<Or<A, B>> {(x: Or<A, B>) in
switch x {
case let .left(a):
return f.left.not(a.value)
case let .right(b):
return f.right.not(b.value)
}
}
}
|
gpl-3.0
|
a4456dd88c8abb51ea3100c5755d0353
| 21.016529 | 75 | 0.433771 | 3.28202 | false | false | false | false |
FromF/OlympusCameraKit
|
HDRRecCameraSwift/RecCameraSwift/ViewController.swift
|
1
|
1615
|
//
// ViewController.swift
// RecCameraSwift
//
// Created by haruhito on 2015/04/12.
// Copyright (c) 2015年 FromF. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var connectButton: UIButton!
//AppDelegate instance
var appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Rechability Notification Regist
NSNotificationCenter.defaultCenter().addObserver(self, selector: "NotificationNetowork:", name: appDelegate.NotificationNetworkConnected as String, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "NotificationNetowork:", name: appDelegate.NotificationNetworkDisconnected as String, object: nil)
//ConnectButton Update
connectButtonEnable()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func connectButtonEnable() {
let status : Int = appDelegate.reachabilityForLocalWiFi.currentReachabilityStatus().value
if (status == ReachableViaWiFi.value) {
connectButton.enabled = true
} else {
connectButton.enabled = false
}
}
// MARK: - Notification
func NotificationNetowork(notification : NSNotification?) {
//ConnectButton Update
connectButtonEnable()
}
}
|
mit
|
d1e92e20293e626e51ac4cd7f65d7dd1
| 31.26 | 171 | 0.681339 | 5.358804 | false | false | false | false |
kstaring/swift
|
validation-test/compiler_crashers_fixed/00064-bool.swift
|
11
|
672
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
func q(v: h) -> <r>(() -> r) -> h {
n { u o "\(v): \(u())" }
}
struct e<r> {
j p: , () -> ())] = []
}
protocol p {
}
protocol m : p {
}
protocol v : p {
}
protocol m {
v = m
}
func s<s : m, v : m u v.v == s> (m: v) {
}
func s<v : m u v.v == v> (m: v) {
}
s( {
({})
}
t
|
apache-2.0
|
ffbfe189b8b6c5b5dee3507724edc013
| 20.677419 | 78 | 0.580357 | 2.811715 | false | false | false | false |
zskyfly/yelp
|
Yelp/FiltersViewController.swift
|
1
|
4376
|
//
// FiltersViewController.swift
// Yelp
//
// Created by Zachary Matthews on 2/18/16.
// Copyright © 2016 Timothy Lee. All rights reserved.
//
import UIKit
protocol FiltersViewControllerDelegate {
func filtersViewController(filtersViewController: FiltersViewController, didUpdateFilters filters: [SearchFilter])
}
class FiltersViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var searchFilters: [SearchFilter]!
var delegate: FiltersViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.allowsSelection = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onCancelButton(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func onSearchButton(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
delegate?.filtersViewController(self, didUpdateFilters: self.searchFilters)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension FiltersViewController: UITableViewDataSource {
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let searchFilter = self.searchFilters[section]
return searchFilter.sectionName
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let searchFilter = self.searchFilters[section]
switch searchFilter.cellIdentifier {
case "SwitchCell":
return searchFilter.values.count
case "SegmentedCell":
return 1
default:
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell
let section = indexPath.section
let index = indexPath.row
let searchFilter = self.searchFilters[section]
let searchFilterValues = searchFilter.values
let selectedIndex = searchFilter.selectedIndex
let searchFilterValue = searchFilterValues[index]
let searchFilterState = searchFilter.states[index]
switch searchFilter.cellIdentifier {
case "SwitchCell":
let switchCell = tableView.dequeueReusableCellWithIdentifier("SwitchCell", forIndexPath: indexPath) as! SwitchCell
switchCell.delegate = self
switchCell.filterState = searchFilterState
switchCell.filterValue = searchFilterValue
cell = switchCell
break
case "SegmentedCell":
let segmentedCell = tableView.dequeueReusableCellWithIdentifier("SegmentedCell", forIndexPath: indexPath) as! SegmentedCell
segmentedCell.delegate = self
segmentedCell.selectedIndex = selectedIndex
segmentedCell.segmentNames = searchFilterValues
cell = segmentedCell
break
default:
cell = UITableViewCell()
}
return cell
}
}
extension FiltersViewController: UITableViewDelegate {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.searchFilters.count
}
}
extension FiltersViewController: SwitchCellDelegate {
func switchCell(switchCell: SwitchCell, didChangeValue value: Bool) {
let indexPath = tableView.indexPathForCell(switchCell)!
let section = indexPath.section
let row = indexPath.row
self.searchFilters[section].states[row] = value
}
}
extension FiltersViewController: SegmentedCellDelegate {
func segmentedCell(segmentedCell: SegmentedCell, didChangeValue value: Int) {
let indexPath = tableView.indexPathForCell(segmentedCell)!
let section = indexPath.section
self.searchFilters[section].selectedIndex = value
}
}
|
apache-2.0
|
06968f06afc1ee998390c81cc2efc3da
| 29.809859 | 135 | 0.693257 | 5.580357 | false | false | false | false |
russbishop/swift
|
stdlib/public/SDK/Foundation/URLRequest.swift
|
1
|
10408
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
@available(*, deprecated, message: "Please use the struct type URLRequest")
public typealias MutableURLRequest = NSMutableURLRequest
public struct URLRequest : ReferenceConvertible, CustomStringConvertible, Equatable, Hashable {
public typealias ReferenceType = NSURLRequest
public typealias CachePolicy = NSURLRequest.CachePolicy
public typealias NetworkServiceType = NSURLRequest.NetworkServiceType
/*
NSURLRequest has a fragile ivar layout that prevents the swift subclass approach here, so instead we keep an always mutable copy
*/
internal var _handle: _MutableHandle<NSMutableURLRequest>
internal mutating func _applyMutation<ReturnType>(_ whatToDo : @noescape (NSMutableURLRequest) -> ReturnType) -> ReturnType {
if !isUniquelyReferencedNonObjC(&_handle) {
let ref = _handle._uncopiedReference()
_handle = _MutableHandle(reference: ref)
}
return whatToDo(_handle._uncopiedReference())
}
/// Creates and initializes a URLRequest with the given URL and cache policy.
/// - parameter: url The URL for the request.
/// - parameter: cachePolicy The cache policy for the request. Defaults to `.useProtocolCachePolicy`
/// - parameter: timeoutInterval The timeout interval for the request. See the commentary for the `timeoutInterval` for more information on timeout intervals. Defaults to 60.0
public init(url: URL, cachePolicy: CachePolicy = .useProtocolCachePolicy, timeoutInterval: TimeInterval = 60.0) {
_handle = _MutableHandle(adoptingReference: NSMutableURLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval))
}
private init(_bridged request: NSURLRequest) {
_handle = _MutableHandle(reference: request.mutableCopy() as! NSMutableURLRequest)
}
/// The URL of the receiver.
public var url: URL? {
get {
return _handle.map { $0.url }
}
set {
_applyMutation { $0.url = newValue }
}
}
/// The cache policy of the receiver.
public var cachePolicy: CachePolicy {
get {
return _handle.map { $0.cachePolicy }
}
set {
_applyMutation { $0.cachePolicy = newValue }
}
}
/// Returns the timeout interval of the receiver.
/// - discussion: The timeout interval specifies the limit on the idle
/// interval allotted to a request in the process of loading. The "idle
/// interval" is defined as the period of time that has passed since the
/// last instance of load activity occurred for a request that is in the
/// process of loading. Hence, when an instance of load activity occurs
/// (e.g. bytes are received from the network for a request), the idle
/// interval for a request is reset to 0. If the idle interval ever
/// becomes greater than or equal to the timeout interval, the request
/// is considered to have timed out. This timeout interval is measured
/// in seconds.
public var timeoutInterval: TimeInterval {
get {
return _handle.map { $0.timeoutInterval }
}
set {
_applyMutation { $0.timeoutInterval = newValue }
}
}
/// The main document URL associated with this load.
/// - discussion: This URL is used for the cookie "same domain as main
/// document" policy.
public var mainDocumentURL: URL? {
get {
return _handle.map { $0.mainDocumentURL }
}
set {
_applyMutation { $0.mainDocumentURL = newValue }
}
}
/// The URLRequest.NetworkServiceType associated with this request.
/// - discussion: This will return URLRequest.NetworkServiceType.default for requests that have
/// not explicitly set a networkServiceType
@available(OSX 10.7, iOS 4.0, *)
public var networkServiceType: NetworkServiceType {
get {
return _handle.map { $0.networkServiceType }
}
set {
_applyMutation { $0.networkServiceType = newValue }
}
}
/// `true` if the receiver is allowed to use the built in cellular radios to
/// satisfy the request, `false` otherwise.
@available(OSX 10.8, iOS 6.0, *)
public var allowsCellularAccess: Bool {
get {
return _handle.map { $0.allowsCellularAccess }
}
set {
_applyMutation { $0.allowsCellularAccess = newValue }
}
}
/// The HTTP request method of the receiver.
public var httpMethod: String? {
get {
return _handle.map { $0.httpMethod }
}
set {
_applyMutation {
if let value = newValue {
$0.httpMethod = value
} else {
$0.httpMethod = "GET"
}
}
}
}
/// A dictionary containing all the HTTP header fields of the
/// receiver.
public var allHTTPHeaderFields: [String : String]? {
get {
return _handle.map { $0.allHTTPHeaderFields }
}
set {
_applyMutation { $0.allHTTPHeaderFields = newValue }
}
}
/// The value which corresponds to the given header
/// field. Note that, in keeping with the HTTP RFC, HTTP header field
/// names are case-insensitive.
/// - parameter: field the header field name to use for the lookup (case-insensitive).
public func value(forHTTPHeaderField field: String) -> String? {
return _handle.map { $0.value(forHTTPHeaderField: field) }
}
/// If a value was previously set for the given header
/// field, that value is replaced with the given value. Note that, in
/// keeping with the HTTP RFC, HTTP header field names are
/// case-insensitive.
public mutating func setValue(_ value: String?, forHTTPHeaderField field: String) {
_applyMutation {
$0.setValue(value, forHTTPHeaderField: field)
}
}
/// This method provides a way to add values to header
/// fields incrementally. If a value was previously set for the given
/// header field, the given value is appended to the previously-existing
/// value. The appropriate field delimiter, a comma in the case of HTTP,
/// is added by the implementation, and should not be added to the given
/// value by the caller. Note that, in keeping with the HTTP RFC, HTTP
/// header field names are case-insensitive.
public mutating func addValue(_ value: String, forHTTPHeaderField field: String) {
_applyMutation {
$0.addValue(value, forHTTPHeaderField: field)
}
}
/// This data is sent as the message body of the request, as
/// in done in an HTTP POST request.
public var httpBody: Data? {
get {
return _handle.map { $0.httpBody }
}
set {
_applyMutation { $0.httpBody = newValue }
}
}
/// The stream is returned for examination only; it is
/// not safe for the caller to manipulate the stream in any way. Also
/// note that the HTTPBodyStream and HTTPBody are mutually exclusive - only
/// one can be set on a given request. Also note that the body stream is
/// preserved across copies, but is LOST when the request is coded via the
/// NSCoding protocol
public var httpBodyStream: InputStream? {
get {
return _handle.map { $0.httpBodyStream }
}
set {
_applyMutation { $0.httpBodyStream = newValue }
}
}
/// `true` if cookies will be sent with and set for this request; otherwise `false`.
public var httpShouldHandleCookies: Bool {
get {
return _handle.map { $0.httpShouldHandleCookies }
}
set {
_applyMutation { $0.httpShouldHandleCookies = newValue }
}
}
/// `true` if the receiver should transmit before the previous response
/// is received. `false` if the receiver should wait for the previous response
/// before transmitting.
@available(OSX 10.7, iOS 4.0, *)
public var httpShouldUsePipelining: Bool {
get {
return _handle.map { $0.httpShouldUsePipelining }
}
set {
_applyMutation { $0.httpShouldUsePipelining = newValue }
}
}
public var hashValue: Int {
return _handle.map { $0.hashValue }
}
public var description: String {
return _handle.map { $0.description }
}
public var debugDescription: String {
return _handle.map { $0.debugDescription }
}
}
public func ==(lhs: URLRequest, rhs: URLRequest) -> Bool {
return lhs._handle._uncopiedReference().isEqual(rhs._handle._uncopiedReference())
}
extension URLRequest : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public static func _getObjectiveCType() -> Any.Type {
return NSURLRequest.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSURLRequest {
return _handle._copiedReference()
}
public static func _forceBridgeFromObjectiveC(_ input: NSURLRequest, result: inout URLRequest?) {
result = URLRequest(_bridged: input)
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSURLRequest, result: inout URLRequest?) -> Bool {
result = URLRequest(_bridged: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURLRequest?) -> URLRequest {
var result: URLRequest? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
|
apache-2.0
|
616c6ca5e55934a33d23c3efdd4119e1
| 36.574007 | 179 | 0.622886 | 5.062257 | false | false | false | false |
PlanTeam/BSON
|
Sources/BSON/Codable/Codable.swift
|
1
|
508
|
internal struct BSONKey: CodingKey {
var stringValue: String
var intValue: Int?
init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
init?(intValue: Int) {
self.stringValue = String(intValue)
self.intValue = intValue
}
init(stringValue: String, intValue: Int?) {
self.stringValue = stringValue
self.intValue = intValue
}
static let `super` = BSONKey(stringValue: "super")!
}
|
mit
|
b74b035fd60d6bf2ea3ef3cb19927eb6
| 23.190476 | 55 | 0.600394 | 4.66055 | false | false | false | false |
1170197998/SinaWeibo
|
SFWeiBo/SFWeiBo/Classes/Main/MainViewController.swift
|
1
|
6206
|
//
// MainViewController.swift
// SFWeiBo
//
// Created by mac on 16/3/22.
// Copyright © 2016年 ShaoFeng. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
//添加所有子控制器
addChildViewControllers()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//从iOS7开始就不推荐在viewDidload中设置控件frame
//添加 加号 按钮
setupComposeButton()
}
// MARK: - 中间按钮的监听事件
// 监听按钮点击的方法不能是私有方法(不能加private),因为是有运行循环触发的
func composeButtonClick() {
let vc = ComposeViewController()
let nav = UINavigationController(rootViewController: vc)
presentViewController(nav, animated: true, completion: nil)
}
// MARK: - 添加 加号 按钮
private func setupComposeButton() {
//添加 加号 按钮
tabBar.addSubview(composeButton)
//调整 加号 按钮的位置
let width = UIScreen.mainScreen().bounds.size.width / CGFloat((viewControllers?.count)!)
let rect = CGRect(x: 0, y: 0, width: width, height: 49)
//第一个参数:frame的大小
//第二个参数:x方向偏移的大小
//第三个参数:y方向偏移的大小
composeButton.frame = CGRectOffset(rect, 2 * width, 0)
}
// MARK: - 添加所有子控制器
private func addChildViewControllers() {
//1.获取json数据
let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil)
//2.通过文件路径创建NSData
if let jsonPath = path {
let jsonData = NSData(contentsOfFile: jsonPath)
do {
//这里面放置有可能发生异常的代码
//3.序列化json数据 --> Array
//try :发生异常会调到 catch 中继续执行
//try! : 发生异常直接崩溃
let dictArray = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers)
//print(dictArray)
//4.遍历数组,动态创建控制器和设置数据
//在Swift中,如果需要遍历一个数组,必须明确数据的类型
for dict in dictArray as! [[String:String]] {
//addChildViewController下面的这个方法要求必须有参数,,但是字典的返回值是可选类型
addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!)
}
//如果服务器返回来数据,就从服务器加载数据(执行do里面的代码)加载控制器
//如果服务器没有返回数据(异常情况,就本地代码加载控制器,执行catch里面的代码)
} catch {
//发生异常会执行的代码
print(error)
//添加子控制器(从本地加载创建控制器)
addChildViewController("HomeTableViewController", title: "首页", imageName: "tabbar_home")
addChildViewController("MessageTableViewController", title: "消息", imageName: "tabbar_message_center")
addChildViewController("NullViewController", title: "", imageName: "")
addChildViewController("DiscoverTableViewController", title: "广场", imageName: "tabbar_discover")
addChildViewController("ProfileTableViewController", title: "我", imageName: "tabbar_profile")
}
}
}
// MARK: - 初始化子控制器(控制器名字,标题,图片) <传控制器的名字代替传控制器>
// private func addChildViewController(childController: UIViewController, title:String, imageName:String) {
private func addChildViewController(childControllerName: String, title:String, imageName:String) {
//0.动态获取命名空间(CFBundleExecutable这个键对应的值就是项目名称,也就是命名空间)
let nameSpace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
//1.将字符串转化为类
//默认情况下,命名空间就是项目名称,但是命名空间是可以修改的
let cls:AnyClass? = NSClassFromString(nameSpace + "." + childControllerName) //SFWeiBo.是命名空间
//2.通过类创建对象
//2.1将anyClass转换为指定的类型
let viewControllerCls = cls as! UIViewController.Type
//2.2通过class创建对象
let vc = viewControllerCls.init()
//1设置tabbar对应的按钮数据
vc.tabBarItem.image = UIImage(named: imageName)
vc.tabBarItem.selectedImage = UIImage(named: imageName + "highlighted")
vc.title = title
//2.给首页包装导航条
let nav = UINavigationController()
nav.addChildViewController(vc)
//3.将导航控制器添加到当前控制器
addChildViewController(nav)
}
// MARK: - 懒加载控件
private lazy var composeButton:UIButton = {
let button = UIButton()
//设置前景图片
button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
//设置前景图片
button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState:UIControlState.Normal)
button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
//添加监听事件
button.addTarget(self, action: #selector(MainViewController.composeButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
}
|
apache-2.0
|
67ed3eacfc52042cd59d316f99589f08
| 36.258993 | 137 | 0.608612 | 4.708182 | false | false | false | false |
OUCHUNYU/MockCoreMotion
|
MockCoreMotion/MockCMMagnetometerData.swift
|
1
|
1456
|
//
// MockCMMagnetometerData.swift
// MockCoreMotion
//
// Created by Chunyu Ou on 3/11/17.
// Copyright © 2017 Chunyu Ou. All rights reserved.
//
import Foundation
import CoreMotion
open class MockCMMagnetometerData: CMMagnetometerData {
private var _magneticField: CMMagneticField?
private var _timestamp: TimeInterval = Date().timeIntervalSinceReferenceDate
open override var magneticField: CMMagneticField {
get {
return _magneticField ?? super.magneticField
}
set {
_magneticField = newValue
}
}
open override var timestamp: TimeInterval {
get {
return _timestamp
}
set {
_timestamp = newValue
}
}
public init(magneticField: CMMagneticField) {
_magneticField = magneticField
super.init()
}
public required init?(coder: NSCoder) {
if coder.containsValue(forKey: MockCMMagnetometerData.magneticFieldKey),
let magneticFieldValue = coder.decodeObject(forKey: MockCMMagnetometerData.magneticFieldKey) as? CMMagneticField {
_magneticField = magneticFieldValue
}
super.init(coder: coder)
}
private static let magneticFieldKey = "_magneticField"
open override func encode(with coder: NSCoder) {
coder.encode(magneticField, forKey: MockCMMagnetometerData.magneticFieldKey)
}
}
|
mit
|
b9d7a43872f6ced04c25bc531a6b30f4
| 25.944444 | 126 | 0.642612 | 4.833887 | false | false | false | false |
malaonline/iOS
|
mala-ios/View/CourseChoosingView/CourseChoosingClassScheduleCell.swift
|
1
|
4508
|
//
// CourseChoosingClassScheduleCell.swift
// mala-ios
//
// Created by 王新宇 on 1/22/16.
// Copyright © 2016 Mala Online. All rights reserved.
//
import UIKit
class CourseChoosingClassScheduleCell: MalaBaseCell {
// MARK: - Property
/// 课程表数据模型
var classScheduleModel: [[ClassScheduleDayModel]] = [] {
didSet {
self.classSchedule.model = classScheduleModel
}
}
// MARK: - Components
private lazy var classSchedule: ThemeClassSchedule = {
let frame = CGRect(x: 0, y: 0, width: MalaLayout_CardCellWidth, height: MalaLayout_CardCellWidth*0.65)
let classSchedule = ThemeClassSchedule(frame: frame, collectionViewLayout: ThemeClassScheduleFlowLayout(frame: frame))
classSchedule.bounces = false
classSchedule.isScrollEnabled = false
return classSchedule
}()
private lazy var legendView: LegendView = {
let legendView = LegendView()
return legendView
}()
// MARK: - Contructed
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUserInterface()
setupLegends()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Method
private func setupUserInterface() {
// Style
adjustForCourseChoosing()
// SubViews
content.addSubview(classSchedule)
content.addSubview(legendView)
// Autolayout
content.snp.updateConstraints { (maker) -> Void in
maker.top.equalTo(headerView.snp.bottom).offset(14)
}
classSchedule.snp.makeConstraints { (maker) -> Void in
maker.top.equalTo(content)
maker.left.equalTo(content)
maker.right.equalTo(content)
maker.height.equalTo(classSchedule.snp.width).multipliedBy(0.65)
}
legendView.snp.makeConstraints { (maker) -> Void in
maker.top.equalTo(classSchedule.snp.bottom).offset(14)
maker.left.equalTo(content)
maker.height.equalTo(15)
maker.right.equalTo(content)
maker.bottom.equalTo(content)
}
}
private func setupLegends() {
legendView.addLegend(image: .legendActive, title: "可选")
legendView.addLegend(image: .legendDisabled, title: "已售")
legendView.addLegend(image: .legendSelected, title: "已选")
let buttonBought = legendView.addLegend(image: .legendBought, title: "已买")
let ButtonDesc = legendView.addLegend(image: .descIcon, offset: 3)
buttonBought.addTarget(self, action: #selector(CourseChoosingClassScheduleCell.showBoughtDescription), for: .touchUpInside)
ButtonDesc.addTarget(self, action: #selector(CourseChoosingClassScheduleCell.showBoughtDescription), for: .touchUpInside)
}
// MARK: - Events Response
@objc private func showBoughtDescription() {
CouponRulesPopupWindow(title: "已买课程", desc: MalaConfig.boughtDescriptionString()).show()
}
}
// MARK: - LegendView
class LegendView: UIView {
// MARK: - Property
private var currentX: CGFloat = 3
// MARK: - Constructed
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@discardableResult
func addLegend(image imageName: ImageAsset, title: String? = nil, offset: CGFloat? = 12) -> UIButton {
let button = UIButton()
button.adjustsImageWhenHighlighted = false
button.setImage(UIImage(asset: imageName), for: UIControlState())
if title != nil {
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -3, bottom: 0, right: 3)
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 3, bottom: 0, right: -3)
}
button.setTitle(title, for: UIControlState())
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.setTitleColor(UIColor(named: .HeaderTitle), for: UIControlState())
button.sizeToFit()
button.frame.origin.x = (currentX == 3 ? currentX : currentX+(offset ?? 12)+3)
addSubview(button)
currentX = button.frame.maxX
return button
}
}
|
mit
|
5236f87ef12145e98c443f514148d24f
| 33.068702 | 131 | 0.635671 | 4.436382 | false | false | false | false |
ripventura/VCUIKit
|
VCUIKit/Classes/VCTheme/View Controller/Table View/VCTabledViewController.swift
|
1
|
3548
|
//
// VCTableViewController.swift
// VCUIKit
//
// Created by Vitor Cesco on 20/09/17.
//
import UIKit
open class VCTabledViewController: VCViewController {
@IBOutlet open var tableView: UITableView!
// MARK: - Lifecycle
open override func viewDidLoad() {
super.viewDidLoad()
if self.includesRefreshControl {
self.refreshControlManager.setupRefreshControl(scrollView: self.tableView)
}
// If this viewController isTranslucent and doesn't includesRefreshControl
if self.navigationController?.navigationBar != nil &&
self.navigationController!.navigationBar.isTranslucent &&
!self.includesRefreshControl {
if #available(iOS 11, *) {
}
else {
// Adds an inset to compensate the translucent navigation bar on iOS 10-
self.tableView.contentInset = UIEdgeInsets(top: self.tableView.contentInset.top + 64,
left: self.tableView.contentInset.left,
bottom: self.tableView.contentInset.bottom,
right: self.tableView.contentInset.right)
}
}
}
// MARK: - Data Loading
/** Reloads TableView Data */
open func reloadData() {
self.tableView.reloadData()
}
// MARK: - Placeholders
open override func updatePlaceholders(enable: Bool,
title: String? = nil,
text: String? = nil,
drawer: VCDrawerProtocol? = nil,
activity: Bool = false,
buttonTitle: String? = nil) {
self.tableView.refreshControl?.endRefreshing()
self.tableView.isHidden = enable
super.updatePlaceholders(enable: enable,
title: title,
text: text,
drawer: drawer,
activity: activity,
buttonTitle: buttonTitle)
}
// MARK: - SearchControlManagerDelegate
open override func searchControlDidBeginEditing(manager: SearchControlManager) {
if self.disablesRefreshWhenSearching {
// Disables the RefreshControl when searching
self.tableView.bounces = false
self.tableView.alwaysBounceVertical = false
}
}
open override func searchControlCancelButtonPressed(manager: SearchControlManager) {
if self.disablesRefreshWhenSearching {
// Enables back the RefreshControl
self.tableView.bounces = true
self.tableView.alwaysBounceVertical = true
}
}
}
// MARK: - UITableViewDataSource
extension VCTabledViewController: UITableViewDataSource {
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell(style: .default, reuseIdentifier: nil)
}
}
// MARK: - UITableViewDelegate
extension VCTabledViewController: UITableViewDelegate {
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
|
mit
|
3ede478b0fbc15fc366aedaba747271b
| 36.744681 | 105 | 0.575536 | 5.883914 | false | false | false | false |
jamielesouef/UITableViewScrollHeaderDemo
|
scrollHeader/ViewController.swift
|
1
|
2056
|
//
// ViewController.swift
// scrollHeader
//
// Created by Jamie Le Souef on 26/05/2015.
// Copyright (c) 2015 Jamie Le Souef. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var headerImage: UIImageView!
var scaleFactor: CGFloat!
var originalImageSize: CGSize!
var originalImagePosition: CGPoint!
override func viewDidLoad() {
super.viewDidLoad()
headerImage.image = UIImage(named: "header.png")
headerImage.contentMode = UIViewContentMode.ScaleAspectFill
headerImage.clipsToBounds = true
originalImageSize = headerImage.frame.size
originalImagePosition = headerImage.frame.origin
scaleFactor = headerImage.frame.size.height / headerImage.frame.size.width
let tableViewHeader = UIView(frame: CGRect(x: 0, y: 170, width: self.view.frame.width, height: 150))
tableView.tableHeaderView = tableViewHeader
tableView.delegate = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
return cell
}
func scrollViewDidScroll(scrollView: UIScrollView) {
var scrollOffset:CGFloat = scrollView.contentOffset.y
var headerImageFrame:CGRect = headerImage.frame
if scrollOffset < 0 {
headerImage.frame.size.width = originalImageSize.width - (scrollOffset)
headerImage.frame.size.height = originalImageSize.height - (scrollOffset)
headerImage.frame.origin.x = originalImagePosition.x - -scrollOffset/2
} else {
headerImage.frame.origin.y = -scrollOffset
}
}
}
|
mit
|
7d6100be3c805b9b51df08d66b0fd519
| 33.847458 | 115 | 0.681907 | 5.165829 | false | false | false | false |
cherrywoods/swift-meta-serialization
|
Examples/DynamicUnwrap/Example2Metas.swift
|
1
|
1219
|
//
// BasicMetas.swift
// MetaSerialization
//
// Copyright 2018 cherrywoods
//
// 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
@testable import MetaSerialization
indirect enum Example2Meta: Meta {
case string(String)
case array([Example2Meta])
}
extension Example2Meta: Equatable {
static func ==(lhs: Example2Meta, rhs: Example2Meta) -> Bool {
switch (lhs, rhs) {
case (.string(let lhValue), .string(let rhValue)):
return lhValue == rhValue
case (.array(let lhValue), .array(let rhValue)):
return lhValue == rhValue
default:
return false
}
}
}
|
apache-2.0
|
14001f85e9e771de562f8fead7d1da99
| 26.088889 | 76 | 0.654635 | 4.118243 | false | false | false | false |
CardinalNow/CardinalDebugToolkit
|
Example/Sources/CardinalLogger.swift
|
1
|
5891
|
//
// CardinalLogger.swift
// CardinalLogger
//
// Copyright (c) 2017 Cardinal Solutions (https://www.cardinalsolutions.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
open class CardinalLogger {
public enum LogLevel: Int {
case debug
case info
case warning
case error
case critical
}
open var isLoggingEnabled = true
open var logLevel: LogLevel
open var logBuffers: [CardinalLogBuffer] = []
open class func pruneConsoleLogFiles(maxNum: Int) throws {
guard maxNum >= 0 else { return }
var logFilesURLs = consoleLogFileURLs()
guard logFilesURLs.count > maxNum else { return }
logFilesURLs.sort { (lhs, rhs) -> Bool in
let lhsCDate = (try? lhs.resourceValues(forKeys: [.creationDateKey]))?.creationDate
let rhsCDate = (try? rhs.resourceValues(forKeys: [.creationDateKey]))?.creationDate
if let lhsCDate = lhsCDate, let rhsCDate = rhsCDate {
return lhsCDate < rhsCDate
}
return lhs.lastPathComponent < rhs.lastPathComponent
}
let fileManager = FileManager.default
for URL in logFilesURLs.prefix(logFilesURLs.count - maxNum) {
try fileManager.removeItem(at: URL)
}
}
@discardableResult
open class func startLoggingConsoleToFile() -> Bool {
guard let libDir = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first else {
return false
}
let logDirURL = URL(fileURLWithPath: libDir, isDirectory: true).appendingPathComponent("consoleLogs", isDirectory: true)
do {
try FileManager.default.createDirectory(at: logDirURL, withIntermediateDirectories: true, attributes: nil)
} catch {
return false
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd_HH:mm:ss"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let logFileName = dateFormatter.string(from: Date())
let logFileURL = logDirURL.appendingPathComponent("\(logFileName).log", isDirectory: false)
let result = freopen(logFileURL.path.cString(using: .ascii), "a+", stderr)
return (result != nil)
}
open class func consoleLogFileURLs() -> [URL] {
guard let libDir = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first else {
return []
}
let libDirURL = URL(fileURLWithPath: libDir, isDirectory: true).appendingPathComponent("consoleLogs", isDirectory: true)
if let fileURLs = try? FileManager.default.contentsOfDirectory(at: libDirURL, includingPropertiesForKeys: [.creationDateKey, .fileSizeKey], options: .skipsHiddenFiles) {
return fileURLs.filter({ $0.isFileURL && $0.pathExtension == "log" })
} else {
return []
}
}
public init(logLevel: LogLevel) {
self.logLevel = logLevel
}
open func debug(_ message: String, tag: String? = nil) {
log(message, level: .debug, tag: tag)
}
open func debug(_ error: Error, tag: String? = nil) {
log(error, level: .debug, tag: tag)
}
open func info(_ message: String, tag: String? = nil) {
log(message, level: .info, tag: tag)
}
open func info(_ error: Error, tag: String? = nil) {
log(error, level: .info, tag: tag)
}
open func warning(_ message: String, tag: String? = nil) {
log(message, level: .warning, tag: tag)
}
open func warning(_ error: Error, tag: String? = nil) {
log(error, level: .warning, tag: tag)
}
open func error(_ message: String, tag: String? = nil) {
log(message, level: .error, tag: tag)
}
open func error(_ error: Error, tag: String? = nil) {
log(error, level: .error, tag: tag)
}
open func critical(_ message: String, tag: String? = nil) {
log(message, level: .critical, tag: tag)
}
open func critical(_ error: Error, tag: String? = nil) {
log(error, level: .critical, tag: tag)
}
open func log(_ error: Error, level: LogLevel, tag: String? = nil) {
log("\(error)", level: level, tag: tag)
}
open func log(_ message: String, level: LogLevel, tag: String? = nil) {
guard isLoggingEnabled && logLevel.rawValue <= level.rawValue else {
return
}
let formattedMessage: String
if let tag = tag {
formattedMessage = "[\(tag)] \(message)"
} else {
formattedMessage = message
}
NSLog(formattedMessage)
for bufffer in logBuffers {
bufffer.log(formattedMessage: formattedMessage, message: message, tag: tag)
}
}
}
|
mit
|
2364b4c4bff37ebe6f5d365f8c51e941
| 33.652941 | 177 | 0.63979 | 4.422673 | false | false | false | false |
fireflyexperience/BSImagePicker
|
Pod/Classes/Model/Settings.swift
|
1
|
2502
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// 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
final class Settings : BSImagePickerSettings {
var maxNumberOfSelections: Int = Int.max
var selectionCharacter: Character? = nil
var selectionFillColor: UIColor = UIView().tintColor
var selectionStrokeColor: UIColor = UIColor.white
var selectionShadowColor: UIColor = UIColor.black
var selectionTextAttributes: [String: AnyObject] = {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.alignment = .center
return [
NSFontAttributeName: UIFont.boldSystemFont(ofSize: 10.0),
NSParagraphStyleAttributeName: paragraphStyle,
NSForegroundColorAttributeName: UIColor.white
]
}()
var cellsPerRow: (_ verticalSize: UIUserInterfaceSizeClass, _ horizontalSize: UIUserInterfaceSizeClass) -> Int = {(verticalSize: UIUserInterfaceSizeClass, horizontalSize: UIUserInterfaceSizeClass) -> Int in
switch (verticalSize, horizontalSize) {
case (.compact, .regular): // iPhone5-6 portrait
return 3
case (.compact, .compact): // iPhone5-6 landscape
return 5
case (.regular, .regular): // iPad portrait/landscape
return 7
default:
return 3
}
}
}
|
mit
|
6145b345815b0500a4ef365dffa7b520
| 45.188679 | 210 | 0.70012 | 4.992016 | false | false | false | false |
Hansoncoder/SpriteDemo
|
SpriteKitDemo/SpriteKitDemo/GameScene.swift
|
1
|
1295
|
//
// GameScene.swift
// SpriteKitDemo
//
// Created by Hanson on 16/5/9.
// Copyright (c) 2016年 Hanson. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
myLabel.text = "Hello, World!"
myLabel.fontSize = 45
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
self.addChild(myLabel)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
let location = touch.locationInNode(self)
let sprite = SKSpriteNode(imageNamed:"Spaceship")
sprite.xScale = 0.5
sprite.yScale = 0.5
sprite.position = location
let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1)
sprite.runAction(SKAction.repeatActionForever(action))
self.addChild(sprite)
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
|
apache-2.0
|
0811a915759e82b4d02f6888fcb62fc3
| 27.733333 | 92 | 0.583913 | 4.771218 | false | false | false | false |
cozkurt/coframework
|
COFramework/COFramework/Swift/Extentions/UITextview+Additions.swift
|
1
|
2181
|
//
// UITextview+Additions.swift
// FuzFuz
//
// Created by Cenker Ozkurt on 10/07/19.
// Copyright © 2019 Cenker Ozkurt, Inc. All rights reserved.
//
import UIKit
extension UITextView {
public func setTextWhileKeepingAttributes(_ string: String) {
if let newAttributedText = self.attributedText {
let mutableAttributedText = newAttributedText.mutableCopy()
(mutableAttributedText as AnyObject).mutableString.setString(string)
self.attributedText = mutableAttributedText as? NSAttributedString
}
}
public func applySpacingToTextViewAndScroll(_ contentOffset: CGPoint = .zero, spacing: CGFloat, text: String) {
let style = NSMutableParagraphStyle()
style.lineSpacing = spacing
let attributes = [NSAttributedString.Key.paragraphStyle : style, NSAttributedString.Key.font : self.font, NSAttributedString.Key.foregroundColor : self.textColor ]
self.attributedText = NSAttributedString(string: text, attributes:attributes as [NSAttributedString.Key : Any])
DispatchQueue.main.async {
self.setContentOffset(contentOffset, animated: false)
}
}
public func checkLimits(text: String, range: NSRange, limit: Int, lineFeed: Bool) -> Bool {
// if next line allowed then skio
if lineFeed == false && text == "\n" {
self.resignFirstResponder()
return false
}
// filter out adult content
// TO DO: Adult content check disabled
// self.text = AdultContentManager.sharedInstance.filterAdultContent(string: self.text)
// get the current text, or use an empty string if that failed
let currentText = self.text ?? ""
// attempt to read the range they are trying to change, or exit if we can't
guard let stringRange = Range(range, in: currentText) else { return false }
// add their new text to the existing text
let updatedText = currentText.replacingCharacters(in: stringRange, with: text)
// make sure the result is under limit
return updatedText.count <= limit
}
}
|
gpl-3.0
|
71fc737b0cf4cf31cd2b7a24a8052404
| 37.928571 | 171 | 0.660092 | 4.977169 | false | false | false | false |
velvetroom/columbus
|
Source/Model/Settings/MSettingsDistance.swift
|
1
|
1179
|
import UIKit
final class MSettingsDistance:MSettingsProtocol
{
let reusableIdentifier:String = VSettingsListCellDistance.reusableIdentifier
let cellHeight:CGFloat = 150
let items:[MSettingsDistanceProtocol]
let indexMap:[DSettingsDistance:Int]
private(set) weak var settings:DSettings!
private(set) weak var database:Database!
var selectedIndex:Int?
{
get
{
let index:Int? = indexMap[settings.distance]
return index
}
}
init(
settings:DSettings,
database:Database)
{
self.settings = settings
self.database = database
items = MSettingsDistance.factoryItems()
indexMap = MSettingsDistance.factoryIndexMap(items:items)
}
//MARK: internal
func selected(index:Int)
{
settings.distance = items[index].distance
database.save { }
}
func itemsTitle() -> [String]
{
var titles:[String] = []
for item:MSettingsDistanceProtocol in items
{
titles.append(item.title)
}
return titles
}
}
|
mit
|
b520041e032defe29e91c225451e5eb3
| 21.673077 | 80 | 0.587786 | 4.953782 | false | false | false | false |
breadwallet/breadwallet-core
|
Swift/BRCryptoTests/BRCryptoAmountTests.swift
|
1
|
17360
|
//
// BRCryptoAmpuntTests.swift
// BRCryptoTests
//
// Created by Ed Gamble on 10/30/18.
// Copyright © 2018-2019 Breadwallet AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
// See the CONTRIBUTORS file at the project root for a list of contributors.
//
import XCTest
@testable import BRCrypto
class BRCryptoAmountTests: XCTestCase {
override func setUp() {
}
override func tearDown() {
}
func testCurrency() {
let btc = Currency (uids: "Bitcoin", name: "Bitcoin", code: "BTC", type: "native", issuer: nil)
XCTAssert (btc.name == "Bitcoin")
XCTAssert (btc.code == "BTC")
XCTAssert (btc.type == "native")
let eth = Currency (uids: "Ethereum", name: "Ethereum", code: "ETH", type: "native", issuer: nil)
XCTAssert (eth.name == "Ethereum")
XCTAssert (eth.code == "ETH")
XCTAssert (eth.type == "native")
XCTAssertFalse (btc.name == eth.name)
XCTAssertFalse (btc.code == eth.code)
XCTAssertTrue (btc.type == eth.type)
// Not normally how a Currency is created; but used internally
let eth_too = Currency (core: eth.core)
XCTAssert (eth_too.name == "Ethereum")
XCTAssert (eth_too.code == "ETH")
XCTAssert (eth_too.type == "native")
}
func testUnit () {
let btc = Currency (uids: "Bitcoin", name: "Bitcoin", code: "BTC", type: "native", issuer: nil)
let eth = Currency (uids: "Ethereum", name: "Ethereum", code: "ETH", type: "native", issuer: nil)
let BTC_SATOSHI = BRCrypto.Unit (currency: btc, code: "BTC-SAT", name: "Satoshi", symbol: "SAT")
let BTC_BTC = BRCrypto.Unit (currency: btc, code: "BTC-BTC", name: "Bitcoin", symbol: "B", base: BTC_SATOSHI, decimals: 8)
XCTAssert (BTC_SATOSHI.currency.code == btc.code)
XCTAssert (BTC_SATOSHI.name == "Satoshi")
XCTAssert (BTC_SATOSHI.symbol == "SAT");
XCTAssertTrue (BTC_SATOSHI.hasCurrency (btc))
XCTAssertFalse (BTC_SATOSHI.hasCurrency (eth))
XCTAssertTrue (BTC_SATOSHI.isCompatible (with: BTC_SATOSHI))
let test = BTC_SATOSHI.core == BTC_SATOSHI.base.core
XCTAssertTrue (test)
XCTAssert (BTC_BTC.currency.code == btc.code)
XCTAssertTrue (BTC_BTC.isCompatible (with: BTC_SATOSHI))
XCTAssertTrue (BTC_SATOSHI.isCompatible (with: BTC_BTC))
let ETH_WEI = BRCrypto.Unit (currency: eth, code: "ETH-WEI", name: "WEI", symbol: "wei")
XCTAssertFalse (ETH_WEI.isCompatible (with: BTC_BTC))
XCTAssertFalse (BTC_BTC.isCompatible (with: ETH_WEI))
// Not normally how a Unit is created; but used internally
let BTC_SATOSHI_TOO = Unit (core: BTC_SATOSHI.core)
XCTAssert (BTC_SATOSHI_TOO.currency.code == btc.code)
XCTAssert (BTC_SATOSHI_TOO.name == "Satoshi")
XCTAssert (BTC_SATOSHI_TOO.symbol == "SAT");
XCTAssertTrue (BTC_SATOSHI_TOO.hasCurrency (btc))
XCTAssertFalse (BTC_SATOSHI_TOO.hasCurrency (eth))
XCTAssertTrue (BTC_SATOSHI_TOO.isCompatible (with: BTC_SATOSHI))
}
func testAmount () {
let btc = Currency (uids: "Bitcoin", name: "Bitcoin", code: "BTC", type: "native", issuer: nil)
let eth = Currency (uids: "Ethereum", name: "Ethereum", code: "ETH", type: "native", issuer: nil)
let BTC_SATOSHI = BRCrypto.Unit (currency: btc, code: "BTC-SAT", name: "Satoshi", symbol: "SAT")
let BTC_BTC = BRCrypto.Unit (currency: btc, code: "BTC-BTC", name: "Bitcoin", symbol: "B", base: BTC_SATOSHI, decimals: 8)
let ETH_WEI = BRCrypto.Unit (currency: eth, code: "ETH-WEI", name: "WEI", symbol: "wei")
let ETH_GWEI = BRCrypto.Unit (currency: eth, code: "ETH-GWEI", name: "GWEI", symbol: "gwei", base: ETH_WEI, decimals: 9)
let ETH_ETHER = BRCrypto.Unit (currency: eth, code: "ETH-ETH", name: "ETHER", symbol: "E", base: ETH_WEI, decimals: 18)
let btc1 = Amount.create (integer: 100000000, unit: BTC_SATOSHI)
XCTAssert (100000000 == btc1.double (as: BTC_SATOSHI))
XCTAssert (1 == btc1.double (as: BTC_BTC))
XCTAssertFalse (btc1.isNegative)
let btc1n = btc1.negate
XCTAssert (-100000000 == btc1n.double (as: BTC_SATOSHI))
XCTAssert (-1 == btc1n.double (as: BTC_BTC))
XCTAssertTrue(btc1n.isNegative)
XCTAssertFalse(btc1n.negate.isNegative)
let btc2 = Amount.create (integer: 1, unit: BTC_BTC)
XCTAssert (1 == btc2.double (as: BTC_BTC))
XCTAssert (100000000 == btc2.double (as: BTC_SATOSHI))
XCTAssert (btc1 == btc2)
let btc3 = Amount.create (double: 1.5, unit: BTC_BTC);
XCTAssert (1.5 == btc3.double (as: BTC_BTC))
XCTAssert (150000000 == btc3.double (as: BTC_SATOSHI))
let btc4 = Amount.create (double: -1.5, unit: BTC_BTC);
XCTAssertTrue (btc4.isNegative)
XCTAssert (-1.5 == btc4.double (as: BTC_BTC))
XCTAssert (-150000000 == btc4.double (as: BTC_SATOSHI))
if #available(iOS 13, *) {
XCTAssertEqual ("-B 1.50", btc4.string (as: BTC_BTC))
XCTAssertEqual ("-SAT 150,000,000", btc4.string (as: BTC_SATOSHI)!)
}
else {
XCTAssertEqual ("-B1.50", btc4.string (as: BTC_BTC))
XCTAssertEqual ("-SAT150,000,000", btc4.string (as: BTC_SATOSHI)!)
}
XCTAssertEqual (btc1.double(as: BTC_BTC), btc1.convert(to: BTC_SATOSHI)?.double(as: BTC_BTC))
XCTAssertEqual (btc1.double(as: BTC_SATOSHI), btc1.convert(to: BTC_BTC)?.double(as: BTC_SATOSHI))
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 2
formatter.generatesDecimalNumbers = true
XCTAssert ("-1.50" == btc4.string (as: BTC_BTC, formatter: formatter))
let eth1 = Amount.create (double: 1e9, unit: ETH_GWEI)
let eth2 = Amount.create (double: 1.0, unit: ETH_ETHER)
let eth3 = Amount.create (double: 1.1, unit: ETH_ETHER)
XCTAssert (eth1 == eth2)
XCTAssert (eth1 < eth3)
XCTAssert (eth1 != eth3)
XCTAssert ((eth1 + eth1)! == (eth2 + eth2))
XCTAssert (0.0 == (eth2 - eth1)!.double (as: ETH_WEI))
XCTAssert (0.0 == (eth2 - eth1)!.double (as: ETH_ETHER))
XCTAssert (2.0 == (eth2 + eth1)!.double (as: ETH_ETHER))
XCTAssertTrue ((eth2 - eth3)!.isNegative)
XCTAssertFalse ((eth2 - eth2)!.isNegative)
let a1 = Amount.create (double: +1.0, unit: ETH_WEI)
let a2 = Amount.create (double: -1.0, unit: ETH_WEI)
XCTAssert (+0.0 == (a1 + a2)!.double (as: ETH_WEI));
XCTAssert (+0.0 == (a2 + a1)!.double (as: ETH_WEI));
XCTAssert (-2.0 == (a2 + a2)!.double (as: ETH_WEI));
XCTAssert (+2.0 == (a1 + a1)!.double (as: ETH_WEI));
XCTAssert (+2.0 == (a1 - a2)!.double (as: ETH_WEI))
XCTAssert (-2.0 == (a2 - a1)!.double (as: ETH_WEI))
XCTAssert (+0.0 == (a1 - a1)!.double (as: ETH_WEI))
XCTAssert (+0.0 == (a2 - a2)!.double (as: ETH_WEI))
//
// String
//
let btc1s = Amount.create (string: "100000000", unit: BTC_SATOSHI)!
XCTAssert (100000000 == btc1s.double (as: BTC_SATOSHI))
XCTAssert (1 == btc1s.double (as: BTC_BTC))
let btc2s = Amount.create (string: "1", unit: BTC_BTC)!
XCTAssert (1 == btc2s.double (as: BTC_BTC))
XCTAssert (100000000 == btc2s.double (as: BTC_SATOSHI))
XCTAssert (btc1s == btc2s)
let btc3s = Amount.create (string: "0x5f5e100", unit: BTC_SATOSHI)!
XCTAssert (100000000 == btc3s.double (as: BTC_SATOSHI))
XCTAssert (1 == btc3s.double (as: BTC_BTC))
if #available(iOS 13, *) {
XCTAssertEqual ("SAT 100,000,000", btc3s.string (as: BTC_SATOSHI)!)
XCTAssertEqual ("B 1.00", btc3s.string (as: BTC_BTC)!)
}
else {
XCTAssertEqual ("SAT100,000,000", btc3s.string (as: BTC_SATOSHI)!)
XCTAssertEqual ("B1.00", btc3s.string (as: BTC_BTC)!)
}
let btc4s = Amount.create (string: "0x5f5e100", negative: true, unit: BTC_SATOSHI)!
XCTAssert (-100000000 == btc4s.double (as: BTC_SATOSHI))
XCTAssert (-1 == btc4s.double (as: BTC_BTC))
if #available(iOS 13, *) {
XCTAssertEqual ("-SAT 100,000,000", btc4s.string (as: BTC_SATOSHI)!)
XCTAssertEqual ("-B 1.00", btc4s.string (as: BTC_BTC)!)
}
else {
XCTAssertEqual ("-SAT100,000,000", btc4s.string (as: BTC_SATOSHI)!)
XCTAssertEqual ("-B1.00", btc4s.string (as: BTC_BTC)!)
}
XCTAssertNil (Amount.create (string: "w0x5f5e100", unit: BTC_SATOSHI))
XCTAssertNil (Amount.create (string: "0x5f5e100w", unit: BTC_SATOSHI))
XCTAssertNil (Amount.create (string: "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000", unit: BTC_SATOSHI))
// Negative/Positive
XCTAssertNil (Amount.create (string: "-1", unit: BTC_SATOSHI))
XCTAssertNil (Amount.create (string: "+1", unit: BTC_SATOSHI))
XCTAssertNil (Amount.create (string: "0.1", unit: BTC_SATOSHI))
XCTAssertNil (Amount.create (string: "1.1", unit: BTC_SATOSHI))
XCTAssertNotNil (Amount.create (string: "1.0", unit: BTC_SATOSHI))
XCTAssertNotNil (Amount.create (string: "1.", unit: BTC_SATOSHI))
XCTAssertNotNil (Amount.create (string: "0.1", unit: BTC_BTC))
XCTAssertNotNil (Amount.create (string: "1.1", unit: BTC_BTC))
XCTAssertNotNil (Amount.create (string: "1.0", unit: BTC_BTC))
XCTAssertNotNil (Amount.create (string: "1.", unit: BTC_BTC))
XCTAssert ( 10000000 == Amount.create (string: "0.1", unit: BTC_BTC)?.double(as: BTC_SATOSHI))
XCTAssert (110000000 == Amount.create (string: "1.1", unit: BTC_BTC)?.double(as: BTC_SATOSHI))
XCTAssert (100000000 == Amount.create (string: "1.0", unit: BTC_BTC)?.double(as: BTC_SATOSHI))
XCTAssert (100000000 == Amount.create (string: "1.", unit: BTC_BTC)?.double(as: BTC_SATOSHI))
XCTAssertNotNil (Amount.create (string: "0.12345678", unit: BTC_BTC))
XCTAssertNil (Amount.create (string: "0.123456789", unit: BTC_BTC))
}
func testAmountETH () {
var result: String! = nil
let eth = Currency (uids: "Ethereum", name: "Ethereum", code: "ETH", type: "native", issuer: nil)
let ETH_WEI = BRCrypto.Unit (currency: eth, code: "ETH-WEI", name: "WEI", symbol: "wei")
let ETH_GWEI = BRCrypto.Unit (currency: eth, code: "ETH-GWEI", name: "GWEI", symbol: "gwei", base: ETH_WEI, decimals: 9)
let ETH_ETHER = BRCrypto.Unit (currency: eth, code: "ETH-ETH", name: "ETHER", symbol: "E", base: ETH_WEI, decimals: 18)
let a1 = Amount.create(string: "12.12345678", negative: false, unit: ETH_ETHER)
XCTAssertNotNil(a1)
XCTAssertNotNil(a1!.double (as: ETH_ETHER))
XCTAssertEqual(12.12345678, a1!.double (as: ETH_ETHER)!)
let a2 = Amount.create(string: "123.12345678", negative: false, unit: ETH_ETHER)
XCTAssertNotNil(a2)
XCTAssertNotNil(a2!.double (as: ETH_ETHER))
XCTAssertEqual(123.12345678, a2!.double (as: ETH_ETHER)!)
let a3 = Amount.create(string: "12.12345678", negative: false, unit: ETH_GWEI)
XCTAssertNotNil(a3)
XCTAssertNotNil(a3!.double (as: ETH_GWEI))
XCTAssertEqual(12.12345678, a3!.double (as: ETH_GWEI)!)
let a4 = Amount.create(string: "123.12345678", negative: false, unit: ETH_GWEI)
XCTAssertNotNil(a4)
XCTAssertNotNil(a4!.double (as: ETH_GWEI))
XCTAssertEqual(123.12345678, a4!.double (as: ETH_GWEI)!)
// Avoid a 'exact double' representation error:
// was 1.234567891234567891, now: 1.234567891234567936
let a5 = Amount.create(string: "1.234567891234567936", negative: false, unit: ETH_ETHER)
XCTAssertNotNil(a5)
XCTAssertNotNil (a5?.double(as: ETH_WEI))
XCTAssertEqual(1234567891234567936, a5?.double(as: ETH_WEI)!)
XCTAssertEqual("1234567891234567936", a5?.string (base: 10, preface: ""))
// Lost precision - last 5 digits
if #available(iOS 13, *) { result = "wei 1,234,567,891,234,568,000" }
else { result = "wei1,234,567,891,234,570,000" }
XCTAssertEqual(result, a5?.string(as: ETH_WEI)!)
XCTAssertEqual("1000000000000000000", Amount.create(string: "1", negative: false, unit: ETH_ETHER)!.string (base: 10, preface: ""))
// String (1000000000000000000, radix:16, uppercase: true) -> DE0B6B3A7640000
XCTAssertEqual("0xDE0B6B3A7640000".lowercased(), Amount.create(string: "1", negative: false, unit: ETH_ETHER)!.string (base: 16, preface: "0x"))
let a6 = Amount.create(string: "123000000000000000000.0", negative: false, unit: ETH_WEI)
XCTAssertNotNil(a6)
if #available(iOS 13, *) { result = "wei 123,000,000,000,000,000,000" }
else { result = "wei123,000,000,000,000,000,000" }
XCTAssertEqual(result, a6?.string(as: ETH_WEI)!)
let a6Double = a6?.double (as: ETH_WEI)
XCTAssertEqual(a6Double, 1.23e20)
let a7 = Amount.create(string: "123456789012345678.0", negative: false, unit: ETH_WEI)
XCTAssertNotNil(a7)
XCTAssertEqual ("123456789012345678", a7?.string(base: 10, preface: ""))
// Note: a DIFFERENT VALUE between iOS 13
if #available(iOS 13, *) { result = "wei 123,456,789,012,345,680" }
else { result = "wei123,456,789,012,346,000" }
XCTAssertEqual (result, a7?.string(as: ETH_WEI)!)
// XCTAssertNotEqual("wei123,456,789,012,345,678", a7?.string(as: ETH_WEI)!)
let a7Double = a7?.double(as: ETH_WEI)
XCTAssertEqual(a7Double, 1.2345678901234568e17)
}
func testAmountBTC () {
let btc = Currency (uids: "Bitcoin", name: "Bitcoin", code: "BTC", type: "native", issuer: nil)
let BTC_SATOSHI = BRCrypto.Unit (currency: btc, code: "BTC-SAT", name: "Satoshi", symbol: "SAT")
let BTC_BTC = BRCrypto.Unit (currency: btc, code: "BTC-BTC", name: "Bitcoin", symbol: "B", base: BTC_SATOSHI, decimals: 8)
XCTAssertEqual (btc, BTC_SATOSHI.currency)
let btc1 = Amount.create (integer: 100000000, unit: BTC_SATOSHI)
XCTAssert (100000000 == btc1.double (as: BTC_SATOSHI))
XCTAssert (1 == btc1.double (as: BTC_BTC))
XCTAssertFalse (btc1.isNegative)
}
func testAmountExtended () {
let btc = Currency (uids: "Bitcoin", name: "Bitcoin", code: "BTC", type: "native", issuer: nil)
let BTC_SATOSHI = BRCrypto.Unit (currency: btc, code: "BTC-SAT", name: "Satoshi", symbol: "SAT")
let BTC_MONGO = BRCrypto.Unit (currency: btc, code: "BTC-MONGO", name: "BitMongo", symbol: "BM", base: BTC_SATOSHI, decimals: 70)
let btc1 = Amount.create (integer: 100000000, unit: BTC_SATOSHI)
let btc2 = Amount.create (integer: 100000001, unit: BTC_SATOSHI)
XCTAssertFalse(btc1 > btc2)
XCTAssertFalse(btc1 > btc1)
XCTAssertTrue (btc2 > btc1)
XCTAssertTrue (btc1 <= btc2)
XCTAssertTrue (btc1 <= btc1)
XCTAssertTrue (btc2 >= btc1)
XCTAssertTrue (btc2 >= btc2)
XCTAssertEqual (btc1.currency, btc)
XCTAssertTrue (btc1.hasCurrency(btc))
let btc3 = Amount.create(double: 1e20, unit: BTC_SATOSHI)
XCTAssertNotNil (btc3.double(as: BTC_MONGO))
let btc4 = Amount (core: btc1.core, take: true)
XCTAssertTrue (btc4.core == btc1.core)
}
func testCurrencyPair () {
let btc = Currency (uids: "Bitcoin", name: "Bitcoin", code: "BTC", type: "native", issuer: nil)
let BTC_SATOSHI = BRCrypto.Unit (currency: btc, code: "BTC-SAT", name: "Satoshi", symbol: "SAT")
let BTC_BTC = BRCrypto.Unit (currency: btc, code: "BTC-BTC", name: "Bitcoin", symbol: "B", base: BTC_SATOSHI, decimals: 8)
let usd = Currency (uids: "USDollar", name: "USDollar", code: "USD", type: "fiat", issuer: nil)
let usd_cents = BRCrypto.Unit (currency: usd, code: "USD-Cents", name: "Cents", symbol: "c")
let usd_dollar = BRCrypto.Unit (currency: usd, code: "USD-Dollar", name: "Dollars", symbol: "$", base: usd_cents, decimals: 2)
let pair = CurrencyPair (baseUnit: BTC_BTC, quoteUnit: usd_dollar, exchangeRate: 10000)
XCTAssertEqual("Bitcoin/Dollars=10000.0", pair.description)
// BTC -> USD
let oneBTCinUSD = pair.exchange(asBase: Amount.create(double: 1.0, unit: BTC_BTC))
XCTAssertNotNil(oneBTCinUSD)
XCTAssertEqual (10000.0, oneBTCinUSD!.double(as: usd_dollar)!, accuracy: 1e-6)
// USD -> BTC
let oneUSDinBTC = pair.exchange(asQuote: Amount.create(double: 1.0, unit: usd_dollar))
XCTAssertNotNil (oneUSDinBTC)
XCTAssertEqual (1/10000.0, oneUSDinBTC!.double(as: BTC_BTC)!, accuracy: 1e-6)
let oneBTC = Amount.create(double: 1.0, unit: BTC_BTC)
XCTAssertEqual("$10,000.00", oneBTC.string(pair: pair))
}
}
|
mit
|
7d05396325e8784acdf55ad0956a54cb
| 46.928177 | 153 | 0.608012 | 3.330774 | false | false | false | false |
sugar2010/SwiftOptimizer
|
SwiftOptimizer/main.swift
|
2
|
1081
|
//
// main.swift
// SwiftOptimizer
//
// Created by Helin Gai on 7/19/14.
// Copyright (c) 2014 SHFuse. All rights reserved.
//
import Foundation
class RosenBrockFunction: CostFunction
{
override func value(parameters: matrix) -> Double {
return pow(1.0 - parameters[0], 2) + 100 * pow(parameters[1] - pow(parameters[0], 2), 2.0)
}
}
var myEndCriteria = EndCriteria(maxIterations: 1000, maxStationaryStateIterations: 100, rootEpsilon: 1.0e-8, functionEpsilon: 1.0e-9, gradientNormEpsilon: 1.0e-5)
var myFunc = RosenBrockFunction()
var constraint = NoConstraint()
var initialValue = zeros(2) + 100
var problem = Problem(costFunction: myFunc, constraint: constraint, initialValue: initialValue)
var solver = Simplex(lambda: 0.1)
var solved = solver.minimize(&problem, endCriteria: myEndCriteria)
println(problem.currentValue)
var problem2 = Problem(costFunction: myFunc, constraint: constraint, initialValue: initialValue)
var bfgsSolver = BFGS()
var bfgsSolved = bfgsSolver.minimize(&problem2, endCriteria: myEndCriteria)
println(problem2.currentValue)
|
mit
|
6065d62121ac3d807f7cf6e7286687f7
| 29.885714 | 162 | 0.748381 | 3.388715 | false | false | false | false |
thiagolioy/marvelapp
|
MarvelTests/CharactersCollectionDatasourceSpec.swift
|
1
|
2381
|
//
// CharactersCollectionDatasourceSpec.swift
// Marvel
//
// Created by Thiago Lioy on 27/11/16.
// Copyright © 2016 Thiago Lioy. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import Marvel
class CharactersCollectionDatasourceSpec: QuickSpec {
override func spec() {
describe("CharactersCollectionDatasource") {
var controller: CharactersViewController!
var character: Marvel.Character!
beforeEach {
let testBundle = Bundle(for: type(of: self))
let mockLoader = MockLoader(file: "character", in: testBundle)
character = (mockLoader?.map(to: Character.self))!
let apiMock = MarvelAPICallsMock(characters: [character])
controller = Storyboard.Main.charactersViewControllerScene.viewController() as! CharactersViewController
controller.apiManager = apiMock
//Load view components
let _ = controller.view
controller.showAsGrid(UIButton())
}
it("should have a valid datasource") {
expect(controller.collectionDatasource).toNot(beNil())
}
it("should have a cell of expected type") {
let indexPath = IndexPath(row: 0, section: 0)
let cell = controller.collectionDatasource!.collectionView(controller.collectionView, cellForItemAt: indexPath)
expect(cell.isKind(of: CharacterCollectionCell.self)).to(beTruthy())
}
it("should have a configured cell") {
let indexPath = IndexPath(row: 0, section: 0)
let cell = controller.collectionDatasource!.collectionView(controller.collectionView, cellForItemAt: indexPath) as! CharacterCollectionCell
let name = cell.name.text!
expect(name).to(equal(character.name))
}
it("should have the right numberOfRowsInSection") {
let count = controller.collectionDatasource!.collectionView(controller.collectionView, numberOfItemsInSection: 0)
expect(count).to(equal(1))
}
}
}
}
|
mit
|
ce2e8a38c1524ef0767bec09b5609728
| 37.387097 | 155 | 0.577311 | 5.653207 | false | false | false | false |
kusl/swift
|
validation-test/compiler_crashers_2_fixed/0004-rdar20564605.swift
|
9
|
4574
|
// RUN: not %target-swift-frontend %s -parse
public protocol Q_SequenceDefaultsType {
typealias Element
typealias Generator : GeneratorType
func generate() -> Generator
}
extension Q_SequenceDefaultsType {
public final func underestimateCount() -> Int { return 0 }
public final func preprocessingPass<R>(body: (Self)->R) -> R? {
return nil
}
/// Create a ContiguousArray containing the elements of `self`,
/// in the same order.
public final func copyToContiguousArray() -> ContiguousArray<Generator.Element> {
let initialCapacity = underestimateCount()
var result = _ContiguousArrayBuffer<Generator.Element>(
count: initialCapacity, minimumCapacity: 0)
var g = self.generate()
while let x = g.next() {
result += CollectionOfOne(x)
}
return ContiguousArray(result)
}
/// Initialize the storage at baseAddress with the contents of this
/// sequence.
public final func initializeRawMemory(
baseAddress: UnsafeMutablePointer<Generator.Element>
) {
var p = baseAddress
var g = self.generate()
while let element = g.next() {
p.initialize(element)
++p
}
}
public final static func _constrainElement(Generator.Element) {}
}
/// A type that can be iterated with a `for`\ ...\ `in` loop.
///
/// `SequenceType` makes no requirement on conforming types regarding
/// whether they will be destructively "consumed" by iteration. To
/// ensure non-destructive iteration, constrain your *sequence* to
/// `CollectionType`.
public protocol Q_SequenceType : Q_SequenceDefaultsType {
/// A type that provides the *sequence*\ 's iteration interface and
/// encapsulates its iteration state.
typealias Generator : GeneratorType
/// Return a *generator* over the elements of this *sequence*.
///
/// Complexity: O(1)
func generate() -> Generator
/// Return a value less than or equal to the number of elements in
/// self, **nondestructively**.
///
/// Complexity: O(N)
func underestimateCount() -> Int
/// If `self` is multi-pass (i.e., a `CollectionType`), invoke the function
/// on `self` and return its result. Otherwise, return `nil`.
func preprocessingPass<R>(body: (Self)->R) -> R?
/// Create a ContiguousArray containing the elements of `self`,
/// in the same order.
func copyToContiguousArray() -> ContiguousArray<Element>
/// Initialize the storage at baseAddress with the contents of this
/// sequence.
func initializeRawMemory(
baseAddress: UnsafeMutablePointer<Element>
)
static func _constrainElement(Element)
}
public extension GeneratorType {
typealias Generator = Self
public final func generate() -> Generator {
return self
}
}
public protocol Q_CollectionDefaultsType : Q_SequenceType {
typealias Index : ForwardIndexType
var startIndex: Index {get}
var endIndex: Index {get}
}
public protocol Q_Indexable {
typealias Index : ForwardIndexType
typealias Element
var startIndex: Index {get}
var endIndex: Index {get}
subscript(i: Index) -> Element {get}
}
extension Q_Indexable {
typealias Generator = Q_IndexingGenerator<Self>
public final func generate() -> Q_IndexingGenerator<Self> {
return Q_IndexingGenerator(pos: self.startIndex, elements: self)
}
}
extension Q_CollectionDefaultsType {
public final func count() -> Index.Distance {
return distance(startIndex, endIndex)
}
public final func underestimateCount() -> Int {
let n = count().toIntMax()
return n > IntMax(Int.max) ? Int.max : Int(n)
}
public final func preprocessingPass<R>(body: (Self)->R) -> R? {
return body(self)
}
}
public struct Q_IndexingGenerator<C: Q_Indexable> : GeneratorType {
public typealias Element = C.Element
var pos: C.Index
let elements: C
public mutating func next() -> Element? {
if pos == elements.endIndex {
return nil
}
let ret = elements[pos]
++pos
return ret
}
}
public protocol Q_CollectionType : Q_Indexable, Q_CollectionDefaultsType {
func count() -> Index.Distance
subscript(position: Index) -> Element {get}
}
extension Array : Q_CollectionType {
public func copyToContiguousArray() -> ContiguousArray<Element> {
return ContiguousArray(self~>_copyToNativeArrayBuffer())
}
}
struct Boo : Q_CollectionType {
let startIndex: Int = 0
let endIndex: Int = 10
func generate() -> Q_IndexingGenerator<Boo> {
return Q_IndexingGenerator(pos: self.startIndex, elements: self)
}
typealias Element = String
subscript(i: Int) -> String {
return "Boo"
}
}
|
apache-2.0
|
7070062454210a78f1cea3eb02c5a59e
| 25.905882 | 83 | 0.693048 | 4.311027 | false | false | false | false |
blockstack/blockstack-portal
|
native/macos/Blockstack/Pods/Swifter/Sources/String+File.swift
|
6
|
4490
|
//
// String+File.swift
// Swifter
//
// Copyright © 2016 Damian Kołakowski. All rights reserved.
//
import Foundation
extension String {
public enum FileError: Error {
case error(Int32)
}
public class File {
let pointer: UnsafeMutablePointer<FILE>
public init(_ pointer: UnsafeMutablePointer<FILE>) {
self.pointer = pointer
}
public func close() -> Void {
fclose(pointer)
}
public func seek(_ offset: Int) -> Bool {
return (fseek(pointer, offset, SEEK_SET) == 0)
}
public func read(_ data: inout [UInt8]) throws -> Int {
if data.count <= 0 {
return data.count
}
let count = fread(&data, 1, data.count, self.pointer)
if count == data.count {
return count
}
if feof(self.pointer) != 0 {
return count
}
if ferror(self.pointer) != 0 {
throw FileError.error(errno)
}
throw FileError.error(0)
}
public func write(_ data: [UInt8]) throws -> Void {
if data.count <= 0 {
return
}
try data.withUnsafeBufferPointer {
if fwrite($0.baseAddress, 1, data.count, self.pointer) != data.count {
throw FileError.error(errno)
}
}
}
public static func currentWorkingDirectory() throws -> String {
guard let path = getcwd(nil, 0) else {
throw FileError.error(errno)
}
return String(cString: path)
}
}
public static var pathSeparator = "/"
public func openNewForWriting() throws -> File {
return try openFileForMode(self, "wb")
}
public func openForReading() throws -> File {
return try openFileForMode(self, "rb")
}
public func openForWritingAndReading() throws -> File {
return try openFileForMode(self, "r+b")
}
public func openFileForMode(_ path: String, _ mode: String) throws -> File {
guard let file = path.withCString({ pathPointer in mode.withCString({ fopen(pathPointer, $0) }) }) else {
throw FileError.error(errno)
}
return File(file)
}
public func exists() throws -> Bool {
return try self.withStat {
if let _ = $0 {
return true
}
return false
}
}
public func directory() throws -> Bool {
return try self.withStat {
if let stat = $0 {
return stat.st_mode & S_IFMT == S_IFDIR
}
return false
}
}
public func files() throws -> [String] {
guard let dir = self.withCString({ opendir($0) }) else {
throw FileError.error(errno)
}
defer { closedir(dir) }
var results = [String]()
while let ent = readdir(dir) {
var name = ent.pointee.d_name
let fileName = withUnsafePointer(to: &name) { (ptr) -> String? in
#if os(Linux)
return String(validatingUTF8: ptr.withMemoryRebound(to: CChar.self, capacity: Int(ent.pointee.d_reclen), { (ptrc) -> [CChar] in
return [CChar](UnsafeBufferPointer(start: ptrc, count: 256))
}))
#else
var buffer = ptr.withMemoryRebound(to: CChar.self, capacity: Int(ent.pointee.d_reclen), { (ptrc) -> [CChar] in
return [CChar](UnsafeBufferPointer(start: ptrc, count: Int(ent.pointee.d_namlen)))
})
buffer.append(0)
return String(validatingUTF8: buffer)
#endif
}
if let fileName = fileName {
results.append(fileName)
}
}
return results
}
private func withStat<T>(_ closure: ((stat?) throws -> T)) throws -> T {
return try self.withCString({
var statBuffer = stat()
if stat($0, &statBuffer) == 0 {
return try closure(statBuffer)
}
if errno == ENOENT {
return try closure(nil)
}
throw FileError.error(errno)
})
}
}
|
mpl-2.0
|
aa707d135d5fa94c7b7a882294b26f90
| 29.324324 | 145 | 0.492647 | 4.714286 | false | false | false | false |
apradanas/swift-army
|
swift-army/ColorUtil.swift
|
1
|
2714
|
//
// ColorUtil.swift
// swift-army
//
// Created by @apradanas on 4/29/15.
// Copyright (c) 2015 @apradanas. All rights reserved.
//
import Foundation
public extension UIColor {
/**
Initialize with String color code.
*/
convenience init(rgbaString rgba: String) {
var hex: String = rgba
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = advance(rgba.startIndex, 1)
hex = rgba.substringFromIndex(index)
}
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue) {
switch (hex.length) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8")
}
} else {
println("Scan hex error")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
/**
Initialize with UInt color code.
*/
convenience init(rgbaUInt rgba: UInt) {
var colorStr = String(format: "%0X", rgba)
if rgba <= 0xFFF {
colorStr = String(format: "%03X", rgba)
} else if rgba <= 0xFFFF {
colorStr = String(format: "%04X", rgba)
} else if rgba <= 0xFFFFFF {
colorStr = String(format: "%06X", rgba)
} else if rgba <= 0xFFFFFFFF {
colorStr = String(format: "%08X", rgba)
}
self.init(rgbaString: colorStr)
}
}
|
mit
|
8d53284d3351a67c14bb166ca4e7e83f
| 34.25974 | 105 | 0.488578 | 3.916306 | false | false | false | false |
biohazardlover/NintendoEverything
|
Pods/ImageViewer/ImageViewer/Source/VideoViewController.swift
|
2
|
6975
|
//
// ImageViewController.swift
// ImageViewer
//
// Created by Kristian Angyal on 01/08/2016.
// Copyright © 2016 MailOnline. All rights reserved.
//
import UIKit
import AVFoundation
extension VideoView: ItemView {}
class VideoViewController: ItemBaseController<VideoView> {
fileprivate let swipeToDismissFadeOutAccelerationFactor: CGFloat = 6
let videoURL: URL
let player: AVPlayer
unowned let scrubber: VideoScrubber
let fullHDScreenSizeLandscape = CGSize(width: 1920, height: 1080)
let fullHDScreenSizePortrait = CGSize(width: 1080, height: 1920)
let embeddedPlayButton = UIButton.circlePlayButton(70)
private var autoPlayStarted: Bool = false
private var autoPlayEnabled: Bool = false
init(index: Int, itemCount: Int, fetchImageBlock: @escaping FetchImageBlock, videoURL: URL, scrubber: VideoScrubber, configuration: GalleryConfiguration, isInitialController: Bool = false) {
self.videoURL = videoURL
self.scrubber = scrubber
self.player = AVPlayer(url: self.videoURL)
///Only those options relevant to the paging VideoViewController are explicitly handled here, the rest is handled by ItemViewControllers
for item in configuration {
switch item {
case .videoAutoPlay(let enabled):
autoPlayEnabled = enabled
default: break
}
}
super.init(index: index, itemCount: itemCount, fetchImageBlock: fetchImageBlock, configuration: configuration, isInitialController: isInitialController)
}
override func viewDidLoad() {
super.viewDidLoad()
if isInitialController == true { embeddedPlayButton.alpha = 0 }
embeddedPlayButton.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleBottomMargin, .flexibleRightMargin]
self.view.addSubview(embeddedPlayButton)
embeddedPlayButton.center = self.view.boundsCenter
embeddedPlayButton.addTarget(self, action: #selector(playVideoInitially), for: UIControlEvents.touchUpInside)
self.itemView.player = player
self.itemView.contentMode = .scaleAspectFill
}
override func viewWillAppear(_ animated: Bool) {
self.player.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
self.player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)
UIApplication.shared.beginReceivingRemoteControlEvents()
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
self.player.removeObserver(self, forKeyPath: "status")
self.player.removeObserver(self, forKeyPath: "rate")
UIApplication.shared.endReceivingRemoteControlEvents()
super.viewWillDisappear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
performAutoPlay()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.player.pause()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let isLandscape = itemView.bounds.width >= itemView.bounds.height
itemView.bounds.size = aspectFitSize(forContentOfSize: isLandscape ? fullHDScreenSizeLandscape : fullHDScreenSizePortrait, inBounds: self.scrollView.bounds.size)
itemView.center = scrollView.boundsCenter
}
@objc func playVideoInitially() {
self.player.play()
UIView.animate(withDuration: 0.25, animations: { [weak self] in
self?.embeddedPlayButton.alpha = 0
}, completion: { [weak self] _ in
self?.embeddedPlayButton.isHidden = true
})
}
override func closeDecorationViews(_ duration: TimeInterval) {
UIView.animate(withDuration: duration, animations: { [weak self] in
self?.embeddedPlayButton.alpha = 0
self?.itemView.previewImageView.alpha = 1
})
}
override func presentItem(alongsideAnimation: () -> Void, completion: @escaping () -> Void) {
let circleButtonAnimation = {
UIView.animate(withDuration: 0.15, animations: { [weak self] in
self?.embeddedPlayButton.alpha = 1
})
}
super.presentItem(alongsideAnimation: alongsideAnimation) {
circleButtonAnimation()
completion()
}
}
override func displacementTargetSize(forSize size: CGSize) -> CGSize {
let isLandscape = itemView.bounds.width >= itemView.bounds.height
return aspectFitSize(forContentOfSize: isLandscape ? fullHDScreenSizeLandscape : fullHDScreenSizePortrait, inBounds: rotationAdjustedBounds().size)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "rate" || keyPath == "status" {
fadeOutEmbeddedPlayButton()
}
else if keyPath == "contentOffset" {
handleSwipeToDismissTransition()
}
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
func handleSwipeToDismissTransition() {
guard let _ = swipingToDismiss else { return }
embeddedPlayButton.center.y = view.center.y - scrollView.contentOffset.y
}
func fadeOutEmbeddedPlayButton() {
if player.isPlaying() && embeddedPlayButton.alpha != 0 {
UIView.animate(withDuration: 0.3, animations: { [weak self] in
self?.embeddedPlayButton.alpha = 0
})
}
}
override func remoteControlReceived(with event: UIEvent?) {
if let event = event {
if event.type == UIEventType.remoteControl {
switch event.subtype {
case .remoteControlTogglePlayPause:
if self.player.isPlaying() {
self.player.pause()
}
else {
self.player.play()
}
case .remoteControlPause:
self.player.pause()
case .remoteControlPlay:
self.player.play()
case .remoteControlPreviousTrack:
self.player.pause()
self.player.seek(to: CMTime(value: 0, timescale: 1))
self.player.play()
default:
break
}
}
}
}
private func performAutoPlay() {
guard autoPlayEnabled else { return }
guard autoPlayStarted == false else { return }
autoPlayStarted = true
embeddedPlayButton.isHidden = true
scrubber.play()
}
}
|
mit
|
e18de3b395e4270735b3d4e9062bc2fe
| 28.803419 | 194 | 0.634786 | 5.27534 | false | false | false | false |
raptorxcz/Rubicon
|
Generator/Syntactic analysis/Parser/ClosureTypeParser.swift
|
1
|
4368
|
//
// ClosureTypeParser.swift
// Generator
//
// Created by Jan Halousek on 10.09.18.
// Copyright © 2018 Kryštof Matěj. All rights reserved.
//
public enum ClosureTypeParserError: Error {
case invalidStartToken
case missingClosureArrow
case missingClosureReturnType
case missingEndingBracket
}
public class ClosureTypeParser {
private let storage: Storage
public init(storage: Storage) {
self.storage = storage
}
public func parse() throws -> Type {
guard isFirstTokenValidForClosure() else {
throw ClosureTypeParserError.invalidStartToken
}
return try parseClosure()
}
private func parseClosure() throws -> Type {
let prefix = try parsePrefix()
guard try parseIsLeftBracket() else {
return try parseSimpleTypeClosure(prefix: prefix)
}
let hasBoundingBrackets = try parseIsLeftBracket()
let parametersTypes = try parseParametersList()
let isThrowing = try parseIsThrowing()
try parseArrow()
let returnType = try parseSimpleType()
if hasBoundingBrackets {
try parseRightBracket()
}
var isOptional = false
if hasBoundingBrackets {
isOptional = try parseIsOptional()
}
let name = makeClosureName(parameters: parametersTypes, returnType: returnType, isOptional: isOptional, isThrowing: isThrowing)
return Type(name: name, isOptional: isOptional, isClosure: true, prefix: prefix)
}
private func parseSimpleTypeClosure(prefix: TypePrefix?) throws -> Type {
var simpleType = try parseSimpleType()
simpleType.isClosure = true
simpleType.prefix = prefix
return simpleType
}
private func parseParametersList() throws -> [Type] {
var types = [Type]()
while !isCurrentTokenRightBracket() {
types.append(try parseSimpleType())
if !(try parseIsComma()) {
break
}
}
_ = try storage.next()
return types
}
private func parseSimpleType() throws -> Type {
return try SimpleTypeParser(storage: storage).parse()
}
private func isFirstTokenValidForClosure() -> Bool {
let currentToken = storage.current
return (
currentToken == .escaping ||
currentToken == .autoclosure ||
currentToken == .leftBracket
)
}
private func isCurrentTokenRightBracket() -> Bool {
return storage.current == .rightBracket
}
private func parsePrefix() throws -> TypePrefix? {
if try parseIs(token: .escaping) {
return .escaping
} else if try parseIs(token: .autoclosure) {
return .autoclosure
}
return nil
}
private func parseRightBracket() throws {
_ = try parseIs(token: .rightBracket)
}
private func parseIsLeftBracket() throws -> Bool {
return try parseIs(token: .leftBracket)
}
private func parseIsThrowing() throws -> Bool {
return try parseIs(token: .throws)
}
private func parseIsOptional() throws -> Bool {
return try parseIs(token: .questionMark)
}
private func parseArrow() throws {
guard case .arrow = storage.current else {
throw ClosureTypeParserError.missingClosureArrow
}
_ = try storage.next()
}
private func parseIsComma() throws -> Bool {
return try parseIs(token: .comma)
}
private func parseIs(token: Token) throws -> Bool {
guard storage.current == token else {
return false
}
_ = try storage.next()
return true
}
private func makeClosureName(parameters: [Type], returnType: Type, isOptional: Bool, isThrowing: Bool) -> String {
let parametersString = parameters
.map { TypeStringFactory.makeSimpleString($0) }
.joined(separator: ", ")
let returnTypeString = TypeStringFactory.makeSimpleString(returnType)
var name = (isOptional ? "(" : "")
name += "(" + parametersString + ")"
name += (isThrowing ? " throws" : "")
name += " -> "
name += returnTypeString
if isOptional {
name += ")"
}
return name
}
}
|
mit
|
89e4a9bf04aeb72ea33c25fbe49af1df
| 27.344156 | 135 | 0.60504 | 4.88255 | false | false | false | false |
chiswicked/ParseTemplate-Swift
|
ParseTemplate-Swift/LogInViewController.swift
|
1
|
8051
|
//
// ViewController.swift
// ParseTemplate-Swift
//
// Created by Norbert Metz on 29/11/2015.
// Copyright © 2015 Norbert Metz. 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 Parse
import ParseFacebookUtilsV4
import UIKit
class LogInViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var parseLoginButton: UIButton!
@IBOutlet weak var facebookLoginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
emailTextField.delegate = self
passwordTextField.delegate = self
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let token = PFUser.currentUser()?.sessionToken
print("Token: \(token)")
if let user = PFUser.currentUser() {
if user.authenticated {
print("User authenticated")
performSegueWithIdentifier("fromLogInToMain", sender: nil)
}
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
switch textField {
case emailTextField:
passwordTextField.becomeFirstResponder()
case passwordTextField:
passwordTextField.resignFirstResponder()
default: break
}
return true
}
@IBAction func loginButtonTapped(sender: UIButton) {
print("Log In Button Tapped")
// Start activity indicator
let activityIndicator = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
activityIndicator.labelText = "Authenticating"
activityIndicator.detailsLabelText = "Please wait"
defer {
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
}
switch sender {
case parseLoginButton:
dismissKeyboard()
// Validate email
guard !emailTextField.text!.isEmpty else {
emailTextField.shake()
return
}
// Validate password
guard !passwordTextField.text!.isEmpty else {
passwordTextField.shake()
return
}
// Initiate Parse authentication process
PFUser.logInWithUsernameInBackground(emailTextField.text!, password: passwordTextField.text!) { user, error in
if let user = PFUser.currentUser() {
if user.authenticated {
// Parse login successful
print("Log in succesful: \(PFUser.currentUser())")
self.passwordTextField.text = ""
self.performSegueWithIdentifier("fromLogInToMain", sender: nil)
}
} else if let error = error {
// Parse login error
self.alert("Authentication Error", message: error.localizedDescription)
}
}
case facebookLoginButton:
// Initiate Facebook authentication process
PFFacebookUtils.logInInBackgroundWithReadPermissions(FacebookConfig.loginPermissions) { (user:PFUser?, error: NSError?) in
if let user = PFUser.currentUser() {
if user.authenticated {
// Facebook login successful
print("Log in succesful: \(PFUser.currentUser())")
self.passwordTextField.text = ""
print("New user: \(user.isNew)")
if user.isNew {
// Loggen in with Facebook for the first time (sign up)
let userDetails = FBSDKGraphRequest(graphPath: "me", parameters: FacebookConfig.userDetailsParameters)
userDetails.startWithCompletionHandler() { (connection, result, error) in
if let user = PFUser.currentUser() {
// TODO: Check if account could be linked to existing user
let userEmail = result["email"] as? String
let userFirstName = result["first_name"] as? String
let userLastName = result["last_name"] as? String
let userMarketingConsent = false
user.email = userEmail
user.setObject(userFirstName!, forKey: "firstName")
user.setObject(userLastName!, forKey: "lastName")
user.setObject(userMarketingConsent, forKey: "marketingConsent")
user.saveInBackgroundWithBlock() { (success: Bool, erro:NSError?) in
if success {
print("Successfully updated user details")
}
// TODO: Proper segueing in main thread
}
}
}
}
self.performSegueWithIdentifier("fromLogInToMain", sender: nil)
}
} else if let error = error {
// Facebook login error
self.alert("Authentication Error", message: error.localizedDescription)
}
}
default: break
}
}
@IBAction func resetPasswordButtonTapped(sender: UIButton) {
print("Password Reset Button Tapped")
performSegueWithIdentifier("fromLogInToResetPassword", sender: nil)
}
@IBAction func signUpButtonTapped(sender: UIButton) {
print("Sign Up Button Tapped")
performSegueWithIdentifier("fromLogInToSignUp", sender: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
56f9482dd674ff8e67cae2826b04ce05
| 38.655172 | 134 | 0.528696 | 6.502423 | false | false | false | false |
AvdLee/ALDataRequestView
|
Example/ALDataRequestView/ViewController.swift
|
1
|
5268
|
//
// ViewController.swift
// ALDataRequestView
//
// Created by Antoine van der Lee on 02/28/2016.
// Copyright (c) 2016 Antoine van der Lee. All rights reserved.
//
import UIKit
import ALDataRequestView
import PureLayout
import RxSwift
import ReactiveSwift
import RxCocoa
import Result
class ViewController: UIViewController {
var dataRequestView:ALDataRequestView?
var signalProducer:SignalProducer<[String], NSError>?
var dataSignalProducer:SignalProducer<Data, NSError>?
var rxDisposable:RxSwift.Disposable?
let (signal, subscriber) = Signal<[String], NSError>.pipe()
override func viewDidLoad() {
super.viewDidLoad()
dataRequestView = ALDataRequestView(forAutoLayout: ())
view.addSubview(dataRequestView!)
dataRequestView?.autoPinEdgesToSuperviewEdges()
dataRequestView?.dataSource = self
view.sendSubview(toBack: dataRequestView!)
testWithFailureCallObservable()
// testWithFailureCallSignalProducer()
// testWithFailureCallObservable()
}
deinit {
print("Deinit vc")
}
func testWithEmptySignalProducer(){
signalProducer = SignalProducer(signal).attachTo(dataRequestView: dataRequestView!)
signalProducer?.start()
delay(delay: 3.0, closure: { [weak self] () -> Void in
let emptyArray:[String] = []
self?.subscriber.send(value: emptyArray) // Send empty array
self?.subscriber.sendCompleted()
})
}
func testWithFailureCallSignalProducer(){
let request = URLRequest(url: URL(string: "http://httpbin.org/status/400")!)
dataSignalProducer = URLSession.shared
.reactive.data(with: request)
.flatMapError({ (error) -> SignalProducer<(Data, URLResponse), NSError> in
return SignalProducer(error: error as NSError)
})
.flatMap(.latest, transform: { (data, response) -> SignalProducer<Data, NSError> in
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode > 299 {
return SignalProducer(error: NSError(domain: "", code: httpResponse.statusCode, userInfo: nil))
}
return SignalProducer(value: data)
})
.attachTo(dataRequestView: dataRequestView!)
dataSignalProducer?.start()
}
func testWithFailureCallObservable(){
let request = URLRequest(url: URL(string: "http://httpbin.org/status/400")!)
rxDisposable = URLSession.shared.rx.data(request: request).attachTo(dataRequestView: dataRequestView!).subscribe()
}
@IBAction func setLoadingButtonTapped(sender: UIButton) {
dataRequestView?.changeRequestState(state: RequestState.loading)
}
@IBAction func setEmptyButtonTapped(sender: UIButton) {
dataRequestView?.changeRequestState(state: RequestState.empty)
}
@IBAction func setReloadButtonTapped(sender: UIButton) {
dataRequestView?.changeRequestState(state: RequestState.failed)
}
func delay(delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
closure()
}
}
}
extension ViewController : ALDataRequestViewDataSource {
func loadingViewForDataRequestView(dataRequestView: ALDataRequestView) -> UIView? {
let loadingView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
loadingView.startAnimating()
return loadingView
}
func reloadViewController(for dataRequestView: ALDataRequestView) -> ALDataReloadType? {
let reloadVC = ReloadViewController()
return reloadVC
}
func emptyView(for dataRequestView: ALDataRequestView) -> UIView? {
let emptyLabel = UILabel(forAutoLayout: ())
emptyLabel.text = "Data is empty"
return emptyLabel
}
func hideAnimationDuration(for dataRequestView: ALDataRequestView) -> Double {
return 0.25
}
func showAnimationDuration(for dataRequestView: ALDataRequestView) -> Double {
return 0.25
}
}
final class ReloadViewController : UIViewController, ALDataReloadType {
var retryButton:UIButton?
var statusLabel:UILabel!
init(){
super.init(nibName: nil, bundle: nil)
retryButton = UIButton(type: UIButtonType.system)
retryButton?.setTitle("Reload!", for: UIControlState.normal)
view.addSubview(retryButton!)
retryButton?.autoCenterInSuperview()
statusLabel = UILabel(forAutoLayout: ())
view.addSubview(statusLabel)
statusLabel.autoAlignAxis(toSuperviewAxis: ALAxis.vertical)
statusLabel.autoPinEdge(.bottom, to: .top, of: retryButton!)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setup(for reloadType:ReloadType){
switch reloadType.reason {
case .generalError:
statusLabel.text = "General error occured"
case .noInternetConnection:
statusLabel.text = "Your internet connection is lost"
}
}
}
|
mit
|
052adc2c0ecf79c8d4277ce41407a27d
| 32.769231 | 122 | 0.657935 | 5.109602 | false | false | false | false |
SimplicityMobile/Simplicity
|
Simplicity/LoginProviders/VKontakte.swift
|
2
|
1562
|
//
// VKontakte.swift
// Simplicity
//
// Created by Andrey Toropchin on 14.07.16.
// Copyright © 2016 Stormpath. All rights reserved.
//
/**
Class implementing VKontakte (VK.com) implicit grant flow.
## Using VKontakte in your app.
To get started, you first need to [create an application](https://vk.com/dev/) with VKontakte.
After registering your app, go into your client settings page.
Set App Bundle ID for iOS to your App Bundle in Xcode -> Target -> Bundle Identifier (e.g. com.developer.applicationName)
Finally, open up your App's Xcode project and go to the project's
info tab. Under "URL Types", add a new entry, and in the URL schemes form
field, type in `vk[CLIENT_ID_HERE]`. Then, you can initiate the login
screen by calling:
```
Simplicity.login(VKontakte()) { (accessToken, error) in
// Insert code here
}
```
*/
public class VKontakte: OAuth2 {
public init() {
guard let urlScheme = Helpers.registeredURLSchemes(filter: {$0.hasPrefix("vk")}).first,
let range = urlScheme.range(of: "\\d+", options: .regularExpression) else {
preconditionFailure("You must configure your VK URL Scheme to use VK login.")
}
let clientId = urlScheme.substring(with: range)
let authorizationEndpoint = URL(string: "https://oauth.vk.com/authorize")!
let redirectEndpoint = URL(string: urlScheme + "://authorize")!
super.init(clientId: clientId, authorizationEndpoint: authorizationEndpoint, redirectEndpoint: redirectEndpoint, grantType: .Implicit)
}
}
|
apache-2.0
|
488838879193021a9d83e5fffb253fff
| 36.166667 | 142 | 0.693786 | 4.023196 | false | false | false | false |
sbooth/SFBAudioEngine
|
SimplePlayer-macOS/AppDelegate.swift
|
1
|
3965
|
//
// Copyright (c) 2009 - 2022 Stephen F. Booth <[email protected]>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
import os.log
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject {
@IBOutlet weak var playerWindowController: PlayerWindowController!
@IBOutlet weak var openURLPanel: NSWindow!
@IBOutlet weak var openURLPanelTextField: NSTextField!
@IBAction func openFile(_ sender: AnyObject?) {
let openPanel = NSOpenPanel()
openPanel.allowsMultipleSelection = false
openPanel.canChooseDirectories = false
openPanel.allowedFileTypes = PlayerWindowController.supportedPathExtensions
if(openPanel.runModal() == .OK) {
if let url = openPanel.urls.first {
playerWindowController.play(url: url)
}
}
}
@IBAction func openURL(_ sender: AnyObject?) {
openURLPanel.center()
openURLPanel.makeKeyAndOrderFront(sender)
}
@IBAction func addFiles(_ sender: AnyObject?) {
let openPanel = NSOpenPanel()
openPanel.allowsMultipleSelection = true
openPanel.canChooseDirectories = false
openPanel.allowedFileTypes = PlayerWindowController.supportedPathExtensions
if(openPanel.runModal() == .OK) {
playerWindowController.addToPlaylist(urls: openPanel.urls)
}
}
@IBAction func openURLPanelOpenAction(_ sender: AnyObject?) {
openURLPanel.orderOut(sender)
if let url = URL(string: openURLPanelTextField.stringValue) {
playerWindowController.play(url: url)
}
}
@IBAction func openURLPanelCancelAction(_ sender: AnyObject?) {
openURLPanel.orderOut(sender)
}
@IBAction func analyzeFiles(_ sender: AnyObject?) {
let openPanel = NSOpenPanel()
openPanel.allowsMultipleSelection = true
openPanel.canChooseDirectories = false
openPanel.allowedFileTypes = PlayerWindowController.supportedPathExtensions
if openPanel.runModal() == .OK {
do {
let rg = try ReplayGainAnalyzer.analyzeAlbum(openPanel.urls)
os_log("Album gain %.2f dB, peak %.8f; Tracks: [%{public}@]", rg.0.gain, rg.0.peak, rg.1.map({ (url, replayGain) in String(format: "\"%@\" gain %.2f dB, peak %.8f", FileManager.default.displayName(atPath: url.lastPathComponent), replayGain.gain, replayGain.peak) }).joined(separator: ", "))
let alert = NSAlert()
alert.messageText = "Replay Gain Analysis Complete"
alert.informativeText = "Check log for details."
alert.runModal()
} catch let error {
NSApp.presentError(error)
}
}
}
@IBAction func exportWAVEFile(_ sender: AnyObject?) {
let openPanel = NSOpenPanel()
openPanel.allowsMultipleSelection = false
openPanel.canChooseDirectories = false
openPanel.allowedFileTypes = PlayerWindowController.supportedPathExtensions
if openPanel.runModal() == .OK, let url = openPanel.url {
let destURL = url.deletingPathExtension().appendingPathExtension("wav")
if FileManager.default.fileExists(atPath: destURL.path) {
let alert = NSAlert()
alert.messageText = "Do you want to overwrite the existing file?"
alert.informativeText = "A file with the same name already exists."
alert.addButton(withTitle: "Overwrite")
alert.addButton(withTitle: "Cancel")
if alert.runModal() != NSApplication.ModalResponse.alertFirstButtonReturn {
return
}
}
do {
try AudioConverter.convert(url, to: destURL)
// Silently fail if metadata can't be copied
try? AudioFile.copyMetadata(from: url, to: destURL)
} catch let error {
try? FileManager.default.trashItem(at: destURL, resultingItemURL: nil)
NSApp.presentError(error)
}
}
}
}
// MARK: - NSApplicationDelegate
extension AppDelegate: NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
playerWindowController.showWindow(self)
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
true
}
func application(_ application: NSApplication, open urls: [URL]) {
if let url = urls.first {
playerWindowController.play(url: url)
}
}
}
|
mit
|
79e06960c7c76e4b1b0ec31ddc125ca3
| 29.976563 | 294 | 0.737201 | 4.0091 | false | false | false | false |
devpunk/velvet_room
|
Source/View/SaveData/VSaveDataBarBack.swift
|
1
|
1186
|
import UIKit
final class VSaveDataBarBack:View<ArchSaveData>
{
weak var layoutBottom:NSLayoutConstraint!
let kWidth:CGFloat = 60
let kHeight:CGFloat = 50
required init(controller:CSaveData)
{
super.init(controller:controller)
factoryViews()
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: selectors
@objc
private func selectorBack(sender button:UIButton)
{
controller.back()
}
//MARK: private
private func factoryViews()
{
let button:UIButton = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(
#imageLiteral(resourceName: "assetGenericBack"),
for:UIControlState.normal)
button.imageView!.clipsToBounds = true
button.imageView!.contentMode = UIViewContentMode.center
button.addTarget(
self,
action:#selector(selectorBack(sender:)),
for:UIControlEvents.touchUpInside)
addSubview(button)
NSLayoutConstraint.equals(
view:button,
toView:self)
}
}
|
mit
|
e4e1f352b8efa562c87d0cca28e8a2f6
| 22.72 | 64 | 0.604553 | 5.22467 | false | false | false | false |
shorlander/firefox-ios
|
Storage/SQL/SQLiteMetadata.swift
|
1
|
2523
|
/* 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 Deferred
import Shared
/// The sqlite-backed implementation of the metadata protocol containing images and content for pages.
open class SQLiteMetadata {
let db: BrowserDB
required public init(db: BrowserDB) {
self.db = db
}
}
extension SQLiteMetadata: Metadata {
// A cache key is a conveninent, readable identifier for a site in the metadata database which helps
// with deduping entries for the same page.
typealias CacheKey = String
/// Persists the given PageMetadata object to browser.db in the page_metadata table.
///
/// - parameter metadata: Metadata object
/// - parameter pageURL: URL of page metadata was fetched from
/// - parameter expireAt: Expiration/TTL interval for when this metadata should expire at.
///
/// - returns: Deferred on success
public func storeMetadata(_ metadata: PageMetadata, forPageURL pageURL: URL,
expireAt: UInt64) -> Success {
guard let cacheKey = SQLiteMetadata.cacheKeyForURL(pageURL as URL) else {
return succeed()
}
// Replace any matching cache_key entries if they exist
let selectUniqueCacheKey = "COALESCE((SELECT cache_key FROM \(TablePageMetadata) WHERE cache_key = ?), ?)"
let args: Args = [cacheKey, cacheKey, metadata.siteURL, metadata.mediaURL, metadata.title,
metadata.type, metadata.description, metadata.providerName,
expireAt]
let insert =
"INSERT OR REPLACE INTO \(TablePageMetadata)" +
"(cache_key, site_url, media_url, title, type, description, provider_name, expired_at) " +
"VALUES ( \(selectUniqueCacheKey), ?, ?, ?, ?, ?, ?, ?)"
return self.db.run(insert, withArgs: args)
}
/// Purges any metadata items living in page_metadata that are expired.
///
/// - returns: Deferred on success
public func deleteExpiredMetadata() -> Success {
let sql = "DELETE FROM page_metadata WHERE expired_at <= (CAST(strftime('%s', 'now') AS LONG)*1000)"
return self.db.run(sql)
}
static func cacheKeyForURL(_ url: URL) -> CacheKey? {
var key = url.normalizedHost ?? ""
key = key + url.path + (url.query ?? "")
return key
}
}
|
mpl-2.0
|
d14ef8c142375ed7a420370cd6526b9a
| 39.047619 | 114 | 0.644075 | 4.473404 | false | false | false | false |
wendru/simple-twitter-client
|
Twittah/TweetDetailViewController.swift
|
1
|
4715
|
//
// TweetDetailViewController.swift
// Twittah
//
// Created by Andrew Wen on 2/23/15.
// Copyright (c) 2015 wendru. All rights reserved.
//
import UIKit
class TweetDetailViewController: UIViewController {
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var handleLabel: UILabel!
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet weak var timestampLabel: UILabel!
@IBOutlet weak var textField: UITextView!
@IBOutlet weak var replyButton: UIBarButtonItem!
@IBOutlet weak var faveImage: FaveImageView!
@IBOutlet weak var retweetImage: RetweetImageView!
@IBOutlet weak var replyImage: ReplyImageView!
var tweet: Tweet?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setUp()
hydrate()
}
func setUp() {
replyButton.tintColor = UIColor.whiteColor()
textField.hidden = true
}
func hydrate() {
profileImage.setImageWithURL(NSURL(string: tweet!.user!.profileImageUrl!))
profileImage.layer.cornerRadius = 4
profileImage.clipsToBounds = true
nameLabel.text = tweet!.user?.name!
let sn = tweet!.user?.screenname!
handleLabel.text = NSString(format: "@%@", sn!)
contentLabel.text = tweet!.text!
timestampLabel.text = tweet!.createdAtString
let faved = tweet?.favorited!
let retweeted = tweet?.retweeted!
faveImage.setFaved(faved!)
retweetImage.setRetweeted(retweeted!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onTimelineButtonTap(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func retweetButtonTapped(sender: AnyObject) {
var params = NSMutableDictionary()
params["id"] = tweet?.id
TwitterClient.sharedInstance.retweetWithParams(params, completion: { (response, error) -> () in
if error == nil {
self.retweetImage.setRetweeted(true)
} else {
UIAlertView(
title: nil,
message: "Unable to retweet",
delegate: self,
cancelButtonTitle: "Well damn...")
.show()
}
})
}
@IBAction func favButtonTapped(sender: AnyObject) {
var params = NSMutableDictionary()
params["id"] = tweet?.id
TwitterClient.sharedInstance.createFavoriteWithParams(params, completion: { (response, error) -> () in
if error == nil {
self.faveImage.setFaved(true)
} else {
UIAlertView(
title: nil,
message: "Unable to mark tweet as favorite",
delegate: self,
cancelButtonTitle: "Well damn...")
.show()
}
})
}
@IBAction func onReplyButtonTap(sender: UIBarButtonItem) {
var params = NSMutableDictionary()
params["status"] = textField.text!
params["in_reply_to_status_id"] = tweet?.id
TwitterClient.sharedInstance.updateStatusWithParams(params, completion: { (response, error) -> () in
if error == nil {
self.replyImage.setReplied(true)
self.replyButton.tintColor = UIColor.whiteColor()
self.resignFirstResponder()
self.textField.editable = false
} else {
UIAlertView(
title: nil,
message: "Unable to reply",
delegate: self,
cancelButtonTitle: "Well damn...")
.show()
}
})
}
@IBAction func replyTapped(sender: AnyObject) {
replyButton.tintColor = UIColor.grayColor()
textField.hidden = false
let sn = tweet?.user?.screenname!
textField.text = NSString(format: "@%@ ", sn!)
textField.becomeFirstResponder()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
gpl-2.0
|
67db382feacedd23ff3a778fa48c1bc4
| 30.858108 | 110 | 0.576458 | 5.244716 | false | false | false | false |
joearms/joearms.github.io
|
includes/swift/experiment1.swift
|
1
|
424
|
// experiment1.swift
// run with:
// $ swift experiment1.swift
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
let window = NSWindow()
func applicationDidFinishLaunching(aNotification: NSNotification) {
window.makeKeyAndOrderFront(window)
window.level = 1
}
}
let app = NSApplication.sharedApplication()
let controller = AppDelegate()
app.delegate = controller
app.run()
|
mit
|
ac41ca8c5e4d0d38e066805d2e9cea11
| 19.190476 | 71 | 0.726415 | 4.608696 | false | false | false | false |
antonio081014/LeeCode-CodeBase
|
Swift/convert-binary-number-in-a-linked-list-to-integer.swift
|
2
|
756
|
/**
* https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/
*
*
*/
// Date: Sun Nov 1 08:47:17 PST 2020
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
func getDecimalValue(_ head: ListNode?) -> Int {
var node = head
var result = 0
while let cnode = node {
result = (result << 1) + cnode.val
node = cnode.next
}
return result
}
}
|
mit
|
0507fe27185f0bc932328a6d3579a146
| 27.037037 | 87 | 0.555556 | 3.330396 | false | false | false | false |
southfox/JFAlgo
|
Example/JFAlgo/MissingIntegerViewController.swift
|
1
|
2701
|
//
// MissingIntegerViewController.swift
// JFAlgo
//
// Created by Javier Fuchs on 9/8/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
import JFAlgo
/// Find the minimal positive integer not occurring in a given sequence.
/// Write a function:
///
/// public func solution(inout A : [Int]) -> Int
/// that, given a non-empty zero-indexed array A of N integers, returns the minimal positive integer (greater than 0) that does not occur in A.
///
/// For example, given:
///
/// A[0] = 1
/// A[1] = 3
/// A[2] = 6
/// A[3] = 4
/// A[4] = 1
/// A[5] = 2
/// the function should return 5.
///
/// Assume that:
///
/// N is an integer within the range [1..100,000];
/// each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
/// Complexity:
///
/// expected worst-case time complexity is O(N);
/// expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
/// Elements of input arrays can be modified.
class MissingIntegerViewController : BaseCollectionViewController {
let missingInteger = MissingInteger()
@IBAction override func runAction() {
super.runAction()
guard let text = numberField.text,
number = Int(text) else {
return
}
if missingInteger.checkDomainGenerator(number) == false {
self.showAlert(missingInteger.domainErrorMessage(), completion: closure)
return
}
guard var array = A else {
self.showAlert("\(number) generates a nil array.", completion: closure)
return
}
let solution = missingInteger.solution(&array, N: number)
if solution != 0 {
self.showAlert("SUCCESS: array missing integer is \(solution).", completion: closure)
}
else {
self.showAlert("FAILURE: array has no missing integer", completion: closure)
}
}
@IBAction override func generateAction(sender: AnyObject) {
super.generateAction(sender)
guard let text = numberField.text,
number = Int(text) else {
return
}
if missingInteger.checkDomainGenerator(number) == false {
self.showAlert(missingInteger.domainErrorMessage(), completion: closure)
return
}
guard let array = missingInteger.generateDomain(number) else {
self.showAlert("\(number) generates a nil array.", completion: closure)
return
}
A = array
self.reload()
}
}
|
mit
|
c74221595ccc842fb07428f7a90f50bb
| 27.702128 | 143 | 0.603039 | 4.386992 | false | false | false | false |
superk589/CGSSGuide
|
DereGuide/Toolbox/Colleague/Controller/ColleagueViewController.swift
|
2
|
7707
|
//
// ColleagueViewController.swift
// DereGuide
//
// Created by zzk on 2017/8/2.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
import CloudKit
import CoreData
import EasyTipView
import ZKDrawerController
class ColleagueViewController: BaseTableViewController {
lazy var filterController: ColleagueFilterController = {
let vc = ColleagueFilterController(style: .grouped)
vc.delegate = self
return vc
}()
private var refresher = CGSSRefreshHeader()
private var loader = CGSSRefreshFooter()
override func viewDidLoad() {
super.viewDidLoad()
prepareNavigationBar()
tableView.register(ColleagueTableViewCell.self, forCellReuseIdentifier: ColleagueTableViewCell.description())
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 159
tableView.tableFooterView = UIView()
tableView.backgroundColor = .white
tableView.separatorStyle = .none
tableView.mj_header = refresher
refresher.refreshingBlock = { [weak self] in
self?.fetchLatestProfiles()
}
tableView.mj_footer = loader
loader.refreshingBlock = { [weak self] in
self?.fetchMore {
self?.loader.state = self?.cursor == nil ? .noMoreData : .idle
}
}
refresher.beginRefreshing()
}
var remote = ProfileRemote()
var cursor: CKQueryOperation.Cursor?
var profiles = [Profile]()
lazy var currentSetting: ColleagueFilterController.FilterSetting = self.filterController.setting
private var isFetching: Bool = false
@objc func fetchLatestProfiles() {
isFetching = true
remote.fetchRecordsWith([currentSetting.predicate], [remote.defaultSortDescriptor], resultsLimit: Config.cloudKitFetchLimits) { (remoteProfiles, cursor, error) in
DispatchQueue.main.async {
if error != nil {
UIAlertController.showHintMessage(NSLocalizedString("获取数据失败,请检查您的网络并确保iCloud处于登录状态", comment: ""), in: nil)
} else {
self.profiles = remoteProfiles.map { Profile.insert(remoteRecord: $0, into: self.childContext) }
}
self.isFetching = false
self.refresher.endRefreshing()
self.cursor = cursor
self.loader.state = cursor == nil ? .noMoreData : .idle
self.tableView.reloadData()
}
}
}
func fetchMore(completion: @escaping () -> ()) {
guard let cursor = cursor else {
completion()
return
}
isFetching = true
remote.fetchRecordsWith(cursor: cursor, resultsLimit: Config.cloudKitFetchLimits) { (remoteProfiles, cursor, error) in
DispatchQueue.main.async {
self.isFetching = false
if error != nil {
UIAlertController.showHintMessage(NSLocalizedString("获取数据失败,请检查您的网络并确保iCloud处于登录状态", comment: ""), in: nil)
} else {
let moreProfiles = remoteProfiles.map { Profile.insert(remoteRecord: $0, into: self.childContext) }
self.profiles.append(contentsOf: moreProfiles)
self.cursor = cursor
self.tableView.reloadData()
// self.tableView.beginUpdates()
// self.tableView.insertRows(at: moreProfiles.enumerated().map { IndexPath.init(row: $0.offset + self.profiles.count - moreProfiles.count, section: 0) }, with: .automatic)
// self.tableView.endUpdates()
}
completion()
}
}
self.cursor = nil
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ColleagueTableViewCell.description(), for: indexPath) as! ColleagueTableViewCell
cell.setup(profiles[indexPath.row])
cell.delegate = self
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return profiles.count
}
var context: NSManagedObjectContext {
return CoreDataStack.default.viewContext
}
lazy var profile: Profile = Profile.findOrCreate(in: self.context, configure: { _ in })
lazy var childContext: NSManagedObjectContext = self.context.newChildContext()
private var item: UIBarButtonItem!
private func prepareNavigationBar() {
let compose = UIBarButtonItem(barButtonSystemItem: .compose, target: self, action: #selector(composeAction))
let filter = UIBarButtonItem(image: #imageLiteral(resourceName: "798-filter-toolbar"), style: .plain, target: self, action: #selector(filterAction))
navigationItem.rightBarButtonItems = [compose, filter]
navigationItem.title = NSLocalizedString("寻找同僚", comment: "")
}
@objc func composeAction() {
// let vc = ColleagueComposeViewController()
// vc.setup(parentProfile: profile)
// vc.delegate = self
let vc = DMComposingStepOneController()
if UIDevice.current.userInterfaceIdiom == .pad {
let nav = BaseNavigationController(rootViewController: vc)
let drawer = ZKDrawerController(center: nav)
drawer.modalPresentationStyle = .formSheet
present(drawer, animated: true, completion: nil)
} else {
navigationController?.pushViewController(vc, animated: true)
}
}
@objc func filterAction() {
let nav = BaseNavigationController(rootViewController: filterController)
let drawer = ZKDrawerController(center: nav)
drawer.modalPresentationStyle = .formSheet
present(drawer, animated: true, completion: nil)
}
}
extension ColleagueViewController: ColleagueTableViewCellDelegate {
func colleagueTableViewCell(_ cell: ColleagueTableViewCell, didTap cardIcon: CGSSCardIconView) {
if let cardID = cardIcon.cardID, let card = CGSSDAO.shared.findCardById(cardID) {
let vc = CDTabViewController(card: card)
navigationController?.pushViewController(vc, animated: true)
}
}
@nonobjc func colleagueTableViewCell(_ cell: ColleagueTableViewCell, didTap gameID: String) {
UIPasteboard.general.string = gameID
UIAlertController.showHintMessage(NSLocalizedString("已复制ID到剪贴板", comment: ""), in: nil)
}
}
extension ColleagueViewController: ColleagueComposeViewControllerDelegate {
func didSave(_ colleagueComposeViewController: ColleagueComposeViewController) {
}
func didPost(_ colleagueComposeViewController: ColleagueComposeViewController) {
refresher.beginRefreshing()
// fetchLatestProfiles()
}
func didRevoke(_ colleagueComposeViewController: ColleagueComposeViewController) {
refresher.beginRefreshing()
// fetchLatestProfiles()
}
}
extension ColleagueViewController: ColleagueFilterControllerDelegate {
func didDone(_ colleagueFilterController: ColleagueFilterController) {
currentSetting = filterController.setting
refresher.beginRefreshing()
// fetchLatestProfiles()
}
}
|
mit
|
5715dcf46f9ba14d6e1f4ac2051f148a
| 36.399015 | 190 | 0.645548 | 5.297976 | false | false | false | false |
xingfukun/IQKeyboardManager
|
Demo/Swift_Demo/ViewController/ScrollViewController.swift
|
18
|
2300
|
//
// ScrollViewController.swift
// IQKeyboard
//
// Created by Iftekhar on 23/09/14.
// Copyright (c) 2014 Iftekhar. All rights reserved.
//
import Foundation
import UIKit
class ScrollViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UITextViewDelegate {
@IBOutlet private var scrollViewDemo : UIScrollView!
@IBOutlet private var simpleTableView : UITableView!
@IBOutlet private var scrollViewOfTableViews : UIScrollView!
@IBOutlet private var tableViewInsideScrollView : UITableView!
@IBOutlet private var scrollViewInsideScrollView : UIScrollView!
@IBOutlet private var topTextField : UITextField!
@IBOutlet private var bottomTextField : UITextField!
@IBOutlet private var topTextView : UITextView!
@IBOutlet private var bottomTextView : UITextView!
override func viewDidLoad() {
super.viewDidLoad()
scrollViewDemo.contentSize = CGSizeMake(0, 321)
scrollViewInsideScrollView.contentSize = CGSizeMake(0,321)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "\(indexPath.section) \(indexPath.row)"
var cell : UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(identifier) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: identifier)
cell?.selectionStyle = UITableViewCellSelectionStyle.None
cell?.backgroundColor = UIColor.clearColor()
let textField = UITextField(frame: CGRectInset(cell!.contentView.bounds, 5, 5))
textField.autoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleWidth
textField.placeholder = identifier
textField.borderStyle = UITextBorderStyle.RoundedRect
cell?.contentView.addSubview(textField)
}
return cell!
}
override func shouldAutorotate() -> Bool {
return true
}
}
|
mit
|
05c150c0e17e8ed5149d155e9d313ad2
| 34.9375 | 154 | 0.700435 | 5.989583 | false | false | false | false |
Alliants/ALAccordion
|
Example/ALAccordion Example/Views/Headers/ALDoubleLineHeaderView.swift
|
1
|
3175
|
//
// ALDoubleLineHeaderView.swift
// ALAccordion Example
//
// Created by Sam Williams on 21/04/2015.
// Copyright (c) 2015 Alliants Ltd. All rights reserved.
//
// http://alliants.com
//
import UIKit
class ALDoubleLineHeaderView: UIView
{
//
// MARK: - Properties
//
let topSeparator: ALSeparatorView =
{
let view = ALSeparatorView()
view.separatorColor = UIColor.white.withAlphaComponent(0.5)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let bottomSeparator: ALSeparatorView =
{
let view = ALSeparatorView()
view.separatorColor = UIColor.white.withAlphaComponent(0.5)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let titleLabel: UILabel =
{
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 17.0)
label.textColor = UIColor.white
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let detailLabel: UILabel =
{
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14.0)
label.textColor = UIColor.white
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
fileprivate var titleLabel_bottom: NSLayoutConstraint!
//
// MARK: - Initialisers
//
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
override init(frame: CGRect)
{
super.init(frame: frame)
self.commonInit()
}
override func awakeFromNib()
{
super.awakeFromNib()
self.commonInit()
}
func commonInit()
{
// Create and setup views
self.addSubview(self.topSeparator)
self.addSubview(self.titleLabel)
self.addSubview(self.detailLabel)
self.addSubview(self.bottomSeparator)
// Setup constraints
let views = ["topSeparator": self.topSeparator, "titleLabel": self.titleLabel, "detailLabel": self.detailLabel, "bottomSeparator": self.bottomSeparator]
let vertical = NSLayoutConstraint.constraints(withVisualFormat: "V:|[topSeparator(1)]-(15)-[titleLabel]-1-[detailLabel]-(15)-[bottomSeparator(1)]|", options: [], metrics: nil, views: views)
let horizontal_topSeparator = NSLayoutConstraint.constraints(withVisualFormat: "H:|[topSeparator]|", options: [], metrics: nil, views: views)
let horizontal_titleLabel = NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[titleLabel]-15-|", options: [], metrics: nil, views: views)
let horizontal_detailLabel = NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[detailLabel]-15-|", options: [], metrics: nil, views: views)
let horizontal_bottomSeparator = NSLayoutConstraint.constraints(withVisualFormat: "H:|[bottomSeparator]|", options: [], metrics: nil, views: views)
self.addConstraints(vertical + horizontal_topSeparator + horizontal_titleLabel + horizontal_detailLabel + horizontal_bottomSeparator)
}
}
|
mit
|
a9c0a639632bc7c852e3ff238a0ae4ff
| 29.238095 | 197 | 0.661102 | 4.937792 | false | false | false | false |
kbelter/SnazzyList
|
SnazzyList/Classes/src/Helpers/extensions/UILabel.swift
|
1
|
3818
|
//
// UILabel.swift
// Noteworth2
//
// Created by Kevin on 12/20/18.
// Copyright © 2018 Noteworth. All rights reserved.
//
import UIKit
extension UILabel {
convenience init(font: UIFont, textColor: UIColor, textAlignment: NSTextAlignment) {
self.init(frame: CGRect.zero)
self.font = font
self.textColor = textColor
self.textAlignment = textAlignment
self.translatesAutoresizingMaskIntoConstraints = false
}
func addNormalLineSpacing(lineSpacing: CGFloat) {
let oldText = self.text ?? ""
let oldFont = self.font!
let oldColor = self.textColor!
let oldAlignment = self.textAlignment
let style = NSMutableParagraphStyle()
style.alignment = oldAlignment
style.lineSpacing = lineSpacing
let attributedString = NSMutableAttributedString(string: oldText)
let range = NSMakeRange(0, attributedString.length)
attributedString.addAttribute(NSAttributedString.Key.font, value: oldFont, range: range)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: oldColor, range: range)
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: range)
self.text = nil
self.attributedText = attributedString
}
func addNormalLineSpacing(lineSpacing: CGFloat,
withLineBreakMode mode: NSLineBreakMode) {
let oldText = self.text ?? ""
let oldFont = self.font!
let oldColor = self.textColor!
let oldAlignment = self.textAlignment
let style = NSMutableParagraphStyle()
style.alignment = oldAlignment
style.lineSpacing = lineSpacing
style.lineBreakMode = mode
let attributedString = NSMutableAttributedString(string: oldText)
let range = NSMakeRange(0, attributedString.length)
attributedString.addAttribute(NSAttributedString.Key.font, value: oldFont, range: range)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: oldColor, range: range)
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: range)
self.text = nil
self.attributedText = attributedString
}
func addAttributedLineSpacing(lineSpacing: CGFloat, textAlignment: NSTextAlignment) {
guard let attributed = self.attributedText else { return }
let attributedString = NSMutableAttributedString(attributedString: attributed)
let range = NSMakeRange(0, attributedString.length)
let style = NSMutableParagraphStyle()
style.alignment = textAlignment
style.lineSpacing = lineSpacing
attributedString.removeAttribute(NSAttributedString.Key.paragraphStyle, range: range)
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: range)
self.attributedText = attributedString
}
func addFontAfterNewLineCharacter(font: UIFont) {
let oldText = self.text ?? ""
guard let range = oldText.rangeOfCharacter(from: CharacterSet.newlines) else { return }
let startPosition = oldText.distance(from: oldText.startIndex, to: range.lowerBound)
if startPosition >= 0 && startPosition < oldText.count {
let attributedString = NSMutableAttributedString(string: oldText)
let range = NSMakeRange(startPosition, attributedString.length - startPosition)
attributedString.addAttribute(NSAttributedString.Key.font, value: font, range: range)
self.text = nil
self.attributedText = attributedString
}
}
}
|
apache-2.0
|
8119bc5227c5e0e63a5011afddf23f17
| 39.606383 | 108 | 0.675662 | 5.580409 | false | false | false | false |
mcrollin/S2Geometry
|
Sources/R2/R2Rectangle.swift
|
1
|
7889
|
//
// R2Rectangle.swift
// S2Geometry
//
// Created by Marc Rollin on 4/9/17.
// Copyright © 2017 Marc Rollin. All rights reserved.
//
import Foundation
/// R2Rectangle represents a closed axis-aligned rectangle in the (x,y) plane.
struct R2Rectangle {
let x: R1Interval
let y: R1Interval
}
// MARK: CustomStringConvertible compliance
extension R2Rectangle: CustomStringConvertible {
var description: String {
return "[x:\(low), y:\(high)]"
}
}
// MARK: Equatable compliance
extension R2Rectangle: Equatable {
/// - returns: true iff both points have similar x- and y-intervals.
static func == (lhs: R2Rectangle, rhs: R2Rectangle) -> Bool {
return lhs.x == rhs.x && lhs.y == lhs.y
}
}
// MARK: AlmostEquatable compliance
extension R2Rectangle: AlmostEquatable {
/// - returns: true if the x- and y-intervals of the two rectangles are the same up to the given tolerance.
static func ==~ (lhs: R2Rectangle, rhs: R2Rectangle) -> Bool {
return lhs.x ==~ rhs.x && lhs.y ==~ lhs.y
}
}
// MARK: Static factories and Arithmetic operators
extension R2Rectangle {
/// Constructs the canonical empty rectangle. Use IsEmpty() to test
/// for empty rectangles, since they have more than one representation.
/// A Rect() is not the same as the empty.
static let empty = R2Rectangle(x: .empty, y: .empty)
/// Expands the rectangle to include the given rectangle.
/// This is the same as replacing the rectangle by the union
/// of the two rectangles, but is more efficient.
///
/// - returns: the expanded rectangle.
static func + (lhs: R2Rectangle, rhs: R2Rectangle) -> R2Rectangle {
return lhs.union(with: rhs)
}
}
// MARK: Instance methods and computed properties
extension R2Rectangle {
/// Low corner of the rect.
var low: R2Point {
return R2Point(x: x.low, y: y.low)
}
/// High corner of the rect.
var high: R2Point {
return R2Point(x: x.high, y: y.high)
}
/// Center of the rectangle in (x,y)-space
var center: R2Point {
return R2Point(x: x.center, y: y.center)
}
/// Width and height of this rectangle in (x,y)-space.
/// Empty rectangles have a negative width and height.
var size: R2Point {
return R2Point(x: x.length, y: y.length)
}
/// Four vertices of the rectangle.
/// Vertices are returned in CCW direction starting with the lower left corner.
var vertices: [R2Point] {
return [
R2Point(x: x.low, y: y.low),
R2Point(x: x.high, y: y.low),
R2Point(x: x.high, y: y.high),
R2Point(x: x.low, y: y.high)
]
}
/// Whether the rectangle is empty.
var isEmpty: Bool {
return x.isEmpty
}
/// Whether the rectangle is valid.
/// This requires the width to be empty iff the height is empty.
var isValid: Bool {
return x.isEmpty == y.isEmpty
}
/// Constructs a rectangle that contains the given points.
init(points: R2Point...) {
guard !points.isEmpty else {
self.x = R1Interval(point: 0.0)
self.y = R1Interval(point: 0.0)
return
}
var x: R1Interval = .empty
var y: R1Interval = .empty
for point in points {
x = x.add(point: point.x)
y = y.add(point: point.y)
}
self.x = x
self.y = y
}
/// Constructs a rectangle with the given center and size.
/// Both dimensions of size must be non-negative.
init(center: R2Point, size: R2Point) {
x = R1Interval(low: center.x - size.x / 2, high: center.x + size.x / 2)
y = R1Interval(low: center.y - size.y / 2, high: center.y + size.y / 2)
}
/// In direction i along the X-axis (0=left, 1=right) and direction j along the Y-axis (0=down, 1=up).
///
/// - returns: the vertex.
func vertex(i: Int, j: Int) -> R2Point {
let xx = i == 1 ? x.high : x.low
let yy = j == 1 ? y.high : y.low
return R2Point(x: xx, y: yy)
}
/// Rectangles are closed regions, i.e. they contain their boundary.
///
/// - returns: true if the rectangle contains the given point.
func contains(point: R2Point) -> Bool {
return x.contains(point: point.x)
&& y.contains(point: point.y)
}
/// The region excluding its boundary.
///
/// - returns: true iff the given point is contained in the interior of the region.
func interiorContains(point: R2Point) -> Bool {
return x.interiorContains(point: point.x)
&& y.interiorContains(point: point.y)
}
/// - returns: true iff the rectangle contains the given rectangle.
func contains(rectangle other: R2Rectangle) -> Bool {
return x.contains(interval: other.x)
&& y.contains(interval: other.y)
}
/// Including its boundary.
///
/// - returns: true iff the interior of this rectangle contains all of the points of the given other rectangle.
func interiorContains(rectangle other: R2Rectangle) -> Bool {
return x.interiorContains(interval: other.x)
&& y.interiorContains(interval: other.y)
}
/// - returns: true iff this rectangle and the other rectangle have any points in common.
func intersects(with other: R2Rectangle) -> Bool {
return x.intersects(with: other.x)
&& y.intersects(with: other.y)
}
/// Including the boundary.
///
/// - returns: true iff the interior of this rectangle intersects any point of the given other rectangle.
func interiorIntersects(with other: R2Rectangle) -> Bool {
return x.interiorIntersects(with: other.x)
&& y.interiorIntersects(with: other.y)
}
/// The rectangle is expanded by the minimum amount possible.
///
/// - returns: the rectangle expanded to include the given point.
func add(point: R2Point) -> R2Rectangle {
return R2Rectangle(x: x.add(point: point.x),
y: y.add(point: point.y))
}
/// The rectangle must be non-empty.
///
/// - returns: the closest point in the rectangle to the given point.
func clamp(to point: R2Point) -> R2Point {
return R2Point(x: x.clamp(to: point.x),
y: y.clamp(to: point.y))
}
/// The rectangle that has been expanded in the x-direction by margin.x,
/// and in y-direction by margin.y. If either margin is empty, then shrink
/// the interval on the corresponding sides instead. The resulting rectangle
/// may be empty. Any expansion of an empty rectangle remains empty.
///
/// - returns: the expanded rectangle.
func expanded(margin: R2Point) -> R2Rectangle {
let xx = x.expanded(by: margin.x)
let yy = y.expanded(by: margin.y)
if xx.isEmpty || yy.isEmpty {
return .empty
}
return R2Rectangle(x: xx, y: yy)
}
/// - returns: a Rectangle that has been expanded by the amount on all sides.
func expanded(margin: Double) -> R2Rectangle {
return expanded(margin: R2Point(x: margin, y: margin))
}
/// - returns: the smallest rectangle containing the union of this rectangle and the given rectangle.
func union(with other: R2Rectangle) -> R2Rectangle {
return R2Rectangle(x: x.union(with: other.x),
y: y.union(with: other.y))
}
/// - returns: the smallest rectangle containing the intersection of this rectangle and the given rectangle.
func intersection(with other: R2Rectangle) -> R2Rectangle {
let xx = x.intersection(with: other.x)
let yy = y.intersection(with: other.y)
if xx.isEmpty || yy.isEmpty {
return .empty
}
return R2Rectangle(x: xx, y: yy)
}
}
|
mit
|
25a09ecbf066ec1f3a5b945d8bff5ab8
| 31.327869 | 115 | 0.611308 | 3.794132 | false | false | false | false |
jasonhenderson/examples-ios
|
WebServices/WebServices/ViewController.swift
|
1
|
4705
|
//
// ViewController.swift
// WebServices
//
// Created by Jason Henderson on 10/15/17.
// Copyright © 2017 Jason Henderson. All rights reserved.
//
import UIKit
import Toast_Swift
class ViewController: UIViewController {
@IBOutlet weak var resultTextView: UITextView!
var result = (data: [ApiDictionary](), errors: [ErrorWithLevel]())
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onCallWebServiceTouched(_ sender: Any) {
// Reset call result data
self.result.data.removeAll()
self.result.errors.removeAll()
// Must be called on main
self.view.makeToastActivity(.center)
// Manufacture data
let searchTerms = ["california fire", "hurricane", "tornado", "earthquake"]
// Dispatch entire process off main so we don't lock anything
DispatchQueue.global(qos: .default).async {
// This defer block executes at the end of the default QOS queue context
defer {
// Do UI stuff on main thread
DispatchQueue.main.async {
// Always hide activity indicator
self.view.hideToastActivity()
// If there are errors, present them
if self.result.errors.count > 0 {
guard let error = self.result.errors.highestPriority else {
return
}
// Present the user with the error information
// Prepare the styling of the toast
var style = ToastStyle()
style.titleAlignment = .center
style.messageAlignment = .center
style.backgroundColor = error.color
// Display the toast
self.view.makeToast("\(error)", duration: 3.0, position: .center, title: "\(error.level)", image: nil, style: style)
}
else {
// Otherwise show the results
let description =
self.result.data
.map({ (imageInfo) -> String in
return imageInfo["title"] as? String ?? ""
})
.reduce("") {description, title in "\(description)\n\(title)"}
self.resultTextView.text = description
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Process the group of requests together
////////////////////////////////////////////////////////////////////////////////
let groupQueue = DispatchQueue(label: "edu.csumb.cst.jahenderson", attributes: .concurrent, target: .global(qos: .default))
let group = DispatchGroup()
for (_, searchTerm) in searchTerms.enumerated() {
group.enter()
groupQueue.async(group: group) {
ApiHelper.fetchImages(search: searchTerm) { fetched, error in
defer {
// But we must always signal we are done
group.leave()
}
// Check for error first
if let foundError = error {
self.result.errors.append(foundError)
return
}
// Then make sure we have data
guard let newImageInfos = fetched else {
return
}
// Add the images found
self.result.data.append(contentsOf: newImageInfos)
}
}
}
// Wait for all the calls to end or timeout
let _ = group.wait(timeout: .now() + 60)
}
}
}
|
gpl-3.0
|
75bb558a6d492939e6d3a7665ed18397
| 37.557377 | 140 | 0.430272 | 6.488276 | false | false | false | false |
jmgc/swift
|
test/SPI/run_spi_client.swift
|
1
|
1252
|
/// Compile an SPI lib and client
// RUN: %empty-directory(%t)
/// Compile the lib with SPI decls
// RUN: %target-build-swift-dylib(%t/%target-library-name(SPIHelper)) -Xfrontend -enable-experimental-prespecialization %S/Inputs/spi_helper.swift -emit-module -emit-module-path %t/SPIHelper.swiftmodule -module-name SPIHelper -enable-library-evolution
// RUN: %target-codesign %t/%target-library-name(SPIHelper)
/// Client with SPI access
// RUN: %target-swiftc_driver -I %t -L %t %s -o %t/spi_client -lSPIHelper %target-rpath(%t)
// RUN: %target-codesign %t/spi_client
// RUN: %target-run %t/spi_client %t/%target-library-name(SPIHelper) > %t/output
// RUN: %FileCheck %s < %t/output
// REQUIRES: executable_test
@_spi(HelperSPI) import SPIHelper
publicFunc()
// CHECK: publicFunc
spiFunc()
// CHECK: spiFunc
var c = SPIClass()
// CHECK: SPIClass.init
c.spiMethod()
// CHECK: SPIClass.spiMethod
c.spiVar = "write"
print(c.spiVar)
// CHECK: write
var s = SPIStruct()
// CHECK: SPIStruct.init
s.spiMethod()
// CHECK: SPIStruct.spiMethod
s.spiVar = "write"
print(s.spiVar)
// CHECK: write
var e = SPIEnum()
// CHECK: SPIEnum.init
e.spiMethod()
// CHECK: SPIEnum.spiMethod
var ps = PublicStruct()
ps.spiMethod()
// CHECK: PublicStruct.spiMethod
|
apache-2.0
|
3d7c5bcf62e3251c95ed46699e40fe78
| 24.55102 | 251 | 0.71246 | 3.1067 | false | false | false | false |
CaiMiao/CGSSGuide
|
DereGuide/Unit/Simulation/View/UnitSimulationMainBodyCell.swift
|
1
|
11812
|
//
// UnitSimulationMainBodyCell.swift
// DereGuide
//
// Created by zzk on 2017/5/16.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
import SnapKit
protocol UnitSimulationMainBodyCellDelegate: class {
func startCalculate(_ unitSimulationMainBodyCell: UnitSimulationMainBodyCell)
func startSimulate(_ unitSimulationMainBodyCell: UnitSimulationMainBodyCell)
func cancelSimulating(_ unitSimulationMainBodyCell: UnitSimulationMainBodyCell)
func startAfkModeSimulating(_ unitSimulationMainBodyCell: UnitSimulationMainBodyCell)
func cancelAfkModeSimulating(_ unitSimulationMainBodyCell: UnitSimulationMainBodyCell)
}
class UnitSimulationMainBodyCell: UITableViewCell {
var calculationButton: UIButton!
var calculationGrid: GridLabel!
var simulationButton: UIButton!
var cancelButton: UIButton!
var simulationGrid: GridLabel!
var simulatingIndicator: UIActivityIndicatorView!
var cancelButtonWidthConstraint: Constraint!
var cancelButtonLeftConstraint: Constraint!
let afkModeButton = WideButton()
let afkModeCancelButton = WideButton()
let afkModeIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
let afkModeGrid = GridLabel(rows: 2, columns: 3)
var afkModeCancelButtonLeftConstraint: Constraint!
var afkModeCancelButtonWidthConstraint: Constraint!
// var scoreDistributionButton: UIButton!
//
// var scoreDetailButton: UIButton!
//
// var supportSkillDetailButton: UIButton!
weak var delegate: UnitSimulationMainBodyCellDelegate?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
calculationButton = WideButton()
calculationButton.setTitle(NSLocalizedString("一般计算", comment: "队伍详情页面"), for: .normal)
calculationButton.backgroundColor = Color.dance
calculationButton.addTarget(self, action: #selector(startCalculate), for: .touchUpInside)
contentView.addSubview(calculationButton)
calculationButton.snp.makeConstraints { (make) in
make.left.equalTo(10)
make.right.equalTo(-10)
make.top.equalTo(10)
}
calculationGrid = GridLabel.init(rows: 2, columns: 4)
contentView.addSubview(calculationGrid)
calculationGrid.snp.makeConstraints { (make) in
make.left.equalTo(10)
make.right.equalTo(-10)
make.top.equalTo(calculationButton.snp.bottom).offset(10)
}
simulationButton = WideButton()
simulationButton.setTitle(NSLocalizedString("模拟计算", comment: "队伍详情页面"), for: .normal)
simulationButton.backgroundColor = Color.vocal
simulationButton.addTarget(self, action: #selector(startSimulate), for: .touchUpInside)
contentView.addSubview(simulationButton)
simulationButton.snp.makeConstraints { (make) in
make.left.equalTo(10)
make.top.equalTo(calculationGrid.snp.bottom).offset(10)
}
simulatingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
simulationButton.addSubview(simulatingIndicator)
simulatingIndicator.snp.makeConstraints { (make) in
make.right.equalTo(simulationButton.titleLabel!.snp.left)
make.centerY.equalTo(simulationButton)
}
cancelButton = WideButton()
cancelButton.setTitle(NSLocalizedString("取消", comment: ""), for: .normal)
cancelButton.backgroundColor = Color.vocal
cancelButton.addTarget(self, action: #selector(cancelSimulating), for: .touchUpInside)
contentView.addSubview(cancelButton)
cancelButton.snp.makeConstraints { (make) in
make.right.equalTo(-10)
make.top.equalTo(simulationButton)
self.cancelButtonWidthConstraint = make.width.equalTo(0).constraint
self.cancelButtonLeftConstraint = make.left.equalTo(simulationButton.snp.right).constraint
make.width.equalTo(calculationGrid.snp.width).dividedBy(4).priority(900)
make.left.equalTo(simulationButton.snp.right).offset(1).priority(900)
}
cancelButton.titleLabel?.adjustsFontSizeToFitWidth = true
cancelButton.titleLabel?.baselineAdjustment = .alignCenters
simulationGrid = GridLabel.init(rows: 2, columns: 4)
contentView.addSubview(simulationGrid)
simulationGrid.snp.makeConstraints { (make) in
make.left.equalTo(10)
make.right.equalTo(-10)
make.top.equalTo(simulationButton.snp.bottom).offset(10)
}
contentView.addSubview(afkModeButton)
afkModeButton.setTitle(NSLocalizedString("模拟挂机模式", comment: ""), for: .normal)
afkModeButton.backgroundColor = .passion
afkModeButton.snp.makeConstraints { (make) in
make.left.equalTo(10)
make.top.equalTo(simulationGrid.snp.bottom).offset(10)
}
afkModeButton.addTarget(self, action: #selector(startAfkModeSimulating), for: .touchUpInside)
contentView.addSubview(afkModeGrid)
afkModeGrid.snp.makeConstraints { (make) in
make.left.equalTo(10)
make.right.equalTo(-10)
make.top.equalTo(afkModeButton.snp.bottom).offset(10)
make.bottom.equalTo(-10)
}
afkModeButton.addSubview(afkModeIndicator)
afkModeIndicator.snp.makeConstraints { (make) in
make.right.equalTo(afkModeButton.titleLabel!.snp.left)
make.centerY.equalTo(afkModeButton)
}
afkModeCancelButton.setTitle(NSLocalizedString("取消", comment: ""), for: .normal)
afkModeCancelButton.backgroundColor = .passion
afkModeCancelButton.addTarget(self, action: #selector(cancelAfkModeSimulating), for: .touchUpInside)
contentView.addSubview(afkModeCancelButton)
afkModeCancelButton.snp.makeConstraints { (make) in
make.right.equalTo(-10)
make.top.equalTo(afkModeButton)
self.afkModeCancelButtonWidthConstraint = make.width.equalTo(0).constraint
self.afkModeCancelButtonLeftConstraint = make.left.equalTo(afkModeButton.snp.right).constraint
make.width.equalTo(afkModeGrid.snp.width).dividedBy(4).priority(900)
make.left.equalTo(afkModeButton.snp.right).offset(1).priority(900)
}
afkModeCancelButton.titleLabel?.adjustsFontSizeToFitWidth = true
afkModeCancelButton.titleLabel?.baselineAdjustment = .alignCenters
prepareGridViewFields()
selectionStyle = .none
}
private func prepareGridViewFields() {
var calculationString = [[String]]()
calculationString.append([NSLocalizedString("表现值", comment: "队伍详情页面"), NSLocalizedString("极限分数", comment: "队伍详情页面") + "1", NSLocalizedString("极限分数", comment: "队伍详情页面") + "2", NSLocalizedString("平均分数", comment: "队伍详情页面")])
calculationString.append(["", "", "", ""])
calculationGrid.setContents(calculationString)
var simulationStrings = [[String]]()
simulationStrings.append(["1%", "5%", "20%", "50%"])
simulationStrings.append(["", "", "", ""])
simulationGrid.setContents(simulationStrings)
var afkModeStrings = [[String]]()
afkModeStrings.append([NSLocalizedString("存活率%", comment: ""), NSLocalizedString("S Rank率%", comment: ""), NSLocalizedString("最高得分", comment: "")])
afkModeStrings.append(["", "", "", ""])
afkModeGrid.setContents(afkModeStrings)
}
func resetCalculationButton() {
calculationButton.setTitle(NSLocalizedString("一般计算", comment: ""), for: .normal)
calculationButton.isUserInteractionEnabled = true
}
func stopSimulationAnimating() {
simulationButton.isUserInteractionEnabled = true
UIView.animate(withDuration: 0.25) {
self.cancelButtonWidthConstraint.activate()
self.cancelButtonLeftConstraint.activate()
self.layoutIfNeeded()
}
simulatingIndicator.stopAnimating()
simulationButton.setTitle(NSLocalizedString("模拟计算", comment: ""), for: .normal)
}
func startSimulationAnimating() {
simulatingIndicator.startAnimating()
UIView.animate(withDuration: 0.25) {
self.cancelButtonLeftConstraint.deactivate()
self.cancelButtonWidthConstraint.deactivate()
self.layoutIfNeeded()
}
simulationButton.isUserInteractionEnabled = false
}
func startAfkModeSimulationAnimating() {
afkModeIndicator.startAnimating()
UIView.animate(withDuration: 0.25) {
self.afkModeCancelButtonLeftConstraint.deactivate()
self.afkModeCancelButtonWidthConstraint.deactivate()
self.layoutIfNeeded()
}
afkModeButton.isUserInteractionEnabled = false
}
func stopAfkModeSimulationAnimating() {
afkModeButton.isUserInteractionEnabled = true
UIView.animate(withDuration: 0.25) {
self.afkModeCancelButtonLeftConstraint.activate()
self.afkModeCancelButtonWidthConstraint.activate()
self.layoutIfNeeded()
}
afkModeIndicator.stopAnimating()
afkModeButton.setTitle(NSLocalizedString("模拟挂机模式", comment: ""), for: .normal)
}
func setupCalculationResult(value1: Int, value2: Int, value3: Int, value4: Int) {
calculationGrid[1, 0].text = String(value1)
calculationGrid[1, 1].text = String(value2)
calculationGrid[1, 2].text = String(value3)
calculationGrid[1, 3].text = String(value4)
}
func setupSimulationResult(value1: Int, value2: Int, value3: Int, value4: Int) {
simulationGrid[1, 0].text = String(value1)
simulationGrid[1, 1].text = String(value2)
simulationGrid[1, 2].text = String(value3)
simulationGrid[1, 3].text = String(value4)
}
func setupAfkModeResult(value1: String, value2: String, value3: String) {
afkModeGrid[1, 0].text = value1
afkModeGrid[1, 1].text = value2
afkModeGrid[1, 2].text = value3
}
func setupAppeal(_ appeal: Int) {
calculationGrid[1, 0].text = String(appeal)
}
func clearCalculationGrid() {
calculationGrid[1, 2].text = ""
calculationGrid[1, 1].text = ""
calculationGrid[1, 0].text = ""
calculationGrid[1, 3].text = ""
}
func clearSimulationGrid() {
simulationGrid[1, 0].text = ""
simulationGrid[1, 1].text = ""
simulationGrid[1, 2].text = ""
simulationGrid[1, 3].text = ""
}
func clearAfkModeGrid() {
afkModeGrid[1, 0].text = ""
afkModeGrid[1, 1].text = ""
afkModeGrid[1, 2].text = ""
}
@objc func startCalculate() {
delegate?.startCalculate(self)
}
@objc func startSimulate() {
delegate?.startSimulate(self)
}
@objc func cancelSimulating() {
delegate?.cancelSimulating(self)
}
@objc private func startAfkModeSimulating() {
delegate?.startAfkModeSimulating(self)
}
@objc private func cancelAfkModeSimulating() {
delegate?.cancelAfkModeSimulating(self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
eb9a2cbf183bd1f117a628cd94c5c63f
| 38.016779 | 229 | 0.660704 | 4.527648 | false | false | false | false |
scsonic/cosremote
|
ios/CosRemote/LedArrayController.swift
|
1
|
4829
|
//
// LedArrayController.swift
// CosRemote
//
// Created by 郭 又鋼 on 2016/2/27.
// Copyright © 2016年 郭 又鋼. All rights reserved.
//
import Foundation
import UIKit
class LedArrayController: UIViewController {
@IBOutlet var ivImage: UIImageView!
@IBOutlet var lbCurrentColor: UILabel!
var fRed : CGFloat = 0
var fGreen : CGFloat = 0
var fBlue : CGFloat = 0
var fAlpha: CGFloat = 0
var r = 0 ;
var g = 0 ;
var b = 0 ;
var a = 0 ;
var lastSelectTime = NSDate() ;
var naviTitle:String = "" ;
var type:Int = 0 ;
override func viewDidLoad() {
}
var callback:(( view:LedArrayController,remote:CosRemoteV1, r:Int, g:Int, b:Int ) -> Void )?
override func viewDidAppear(animated: Bool) {
let gesture = UITapGestureRecognizer(target: self, action: #selector(LedArrayController.imageTouched(_:)))
gesture.numberOfTapsRequired = 1
gesture.numberOfTouchesRequired = 1;
self.ivImage.addGestureRecognizer(gesture) ;
let pan = UIPanGestureRecognizer(target: self, action: #selector(LedArrayController.imagePaned(_:)))
self.ivImage.addGestureRecognizer(pan) ;
ivImage.userInteractionEnabled = true ;
}
override func viewWillAppear(animated: Bool) {
self.navigationItem.title = self.naviTitle
}
func imageTouched(gesture:UIGestureRecognizer) {
print( "touched ") ;
print( "xy= \(gesture.locationInView(self.ivImage).x), \( gesture.locationInView(self.ivImage).y )" )
let pointColor = self.getPixelColorAtPoint(gesture.locationInView(self.ivImage))
self.lbCurrentColor.backgroundColor = pointColor
toRGB( pointColor )
self.switchType()
}
func setSelectColorCallback( callback: ( view:LedArrayController,remote:CosRemoteV1, r:Int, g:Int, b:Int ) -> Void ) {
self.callback = callback
}
var index = 0 ;
func imagePaned( gesture:UIPanGestureRecognizer ) {
print( "xy= \(gesture.locationInView(self.ivImage).x), \( gesture.locationInView(self.ivImage).y )" )
let pointColor = self.getPixelColorAtPoint(gesture.locationInView(self.ivImage))
self.lbCurrentColor.backgroundColor = pointColor
toRGB( pointColor )
self.switchType()
}
func toRGB( color:UIColor) {
if color.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
r = Int(fRed * 255.0)
g = Int(fGreen * 255.0)
b = Int(fBlue * 255.0)
a = Int(fAlpha * 255.0)
print( "rgb = \(r),\(g),\(b) " ) ;
} else {
// just do nothing XD
}
}
func getPixelColorAtPoint(point:CGPoint) -> UIColor{
let pixel = UnsafeMutablePointer<CUnsignedChar>.alloc(4)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, bitmapInfo.rawValue)
CGContextTranslateCTM(context, -point.x, -point.y)
view.layer.renderInContext(context!)
let color:UIColor = UIColor(red: CGFloat(pixel[0])/255.0, green: CGFloat(pixel[1])/255.0, blue: CGFloat(pixel[2])/255.0, alpha: CGFloat(pixel[3])/255.0)
pixel.dealloc(4)
return color
}
func switchType() {
switch self.type {
case 0:
self.type0()
break ;
case 1:
self.type1() ;
break ;
case 2:
self.type2() ;
break;
case 3:
self.type3() ;
break
default:
self.type0() ;
}
}
// 一顆一顆循序
func type0() {
self.index = self.index + 1;
self.index = self.index % 60 ;
if let remote = Common.global.cosRemote {
remote.setLed(index, r: self.r, g: self.g, b: self.b)
}
}
//跑馬燈v2
func type1() {
self.index = self.index + 1;
self.index = self.index % 60 ;
if let remote = Common.global.cosRemote {
remote.setLed(index, r: self.r, g: self.g, b: self.b)
}
}
//全部單一
func type2() {
if let remote = Common.global.cosRemote {
remote.setLed(255, r: self.r, g: self.g, b: self.b)
}
}
//轉hsl
func type3() {
if let remote = Common.global.cosRemote {
remote.setLed(0, r: self.r, g: self.g, b: self.b)
}
}
}
|
mit
|
b76f2cd6cfefc78d318f6a37ac6b51b0
| 26.354286 | 160 | 0.556832 | 4.035413 | false | false | false | false |
ramoslin02/EasyAnimation
|
DemoApp/DemoApp/DemoSpringAnimationsViewController.swift
|
1
|
1820
|
//
// DemoSpringAnimationsViewController.swift
// DemoApp
//
// Created by Marin Todorov on 5/29/15.
// Copyright (c) 2015 Underplot ltd. All rights reserved.
//
import UIKit
class DemoSpringAnimationsViewController: UIViewController {
@IBOutlet weak var redSquare: UIView!
@IBOutlet weak var blueSquare: UIView!
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
animate()
}
func animate() {
UIView.animateAndChainWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.33, initialSpringVelocity: 0.0, options: nil,
animations: {
//spring animate the view
self.redSquare.transform = CGAffineTransformConcat(
CGAffineTransformMakeRotation(CGFloat(M_PI_2)),
CGAffineTransformMakeScale(1.5, 1.5)
)
//spring animate the layer
self.blueSquare.layer.transform = CATransform3DConcat(
CATransform3DMakeRotation(CGFloat(-M_PI_2), 0.0, 0.0, 1.0),
CATransform3DMakeScale(1.33, 1.33, 1.33)
)
self.blueSquare.layer.cornerRadius = 50.0
}, completion: nil).animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.33, initialSpringVelocity: 0.0, options: .Repeat,
animations: {
//spring animate the view
self.redSquare.transform = CGAffineTransformIdentity
//spring animate the layer
self.blueSquare.layer.transform = CATransform3DIdentity
self.blueSquare.layer.cornerRadius = 0.0
}, completion: nil)
}
}
|
mit
|
565452a32693683a02d38d24de9ab87f
| 33.339623 | 144 | 0.571429 | 5.055556 | false | false | false | false |
alexhillc/AXPhotoViewer
|
Source/Classes/Transition Controller + Animators/AXPhotosTransitionController.swift
|
1
|
7014
|
//
// AXPhotosTransitionController.swift
// AXPhotoViewer
//
// Created by Alex Hill on 6/4/17.
// Copyright © 2017 Alex Hill. All rights reserved.
//
import UIKit
#if os(iOS)
import FLAnimatedImage
#elseif os(tvOS)
import FLAnimatedImage_tvOS
#endif
class AXPhotosTransitionController: NSObject, UIViewControllerTransitioningDelegate, AXPhotosTransitionAnimatorDelegate {
fileprivate static let supportedModalPresentationStyles: [UIModalPresentationStyle] = [.fullScreen,
.currentContext,
.custom,
.overFullScreen,
.overCurrentContext]
weak var delegate: AXPhotosTransitionControllerDelegate?
/// Custom animator for presentation.
fileprivate var presentationAnimator: AXPhotosPresentationAnimator?
/// Custom animator for dismissal.
fileprivate var dismissalAnimator: AXPhotosDismissalAnimator?
/// If this flag is `true`, the transition controller will ignore any user gestures and instead trigger an immediate dismissal.
var forceNonInteractiveDismissal = false
/// The transition configuration passed in at initialization. The controller uses this object to apply customization to the transition.
let transitionInfo: AXTransitionInfo
fileprivate var supportsContextualPresentation: Bool {
get {
return (self.transitionInfo.startingView != nil)
}
}
fileprivate var supportsContextualDismissal: Bool {
get {
return (self.transitionInfo.endingView != nil)
}
}
fileprivate var supportsInteractiveDismissal: Bool {
get {
#if os(iOS)
return self.transitionInfo.interactiveDismissalEnabled
#else
return false
#endif
}
}
init(transitionInfo: AXTransitionInfo) {
self.transitionInfo = transitionInfo
super.init()
}
// MARK: - UIViewControllerTransitioningDelegate
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
var photosViewController: AXPhotosViewController
if let dismissed = dismissed as? AXPhotosViewController {
photosViewController = dismissed
} else if let childViewController = dismissed.children.filter({ $0 is AXPhotosViewController }).first as? AXPhotosViewController {
photosViewController = childViewController
} else {
assertionFailure("Could not find AXPhotosViewController in container's children.")
return nil
}
guard let photo = photosViewController.dataSource.photo(at: photosViewController.currentPhotoIndex) else { return nil }
// resolve transitionInfo's endingView
self.transitionInfo.resolveEndingViewClosure?(photo, photosViewController.currentPhotoIndex)
if !type(of: self).supportedModalPresentationStyles.contains(photosViewController.modalPresentationStyle) {
return nil
}
if !self.supportsContextualDismissal && !self.supportsInteractiveDismissal {
return nil
}
self.dismissalAnimator = self.dismissalAnimator ?? AXPhotosDismissalAnimator(transitionInfo: self.transitionInfo)
self.dismissalAnimator?.delegate = self
return self.dismissalAnimator
}
public func animationController(forPresented presented: UIViewController,
presenting: UIViewController,
source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
var photosViewController: AXPhotosViewController
if let presented = presented as? AXPhotosViewController {
photosViewController = presented
} else if let childViewController = presented.children.filter({ $0 is AXPhotosViewController }).first as? AXPhotosViewController {
photosViewController = childViewController
} else {
assertionFailure("Could not find AXPhotosViewController in container's children.")
return nil
}
if !type(of: self).supportedModalPresentationStyles.contains(photosViewController.modalPresentationStyle) {
return nil
}
if !self.supportsContextualPresentation {
return nil
}
self.presentationAnimator = AXPhotosPresentationAnimator(transitionInfo: self.transitionInfo)
self.presentationAnimator?.delegate = self
return self.presentationAnimator
}
public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if !self.supportsInteractiveDismissal || self.forceNonInteractiveDismissal {
return nil
}
self.dismissalAnimator = self.dismissalAnimator ?? AXPhotosDismissalAnimator(transitionInfo: self.transitionInfo)
self.dismissalAnimator?.delegate = self
return self.dismissalAnimator
}
#if os(iOS)
// MARK: - Interaction handling
public func didPanWithGestureRecognizer(_ sender: UIPanGestureRecognizer, in viewController: UIViewController) {
self.dismissalAnimator?.didPanWithGestureRecognizer(sender, in: viewController)
}
#endif
// MARK: - AXPhotosTransitionAnimatorDelegate
func transitionAnimator(_ animator: AXPhotosTransitionAnimator, didCompletePresentationWith transitionView: UIImageView) {
self.delegate?.transitionController(self, didCompletePresentationWith: transitionView)
self.presentationAnimator = nil
}
func transitionAnimator(_ animator: AXPhotosTransitionAnimator, didCompleteDismissalWith transitionView: UIImageView) {
self.delegate?.transitionController(self, didCompleteDismissalWith: transitionView)
self.dismissalAnimator = nil
}
func transitionAnimatorDidCancelDismissal(_ animator: AXPhotosTransitionAnimator) {
self.delegate?.transitionControllerDidCancelDismissal(self)
self.dismissalAnimator = nil
}
}
protocol AXPhotosTransitionControllerDelegate: class {
func transitionController(_ transitionController: AXPhotosTransitionController, didCompletePresentationWith transitionView: UIImageView)
func transitionController(_ transitionController: AXPhotosTransitionController, didCompleteDismissalWith transitionView: UIImageView)
func transitionControllerDidCancelDismissal(_ transitionController: AXPhotosTransitionController)
}
|
mit
|
48b185cbb18a083ff09097dbe500fc0b
| 41.50303 | 151 | 0.673036 | 6.641098 | false | false | false | false |
PerfectServers/Perfect-Authentication-Server
|
Sources/PerfectAuthServer/Models/ApplicationExtension.swift
|
1
|
619
|
//
// ApplicationExtension.swift
// PerfectLib
//
// Created by Jonathan Guthrie on 2017-08-04.
//
import PerfectLocalAuthentication
import StORM
extension Application {
public static func list() -> [[String: Any]] {
var list = [[String: Any]]()
let t = Application()
let cursor = StORMCursor(limit: 9999999,offset: 0)
try? t.select(
columns: [],
whereclause: "true",
params: [],
orderby: ["name"],
cursor: cursor
)
for row in t.rows() {
var r = [String: Any]()
r["id"] = row.id
r["name"] = row.name
r["clientid"] = row.clientid
list.append(r)
}
return list
}
}
|
apache-2.0
|
aa231984598442dcea6290ad2507a0b8
| 16.194444 | 52 | 0.612278 | 2.990338 | false | false | false | false |
WhisperSystems/Signal-iOS
|
SignalServiceKit/tests/Storage/SDSDatabaseStorageTest.swift
|
1
|
7242
|
//
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import XCTest
@testable import SignalServiceKit
extension TSThread {
@objc
public class func anyFetchAll(databaseStorage: SDSDatabaseStorage) -> [TSThread] {
var result = [TSThread]()
databaseStorage.read { transaction in
result += anyFetchAll(transaction: transaction)
}
return result
}
}
// MARK: -
extension TSInteraction {
@objc
public class func anyFetchAll(databaseStorage: SDSDatabaseStorage) -> [TSInteraction] {
var result = [TSInteraction]()
databaseStorage.read { transaction in
result += anyFetchAll(transaction: transaction)
}
return result
}
}
// MARK: -
class SDSDatabaseStorageTest: SSKBaseTestSwift {
func test_threads() {
let storage = SDSDatabaseStorage.shared
XCTAssertEqual(0, TSThread.anyFetchAll(databaseStorage: storage).count)
let contactAddress = SignalServiceAddress(phoneNumber: "+13213214321")
let contactThread = TSContactThread(contactAddress: contactAddress)
storage.write { transaction in
XCTAssertEqual(0, TSThread.anyFetchAll(transaction: transaction).count)
contactThread.anyInsert(transaction: transaction)
XCTAssertEqual(1, TSThread.anyFetchAll(transaction: transaction).count)
}
XCTAssertEqual(1, TSThread.anyFetchAll(databaseStorage: storage).count)
let groupId = Randomness.generateRandomBytes(Int32(kGroupIdLength))
let groupModel = TSGroupModel(title: "Test Group",
members: [contactAddress],
groupAvatarData: nil,
groupId: groupId)
let groupThread = TSGroupThread(groupModel: groupModel)
storage.write { transaction in
XCTAssertEqual(1, TSThread.anyFetchAll(transaction: transaction).count)
groupThread.anyInsert(transaction: transaction)
XCTAssertEqual(2, TSThread.anyFetchAll(transaction: transaction).count)
}
XCTAssertEqual(2, TSThread.anyFetchAll(databaseStorage: storage).count)
storage.write { transaction in
XCTAssertEqual(2, TSThread.anyFetchAll(transaction: transaction).count)
contactThread.anyRemove(transaction: transaction)
XCTAssertEqual(1, TSThread.anyFetchAll(transaction: transaction).count)
}
XCTAssertEqual(1, TSThread.anyFetchAll(databaseStorage: storage).count)
// Update
storage.write { transaction in
let threads = TSThread.anyFetchAll(transaction: transaction)
guard let firstThread = threads.first else {
XCTFail("Missing model.")
return
}
XCTAssertNil(firstThread.messageDraft)
firstThread.update(withDraft: "Some draft", transaction: transaction)
}
storage.read { transaction in
let threads = TSThread.anyFetchAll(transaction: transaction)
guard let firstThread = threads.first else {
XCTFail("Missing model.")
return
}
XCTAssertEqual(firstThread.messageDraft, "Some draft")
}
XCTAssertEqual(1, TSThread.anyFetchAll(databaseStorage: storage).count)
storage.write { transaction in
XCTAssertEqual(1, TSThread.anyFetchAll(transaction: transaction).count)
groupThread.anyRemove(transaction: transaction)
XCTAssertEqual(0, TSThread.anyFetchAll(transaction: transaction).count)
}
XCTAssertEqual(0, TSThread.anyFetchAll(databaseStorage: storage).count)
}
func test_interactions() {
let storage = SDSDatabaseStorage.shared
XCTAssertEqual(0, TSInteraction.anyFetchAll(databaseStorage: storage).count)
let contactAddress = SignalServiceAddress(phoneNumber: "+13213214321")
let contactThread = TSContactThread(contactAddress: contactAddress)
storage.write { transaction in
XCTAssertEqual(0, TSThread.anyFetchAll(transaction: transaction).count)
contactThread.anyInsert(transaction: transaction)
XCTAssertEqual(1, TSThread.anyFetchAll(transaction: transaction).count)
}
XCTAssertEqual(1, TSThread.anyFetchAll(databaseStorage: storage).count)
XCTAssertEqual(0, TSInteraction.anyFetchAll(databaseStorage: storage).count)
let message1 = TSOutgoingMessage(in: contactThread, messageBody: "message1", attachmentId: nil)
storage.write { transaction in
XCTAssertEqual(1, TSThread.anyFetchAll(transaction: transaction).count)
XCTAssertEqual(0, TSInteraction.anyFetchAll(transaction: transaction).count)
message1.anyInsert(transaction: transaction)
XCTAssertEqual(1, TSThread.anyFetchAll(transaction: transaction).count)
XCTAssertEqual(1, TSInteraction.anyFetchAll(transaction: transaction).count)
}
XCTAssertEqual(1, TSThread.anyFetchAll(databaseStorage: storage).count)
XCTAssertEqual(1, TSInteraction.anyFetchAll(databaseStorage: storage).count)
let message2 = TSOutgoingMessage(in: contactThread, messageBody: "message2", attachmentId: nil)
storage.write { transaction in
XCTAssertEqual(1, TSThread.anyFetchAll(transaction: transaction).count)
XCTAssertEqual(1, TSInteraction.anyFetchAll(transaction: transaction).count)
message2.anyInsert(transaction: transaction)
XCTAssertEqual(1, TSThread.anyFetchAll(transaction: transaction).count)
XCTAssertEqual(2, TSInteraction.anyFetchAll(transaction: transaction).count)
}
XCTAssertEqual(1, TSThread.anyFetchAll(databaseStorage: storage).count)
XCTAssertEqual(2, TSInteraction.anyFetchAll(databaseStorage: storage).count)
storage.write { transaction in
XCTAssertEqual(1, TSThread.anyFetchAll(transaction: transaction).count)
XCTAssertEqual(2, TSInteraction.anyFetchAll(transaction: transaction).count)
message1.anyRemove(transaction: transaction)
XCTAssertEqual(1, TSThread.anyFetchAll(transaction: transaction).count)
XCTAssertEqual(1, TSInteraction.anyFetchAll(transaction: transaction).count)
}
XCTAssertEqual(1, TSThread.anyFetchAll(databaseStorage: storage).count)
XCTAssertEqual(1, TSInteraction.anyFetchAll(databaseStorage: storage).count)
storage.write { transaction in
XCTAssertEqual(1, TSThread.anyFetchAll(transaction: transaction).count)
XCTAssertEqual(1, TSInteraction.anyFetchAll(transaction: transaction).count)
message2.anyRemove(transaction: transaction)
XCTAssertEqual(1, TSThread.anyFetchAll(transaction: transaction).count)
XCTAssertEqual(0, TSInteraction.anyFetchAll(transaction: transaction).count)
}
XCTAssertEqual(1, TSThread.anyFetchAll(databaseStorage: storage).count)
XCTAssertEqual(0, TSInteraction.anyFetchAll(databaseStorage: storage).count)
}
}
|
gpl-3.0
|
eada17b8a9c61de364e3488017737d6b
| 41.350877 | 103 | 0.682684 | 5.217579 | false | false | false | false |
CM-Studio/NotLonely-iOS
|
NotLonely-iOS/View/PageViewController/PageViewController.swift
|
1
|
3565
|
//
// PageViewController.swift
// Apitest
//
// Created by plusub on 4/17/16.
// Copyright © 2016 cm. All rights reserved.
//
import UIKit
class PageViewController: UIViewController, UIScrollViewDelegate, PageMenuViewDelegate {
let width = UIScreen.mainScreen().bounds.size.width
let height = UIScreen.mainScreen().bounds.size.height
var titleArray: Array<String> = []
var scrollView: UIScrollView!
var viewArray: Array<UIViewController> = []
var scrollY: CGFloat = 0
var scrollX: CGFloat = 0
var menuView: PageMenuView!
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController!.view.setNeedsLayout()
self.automaticallyAdjustsScrollViewInsets = true
// Do any additional setup after loading the view.
scrollViewLayout()
menuViewLayout()
}
func scrollViewLayout() {
self.scrollView = UIScrollView(frame: CGRectMake(0, navigationBarHeight + statusBarHeight + 44, width, height - (navigationBarHeight + statusBarHeight + 44)))
self.scrollView.pagingEnabled = true
self.scrollView.bounces = false
self.scrollView.delegate = self
self.scrollView.showsHorizontalScrollIndicator = false
self.scrollView.backgroundColor = UIColor.redColor()
let contentWidth = CGFloat(titleArray.count)
self.scrollView.contentSize = CGSizeMake(contentWidth * width, height - 230)
scrollY = 0
for i in 0 ..< viewArray.count {
// let tableViewController = UITableViewController(style: .Plain)
// if i == 0 {
// tableViewController.view.backgroundColor = UIColor.greenColor()
// } else if i == 1 {
// tableViewController.view.backgroundColor = UIColor.yellowColor()
// }
// tableViewController.tableView.contentInset = UIEdgeInsetsMake(44, 0, 0, 0)
viewArray[i].view.frame = CGRectMake(CGFloat(i) * width, -66, width, height - (navigationBarHeight + statusBarHeight + 44))
// viewArray.append(viewArray[i])
self.addChildViewController(viewArray[i])
self.tabBarController!.view.setNeedsLayout()
self.navigationController!.view.setNeedsLayout()
}
scrollView.addSubview(viewArray[0].view)
self.view.addSubview(scrollView)
}
func menuViewLayout() {
menuView = PageMenuView(frame: CGRectMake(0, navigationBarHeight + statusBarHeight, width, 44))
menuView.backgroundColor = UIColor.NLMenu()
menuView.delegate = self
menuView.setMenu(titleArray)
self.view.addSubview(self.menuView)
}
func selectIndex(index: Int) {
UIView.animateWithDuration(0.3) {
self.scrollView?.contentOffset = CGPointMake(self.width * CGFloat(index), -64)
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollX == scrollView.contentOffset.x{
return;
}
if scrollY >= -104 {
scrollY = -104
}
// for tableViewController in viewArray {
// tableViewController.tableView.contentOffset = CGPointMake(0, scrollY)
// }
let rate = (scrollView.contentOffset.x / width)
self.menuView.scollToRate(rate)
scrollView.addSubview(viewArray[Int(rate+0.7)].view)
scrollX = scrollView.contentOffset.x
}
}
|
mit
|
c01f900afb121db35a67039da8e6516d
| 32.622642 | 166 | 0.622896 | 5.005618 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Blockchain/Announcements/Kinds/OneTime/NewAssetAnnouncement.swift
|
1
|
4111
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import DIKit
import MoneyKit
import PlatformKit
import PlatformUIKit
import RxSwift
import SwiftUI
import ToolKit
/// This is a generic announcement that introduces a new crypto currency.
final class NewAssetAnnouncement: OneTimeAnnouncement, ActionableAnnouncement {
private typealias LocalizedString = LocalizationConstants.AnnouncementCards.NewAsset
// MARK: - Properties
var viewModel: AnnouncementCardViewModel {
let title = String(format: LocalizedString.title, cryptoCurrency!.name, cryptoCurrency!.displayCode)
let description = String(format: LocalizedString.description, cryptoCurrency!.displayCode)
let buttonTitle = String(format: LocalizedString.ctaButton, cryptoCurrency!.displayCode)
let button = ButtonViewModel.primary(
with: buttonTitle,
background: .primaryButton
)
button.tapRelay
.bind { [weak self] in
guard let self = self else { return }
self.analyticsRecorder.record(
event: self.actionAnalyticsEvent
)
self.markRemoved()
self.action()
self.dismiss()
}
.disposed(by: disposeBag)
return AnnouncementCardViewModel(
type: type,
badgeImage: .init(
image: cryptoCurrency!.logoResource,
contentColor: nil,
backgroundColor: .clear,
cornerRadius: .round,
size: .edge(40)
),
title: title,
description: description,
buttons: [button],
dismissState: .dismissible { [weak self] in
guard let self = self else { return }
self.analyticsRecorder.record(event: self.dismissAnalyticsEvent)
self.markRemoved()
self.dismiss()
},
didAppear: { [weak self] in
guard let self = self else { return }
self.analyticsRecorder.record(event: self.didAppearAnalyticsEvent)
}
)
}
var associatedAppModes: [AppMode] {
[AppMode.trading, AppMode.legacy]
}
var shouldShow: Bool {
cryptoCurrency != nil && !isDismissed
}
var key: AnnouncementRecord.Key {
.newAsset(code: cryptoCurrency?.code ?? "")
}
let type = AnnouncementType.newAsset
let analyticsRecorder: AnalyticsEventRecorderAPI
let cryptoCurrency: CryptoCurrency?
let dismiss: CardAnnouncementAction
let recorder: AnnouncementRecorder
let action: CardAnnouncementAction
private let disposeBag = DisposeBag()
// MARK: - Setup
init(
cryptoCurrency: CryptoCurrency?,
cacheSuite: CacheSuite = resolve(),
analyticsRecorder: AnalyticsEventRecorderAPI = resolve(),
errorRecorder: ErrorRecording = resolve(),
dismiss: @escaping CardAnnouncementAction,
action: @escaping CardAnnouncementAction
) {
recorder = AnnouncementRecorder(cache: cacheSuite, errorRecorder: errorRecorder)
self.cryptoCurrency = cryptoCurrency
self.analyticsRecorder = analyticsRecorder
self.dismiss = dismiss
self.action = action
}
}
// MARK: SwiftUI Preview
#if DEBUG
struct NewAssetAnnouncementContainer: UIViewRepresentable {
typealias UIViewType = AnnouncementCardView
func makeUIView(context: Context) -> UIViewType {
let presenter = NewAssetAnnouncement(
cryptoCurrency: .bitcoin,
dismiss: {},
action: {}
)
return AnnouncementCardView(using: presenter.viewModel)
}
func updateUIView(_ uiView: UIViewType, context: Context) {}
}
struct NewAssetAnnouncementContainer_Previews: PreviewProvider {
static var previews: some View {
Group {
NewAssetAnnouncementContainer().colorScheme(.light)
}.previewLayout(.fixed(width: 375, height: 250))
}
}
#endif
|
lgpl-3.0
|
153e484bef7d59a9745c996e4cd6a3b9
| 30.374046 | 108 | 0.63382 | 5.56157 | false | false | false | false |
InAppPurchase/InAppPurchase
|
InAppPurchase/IAPEntitlementModel.swift
|
1
|
3065
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Chris Davis
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// IAPEntitlementModel.swift
// InAppPurchase
//
// Created by Chris Davis on 15/12/2015.
// Email: [email protected]
// Copyright © 2015 nthState. All rights reserved.
//
import Foundation
// MARK: Class
public class IAPEntitlementModel : IAPHydrateable, CustomDebugStringConvertible
{
// MARK: Properties
public var entitlementId:String!
public var used:Bool
public var dateUsed:NSDate?
public var expiryDate:NSDate?
public var productId:String!
public var debugDescription: String {
return "entitlementId: \(entitlementId), used: \(used), productId: \(productId), dateUsed: \(dateUsed), expiryDate: \(expiryDate)"
}
// MARK: Initalizers
/**
Initalizer
*/
init()
{
used = false
}
/**
Initalizer with hydration
- parameter dic: The dictionary of values
*/
convenience required public init(dic:NSDictionary)
{
self.init()
hydrate(dic)
}
// MARK: Hydration
/**
Hydrate the object
- parameter dic: The dictionary of values
*/
func hydrate(dic:NSDictionary)
{
if let _entitlementId = dic["entitlementId"] as? String
{
entitlementId = _entitlementId
}
if let _used = dic["used"] as? Bool
{
used = _used
}
if
let _dateUsed = dic["dateUsed"] as? String,
let _converted = NSDate.dateToTimeZoneString(_dateUsed)
{
dateUsed = _converted
}
if let _productId = dic["productId"] as? String
{
productId = _productId
}
if
let _expiryDate = dic["expiryDate"] as? String,
let _converted = NSDate.dateToTimeZoneString(_expiryDate)
{
expiryDate = _converted
}
}
}
|
mit
|
0f91c00069c66b258fc3d4773f5a5d84
| 28.461538 | 138 | 0.634138 | 4.352273 | false | false | false | false |
VirgilSecurity/virgil-sdk-pfs-x
|
Source/Client/Models/Responses/BootstrapCardsResponse.swift
|
1
|
855
|
//
// BootstrapCardsResponse.swift
// VirgilSDKPFS
//
// Created by Oleksandr Deundiak on 6/13/17.
// Copyright © 2017 VirgilSecurity. All rights reserved.
//
import Foundation
class BootstrapCardsResponse: NSObject, Deserializable {
let ltc: [AnyHashable: Any]
let otc: [[AnyHashable: Any]]
fileprivate init(ltc: [AnyHashable: Any], otc: [[AnyHashable: Any]]) {
self.ltc = ltc
self.otc = otc
}
required convenience init?(dictionary: Any) {
guard let dictionary = dictionary as? [String: Any] else {
return nil
}
guard let ltc = dictionary["long_time_card"] as? [AnyHashable: Any],
let otc = dictionary["one_time_cards"] as? [[AnyHashable: Any]] else {
return nil
}
self.init(ltc: ltc, otc: otc)
}
}
|
bsd-3-clause
|
5a3f74d1ba2fc21013d955a70d780727
| 25.6875 | 82 | 0.590164 | 3.864253 | false | false | false | false |
baottran/nSURE
|
nSURE/AssessmentReviewDetailsViewController.swift
|
1
|
4885
|
//
// AssessmentReviewViewController.swift
// nSURE
//
// Created by Bao Tran on 7/15/15.
// Copyright (c) 2015 Sprout Designs. All rights reserved.
//
import UIKit
class AssessmentReviewDetailsViewController: UIViewController {
var assessmentObj: PFObject?
var vehicleObj: PFObject?
@IBOutlet weak var customerNameLabel: UILabel!
@IBOutlet weak var vehicleLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var phoneLabel: UILabel!
@IBOutlet weak var locationLabel: UITextView!
@IBOutlet weak var notesTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// println("assessmentObject: \(assessmentObj)")
if let assessment = assessmentObj {
let customer = assessment["customer"] as! PFObject
let customerFirstName = customer["firstName"] as! String
let customerLastName = customer["lastName"] as! String
customerNameLabel.text = "\(customerFirstName) \(customerLastName)"
if let customerPhone = customer["defaultPhone"] as? PFObject {
buildPhone(customerPhone.objectId!)
}
let assessmentDate = assessment["assessmentDate"] as! NSDate
dateLabel.text = assessmentDate.toLongDateString()
timeLabel.text = assessmentDate.toShortTimeString()
let customerVehicle = assessment["damagedVehicle"] as! PFObject
buildVehicle(customerVehicle.objectId!)
let customerAddress = assessment["assessmentLocation"] as! PFObject
buildAddress(customerAddress.objectId!)
let notes = assessment["intakeNotes"] as! String
notesTextView.text = notes
notesTextView.font = UIFont.systemFontOfSize(25)
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func buildPhone(objId: String){
let query = PFQuery(className: "Phone")
query.getObjectInBackgroundWithId(objId, block: { phoneObj, error in
if let phone = phoneObj {
print("here's the phone", terminator: "")
let phoneNum = phone["number"] as! String
self.phoneLabel.text = phoneNum
}
})
}
func buildVehicle(objId: String){
let vehicleQuery = queryObject("Vehicle", objId: objId)
let results = vehicleQuery.findObjects()
if let car = results as? [PFObject] {
vehicleObj = car[0] as PFObject
let make = car[0]["make"] as! String
let model = car[0]["model"] as! String
let year = car[0]["year"] as! String
self.vehicleLabel.text = "\(year) \(make) \(model)"
}
}
func queryObject(className: String, objId: String) -> PFQuery {
let query = PFQuery(className: className)
query.getObjectWithId(objId)
return query
}
func buildAddress(objId: String){
let addressQuery = queryObject("Address", objId: objId)
let results = addressQuery.findObjects()
if let addy = results as? [PFObject] {
let street = addy[0]["street"] as! String
let apartment = addy[0]["apartment"] as! String
let city = addy[0]["city"] as! String
let zip = addy[0]["zip"] as! String
let state = addy[0]["state"] as! String
self.locationLabel.text = "\(street), \(apartment)\n\(city), \(state) \(zip)"
self.locationLabel.font = UIFont.systemFontOfSize(25)
} else {
print("not address", terminator: "")
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Log Vehicle Damage" {
let vehicleDamageViewController = segue.destinationViewController as! ASVehicleViewController
vehicleDamageViewController.assessmentObj = assessmentObj
vehicleDamageViewController.vehicleObj = vehicleObj
vehicleDamageViewController.customerPhone = phoneLabel.text
}
}
/*
// 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
|
83f682f75ab8521661d0ba92055d2705
| 34.919118 | 106 | 0.604299 | 5.036082 | false | false | false | false |
fuzza/SwiftyJanet
|
Tests/SwiftyJanetTests/TestExtensions/ActionPair+Equatable.swift
|
1
|
154
|
@testable import SwiftyJanet
func == <T: JanetAction> (lhs: ActionPair<T>, rhs: ActionPair<T>) -> Bool {
return (lhs.0 == rhs.0) && (lhs.1 == rhs.1)
}
|
mit
|
c6aed7471a01598f2f81d264a46bf70d
| 29.8 | 75 | 0.616883 | 2.610169 | false | true | false | false |
LearningSwift2/LearningApps
|
SimpleMapAnnotation/SimpleUserLocation/ViewController.swift
|
1
|
4053
|
//
// ViewController.swift
// SimpleUserLocation
//
// Created by Phil Wright on 2/16/16.
// Copyright © 2016 The Iron Yard. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
var locationManager = CLLocationManager()
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
self.updateLocationTapped()
}
@IBAction func updateLocationTapped() {
let status = CLAuthorizationStatus.AuthorizedWhenInUse
if status != .Denied {
self.mapView.showsUserLocation = true
self.locationManager.requestLocation()
}
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
self.updateLocationTapped()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.count > 0 {
let location = locations.first
print(location?.coordinate.latitude)
print(location?.coordinate.longitude)
// Find the Center Coordinate
if let center = location?.coordinate {
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
self.mapView.showsUserLocation = true
self.createAnnotation("Apple Computer", subTitle: "", coordinate: center)
print("mapView updated")
}
}
print("location updated")
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print(error.localizedDescription)
}
func geoLocation(fullAddressString:String) {
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString(fullAddressString, completionHandler: { placemarks, error in
})
}
func createAnnotation(title: String, subTitle: String, coordinate: CLLocationCoordinate2D) {
let annotation = MKPointAnnotation()
annotation.title = title
annotation.subtitle = subTitle
annotation.coordinate = coordinate
if self.mapView != nil {
self.mapView.addAnnotation(annotation)
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "MyPinIdentifier"
// ensure annotation
if annotation.isKindOfClass(MKUserLocation) {
return nil
}
// Reuse the annotation if possible
var annotationView:MKPinAnnotationView? = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? MKPinAnnotationView
if annotationView == nil {
// pin color
annotationView?.pinTintColor = UIColor.orangeColor()
// Ensure proper use of identifier
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
// show Callout (true/false)
annotationView?.canShowCallout = true
let leftIconView = UIImageView(frame: CGRectMake(0, 0, 37, 30))
leftIconView.image = UIImage(named: "apple")
annotationView?.leftCalloutAccessoryView = leftIconView
//
// // Automatically select the annotation
// self.mapView.selectAnnotation(annotation, animated: false)
}
return annotationView
}
}
|
apache-2.0
|
98b75a0bec00d3e88041d2940fea81b0
| 29.938931 | 137 | 0.618213 | 6.272446 | false | false | false | false |
WebAPIKit/WebAPIKit
|
Sources/WebAPIKit/Response/ResponseHeaderKey.swift
|
1
|
2662
|
/**
* WebAPIKit
*
* Copyright (c) 2017 Evan Liu. Licensed under the MIT license, as follows:
*
* 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
/// Wrapper for http response header keys.
public struct ResponseHeaderKey: RawValueWrapper {
public let rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
}
extension HTTPURLResponse {
/// Get header response header value by key as `ResponseHeaderKey`.
public func value(forHeaderKey key: ResponseHeaderKey) -> String? {
return allHeaderFields[key.rawValue] as? String
}
}
extension WebAPIResponse {
/// Get header response header value by key as `ResponseHeaderKey`.
public func value(forHeaderKey key: ResponseHeaderKey) -> String? {
return headers[key.rawValue] as? String
}
}
// MARK: Common used keys
extension ResponseHeaderKey {
/// Valid actions for a specified resource. To be used for a 405 Method not allowed.
/// - `Allow: GET, HEAD`
public static let allow = ResponseHeaderKey("Allow")
/// Where in a full body message this partial message belongs.
/// - `Content-Range: bytes 21010-47021/47022`
public static let contentRange = ResponseHeaderKey("Content-Range")
/// An identifier for a specific version of a resource, often a message digest.
/// - `ETag: "737060cd8c284d8af7ad3082f209582d"`
public static let eTag = ResponseHeaderKey("ETag")
/// An HTTP cookie.
/// - `Set-Cookie: UserID=JohnDoe; Max-Age=3600; Version=`
public static let setCookie = ResponseHeaderKey("Set-Cookie")
}
|
mit
|
6616053d45daf061c65b584929c6d2bc
| 34.972973 | 88 | 0.719384 | 4.279743 | false | false | false | false |
silence0201/Swift-Study
|
Learn/13.类继承/从一个实例开始.playground/section-1.swift
|
1
|
405
|
class Person {
var name: String
var age: Int
func description() -> String {
return "\(name) 年龄是: \(age)"
}
init() {
name = ""
age = 1
}
}
class Student: Person {
var school: String
override init() {
school = ""
super.init()
age = 8
}
}
let student = Student()
print("学生: \(student.description())")
|
mit
|
acfa4027e2cee53eb21c8e9247a6c232
| 14.192308 | 37 | 0.475949 | 3.834951 | false | false | false | false |
ello/ello-ios
|
Specs/Controllers/Stream/Cells/AnnouncementCellSpec.swift
|
1
|
3061
|
////
/// AnnouncementCellSpec.swift
//
@testable import Ello
import Quick
import Nimble
class AnnouncementCellSpec: QuickSpec {
override func spec() {
describe("AnnouncementCell") {
context("snapshots") {
func config(
_ title: String,
_ body: String,
isStaffPreview: Bool = false
) -> AnnouncementCell.Config {
var config = AnnouncementCell.Config()
config.isStaffPreview = isStaffPreview
config.title = title
config.body = body
config.image = specImage(named: "specs-avatar")
config.callToAction = "Learn More"
return config
}
let expectations: [(String, AnnouncementCell.Config)] = [
("short title, short description", config("short title", "short description")),
("staff", config("short title", "short description", isStaffPreview: true)),
(
"long title, short description",
config(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"short description"
)
),
(
"short title, long description",
config(
"short title",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc consectetur molestie faucibus."
)
),
(
"long title, long description",
config(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc consectetur molestie faucibus."
)
),
]
for (description, config) in expectations {
it("should have valid snapshot for \(description)") {
let announcement = Announcement.stub([
"header": config.title!, "body": config.body!,
"ctaCaption": config.callToAction!
])
let width: CGFloat = 375
let height = AnnouncementCellSizeCalculator.calculateAnnouncementHeight(
announcement,
cellWidth: width
)
let subject = AnnouncementCell(
frame: CGRect(origin: .zero, size: CGSize(width: width, height: height))
)
subject.config = config
expectValidSnapshot(subject)
}
}
}
}
}
}
|
mit
|
0b82755c62a178e7cdcb59cfe36f4b3b
| 40.364865 | 122 | 0.432212 | 6.727473 | false | true | false | false |
surik00/RocketWidget
|
RocketWidget/Model/EventMonitor.swift
|
1
|
780
|
//
// EventMonitor.swift
// RocketWidget
//
// Created by Suren Khorenyan on 08.10.17.
// Copyright © 2017 Suren Khorenyan. All rights reserved.
//
import Cocoa
public class EventMonitor {
private var monitor: Any?
private let mask: NSEvent.EventTypeMask
private let handler: (NSEvent?) -> Void
public init(mask: NSEvent.EventTypeMask, handler: @escaping (NSEvent?) -> Void) {
self.mask = mask
self.handler = handler
}
deinit {
stop()
}
public func start() {
monitor = NSEvent.addGlobalMonitorForEvents(matching: mask, handler: handler)
}
public func stop() {
if monitor != nil {
NSEvent.removeMonitor(monitor!)
monitor = nil
}
}
}
|
bsd-3-clause
|
7aedfa74a6746998fd3e307dd9bd8a3a
| 20.638889 | 85 | 0.594352 | 4.233696 | false | false | false | false |
darina/omim
|
iphone/Maps/Bookmarks/Categories/Sharing/EditOnWebAlertViewController.swift
|
8
|
1294
|
class EditOnWebAlertViewController: UIViewController {
private let transitioning = FadeTransitioning<AlertPresentationController>()
private var alertTitle = ""
private var alertMessage = ""
private var buttonTitle = ""
var onAcceptBlock: MWMVoidBlock?
var onCancelBlock: MWMVoidBlock?
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var acceptButton: UIButton!
convenience init(with title: String, message: String, acceptButtonTitle: String) {
self.init()
alertTitle = title
alertMessage = message
buttonTitle = acceptButtonTitle
}
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = alertTitle
messageLabel.text = alertMessage
acceptButton.setTitle(buttonTitle, for: .normal)
cancelButton.setTitle(L("cancel"), for: .normal)
}
override var transitioningDelegate: UIViewControllerTransitioningDelegate? {
get { return transitioning }
set { }
}
override var modalPresentationStyle: UIModalPresentationStyle {
get { return .custom }
set { }
}
@IBAction func onAccept(_ sender: UIButton) {
onAcceptBlock?()
}
@IBAction func onCancel(_ sender: UIButton) {
onCancelBlock?()
}
}
|
apache-2.0
|
897a6a9f389e470c18869e073f541d1a
| 25.958333 | 84 | 0.724111 | 4.957854 | false | false | false | false |
apple/swift
|
test/Generics/rdar86431977.swift
|
6
|
611
|
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s
protocol P1 {
associatedtype A
associatedtype B : P1 where B.A == A, B.B == B
}
protocol P2 : P1 where A == Self {}
struct G<T, U> {}
// The GSB used to get the signature of bar() wrong.
extension G {
// CHECK-LABEL: rdar86431977.(file).G extension.foo()@
// CHECK: Generic signature: <T, U where T : P2, T == U>
func foo() where T : P2, U == T {}
// CHECK-LABEL: rdar86431977.(file).G extension.bar()@
// CHECK: Generic signature: <T, U where T : P2, T == U>
func bar() where T : P2, T == U {}
}
|
apache-2.0
|
b775b3e462f4123e1fd5dce2782c86cb
| 26.772727 | 91 | 0.613748 | 2.895735 | false | false | false | false |
couchbits/iOSToolbox
|
Sources/Extensions/ProgressVisualizable.swift
|
1
|
3484
|
//
// ProgressVisualizable.swift
// iOSToolbox
//
// Created by Dominik Gauggel on 05.03.18.
//
import Foundation
public protocol ProgressVisualizable {
var progress: Double { get set }
var isProgressHidden: Bool { get set }
}
fileprivate let ProgressVisualizableAnimationTime = 0.1
fileprivate struct AssociatedKeys {
static var progressViewWidthLayoutConstraint = "com.couchbits.ios-toolbox.progressViewWidthLayoutConstraint"
static var progressView = "com.couchbits.ios-toolbox.progressView"
}
public extension ProgressVisualizable where Self: UIView {
func initializeProgressVisualizable(color: UIColor) {
setProgressView(UIView())
progressView?.backgroundColor = color
addSubview(self.progressView!)
progressView?.translatesAutoresizingMaskIntoConstraints = false
progressView?.topAnchor.constraint(equalTo: topAnchor).isActive = true
progressView?.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
progressView?.heightAnchor.constraint(equalToConstant: 2).isActive = true
setProgressViewWidthLayoutConstraint(progressView?.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0))
progressViewWidthLayoutConstraint?.isActive = true
}
var progress: Double {
get {
return Double(progressViewWidthLayoutConstraint?.multiplier ?? 0)
}
set {
isProgressHidden = false
if let progressViewWidthLayoutConstraint = self.progressViewWidthLayoutConstraint {
progressViewWidthLayoutConstraint.isActive = false
removeConstraint(progressViewWidthLayoutConstraint)
setProgressViewWidthLayoutConstraint(nil)
}
var multiplier = newValue
if newValue < 0 {
multiplier = 0
}
else if newValue > 1 {
multiplier = 1
}
let wealf = self
UIView.animate(withDuration: ProgressVisualizableAnimationTime) {
wealf.setProgressViewWidthLayoutConstraint(wealf.progressView?.widthAnchor.constraint(equalTo: wealf.widthAnchor,
multiplier: CGFloat(multiplier)))
wealf.progressViewWidthLayoutConstraint?.isActive = true
wealf.layoutIfNeeded()
}
}
}
var isProgressHidden: Bool {
get {
return progressView?.isHidden ?? false
}
set {
let wealf = self
UIView.animate(withDuration: ProgressVisualizableAnimationTime, animations: {
wealf.progressView?.isHidden = newValue
wealf.layoutIfNeeded()
})
}
}
func setProgressViewWidthLayoutConstraint(_ constraint: NSLayoutConstraint?) {
setAssociated(value: constraint, associativeKey: &AssociatedKeys.progressViewWidthLayoutConstraint)
}
fileprivate func setProgressView(_ progressView: UIView) {
setAssociated(value: progressView, associativeKey: &AssociatedKeys.progressView)
}
fileprivate var progressViewWidthLayoutConstraint: NSLayoutConstraint? {
return getAssociated(associativeKey: &AssociatedKeys.progressViewWidthLayoutConstraint)
}
fileprivate var progressView: UIView? {
return getAssociated(associativeKey: &AssociatedKeys.progressView)
}
}
|
mit
|
14214fbc4963562bceefd2b230611d20
| 35.673684 | 134 | 0.66217 | 5.826087 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.