repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DanielMandea/coredatahelper | refs/heads/master | Example/CoreDataStackHelper/User+CoreDataClass.swift | mit | 1 | //
// User+CoreDataClass.swift
//
//
// Created by DanielMandea on 3/16/17.
//
//
import Foundation
import CoreData
import CoreDataStackHelper
final class User: NSManagedObject, AddManagedObject, SaveManagedObject, Fetch {
}
// MARK: - UpdateManangedObject
extension User: UpdateManangedObject {
public func update(with data: Any) {
// Checkout data
guard let data = data as? Dictionary<String, Any> else {
return
}
// Update managed object
let updatedName = data["name"] as? String
if name != updatedName {
name = updatedName
}
let updatedUniqueID = data["uniqueID"] as? String
if uniqueID != updatedUniqueID {
uniqueID = updatedUniqueID
}
let updatedAge = data["age"] as? NSNumber
if age != updatedAge {
age = updatedAge
}
}
}
// MARK: - CreateOrUpdateManagedObject
extension User: CreateOrUpdateManagedObject {
static func createOrUpdate(with data: Any, context: NSManagedObjectContext) -> User? {
guard let dataDict = data as? Dictionary<String, Any>,
let uniqueID = dataDict["uniqueID"] as? String else {
return nil
}
var user:User?
let predicate = NSPredicate(format: "uniqueID = %@", uniqueID)
do {
user = try User.fetch(with: predicate, in: context)?.first
} catch {
print(error)
}
if user == nil {
user = User.add(data: data, context: context)
} else {
user?.update(with: data)
}
return user
}
static func createOrUpdateMultiple(with data: Array<Any>, context: NSManagedObjectContext) -> Array<User>? {
var users = [User]()
for dataEntry in data {
if let user = createOrUpdate(with: dataEntry, context: context) {
users.append(user)
}
}
return users
}
}
| 7cc2eec970e82da71cfb9383d5610aa6 | 22.539474 | 110 | 0.642817 | false | false | false | false |
tunespeak/AlamoRecord | refs/heads/master | Example/AlamoRecord/CommentCell.swift | mit | 1 | //
// CommentCell.swift
// AlamoRecord
//
// Created by Dalton Hinterscher on 7/8/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
class CommentCell: BaseTableViewCell {
private var nameLabel: UILabel!
private var emailLabel: UILabel!
private var bodyLabel: UILabel!
required init() {
super.init()
selectionStyle = .none
nameLabel = UILabel()
nameLabel.numberOfLines = 0
nameLabel.font = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize * 1.25)
resizableView.addSubview(nameLabel)
bodyLabel = UILabel()
bodyLabel.numberOfLines = 0
bodyLabel.font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
resizableView.addSubview(bodyLabel)
emailLabel = UILabel()
emailLabel.numberOfLines = 0
emailLabel.font = UIFont.boldSystemFont(ofSize: UIFont.smallSystemFontSize)
emailLabel.textColor = .lightGray
resizableView.addSubview(emailLabel)
nameLabel.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(10)
make.left.equalToSuperview().offset(10)
make.right.equalToSuperview().offset(-10)
}
bodyLabel.snp.makeConstraints { (make) in
make.top.equalTo(nameLabel.snp.bottom).offset(5)
make.left.equalTo(nameLabel)
make.right.equalTo(nameLabel)
}
emailLabel.snp.makeConstraints { (make) in
make.top.equalTo(bodyLabel.snp.bottom).offset(5)
make.left.equalTo(nameLabel)
make.right.equalTo(nameLabel)
}
autoResize(under: emailLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bind(comment: Comment) {
nameLabel.text = comment.name
bodyLabel.text = comment.body
emailLabel.text = comment.email
}
}
| 156b5ad07d1c8a696a4b5cc0ec3c39c4 | 28.705882 | 84 | 0.619307 | false | false | false | false |
eugenehp/Swift3SSHDemo | refs/heads/master | SSHDemo/ViewController.swift | mit | 1 | import UIKit
import Foundation
import NMSSH
import CFNetwork
class ViewController: UIViewController, NMSSHChannelDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// let host = "10.0.1.15:22"
let host = "45.51.135.163:22"
let username = "admin"
let password = "123"
let session = NMSSHSession(host: host, andUsername: username)
print("Trying to connect now..")
session?.connect()
if session?.isConnected == true
{
print("Session connected")
session?.channel.delegate = self
session?.channel.ptyTerminalType = .vanilla
session?.channel.requestPty = true
session?.authenticate(byPassword:password)
do{
try session?.channel.startShell()
let a = try session?.channel.write("sleep\n")
print(a)
print(session?.channel.lastResponse ?? "no respone of last command")
}catch{
print("Error ocurred!!")
}
//For other types
//session.authenticateByPassword(password)
}
//session?.disconnect()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func channel(_ channel: NMSSHChannel!, didReadRawData data: Data!) {
let str = String(data: data, encoding: .isoLatin1)!
print("hello")
print(str)
}
}
| af627eae8a2be4b9a6fde6d7a9d8b8a9 | 28.259259 | 84 | 0.561392 | false | false | false | false |
gssdromen/KcptunMac | refs/heads/master | KcptunMac/Command.swift | gpl-3.0 | 1 | //
// Command.swift
// KcptunMac
//
// Created by Cedric Wu on 8/27/16.
// Copyright © 2016 Cedric Wu. All rights reserved.
//
import Foundation
import ServiceManagement
import Cocoa
import AEXML
class Command {
static let kPidPath = "/var/run/com.cedric.KcptunMac.pid"
class func runKCPTUN(_ configurationErrorBlock: @escaping (() -> Void)) {
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now()) {
let pipe = Pipe()
let file = pipe.fileHandleForReading
let task = Process()
let model = PreferenceModel.sharedInstance
task.launchPath = model.clientPath
if model.localPort.isEmpty || model.remoteAddress.isEmpty {
configurationErrorBlock()
} else {
var args = model.combine()
args.append("&")
task.arguments = args
task.standardOutput = pipe
task.launch()
Command.writePidToFilePath(path: Command.kPidPath, pid: String(task.processIdentifier))
let data = file.readDataToEndOfFile()
file.closeFile()
let grepOutput = String(data: data, encoding: String.Encoding.utf8)
if grepOutput != nil {
print(grepOutput!)
}
}
}
}
class func stopKCPTUN() {
DispatchQueue.global().async {
let task = Process()
if let pid = Command.readPidToFilePath(path: Command.kPidPath) {
task.launchPath = "/bin/kill"
task.arguments = ["-9", pid]
task.launch()
}
}
}
class func genLaunchAgentsPlist(kcptunPath: String, params: [String]) -> AEXMLDocument {
let xml = AEXMLDocument()
let plist = AEXMLElement(name: "plist", value: nil, attributes: ["version": "1.0"])
let dict = AEXMLElement(name: "dict")
plist.addChild(dict)
dict.addChild(name: "key", value: "Label", attributes: [:])
dict.addChild(name: "string", value: "com.cedric.KcptunMac", attributes: [:])
dict.addChild(name: "key", value: "ProgramArguments", attributes: [:])
let arrayElement = AEXMLElement(name: "array")
arrayElement.addChild(name: "string", value: kcptunPath, attributes: [:])
for param in params {
arrayElement.addChild(name: "string", value: param, attributes: [:])
}
dict.addChild(arrayElement)
dict.addChild(name: "key", value: "KeepAlive", attributes: [:])
dict.addChild(name: "true", value: nil, attributes: [:])
xml.addChild(plist)
return xml
}
// 保存kcptun的运行pid
class func writePidToFilePath(path: String, pid: String) {
do {
try pid.write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
} catch let e {
print(e.localizedDescription)
}
}
// 读取kcptun的运行pid
class func readPidToFilePath(path: String) -> String? {
guard FileManager.default.fileExists(atPath: path) else {
return nil
}
if let data = FileManager.default.contents(atPath: path) {
let pid = String(data: data, encoding: String.Encoding.utf8)
return pid
}
return nil
}
// 写开机自启动的plist
class func writeStringToFilePath(path: String, xmlString: String) {
do {
try xmlString.write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
} catch let e {
print(e.localizedDescription)
}
}
// 此方法需要签名才能用
class func triggerRunAtLogin(startup: Bool) {
// 这里请填写你自己的Heler BundleID
let launcherAppIdentifier = "com.cedric.KcptunMac.KcptunMacLauncher"
// 开始注册/取消启动项
let flag = SMLoginItemSetEnabled(launcherAppIdentifier as CFString, startup)
// if flag {
// let userDefaults = UserDefaults.standard
// userDefaults.set(startup, forKey: "LaunchAtLogin")
// userDefaults.synchronize()
// }
//
// var startedAtLogin = false
//
// for app in NSWorkspace.shared().runningApplications {
// if let id = app.bundleIdentifier {
// if id == launcherAppIdentifier {
// startedAtLogin = true
// }
// }
//
// }
//
// if startedAtLogin {
// DistributedNotificationCenter.default().post(name: NSNotification.Name(rawValue: "killhelper"), object: Bundle.main.bundleIdentifier!)
// }
}
}
| 5de1ea949570709880195005d79e8596 | 31.048276 | 148 | 0.576071 | false | false | false | false |
pdx-ios/tvOS-workshop | refs/heads/master | RoShamBo/RoShamBo/ViewController.swift | mit | 1 | //
// ViewController.swift
// RoShamBo
//
// Created by Ryan Arana on 10/6/15.
// Copyright © 2015 PDX-iOS. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var selectedButton: UIButton? {
didSet {
oldValue?.highlighted = false
selectedButton?.highlighted = true
}
}
@IBOutlet weak var inputsView: UIView!
@IBOutlet weak var resultsView: UIView!
@IBOutlet weak var winnerImage: UIImageView!
@IBOutlet weak var actionLabel: UILabel!
@IBOutlet weak var loserImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
resultsView.hidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonClicked(sender: UIButton) {
selectedButton = sender
let playerChoice = Choice(rawValue: sender.tag)!
let result = Game.play(playerChoice)
resultsView.hidden = false
if playerChoice == result.winner {
winnerImage.image = UIImage(named: "\(result.winner.name)-highlighted")
} else {
winnerImage.image = UIImage(named: result.winner.name)
}
if playerChoice == result.loser {
loserImage.image = UIImage(named: "\(result.loser.name)-highlighted")
} else {
loserImage.image = UIImage(named: result.loser.name)
}
actionLabel.text = result.summary
}
}
| 62c780f9b1c2ed752270c5391d0eab51 | 24.883333 | 83 | 0.629749 | false | false | false | false |
zwaldowski/URLGrey | refs/heads/swift-2_0 | URLGrey/Data+CollectionType.swift | mit | 1 | //
// Data+CollectionType.swift
// URLGrey
//
// Created by Zachary Waldowski on 2/7/15.
// Copyright © 2014-2015. Some rights reserved.
//
import Dispatch
/// The deallocation routine to use for custom-backed `Data` instances.
public enum UnsafeBufferOwnership<T> {
/// Copy the buffer passed in; the runtime will manage deallocation.
case Copy
/// Dealloc data created by `malloc` or equivalent.
case Free
/// Free data created by `mmap` or equivalent.
case Unmap
/// Provide some other deallocation routine.
case Custom(UnsafeBufferPointer<T> -> ())
}
public extension Data {
private init(unsafeWithBuffer buffer: UnsafeBufferPointer<T>, queue: dispatch_queue_t, destructor: dispatch_block_t?) {
let baseAddress = UnsafePointer<Void>(buffer.baseAddress)
let bytes = buffer.count * sizeof(T)
self.init(unsafe: dispatch_data_create(baseAddress, bytes, queue, destructor))
}
private init<Owner: CollectionType>(unsafeWithBuffer buffer: UnsafeBufferPointer<T>, queue: dispatch_queue_t = dispatch_get_global_queue(0, 0), owner: Owner) {
self.init(unsafeWithBuffer: buffer, queue: queue, destructor: { _ = owner })
}
/// Create `Data` backed by any arbitrary storage.
///
/// For the `behavior` parameter, pass:
/// - `.Copy` to copy the buffer passed in.
/// - `.Free` to dealloc data created by `malloc` or equivalent.
/// - `.Unmap` to free data created by `mmap` or equivalent.
/// - `.Custom` for some custom deallocation.
public init(unsafeWithBuffer buffer: UnsafeBufferPointer<T>, queue: dispatch_queue_t = dispatch_get_global_queue(0, 0), behavior: UnsafeBufferOwnership<T>) {
let destructor: dispatch_block_t?
switch behavior {
case .Copy:
destructor = nil
case .Free:
destructor = _dispatch_data_destructor_free
case .Unmap:
destructor = _dispatch_data_destructor_munmap
case .Custom(let fn):
destructor = { fn(buffer) }
}
self.init(unsafeWithBuffer: buffer, queue: queue, destructor: destructor)
}
/// Create `Data` backed by the contiguous contents of an array.
/// If the array itself is represented discontiguously, the initializer
/// must first create the storage.
public init(array: [T]) {
let buffer = array.withUnsafeBufferPointer { $0 }
self.init(unsafeWithBuffer: buffer, owner: array)
}
/// Create `Data` backed by a contiguous array.
public init(array: ContiguousArray<T>) {
let buffer = array.withUnsafeBufferPointer { $0 }
self.init(unsafeWithBuffer: buffer, owner: array)
}
}
| c0a552c2f118fa9a95df1e533c5a3294 | 37.492958 | 163 | 0.654226 | false | false | false | false |
congncif/IDMCore | refs/heads/master | IDMCore/Classes/SynchronizedArray.swift | mit | 1 | //
// SynchronizedArray.swift
// IDMCore
//
// Created by FOLY on 12/10/18.
// Thanks to Basem Emara
import Foundation
/// A thread-safe array.
public final class SynchronizedArray<Element> {
fileprivate var queue: DispatchQueue
fileprivate var array = [Element]()
public init(queue: DispatchQueue = DispatchQueue.concurrent,
elements: [Element] = []) {
self.queue = queue
self.array = elements
}
}
// MARK: - Properties
public extension SynchronizedArray {
/// The first element of the collection.
var first: Element? {
var result: Element?
queue.sync { result = self.array.first }
return result
}
/// The last element of the collection.
var last: Element? {
var result: Element?
queue.sync { result = self.array.last }
return result
}
/// The number of elements in the array.
var count: Int {
var result = 0
queue.sync { result = self.array.count }
return result
}
/// A Boolean value indicating whether the collection is empty.
var isEmpty: Bool {
var result = false
queue.sync { result = self.array.isEmpty }
return result
}
/// A textual representation of the array and its elements.
var description: String {
var result = ""
queue.sync { result = self.array.description }
return result
}
}
// MARK: - Immutable
public extension SynchronizedArray {
/// Returns the first element of the sequence that satisfies the given predicate.
///
/// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match.
/// - Returns: The first element of the sequence that satisfies predicate, or nil if there is no element that satisfies predicate.
func first(where predicate: (Element) -> Bool) -> Element? {
var result: Element?
queue.sync { result = self.array.first(where: predicate) }
return result
}
/// Returns the last element of the sequence that satisfies the given predicate.
///
/// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match.
/// - Returns: The last element of the sequence that satisfies predicate, or nil if there is no element that satisfies predicate.
func last(where predicate: (Element) -> Bool) -> Element? {
var result: Element?
queue.sync { result = self.array.last(where: predicate) }
return result
}
/// Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.
///
/// - Parameter isIncluded: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned array.
/// - Returns: An array of the elements that includeElement allowed.
func filter(_ isIncluded: @escaping (Element) -> Bool) -> SynchronizedArray {
var result: SynchronizedArray?
queue.sync {
result = SynchronizedArray(queue: self.queue, elements: self.array.filter(isIncluded))
}
return result ?? self
}
/// Returns the first index in which an element of the collection satisfies the given predicate.
///
/// - Parameter predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match.
/// - Returns: The index of the first element for which predicate returns true. If no elements in the collection satisfy the given predicate, returns nil.
func firstIndex(where predicate: (Element) -> Bool) -> Int? {
var result: Int?
queue.sync { result = self.array.firstIndex(where: predicate) }
return result
}
/// Returns the elements of the collection, sorted using the given predicate as the comparison between elements.
///
/// - Parameter areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false.
/// - Returns: A sorted array of the collection’s elements.
func sorted(by areInIncreasingOrder: (Element, Element) -> Bool) -> SynchronizedArray {
var result: SynchronizedArray?
queue.sync { result = SynchronizedArray(queue: self.queue, elements: self.array.sorted(by: areInIncreasingOrder)) }
return result ?? self
}
/// Returns an array containing the results of mapping the given closure over the sequence’s elements.
///
/// - Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value.
/// - Returns: An array of the non-nil results of calling transform with each element of the sequence.
func map<ElementOfResult>(_ transform: @escaping (Element) -> ElementOfResult) -> [ElementOfResult] {
var result = [ElementOfResult]()
queue.sync { result = self.array.map(transform) }
return result
}
/// Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.
///
/// - Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value.
/// - Returns: An array of the non-nil results of calling transform with each element of the sequence.
func compactMap<ElementOfResult>(_ transform: (Element) -> ElementOfResult?) -> [ElementOfResult] {
var result = [ElementOfResult]()
queue.sync { result = self.array.compactMap(transform) }
return result
}
/// Returns the result of combining the elements of the sequence using the given closure.
///
/// - Parameters:
/// - initialResult: The value to use as the initial accumulating value. initialResult is passed to nextPartialResult the first time the closure is executed.
/// - nextPartialResult: A closure that combines an accumulating value and an element of the sequence into a new accumulating value, to be used in the next call of the nextPartialResult closure or returned to the caller.
/// - Returns: The final accumulated value. If the sequence has no elements, the result is initialResult.
func reduce<ElementOfResult>(_ initialResult: ElementOfResult, _ nextPartialResult: @escaping (ElementOfResult, Element) -> ElementOfResult) -> ElementOfResult {
var result: ElementOfResult?
queue.sync { result = self.array.reduce(initialResult, nextPartialResult) }
return result ?? initialResult
}
/// Returns the result of combining the elements of the sequence using the given closure.
///
/// - Parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - updateAccumulatingResult: A closure that updates the accumulating value with an element of the sequence.
/// - Returns: The final accumulated value. If the sequence has no elements, the result is initialResult.
func reduce<ElementOfResult>(into initialResult: ElementOfResult, _ updateAccumulatingResult: @escaping (inout ElementOfResult, Element) -> Void) -> ElementOfResult {
var result: ElementOfResult?
queue.sync { result = self.array.reduce(into: initialResult, updateAccumulatingResult) }
return result ?? initialResult
}
/// Calls the given closure on each element in the sequence in the same order as a for-in loop.
///
/// - Parameter body: A closure that takes an element of the sequence as a parameter.
func forEach(_ body: (Element) -> Void) {
queue.sync { self.array.forEach(body) }
}
/// Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.
///
/// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element represents a match.
/// - Returns: true if the sequence contains an element that satisfies predicate; otherwise, false.
func contains(where predicate: (Element) -> Bool) -> Bool {
var result = false
queue.sync { result = self.array.contains(where: predicate) }
return result
}
/// Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.
///
/// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element satisfies a condition.
/// - Returns: true if the sequence contains only elements that satisfy predicate; otherwise, false.
func allSatisfy(_ predicate: (Element) -> Bool) -> Bool {
var result = false
queue.sync { result = self.array.allSatisfy(predicate) }
return result
}
}
// MARK: - Mutable
public extension SynchronizedArray {
/// Adds a new element at the end of the array.
///
/// The task is performed asynchronously due to thread-locking management.
///
/// - Parameters:
/// - element: The element to append to the array.
/// - completion: The block to execute when completed.
func append(_ element: Element, completion: (() -> Void)? = nil) {
queue.async(flags: .barrier) {
self.array.append(element)
DispatchQueue.main.async { completion?() }
}
}
/// Adds new elements at the end of the array.
///
/// The task is performed asynchronously due to thread-locking management.
///
/// - Parameters:
/// - element: The elements to append to the array.
/// - completion: The block to execute when completed.
func append(_ elements: [Element], completion: (() -> Void)? = nil) {
queue.async(flags: .barrier) {
self.array += elements
DispatchQueue.main.async { completion?() }
}
}
/// Inserts a new element at the specified position.
///
/// The task is performed asynchronously due to thread-locking management.
///
/// - Parameters:
/// - element: The new element to insert into the array.
/// - index: The position at which to insert the new element.
/// - completion: The block to execute when completed.
func insert(_ element: Element, at index: Int, completion: (() -> Void)? = nil) {
queue.async(flags: .barrier) {
self.array.insert(element, at: index)
DispatchQueue.main.async { completion?() }
}
}
/// Removes and returns the first element of the collection.
///
/// The collection must not be empty.
/// The task is performed asynchronously due to thread-locking management.
///
/// - Parameter completion: The handler with the removed element.
func removeFirst(completion: ((Element) -> Void)? = nil) {
queue.async(flags: .barrier) {
let element = self.array.removeFirst()
DispatchQueue.main.async { completion?(element) }
}
}
/// Removes the specified number of elements from the beginning of the collection.
///
/// The task is performed asynchronously due to thread-locking management.
///
/// - Parameters:
/// - k: The number of elements to remove from the collection.
/// - completion: The block to execute when remove completed.
func removeFirst(_ k: Int, completion: (() -> Void)? = nil) {
queue.async(flags: .barrier) {
defer { DispatchQueue.main.async { completion?() } }
guard 0...self.array.count ~= k else { return }
self.array.removeFirst(k)
}
}
/// Removes and returns the last element of the collection.
///
/// The collection must not be empty.
/// The task is performed asynchronously due to thread-locking management.
///
/// - Parameter completion: The handler with the removed element.
func removeLast(completion: ((Element) -> Void)? = nil) {
queue.async(flags: .barrier) {
let element = self.array.removeLast()
DispatchQueue.main.async { completion?(element) }
}
}
/// Removes the specified number of elements from the end of the collection.
///
/// The task is performed asynchronously due to thread-locking management.
///
/// - Parameters:
/// - k: The number of elements to remove from the collection.
/// - completion: The block to execute when remove completed.
func removeLast(_ k: Int, completion: (() -> Void)? = nil) {
queue.async(flags: .barrier) {
defer { DispatchQueue.main.async { completion?() } }
guard 0...self.array.count ~= k else { return }
self.array.removeLast(k)
}
}
/// Removes and returns the element at the specified position.
///
/// The task is performed asynchronously due to thread-locking management.
///
/// - Parameters:
/// - index: The position of the element to remove.
/// - completion: The handler with the removed element.
func remove(at index: Int, completion: ((Element) -> Void)? = nil) {
queue.async(flags: .barrier) {
let element = self.array.remove(at: index)
DispatchQueue.main.async { completion?(element) }
}
}
/// Removes and returns the elements that meet the criteria.
///
/// The task is performed asynchronously due to thread-locking management.
///
/// - Parameters:
/// - predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match.
/// - completion: The handler with the removed elements.
func remove(where predicate: @escaping (Element) -> Bool, completion: (([Element]) -> Void)? = nil) {
queue.async(flags: .barrier) {
var elements = [Element]()
while let index = self.array.firstIndex(where: predicate) {
elements.append(self.array.remove(at: index))
}
DispatchQueue.main.async { completion?(elements) }
}
}
/// Removes all elements from the array.
///
/// The task is performed asynchronously due to thread-locking management.
///
/// - Parameter completion: The handler with the removed elements.
func removeAll(completion: (([Element]) -> Void)? = nil) {
queue.async(flags: .barrier) {
let elements = self.array
self.array.removeAll()
DispatchQueue.main.async { completion?(elements) }
}
}
}
public extension SynchronizedArray {
/// Accesses the element at the specified position if it exists.
///
/// - Parameter index: The position of the element to access.
/// - Returns: optional element if it exists.
subscript(index: Int) -> Element? {
get {
var result: Element?
queue.sync {
result = self.array[safe: index]
}
return result
}
set {
guard let newValue = newValue else { return }
queue.async(flags: .barrier) {
self.array[index] = newValue
}
}
}
}
// MARK: - Equatable
public extension SynchronizedArray where Element: Equatable {
/// Returns a Boolean value indicating whether the sequence contains the given element.
///
/// - Parameter element: The element to find in the sequence.
/// - Returns: true if the element was found in the sequence; otherwise, false.
func contains(_ element: Element) -> Bool {
var result = false
queue.sync { result = self.array.contains(element) }
return result
}
/// Removes the specified element.
///
/// The task is performed asynchronously due to thread-locking management.
///
/// - Parameter element: An element to search for in the collection.
func remove(_ element: Element, completion: (() -> Void)? = nil) {
queue.async(flags: .barrier) {
self.array.remove(element)
DispatchQueue.main.async { completion?() }
}
}
/// Removes the specified element.
///
/// The task is performed asynchronously due to thread-locking management.
///
/// - Parameters:
/// - left: The collection to remove from.
/// - right: An element to search for in the collection.
static func -= (left: inout SynchronizedArray, right: Element) {
left.remove(right)
}
}
// MARK: - Infix operators
public extension SynchronizedArray {
/// Adds a new element at the end of the array.
///
/// The task is performed asynchronously due to thread-locking management.
///
/// - Parameters:
/// - left: The collection to append to.
/// - right: The element to append to the array.
static func += (left: inout SynchronizedArray, right: Element) {
left.append(right)
}
/// Adds new elements at the end of the array.
///
/// The task is performed asynchronously due to thread-locking management.
///
/// - Parameters:
/// - left: The collection to append to.
/// - right: The elements to append to the array.
static func += (left: inout SynchronizedArray, right: [Element]) {
left.append(right)
}
}
private extension SynchronizedArray {
// swiftlint:disable file_length
}
extension Array where Element: Equatable {
mutating func remove(_ element: Element) {
guard let index = firstIndex(of: element) else { return }
remove(at: index)
}
}
extension Collection {
subscript(safe index: Index) -> Element? {
// http://www.vadimbulavin.com/handling-out-of-bounds-exception/
return indices.contains(index) ? self[index] : nil
}
}
| a9fa4ad1c66ec535a290a45ff888a018 | 40.006818 | 226 | 0.64773 | false | false | false | false |
WickedColdfront/Slide-iOS | refs/heads/master | Pods/MisterFusion/MisterFusion/MisterFusion.swift | apache-2.0 | 2 | //
// MisterFusion.swift
// MisterFusion
//
// Created by Taiki Suzuki on 2015/11/13.
// Copyright © 2015年 Taiki Suzuki. All rights reserved.
//
import UIKit
open class MisterFusion: NSObject {
fileprivate let item: UIView?
fileprivate let attribute: NSLayoutAttribute?
fileprivate let relatedBy: NSLayoutRelation?
fileprivate let toItem: UIView?
fileprivate let toAttribute: NSLayoutAttribute?
fileprivate let multiplier: CGFloat?
fileprivate let constant: CGFloat?
fileprivate let priority: UILayoutPriority?
fileprivate let horizontalSizeClass: UIUserInterfaceSizeClass?
fileprivate let verticalSizeClass: UIUserInterfaceSizeClass?
fileprivate let identifier: String?
override open var description: String {
return "\(super.description)\n" +
"item : \(item as UIView?)\n" +
"attribute : \(attribute as NSLayoutAttribute?))\n" +
"relatedBy : \(relatedBy as NSLayoutRelation?))\n" +
"toItem : \(toItem as UIView?)\n" +
"toAttribute : \(toAttribute as NSLayoutAttribute?))\n" +
"multiplier : \(multiplier as CGFloat?)\n" +
"constant : \(constant as CGFloat?)\n" +
"priority : \(priority as UILayoutPriority?)\n" +
"horizontalSizeClass: \(horizontalSizeClass as UIUserInterfaceSizeClass?)\n" +
"verticalSizeClass : \(verticalSizeClass as UIUserInterfaceSizeClass?)\n"
}
init(item: UIView?, attribute: NSLayoutAttribute?, relatedBy: NSLayoutRelation?, toItem: UIView?, toAttribute: NSLayoutAttribute?, multiplier: CGFloat?, constant: CGFloat?, priority: UILayoutPriority?, horizontalSizeClass: UIUserInterfaceSizeClass?, verticalSizeClass: UIUserInterfaceSizeClass?, identifier: String?) {
self.item = item
self.attribute = attribute
self.relatedBy = relatedBy
self.toItem = toItem
self.toAttribute = toAttribute
self.multiplier = multiplier
self.constant = constant
self.priority = priority
self.horizontalSizeClass = horizontalSizeClass
self.verticalSizeClass = verticalSizeClass
self.identifier = identifier
super.init()
}
@available(*, unavailable)
open var Equal: (MisterFusion) -> MisterFusion? {
return { [weak self] in
guard let me = self else { return nil }
return me |==| $0
}
}
@available(*, unavailable)
open var NotRelatedEqualConstant: (CGFloat) -> MisterFusion? {
return { [weak self] in
guard let me = self else { return nil }
return me |==| $0
}
}
@available(*, unavailable)
open var LessThanOrEqual: (MisterFusion) -> MisterFusion? {
return { [weak self] in
guard let me = self else { return nil }
return me |<=| $0
}
}
@available(iOS, unavailable)
open var NotRelatedLessThanOrEqualConstant: (CGFloat) -> MisterFusion? {
return { [weak self] in
guard let me = self else { return nil }
return me |<=| $0
}
}
@available(iOS, unavailable)
open var GreaterThanOrEqual: (MisterFusion) -> MisterFusion? {
return { [weak self] in
guard let me = self else { return nil }
return me |>=| $0
}
}
@available(iOS, unavailable)
open var NotRelatedGreaterThanOrEqualConstant: (CGFloat) -> MisterFusion? {
return { [weak self] in
guard let me = self else { return nil }
return me |>=| $0
}
}
@available(iOS, unavailable)
open var Multiplier: (CGFloat) -> MisterFusion? {
return { [weak self] in
guard let me = self else { return nil }
return me |*| $0
}
}
@available(iOS, unavailable)
open var Constant: (CGFloat) -> MisterFusion? {
return { [weak self] in
guard let me = self else { return nil }
return me |+| $0
}
}
@available(iOS, unavailable)
open var Priority: (UILayoutPriority) -> MisterFusion? {
return { [weak self] in
guard let me = self else { return nil }
return me |<>| $0
}
}
@available(*, unavailable)
open var NotRelatedConstant: (CGFloat) -> MisterFusion? {
return { [weak self] in
guard let me = self else { return nil }
return me |==| $0
}
}
@available(*, unavailable)
open var HorizontalSizeClass: (UIUserInterfaceSizeClass) -> MisterFusion? {
return { [weak self] in
guard let me = self else { return nil }
return me <-> $0
}
}
@available(*, unavailable)
open var VerticalSizeClass: (UIUserInterfaceSizeClass) -> MisterFusion? {
return { [weak self] in
guard let me = self else { return nil }
return me <|> $0
}
}
@available(*, unavailable)
open var Identifier: (String) -> MisterFusion? {
return { [weak self] in
guard let me = self else { return nil }
return me -=- $0
}
}
}
precedencegroup MisterFusionAdditive {
associativity: left
higherThan: TernaryPrecedence, CastingPrecedence, AssignmentPrecedence
}
infix operator |==| : MisterFusionAdditive
public func |==| (left: MisterFusion, right: MisterFusion) -> MisterFusion {
return MisterFusion(item: left.item, attribute: left.attribute, relatedBy: .equal, toItem: right.item, toAttribute: right.attribute, multiplier: nil, constant: nil, priority: nil, horizontalSizeClass: nil, verticalSizeClass: nil, identifier: left.identifier)
}
public func |==| (left: MisterFusion, right: CGFloat) -> MisterFusion {
return MisterFusion(item: left.item, attribute: left.attribute, relatedBy: .equal, toItem: nil, toAttribute: .notAnAttribute, multiplier: nil, constant: right, priority: nil, horizontalSizeClass: nil, verticalSizeClass: nil, identifier: left.identifier)
}
infix operator |<=| : MisterFusionAdditive
public func |<=| (left: MisterFusion, right: MisterFusion) -> MisterFusion {
return MisterFusion(item: left.item, attribute: left.attribute, relatedBy: .lessThanOrEqual, toItem: right.item, toAttribute: right.attribute, multiplier: nil, constant: nil, priority: nil, horizontalSizeClass: nil, verticalSizeClass: nil, identifier: left.identifier)
}
public func |<=| (left: MisterFusion, right: CGFloat) -> MisterFusion {
let toAttribute = left.attribute == .height || left.attribute == .width ? .notAnAttribute : left.attribute
return MisterFusion(item: left.item, attribute: left.attribute, relatedBy: .lessThanOrEqual, toItem: nil, toAttribute: toAttribute, multiplier: nil, constant: right, priority: nil, horizontalSizeClass: nil, verticalSizeClass: nil, identifier: left.identifier)
}
infix operator |>=| : MisterFusionAdditive
public func |>=| (left: MisterFusion, right: MisterFusion) -> MisterFusion {
return MisterFusion(item: left.item, attribute: left.attribute, relatedBy: .greaterThanOrEqual, toItem: right.item, toAttribute: right.attribute, multiplier: nil, constant: nil, priority: nil, horizontalSizeClass: nil, verticalSizeClass: nil, identifier: left.identifier)
}
public func |>=| (left: MisterFusion, right: CGFloat) -> MisterFusion {
let toAttribute = left.attribute == .height || left.attribute == .width ? .notAnAttribute : left.attribute
return MisterFusion(item: left.item, attribute: left.attribute, relatedBy: .greaterThanOrEqual, toItem: nil, toAttribute: toAttribute, multiplier: nil, constant: right, priority: nil, horizontalSizeClass: nil, verticalSizeClass: nil, identifier: left.identifier)
}
infix operator |+| : MisterFusionAdditive
public func |+| (left: MisterFusion, right: CGFloat) -> MisterFusion {
return MisterFusion(item: left.item, attribute: left.attribute, relatedBy: left.relatedBy, toItem: left.toItem, toAttribute: left.toAttribute, multiplier: left.multiplier, constant: right, priority: left.priority, horizontalSizeClass: left.horizontalSizeClass, verticalSizeClass: left.verticalSizeClass, identifier: left.identifier)
}
infix operator |-| : MisterFusionAdditive
public func |-| (left: MisterFusion, right: CGFloat) -> MisterFusion {
return MisterFusion(item: left.item, attribute: left.attribute, relatedBy: left.relatedBy, toItem: left.toItem, toAttribute: left.toAttribute, multiplier: left.multiplier, constant: -right, priority: left.priority, horizontalSizeClass: left.horizontalSizeClass, verticalSizeClass: left.verticalSizeClass, identifier: left.identifier)
}
infix operator |*| : MisterFusionAdditive
public func |*| (left: MisterFusion, right: CGFloat) -> MisterFusion {
return MisterFusion(item: left.item, attribute: left.attribute, relatedBy: left.relatedBy, toItem: left.toItem, toAttribute: left.toAttribute, multiplier: right, constant: left.constant, priority: left.priority, horizontalSizeClass: left.horizontalSizeClass, verticalSizeClass: left.verticalSizeClass, identifier: left.identifier)
}
infix operator |/| : MisterFusionAdditive
public func |/| (left: MisterFusion, right: CGFloat) -> MisterFusion {
return MisterFusion(item: left.item, attribute: left.attribute, relatedBy: left.relatedBy, toItem: left.toItem, toAttribute: left.toAttribute, multiplier: 1 / right, constant: left.constant, priority: left.priority, horizontalSizeClass: left.horizontalSizeClass, verticalSizeClass: left.verticalSizeClass, identifier: left.identifier)
}
infix operator |<>| : MisterFusionAdditive
public func |<>| (left: MisterFusion, right: UILayoutPriority) -> MisterFusion {
return MisterFusion(item: left.item, attribute: left.attribute, relatedBy: left.relatedBy, toItem: left.toItem, toAttribute: left.toAttribute, multiplier: left.multiplier, constant: left.constant, priority: right, horizontalSizeClass: left.horizontalSizeClass, verticalSizeClass: left.verticalSizeClass, identifier: left.identifier)
}
infix operator <-> : MisterFusionAdditive
public func <-> (left: MisterFusion, right: UIUserInterfaceSizeClass) -> MisterFusion {
return MisterFusion(item: left.item, attribute: left.attribute, relatedBy: left.relatedBy, toItem: left.toItem, toAttribute: left.toAttribute, multiplier: left.multiplier, constant: left.constant, priority: left.priority, horizontalSizeClass: right, verticalSizeClass: left.verticalSizeClass, identifier: left.identifier)
}
infix operator <|> : MisterFusionAdditive
public func <|> (left: MisterFusion, right: UIUserInterfaceSizeClass) -> MisterFusion {
return MisterFusion(item: left.item, attribute: left.attribute, relatedBy: left.relatedBy, toItem: left.toItem, toAttribute: left.toAttribute, multiplier: left.multiplier, constant: left.constant, priority: left.priority, horizontalSizeClass: left.horizontalSizeClass, verticalSizeClass: right, identifier: left.identifier)
}
infix operator -=- : MisterFusionAdditive
public func -=- (left: MisterFusion, right: String) -> MisterFusion {
return MisterFusion(item: left.item, attribute: left.attribute, relatedBy: left.relatedBy, toItem: left.toItem, toAttribute: left.toAttribute, multiplier: left.multiplier, constant: left.constant, priority: left.priority, horizontalSizeClass: left.horizontalSizeClass, verticalSizeClass: left.verticalSizeClass, identifier: right)
}
extension UIView {
@objc(Top)
public var top: MisterFusion { return createMisterFusion(withAttribute: .top) }
@objc(Right)
public var right: MisterFusion { return createMisterFusion(withAttribute: .right) }
@objc(Left)
public var left: MisterFusion { return createMisterFusion(withAttribute: .left) }
@objc(Bottom)
public var bottom: MisterFusion { return createMisterFusion(withAttribute: .bottom) }
@objc(Height)
public var height: MisterFusion { return createMisterFusion(withAttribute: .height) }
@objc(Width)
public var width: MisterFusion { return createMisterFusion(withAttribute: .width) }
@objc(Leading)
public var leading: MisterFusion { return createMisterFusion(withAttribute: .leading) }
@objc(Trailing)
public var trailing: MisterFusion { return createMisterFusion(withAttribute: .trailing) }
@objc(CenterX)
public var centerX: MisterFusion { return createMisterFusion(withAttribute: .centerX) }
@objc(CenterY)
public var centerY: MisterFusion { return createMisterFusion(withAttribute: .centerY) }
@available(iOS, obsoleted: 7.0, renamed: "lastBaseline")
@objc(Baseline)
public var baseline: MisterFusion { return createMisterFusion(withAttribute: .lastBaseline) }
@objc(NotAnAttribute)
public var notAnAttribute: MisterFusion { return createMisterFusion(withAttribute: .notAnAttribute) }
@objc(LastBaseline)
public var lastBaseline: MisterFusion { return createMisterFusion(withAttribute: .lastBaseline) }
@available(iOS 8.0, *)
@objc(FirstBaseline)
public var firstBaseline: MisterFusion { return createMisterFusion(withAttribute: .firstBaseline) }
@available(iOS 8.0, *)
@objc(LeftMargin)
public var leftMargin: MisterFusion { return createMisterFusion(withAttribute: .leftMargin) }
@available(iOS 8.0, *)
@objc(RightMargin)
public var rightMargin: MisterFusion { return createMisterFusion(withAttribute: .rightMargin) }
@available(iOS 8.0, *)
@objc(TopMargin)
public var topMargin: MisterFusion { return createMisterFusion(withAttribute: .topMargin) }
@available(iOS 8.0, *)
@objc(BottomMargin)
public var bottomMargin: MisterFusion { return createMisterFusion(withAttribute: .bottomMargin) }
@available(iOS 8.0, *)
@objc(LeadingMargin)
public var leadingMargin: MisterFusion { return createMisterFusion(withAttribute: .leadingMargin) }
@available(iOS 8.0, *)
@objc(TrailingMargin)
public var trailingMargin: MisterFusion { return createMisterFusion(withAttribute: .trailingMargin) }
@available(iOS 8.0, *)
@objc(CenterXWithinMargins)
public var centerXWithinMargins: MisterFusion { return createMisterFusion(withAttribute: .centerXWithinMargins) }
@available(iOS 8.0, *)
@objc(CenterYWithinMargins)
public var centerYWithinMargins: MisterFusion { return createMisterFusion(withAttribute: .centerYWithinMargins) }
fileprivate func createMisterFusion(withAttribute attribute: NSLayoutAttribute) -> MisterFusion {
return MisterFusion(item: self, attribute: attribute, relatedBy: nil, toItem: nil, toAttribute: nil, multiplier: nil, constant: nil, priority: nil, horizontalSizeClass: nil, verticalSizeClass: nil, identifier: nil)
}
}
extension UIView {
//MARK: - addConstraint()
func _addLayoutConstraint(_ misterFusion: MisterFusion) -> NSLayoutConstraint? {
let item: UIView = misterFusion.item ?? self
let traitCollection = UIApplication.shared.keyWindow?.traitCollection
if let horizontalSizeClass = misterFusion.horizontalSizeClass
, horizontalSizeClass != traitCollection?.horizontalSizeClass {
return nil
}
if let verticalSizeClass = misterFusion.verticalSizeClass
, verticalSizeClass != traitCollection?.verticalSizeClass {
return nil
}
let attribute: NSLayoutAttribute = misterFusion.attribute ?? .notAnAttribute
let relatedBy: NSLayoutRelation = misterFusion.relatedBy ?? .equal
let toAttribute: NSLayoutAttribute = misterFusion.toAttribute ?? attribute
let toItem: UIView? = toAttribute == .notAnAttribute ? nil : misterFusion.toItem ?? self
let multiplier: CGFloat = misterFusion.multiplier ?? 1
let constant: CGFloat = misterFusion.constant ?? 0
let constraint = NSLayoutConstraint(item: item, attribute: attribute, relatedBy: relatedBy, toItem: toItem, attribute: toAttribute, multiplier: multiplier, constant: constant)
constraint.priority = misterFusion.priority ?? UILayoutPriorityRequired
constraint.identifier = misterFusion.identifier
addConstraint(constraint)
return constraint
}
func _addLayoutConstraints(_ misterFusions: [MisterFusion]) -> [NSLayoutConstraint] {
return misterFusions.flatMap { _addLayoutConstraint($0) }
}
//MARK: - addSubview()
func _addLayoutSubview(_ subview: UIView, andConstraint misterFusion: MisterFusion) -> NSLayoutConstraint? {
addSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = false
return _addLayoutConstraint(misterFusion)
}
func _addLayoutSubview(_ subview: UIView, andConstraints misterFusions: [MisterFusion]) -> [NSLayoutConstraint] {
addSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = false
return _addLayoutConstraints(misterFusions)
}
//MARK: - insertSubview(_ at:_)
func _insertLayoutSubview(_ subview: UIView, at index: Int, andConstraint misterFusion: MisterFusion) -> NSLayoutConstraint? {
insertSubview(subview, at: index)
subview.translatesAutoresizingMaskIntoConstraints = false
return _addLayoutConstraint(misterFusion)
}
func _insertLayoutSubview(_ subview: UIView, at index: Int, andConstraints misterFusions: [MisterFusion]) -> [NSLayoutConstraint] {
insertSubview(subview, at: index)
subview.translatesAutoresizingMaskIntoConstraints = false
return _addLayoutConstraints(misterFusions)
}
//MARK: - insertSubview(_ belowSubview:_)
func _insertLayoutSubview(_ subview: UIView, belowSubview siblingSubview: UIView, andConstraint misterFusion: MisterFusion) -> NSLayoutConstraint? {
insertSubview(subview, belowSubview: siblingSubview)
subview.translatesAutoresizingMaskIntoConstraints = false
return _addLayoutConstraint(misterFusion)
}
func _insertLayoutSubview(_ subview: UIView, belowSubview siblingSubview: UIView, andConstraints misterFusions: [MisterFusion]) -> [NSLayoutConstraint] {
insertSubview(subview, belowSubview: siblingSubview)
subview.translatesAutoresizingMaskIntoConstraints = false
return _addLayoutConstraints(misterFusions)
}
//MARK: - insertSubview(_ aboveSubview:_)
func _insertLayoutSubview(_ subview: UIView, aboveSubview siblingSubview: UIView, andConstraint misterFusion: MisterFusion) -> NSLayoutConstraint? {
insertSubview(subview, aboveSubview: siblingSubview)
subview.translatesAutoresizingMaskIntoConstraints = false
return _addLayoutConstraint(misterFusion)
}
func _insertLayoutSubview(_ subview: UIView, aboveSubview siblingSubview: UIView, andConstraints misterFusions: [MisterFusion]) -> [NSLayoutConstraint] {
insertSubview(subview, aboveSubview: siblingSubview)
subview.translatesAutoresizingMaskIntoConstraints = false
return _addLayoutConstraints(misterFusions)
}
}
| 472924823dfe3d8d7279e4a626244fd3 | 47.578283 | 338 | 0.701565 | false | false | false | false |
smoope/ios-sdk | refs/heads/master | Pod/Classes/TraversonOAuthAuthenticator.swift | apache-2.0 | 1 | /*
* Copyright 2016 smoope GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import SwiftyTraverson
import Alamofire
public class TraversonOAuthAuthenticator: TraversonAuthenticator {
var clientId: String
var secret: String
var url: String
public var retries = 2
public init(url: String, clientId: String, secret: String) {
self.url = url
self.clientId = clientId
self.secret = secret
}
public func authenticate(result: TraversonAuthenticatorResult) {
Alamofire.request(.POST, url, parameters: ["grant_type": "client_credentials"], encoding: .URL)
.authenticate(user: clientId, password: secret)
.responseJSON { response in
switch response.result {
case .Success(let json):
let response = json as! NSDictionary
result(authorizationHeader: response.objectForKey("access_token") as? String)
break
default:
result(authorizationHeader: nil)
}
}
}
}
| 6147c5b7a48df5df31a6d17c37878e48 | 28.192308 | 99 | 0.698287 | false | false | false | false |
csound/csound | refs/heads/develop | iOS/Csound iOS Swift Examples/Csound iOS SwiftExamples/CsoundVirtualKeyboard.swift | lgpl-2.1 | 3 | /*
CsoundVirtualKeyboard.swift
Nikhil Singh, Dr. Richard Boulanger
Adapted from the Csound iOS Examples by Steven Yi and Victor Lazzarini
This file is part of Csound iOS SwiftExamples.
The Csound for iOS Library is free software; you can redistribute it
and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
Csound is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Csound; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
*/
import UIKit
class CsoundVirtualKeyboard: UIView {
// Variable declarations
private var keyDown = [Bool].init(repeating: false, count: 25)
private var currentTouches = NSMutableSet()
private var keyRects = [CGRect](repeatElement(CGRect(), count: 25))
private var lastWidth: CGFloat = 0.0
private let keysNum = 25
@IBOutlet var keyboardDelegate: AnyObject? // keyboardDelegate object will handle key presses and releases
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
isMultipleTouchEnabled = true // Enable multiple touch so we can press multiple keys
}
// Check if a key is a white key or a black key depending on its index
func isWhiteKey(_ key: Int) -> Bool {
switch (key % 12) {
case 0, 2, 4, 5, 7, 9, 11:
return true
default:
return false
}
}
// MARK: Update key statuses
private func updateKeyRects() {
if lastWidth == bounds.size.width { return }
lastWidth = bounds.size.width
let whiteKeyHeight: CGFloat = bounds.size.height
let blackKeyHeight: CGFloat = whiteKeyHeight * 0.625
let whiteKeyWidth: CGFloat = bounds.size.width/15.0
let blackKeyWidth: CGFloat = whiteKeyWidth * 0.833333
let leftKeyBound: CGFloat = whiteKeyWidth - (blackKeyWidth / 2.0)
var lastWhiteKey: CGFloat = 0
keyRects[0] = CGRect(x: 0, y: 0, width: whiteKeyWidth, height: whiteKeyHeight)
for i in 1 ..< keysNum {
if !(isWhiteKey(i)) {
keyRects[i] = CGRect(x: (lastWhiteKey * whiteKeyWidth) + leftKeyBound, y: 0, width: blackKeyWidth, height: blackKeyHeight)
} else {
lastWhiteKey += 1
keyRects[i] = CGRect(x: lastWhiteKey * whiteKeyWidth, y: 0, width: whiteKeyWidth, height: whiteKeyHeight)
}
}
}
private func getKeyboardKey(_ point: CGPoint) -> Int {
var keyNum = -1
for i in 0 ..< keysNum {
if keyRects[i].contains(point) {
keyNum = i
if !(isWhiteKey(i)) {
break
}
}
}
return keyNum
}
private func updateKeyStates() {
updateKeyRects()
var count = 0
let touches = currentTouches.allObjects
count = touches.count
var currentKeyState = [Bool](repeatElement(true, count: keysNum))
for i in 0 ..< keysNum {
currentKeyState[i] = false
}
for i in 0 ..< count {
let touch = touches[i] as! UITouch
let point = touch.location(in: self)
let index = getKeyboardKey(point)
if index != -1 {
currentKeyState[index] = true
}
}
var keysUpdated = false
for i in 0 ..< keysNum {
if keyDown[i] != currentKeyState[i] {
keysUpdated = true
let keyDownState = currentKeyState[i]
keyDown[i] = keyDownState
if keyboardDelegate != nil {
if keyDownState {
keyboardDelegate?.keyDown(self, keyNum: i)
} else {
keyboardDelegate?.keyUp(self, keyNum: i)
}
}
}
}
if keysUpdated {
DispatchQueue.main.async { [unowned self] in
self.setNeedsDisplay()
}
}
}
// MARK: Touch Handling Code
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
currentTouches.add(touch)
}
updateKeyStates()
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
updateKeyStates()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
currentTouches.remove(touch)
}
updateKeyStates()
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
currentTouches.remove(touch)
}
updateKeyStates()
}
// MARK: Drawing Code
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let whiteKeyHeight = rect.size.height
let blackKeyHeight = round(rect.size.height * 0.625)
let whiteKeyWidth = rect.size.width/15.0
let blackKeyWidth = whiteKeyWidth * 0.8333333
let blackKeyOffset = blackKeyWidth/2.0
var runningX: CGFloat = 0
let yval = 0
context?.setFillColor(UIColor.white.cgColor)
context?.fill(bounds)
context?.setStrokeColor(UIColor.black.cgColor)
context?.stroke(bounds)
let lineHeight = whiteKeyHeight - 1
var newX = 0
for i in 0 ..< keysNum {
if isWhiteKey(i) {
newX = Int(round(runningX + 0.5))
if keyDown[i] {
let newW = Int(round(runningX + whiteKeyWidth + 0.5) - CGFloat(newX))
context?.setFillColor(UIColor.blue.cgColor)
context?.fill(CGRect(x: CGFloat(newX), y: CGFloat(yval), width: CGFloat(newW), height: whiteKeyHeight - 1))
}
runningX += whiteKeyWidth
context?.setStrokeColor(UIColor.black.cgColor)
context?.stroke(CGRect(x: CGFloat(newX), y: CGFloat(yval), width: CGFloat(newX), height: lineHeight))
}
}
runningX = 0
for i in 0 ..< keysNum {
if isWhiteKey(i) {
runningX += whiteKeyWidth
} else {
if keyDown[i] {
context?.setFillColor(UIColor.blue.cgColor)
} else {
context?.setFillColor(UIColor.black.cgColor)
}
context?.fill(CGRect(x: runningX - blackKeyOffset, y: CGFloat(yval), width: blackKeyWidth, height: blackKeyHeight))
context?.setStrokeColor(UIColor.black.cgColor)
context?.stroke(CGRect(x: runningX - blackKeyOffset, y: CGFloat(yval), width: blackKeyWidth, height: blackKeyHeight))
}
}
}
}
// Protocol for delegate to conform to
@objc protocol CsoundVirtualKeyboardDelegate {
func keyUp(_ keybd:CsoundVirtualKeyboard, keyNum:Int)
func keyDown(_ keybd:CsoundVirtualKeyboard, keyNum:Int)
}
| 972dcf42d82ba932e1ff69219bc6af4f | 32.121849 | 138 | 0.562603 | false | false | false | false |
crescentflare/UniLayout | refs/heads/master | UniLayoutIOS/Example/Tests/Utility/LayoutAnalyzer.swift | mit | 1 | //
// LayoutAnalyzer.swift
// Contains a trace of layout events for analysis
//
import UIKit
@testable import UniLayout
// --
// MARK: Layout analyzer
// --
class LayoutAnalyzer {
static var shared = LayoutAnalyzer()
var items = [LayoutAnalyzerItem]()
func clear() {
items = []
}
func add(_ item: LayoutAnalyzerItem) {
items.append(item)
}
func printEvents() {
var previousItem: LayoutAnalyzerItem?
for item in items {
item.printInfo(previousItem: previousItem)
previousItem = item
}
}
}
// --
// MARK: Layout analyzer item
// --
class LayoutAnalyzerItem {
let view: UIView
let type: LayoutAnalyzerType
let value: Any?
init(view: UIView, type: LayoutAnalyzerType, value: Any? = nil) {
self.view = view
self.type = type
self.value = value
}
func printInfo(previousItem: LayoutAnalyzerItem?) {
let viewLabel = view.accessibilityIdentifier ?? "unknown"
var operationInfo = ""
switch type {
case .changeText:
let stringValue = value as? String ?? ""
operationInfo = type.rawValue + " to '\(stringValue)'"
case .changeBounds:
let rectValue = value as? CGRect ?? CGRect.zero
operationInfo = type.rawValue + " to \(rectValue)"
default:
operationInfo = type.rawValue
}
print("View '\(viewLabel)' had operation: \(operationInfo)")
}
}
// --
// MARK: Layout analyzer event type enum
// --
enum LayoutAnalyzerType: String {
case layoutSubviews = "layout subviews"
case changeBounds = "change bounds"
case changeText = "change text"
}
| 9fb69e77272f1e1fe71547980ab25468 | 20.621951 | 69 | 0.583756 | false | false | false | false |
ontouchstart/swift3-playground | refs/heads/playgroundbook | Graphing.playgroundbook/Contents/Sources/PlaygroundInternal/LinePlotDrawable.swift | mit | 1 | //
// LineChartLayer.swift
// Charts
//
// Copyright © 2016 Apple Inc. All rights reserved.
//
import UIKit
private let FunctionSampleInternalInPoints = 1.0
internal class LinePlotDrawable: ChartDrawable {
var dataProvider: LineData?
var color = Color.blue
var symbol: Symbol? = Symbol()
var lineStyle = LineStyle.none
var lineWidth: CGFloat = 2.0
var label: String?
func draw(onChartView chartView: ChartView, context: CGContext) {
guard let dataProvider = dataProvider else { return }
let modelPoints = dataProvider.data(forBounds: chartView.axisBounds, chartView: chartView)
let screenPoints = modelPoints.map { modelPoint -> CGPoint in
return chartView.convertPointToScreen(modelPoint: CGPoint(x: modelPoint.0, y: modelPoint.1))
}
if lineStyle != .none {
let linePath = pathFromPoints(points: screenPoints)
linePath.lineWidth = lineWidth
switch lineStyle {
case .dashed:
linePath.setLineDash([6,10], count: 2, phase: 0)
case .dotted:
linePath.setLineDash([1,5], count: 2, phase: 0)
default:
break
}
context.setStrokeColor(color.cgColor)
linePath.lineJoinStyle = .round
linePath.stroke()
}
drawSymbolsAtPoints(points: modelPoints, inChartView: chartView, inContext: context)
}
private func pathFromPoints(points: [CGPoint]) -> UIBezierPath {
let path = UIBezierPath()
for (index, point) in points.enumerated() {
if (index == 0) {
path.move(to: point)
} else {
path.addLine(to: point)
}
}
return path
}
private func drawSymbolsAtPoints(points: [(Double, Double)], inChartView chartView: ChartView, inContext context: CGContext) {
guard let symbol = symbol else { return }
for point in points {
let screenPoint = chartView.convertPointToScreen(modelPoint: CGPoint(x: point.0, y: point.1))
symbol.draw(atCenterPoint: CGPoint(x: screenPoint.x, y: screenPoint.y), fillColor: color.uiColor, usingContext: context)
}
}
func boundsOfData(inChartView chartView: ChartView) -> Bounds {
guard let dataProvider = dataProvider else { return Bounds.infinite }
return dataProvider.boundsOfData(chartView: chartView)
}
func values(inScreenRect rect: CGRect, inChartView chartView: ChartView) -> [ChartValue] {
guard let dataProvider = dataProvider else { return [] }
let minPoint = chartView.convertPointFromScreen(screenPoint: CGPoint(x: rect.minX, y: rect.maxY))
let maxPoint = chartView.convertPointFromScreen(screenPoint: CGPoint(x: rect.maxX, y: rect.minY))
let bounds = Bounds(minX: Double(minPoint.x), maxX: Double(maxPoint.x), minY: Double(minPoint.y), maxY: Double(maxPoint.y))
return dataProvider.data(withinBounds: bounds, chartView: chartView).map { data in
let screenPoint = chartView.convertPointToScreen(modelPoint: CGPoint(x: data.1.0, y: data.1.1))
return ChartValue(label: label, index: data.0, value: data.1, color: color, screenPoint: screenPoint)
}
}
}
internal protocol LineData: CustomPlaygroundQuickLookable {
func boundsOfData(chartView: ChartView) -> Bounds
func data(forBounds bounds: Bounds, chartView: ChartView) -> [(Double, Double)]
func data(withinBounds bounds: Bounds, chartView: ChartView) -> [(Int?, (Double, Double))]
}
internal class DiscreteLineData: LineData {
private let xyData: XYData
init(xyData: XYData) {
self.xyData = xyData
}
func boundsOfData(chartView: ChartView) -> Bounds {
guard xyData.count > 0 else { return Bounds.infinite }
let xData = xyData.xData
let yData = xyData.yData
return Bounds(minX: xData.min()!, maxX: xData.max()!, minY: yData.min()!, maxY: yData.max()!)
}
func data(forBounds bounds: Bounds, chartView: ChartView) -> [(Double, Double)] {
// NOTE we may need to hand back data that appears outside the provided bounds otherwise data points/connections may be elided in the drawing.
return xyData.xyData
}
func data(withinBounds bounds: Bounds, chartView: ChartView) -> [(Int?, (Double, Double))] {
var dataWithinBounds = [(Int?, (Double, Double))]()
for (index, data) in xyData.xyData.enumerated() {
if bounds.contains(data: data) {
dataWithinBounds.append((index, data))
}
}
return dataWithinBounds
}
}
extension DiscreteLineData: CustomPlaygroundQuickLookable {
internal var customPlaygroundQuickLook: PlaygroundQuickLook {
get {
let numPoints = xyData.count
let suffix = numPoints == 1 ? "point" : "points"
return .text("\(numPoints) \(suffix)")
}
}
}
internal class FunctionLineData: LineData {
private let function: (Double) -> Double
init(function: (Double) -> Double) {
self.function = function
}
/// For function data, we use the current chart's x bounds and then sample the data to determine the y bounds.
func boundsOfData(chartView: ChartView) -> Bounds {
// grab the data for the current chart bounds.
var bounds = chartView.axisBounds
let boundedData = data(forBounds: bounds, chartView: chartView)
guard boundedData.count > 0 else { return Bounds.infinite }
// grab the y points for the data.
let yData = boundedData.map { $0.1 }
// update the x bounds to indicate that the data is unbounded.
bounds.minX = .infinity
bounds.maxX = .infinity
// udpate the bounds match the y data min and max values.
bounds.minY = yData.min()!
bounds.maxY = yData.max()!
return bounds
}
func data(forBounds bounds: Bounds, chartView: ChartView) -> [(Double, Double)] {
let axisBounds = chartView.axisBounds
let screenZeroAsModel = chartView.convertPointFromScreen(screenPoint: CGPoint.zero).x
let screenStrideOffsetAsModel = chartView.convertPointFromScreen(screenPoint: CGPoint(x: FunctionSampleInternalInPoints, y: 0.0)).x
let modelStride = Double(screenStrideOffsetAsModel - screenZeroAsModel)
var data = [(Double, Double)]()
for x in stride(from: axisBounds.minX, through: axisBounds.maxX, by: modelStride) {
data.append((x, function(x)))
}
// make sure we always go to the end.
data.append(axisBounds.maxX, function(axisBounds.maxX))
return data
}
func data(withinBounds bounds: Bounds, chartView: ChartView) -> [(Int?, (Double, Double))] {
let data = (bounds.midX, function(bounds.midX))
if bounds.contains(data: data) {
return [(nil, data)] // Function data won't ever have an index.
}
return []
}
}
extension FunctionLineData: CustomPlaygroundQuickLookable {
internal var customPlaygroundQuickLook: PlaygroundQuickLook {
get {
return .text(String(function))
}
}
}
| 0186ca86c80199111a390a623ac990d2 | 34.632075 | 150 | 0.616495 | false | false | false | false |
trill-lang/LLVMSwift | refs/heads/master | Sources/LLVM/OpCode.swift | mit | 1 | #if SWIFT_PACKAGE
import cllvm
#endif
/// Enumerates the opcodes of instructions available in the LLVM IR language.
public enum OpCode: CaseIterable {
// MARK: Terminator Instructions
/// The opcode for the `ret` instruction.
case ret
/// The opcode for the `br` instruction.
case br
/// The opcode for the `switch` instruction.
case `switch`
/// The opcode for the `indirectBr` instruction.
case indirectBr
/// The opcode for the `invoke` instruction.
case invoke
/// The opcode for the `unreachable` instruction.
case unreachable
// MARK: Standard Binary Operators
/// The opcode for the `add` instruction.
case add
/// The opcode for the `fadd` instruction.
case fadd
/// The opcode for the `sub` instruction.
case sub
/// The opcode for the `fsub` instruction.
case fsub
/// The opcode for the `mul` instruction.
case mul
/// The opcode for the `fmul` instruction.
case fmul
/// The opcode for the `udiv` instruction.
case udiv
/// The opcode for the `sdiv` instruction.
case sdiv
/// The opcode for the `fdiv` instruction.
case fdiv
/// The opcode for the `urem` instruction.
case urem
/// The opcode for the `srem` instruction.
case srem
/// The opcode for the `frem` instruction.
case frem
// MARK: Logical Operators
/// The opcode for the `shl` instruction.
case shl
/// The opcode for the `lshr` instruction.
case lshr
/// The opcode for the `ashr` instruction.
case ashr
/// The opcode for the `and` instruction.
case and
/// The opcode for the `or` instruction.
case or
/// The opcode for the `xor` instruction.
case xor
// MARK: Memory Operators
/// The opcode for the `alloca` instruction.
case alloca
/// The opcode for the `load` instruction.
case load
/// The opcode for the `store` instruction.
case store
/// The opcode for the `getElementPtr` instruction.
case getElementPtr
// MARK: Cast Operators
/// The opcode for the `trunc` instruction.
case trunc
/// The opcode for the `zext` instruction.
case zext
/// The opcode for the `sext` instruction.
case sext
/// The opcode for the `fpToUI` instruction.
case fpToUI
/// The opcode for the `fpToSI` instruction.
case fpToSI
/// The opcode for the `uiToFP` instruction.
case uiToFP
/// The opcode for the `siToFP` instruction.
case siToFP
/// The opcode for the `fpTrunc` instruction.
case fpTrunc
/// The opcode for the `fpExt` instruction.
case fpExt
/// The opcode for the `ptrToInt` instruction.
case ptrToInt
/// The opcode for the `intToPtr` instruction.
case intToPtr
/// The opcode for the `bitCast` instruction.
case bitCast
/// The opcode for the `addrSpaceCast` instruction.
case addrSpaceCast
// MARK: Other Operators
/// The opcode for the `icmp` instruction.
case icmp
/// The opcode for the `fcmp` instruction.
case fcmp
/// The opcode for the `PHI` instruction.
case phi
/// The opcode for the `call` instruction.
case call
/// The opcode for the `select` instruction.
case select
/// The opcode for the `userOp1` instruction.
case userOp1
/// The opcode for the `userOp2` instruction.
case userOp2
/// The opcode for the `vaArg` instruction.
case vaArg
/// The opcode for the `extractElement` instruction.
case extractElement
/// The opcode for the `insertElement` instruction.
case insertElement
/// The opcode for the `shuffleVector` instruction.
case shuffleVector
/// The opcode for the `extractValue` instruction.
case extractValue
/// The opcode for the `insertValue` instruction.
case insertValue
// MARK: Atomic operators
/// The opcode for the `fence` instruction.
case fence
/// The opcode for the `atomicCmpXchg` instruction.
case atomicCmpXchg
/// The opcode for the `atomicRMW` instruction.
case atomicRMW
// MARK: Exception Handling Operators
/// The opcode for the `resume` instruction.
case resume
/// The opcode for the `landingPad` instruction.
case landingPad
/// The opcode for the `cleanupRet` instruction.
case cleanupRet
/// The opcode for the `catchRet` instruction.
case catchRet
/// The opcode for the `catchPad` instruction.
case catchPad
/// The opcode for the `cleanupPad` instruction.
case cleanupPad
/// The opcode for the `catchSwitch` instruction.
case catchSwitch
/// Creates an `OpCode` from an `LLVMOpcode`
init(rawValue: LLVMOpcode) {
switch rawValue {
case LLVMRet: self = .ret
case LLVMBr: self = .br
case LLVMSwitch: self = .switch
case LLVMIndirectBr: self = .indirectBr
case LLVMInvoke: self = .invoke
case LLVMUnreachable: self = .unreachable
case LLVMAdd: self = .add
case LLVMFAdd: self = .fadd
case LLVMSub: self = .sub
case LLVMFSub: self = .fsub
case LLVMMul: self = .mul
case LLVMFMul: self = .fmul
case LLVMUDiv: self = .udiv
case LLVMSDiv: self = .sdiv
case LLVMFDiv: self = .fdiv
case LLVMURem: self = .urem
case LLVMSRem: self = .srem
case LLVMFRem: self = .frem
case LLVMShl: self = .shl
case LLVMLShr: self = .lshr
case LLVMAShr: self = .ashr
case LLVMAnd: self = .and
case LLVMOr: self = .or
case LLVMXor: self = .xor
case LLVMAlloca: self = .alloca
case LLVMLoad: self = .load
case LLVMStore: self = .store
case LLVMGetElementPtr: self = .getElementPtr
case LLVMTrunc: self = .trunc
case LLVMZExt: self = .zext
case LLVMSExt: self = .sext
case LLVMFPToUI: self = .fpToUI
case LLVMFPToSI: self = .fpToSI
case LLVMUIToFP: self = .uiToFP
case LLVMSIToFP: self = .siToFP
case LLVMFPTrunc: self = .fpTrunc
case LLVMFPExt: self = .fpExt
case LLVMPtrToInt: self = .ptrToInt
case LLVMIntToPtr: self = .intToPtr
case LLVMBitCast: self = .bitCast
case LLVMAddrSpaceCast: self = .addrSpaceCast
case LLVMICmp: self = .icmp
case LLVMFCmp: self = .fcmp
case LLVMPHI: self = .phi
case LLVMCall: self = .call
case LLVMSelect: self = .select
case LLVMUserOp1: self = .userOp1
case LLVMUserOp2: self = .userOp2
case LLVMVAArg: self = .vaArg
case LLVMExtractElement: self = .extractElement
case LLVMInsertElement: self = .insertElement
case LLVMShuffleVector: self = .shuffleVector
case LLVMExtractValue: self = .extractValue
case LLVMInsertValue: self = .insertValue
case LLVMFence: self = .fence
case LLVMAtomicCmpXchg: self = .atomicCmpXchg
case LLVMAtomicRMW: self = .atomicRMW
case LLVMResume: self = .resume
case LLVMLandingPad: self = .landingPad
case LLVMCleanupRet: self = .cleanupRet
case LLVMCatchRet: self = .catchRet
case LLVMCatchPad: self = .catchPad
case LLVMCleanupPad: self = .cleanupPad
case LLVMCatchSwitch: self = .catchSwitch
default: fatalError("invalid LLVMOpcode \(rawValue)")
}
}
}
extension OpCode {
/// `BinaryOperation` enumerates the subset of opcodes that are binary operations.
public enum Binary: CaseIterable {
/// The `add` instruction.
case add
/// The `fadd` instruction.
case fadd
/// The `sub` instruction.
case sub
/// The `fsub` instruction.
case fsub
/// The `mul` instruction.
case mul
/// The `fmul` instruction.
case fmul
/// The `udiv` instruction.
case udiv
/// The `sdiv` instruction.
case sdiv
/// The `fdiv` instruction.
case fdiv
/// The `urem` instruction.
case urem
/// The `srem` instruction.
case srem
/// The `frem` instruction.
case frem
/// The `shl` instruction.
case shl
/// The `lshr` instruction.
case lshr
/// The `ashr` instruction.
case ashr
/// The `and` instruction.
case and
/// The `or` instruction.
case or
/// The `xor` instruction.
case xor
static let binaryOperationMap: [Binary: LLVMOpcode] = [
.add: LLVMAdd, .fadd: LLVMFAdd, .sub: LLVMSub, .fsub: LLVMFSub,
.mul: LLVMMul, .fmul: LLVMFMul, .udiv: LLVMUDiv, .sdiv: LLVMSDiv,
.fdiv: LLVMFDiv, .urem: LLVMURem, .srem: LLVMSRem, .frem: LLVMFRem,
.shl: LLVMShl, .lshr: LLVMLShr, .ashr: LLVMAShr, .and: LLVMAnd,
.or: LLVMOr, .xor: LLVMXor,
]
/// Retrieves the corresponding `LLVMOpcode`.
public var llvm: LLVMOpcode {
return Binary.binaryOperationMap[self]!
}
/// Retrieves the corresponding opcode for this binary operation.
public var opCode: OpCode {
return OpCode(rawValue: self.llvm)
}
}
/// `CastOperation` enumerates the subset of opcodes that are cast operations.
public enum Cast: CaseIterable {
/// The `trunc` instruction.
case trunc
/// The `zext` instruction.
case zext
/// The `sext` instruction.
case sext
/// The `fpToUI` instruction.
case fpToUI
/// The `fpToSI` instruction.
case fpToSI
/// The `uiToFP` instruction.
case uiToFP
/// The `siToFP` instruction.
case siToFP
/// The `fpTrunc` instruction.
case fpTrunc
/// The `fpext` instruction.
case fpext
/// The `ptrToInt` instruction.
case ptrToInt
/// The `intToPtr` instruction.
case intToPtr
/// The `bitCast` instruction.
case bitCast
/// The `addrSpaceCast` instruction.
case addrSpaceCast
static let castOperationMap: [Cast: LLVMOpcode] = [
.trunc: LLVMTrunc,
.zext: LLVMZExt,
.sext: LLVMSExt,
.fpToUI: LLVMFPToUI,
.fpToSI: LLVMFPToSI,
.uiToFP: LLVMUIToFP,
.siToFP: LLVMSIToFP,
.fpTrunc: LLVMFPTrunc,
.fpext: LLVMFPExt,
.ptrToInt: LLVMPtrToInt,
.intToPtr: LLVMIntToPtr,
.bitCast: LLVMBitCast,
.addrSpaceCast: LLVMAddrSpaceCast,
]
/// Retrieves the corresponding `LLVMOpcode`.
public var llvm: LLVMOpcode {
return Cast.castOperationMap[self]!
}
/// Retrieves the corresponding opcode for this cast operation.
public var opCode: OpCode {
return OpCode(rawValue: self.llvm)
}
}
}
| a98f220255f57bd9ca91e1242f7ccc80 | 27.979769 | 84 | 0.664606 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/TBD/protocol.swift | apache-2.0 | 10 | // RUN: %target-swift-frontend -emit-ir -o- -parse-as-library -module-name test -validate-tbd-against-ir=missing %s
public protocol Public {
func publicMethod()
associatedtype PublicAT
var publicVarGet: Int { get }
var publicVarGetSet: Int { get set }
}
protocol Internal {
func internalMethod()
associatedtype InternalAT
var internalVarGet: Int { get }
var internalVarGetSet: Int { get set }
}
private protocol Private {
func privateMethod()
associatedtype PrivateAT
var privateVarGet: Int { get }
var privateVarGetSet: Int { get set }
}
// Naming scheme: type access, protocol access, witness access, type kind
public struct PublicPublicPublicStruct: Public {
public func publicMethod() {}
public typealias PublicAT = Int
public let publicVarGet: Int = 0
public var publicVarGetSet: Int = 0
}
public struct PublicInternalPublicStruct: Internal {
public func internalMethod() {}
public typealias InternalAT = Int
public let internalVarGet: Int = 0
public var internalVarGetSet: Int = 0
}
public struct PublicPrivatePublicStruct: Private {
public func privateMethod() {}
public typealias PrivateAT = Int
public let privateVarGet: Int = 0
public var privateVarGetSet: Int = 0
}
public struct PublicInternalInternalStruct: Internal {
func internalMethod() {}
typealias InternalAT = Int
let internalVarGet: Int = 0
var internalVarGetSet: Int = 0
}
public struct PublicPrivateInternalStruct: Private {
func privateMethod() {}
typealias PrivateAT = Int
let privateVarGet: Int = 0
var privateVarGetSet: Int = 0
}
public struct PublicPrivateFileprivateStruct: Private {
fileprivate func privateMethod() {}
fileprivate typealias PrivateAT = Int
fileprivate let privateVarGet: Int = 0
fileprivate var privateVarGetSet: Int = 0
}
struct InternalPublicInternalStruct: Public {
func publicMethod() {}
typealias PublicAT = Int
let publicVarGet: Int = 0
var publicVarGetSet: Int = 0
}
struct InternalInternalInternalStruct: Internal {
func internalMethod() {}
typealias InternalAT = Int
let internalVarGet: Int = 0
var internalVarGetSet: Int = 0
}
struct InternalPrivateInternalStruct: Private {
func privateMethod() {}
typealias PrivateAT = Int
let privateVarGet: Int = 0
var privateVarGetSet: Int = 0
}
struct InternalPrivateFileprivateStruct: Private {
fileprivate func privateMethod() {}
fileprivate typealias PrivateAT = Int
fileprivate let privateVarGet: Int = 0
fileprivate var privateVarGetSet: Int = 0
}
private struct PrivatePublicInternalStruct: Public {
func publicMethod() {}
typealias PublicAT = Int
let publicVarGet: Int = 0
var publicVarGetSet: Int = 0
}
private struct PrivateInternalInternalStruct: Internal {
func internalMethod() {}
typealias InternalAT = Int
let internalVarGet: Int = 0
var internalVarGetSet: Int = 0
}
private struct PrivatePrivateInternalStruct: Private {
func privateMethod() {}
typealias PrivateAT = Int
let privateVarGet: Int = 0
var privateVarGetSet: Int = 0
}
private struct PrivatePrivateFileprivateStruct: Private {
fileprivate func privateMethod() {}
fileprivate typealias PrivateAT = Int
fileprivate let privateVarGet: Int = 0
fileprivate var privateVarGetSet: Int = 0
}
| d3eedd67397303d69b27fdc20af8b5f7 | 27.745763 | 115 | 0.723172 | false | false | false | false |
Qmerce/ios-sdk | refs/heads/master | Sources/EmbededUnit/AdProvider/PubMatic/APEPubMaticViewProvider.swift | mit | 1 |
//
// APEPubMaticViewProvider.swift
// ApesterKit
//
// Created by Hasan Sawaed Tabash on 06/10/2021.
// Copyright © 2021 Apester. All rights reserved.
//
import Foundation
extension APEUnitView {
struct PubMaticViewProvider {
var view: POBBannerView?
var delegate: PubMaticViewDelegate?
}
}
extension APEUnitView.PubMaticViewProvider {
struct Params: Hashable {
enum AdType: String {
case bottom
case inUnit
var size: CGSize {
switch self {
case .bottom: return .init(width: 320, height: 50)
case .inUnit: return .init(width: 300, height: 250)
}
}
}
let adUnitId: String
let profileId: Int
let publisherId: String
let appStoreUrl: String
let isCompanionVariant: Bool
let adType: AdType
let appDomain: String
let testMode: Bool
let debugLogs: Bool
let bidSummaryLogs: Bool
let timeInView: Int?
init?(from dictionary: [String: Any]) {
guard let provider = dictionary[Constants.Monetization.adProvider] as? String,
provider == Constants.Monetization.pubMatic,
let appStoreUrl = dictionary[Constants.Monetization.appStoreUrl] as? String,
let profileIdStr = dictionary[Constants.Monetization.profileId] as? String,
let profileId = Int(profileIdStr),
let isCompanionVariant = dictionary[Constants.Monetization.isCompanionVariant] as? Bool,
let publisherId = dictionary[Constants.Monetization.publisherId] as? String,
let adUnitId = dictionary[Constants.Monetization.pubMaticUnitId] as? String,
let adTypeStr = dictionary[Constants.Monetization.adType] as? String,
let adType = AdType(rawValue: adTypeStr) else {
return nil
}
self.adUnitId = adUnitId
self.profileId = profileId
self.publisherId = publisherId
self.appStoreUrl = appStoreUrl
self.isCompanionVariant = isCompanionVariant
self.adType = adType
self.appDomain = dictionary[Constants.Monetization.appDomain] as? String ?? ""
self.testMode = dictionary[Constants.Monetization.testMode] as? Bool ?? false
self.debugLogs = dictionary[Constants.Monetization.debugLogs] as? Bool ?? false
self.bidSummaryLogs = dictionary[Constants.Monetization.bidSummaryLogs] as? Bool ?? false
self.timeInView = dictionary[Constants.Monetization.timeInView] as? Int
}
}
}
// MARK:- PubMatic ADs
extension APEUnitView {
private func makePubMaticViewDelegate(adType: PubMaticViewProvider.Params.AdType) -> PubMaticViewDelegate {
PubMaticViewDelegate(adType: adType,
containerViewController: containerViewController,
receiveAdSuccessCompletion: { [weak self] adType in
guard let self = self else { return }
if case .inUnit = adType {
self.pubMaticViewCloseButton.isHidden = false
}
self.messageDispatcher.sendNativeAdEvent(to: self.unitWebView,
Constants.Monetization.playerMonImpression)
},
receiveAdErrorCompletion: { [weak self] adType, error in
guard let self = self else { return }
self.messageDispatcher.sendNativeAdEvent(to: self.unitWebView,
Constants.Monetization.playerMonLoadingImpressionFailed)
print(error?.localizedDescription ?? "")
if case .inUnit = adType {
self.pubMaticViewCloseButton.isHidden = false
}
self.hidePubMaticView()
})
}
func setupPubMaticView(params: PubMaticViewProvider.Params) {
defer {
showPubMaticViews()
}
var pubMaticView = self.pubMaticViewProviders[params.adType]?.view
guard pubMaticView == nil else {
pubMaticView?.forceRefresh()
return
}
let appInfo = POBApplicationInfo()
appInfo.domain = params.appDomain
appInfo.storeURL = URL(string: params.appStoreUrl)!
OpenWrapSDK.setApplicationInfo(appInfo)
self.messageDispatcher.sendNativeAdEvent(to: self.unitWebView, Constants.Monetization.playerMonLoadingPass)
let adSizes = [POBAdSizeMake(params.adType.size.width, params.adType.size.height)].compactMap({ $0 })
pubMaticView = POBBannerView(publisherId: params.publisherId,
profileId: .init(value: params.profileId),
adUnitId: params.adUnitId,
adSizes: adSizes)
pubMaticView?.request.testModeEnabled = params.testMode
pubMaticView?.request.debug = params.debugLogs
pubMaticView?.request.bidSummaryEnabled = params.bidSummaryLogs
let delegate = pubMaticViewProviders[params.adType]?.delegate ?? makePubMaticViewDelegate(adType: params.adType)
pubMaticView?.delegate = delegate
pubMaticView?.loadAd()
self.pubMaticViewProviders[params.adType] = PubMaticViewProvider(view: pubMaticView, delegate: delegate)
guard let timeInView = params.timeInView, pubMaticViewTimer == nil else { return }
pubMaticViewTimer = Timer.scheduledTimer(withTimeInterval: Double(timeInView), repeats: false) { _ in
self.hidePubMaticView()
}
}
func removePubMaticView(of adType: PubMaticViewProvider.Params.AdType) {
pubMaticViewProviders[adType]?.view?.removeFromSuperview()
pubMaticViewProviders[adType] = nil
guard pubMaticViewTimer != nil else { return }
pubMaticViewCloseButton.removeFromSuperview()
pubMaticViewTimer?.invalidate()
pubMaticViewTimer = nil
}
@objc func hidePubMaticView() {
removePubMaticView(of: .inUnit)
}
func showPubMaticViews() {
self.pubMaticViewProviders
.forEach({ type, provider in
guard let containerView = unitWebView, let pubMaticView = provider.view else { return }
containerView.addSubview(pubMaticView)
containerView.bringSubviewToFront(pubMaticView)
if case .inUnit = type {
if let bottomView = self.pubMaticViewProviders[.bottom]?.view {
containerView.bringSubviewToFront(bottomView)
}
self.pubMaticViewCloseButton.isHidden = true
containerView.addSubview(self.pubMaticViewCloseButton)
containerView.bringSubviewToFront(self.pubMaticViewCloseButton)
}
pubMaticView.translatesAutoresizingMaskIntoConstraints = false
pubMaticView.removeConstraints(pubMaticView.constraints)
NSLayoutConstraint.activate(pubMaticViewLayoutConstraints(pubMaticView, containerView: containerView, type: type))
})
}
private func pubMaticViewLayoutConstraints(_ pubMaticView: POBBannerView, containerView: UIView, type: PubMaticViewProvider.Params.AdType) -> [NSLayoutConstraint] {
var constraints = [pubMaticView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor, constant: 0),
pubMaticView.widthAnchor.constraint(equalToConstant: type.size.width),
pubMaticView.heightAnchor.constraint(equalToConstant: type.size.height)]
switch type {
case .bottom:
constraints += [pubMaticView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 0)]
case .inUnit:
constraints += [pubMaticView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor, constant: 0),
pubMaticViewCloseButton.centerXAnchor.constraint(equalTo: containerView.centerXAnchor,
constant: type.size.width/2 + 7),
pubMaticViewCloseButton.centerYAnchor.constraint(equalTo: containerView.centerYAnchor,
constant: -type.size.height/2 - 7)
]
}
return constraints
}
}
| 3acaabac327565435b11ff7b9a6e5a2d | 46.910526 | 168 | 0.583983 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/BlockchainComponentLibrary/Sources/Examples/RootView.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import SwiftUI
@MainActor
public struct RootView: View {
@State var colorScheme: ColorScheme
@State var layoutDirection: LayoutDirection
private static let data: NavigationLinkProviderList = [
"1 - Base": [
NavigationLinkProvider(view: ColorsExamplesView(), title: "🌈 Colors"),
NavigationLinkProvider(view: TypographyExamplesView(), title: "🔠 Typography"),
NavigationLinkProvider(view: SpacingExamplesView(), title: "🔳 Spacing Rules"),
NavigationLinkProvider(view: IconsExamplesView(), title: "🖼 Icons")
],
"2 - Primitives": [
NavigationLinkProvider(view: TabBarExamplesView(), title: "🎼 TabBar"),
NavigationLinkProvider(view: ButtonExamplesView(), title: "🕹 Buttons"),
NavigationLinkProvider(view: PrimaryDividerExamples(), title: "🗂 Dividers"),
NavigationLinkProvider(view: SVGExamples(), title: "✍️ SVG"),
NavigationLinkProvider(view: GIFExamples(), title: "🌠 GIF"),
NavigationLinkProvider(view: ProgressViewExamples(), title: "🌀 ProgressView"),
NavigationLinkProvider(view: PrimarySwitchExamples(), title: "🔌 PrimarySwitch"),
NavigationLinkProvider(view: TagViewExamples(), title: "🏷 Tag"),
NavigationLinkProvider(view: CheckboxExamples(), title: "✅ Checkbox"),
NavigationLinkProvider(view: RichTextExamples(), title: "🤑 Rich Text"),
NavigationLinkProvider(view: SegmentedControlExamples(), title: "🚥 SegmentedControl"),
NavigationLinkProvider(view: InputExamples(), title: "⌨️ Input"),
NavigationLinkProvider(view: PrimaryPickerExamples(), title: "⛏ Picker"),
NavigationLinkProvider(view: AlertExamples(), title: "⚠️ Alert"),
NavigationLinkProvider(view: AlertToastExamples(), title: "🚨 AlertToast"),
NavigationLinkProvider(view: PageControlExamples(), title: "📑 PageControl"),
NavigationLinkProvider(view: PrimarySliderExamples(), title: "🎚 Slider"),
NavigationLinkProvider(view: RadioExamples(), title: "🔘 Radio"),
NavigationLinkProvider(view: ChartBalanceExamples(), title: "⚖️ Chart Balance"),
NavigationLinkProvider(view: LineGraphExamples(), title: "📈 Line Graph"),
NavigationLinkProvider(view: FilterExamples(), title: "🗳 Filter")
],
"3 - Compositions": [
NavigationLinkProvider(view: PrimaryNavigationExamples(), title: "✈️ Navigation"),
NavigationLinkProvider(view: CalloutCardExamples(), title: "💬 CalloutCard"),
NavigationLinkProvider(view: SectionHeadersExamples(), title: "🪖 SectionHeaders"),
NavigationLinkProvider(view: RowExamplesView(), title: "🚣♀️ Rows"),
NavigationLinkProvider(view: BottomSheetExamples(), title: "📄 BottomSheet"),
NavigationLinkProvider(view: SearchBarExamples(), title: "🔎 SearchBar"),
NavigationLinkProvider(view: AlertCardExamples(), title: "🌋 AlertCard"),
NavigationLinkProvider(view: PromoCardExamples(), title: "🛎 PromoCard"),
NavigationLinkProvider(view: AnnouncementCardExamples(), title: "🎙 AnnouncementCard"),
NavigationLinkProvider(view: LargeAnnouncementCardExamples(), title: "📡 LargeAnnouncementCard")
]
]
public init(colorScheme: ColorScheme = .light, layoutDirection: LayoutDirection = .leftToRight) {
_colorScheme = State(initialValue: colorScheme)
_layoutDirection = State(initialValue: layoutDirection)
}
public static var content: some View {
NavigationLinkProviderView(data: data)
}
public var body: some View {
PrimaryNavigationView {
NavigationLinkProviderView(data: RootView.data)
.primaryNavigation(title: "📚 Component Library") {
Button(colorScheme == .light ? "🌗" : "🌓") {
colorScheme = colorScheme == .light ? .dark : .light
}
Button(layoutDirection == .leftToRight ? "➡️" : "⬅️") {
layoutDirection = layoutDirection == .leftToRight ? .rightToLeft : .leftToRight
}
}
}
.colorScheme(colorScheme)
.environment(\.layoutDirection, layoutDirection)
}
}
struct RootView_Previews: PreviewProvider {
static var previews: some View {
ForEach(
ColorScheme.allCases,
id: \.self
) { colorScheme in
RootView(colorScheme: colorScheme)
}
}
}
| 3dbfe1a99321fb60ef44c26a233c1402 | 50.173913 | 107 | 0.6387 | false | false | false | false |
XcqRomance/BookRoom-complete- | refs/heads/master | BookRoom/BookCell.swift | mit | 1 | //
// BookCell.swift
// BookRoom
//
// Created by romance on 2017/5/4.
// Copyright © 2017年 romance. All rights reserved.
//
import UIKit
import SDWebImage
final class BookCell: UICollectionViewCell {
@IBOutlet weak var bookCover: UIImageView!
@IBOutlet weak var coverName: UILabel!
@IBOutlet weak var isReadImageView: UIImageView!
@IBOutlet weak var bookWidth: NSLayoutConstraint!
@IBOutlet weak var bookHeight: NSLayoutConstraint!
@IBOutlet weak var gradientView: UIView!
var book: Book? {
didSet {
bookCover.sd_setImage(with: URL(string: (book?.pic.aliyunThumb())!), placeholderImage: UIImage(named: "bookDefault"), options: .retryFailed) { (_, _, _, _) in
self.coverName.isHidden = true
}
coverName.text = book?.bookName
// title.text = book?.bookName
if (book?.isRead)! { // 是否阅读过该书籍
isReadImageView.isHidden = false
} else {
isReadImageView.isHidden = true
}
if book?.orientation == 1 { // 竖版书籍
bookWidth.constant = 67
bookHeight.constant = 88
} else {
bookWidth.constant = 96
bookHeight.constant = 67
}
layoutIfNeeded()
}
}
override func awakeFromNib() {
super.awakeFromNib()
bookCover.layer.cornerRadius = 10
let gradLayer = CAGradientLayer()
gradLayer.colors = [UIColor.hexColor(0x045b94).cgColor, UIColor.hexColor(0x176da6).cgColor]
gradLayer.startPoint = CGPoint(x: 0, y: 0)
gradLayer.endPoint = CGPoint(x: 0, y: 1)
gradLayer.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width / 3, height: 25)
gradientView.layer.addSublayer(gradLayer)
}
}
| e78f8be8eb781fec57b0403b4d557af0 | 27.474576 | 164 | 0.65119 | false | false | false | false |
derekcdaley/anipalooza | refs/heads/master | AnimalController.swift | gpl-3.0 | 1 | //
// AnimalController.swift
// Guess It
//
// Created by Derek Daley on 3/15/17.
// Copyright © 2017 DSkwared. All rights reserved.
//
import SpriteKit
class AnimalController: SKSpriteNode {
private var animateAnimalAction = SKAction();
private var animals = [SKNode]();
func shuffle( animalssArray: [SKNode]) -> [SKNode] {
var animalssArray = animalssArray;
for i in ((0 + 1)...animalssArray.count - 1).reversed() {
let j = Int(arc4random_uniform(UInt32(i-1)));
swap(&animalssArray[i], &animalssArray[j]);
}
return animalssArray;
}
func arrangeAnimalsInScene(scene: SKScene){
let animal = Animal();
animals = animal.createAnimals();
animals = shuffle(animalssArray: animals);
if scene.name == "Level1Scene" {
for i in 0...3 {
var x = 0;
var y = 0;
switch(i){
case 0:
x = -150;
y = -50;
case 1:
x = 150;
y = -50;
case 2:
x = 0;
y = -210;
default:
x = 0;
y = 110;
}
animals[i].position = CGPoint(x: x, y: y);
scene.addChild(animals[i]);
}
}else if scene.name == "Level2Scene" {
for i in 0...3 {
var x = 0;
var y = 0;
switch(i){
case 0:
x = -150;
y = -130;
case 1:
x = 150;
y = -130;
case 2:
x = -150;
y = -330;
default:
x = 150;
y = -330;
}
animals[i].position = CGPoint(x: x, y: y);
scene.addChild(animals[i]);
}
}
}
}
| 6a40615bdf763b54a539bff282dbdd1e | 25.82716 | 65 | 0.364013 | false | false | false | false |
ikemai/ColorAdjuster | refs/heads/master | Example/ColorAdjuster/AdjustmentRbgView.swift | mit | 1 | //
// AdjustmentRbgView.swift
// ColorAdjuster
//
// Created by Mai Ikeda on 2015/10/10.
// Copyright © 2015年 CocoaPods. All rights reserved.
//
import UIKit
class AdjustmentRbgView: UIView {
@IBOutlet weak var baseView: UIView!
@IBOutlet weak var targetView: UIView!
@IBOutlet weak var rgbLabel: UILabel!
@IBOutlet weak var rSlider: UISlider!
@IBOutlet weak var gSlider: UISlider!
@IBOutlet weak var bSlider: UISlider!
private var rValue: CGFloat { return CGFloat(rSlider.value) * 2 }
private var gValue: CGFloat { return CGFloat(gSlider.value) * 2 }
private var bValue: CGFloat { return CGFloat(bSlider.value) * 2 }
override func awakeFromNib() {
super.awakeFromNib()
rSlider.value = 0.5
gSlider.value = 0.5
bSlider.value = 0.5
updateBaseColor(UIColor(hex: 0xB7EAE7))
}
func updateBaseColor(color: UIColor) {
baseView.backgroundColor = color
updateRGBColor()
}
func updateRGBColor() {
guard let color = baseView.backgroundColor else { return }
let adjustmentColor = color.colorWithRGBComponent(red: rValue, green: gValue, blue: bValue)
targetView.backgroundColor = adjustmentColor
if let rbg = adjustmentColor?.colorRGB() {
let r = Double(Int(rbg.red * 100)) / 100
let g = Double(Int(rbg.green * 100)) / 100
let b = Double(Int(rbg.blue * 100)) / 100
rgbLabel.text = "R = \(r) : G = \(g) : B = \(b)"
}
}
}
| 10ab8cec81cbb12c949346f9dbddb2b8 | 28.867925 | 99 | 0.607707 | false | false | false | false |
jpush/jchat-swift | refs/heads/master | JChat/Src/UserModule/ViewController/JCUpdatePassworkViewController.swift | mit | 1 | //
// JCUpdatePassworkViewController.swift
// JChat
//
// Created by JIGUANG on 2017/3/16.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
import JMessage
class JCUpdatePassworkViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
_init()
}
private lazy var oldPasswordTextField: UITextField = {
var textField = UITextField()
textField.placeholder = "请输入原始密码"
textField.isSecureTextEntry = true
textField.font = UIFont.systemFont(ofSize: 16)
return textField
}()
private lazy var newPasswordTextField: UITextField = {
var textField = UITextField()
textField.placeholder = "请设置登录密码"
textField.isSecureTextEntry = true
textField.font = UIFont.systemFont(ofSize: 16)
return textField
}()
private lazy var checkPasswordTextField: UITextField = {
var textField = UITextField()
textField.placeholder = "请再次输入"
textField.isSecureTextEntry = true
textField.font = UIFont.systemFont(ofSize: 16)
return textField
}()
private lazy var updateButton: UIButton = {
var updateButton = UIButton()
updateButton.setTitle("确认", for: .normal)
updateButton.layer.cornerRadius = 3.0
updateButton.layer.masksToBounds = true
updateButton.addTarget(self, action: #selector(_updatePasswork), for: .touchUpInside)
return updateButton
}()
private lazy var oldPasswordLabel: UILabel = {
var label = UILabel()
label.text = "原始密码"
label.font = UIFont.systemFont(ofSize: 16)
return label
}()
private lazy var newPasswordLabel: UILabel = {
var label = UILabel()
label.text = "新密码"
label.font = UIFont.systemFont(ofSize: 16)
return label
}()
private lazy var checkPasswordLabel: UILabel = {
var label = UILabel()
label.text = "确认密码"
label.font = UIFont.systemFont(ofSize: 16)
return label
}()
private lazy var line1: UILabel = {
var label = UILabel()
label.backgroundColor = UIColor(netHex: 0xd9d9d9)
return label
}()
private lazy var line2: UILabel = {
var label = UILabel()
label.backgroundColor = UIColor(netHex: 0xd9d9d9)
return label
}()
private lazy var bgView: UIView = UIView()
//MARK: - private func
private func _init() {
self.title = "修改密码"
view.backgroundColor = UIColor(netHex: 0xe8edf3)
updateButton.setBackgroundImage(UIImage.createImage(color: UIColor(netHex: 0x2dd0cf), size: CGSize(width: view.width - 30, height: 40)), for: .normal)
bgView.backgroundColor = .white
view.addSubview(bgView)
bgView.addSubview(oldPasswordLabel)
bgView.addSubview(newPasswordLabel)
bgView.addSubview(checkPasswordLabel)
bgView.addSubview(oldPasswordTextField)
bgView.addSubview(newPasswordTextField)
bgView.addSubview(checkPasswordTextField)
bgView.addSubview(line1)
bgView.addSubview(line2)
view.addSubview(updateButton)
view.addConstraint(_JCLayoutConstraintMake(bgView, .left, .equal, view, .left))
view.addConstraint(_JCLayoutConstraintMake(bgView, .right, .equal, view, .right))
if isIPhoneX {
view.addConstraint(_JCLayoutConstraintMake(bgView, .top, .equal, view, .top, 88))
} else {
view.addConstraint(_JCLayoutConstraintMake(bgView, .top, .equal, view, .top, 64))
}
view.addConstraint(_JCLayoutConstraintMake(bgView, .height, .equal, nil, .notAnAttribute, 135))
bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordLabel, .left, .equal, bgView, .left, 15))
bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordLabel, .top, .equal, bgView, .top, 11.5))
bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordLabel, .width, .equal, nil, .notAnAttribute, 75))
bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordLabel, .height, .equal, nil, .notAnAttribute, 22.5))
bgView.addConstraint(_JCLayoutConstraintMake(line1, .left, .equal, oldPasswordLabel, .left))
bgView.addConstraint(_JCLayoutConstraintMake(line1, .top, .equal, bgView, .top, 44.5))
bgView.addConstraint(_JCLayoutConstraintMake(line1, .right, .equal, bgView, .right, -15))
bgView.addConstraint(_JCLayoutConstraintMake(line1, .height, .equal, nil, .notAnAttribute, 0.5))
bgView.addConstraint(_JCLayoutConstraintMake(line2, .left, .equal, line1, .left))
bgView.addConstraint(_JCLayoutConstraintMake(line2, .top, .equal, line1, .top, 45))
bgView.addConstraint(_JCLayoutConstraintMake(line2, .right, .equal, line1, .right))
bgView.addConstraint(_JCLayoutConstraintMake(line2, .height, .equal, nil, .notAnAttribute, 0.5))
bgView.addConstraint(_JCLayoutConstraintMake(newPasswordLabel, .left, .equal, oldPasswordLabel, .left))
bgView.addConstraint(_JCLayoutConstraintMake(newPasswordLabel, .top, .equal, line1, .bottom, 11.5))
bgView.addConstraint(_JCLayoutConstraintMake(newPasswordLabel, .width, .equal, nil, .notAnAttribute, 75))
bgView.addConstraint(_JCLayoutConstraintMake(newPasswordLabel, .height, .equal, nil, .notAnAttribute, 22.5))
bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordLabel, .left, .equal, oldPasswordLabel, .left))
bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordLabel, .top, .equal, line2, .bottom, 11.5))
bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordLabel, .width, .equal, nil, .notAnAttribute, 75))
bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordLabel, .height, .equal, nil, .notAnAttribute, 22.5))
bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordTextField, .left, .equal, oldPasswordLabel, .right, 20))
bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordTextField, .top, .equal, bgView, .top, 11.5))
bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordTextField, .right, .equal, bgView, .right, -15))
bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordTextField, .height, .equal, nil, .notAnAttribute, 22.5))
bgView.addConstraint(_JCLayoutConstraintMake(newPasswordTextField, .left, .equal, oldPasswordTextField, .left))
bgView.addConstraint(_JCLayoutConstraintMake(newPasswordTextField, .top, .equal, line1, .bottom, 11.5))
bgView.addConstraint(_JCLayoutConstraintMake(newPasswordTextField, .right, .equal, oldPasswordTextField, .right))
bgView.addConstraint(_JCLayoutConstraintMake(newPasswordTextField, .height, .equal, oldPasswordTextField, .height))
bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordTextField, .left, .equal, oldPasswordTextField, .left))
bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordTextField, .top, .equal, line2, .bottom, 11.5))
bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordTextField, .right, .equal, oldPasswordTextField, .right))
bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordTextField, .height, .equal, oldPasswordTextField, .height))
view.addConstraint(_JCLayoutConstraintMake(updateButton, .left, .equal, view, .left, 15))
view.addConstraint(_JCLayoutConstraintMake(updateButton, .right, .equal, view, .right, -15))
view.addConstraint(_JCLayoutConstraintMake(updateButton, .top, .equal, bgView, .bottom, 15))
view.addConstraint(_JCLayoutConstraintMake(updateButton, .height, .equal, nil, .notAnAttribute, 40))
}
//MARK: - click event
@objc func _updatePasswork() {
view.endEditing(true)
let oldPassword = oldPasswordTextField.text!
let newPassword = newPasswordTextField.text!
let checkPassword = checkPasswordTextField.text!
if oldPassword.isEmpty || newPassword.isEmpty || checkPassword.isEmpty {
MBProgressHUD_JChat.show(text: "所有信息不能为空", view: view)
return
}
if newPassword != checkPassword {
MBProgressHUD_JChat.show(text: "新密码和确认密码不一致", view: view)
return
}
MBProgressHUD_JChat.showMessage(message: "修改中", toView: view)
JMSGUser.updateMyPassword(withNewPassword: newPassword, oldPassword: oldPassword) { (result, error) in
MBProgressHUD_JChat.hide(forView: self.view, animated: true)
if error == nil {
self.navigationController?.popViewController(animated: true)
} else {
MBProgressHUD_JChat.show(text: "更新失败", view: self.view)
}
}
}
}
| d181a23a723b43775cbc45521733d932 | 48.227778 | 158 | 0.678592 | false | false | false | false |
sovereignshare/fly-smuthe | refs/heads/master | Fly Smuthe/Fly Smuthe/DataCollectionManager.swift | gpl-3.0 | 1 | //
// DataCollectionManager.swift
// Fly Smuthe
//
// Created by Adam M Rivera on 8/27/15.
// Copyright (c) 2015 Adam M Rivera. All rights reserved.
//
import Foundation
import UIKit
import CoreLocation
import CoreMotion
class DataCollectionManager : NSObject, CLLocationManagerDelegate {
let locationManager = CLLocationManager();
let motionManager = CMMotionManager();
var latestTurbulenceDataState: TurbulenceStatisticModel!;
var delegate: DataCollectionManagerDelegate!;
class var sharedInstance: DataCollectionManager {
struct Singleton {
static let instance = DataCollectionManager()
}
return Singleton.instance;
}
func startCollection(delegate: DataCollectionManagerDelegate){
self.delegate = delegate;
locationManager.delegate = self;
motionManager.startAccelerometerUpdates();
evaluateAccess();
}
func evaluateAccess() {
switch CLLocationManager.authorizationStatus() {
case CLAuthorizationStatus.AuthorizedAlways:
locationManager.startUpdatingLocation();
case CLAuthorizationStatus.NotDetermined:
locationManager.requestAlwaysAuthorization()
case CLAuthorizationStatus.AuthorizedWhenInUse, CLAuthorizationStatus.Restricted, CLAuthorizationStatus.Denied:
let alertController = UIAlertController(
title: "Background Location Access Disabled",
message: "In order to provide anonymous, automatic turbulence 'PIREPs', please open this app's settings and set location access to 'Always'.",
preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
let openAction = UIAlertAction(title: "Open Settings", style: .Default) { (action) in
if let url = NSURL(string:UIApplicationOpenSettingsURLString) {
UIApplication.sharedApplication().openURL(url)
}
}
alertController.addAction(openAction)
self.delegate.requestAccess(alertController);
if(CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse){
locationManager.startUpdatingLocation();
}
}
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if (status == CLAuthorizationStatus.AuthorizedAlways || status == CLAuthorizationStatus.AuthorizedWhenInUse){
locationManager.startUpdatingLocation();
} else {
evaluateAccess();
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var xAccel: Double!;
var yAccel: Double!;
var zAccel: Double!;
var altitude: Int!;
var latitude: Double!;
var longitude: Double!;
var weakLocation: CLLocation!;
var weakAccelData: CMAccelerometerData!;
var hasLocationData = false;
var hasAccelData = false;
if let location = locations.last {
altitude = Int(location.altitude);
latitude = location.coordinate.latitude;
longitude = location.coordinate.longitude;
weakLocation = location;
hasLocationData = true;
}
if let currentAccelValues = motionManager.accelerometerData{
weakAccelData = currentAccelValues;
xAccel = currentAccelValues.acceleration.x;
yAccel = currentAccelValues.acceleration.y;
zAccel = currentAccelValues.acceleration.z;
hasAccelData = true;
}
if let strongDelegate = self.delegate{
strongDelegate.receivedUpdate(weakLocation, accelerometerData: weakAccelData);
}
let newTurbulenceDataState = TurbulenceStatisticModel(xAccel: xAccel, yAccel: yAccel, zAccel: zAccel, altitude: altitude, latitude: latitude, longitude: longitude);
if((latestTurbulenceDataState == nil && hasLocationData && hasAccelData) || (latestTurbulenceDataState != nil && latestTurbulenceDataState.hasNotableChange(newTurbulenceDataState))){
latestTurbulenceDataState = newTurbulenceDataState;
TurbulenceStatisticRepository.sharedInstance.save(latestTurbulenceDataState);
}
SyncManager.sharedInstance.startBackgroundSync();
}
}
protocol DataCollectionManagerDelegate {
func requestAccess(controller: UIAlertController);
func receivedUpdate(lastLocation: CLLocation!, accelerometerData: CMAccelerometerData!);
} | a3561733db932258a47c27f6431f6183 | 37.338583 | 190 | 0.655711 | false | false | false | false |
rolson/arcgis-runtime-samples-ios | refs/heads/master | arcgis-ios-sdk-samples/Display information/Picture marker symbols/PictureMarkerSymbolsViewController.swift | apache-2.0 | 1 | // Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class PictureMarkerSymbolsViewController: UIViewController {
@IBOutlet var mapView:AGSMapView!
private var graphicsOverlay = AGSGraphicsOverlay()
override func viewDidLoad() {
super.viewDidLoad()
//add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["PictureMarkerSymbolsViewController"]
//initialize map with basemap
let map = AGSMap(basemap: AGSBasemap.topographicBasemap())
//initial envelope
let center = AGSPoint(x: -225166.5, y: 6551249, spatialReference: AGSSpatialReference.webMercator())
map.initialViewpoint = AGSViewpoint(center: center, scale: 1e5)
//assign the map to the map view
self.mapView.map = map
//add the graphics overlay to the map view
self.mapView.graphicsOverlays.addObject(self.graphicsOverlay)
//add picture marker symbol using a remote image
self.addPictureMarkerSymbolFromURL()
//add picture marker symbol using image in assets
self.addPictureMarkerSymbolFromImage()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func addPictureMarkerSymbolFromURL() {
let url = NSURL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Recreation/FeatureServer/0/images/e82f744ebb069bb35b234b3fea46deae")!
let campsiteSymbol = AGSPictureMarkerSymbol(URL: url)
//optionally set the size (if not set, the size in pixels of the image will be used)
campsiteSymbol.width = 24
campsiteSymbol.height = 24
//location for camp site
let campsitePoint = AGSPoint(x: -223560, y: 6552021, spatialReference: AGSSpatialReference.webMercator())
//graphic for camp site
let graphic = AGSGraphic(geometry: campsitePoint, symbol: campsiteSymbol, attributes: nil)
//add the graphic to the overlay
self.graphicsOverlay.graphics.addObject(graphic)
}
private func addPictureMarkerSymbolFromImage() {
//image name
let imageName = "PinBlueStar"
//create pin symbol using the image
let pinSymbol = AGSPictureMarkerSymbol(image: UIImage(named: imageName)!)
//change offsets, so the symbol aligns properly to the point
pinSymbol.offsetY = pinSymbol.image!.size.height/2
//location for pin
let pinPoint = AGSPoint(x: -226773, y: 6550477, spatialReference: AGSSpatialReference.webMercator())
//graphic for pin
let graphic = AGSGraphic(geometry: pinPoint, symbol: pinSymbol, attributes: nil)
//add the graphic to the overlay
self.graphicsOverlay.graphics.addObject(graphic)
}
}
| 4f6fc577d4ff00138f5e892072a3c38f | 37.37234 | 162 | 0.677849 | false | false | false | false |
cafbuddy/cafbuddy-iOS | refs/heads/master | Caf Buddy/MealListingHeader.swift | mit | 1 | //
// collectionViewHeader.swift
// Caf Buddy
//
// Created by Jacob Forster on 3/1/15.
// Copyright (c) 2015 St. Olaf Acm. All rights reserved.
//
import Foundation
class MealListingHeader : UICollectionReusableView {
var headerTitle = UILabel()
var rightLine = UIView()
var leftLine = UIView()
func setTitle(title: String, sectionIndex : Int) {
headerTitle.text = title
headerTitle.font = UIFont.boldSystemFontOfSize(22)
headerTitle.textColor = colorWithHexString(COLOR_DARKER_BLUE)
headerTitle.textAlignment = NSTextAlignment.Center
var offset : Int = 0
if (sectionIndex == 0) {
offset = 5
}
headerTitle.frame = CGRectMake(0, CGFloat(offset), self.frame.size.width, 40)
offset = 0
if (sectionIndex == 1) {
offset = 5
}
rightLine.frame = CGRectMake(10, 25 - CGFloat(offset), (self.frame.size.width / 2) - 70, 2)
rightLine.backgroundColor = colorWithHexString(COLOR_DARKER_BLUE)
leftLine.frame = CGRectMake(self.frame.size.width - (self.frame.size.width / 2) + 60, 25 - CGFloat(offset), (self.frame.size.width / 2) - 70, 2)
leftLine.backgroundColor = colorWithHexString(COLOR_DARKER_BLUE)
self.addSubview(rightLine)
self.addSubview(leftLine)
self.addSubview(headerTitle)
}
} | 7097dacde2cfd6bf15dbc06cbc0d0971 | 28.9375 | 152 | 0.616992 | false | false | false | false |
Eonil/EditorLegacy | refs/heads/master | Modules/SQLite3/Sources/Value.swift | mit | 2 | //
// Value.swift
// EonilSQLite3
//
// Created by Hoon H. on 9/15/14.
//
//
import Foundation
public typealias Binary = Blob
/// We don't use Swift `nil` to represent SQLite3 `NULL` because it
/// makes program more complex.
///
/// https://www.sqlite.org/datatype3.html
public enum Value : Equatable, Hashable, Printable, NilLiteralConvertible, IntegerLiteralConvertible, FloatLiteralConvertible, StringLiteralConvertible {
case Null
case Integer(Int64)
case Float(Double)
case Text(String)
case Blob(Binary)
}
public extension Value {
}
public extension Value {
public var hashValue:Int {
get {
switch self {
case Null: return 0
case let Integer(s): return s.hashValue
case let Float(s): return s.hashValue
case let Text(s): return s.hashValue
case let Blob(s): return s.hashValue
}
}
}
}
public extension Value {
public init(nilLiteral: ()) {
self = Value.Null
}
public init(integerLiteral value: Int64) {
self = Integer(value)
}
// public init(integerLiteral value: Int) {
// precondition(IntMax(value) <= IntMax(Int64.max))
// self = Integer(Int64(value))
// }
public init(floatLiteral value: Double) {
self = Float(value)
}
public init(stringLiteral value: String) {
self = Text(value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self = Text(value)
}
public init(unicodeScalarLiteral value: String) {
self = Text(value)
}
}
public extension Value {
public var description:String {
get {
switch self {
case let Null(s): return "NULL"
case let Integer(s): return "INTEGER(\(s))"
case let Float(s): return "FLOAT(\(s))"
case let Text(s): return "TEXT(\(s))"
case let Blob(s): return "BLOB(~~~~)"
// default: fatalError("Unsupported value case.")
}
}
}
}
public func == (l:Value, r:Value) -> Bool {
switch (l,r) {
case let (Value.Null, Value.Null): return true
case let (Value.Integer(a), Value.Integer(b)): return a == b
case let (Value.Float(a), Value.Float(b)): return a == b
case let (Value.Text(a), Value.Text(b)): return a == b
case let (Value.Blob(a), Value.Blob(b)): return a == b
default: return false
}
}
//public func == (l:Value, r:()?) -> Bool {
// return l == Value.Null && r == nil
//}
//
//public func == (l:Value, r:Int) -> Bool {
// return l == Int64(r)
//}
//public func == (l:Value, r:Int64) -> Bool {
// if let v2 = l.integer { return v2 == r }
// return false
//}
//public func == (l:Value, r:Double) -> Bool {
// if let v2 = l.float { return v2 == r }
// return false
//}
//public func == (l:Value, r:String) -> Bool {
// if let v2 = l.text { return v2 == r }
// return false
//}
//public func == (l:Value, r:Binary) -> Bool {
// if let v2 = l.blob { return v2 == r }
// return false
//}
public extension Value {
// init(){
// self = Value.Null
// }
public init(_ v:Int64?) {
self = v == nil ? Null : Integer(v!)
}
public init(_ v:Double?) {
self = v == nil ? Null : Float(v!)
}
public init(_ v:String?) {
self = v == nil ? Null : Text(v!)
}
public init(_ v:Binary?) {
self = v == nil ? Null : Blob(v!)
}
public var null:Bool {
get {
return self == Value.Null
// switch self {
// case let Null: return true
// default: return false
// }
}
}
public var integer:Int64? {
get {
switch self {
case let Integer(s): return s
default: return nil
}
}
}
public var float:Double? {
get {
switch self {
case let Float(s): return s
default: return nil
}
}
}
public var text:String? {
get {
switch self {
case let Text(s): return s
default: return nil
}
}
}
public var blob:Binary? {
get {
switch self {
case let Blob(s): return s
default: return nil
}
}
}
}
//
//public typealias Value = AnyObject ///< Don't use `Any`. Currently, it causes many subtle unknown problems.
//
//
//
//
////
////public typealias FieldList = [Value] ///< The value can be one of these types; `Int`, `Double`, `String`, `Blob`. A field with NULL will not be stored.
////public typealias Record = [String:Value]
////
////struct RowList
////{
//// let columns:[String]
//// let items:[FieldList]
////}
//
//
//
//
//
////typealias Integer = Int64
//
///// 64-bit signed integer class type.
///// Defined to provide conversion to AnyObject.
///// (Swift included in Xcode 6.0.1 does not support this conversion...)
//public class Integer : Printable//, SignedIntegerType, SignedNumberType
//{
// public init(_ number:Int64)
// {
// self.number = number
// }
//
//
// public var description:String
// {
// get
// {
// return number.description
// }
// }
//
//// public var hashValue:Int
//// {
//// get
//// {
//// return number.hashValue
//// }
//// }
////
//// public var arrayBoundValue:Int64.ArrayBound
//// {
//// get
//// {
//// return number.arrayBoundValue
//// }
//// }
//// public func toIntMax() -> IntMax
//// {
//// return number.toIntMax()
//// }
////
//// public class func from(x: IntMax) -> Integer
//// {
//// return Integer(Int64.from(x))
//// }
//
// let number:Int64
//}
//
//extension Int64
//{
// init(_ integer:Integer)
// {
// self.init(integer.number)
// }
//}
/// Represents BLOB.
public class Blob: Hashable
{
init(address:UnsafePointer<()>, length:Int) {
precondition(address != nil)
precondition(length >= 0)
value = NSData(bytes: address, length: length)
}
public var hashValue:Int {
get {
return value.hashValue
}
}
var length:Int
{
get
{
return value.length
}
}
var address:UnsafePointer<()>
{
get
{
return value.bytes
}
}
private init(value:NSData)
{
self.value = value
}
private let value:NSData
}
public func == (l:Blob, r:Blob) -> Bool {
return l.value == r.value
}
| 612f8502a6988461f753625f2b2a25f3 | 16.011696 | 158 | 0.601066 | false | false | false | false |
hooman/swift | refs/heads/main | test/Generics/unify_nested_types_2.swift | apache-2.0 | 2 | // RUN: %target-typecheck-verify-swift -requirement-machine=verify -dump-requirement-machine 2>&1 | %FileCheck %s
protocol P1 {
associatedtype T : P1
}
protocol P2 {
associatedtype T where T == X<U>
associatedtype U
}
extension Int : P1 {
public typealias T = Int
}
struct X<A> : P1 {
typealias T = X<A>
}
struct G<T : P1 & P2> {}
// Since G.T.T == G.T.T.T == G.T.T.T.T = ... = X<T.U>, we tie off the
// recursion by introducing a same-type requirement G.T.T => G.T.
// CHECK-LABEL: Adding generic signature <τ_0_0 where τ_0_0 : P1, τ_0_0 : P2> {
// CHECK-LABEL: Rewrite system: {
// CHECK: - τ_0_0.[P1&P2:T].[concrete: X<τ_0_0> with <τ_0_0.[P2:U]>] => τ_0_0.[P1&P2:T]
// CHECK: - [P1&P2:T].T => [P1&P2:T].[P1:T]
// CHECK: - τ_0_0.[P1&P2:T].[P1:T] => τ_0_0.[P1&P2:T]
// CHECK: }
// CHECK: }
| 129aa8c95f0b25a571aaf19142607a53 | 25.064516 | 113 | 0.589109 | false | false | false | false |
cwwise/CWWeChat | refs/heads/master | CWWeChat/MainClass/Contacts/ContactSetting/CWContactSettingController.swift | mit | 2 | //
// CWContactSettingController.swift
// CWWeChat
//
// Created by wei chen on 2017/9/5.
// Copyright © 2017年 cwwise. All rights reserved.
//
import UIKit
class CWContactSettingController: CWBaseTableViewController {
lazy var tableViewManager: CWTableViewManager = {
let tableViewManager = CWTableViewManager(tableView: self.tableView)
tableViewManager.delegate = self
tableViewManager.dataSource = self
return tableViewManager
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "资料设置"
setupData()
}
func setupData() {
let item1 = CWTableViewItem(title: "设置备注及标签")
tableViewManager.addSection(itemsOf: [item1])
let item2 = CWTableViewItem(title: "把她推荐给朋友")
tableViewManager.addSection(itemsOf: [item2])
let item3 = CWBoolItem(title: "设置为星标用户", value: true)
tableViewManager.addSection(itemsOf: [item3])
let item4 = CWBoolItem(title: "不让她看我的朋友圈", value: true)
let item5 = CWBoolItem(title: "不看她的朋友圈 ", value: true)
tableViewManager.addSection(itemsOf: [item4, item5])
let item6 = CWBoolItem(title: "加入黑名单", value: true)
let item7 = CWTableViewItem(title: "投诉")
tableViewManager.addSection(itemsOf: [item6, item7])
let frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 80)
let footerView = UIView(frame: frame)
self.tableView.tableFooterView = footerView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension CWContactSettingController: CWTableViewManagerDelegate, CWTableViewManagerDataSource {
}
| 9dd5616bb1e65820959daa70a2128187 | 27.873016 | 96 | 0.647609 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/Utility/Blogging Reminders/BloggingRemindersScheduleFormatter.swift | gpl-2.0 | 2 | import Foundation
struct BloggingRemindersScheduleFormatter {
private let calendar: Calendar
init(calendar: Calendar? = nil) {
self.calendar = calendar ?? {
var calendar = Calendar.current
calendar.locale = Locale.autoupdatingCurrent
return calendar
}()
}
/// Attributed short description string of the current schedule for the specified blog.
///
func shortScheduleDescription(for schedule: BloggingRemindersScheduler.Schedule, time: String? = nil) -> NSAttributedString {
switch schedule {
case .none:
return Self.stringToAttributedString(TextContent.shortNoRemindersDescription)
case .weekdays(let days):
guard days.count > 0 else {
return shortScheduleDescription(for: .none, time: time)
}
return Self.shortScheduleDescription(for: days.count, time: time)
}
}
/// Attributed long description string of the current schedule for the specified blog.
///
func longScheduleDescription(for schedule: BloggingRemindersScheduler.Schedule, time: String) -> NSAttributedString {
switch schedule {
case .none:
return NSAttributedString(string: TextContent.longNoRemindersDescription)
case .weekdays(let days):
guard days.count > 0 else {
return longScheduleDescription(for: .none, time: time)
}
// We want the days sorted by their localized index because under some locale configurations
// Sunday is the first day of the week, whereas in some other localizations Monday comes first.
let sortedDays = days.sorted { (first, second) -> Bool in
let firstIndex = self.calendar.localizedWeekdayIndex(unlocalizedWeekdayIndex: first.rawValue)
let secondIndex = self.calendar.localizedWeekdayIndex(unlocalizedWeekdayIndex: second.rawValue)
return firstIndex < secondIndex
}
let markedUpDays: [String] = sortedDays.compactMap({ day in
return "<strong>\(self.calendar.weekdaySymbols[day.rawValue])</strong>"
})
let text: String
if days.count == 1 {
text = String(format: TextContent.oneReminderLongDescriptionWithTime, markedUpDays.first ?? "", "<strong>\(time)</strong>")
} else {
let formatter = ListFormatter()
let formattedDays = formatter.string(from: markedUpDays) ?? ""
text = String(format: TextContent.manyRemindersLongDescriptionWithTime, "<strong>\(days.count)</strong>", formattedDays, "<strong>\(time)</strong>")
}
return Self.stringToAttributedString(text)
}
}
}
// MARK: - Private type methods and properties
private extension BloggingRemindersScheduleFormatter {
static func shortScheduleDescription(for days: Int, time: String?) -> NSAttributedString {
guard let time = time else {
return shortScheduleDescription(for: days)
}
return shortScheduleDescriptionWithTime(for: days, time: time)
}
static func shortScheduleDescriptionWithTime(for days: Int, time: String) -> NSAttributedString {
let text: String = {
switch days {
case 1:
return String(format: TextContent.oneReminderShortDescriptionWithTime, time)
case 2:
return String(format: TextContent.twoRemindersShortDescriptionWithTime, time)
case 7:
return "<strong>" + String(format: TextContent.everydayRemindersShortDescriptionWithTime, time) + "</strong>"
default:
return String(format: TextContent.manyRemindersShortDescriptionWithTime, days, time)
}
}()
return Self.stringToAttributedString(text)
}
static func shortScheduleDescription(for days: Int) -> NSAttributedString {
let text: String = {
switch days {
case 1:
return TextContent.oneReminderShortDescription
case 2:
return TextContent.twoRemindersShortDescription
case 7:
return "<strong>" + TextContent.everydayRemindersShortDescription + "</strong>"
default:
return String(format: TextContent.manyRemindersShortDescription, days)
}
}()
return Self.stringToAttributedString(text)
}
static func stringToAttributedString(_ string: String) -> NSAttributedString {
let htmlData = NSString(string: string).data(using: String.Encoding.unicode.rawValue) ?? Data()
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [.documentType: NSAttributedString.DocumentType.html]
let attributedString = (try? NSMutableAttributedString(data: htmlData,
options: options,
documentAttributes: nil)) ?? NSMutableAttributedString()
// This loop applies the default font to the whole text, while keeping any symbolic attributes the previous font may
// have had (such as bold style).
attributedString.enumerateAttribute(.font, in: NSRange(location: 0, length: attributedString.length)) { (value, range, stop) in
guard let oldFont = value as? UIFont,
let newDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body)
.withSymbolicTraits(oldFont.fontDescriptor.symbolicTraits) else {
return
}
let newFont = UIFont(descriptor: newDescriptor, size: 0)
attributedString.addAttributes([.font: newFont], range: range)
}
return attributedString
}
enum TextContent {
static let shortNoRemindersDescription = NSLocalizedString("None set", comment: "Title shown on table row where no blogging reminders have been set up yet")
static let longNoRemindersDescription = NSLocalizedString("You have no reminders set.", comment: "Text shown to the user when setting up blogging reminders, if they complete the flow and have chosen not to add any reminders.")
// Ideally we should use stringsdict to translate plurals, but GlotPress currently doesn't support this.
static let oneReminderLongDescriptionWithTime = NSLocalizedString("You'll get a reminder to blog <strong>once</strong> a week on %@ at %@.",
comment: "Blogging Reminders description confirming a user's choices. The placeholder will be replaced at runtime with a day of the week. The HTML markup is used to bold the word 'once'.")
static let manyRemindersLongDescriptionWithTime = NSLocalizedString("You'll get reminders to blog %@ times a week on %@.",
comment: "Blogging Reminders description confirming a user's choices. The first placeholder will be populated with a count of the number of times a week they'll be reminded. The second will be a formatted list of days. For example: 'You'll get reminders to blog 2 times a week on Monday and Tuesday.")
static let oneReminderShortDescriptionWithTime = NSLocalizedString("<strong>Once</strong> a week at %@",
comment: "Short title telling the user they will receive a blogging reminder once per week. The word for 'once' should be surrounded by <strong> HTML tags.")
static let twoRemindersShortDescriptionWithTime = NSLocalizedString("<strong>Twice</strong> a week at %@",
comment: "Short title telling the user they will receive a blogging reminder two times a week. The word for 'twice' should be surrounded by <strong> HTML tags.")
static let manyRemindersShortDescriptionWithTime = NSLocalizedString("<strong>%d</strong> times a week at %@",
comment: "A short description of how many times a week the user will receive a blogging reminder. The '%d' placeholder will be populated with a count of the number of times a week they'll be reminded, and should be surrounded by <strong> HTML tags.")
static let everydayRemindersShortDescriptionWithTime = NSLocalizedString("Every day at %@",
comment: "Short title telling the user they will receive a blogging reminder every day of the week.")
static let oneReminderShortDescription = NSLocalizedString("<strong>Once</strong> a week",
comment: "Short title telling the user they will receive a blogging reminder once per week. The word for 'once' should be surrounded by <strong> HTML tags.")
static let twoRemindersShortDescription = NSLocalizedString("<strong>Twice</strong> a week",
comment: "Short title telling the user they will receive a blogging reminder two times a week. The word for 'twice' should be surrounded by <strong> HTML tags.")
static let manyRemindersShortDescription = NSLocalizedString("<strong>%d</strong> times a week",
comment: "A short description of how many times a week the user will receive a blogging reminder. The '%d' placeholder will be populated with a count of the number of times a week they'll be reminded, and should be surrounded by <strong> HTML tags.")
static let everydayRemindersShortDescription = NSLocalizedString("Every day",
comment: "Short title telling the user they will receive a blogging reminder every day of the week.")
}
}
| c1c8a8b89b528591d180dd831a926dfe | 56.095506 | 363 | 0.62885 | false | false | false | false |
FandyLiu/FDDemoCollection | refs/heads/master | Swift/WidgetDemo/WidgetDemo/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// WidgetDemo
//
// Created by QianTuFD on 2017/6/23.
// Copyright © 2017年 fandy. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return true
}
func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
return true
}
// iOS (9.0 and later), tvOS (9.0 and later)
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return true
}
func abc(url: URL) {
let prefix = "fandyTest://action="
let urlStr = url.absoluteString
if urlStr.hasPrefix(prefix) {
// let action = urlStr.replacingOccurrences(of: prefix, with: "")
let index = prefix.characters.index(prefix.startIndex, offsetBy: prefix.characters.count)
let action = urlStr.substring(from: index)
if action == "richScan" {
}
}
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 1e054051c65a57149c15ee1f0162525a | 40.653333 | 285 | 0.696863 | false | false | false | false |
esttorhe/SlackTeamExplorer | refs/heads/master | SlackTeamExplorer/SlackTeamExplorer/ViewControllers/ViewController.swift | mit | 1 | //
// ViewController.swift
// SlackTeamExplorer
//
// Created by Esteban Torres on 29/6/15.
// Copyright (c) 2015 Esteban Torres. All rights reserved.
//
// Native Frameworks
import UIKit
// Shared
import SlackTeamCoreDataProxy
// Misc.
import HexColors
// Network
import SDWebImage
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var loadingActivityIndicator: UIActivityIndicatorView!
// ViewModels
let membersViewModel = MembersViewModel()
override func viewDidLoad() {
super.viewDidLoad()
// Configure transparent nav bar
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.translucent = true
self.navigationController?.navigationBar.tintColor = UIColor.blackColor()
// Configure the view models
membersViewModel.beginLoadingSignal.deliverOnMainThread().subscribeNext { [unowned self] _ in
self.loadingActivityIndicator.startAnimating()
}
membersViewModel.endLoadingSignal.deliverOnMainThread().subscribeNext { [unowned self] _ in
self.loadingActivityIndicator.stopAnimating()
}
membersViewModel.updateContentSignal.deliverOnMainThread().subscribeNext({ [unowned self] members in
self.collectionView.reloadData()
}, error: { [unowned self] error in
let alertController = UIAlertController(title: "Unable to fetch members", message: error?.description, preferredStyle: .Alert)
let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
alertController.dismissViewControllerAnimated(true, completion: nil)
})
alertController.addAction(ok)
self.presentViewController(alertController, animated: true, completion: nil)
println("• Unable to load members: \(error)")
})
// Trigger first load
membersViewModel.active = true
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.collectionView.collectionViewLayout.invalidateLayout()
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let detailVC = segue.destinationViewController as? DetailViewController,
cell = sender as? MemberCell,
indexPath = collectionView.indexPathForCell(cell) {
let member = membersViewModel.memberAtIndexPath(indexPath)
detailVC.memberViewModel = MemberViewModel(memberID: member.objectID)
}
}
// MARK: - Collection View
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.membersViewModel.numberOfItemsInSection(section)
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MemberCell", forIndexPath: indexPath) as! MemberCell
cell.avatarImageView.image = nil
cell.avatarImageView.backgroundColor = UIColor.slackPurpleColor()
cell.usernameLabel.text = nil
cell.titleLabel.text = nil
let member = membersViewModel.memberAtIndexPath(indexPath)
cell.usernameLabel.text = "@\(member.name)"
if let profile = member.profile {
if let imageURL = profile.image192 {
cell.avatarImageView.sd_setImageWithURL(NSURL(string: imageURL), placeholderImage: nil) { (image, error, cacheType, url) in
if let img = image {
cell.avatarImageView.image = img
} else if let fburl = profile.fallBackImageURL {
cell.avatarImageView.sd_setImageWithURL(fburl)
}
}
}
if let title = profile.title {
cell.titleLabel.text = title
}
}
if let strColor = member.color, color = UIColor(hexString: strColor) {
cell.avatarImageView.layer.borderWidth = 4.0
cell.avatarImageView.layer.borderColor = color.CGColor
cell.layer.cornerRadius = 10.0
}
return cell
}
override func didRotateFromInterfaceOrientation(_: UIInterfaceOrientation) {
collectionView.collectionViewLayout.invalidateLayout()
}
// MARK: - Collection View Flow Layout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
collectionView.layoutIfNeeded()
return CGSizeMake(CGRectGetWidth(collectionView.bounds) - 30.0, 81.0)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 10.0
}
} | 1e9e92345e4ebccc251a74b5aa56ecbf | 39.492857 | 178 | 0.663197 | false | false | false | false |
wang-chuanhui/CHSDK | refs/heads/master | Source/Transformation/OptionalTransformational.swift | mit | 1 | //
// OptionalTransformational.swift
// CHSDK
//
// Created by 王传辉 on 2017/8/4.
// Copyright © 2017年 王传辉. All rights reserved.
//
import Foundation
extension Optional: OptionalTransformational {
public static func _transform(from value: Any) -> Optional {
if let wrapped = value as? Wrapped {
return Optional.some(wrapped)
}else if let wrapped = (Wrapped.self as? Transformational.Type)?.___transform(from: value) as? Wrapped {
return Optional.some(wrapped)
}
return Optional.none
}
func getWrappedValue() -> Any? {
return self.map( { (wrapped) -> Any in
return wrapped as Any
})
}
public func _toJSONValue() -> Any? {
if let value = getWrappedValue() {
if let transform = value as? Transformational {
return transform
}
}
return nil
}
}
extension ImplicitlyUnwrappedOptional: OptionalTransformational {
public static func _transform(from value: Any) -> ImplicitlyUnwrappedOptional {
if let wrapped = value as? Wrapped {
return ImplicitlyUnwrappedOptional.some(wrapped)
}else if let wrapped = (Wrapped.self as? Transformational.Type)?.___transform(from: value) as? Wrapped {
return ImplicitlyUnwrappedOptional.some(wrapped)
}
return ImplicitlyUnwrappedOptional.none
}
func getWrappedValue() -> Any? {
return self == nil ? nil : self!
}
public func _toJSONValue() -> Any? {
if let value = getWrappedValue() {
if let transform = value as? Transformational {
return transform
}
}
return nil
}
}
| 05957091cabc8cf0fab65b0549861219 | 25.969231 | 112 | 0.592128 | false | false | false | false |
sindanar/PDStrategy | refs/heads/master | Example/PDStrategy/PDStrategy/Date3StaticCellsCell.swift | mit | 1 | //
// Date3StaticCellsCell.swift
// PDStrategy
//
// Created by Pavel Deminov on 05/11/2017.
// Copyright © 2017 Pavel Deminov. All rights reserved.
//
import UIKit
class Date3StaticCellsCell: PDTableViewCell {
var titleLabel: PDTitleLabel!
var valueLabel: PDValueLabel!
var dateLabel: PDDateLabel!
override func setup() {
selectionStyle = .none
let titleValueDate = TitleValueDateBuilder.addTitleValueDate3(to: contentView)
titleLabel = titleValueDate.titleLabel
valueLabel = titleValueDate.valueLabel
dateLabel = titleValueDate.dateLabel
}
override func updateUI() {
titleLabel.text = itemInfo?.pdTitle
valueLabel.text = itemInfo?.pdValue as? String
dateLabel.date = itemInfo?.pdDate
}
}
| 4cc2b2e2a5f8eab6292d3cb097b016be | 24.806452 | 86 | 0.68625 | false | false | false | false |
Kiandr/CrackingCodingInterview | refs/heads/master | Swift/Ch 8. Recursion and Dynamic Programming/Ch 8. Recursion and Dynamic Programming.playground/Pages/8.1 Triple Step.xcplaygroundpage/Contents.swift | mit | 1 | import Foundation
/*:
8.1 A child is running up a staircase with n steps and can hop either 1, 2, or 3 steps at a time.
Count the number of ways the child can run up the stairs.
*/
func countWays(steps: Int) -> Int {
let results = Array<Int?>(repeating: nil, count: steps + 1)
let result = countWays(steps: steps, results: results)
return result
}
private func countWays(steps: Int, results: [Int?]) -> Int {
guard steps > 0 else { return steps < 0 ? 0 : 1 }
if let result = results[steps] {
return result
}
var results = results
let n1 = countWays(steps: steps - 1, results: results)
let n2 = countWays(steps: steps - 2, results: results)
let n3 = countWays(steps: steps - 3, results: results)
results[steps] = n1 + n2 + n3
return results[steps]!
}
assert(countWays(steps: 5) == 13)
| 2935aa78e3f858edf98e3498b33c5e24 | 27.5 | 99 | 0.642105 | false | false | false | false |
mthistle/HockeyTweetSwift | refs/heads/master | HockeyTweetSwift/Models/Teams.swift | mit | 1 | //
// Teams.swift
// HockeyTweetSwift
//
// Created by Mark Thistle on 2014-07-13.
// Copyright (c) 2014 Test. All rights reserved.
//
import Foundation
class Teams: NSObject {
var teamTLA = [
"NJD",
"NYI",
"NYR",
"PHI",
"PIT",
"BOS",
"BUF",
"MTL",
"OTT",
"TOR",
"ATL",
"CAR",
"FLA",
"TBL",
"WSH",
"CHI",
"CBJ",
"DET",
"NSH",
"STL",
"CGY",
"COL",
"EDM",
"MIN",
"VAN",
"ANA",
"DAL",
"LAK",
"PHX",
"SJS"]
var teamNames = [
"New Jersey Devils",
"New York Islanders",
"New York Rangers",
"Philadelphia Flyers",
"Pittsburgh Penguins",
"Boston Bruins",
"Buffalo Sabres",
"Montreal Canadiens",
"Ottawa Senators",
"Toronto Maple Leafs",
"Atlanta Thrashers",
"Carolina Hurricanes",
"Florida Panthers",
"Tampa Bay Lightning",
"Washington Capitals",
"Chicago Blackhawks",
"Columbus Blue Jackets",
"Detroit Red Wings",
"Nashville Predators",
"St Louis Blues",
"Calgary Flames",
"Colorado Avalanche",
"Edmonton Oilers",
"Minnesota Wild",
"Vancouver Canucks",
"Anaheim Ducks",
"Dallas Stars",
"Los Angeles Kings",
"Phoenix Coyotes",
"San Jose Sharks"]
// Initialize an empty dictionary so we have a starting point from which to
// add values in the init call.
var rosters = [String: Array<String>]()
override init() {
teamNames = sorted(teamNames, { s1, s2 in return s1 < s2 })
teamTLA = sorted(teamTLA, { s1, s2 in return s1 < s2 })
// TODO: Ok, need to convert from NS to Swift here
// var rostersLoaded = true
// if let path: String = NSBundle.mainBundle().pathForResource("players", ofType: "plist") {
// let teams = NSDictionary(contentsOfFile: path)
// //rosters = rostersFromTeams(teams["players"] as NSDictionary)
// } else {
// rostersLoaded = false
// }
// if !rostersLoaded {
for team in teamTLA {
rosters[team] = ["--"]
}
//}
super.init()
}
func playersOnTeam(team: String) -> Array<String>! {
//if let players: NSDictionary = rosters["players"] as? NSDictionary {
// let ns_team: NSString = NSString(string: team)
//for teamPlayers in players.objectForKey(ns_team) {
//}
//return nil
//}
return nil
}
func rostersFromTeams(teams: NSDictionary) -> Dictionary<String, Array<String>>! {
var tmprosters: Dictionary<String, Array<String>>
for team in teamTLA {
}
return nil
}
} | 5bc8b8da1970ec0387c1f386ca8c1b0b | 24.771186 | 107 | 0.488816 | false | false | false | false |
WebAPIKit/WebAPIKit | refs/heads/master | Sources/WebAPIKit/Stub/StubRequestMatcher.swift | mit | 1 | /**
* 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
public struct StubRequestMatcher {
public let request: URLRequest
public let provider: WebAPIProvider?
}
extension StubHTTPClient {
@discardableResult
public func stub(match: @escaping (StubRequestMatcher) -> Bool) -> StubResponder {
return stub(responder: StubResponder {
match(StubRequestMatcher(request: $0, provider: self.provider))
})
}
}
// MARK: Method
extension StubRequestMatcher {
public func methodEqualTo(_ method: HTTPMethod) -> Bool {
return request.httpMethod == method.rawValue
}
}
// MARK: Path
extension StubRequestMatcher {
public var requestPath: String? {
guard let path = request.url?.path else {
return nil
}
guard let basePath = provider?.baseURL.path, !basePath.isEmpty, basePath != "/" else {
return path
}
return path.substring(from: basePath.endIndex)
}
public func pathEqualTo(_ path: String) -> Bool {
return requestPath == path
}
public func pathHasPrefix(_ path: String) -> Bool {
return requestPath?.hasPrefix(path) == true
}
public func pathHasSuffix(_ path: String) -> Bool {
return requestPath?.hasSuffix(path) == true
}
public func pathContains(_ path: String) -> Bool {
return requestPath?.contains(path) == true
}
}
extension StubHTTPClient {
public enum PathMatchMode {
case equalTo, prefix, suffix, contains
}
@discardableResult
public func stub(path: String, mode: PathMatchMode = .equalTo, method: HTTPMethod? = nil) -> StubResponder {
return stub {
if let method = method, !$0.methodEqualTo(method) {
return false
}
switch mode {
case .equalTo: return $0.pathEqualTo(path)
case .prefix: return $0.pathHasPrefix(path)
case .suffix: return $0.pathHasSuffix(path)
case .contains: return $0.pathContains(path)
}
}
}
}
| ee8af091730ca34c4e5014813553d66c | 29.613208 | 112 | 0.663174 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/SILGen/multi_file.swift | apache-2.0 | 3 | // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -primary-file %s %S/Inputs/multi_file_helper.swift | %FileCheck %s
func markUsed<T>(_ t: T) {}
// CHECK-LABEL: sil hidden @_T010multi_file12rdar16016713{{[_0-9a-zA-Z]*}}F
func rdar16016713(_ r: Range) {
// CHECK: [[LIMIT:%[0-9]+]] = function_ref @_T010multi_file5RangeV5limitSivg : $@convention(method) (Range) -> Int
// CHECK: {{%[0-9]+}} = apply [[LIMIT]]({{%[0-9]+}}) : $@convention(method) (Range) -> Int
markUsed(r.limit)
}
// CHECK-LABEL: sil hidden @_T010multi_file26lazyPropertiesAreNotStored{{[_0-9a-zA-Z]*}}F
func lazyPropertiesAreNotStored(_ container: LazyContainer) {
var container = container
// CHECK: {{%[0-9]+}} = function_ref @_T010multi_file13LazyContainerV7lazyVarSivg : $@convention(method) (@inout LazyContainer) -> Int
markUsed(container.lazyVar)
}
// CHECK-LABEL: sil hidden @_T010multi_file29lazyRefPropertiesAreNotStored{{[_0-9a-zA-Z]*}}F
func lazyRefPropertiesAreNotStored(_ container: LazyContainerClass) {
// CHECK: bb0([[ARG:%.*]] : @owned $LazyContainerClass):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: {{%[0-9]+}} = class_method [[BORROWED_ARG]] : $LazyContainerClass, #LazyContainerClass.lazyVar!getter.1 : (LazyContainerClass) -> () -> Int, $@convention(method) (@guaranteed LazyContainerClass) -> Int
markUsed(container.lazyVar)
}
// CHECK-LABEL: sil hidden @_T010multi_file25finalVarsAreDevirtualizedyAA18FinalPropertyClassCF
func finalVarsAreDevirtualized(_ obj: FinalPropertyClass) {
// CHECK: bb0([[ARG:%.*]] : @owned $FinalPropertyClass):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: ref_element_addr [[BORROWED_ARG]] : $FinalPropertyClass, #FinalPropertyClass.foo
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
markUsed(obj.foo)
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: class_method [[BORROWED_ARG]] : $FinalPropertyClass, #FinalPropertyClass.bar!getter.1
markUsed(obj.bar)
}
// rdar://18448869
// CHECK-LABEL: sil hidden @_T010multi_file34finalVarsDontNeedMaterializeForSetyAA27ObservingPropertyFinalClassCF
func finalVarsDontNeedMaterializeForSet(_ obj: ObservingPropertyFinalClass) {
obj.foo += 1
// CHECK: function_ref @_T010multi_file27ObservingPropertyFinalClassC3fooSivg
// CHECK: function_ref @_T010multi_file27ObservingPropertyFinalClassC3fooSivs
}
// rdar://18503960
// Ensure that we type-check the materializeForSet accessor from the protocol.
class HasComputedProperty: ProtocolWithProperty {
var foo: Int {
get { return 1 }
set {}
}
}
// CHECK-LABEL: sil hidden [transparent] @_T010multi_file19HasComputedPropertyC3fooSivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasComputedProperty) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK-LABEL: sil private [transparent] [thunk] @_T010multi_file19HasComputedPropertyCAA012ProtocolWithE0A2aDP3fooSivmTW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasComputedProperty) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
| 272f20481a17d6d34f67f289869377f0 | 55.125 | 292 | 0.728285 | false | false | false | false |
LawrenceHan/iOS-project-playground | refs/heads/master | ShotsApp_example/ShotsApp/font/Spring/SpringAnimation.swift | mit | 1 | //
// SpringAnimation.swift
// ShotsDemo
//
// Created by Meng To on 2014-07-04.
// Copyright (c) 2014 Meng To. All rights reserved.
//
import UIKit
var duration = 0.7
var delay = 0.0
var damping = 0.7
var velocity = 0.7
func spring(duration: NSTimeInterval, animations: (() -> Void)!) {
UIView.animateWithDuration(
duration,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.7,
options: [],
animations: {
animations()
},
completion: nil
)
}
func springWithDelay(duration: NSTimeInterval, delay: NSTimeInterval, animations: (() -> Void)!) {
UIView.animateWithDuration(
duration,
delay: delay,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.7,
options: [],
animations: {
animations()
},
completion: nil
)
}
func slideUp(duration: NSTimeInterval, animations: (() -> Void)!) {
UIView.animateWithDuration(
duration,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.8,
options: [],
animations: {
animations()
},
completion: nil
)
}
func springWithCompletion(duration: NSTimeInterval, animations: (() -> Void)!, completion: ((Bool) -> Void)!) {
UIView.animateWithDuration(
duration,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.7,
options: [],
animations: {
animations()
}, completion: { finished in
completion(finished)
}
)
}
func springScaleFrom (view: UIView, x: CGFloat, y: CGFloat, scaleX: CGFloat, scaleY: CGFloat) {
let translation = CGAffineTransformMakeTranslation(x, y)
let scale = CGAffineTransformMakeScale(scaleX, scaleY)
view.transform = CGAffineTransformConcat(translation, scale)
UIView.animateWithDuration(
duration,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.7,
options: [],
animations: {
let translation = CGAffineTransformMakeTranslation(0, 0)
let scale = CGAffineTransformMakeScale(1, 1)
view.transform = CGAffineTransformConcat(translation, scale)
}, completion:nil)
}
func springScaleTo (view: UIView, x: CGFloat, y: CGFloat, scaleX: CGFloat, scaleY: CGFloat) {
let translation = CGAffineTransformMakeTranslation(0, 0)
let scale = CGAffineTransformMakeScale(1, 1)
view.transform = CGAffineTransformConcat(translation, scale)
UIView.animateWithDuration(
duration,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.7,
options: [],
animations: {
let translation = CGAffineTransformMakeTranslation(x, y)
let scale = CGAffineTransformMakeScale(scaleX, scaleY)
view.transform = CGAffineTransformConcat(translation, scale)
},
completion: nil
)
}
func popoverTopRight(view: UIView) {
view.hidden = false
let translate = CGAffineTransformMakeTranslation(200, -200)
let scale = CGAffineTransformMakeScale(0.3, 0.3)
view.alpha = 0
view.transform = CGAffineTransformConcat(translate, scale)
UIView.animateWithDuration(
duration,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.7,
options: [],
animations: {
let translate = CGAffineTransformMakeTranslation(0, 0)
let scale = CGAffineTransformMakeScale(1, 1)
view.transform = CGAffineTransformConcat(translate, scale)
view.alpha = 1
},
completion: nil
)
} | c6e04a9c4ea93a4173c58bb8520f333b | 26.786765 | 111 | 0.612493 | false | false | false | false |
vonholst/deeplearning_example_kog | refs/heads/master | HotdogOrNohotdog/HotdogOrNohotdog/ViewController.swift | mit | 1 | //
// ViewController.swift
// HotdogOrNohotdog
//
// Created by Michael Jasinski on 2017-10-25.
// Copyright © 2017 HiQ. All rights reserved.
//
import UIKit
import CoreML
import Vision
import AVFoundation
class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
// Connect UI to code
@IBOutlet weak var classificationText: UILabel!
@IBOutlet weak var cameraView: UIView!
private var requests = [VNRequest]()
private lazy var cameraLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)
private lazy var captureSession: AVCaptureSession = {
let session = AVCaptureSession()
session.sessionPreset = AVCaptureSession.Preset.photo
guard
let backCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back),
let input = try? AVCaptureDeviceInput(device: backCamera)
else { return session }
session.addInput(input)
return session
}()
var player: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
self.cameraView?.layer.addSublayer(self.cameraLayer)
let videoOutput = AVCaptureVideoDataOutput()
videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "MyQueue"))
self.captureSession.addOutput(videoOutput)
self.captureSession.startRunning()
setupVision()
self.classificationText.text = ""
cameraView.bringSubview(toFront: self.classificationText)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.cameraLayer.frame = self.cameraView?.bounds ?? .zero
}
func setupVision() {
guard let visionModel = try? VNCoreMLModel(for: hotdog_classifier().model)
else { fatalError("Can't load VisionML model") }
let classificationRequest = VNCoreMLRequest(model: visionModel, completionHandler: handleClassifications)
classificationRequest.imageCropAndScaleOption = VNImageCropAndScaleOption.centerCrop
self.requests = [classificationRequest]
}
func handleClassifications(request: VNRequest, error: Error?) {
guard let observations = request.results as? [VNClassificationObservation]
else { print("no results: \(error!)"); return }
guard let best = observations.first
else { fatalError("can't get best result") }
print("\(best.identifier), \(best.confidence)")
// latch to hotdog / no-hotdog
if best.confidence > 0.9 && best.identifier == "hotdog" {
DispatchQueue.main.async {
if self.classificationText.text == "" {
self.playSound()
}
self.classificationText.text = "🌭"
}
} else if best.confidence > 0.6 && best.identifier == "non_hotdog" {
DispatchQueue.main.async {
self.classificationText.text = ""
}
}
}
func playSound() {
guard let url = Bundle.main.url(forResource: "hotdog", withExtension: "wav") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
return
}
var requestOptions:[VNImageOption : Any] = [:]
if let cameraIntrinsicData = CMGetAttachment(sampleBuffer, kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix, nil) {
requestOptions = [.cameraIntrinsics:cameraIntrinsicData]
}
let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: CGImagePropertyOrientation(rawValue: 1)!, options: requestOptions)
do {
try imageRequestHandler.perform(self.requests)
} catch {
print(error)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| bcab1642484bd3a4a00d6dd71b399ae8 | 37.720339 | 163 | 0.650252 | false | false | false | false |
PodRepo/firefox-ios | refs/heads/master | Client/Frontend/Settings/SearchSettingsTableViewController.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class SearchSettingsTableViewController: UITableViewController {
private let SectionDefault = 0
private let ItemDefaultEngine = 0
private let ItemDefaultSuggestions = 1
private let NumberOfItemsInSectionDefault = 2
private let SectionOrder = 1
private let NumberOfSections = 2
private let IconSize = CGSize(width: OpenSearchEngine.PreferredIconSize, height: OpenSearchEngine.PreferredIconSize)
private let SectionHeaderIdentifier = "SectionHeaderIdentifier"
var model: SearchEngines!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("Search", comment: "Navigation title for search settings.")
// To allow re-ordering the list of search engines at all times.
tableView.editing = true
// So that we push the default search engine controller on selection.
tableView.allowsSelectionDuringEditing = true
tableView.registerClass(SettingsTableSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
// Insert Done button if being presented outside of the Settings Nav stack
if !(self.navigationController is SettingsNavigationController) {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "SELDismiss")
}
tableView.tableFooterView = UIView()
tableView.separatorColor = UIConstants.TableViewSeparatorColor
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell!
var engine: OpenSearchEngine!
if indexPath.section == SectionDefault {
switch indexPath.item {
case ItemDefaultEngine:
engine = model.defaultEngine
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.editingAccessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.accessibilityLabel = NSLocalizedString("Default Search Engine", comment: "Accessibility label for default search engine setting.")
cell.accessibilityValue = engine.shortName
cell.textLabel?.text = engine.shortName
cell.imageView?.image = engine.image?.createScaled(IconSize)
case ItemDefaultSuggestions:
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.textLabel?.text = NSLocalizedString("Show search suggestions", comment: "Label for show search suggestions setting.")
let toggle = UISwitch()
toggle.onTintColor = UIConstants.ControlTintColor
toggle.addTarget(self, action: "SELdidToggleSearchSuggestions:", forControlEvents: UIControlEvents.ValueChanged)
toggle.on = model.shouldShowSearchSuggestions
cell.editingAccessoryView = toggle
cell.selectionStyle = .None
default:
// Should not happen.
break
}
} else {
// The default engine is not a quick search engine.
let index = indexPath.item + 1
engine = model.orderedEngines[index]
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.showsReorderControl = true
let toggle = UISwitch()
toggle.onTintColor = UIConstants.ControlTintColor
// This is an easy way to get from the toggle control to the corresponding index.
toggle.tag = index
toggle.addTarget(self, action: "SELdidToggleEngine:", forControlEvents: UIControlEvents.ValueChanged)
toggle.on = model.isEngineEnabled(engine)
cell.editingAccessoryView = toggle
cell.textLabel?.text = engine.shortName
cell.imageView?.image = engine.image?.createScaled(IconSize)
cell.selectionStyle = .None
}
// So that the seperator line goes all the way to the left edge.
cell.separatorInset = UIEdgeInsetsZero
return cell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return NumberOfSections
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == SectionDefault {
return NumberOfItemsInSectionDefault
} else {
// The first engine -- the default engine -- is not shown in the quick search engine list.
return model.orderedEngines.count - 1
}
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if indexPath.section == SectionDefault && indexPath.item == ItemDefaultEngine {
let searchEnginePicker = SearchEnginePicker()
// Order alphabetically, so that picker is always consistently ordered.
// Every engine is a valid choice for the default engine, even the current default engine.
searchEnginePicker.engines = model.orderedEngines.sort { e, f in e.shortName < f.shortName }
searchEnginePicker.delegate = self
searchEnginePicker.selectedSearchEngineName = model.defaultEngine.shortName
navigationController?.pushViewController(searchEnginePicker, animated: true)
}
return nil
}
// Don't show delete button on the left.
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.None
}
// Don't reserve space for the delete button on the left.
override func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
// Hide a thin vertical line that iOS renders between the accessoryView and the reordering control.
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.editing {
for v in cell.subviews {
if v.frame.width == 1.0 {
v.backgroundColor = UIColor.clearColor()
}
}
}
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderIdentifier) as! SettingsTableSectionHeaderView
var sectionTitle: String
if section == SectionDefault {
sectionTitle = NSLocalizedString("Default Search Engine", comment: "Title for default search engine settings section.")
} else {
sectionTitle = NSLocalizedString("Quick-search Engines", comment: "Title for quick-search engines settings section.")
}
headerView.titleLabel.text = sectionTitle
return headerView
}
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if indexPath.section == SectionDefault {
return false
} else {
return true
}
}
override func tableView(tableView: UITableView, moveRowAtIndexPath indexPath: NSIndexPath, toIndexPath newIndexPath: NSIndexPath) {
// The first engine (default engine) is not shown in the list, so the indices are off-by-1.
let index = indexPath.item + 1
let newIndex = newIndexPath.item + 1
let engine = model.orderedEngines.removeAtIndex(index)
model.orderedEngines.insert(engine, atIndex: newIndex)
tableView.reloadData()
}
// Snap to first or last row of the list of engines.
override func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath, toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath {
// You can't drag or drop on the default engine.
if sourceIndexPath.section == SectionDefault || proposedDestinationIndexPath.section == SectionDefault {
return sourceIndexPath
}
if (sourceIndexPath.section != proposedDestinationIndexPath.section) {
var row = 0
if (sourceIndexPath.section < proposedDestinationIndexPath.section) {
row = tableView.numberOfRowsInSection(sourceIndexPath.section) - 1
}
return NSIndexPath(forRow: row, inSection: sourceIndexPath.section)
}
return proposedDestinationIndexPath
}
func SELdidToggleEngine(toggle: UISwitch) {
let engine = model.orderedEngines[toggle.tag] // The tag is 1-based.
if toggle.on {
model.enableEngine(engine)
} else {
model.disableEngine(engine)
}
}
func SELdidToggleSearchSuggestions(toggle: UISwitch) {
// Setting the value in settings dismisses any opt-in.
model.shouldShowSearchSuggestionsOptIn = false
model.shouldShowSearchSuggestions = toggle.on
}
func SELcancel() {
navigationController?.popViewControllerAnimated(true)
}
func SELDismiss() {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
extension SearchSettingsTableViewController: SearchEnginePickerDelegate {
func searchEnginePicker(searchEnginePicker: SearchEnginePicker, didSelectSearchEngine searchEngine: OpenSearchEngine?) {
if let engine = searchEngine {
model.defaultEngine = engine
self.tableView.reloadData()
}
navigationController?.popViewControllerAnimated(true)
}
}
| 9a91c208005b1c7eb7c2fb8463551889 | 43.558442 | 202 | 0.684737 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | refs/heads/master | enums/XGPokeSpots.swift | gpl-2.0 | 1 | //
// XGPokeSpots.swift
// XG Tool
//
// Created by StarsMmd on 08/06/2015.
// Copyright (c) 2015 StarsMmd. All rights reserved.
//
import Foundation
enum XGPokeSpots : Int, Codable, CaseIterable {
case rock = 0x00
case oasis = 0x01
case cave = 0x02
case all = 0x03
var string : String {
get {
switch self {
case .rock : return "Rock"
case .oasis : return "Oasis"
case .cave : return "Cave"
case .all : return "All"
}
}
}
var numberOfEntries : Int {
let rel = XGFiles.common_rel.data!
return rel.get4BytesAtOffset(self.commonRelEntriesIndex.startOffset)
}
var entries: [XGPokeSpotPokemon] {
return (0 ..< numberOfEntries).map { (index) -> XGPokeSpotPokemon in
return XGPokeSpotPokemon(index: index, pokespot: self)
}
}
func setEntries(entries: Int) {
if let rel = XGFiles.common_rel.data {
rel.replace4BytesAtOffset(self.commonRelEntriesIndex.startOffset, withBytes: entries)
rel.save()
}
}
var commonRelIndex : CommonIndexes {
get {
switch self {
case .rock:
return .PokespotRock
case .oasis:
return .PokespotOasis
case .cave:
return .PokespotCave
case .all:
return .PokespotAll
}
}
}
var commonRelEntriesIndex : CommonIndexes {
get {
switch self {
case .rock:
return .PokespotRockEntries
case .oasis:
return .PokespotOasisEntries
case .cave:
return .PokespotCaveEntries
case .all:
return .PokespotAllEntries
}
}
}
func relocatePokespotData(toOffset offset: Int) {
common.replacePointer(index: self.commonRelIndex.rawValue, newAbsoluteOffset: offset)
}
}
extension XGPokeSpots: XGEnumerable {
var enumerableName: String {
return string
}
var enumerableValue: String? {
return rawValue.string
}
static var className: String {
return "Pokespots"
}
static var allValues: [XGPokeSpots] {
return allCases
}
}
extension XGPokeSpots: XGDocumentable {
var documentableName: String {
return string
}
static var DocumentableKeys: [String] {
return ["Encounters"]
}
func documentableValue(for key: String) -> String {
switch key {
case "Encounters":
var text = ""
for i in 0 ..< self.numberOfEntries {
let encounter = XGPokeSpotPokemon(index: i, pokespot: self)
text += "\n" + encounter.pokemon.name.string.spaceToLength(20)
text += " Lv. " + encounter.minLevel.string + " - " + encounter.maxLevel.string
}
return text
default:
return ""
}
}
}
| adc033b2a9ae51d7e79f03470166fb23 | 16.248276 | 88 | 0.668533 | false | false | false | false |
codingforentrepreneurs/Django-to-iOS | refs/heads/master | Source/ios/srvup/CommentTableViewController.swift | apache-2.0 | 1 | //
// CommentTableViewController.swift
// srvup
//
// Created by Justin Mitchel on 6/23/15.
// Copyright (c) 2015 Coding for Entrepreneurs. All rights reserved.
//
import UIKit
class CommentTableViewController: UITableViewController, UITextViewDelegate {
var lecture: Lecture?
var webView = UIWebView()
var message = UITextView()
let textArea = UITextView()
let textAreaPlaceholder = "Your comment here..."
let aRefeshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
let btn = UINavButton(title: "Back", direction: .Right, parentView: self.view)
btn.addTarget(self, action: "popView:", forControlEvents: UIControlEvents.TouchUpInside)
btn.frame.origin.y = btn.frame.origin.y - 10
self.view.addSubview(btn)
let newCommentBtn = UINavButton(title: "New", direction: .Left, parentView: self.view)
newCommentBtn.addTarget(self, action: "scrollToFooter:", forControlEvents: UIControlEvents.TouchUpInside)
newCommentBtn.frame.origin.y = btn.frame.origin.y
self.view.addSubview(newCommentBtn)
let headerView = UIView()
headerView.frame = CGRectMake(0, 0, self.view.frame.width, 395)
headerView.backgroundColor = .whiteColor()
let headerTextView = UITextView()
headerTextView.frame = CGRectMake(0, btn.frame.origin.y, self.view.frame.width, btn.frame.height)
headerTextView.text = "\(self.lecture!.title)"
headerTextView.textColor = .blackColor()
headerTextView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
headerTextView.textAlignment = .Center
headerTextView.font = UIFont.boldSystemFontOfSize(26)
headerTextView.editable = false
headerTextView.scrollEnabled = false
headerView.addSubview(headerTextView)
self.tableView.tableHeaderView = headerView
self.tableView.tableFooterView = self.addContactForm()
self.aRefeshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.aRefeshControl.addTarget(self, action: "updateItems:", forControlEvents: UIControlEvents.ValueChanged)
self.view.addSubview(self.aRefeshControl)
let webViewWidth = self.view.frame.width - 20
let webViewVideoHeight = 275
let embedCode = lecture!.embedCode
let cssCode = "<style>body{padding:0px;margin:0px;}iframe{width:\(webViewWidth);height:\(webViewVideoHeight);}</style>"
let htmlCode = "<html>\(cssCode)<body>\(embedCode)</body></html>"
self.webView.frame = CGRectMake(10, 75, webViewWidth, 275)
let url = NSURL(string: "http://codingforentrepreneurs.com")
self.webView.loadHTMLString(htmlCode, baseURL: url)
self.webView.scrollView.bounces = false
self.webView.backgroundColor = .whiteColor()
let commentLabel = UILabel()
commentLabel.frame = CGRectMake(self.webView.frame.origin.x, self.webView.frame.origin.y + self.webView.frame.height + 10, self.webView.frame.width, 50)
commentLabel.text = "Comments"
commentLabel.font = UIFont.boldSystemFontOfSize(16)
headerView.addSubview(commentLabel)
headerView.addSubview(self.webView)
}
func updateItems(sender:AnyObject) {
self.lecture?.updateLectureComments({ (success) -> Void in
if success {
println("grabbed comment successfully")
self.aRefeshControl.endRefreshing()
self.tableView.reloadData()
} else {
Notification().notify("Error updated data", delay: 2.0, inSpeed: 0.7, outSpeed: 2.5)
self.aRefeshControl.endRefreshing()
}
})
}
func addContactForm() -> UIView {
let commentView = UITextView()
commentView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
commentView.backgroundColor = .blackColor()
commentView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
commentView.text = "Add New Comment"
commentView.textColor = .blackColor()
commentView.backgroundColor = .redColor()
commentView.textAlignment = .Center
commentView.font = UIFont.boldSystemFontOfSize(24)
let topOffset = CGFloat(25)
let xOffset = CGFloat(10)
let spacingE = CGFloat(10)
// response message
self.message.editable = false
self.message.frame = CGRectMake(xOffset, topOffset, commentView.frame.width - (2 * xOffset), 30)
self.message.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.0)
self.message.textColor = .redColor()
// title
let label = UILabel()
label.text = "Add new Comment"
label.frame = CGRectMake(xOffset, self.message.frame.origin.y + self.message.frame.height + spacingE, self.message.frame.width, 30)
label.textColor = .whiteColor()
// text area field
self.textArea.editable = true
self.textArea.text = self.textAreaPlaceholder
self.textArea.delegate = self
self.textArea.frame = CGRectMake(xOffset, label.frame.origin.y + label.frame.height + spacingE, label.frame.width, 250)
// submit button
let submitBtn = UIButton()
submitBtn.frame = CGRectMake(xOffset, self.textArea.frame.origin.y + self.textArea.frame.height + spacingE, self.textArea.frame.width, 30)
submitBtn.setTitle("Submit", forState: UIControlState.Normal)
submitBtn.addTarget(self, action: "commentFormAction:", forControlEvents: UIControlEvents.TouchUpInside)
submitBtn.tag = 1
// cancel button
let cancelBtn = UIButton()
cancelBtn.frame = CGRectMake(xOffset, submitBtn.frame.origin.y + submitBtn.frame.height + spacingE, submitBtn.frame.width, 30)
cancelBtn.setTitle("Cancel", forState: UIControlState.Normal)
cancelBtn.addTarget(self, action: "commentFormAction:", forControlEvents: UIControlEvents.TouchUpInside)
cancelBtn.tag = 2
commentView.addSubview(label)
commentView.addSubview(self.message)
commentView.addSubview(self.textArea)
commentView.addSubview(submitBtn)
commentView.addSubview(cancelBtn)
return commentView
}
func textViewDidBeginEditing(textView: UITextView) {
self.message.text = ""
if textView.text == self.textAreaPlaceholder {
textView.text = ""
}
}
func commentFormAction(sender: AnyObject) {
let tag = sender.tag
switch tag {
case 1:
if self.textArea.text != "" && self.textArea.text != self.textAreaPlaceholder {
self.textArea.endEditing(true)
self.lecture!.addComment(self.textArea.text, completion: addCommentCompletionHandler)
self.textArea.text = self.textAreaPlaceholder
} else {
self.message.text = "A comment is required."
}
default:
// println("cancelled")
// self.commentView.removeFromSuperview()
self.backToTop(self)
}
}
func addCommentCompletionHandler(success:Bool) -> Void {
if !success {
self.scrollToFooter(self)
Notification().notify("Failed to add", delay: 2.5, inSpeed: 0.7, outSpeed: 1.2)
} else {
Notification().notify("Message Added", delay: 1.5, inSpeed: 0.5, outSpeed: 1.0)
self.backToTop(self)
}
}
func backToTop(sender:AnyObject) {
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
}
func scrollToFooter(sender:AnyObject) {
let lastRowItem = self.lecture!.commentSet.count - 1
let section = 0
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: lastRowItem, inSection: section), atScrollPosition: UITableViewScrollPosition.Top, animated: true)
}
func popView(sender:AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
// self.dismissViewControllerAnimated(true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.lecture!.commentSet.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
let text = self.lecture!.commentSet[indexPath.row]["text"].string!
let user = self.lecture!.commentSet[indexPath.row]["user"].string
let children = self.lecture!.commentSet[indexPath.row]["children"].array
var responses = 0
if children != nil {
responses = children!.count
}
var newText = ""
if user != nil {
newText = "\(text) \n\n via \(user!) - \(responses) Responses"
} else {
newText = "\(text)"
}
cell.textLabel?.text = newText
cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
cell.textLabel?.numberOfLines = 0
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let text = self.lecture!.commentSet[indexPath.row]["text"].string!
let user = self.lecture!.commentSet[indexPath.row]["user"].string
let children = self.lecture!.commentSet[indexPath.row]["children"].array
var responses = 0
if children != nil {
responses = children!.count
}
var newText = ""
if user != nil {
newText = "\(text) \n\n via \(user!) - \(responses) Responses"
} else {
newText = "\(text)"
}
let cellFont = UIFont.boldSystemFontOfSize(14)
let attrString = NSAttributedString(string: newText, attributes: [NSFontAttributeName : cellFont])
let constraintSize = CGSizeMake(self.tableView.bounds.size.width, CGFloat(MAXFLOAT))
let rect = attrString.boundingRectWithSize(constraintSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)
return rect.size.height + 50
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| b24f21c6d7410f37f93d10f938c76c85 | 38.807927 | 162 | 0.642797 | false | false | false | false |
CodaFi/swift | refs/heads/main | validation-test/Sanitizers/tsan-type-metadata.swift | apache-2.0 | 20 | // REQUIRES: rdar64809726
// RUN: %target-swiftc_driver -target %sanitizers-target-triple -sanitize=thread %import-libdispatch %s -o %t_binary
// RUN: %env-TSAN_OPTIONS=halt_on_error=1 %target-run %t_binary
// REQUIRES: executable_test
// REQUIRES: stress_test
// REQUIRES: tsan_runtime
// We expect not to report any races on this testcase.
// This test exercises accesses to type metadata, which uses lockless
// synchronization in the runtime that is relied upon by the direct accesses in the IR.
// We have to make sure TSan does not see the accesses to the metadata from the IR.
// Otherwise, it will report a race.
// Generic classes.
private class KeyWrapper<T: Hashable> {
let value: T
init(_ value: T) {
self.value = value
}
func present() {
print("Key: \(value)")
}
}
private class ValueWrapper<T> {
let value: T
init(_ value: T) {
self.value = value
}
func present() {
print("Value: \(value)")
}
}
// Concrete a class that inherits a generic base.
class Base<T> {
var first, second: T
required init(x: T) {
first = x
second = x
}
func present() {
print("\(type(of: self)) \(T.self) \(first) \(second)")
}
}
class SuperDerived: Derived {
}
class Derived: Base<String> {
var third: String
required init(x: String) {
third = x
super.init(x: x)
}
override func present() {
super.present()
print("...and \(third)")
}
}
func presentBase<T>(_ base: Base<T>) {
base.present()
}
func presentDerived(_ derived: Derived) {
derived.present()
}
public func testMetadata<Key: Hashable, Value>(_ key: Key, _ value: Value) {
let wrappedKey = KeyWrapper(key)
wrappedKey.present()
ValueWrapper(value).present()
presentBase(SuperDerived(x: "two"))
presentBase(Derived(x: "two"))
presentBase(Base(x: "two"))
presentBase(Base(x: 2))
presentDerived(Derived(x: "two"))
}
// Execute concurrently.
import StdlibUnittest
var RaceTestSuite = TestSuite("t")
RaceTestSuite.test("test_metadata") {
runRaceTest(trials: 1) {
testMetadata(4, 4)
}
}
runAllTests()
| 9bdfbb3bb30e0f759be4a98521b09a81 | 22.431818 | 116 | 0.667313 | false | true | false | false |
adamdahan/Thnx | refs/heads/master | Thnx/Thnx/Thnx.swift | bsd-3-clause | 1 | /*
* Copyright (C) 2016, Adam Dahan. <http://thnx.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
/**
:name: Strings
- Strings used in the framework
*/
public struct Strings {
static let license = "LICENSE"
static let regex = "(https:\\/\\/github.com\\/)(\\w)*\\/(\\w)*\\/(\\w)*\\/(\\w)*\\/(LICENSE)*(.md)?"
static let githubURL = "https://github.com"
static let githubRawURL = "https://raw.githubusercontent.com"
}
/**
:name: Strings
- Regular expression matching - used for grabbing URLs from HTML.
- Parameter regex: Regular expression as a string
- Parameter text: Text to match against the regular expression
*/
private func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let nsString = text as NSString
let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
return results.map { nsString.substring(with: $0.range)}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
/**
Main object
*/
public class Thnx {
/**
:name: licenses
- Strings used in the framework
- Parameter urls: Urls to github repositories you want to get licenses from as an array of strings
*/
public func licenses(urls: [String]) -> Dictionary <String, String> {
var d = Dictionary <String, String>()
for url in urls {
do {
let urlPath = URL(string: url)
let html = try String(contentsOf: urlPath!)
let results = matches(for: Strings.regex, in: html)
for r in results {
if r.contains(Strings.license) {
let comps = r.components(separatedBy: "/")
let replaced = url.replacingOccurrences(of: Strings.githubURL, with: Strings.githubRawURL)
let url = URL(string: "\(replaced)/\(comps[comps.count - 2])/\(comps.last!)")!
do {
let text = try String(contentsOf: url, encoding: .ascii)
d[url.absoluteString.components(separatedBy: "/")[4]] = text
} catch _ {}
}
}
} catch _ {}
}
return d
}
}
| 8cf1810a226fc96308d8bc6da50bf3d2 | 40.580645 | 114 | 0.644169 | false | false | false | false |
lexicalparadox/Chirppy | refs/heads/master | Chirppy/Tweet.swift | apache-2.0 | 1 | //
// Tweet.swift
// Chirppy
//
// Created by Alexander Doan on 9/26/17.
// Copyright © 2017 Alexander Doan. All rights reserved.
//
import UIKit
import SwiftDate
class Tweet: NSObject {
let dateFormatter = DateFormatter()
let user: User? //user
var retweetedByUser: User? // To signify the user who retweeted this tweet
var id: Int64? // id
var text: String? // text
var createdAt: String? // created_at
var createdAtDate: Date? // internal use - still setting up
var favoritesCount: Int? // favorite_count
var retweetCount: Int? // retweet_count
var favorited: Bool? // favorited
var retweeted: Bool? // retweeted -- to signify that the logged in user retweeted this tweet
var wasRetweeted: Bool // to signify whether this tweet is a retweet of another tweet
init(_ dict : NSDictionary) {
let retweetDict = dict["retweeted_status"] as? NSDictionary
if let retweetDict = retweetDict {
self.wasRetweeted = true
let retweetedByUser = dict["user"] as? NSDictionary
if let retweetedByUser = retweetedByUser {
self.retweetedByUser = User(retweetedByUser)
}
let userDict = retweetDict["user"] as? NSDictionary
self.user = User(userDict ?? NSDictionary())
self.id = retweetDict["id"] as! Int64
self.text = retweetDict["text"] as! String
self.createdAt = retweetDict["created_at"] as! String
if let createdAt = self.createdAt {
let date = try! DateInRegion(string: createdAt, format: .custom("EE MMM dd HH:mm:ss Z yyyy"), fromRegion: Region.Local())
self.createdAtDate = date?.absoluteDate
// DateFormatter.dateFormat(fromTemplate: "EE MMM dd HH:mm:ss Z yyyy", options: 0, locale: Locale.current)
// self.createdAtDate = dateFormatter.date(from: createdAt)
}
self.retweetCount = retweetDict["retweet_count"] as! Int
self.favoritesCount = retweetDict["favorite_count"] as! Int
self.favorited = retweetDict["favorited"] as! Bool
self.retweeted = retweetDict["retweeted"] as! Bool
} else {
let userDict = dict["user"] as? NSDictionary
self.user = User(userDict ?? NSDictionary())
self.id = dict["id"] as! Int64
self.text = dict["text"] as! String
self.createdAt = dict["created_at"] as! String
if let createdAt = self.createdAt {
let date = try! DateInRegion(string: createdAt, format: .custom("EE MMM dd HH:mm:ss Z yyyy"), fromRegion: Region.Local())
self.createdAtDate = date?.absoluteDate
// DateFormatter.dateFormat(fromTemplate: "EE MMM dd HH:mm:ss Z yyyy", options: 0, locale: Locale.current)
// self.createdAtDate = dateFormatter.date(from: createdAt)
}
self.retweetCount = dict["retweet_count"] as! Int
self.favoritesCount = dict["favorite_count"] as! Int
self.favorited = dict["favorited"] as! Bool
self.retweeted = dict["retweeted"] as! Bool
self.wasRetweeted = false
}
}
static func tweetsWithArray(_ list: [NSDictionary]) -> [Tweet] {
var tweets = [Tweet]()
for dictionary in list {
let tweet = Tweet(dictionary)
tweets.append(tweet)
}
return tweets
}
}
| fa00ce73c88fe7dd53e425bc2bf8bcb4 | 40.298851 | 137 | 0.589758 | false | false | false | false |
wikimedia/wikipedia-ios | refs/heads/main | Wikipedia/Code/Collection.swift | mit | 1 | protocol Collection: AnyObject {
var collectionView: UICollectionView { get set }
}
protocol UpdatableCollection: Collection, CollectionViewUpdaterDelegate {
associatedtype T: NSManagedObject
var dataStore: MWKDataStore { get }
var collectionViewUpdater: CollectionViewUpdater<T>? { get set }
var fetchedResultsController: NSFetchedResultsController<T>? { get set }
var basePredicate: NSPredicate { get }
var baseSortDescriptors: [NSSortDescriptor] { get }
func setupFetchedResultsController()
}
extension UpdatableCollection {
func setupCollectionViewUpdater() {
guard let fetchedResultsController = fetchedResultsController else {
return
}
collectionViewUpdater = CollectionViewUpdater(fetchedResultsController: fetchedResultsController, collectionView: collectionView)
collectionViewUpdater?.delegate = self
}
func fetch() {
collectionViewUpdater?.performFetch()
}
func reset() {
setupFetchedResultsController()
setupCollectionViewUpdater()
fetch()
}
}
extension UpdatableCollection where Self: SearchableCollection {
func setupFetchedResultsController() {
guard let request = T.fetchRequest() as? NSFetchRequest<T> else {
assertionFailure("Can't set up NSFetchRequest")
return
}
request.predicate = basePredicate
if let searchPredicate = searchPredicate {
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [basePredicate, searchPredicate])
}
request.sortDescriptors = baseSortDescriptors
fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: dataStore.viewContext, sectionNameKeyPath: nil, cacheName: nil)
}
}
protocol SearchableCollection: UpdatableCollection {
var searchString: String? { get set }
func updateSearchString(_ newSearchString: String)
var searchPredicate: NSPredicate? { get }
}
extension SearchableCollection where Self: EditableCollection {
func updateSearchString(_ newSearchString: String) {
guard newSearchString != searchString else {
return
}
searchString = newSearchString.isEmpty ? nil : newSearchString
editController.close()
reset()
}
}
enum SortActionType: Int {
case byTitle, byRecentlyAdded
func action(with sortDescriptors: [NSSortDescriptor], handler: @escaping ([NSSortDescriptor], UIAlertAction, Int) -> Void) -> SortAction {
let title: String
switch self {
case .byTitle:
title = WMFLocalizedString("sort-by-title-action", value: "Title", comment: "Title of the sort action that allows sorting items by title.")
case .byRecentlyAdded:
title = WMFLocalizedString("sort-by-recently-added-action", value: "Recently added", comment: "Title of the sort action that allows sorting items by date added.")
}
let alertAction = UIAlertAction(title: title, style: .default) { (alertAction) in
handler(sortDescriptors, alertAction, self.rawValue)
}
return SortAction(alertAction: alertAction, type: self, sortDescriptors: sortDescriptors)
}
}
struct SortAction {
let alertAction: UIAlertAction
let type: SortActionType
let sortDescriptors: [NSSortDescriptor]
}
protocol SortableCollection: UpdatableCollection {
var sort: (descriptors: [NSSortDescriptor], alertAction: UIAlertAction?) { get }
var defaultSortAction: SortAction? { get }
var defaultSortDescriptors: [NSSortDescriptor] { get }
var sortActions: [SortActionType: SortAction] { get }
var sortAlert: UIAlertController { get }
func presentSortAlert(from button: UIButton)
func updateSortActionCheckmark()
}
extension SortableCollection where Self: UIViewController {
func alert(title: String, message: String?) -> UIAlertController {
let alert = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
sortActions.values.forEach { alert.addAction($0.alertAction) }
let cancel = UIAlertAction(title: CommonStrings.cancelActionTitle, style: .cancel)
alert.addAction(cancel)
return alert
}
func updateSortActionCheckmark() {
// hax https://stackoverflow.com/questions/40647039/how-to-add-uiactionsheet-button-check-mark
let checkedKey = "checked"
sortActions.values.forEach { $0.alertAction.setValue(false, forKey: checkedKey) }
let checkedAction = sort.alertAction ?? defaultSortAction?.alertAction
checkedAction?.setValue(true, forKey: checkedKey)
}
func presentSortAlert(from button: UIButton) {
if let popoverController = sortAlert.popoverPresentationController {
popoverController.sourceView = button
popoverController.sourceRect = button.bounds
}
present(sortAlert, animated: true)
updateSortActionCheckmark()
}
var baseSortDescriptors: [NSSortDescriptor] {
return sort.descriptors.isEmpty ? defaultSortDescriptors : sort.descriptors
}
var defaultSortDescriptors: [NSSortDescriptor] {
guard let defaultSortAction = defaultSortAction else {
assertionFailure("Sort action not found")
return []
}
return defaultSortAction.sortDescriptors
}
}
protocol EditableCollection: Collection {
var editController: CollectionViewEditController! { get set }
var shouldShowEditButtonsForEmptyState: Bool { get }
func setupEditController()
}
extension EditableCollection where Self: ActionDelegate {
func setupEditController() {
editController = CollectionViewEditController(collectionView: collectionView)
editController.delegate = self
editController.shouldShowEditButtonsForEmptyState = shouldShowEditButtonsForEmptyState
if let navigationDelegate = self as? CollectionViewEditControllerNavigationDelegate {
editController.navigationDelegate = navigationDelegate
}
}
var shouldShowEditButtonsForEmptyState: Bool {
return false
}
}
| 4c1c2213f494197e35ae84d27264b935 | 37.537037 | 174 | 0.706712 | false | false | false | false |
Danappelxx/SwiftMongoDB | refs/heads/linux | Sources/Database.swift | mit | 1 | //
// Database.swift
// SwiftMongoDB
//
// Created by Dan Appel on 11/23/15.
// Copyright © 2015 Dan Appel. All rights reserved.
//
import CMongoC
import BinaryJSON
public final class Database {
let pointer: _mongoc_database
/// Databases are automatically created on the MongoDB server upon insertion of the first document into a collection. There is no need to create a database manually.
public init(client: Client, name: String) {
self.pointer = mongoc_client_get_database(client.pointer, name)
}
deinit {
mongoc_database_destroy(pointer)
}
public var name: String {
let nameRaw = mongoc_database_get_name(pointer)
return String(cString:nameRaw)
}
public var collectionNames: [String]? {
var error = bson_error_t()
var buffer = mongoc_database_get_collection_names(self.pointer, &error)
if error.error.isError {
return nil
}
var names = [String]()
while buffer.pointee != nil {
let name = String(cString:buffer.pointee)
names.append(name)
buffer = buffer.successor()
}
return names
}
public func removeUser(username: String) throws -> Bool {
var error = bson_error_t()
let successful = mongoc_database_remove_user(pointer, username, &error)
try error.throwIfError()
return successful
}
public func removeAllUsers() throws -> Bool {
var error = bson_error_t()
let successful = mongoc_database_remove_all_users(pointer, &error)
try error.throwIfError()
return successful
}
// public func addUser(username username: String, password: String, roles: [String], customData: BSON.Document) throws -> Bool {
//
// guard let rolesJSON = roles.toJSON()?.toString() else { throw MongoError.InvalidData }
//
// var error = bson_error_t()
//
// var rolesRaw = try MongoBSON(json: rolesJSON).bson
// var customDataRaw = try MongoBSON(data: customData).bson
//
// let successful = mongoc_database_add_user(pointer, username, password, &rolesRaw, &customDataRaw, &error)
//
// try error.throwIfError()
//
// return successful
// }
// public func command(command: BSON.Document, flags: QueryFlags = .None, skip: Int = 0, limit: Int = 0, batchSize: Int = 0, fields: [String] = []) throws -> Cursor {
//
// guard let fieldsJSON = fields.toJSON()?.toString() else { throw MongoError.InvalidData }
//
// var commandRaw = try MongoBSON(data: command).bson
// var fieldsRaw = try MongoBSON(json: fieldsJSON).bson
//
// let cursorRaw = mongoc_database_command(pointer, flags.rawFlag, skip.UInt32Value, limit.UInt32Value, batchSize.UInt32Value, &commandRaw, &fieldsRaw, nil)
//
// let cursor = Cursor(cursor: cursorRaw)
//
// return cursor
// }
public func drop() throws -> Bool {
var error = bson_error_t()
let successful = mongoc_database_drop(pointer, &error)
try error.throwIfError()
return successful
}
public func hasCollection(name name: String) throws -> Bool {
var error = bson_error_t()
let successful = mongoc_database_has_collection(pointer, name, &error)
try error.throwIfError()
return successful
}
public func createCollection(name name: String, options: BSON.Document) throws -> Collection {
let options = try BSON.AutoReleasingCarrier(document: options)
var error = bson_error_t()
mongoc_database_create_collection(pointer, name, options.pointer, &error)
try error.throwIfError()
let collection = Collection(database: self, name: name)
return collection
}
public func findCollections(filter filter: BSON.Document) throws -> Cursor {
let filter = try BSON.AutoReleasingCarrier(document: filter)
var error = bson_error_t()
let cursorPointer = mongoc_database_find_collections(pointer, filter.pointer, &error)
try error.throwIfError()
let cursor = Cursor(pointer: cursorPointer)
return cursor
}
public func basicCommand(command command: BSON.Document) throws -> BSON.Document {
let command = try BSON.AutoReleasingCarrier(document: command)
var reply = bson_t()
var error = bson_error_t()
mongoc_database_command_simple(self.pointer, command.pointer, nil, &reply, &error)
try error.throwIfError()
guard let res = BSON.documentFromUnsafePointer(&reply) else {
throw MongoError.CorruptDocument
}
return res
}
}
| 8a9fbba36d006ee229b57898008e8109 | 27.143713 | 169 | 0.639149 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | refs/heads/master | Swift/LeetCode/Array/345_Reverse Vowels of a String.swift | mit | 1 | //
// 345. Reverse Vowels of a String.swift
// https://leetcode.com/problems/reverse-vowels-of-a-string/
//
// Created by Honghao Zhang on 2016-11-02.
// Copyright © 2016 Honghaoz. All rights reserved.
//
//Write a function that takes a string as input and reverse only the vowels of a string.
//
//Example 1:
//
//Input: "hello"
//Output: "holle"
//Example 2:
//
//Input: "leetcode"
//Output: "leotcede"
//Note:
//The vowels does not include the letter "y".
import Foundation
class Num345_ReverseVowels: Solution {
func reverseVowels(_ s: String) -> String {
var s = [Character](s)
var vowelsIndices: [Int] = []
for (index, char) in s.enumerated() {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" ||
char == "A" || char == "E" || char == "I" || char == "O" || char == "U" {
vowelsIndices.append(index)
}
}
for i in 0..<vowelsIndices.count / 2 {
let left = vowelsIndices[i]
let right = vowelsIndices[vowelsIndices.count - 1 - i]
(s[left], s[right]) = (s[right], s[left])
}
return String(s)
}
func test() {
}
}
| 668f1092036e6f034169ecf610d0e3ef | 22.583333 | 88 | 0.581272 | false | false | false | false |
PJayRushton/stats | refs/heads/master | Stats/ShadowableCell.swift | mit | 1 | //
// /||\
// / || \
// / )( \
// /__/ \__\
//
import Foundation
import UIKit
protocol ShadowableCell: class {}
extension ShadowableCell where Self: UICollectionViewCell {
func addShadowToTop() {
let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: bounds.width, height: 1)).cgPath
addShadow(with: path)
}
func addShadowToBottom() {
let path = UIBezierPath(rect: CGRect(x: 0, y: bounds.height, width: bounds.width, height: 1)).cgPath
addShadow(with: path)
}
func removeShadow() {
layer.shadowPath = UIBezierPath(rect: .zero).cgPath
}
}
private extension ShadowableCell where Self: UICollectionViewCell {
func addShadow(with path: CGPath) {
layer.masksToBounds = false
layer.shadowOpacity = 0.25
layer.shadowRadius = 2.0
layer.shadowOffset = .zero
layer.shadowColor = UIColor.black.cgColor
layer.shadowPath = path
clipsToBounds = false
}
}
| 36aa427dc8824527e0cf1a86a88a2143 | 21.644444 | 108 | 0.60157 | false | false | false | false |
ontouchstart/swift3-playground | refs/heads/playgroundbook | ontouchstart/ontouchstart.playgroundbook/Contents/Chapters/Chapter1.playgroundchapter/Pages/Page3.playgroundpage/LiveView.swift | mit | 1 | import UIKit
import PlaygroundSupport
let frame = CGRect(x: 0, y:0, width: 400, height: 300)
let label = UILabel(frame: frame)
label.text = "ontouchstart"
label.textColor = .blue()
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 60)
var view = UIView(frame: frame)
view.addSubview(label)
PlaygroundPage.current.liveView = view
| 0a78889bfb7db80de312bb3881f47729 | 24.357143 | 54 | 0.757746 | false | false | false | false |
jegumhon/URWeatherView | refs/heads/master | URWeatherView/Effect/UREffectLightningLineNode.swift | mit | 1 | //
// UREffectLightningLineNode.swift
// URWeatherView
//
// Created by DongSoo Lee on 2017. 5. 26..
// Copyright © 2017년 zigbang. All rights reserved.
//
import SpriteKit
/// draw the lightning line
class UREffectLightningLineNode: SKNode {
static let textureLightningHalfCircle: SKTexture = SKTexture(image: UIImage(named: "lightning_half_circle", in: Bundle(for: UREffectLigthningNode.self), compatibleWith: nil)!)
static let textureLightningSegment: SKTexture = SKTexture(image: UIImage(named: "lightning_segment", in: Bundle(for: UREffectLigthningNode.self), compatibleWith: nil)!)
var startPoint: CGPoint = .zero
var endPoint: CGPoint = .zero
var lineThickness = 1.3
init(start startPoint: CGPoint, end endPoint: CGPoint, thickness: Double = 1.3) {
super.init()
self.startPoint = startPoint
self.endPoint = endPoint
self.lineThickness = thickness
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func draw() {
let imageThickness = 2.0
let ratioThickness = CGFloat(self.lineThickness / imageThickness)
let startPointInNode = self.convert(self.startPoint, from: self.parent!)
let endPointInNode = self.convert(self.endPoint, from: self.parent!)
let angle = atan2(endPointInNode.y - startPointInNode.y, endPointInNode.x - startPointInNode.x)
let length = hypot(abs(endPointInNode.x - startPointInNode.x), abs(endPointInNode.y - startPointInNode.y))
let halfCircleFront = SKSpriteNode(texture: UREffectLightningLineNode.textureLightningHalfCircle)
halfCircleFront.anchorPoint = CGPoint(x: 1.0, y: 0.5)
halfCircleFront.yScale = ratioThickness
halfCircleFront.zRotation = angle
halfCircleFront.blendMode = .alpha
halfCircleFront.position = startPointInNode
let halfCircleBack = SKSpriteNode(texture: UREffectLightningLineNode.textureLightningHalfCircle)
halfCircleBack.anchorPoint = CGPoint(x: 1.0, y: 0.5)
halfCircleBack.xScale = -1.0
halfCircleBack.yScale = ratioThickness
halfCircleBack.zRotation = angle
halfCircleBack.blendMode = .alpha
halfCircleBack.position = endPointInNode
let lightningSegment = SKSpriteNode(texture: UREffectLightningLineNode.textureLightningSegment)
lightningSegment.xScale = length * 2.0
lightningSegment.yScale = ratioThickness
lightningSegment.zRotation = angle
lightningSegment.position = CGPoint(x: (startPointInNode.x + endPointInNode.x) * 0.5, y: (startPointInNode.y + endPointInNode.y) * 0.5)
self.addChild(halfCircleFront)
self.addChild(halfCircleBack)
self.addChild(lightningSegment)
}
}
| 317aed142f8e7dad3d1d7fcc72ced1da | 39.735294 | 179 | 0.710108 | false | false | false | false |
liuguya/TestKitchen_1606 | refs/heads/master | TestKitchen/TestKitchen/classes/common/UILabel+Util.swift | mit | 1 | //
// UILabel+Util.swift
// TestKitchen
//
// Created by 阳阳 on 16/8/15.
// Copyright © 2016年 liuguyang. All rights reserved.
//
import UIKit
extension UILabel{
class func createLabel(text:String?,font:UIFont?,textAlignment:NSTextAlignment?,textColor:UIColor?)->UILabel{
let label = UILabel()
if let labelText = text {
label.text = labelText
}
if let labelFont = font{
label.font = labelFont
}
if let labelTextAlignment = textAlignment{
label.textAlignment = labelTextAlignment
}
if let labelColor = textColor{
label.textColor = labelColor
}
return label
}
}
| 2c1b831d1c2532eb3c66b11383bb56e4 | 22.03125 | 113 | 0.571235 | false | false | false | false |
CaiMiao/CGSSGuide | refs/heads/master | DereGuide/Model/CGSSLive.swift | mit | 1 | //
// CGSSLive.swift
// DereGuide
//
// Created by zzk on 16/7/23.
// Copyright © 2016年 zzk. All rights reserved.
//
import UIKit
import SwiftyJSON
enum CGSSLiveSimulatorType: String, CustomStringConvertible, ColorRepresentable {
case normal = "常规模式" //!!!无法被本地化 注意使用时本地化
case vocal = "Vocal Burst"
case dance = "Dance Burst"
case visual = "Visual Burst"
case parade = "LIVE Parade"
static let all: [CGSSLiveSimulatorType] = [.normal, .vocal, .dance, .visual, .parade]
var color: UIColor {
switch self {
case .normal:
return Color.parade
case .vocal:
return Color.vocal
case .dance:
return Color.dance
case .visual:
return Color.passion
case .parade:
return Color.parade
}
}
var description: String {
switch self {
case .normal:
return NSLocalizedString("常规模式", comment: "")
default:
return self.rawValue
}
}
}
enum CGSSGrooveType: String, CustomStringConvertible, ColorRepresentable {
case cute = "Cute Groove"
case cool = "Cool Groove"
case passion = "Passion Groove"
static let all: [CGSSGrooveType] = [.cute, .cool, .passion]
var description: String {
return self.rawValue
}
var color: UIColor {
switch self {
case .cute:
return Color.cute
case .cool:
return Color.cool
case .passion:
return Color.passion
}
}
init? (cardType: CGSSCardTypes) {
switch cardType {
case CGSSCardTypes.cute:
self = .cute
case CGSSCardTypes.cool:
self = .cool
case CGSSCardTypes.passion:
self = .passion
default:
return nil
}
}
}
// MARK: 用于排序的属性
extension CGSSLive {
@objc dynamic var updateId: Int {
return details.map { $0.id }.max() ?? 0
}
@objc dynamic var maxDiffStars: Int {
return selectedLiveDetails.map { $0.stars }.max() ?? 0
}
@objc dynamic var maxNumberOfNotes: Int {
return selectedLiveDetails.map {
if $0.numberOfNotes != 0 {
return $0.numberOfNotes
} else {
return getBeatmap(of: $0.difficulty)?.numberOfNotes ?? 0
}
}.max() ?? 0
// this method takes very long time, because it read each beatmap files
// return self.getBeatmap(of: selectableMaxDifficulty)?.numberOfNotes ?? 0
}
@objc dynamic var sLength: Float {
return getBeatmap(of: .debut)?.totalSeconds ?? 0
}
}
extension CGSSLive {
// 每beat占用的秒数
var barSecond: Double {
return 1 / Double(bpm) * 60
}
var color: UIColor {
switch type {
case 1:
return Color.cute
case 2:
return Color.cool
case 3:
return Color.passion
default:
return UIColor.darkText
}
}
var icon: UIImage {
switch type {
case 1:
return #imageLiteral(resourceName: "song-cute")
case 2:
return #imageLiteral(resourceName: "song-cool")
case 3:
return #imageLiteral(resourceName: "song-passion")
default:
return #imageLiteral(resourceName: "song-all")
}
}
var filterType: CGSSLiveTypes {
switch type {
case 1:
return .cute
case 2:
return .cool
case 3:
return .passion
default:
return .office
}
}
var eventFilterType: CGSSLiveEventTypes {
return CGSSLiveEventTypes.init(eventType: eventType)
}
func getBeatmap(of difficulty: CGSSLiveDifficulty) -> CGSSBeatmap? {
return beatmaps.first { $0.difficulty == difficulty }
}
func getLiveDetail(of difficulty: CGSSLiveDifficulty) -> CGSSLiveDetail? {
return details.first { $0.difficulty == difficulty }
}
var jacketURL: URL {
return URL.images.appendingPathComponent("/jacket/\(musicDataId).png")
}
var selectedLiveDetails: [CGSSLiveDetail] {
return details.filter {
self.difficultyTypes.contains($0.difficultyTypes)
}
}
// var title: String {
// if eventType == 0 {
// return name
// } else {
// return name + "(" + NSLocalizedString("活动", comment: "") + ")"
// }
// }
subscript (difficulty: CGSSLiveDifficulty) -> CGSSLiveDetail? {
get {
return getLiveDetail(of: difficulty)
}
}
func merge(anotherLive live: CGSSLive) {
eventType = max(live.eventType, eventType)
startDate = min(live.startDate, startDate)
musicDataId = max(live.musicDataId, musicDataId)
let eventLive: CGSSLive
let normalLive: CGSSLive
if self.eventType > live.eventType {
eventLive = self
normalLive = live
} else {
eventLive = live
normalLive = self
}
if !normalLive.details.contains { $0.difficulty == .masterPlus } {
var liveDetails = normalLive.details
if let masterPlus = eventLive.details.first(where: { $0.difficulty == .masterPlus }) {
liveDetails.append(masterPlus)
id = eventLive.id
}
liveDetails.sort { $0.difficulty.rawValue < $1.difficulty.rawValue }
self.details = liveDetails
}
}
}
class CGSSLive: NSObject {
@objc dynamic var bpm : Int
var eventType : Int
var id : Int
var musicDataId : Int
var name : String
@objc dynamic var startDate : String
var type : Int
var details = [CGSSLiveDetail]()
lazy var beatmapCount: Int = {
let semaphore = DispatchSemaphore.init(value: 0)
var result = 0
let path = String.init(format: DataPath.beatmap, self.id)
let fm = FileManager.default
if fm.fileExists(atPath: path) {
let dbQueue = MusicScoreDBQueue.init(path: path)
dbQueue.getBeatmapCount(callback: { (count) in
result = count
semaphore.signal()
})
} else {
semaphore.signal()
}
semaphore.wait()
return result
}()
lazy var vocalists: [Int] = {
let semaphore = DispatchSemaphore(value: 0)
var result = [Int]()
CGSSGameResource.shared.master.getVocalistsBy(musicDataId: self.musicDataId, callback: { (list) in
result = list
semaphore.signal()
})
semaphore.wait()
return result
}()
lazy var beatmaps: [CGSSBeatmap] = {
guard let beatmaps = CGSSGameResource.shared.getBeatmaps(liveId: self.id) else {
return [CGSSBeatmap]()
}
return beatmaps
}()
/// used in filter
var difficultyTypes: CGSSLiveDifficultyTypes = .all
/**
* Instantiate the instance using the passed json values to set the properties values
*/
init? (fromJson json: JSON){
if json.isEmpty {
return nil
}
bpm = json["bpm"].intValue
eventType = json["event_type"].intValue
id = json["id"].intValue
musicDataId = json["music_data_id"].intValue
name = json["name"].stringValue.replacingOccurrences(of: "\\n", with: "")
startDate = json["start_date"].stringValue
type = json["type"].intValue
super.init()
}
}
| 14e9d40d636e072e35f69d8e074b5ff9 | 25.861592 | 106 | 0.553265 | false | false | false | false |
guoc/spi | refs/heads/master | SPi/ViewController.swift | bsd-3-clause | 1 | //
// ViewController.swift
// SPi
//
// Created by GuoChen on 2/12/2014.
// Copyright (c) 2014 guoc. All rights reserved.
//
import UIKit
class ViewController: UINavigationController, IASKSettingsDelegate {
var appSettingsViewController: IASKAppSettingsViewController!
init() {
let appSettingsViewController = IASKAppSettingsViewController()
super.init(rootViewController: appSettingsViewController)
appSettingsViewController.delegate = self
appSettingsViewController.showCreditsFooter = false
appSettingsViewController.showDoneButton = false
appSettingsViewController.title = "SPi 双拼输入法"
self.appSettingsViewController = appSettingsViewController
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
func settingsViewControllerDidEnd(_ sender: IASKAppSettingsViewController!) {
}
func settingsViewController(_ settingsViewController: IASKViewController!, tableView: UITableView!, heightForHeaderForSection section: Int) -> CGFloat {
if let key = settingsViewController.settingsReader.key(forSection: section) {
if key == "kScreenshotTapKeyboardSettingsIcon" {
return UIImage(named: "Screenshot tap keyboard settings icon")!.size.height
}
}
return 0
}
func settingsViewController(_ settingsViewController: IASKViewController!, tableView: UITableView!, viewForHeaderForSection section: Int) -> UIView! {
if let key = settingsViewController.settingsReader.key(forSection: section) {
if key == "kScreenshotTapKeyboardSettingsIcon" {
let imageView = UIImageView(image: UIImage(named: "Screenshot tap keyboard settings icon"))
imageView.contentMode = .scaleAspectFit
return imageView
}
}
return nil
}
func settingsViewController(_ sender: IASKAppSettingsViewController!, buttonTappedFor specifier: IASKSpecifier!) {
if specifier.key() == "kFeedback" {
UserVoice.presentInterface(forParentViewController: self)
}
}
func pushToTutorialIfNecessary() {
if isCustomKeyboardEnabled() == false {
self.appSettingsViewController.tableView(self.appSettingsViewController.tableView, didSelectRowAt: IndexPath(item: 0, section: 0))
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.blue
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func isCustomKeyboardEnabled() -> Bool {
let bundleID = "name.guoc.SPi.SPiKeyboard"
if let keyboards: [String] = UserDefaults.standard.dictionaryRepresentation()["AppleKeyboards"] as? [String] { // Array of all active keyboards
for keyboard in keyboards {
if keyboard == bundleID {
return true
}
}
}
return false
}
}
| 35ff2b4d42babed1f20a592b4fb0b360 | 34.774194 | 156 | 0.662158 | false | false | false | false |
darwin/textyourmom | refs/heads/master | TextYourMom/Globals.swift | mit | 1 | import UIKit
var model = Model()
var masterController = MasterController()
var sharedLogsModel = LogsModel()
var mainWindow : UIWindow?
var disableScreenSwitching = false
var presentViewControllerQueue = dispatch_queue_create("presentViewControllerQueue", DISPATCH_QUEUE_SERIAL)
var lastError : String?
var mapController : MapController?
var lastLatitude : Double = 0
var lastLongitude : Double = 0
var useSignificantLocationChanges = true
var supressNextStateChangeReport = true
var overrideLocation = 0 // 0 means no override | 9b702db5926c34c90398da90544fd832 | 32.125 | 107 | 0.810964 | false | false | false | false |
twlkyao/Swift | refs/heads/master | var_let/var_let/main.swift | gpl-2.0 | 1 | //
// main.swift
// var_let
//
// Created by Jack on 6/8/14.
// Copyright (c) 2014 Jack. All rights reserved.
//
import Foundation
let product_constant = "iPhone6"
var product_var = "iPad5"
var id = 50
println(id)
var x1 = 30, x2 = "abc"
var value:Int = 33
var 齐士垚 = "Shiyao Qi"
println(齐士垚)
println("x1=\(x1),齐士垚=\(齐士垚)") | 5572473a04e97c4d5e551e9d1143029a | 11.923077 | 49 | 0.626866 | false | false | false | false |
dim0v/DOCheckboxControl | refs/heads/master | Example/DOCheckboxControl/MainTableViewController.swift | mit | 1 | //
// MainTableViewController.swift
// DOCheckboxControl
//
// Created by Dmytro Ovcharenko on 22.07.15.
// Copyright (c) 2015 CocoaPods. All rights reserved.
//
import UIKit
import DOCheckboxControl
class MainTableViewController: UITableViewController {
@IBOutlet weak var programmaticalySwitchableCheckbox: CheckboxControl!
@IBOutlet weak var switchInstantlyBtn: UIButton!
@IBOutlet weak var switchAnimatedBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
programmaticalySwitchableCheckbox.isEnabled = false
switchInstantlyBtn.titleLabel?.numberOfLines = 0;
switchAnimatedBtn.titleLabel?.numberOfLines = 0;
switchInstantlyBtn.titleLabel?.textAlignment = NSTextAlignment.center;
switchAnimatedBtn.titleLabel?.textAlignment = NSTextAlignment.center;
}
@IBAction func switchAnimated() {
programmaticalySwitchableCheckbox.setSelected(!programmaticalySwitchableCheckbox.isSelected, animated: true)
}
@IBAction func switchNotAnimated() {
programmaticalySwitchableCheckbox.setSelected(!programmaticalySwitchableCheckbox.isSelected, animated: false)
}
}
| 17be1a6be901878d13ac44251232ab37 | 33.114286 | 117 | 0.746231 | false | false | false | false |
aryehToDog/DYZB | refs/heads/master | DYZB/DYZB/Class/Home/Controller/WKAmuseViewController.swift | apache-2.0 | 1 | //
// WKAmuseViewController.swift
// DYZB
//
// Created by 阿拉斯加的狗 on 2017/9/3.
// Copyright © 2017年 阿拉斯加的🐶. All rights reserved.
//
import UIKit
fileprivate let amuseMenuViewH: CGFloat = 200
class WKAmuseViewController: WKBaseAnchorViewController {
let amuseViewModel: WKAmuseViewModel = WKAmuseViewModel()
//懒加载
fileprivate lazy var amuseMenuView: WKAmuseMenuView = {
let amuseMenuView = WKAmuseMenuView.amuseMenuView()
amuseMenuView.frame = CGRect(x: 0, y: -amuseMenuViewH, width: WKWidth, height: amuseMenuViewH)
return amuseMenuView
}()
}
extension WKAmuseViewController {
override func setupUI() {
super.setupUI()
collectionView.addSubview(amuseMenuView)
collectionView.contentInset = UIEdgeInsets(top: amuseMenuViewH, left: 0, bottom: 0, right: 0)
}
}
extension WKAmuseViewController {
override func reloadData() {
baseViewModel = amuseViewModel
amuseViewModel.loadAmuseData {
var tempGroupModel = self.amuseViewModel.modelArray
tempGroupModel.remove(at: 0)
self.amuseMenuView.anchorGroupModel = tempGroupModel
self.collectionView.reloadData()
self.finishedCallBackEndAnimatin()
}
}
}
| 634977c2d4a3517ca7a75b3f654d7c61 | 21.428571 | 102 | 0.61925 | false | false | false | false |
Aaron-zheng/yugioh | refs/heads/master | yugioh/CardViewWithStarController.swift | agpl-3.0 | 1 | //
// CardViewWithStarController.swift
// yugioh
//
// Created by Aaron on 30/1/2017.
// Copyright © 2017 sightcorner. All rights reserved.
//
import Foundation
import UIKit
import Kingfisher
class CardViewWithStarController: CardViewBaseController {
@IBOutlet weak var iTableView: UITableView!
private var cardService = CardService()
override func viewDidLoad() {
self.tableView = iTableView
self.setupTableView()
self.afterDeselect = starAfterDeselect
}
func starAfterDeselect() {
self.tableView.reloadData()
}
public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let ids = cardService.list()
self.cardEntitys = []
for index in 0..<ids.count {
cardEntitys.append(getCardEntity(id: ids[index]))
}
return self.cardEntitys.count
}
}
| f6422cd1afd582a062bdd471dd92389a | 20.319149 | 105 | 0.607784 | false | false | false | false |
CPRTeam/CCIP-iOS | refs/heads/master | Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/OFB.swift | gpl-3.0 | 3 | //
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
// Output Feedback (OFB)
//
public struct OFB: BlockMode {
public enum Error: Swift.Error {
/// Invalid IV
case invalidInitializationVector
}
public let options: BlockModeOption = [.initializationVectorRequired, .useEncryptToDecrypt]
private let iv: Array<UInt8>
public init(iv: Array<UInt8>) {
self.iv = iv
}
public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker {
if self.iv.count != blockSize {
throw Error.invalidInitializationVector
}
return OFBModeWorker(blockSize: blockSize, iv: self.iv.slice, cipherOperation: cipherOperation)
}
}
struct OFBModeWorker: BlockModeWorker {
let cipherOperation: CipherOperationOnBlock
let blockSize: Int
let additionalBufferSize: Int = 0
private let iv: ArraySlice<UInt8>
private var prev: ArraySlice<UInt8>?
init(blockSize: Int, iv: ArraySlice<UInt8>, cipherOperation: @escaping CipherOperationOnBlock) {
self.blockSize = blockSize
self.iv = iv
self.cipherOperation = cipherOperation
}
mutating func encrypt(block plaintext: ArraySlice<UInt8>) -> Array<UInt8> {
guard let ciphertext = cipherOperation(prev ?? iv) else {
return Array(plaintext)
}
self.prev = ciphertext.slice
return xor(plaintext, ciphertext)
}
mutating func decrypt(block ciphertext: ArraySlice<UInt8>) -> Array<UInt8> {
guard let decrypted = cipherOperation(prev ?? iv) else {
return Array(ciphertext)
}
let plaintext: Array<UInt8> = xor(decrypted, ciphertext)
prev = decrypted.slice
return plaintext
}
}
| bf6fca7aa63bb9f5d56b72377c681047 | 35.057143 | 217 | 0.735737 | false | false | false | false |
blstream/mEatUp | refs/heads/master | mEatUp/mEatUp/InvitationViewController.swift | apache-2.0 | 1 | //
// InvitationViewController.swift
// mEatUp
//
// Created by Krzysztof Przybysz on 27/04/16.
// Copyright © 2016 BLStream. All rights reserved.
//
import UIKit
import CloudKit
class InvitationViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
let cloudKitHelper = CloudKitHelper()
var users = [User]()
var currentUserList: [User] {
get {
return loadCurrentUserList(filter)
}
}
var completionHandler: ((User) -> Void)? = nil
var filter: ((User) -> Bool)? = nil
var checked = [User]()
var room: Room?
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
guard let roomRecordID = self.room?.recordID else { return }
cloudKitHelper.loadUserRecords({ [unowned self] users in
for user in users {
guard let userRecordID = user.recordID else { return }
self.cloudKitHelper.checkIfUserInRoom(roomRecordID, userRecordID: userRecordID, completionHandler: { [unowned self] userInRoom in
if userInRoom == nil {
self.users.append(user)
self.tableView.reloadData()
}
}, errorHandler: nil)
}
}, errorHandler: nil)
}
@IBAction func cancelButtonTapped(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func inviteButtonTapped(sender: UIBarButtonItem) {
sender.enabled = false
guard let roomRecordID = room?.recordID else { return }
for user in checked {
guard let userRecordID = user.recordID else {
return
}
completionHandler?(user)
let userInRoom = UserInRoom(userRecordID: userRecordID, roomRecordID: roomRecordID, confirmationStatus: .Invited)
cloudKitHelper.saveUserInRoomRecord(userInRoom, completionHandler: {
self.dismissViewControllerAnimated(true, completion: nil)
}, errorHandler: nil)
}
}
func loadCurrentUserList(filter: ((User) -> Bool)?) -> [User] {
guard let filter = filter else {
return users
}
return users.filter({filter($0)})
}
}
extension InvitationViewController: UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return currentUserList.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UserCell", forIndexPath: indexPath)
if let cell = cell as? UserTableViewCell {
let user = currentUserList[indexPath.row]
let accessoryType: UITableViewCellAccessoryType = checked.contains(user) ? .Checkmark : .None
cell.configureWithUser(currentUserList[indexPath.row], accessoryType: accessoryType)
return cell
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let cell = tableView.cellForRowAtIndexPath(indexPath)
let user = currentUserList[indexPath.row]
if checked.contains(user) {
if let index = checked.indexOf(user) {
checked.removeAtIndex(index)
cell?.accessoryType = .None
}
} else {
checked.append(user)
cell?.accessoryType = .Checkmark
}
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
filter = nil
} else {
filter = { user in
guard let name = user.name, let surname = user.surname else {
return false
}
let userName = "\(name) \(surname)"
return userName.lowercaseString.containsString(searchText.lowercaseString)
}
}
tableView.reloadData()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.text = ""
filter = nil
searchBar.endEditing(true)
tableView.reloadData()
}
}
| fcc7019804485a4216e954733f9010f1 | 32.328467 | 145 | 0.601621 | false | false | false | false |
phatblat/Nimble | refs/heads/master | Sources/Nimble/Adapters/NMBExpectation.swift | apache-2.0 | 1 | import Foundation
import Dispatch
#if canImport(Darwin) && !SWIFT_PACKAGE
private func from(objcPredicate: NMBPredicate) -> Predicate<NSObject> {
return Predicate { actualExpression in
let result = objcPredicate.satisfies(({ try actualExpression.evaluate() }),
location: actualExpression.location)
return result.toSwift()
}
}
internal struct ObjCMatcherWrapper: Matcher {
let matcher: NMBMatcher
func matches(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
return matcher.matches(
// swiftlint:disable:next force_try
({ try! actualExpression.evaluate() }),
failureMessage: failureMessage,
location: actualExpression.location)
}
func doesNotMatch(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
return matcher.doesNotMatch(
// swiftlint:disable:next force_try
({ try! actualExpression.evaluate() }),
failureMessage: failureMessage,
location: actualExpression.location)
}
}
// Equivalent to Expectation, but for Nimble's Objective-C interface
public class NMBExpectation: NSObject {
// swiftlint:disable identifier_name
internal let _actualBlock: () -> NSObject?
internal var _negative: Bool
internal let _file: FileString
internal let _line: UInt
internal var _timeout: DispatchTimeInterval = .seconds(1)
// swiftlint:enable identifier_name
@objc public init(actualBlock: @escaping () -> NSObject?, negative: Bool, file: FileString, line: UInt) {
self._actualBlock = actualBlock
self._negative = negative
self._file = file
self._line = line
}
private var expectValue: Expectation<NSObject> {
return expect(_file, line: _line) {
self._actualBlock() as NSObject?
}
}
@objc public var withTimeout: (TimeInterval) -> NMBExpectation {
return { timeout in self._timeout = timeout.dispatchInterval
return self
}
}
@objc public var to: (NMBMatcher) -> Void {
return { matcher in
if let pred = matcher as? NMBPredicate {
self.expectValue.to(from(objcPredicate: pred))
} else {
self.expectValue.to(ObjCMatcherWrapper(matcher: matcher))
}
}
}
@objc public var toWithDescription: (NMBMatcher, String) -> Void {
return { matcher, description in
if let pred = matcher as? NMBPredicate {
self.expectValue.to(from(objcPredicate: pred), description: description)
} else {
self.expectValue.to(ObjCMatcherWrapper(matcher: matcher), description: description)
}
}
}
@objc public var toNot: (NMBMatcher) -> Void {
return { matcher in
if let pred = matcher as? NMBPredicate {
self.expectValue.toNot(from(objcPredicate: pred))
} else {
self.expectValue.toNot(ObjCMatcherWrapper(matcher: matcher))
}
}
}
@objc public var toNotWithDescription: (NMBMatcher, String) -> Void {
return { matcher, description in
if let pred = matcher as? NMBPredicate {
self.expectValue.toNot(from(objcPredicate: pred), description: description)
} else {
self.expectValue.toNot(ObjCMatcherWrapper(matcher: matcher), description: description)
}
}
}
@objc public var notTo: (NMBMatcher) -> Void { return toNot }
@objc public var notToWithDescription: (NMBMatcher, String) -> Void { return toNotWithDescription }
@objc public var toEventually: (NMBMatcher) -> Void {
return { matcher in
if let pred = matcher as? NMBPredicate {
self.expectValue.toEventually(
from(objcPredicate: pred),
timeout: self._timeout,
description: nil
)
} else {
self.expectValue.toEventually(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: nil
)
}
}
}
@objc public var toEventuallyWithDescription: (NMBMatcher, String) -> Void {
return { matcher, description in
if let pred = matcher as? NMBPredicate {
self.expectValue.toEventually(
from(objcPredicate: pred),
timeout: self._timeout,
description: description
)
} else {
self.expectValue.toEventually(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: description
)
}
}
}
@objc public var toEventuallyNot: (NMBMatcher) -> Void {
return { matcher in
if let pred = matcher as? NMBPredicate {
self.expectValue.toEventuallyNot(
from(objcPredicate: pred),
timeout: self._timeout,
description: nil
)
} else {
self.expectValue.toEventuallyNot(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: nil
)
}
}
}
@objc public var toEventuallyNotWithDescription: (NMBMatcher, String) -> Void {
return { matcher, description in
if let pred = matcher as? NMBPredicate {
self.expectValue.toEventuallyNot(
from(objcPredicate: pred),
timeout: self._timeout,
description: description
)
} else {
self.expectValue.toEventuallyNot(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: description
)
}
}
}
@objc public var toNotEventually: (NMBMatcher) -> Void {
return toEventuallyNot
}
@objc public var toNotEventuallyWithDescription: (NMBMatcher, String) -> Void {
return toEventuallyNotWithDescription
}
@objc public class func failWithMessage(_ message: String, file: FileString, line: UInt) {
fail(message, location: SourceLocation(file: file, line: line))
}
}
#endif
| 80c33e055b1a48aaea6f6bf219641ce8 | 33.6875 | 109 | 0.566216 | false | false | false | false |
yramanchuk/gitTest | refs/heads/master | SmartFeed/DB/DataModels/XML/Atom/SFArticleAtom.swift | mit | 1 | //
// SFArticleAtom.swift
// SmartFeed
//
// Created by Yury Ramanchuk on 3/30/16.
// Copyright © 2016 Yury Ramanchuk. All rights reserved.
//
import UIKit
class SFArticleAtom: SFArticle {
var link:[NSDictionary] = [NSDictionary]()
override var linkURL: String? {
get {
for val in link {
let relVal: String = val.objectForKey("_rel") as! String
if relVal == "alternate" {
return val.objectForKey("_href") as? String!;
}
}
return ""
}
set {}
}
// override func propertyConverters() -> [(String?, ((Any?)->())?, (() -> Any?)? )] {
// return [
// (
// "link", {
// let arr: Array<NSDictionary> = ($0 as? Array<NSDictionary>)!
// for val in arr {
// let relVal: String = val.objectForKey("_rel") as! String
// if relVal == "alternate" {
// self.link = val.objectForKey("_href") as? String;
// }
// }
// }, {
// return self.link
// }
// )
// ]
// }
}
| b9e631212dcd2742f9d2cb6f38f5e5d3 | 26.891304 | 88 | 0.4053 | false | false | false | false |
jhurray/Beginning-iOS-in-Swift-Workshop | refs/heads/master | Beginning iOS in Swift/PostComposeViewController.swift | mit | 1 | //
// PostComposeViewController.swift
// Beginning iOS in Swift
//
// Created by Jeff Hurray on 10/26/15.
// Copyright © 2015 jhurray. All rights reserved.
//
import Parse
import UIKit
class PostComposeViewController: UIViewController {
// UI Elements
let titleTextField = UITextField()
let messageTextField = UITextField()
// MARK: Apple's API functions
// This function is called by the ViewController after the view loads.
// This is where you should set up any UI elements
override func viewDidLoad() {
super.viewDidLoad()
// 1) Set title and background color for the view of the viewController
// 2) Call all the setup functions you implemented
// 3) Add your UI Elements to the view
}
// MARK: Helper functions
private func setupNameTextView() {
// 1) Set the delegate for the textfield
// 2) Set the placeholder for the text field
// 3) Set the backgroundColor for the text field
// 4) Set the frame for the text field
}
private func setupMessageTextField() {
// Setup using the same steps as above
}
private func setupNavigationBar() {
// 1) Create cancel and post buttons (UIBarButtonItem)
// let composeBarButton = ...
// 2) Add buttons to navigationItem
// self.navigationItem.leftBarButtonItem = ...
}
// This is a check to see if our post is valid
// We want the body and title to have at least 1 character and for the body to be no longer than 140 chars
private func inputForPostIsValid() -> Bool {
return self.messageTextField.text?.characters.count > 0
&& self.titleTextField.text?.characters.count > 0
&& self.messageTextField.text?.characters.count <= 140
}
internal func createPost() {
// This is a check to see if our post is valid
// the 'guard' statement means make sure that this is true, and if its not do something that raises an error or exits the function
guard self.inputForPostIsValid() else {
print("Invalid input!!!! Please try again")
return
}
// 1) Create new Post PFObject
// let post = PFObject(...)
// 2) Set fields for object
// 'Body' and 'Title'
// 3) Make Parse request to save the post and deal with the success or faliure of the save request
// ~~> if succeess: dismiss the view controller | if faliure : print the error
}
internal func cancel() {
// 1) Dismiss the view controller when cancel is pressed
// self.navigationController?.dismissViewControllerAnimated(...)
}
// MARK: UITextFieldDelegate functions
func textFieldShouldReturn(textField: UITextField) -> Bool {
// dismisses keyboard when return is hit
textField.resignFirstResponder()
return true
}
}
| 3bdc593cd9cf6fb10d766e5885a370f6 | 22.970803 | 138 | 0.572168 | false | false | false | false |
chatwyn/WBStatusBarHUD | refs/heads/master | Demo/Demo/WBStatusBarHUD/WBStatusBarHUD.swift | mit | 2 | //
// WBStatusBarHUD.swift
// WBStatusBarHUD
//
// Created by caowenbo on 16/1/28.
// Copyright © 2016年 曹文博. All rights reserved.
//
import UIKit
/// window背景
private var window:UIWindow?
/// 渐变色layer
private var gradientLayer = CAGradientLayer.init()
/// 字迹动画的时间
private let textAnimationTime:NSTimeInterval = 2
/// 字迹图层
private let pathLayer = CAShapeLayer.init()
/// 背景颜色
private var windowBgColor = UIColor.blackColor()
/// window弹出时间
private let windowTime:NSTimeInterval = 0.25
// 定时器
private var timer:NSTimer?
public class WBStatusBarHUD {
/**
在statusBar显示一段提示
- parameter message: 提示的文字
- parameter image: 文字前边的小图
*/
public class func show(message:String,image:UIImage?=nil) {
// 显示window
showWindow()
// 添加渐变色layer以及动画
addGradientLayer()
// 添加文字动画
addPathLayer(message)
//添加gradientLayer的遮罩
gradientLayer.mask = pathLayer
if let image = image {
let imageView = UIImageView.init(image: image)
imageView.frame = CGRect(x: CGRectGetMinX(pathLayer.frame) - 5 - imageView.image!.size.width, y: 0, width: imageView.image!.size.width, height: imageView.image!.size.height)
imageView.center.y = window!.center.y
window?.addSubview(imageView)
}
}
/**
隐藏
*/
public class func hide() {
timer?.invalidate()
timer = nil
if window != nil {
UIView.animateWithDuration(windowTime, animations: { () -> Void in
window?.center.y -= 20
}, completion: { (bool:Bool) -> Void in
window = nil
pathLayer.removeAllAnimations()
gradientLayer.removeAllAnimations()
})
}
}
/**
showErrorWithText
- parameter msg: default is download fail
*/
public class func showError(msg:String?=nil) {
let image = UIImage.init(named:"WBStatusBarHUD.bundle/error")
show((msg ?? "download fail"),image: image)
}
/**
showLoadingWithText
- parameter msg: default is loading……
*/
public class func showLoading(msg:String?=nil) {
show(msg ?? "loading……", image: nil)
timer?.invalidate()
let activityIndicatorView = UIActivityIndicatorView.init(activityIndicatorStyle: .White)
activityIndicatorView.startAnimating()
activityIndicatorView.frame = CGRect(x: CGRectGetMinX(pathLayer.frame) - 5 - activityIndicatorView.frame.size.width, y: 0, width: activityIndicatorView.frame.size.width, height: activityIndicatorView.frame.size.height)
window?.addSubview(activityIndicatorView)
}
/**
showSuccessWithText
- parameter msg: default is download complete
*/
public class func showSuccess(msg:String?=nil) {
let image = UIImage.init(named:"WBStatusBarHUD.bundle/success")
show(msg ?? "download successful", image: image)
}
/**
setWindowBackGroundColor
- parameter color: default is black color
*/
public class func setWindow(color:UIColor) {
windowBgColor = color
window?.backgroundColor = color
}
// MARK: - private method
/**
显示窗口
*/
private class func showWindow() {
timer?.invalidate()
timer = nil
window = UIWindow.init()
pathLayer.removeAllAnimations()
window!.windowLevel = UIWindowLevelAlert
window!.backgroundColor = windowBgColor
window!.frame = CGRectMake(0, -20,UIScreen.mainScreen().bounds.size.width, 20)
window!.hidden = false
UIView.animateWithDuration(windowTime) { () -> Void in
window!.center.y += 20
}
//这样写是不对的 不知为何 OC中没事
// timer = NSTimer.scheduledTimerWithTimeInterval(textAnimationTime, target:self, selector: "hide", userInfo: nil, repeats: false)
timer = NSTimer.scheduledTimerWithTimeInterval(textAnimationTime + 1, target:window!, selector: "hide", userInfo: nil, repeats: false)
}
/**
添加渐变色的layer 和动画
*/
private class func addGradientLayer() {
// 渐变色的颜色数
let count = 10
var colors:[CGColorRef] = []
for var i = 0; i < count; i++ {
let color = UIColor.init(red: CGFloat(arc4random() % 256) / 255, green: CGFloat(arc4random() % 256) / 255, blue: CGFloat(arc4random() % 256) / 255, alpha: 1.0)
colors.append(color.CGColor)
}
// 渐变色的方向
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
gradientLayer.colors = colors
gradientLayer.frame = window!.bounds
gradientLayer.type = kCAGradientLayerAxial
window!.layer.addSublayer(gradientLayer)
// 渐变色的动画
let animation = CABasicAnimation.init(keyPath: "colors")
animation.duration = 0.5
animation.repeatCount = MAXFLOAT
var toColors:[CGColorRef] = []
for var i = 0; i < count; i++ {
let color = UIColor.init(red: CGFloat(arc4random() % 256) / 255, green: CGFloat(arc4random() % 256) / 255, blue: CGFloat(arc4random() % 256) / 255, alpha: 1.0)
toColors.append(color.CGColor)
}
animation.autoreverses = true
animation.toValue = toColors
gradientLayer.addAnimation(animation, forKey: "gradientLayer")
}
/**
添加笔迹的动画
- parameter message: 显示的文字
*/
private class func addPathLayer(message:String) {
let textPath = bezierPathFrom(message)
pathLayer.bounds = CGPathGetBoundingBox(textPath.CGPath)
pathLayer.position = window!.center
pathLayer.geometryFlipped = true
pathLayer.path = textPath.CGPath
pathLayer.fillColor = nil
pathLayer.lineWidth = 1
pathLayer.strokeColor = UIColor.whiteColor().CGColor
// 笔迹的动画
let textAnimation = CABasicAnimation.init(keyPath: "strokeEnd")
textAnimation.duration = textAnimationTime
textAnimation.fromValue = 0
textAnimation.toValue = 1
textAnimation.delegate = window
pathLayer.addAnimation(textAnimation, forKey: "strokeEnd")
}
/**
将字符串转变成贝塞尔曲线
*/
class func bezierPathFrom(string:String) -> UIBezierPath{
let paths = CGPathCreateMutable()
let fontName = __CFStringMakeConstantString("SnellRoundhand")
let fontRef:AnyObject = CTFontCreateWithName(fontName, 18, nil)
let attrString = NSAttributedString(string: string, attributes: [kCTFontAttributeName as String : fontRef])
let line = CTLineCreateWithAttributedString(attrString as CFAttributedString)
let runA = CTLineGetGlyphRuns(line)
for (var runIndex = 0; runIndex < CFArrayGetCount(runA); runIndex++){
let run = CFArrayGetValueAtIndex(runA, runIndex);
let runb = unsafeBitCast(run, CTRun.self)
let CTFontName = unsafeBitCast(kCTFontAttributeName, UnsafePointer<Void>.self)
let runFontC = CFDictionaryGetValue(CTRunGetAttributes(runb),CTFontName)
let runFontS = unsafeBitCast(runFontC, CTFont.self)
let width = UIScreen.mainScreen().bounds.width
var temp = 0
var offset:CGFloat = 0.0
for(var i = 0; i < CTRunGetGlyphCount(runb); i++){
let range = CFRangeMake(i, 1)
let glyph:UnsafeMutablePointer<CGGlyph> = UnsafeMutablePointer<CGGlyph>.alloc(1)
glyph.initialize(0)
let position:UnsafeMutablePointer<CGPoint> = UnsafeMutablePointer<CGPoint>.alloc(1)
position.initialize(CGPointZero)
CTRunGetGlyphs(runb, range, glyph)
CTRunGetPositions(runb, range, position);
let temp3 = CGFloat(position.memory.x)
let temp2 = (Int) (temp3 / width)
let temp1 = 0
if(temp2 > temp1){
temp = temp2
offset = position.memory.x - (CGFloat(temp) * width)
}
let path = CTFontCreatePathForGlyph(runFontS,glyph.memory,nil)
let x = position.memory.x - (CGFloat(temp) * width) - offset
let y = position.memory.y - (CGFloat(temp) * 80)
var transform = CGAffineTransformMakeTranslation(x, y)
CGPathAddPath(paths, &transform, path)
glyph.destroy()
glyph.dealloc(1)
position.destroy()
position.dealloc(1)
}
}
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointZero)
bezierPath.appendPath(UIBezierPath(CGPath: paths))
return bezierPath
}
}
extension UIWindow{
func hide() {
WBStatusBarHUD.hide()
}
} | bb63b5ae0ebf1e2e3578a0ca06e2382c | 31.037415 | 226 | 0.580059 | false | false | false | false |
suragch/Chimee-iOS | refs/heads/master | Chimee/UIMongolTableView.swift | mit | 1 |
import UIKit
@IBDesignable class UIMongolTableView: UIView {
// MARK:- Unique to TableView
// ********* Unique to TableView *********
fileprivate var view = UITableView()
fileprivate let rotationView = UIView()
fileprivate var userInteractionEnabledForSubviews = true
// read only refernce to the underlying tableview
var tableView: UITableView {
get {
return view
}
}
var tableFooterView: UIView? {
get {
return view.tableFooterView
}
set {
view.tableFooterView = newValue
}
}
func setup() {
// do any setup necessary
self.addSubview(rotationView)
rotationView.addSubview(view)
view.backgroundColor = self.backgroundColor
view.layoutMargins = UIEdgeInsets.zero
view.separatorInset = UIEdgeInsets.zero
}
// FIXME: @IBOutlet still can't be set in IB
@IBOutlet weak var delegate: UITableViewDelegate? {
get {
return view.delegate
}
set {
view.delegate = newValue
}
}
// FIXME: @IBOutlet still can't be set in IB
@IBOutlet weak var dataSource: UITableViewDataSource? {
get {
return view.dataSource
}
set {
view.dataSource = newValue
}
}
@IBInspectable var scrollEnabled: Bool {
get {
return view.isScrollEnabled
}
set {
view.isScrollEnabled = newValue
}
}
func scrollToRowAtIndexPath(_ indexPath: IndexPath, atScrollPosition: UITableViewScrollPosition, animated: Bool) {
view.scrollToRow(at: indexPath, at: atScrollPosition, animated: animated)
}
func registerClass(_ cellClass: AnyClass?, forCellReuseIdentifier identifier: String) {
view.register(cellClass, forCellReuseIdentifier: identifier)
}
func dequeueReusableCellWithIdentifier(_ identifier: String) -> UITableViewCell? {
return view.dequeueReusableCell(withIdentifier: identifier)
}
func reloadData() {
view.reloadData()
}
func insertRowsAtIndexPaths(_ indexPaths: [IndexPath], withRowAnimation animation: UITableViewRowAnimation) {
view.insertRows(at: indexPaths, with: animation)
}
func deleteRowsAtIndexPaths(_ indexPaths: [IndexPath], withRowAnimation animation: UITableViewRowAnimation) {
view.deleteRows(at: indexPaths, with: animation)
}
// MARK:- General code for Mongol views
// *******************************************
// ****** General code for Mongol views ******
// *******************************************
// This method gets called if you create the view in the Interface Builder
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// This method gets called if you create the view in code
override init(frame: CGRect){
super.init(frame: frame)
self.setup()
}
override func awakeFromNib() {
super.awakeFromNib()
self.setup()
}
override func layoutSubviews() {
super.layoutSubviews()
rotationView.transform = CGAffineTransform.identity
rotationView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: self.bounds.height, height: self.bounds.width))
rotationView.transform = translateRotateFlip()
view.frame = rotationView.bounds
}
func translateRotateFlip() -> CGAffineTransform {
var transform = CGAffineTransform.identity
// translate to new center
transform = transform.translatedBy(x: (self.bounds.width / 2)-(self.bounds.height / 2), y: (self.bounds.height / 2)-(self.bounds.width / 2))
// rotate counterclockwise around center
transform = transform.rotated(by: CGFloat(-M_PI_2))
// flip vertically
transform = transform.scaledBy(x: -1, y: 1)
return transform
}
}
| dee9eb6e56c717535e39ba6e88bbb91d | 27.241611 | 148 | 0.584601 | false | false | false | false |
arinjoy/Landmark-Remark | refs/heads/master | LandmarkRemark/LoginSignUpViewModel.swift | mit | 1 | //
// LoginSignUpViewModel.swift
// LandmarkRemark
//
// Created by Arinjoy Biswas on 6/06/2016.
// Copyright © 2016 Arinjoy Biswas. All rights reserved.
//
import Parse
/// The protocol for LoginSignupViewModel delegate, implemented by the LoginSignup view-controller
public protocol LoginSignUpViewModelDelegate: class {
func showInvalidUserName()
func showInvalidPassword()
func loginSuccessWithUser(user: PFUser)
func signupSuccess()
func operationFailureWithErrorMessage(title: String, message: String)
}
/// The view-model for the LoginSignup view-controller
public class LoginSignUpViewModel {
// public properties of the view-model exposed to its view-controller
public var userName: String = ""
public var password: String = ""
// The delgate of the view-model to call back / pass back information to the view-controller
public weak var delegate: LoginSignUpViewModelDelegate?
// reference to the Authentication service
private let authenticationService: UserAuthenticationService
// new initializer
public init(delegate: LoginSignUpViewModelDelegate) {
self.delegate = delegate
authenticationService = UserAuthenticationService()
}
//------------------------------------------------------------------------------------------------
// MARK: - Core methods of the view-model, called by the view-controller based on the user actions
//------------------------------------------------------------------------------------------------
/**
The login mehtod
*/
public func login() {
// checking for valid username and password string, and inform the view-controller
if !isValidUserName() {
delegate?.showInvalidUserName()
}
else if !isValidPassword() {
delegate?.showInvalidPassword()
}
else {
// call to service layer
// passing weak deleagte to break te retain cycle if any (for safety)
// https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html
authenticationService.loginUser(userName, password: password, completionHandler: { [weak delegate = self.delegate!] (user, error) in
if user != nil {
// communicate with the view-controller and send the new logged-in user object
delegate?.loginSuccessWithUser(user!)
} else {
// determine the error message and came from the backend side and send a user-friendly message back to the UI side
var title = "Error Occurred"
var message = "Some unknown error occurred. Please try again."
if error != nil {
if error?.code == 100 {
title = "No Internet Connection"
message = "Internet connection appears to be offine. Could not login."
}
if error?.code == 101 {
title = "Login Failed"
message = "You have entered invalid credentials. Please try again."
}
if error?.code == 401 {
title = "Login Failed"
message = "Could not succeed because access was denied."
}
}
// pass back the error information
delegate?.operationFailureWithErrorMessage(title, message: message)
}
})
}
}
/**
The signup method
*/
public func signup() {
// checking for valid username and password string, and inform the view-controller
if !isValidUserName() {
delegate?.showInvalidUserName()
}
else if !isValidPassword() {
delegate?.showInvalidPassword()
}
else {
// call the service layer
authenticationService.signupUser(userName, password: password, completionHandler: { [weak delegate = self.delegate!] (success, error) in
if error == nil {
delegate?.signupSuccess()
} else {
// determine the error message and came from the backend side and send a user-friendly message back to the UI side
var title = "Error Occurred"
var message = "Some unknown error occurred. Please try again."
if error?.code == 100 {
title = "No Internet Connection"
message = "Internet connection appears to be offine. Could not signup."
}
if error?.code == 202 || error?.code == 203 {
title = "Signup Failed"
message = "The username you have chosen has already been taken up by another user. Please choose a different one. "
}
// pass back the error information
delegate?.operationFailureWithErrorMessage(title, message: message)
}
})
}
}
//------------------------------------------------------------------------------------------------
// MARK: - private helper methods
//------------------------------------------------------------------------------------------------
/**
To check for an acceptable username
*/
private func isValidUserName() -> Bool {
do {
let regex = try NSRegularExpression(pattern: "^[A-Za-z]+([A-Za-z0-9-_.]){2,15}$", options: .CaseInsensitive)
return regex.firstMatchInString(userName, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, userName.characters.count)) != nil
} catch {
return false
}
}
/**
To check for an acceptable password
*/
private func isValidPassword() -> Bool {
do {
let regex = try NSRegularExpression(pattern: "^[A-Za-z0-9.!#$%&'*+/=?^_~-]{3,25}$", options: .CaseInsensitive)
return regex.firstMatchInString(password, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, password.characters.count)) != nil
} catch {
return false
}
}
}
| 1f81ddd4b45bbef155b79d69ed3970da | 37.916168 | 151 | 0.534852 | false | false | false | false |
PGLongo/SuperRecord | refs/heads/master | SuperRecord/NSManagedObjectExtension.swift | mit | 2 | //
// NSManagedObjectExtension.swift
//
// SuperRecord - A small set of utilities to make working with CoreData a bit easier.
// http://mike.kz/
//
// Created by Michael Armstrong on 12/10/2014.
// Copyright (c) 2014 SuperArmstrong.UK. All rights reserved.
//
// RESPONSIBILITY : Several helpers for NSManagedObject to make common operations simpler.
import CoreData
public extension NSManagedObject {
//MARK: Entity update
/**
Update all entity matching the predicate
- parameter context: the NSManagedObjectContext. Default value is SuperCoreDataStack.defaultStack.managedObjectContext
- parameter propertiesToUpdate:
- parameter predicate: the predicate the entity should match
- parameter resultType: the default value is UpdatedObjectsCountResultType (rows number)
- parameter error:
- returns: AnyObject? depends on resultType
*/
class func updateAll (context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, propertiesToUpdate: [String : AnyObject], predicate:NSPredicate?, resultType: NSBatchUpdateRequestResultType = .UpdatedObjectsCountResultType) throws -> AnyObject{
let error: NSError! = NSError(domain: "Migrator", code: 0, userInfo: nil)
let entityName : String = NSStringFromClass(self)
let request = NSBatchUpdateRequest(entityName: entityName);
request.propertiesToUpdate = propertiesToUpdate
request.resultType = resultType
request.predicate = predicate
let result = try! context.executeRequest(request) as! NSBatchUpdateResult;
if let value = result.result {
return value
}
throw error
}
//MARK: Entity deletion
/**
Delete all entity
- parameter context: the NSManagedObjectContext. Default value is SuperCoreDataStack.defaultStack.managedObjectContext
*/
class func deleteAll(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!) -> Void {
deleteAll(nil, context: context)
}
/**
Delete all entity matching the input predicate
- parameter predicate:
- parameter context: the NSManagedObjectContext. Default value is SuperCoreDataStack.defaultStack.managedObjectContext
*/
class func deleteAll(predicate: NSPredicate!, context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!) -> Void {
let results = findAllWithPredicate(predicate, includesPropertyValues: false, context: context, completionHandler: nil)
for result in results {
context.deleteObject(result as! NSManagedObject)
}
}
//MARK: Entity search
/**
Search for all entity with the specify value or create a new Entity
- parameter predicate:
- parameter includesPropertyValues:
- parameter context: the NSManagedObjectContext. Default value is SuperCoreDataStack.defaultStack.managedObjectContext
- returns: NSArray of NSManagedObject.
*/
class func findAllWithPredicate(predicate: NSPredicate!, includesPropertyValues: Bool = true, context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, sortDescriptors: [NSSortDescriptor]? = nil, completionHandler handler: ((NSError!) -> Void)! = nil) -> NSArray {
let entityName : NSString = NSStringFromClass(self)
let entityDescription = NSEntityDescription.entityForName(entityName as String, inManagedObjectContext: context)
let fetchRequest = NSFetchRequest(entityName: entityName as String)
fetchRequest.includesPropertyValues = includesPropertyValues
fetchRequest.predicate = predicate
fetchRequest.entity = entityDescription
fetchRequest.sortDescriptors = sortDescriptors
var results = NSArray()
let error : NSError? = nil
context.performBlockAndWait({ () -> Void in
results = (try! context.executeFetchRequest(fetchRequest)) as! [NSManagedObject]
})
handler?(error);
return results
}
/**
Search for all entity with the specify value or create a new Entity
- parameter context: the NSManagedObjectContext. Default value is SuperCoreDataStack.defaultStack.managedObjectContext
- returns: NSArray of NSManagedObject.
*/
class func findAll(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, sortDescriptors: [NSSortDescriptor]? = nil) -> NSArray {
return findAllWithPredicate(nil, context: context, sortDescriptors:sortDescriptors)
}
/**
Search for all entity with the specify attribute and value
- parameter attribute: name of the attribute of the NSManagedObject
- parameter value: value of the attribute
- parameter context: the NSManagedObjectContext. Default value is SuperCoreDataStack.defaultStack.managedObjectContext
- returns: NSArray of NSManagedObject.
*/
class func findAllWithAttribute(attribute: String!, value: AnyObject, context: NSManagedObjectContext, sortDescriptors: [NSSortDescriptor]? = nil) -> NSArray {
let predicate = NSPredicate.predicateBuilder(attribute, value: value, predicateOperator: .Equal)
return findAllWithPredicate(predicate, context: context, sortDescriptors:sortDescriptors)
}
//MARK: Entity creation
/**
Search for the entity with the specify value or create a new Entity
:predicate: attribute predicate
- parameter context: the NSManagedObjectContext. Default value is SuperCoreDataStack.defaultStack.managedObjectContext
- returns: NSManagedObject.
*/
class func findFirstOrCreateWithPredicate(predicate: NSPredicate!, context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, handler: ((NSError!) -> Void)! = nil) -> NSManagedObject {
let entityName : NSString = NSStringFromClass(self)
let entityDescription = NSEntityDescription.entityForName(entityName as String, inManagedObjectContext: context)
let fetchRequest = NSFetchRequest(entityName: entityName as String)
fetchRequest.fetchLimit = 1
fetchRequest.predicate = predicate
fetchRequest.entity = entityDescription
var fetchedObjects = NSArray()
let error : NSError? = nil
context.performBlockAndWait({ () -> Void in
let results = (try! context.executeFetchRequest(fetchRequest)) as NSArray
fetchedObjects = results
})
if let firstObject = fetchedObjects.firstObject as? NSManagedObject {
handler?(error);
return firstObject
}
let obj = NSManagedObject(entity: entityDescription!, insertIntoManagedObjectContext: context) as NSManagedObject
handler?(error);
return obj
}
/**
Create a new Entity
- parameter context: NSManagedObjectContext
- returns: NSManagedObject.
*/
class func createNewEntity(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!) -> NSManagedObject {
let entityName : NSString = NSStringFromClass(self)
let entityDescription = NSEntityDescription.entityForName(entityName as String, inManagedObjectContext: context)
let obj = NSManagedObject(entity: entityDescription!, insertIntoManagedObjectContext: context)
return obj as NSManagedObject
}
/**
Search for the entity with the specify value or create a new Entity
- parameter attribute: name of the attribute to find
- parameter value: of the attribute to find
- parameter context: the NSManagedObjectContext. Default value is SuperCoreDataStack.defaultStack.managedObjectContext
- returns: NSManagedObject.
*/
class func findFirstOrCreateWithAttribute(attribute: String!, value: AnyObject!, context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, handler: ((NSError!) -> Void)! = nil) -> NSManagedObject {
let predicate = NSPredicate.predicateBuilder(attribute, value: value, predicateOperator: .Equal)
return findFirstOrCreateWithPredicate(predicate, context: context, handler: handler)
}
//MARK: Entity operations
/**
Count all the entity
- parameter context: the NSManagedObjectContext. Default value is SuperCoreDataStack.defaultStack.managedObjectContext
- parameter error:
- returns: Int of total result set count.
*/
class func count(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, error: NSErrorPointer) -> Int {
return count(context, predicate: nil, error: error);
}
/**
Count all the entity matching the input predicate
- parameter context: the NSManagedObjectContext. Default value is SuperCoreDataStack.defaultStack.managedObjectContext
- parameter predicate:
- parameter error:
- returns: Int of total result set count.
*/
class func count(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, predicate : NSPredicate?, error: NSErrorPointer) -> Int {
let entityName : NSString = NSStringFromClass(self)
let fetchRequest = NSFetchRequest(entityName: entityName as String);
fetchRequest.includesPropertyValues = false
fetchRequest.includesSubentities = false
fetchRequest.predicate = predicate
fetchRequest.propertiesToFetch = [];
return context.countForFetchRequest(fetchRequest, error: error)
}
class func function(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, function: String, fieldName: [String], predicate : NSPredicate?, groupByFieldName: [String], handler: ((NSError!) -> Void)) -> [AnyObject] {
let error : NSError? = nil
var expressionsDescription = [AnyObject]();
for field in fieldName{
let expression = NSExpression(forKeyPath: field);
let expressionDescription = NSExpressionDescription();
expressionDescription.expression = NSExpression(forFunction: function, arguments: [expression])
expressionDescription.expressionResultType = NSAttributeType.DoubleAttributeType;
expressionDescription.name = field
expressionsDescription.append(expressionDescription);
}
let entityName : NSString = NSStringFromClass(self)
let fetchRequest = NSFetchRequest(entityName: entityName as String);
if(groupByFieldName.count > 0 ){
fetchRequest.propertiesToGroupBy = groupByFieldName
for groupBy in groupByFieldName {
expressionsDescription.append(groupBy)
}
}
fetchRequest.propertiesToFetch = expressionsDescription
fetchRequest.resultType = NSFetchRequestResultType.DictionaryResultType
fetchRequest.predicate = predicate
var results = [AnyObject]()
context.performBlockAndWait({
do {
try results = context.executeFetchRequest(fetchRequest) as [AnyObject]!;
} catch {
}
});
handler(error);
return results
}
class func function(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, function: String, fieldName: [String], predicate : NSPredicate?, handler: ((NSError!) -> Void)) -> [Double] {
let results = self.function(context, function: function , fieldName: fieldName, predicate: predicate, groupByFieldName: [], handler: handler)
var resultValue = [Double]();
var tempResult = [Double]()
for result in results{
for field in fieldName{
let value = result.valueForKey(field) as! Double
tempResult.append(value)
}
}
resultValue = tempResult
return resultValue;
}
class func sum(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, fieldName: [String], predicate : NSPredicate? = nil, handler: ((NSError!) -> Void)! = nil) -> [Double] {
return function(context, function: "sum:", fieldName: fieldName, predicate: predicate, handler: handler);
}
class func sum(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, fieldName: String, predicate : NSPredicate? = nil, handler: ((NSError!) -> Void)! = nil) -> Double! {
var results = sum(context, fieldName: [fieldName], predicate: predicate, handler: handler)
return results.isEmpty ? 0 : results[0];
}
class func sum(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, fieldName: [String], predicate : NSPredicate?, groupByField:[String], handler: ((NSError!) -> Void))-> [AnyObject] {
return function(context, function: "sum:", fieldName: fieldName, predicate: predicate, groupByFieldName: groupByField, handler: handler)
}
class func max(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, fieldName: [String], predicate : NSPredicate?, handler: ((NSError!) -> Void)) -> [Double] {
return function(context, function: "max:", fieldName: fieldName, predicate: predicate, handler: handler);
}
class func max(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, fieldName: String, predicate : NSPredicate? = nil, handler: ((NSError!) -> Void)! = nil) -> Double! {
var results = max(context, fieldName: [fieldName], predicate: predicate, handler: handler)
return results.isEmpty ? 0 : results[0];
}
class func max(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, fieldName: [String], predicate : NSPredicate?, groupByField:[String], handler: ((NSError!) -> Void))-> [AnyObject] {
return function(context, function: "max:", fieldName: fieldName, predicate: predicate, groupByFieldName: groupByField, handler: handler)
}
class func min(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, fieldName: [String], predicate : NSPredicate?, handler: ((NSError!) -> Void)) -> [Double] {
return function(context, function: "min:", fieldName: fieldName, predicate: predicate, handler: handler);
}
class func min(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, fieldName: String, predicate : NSPredicate? = nil, handler: ((NSError!) -> Void)! = nil) -> Double! {
var results = min(context, fieldName: [fieldName], predicate: predicate, handler: handler)
return results.isEmpty ? 0 : results[0];
}
class func min(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, fieldName: [String], predicate : NSPredicate?, groupByField:[String], handler: ((NSError!) -> Void))-> [AnyObject] {
return function(context, function: "min:", fieldName: fieldName, predicate: predicate, groupByFieldName: groupByField, handler: handler)
}
class func avg(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, fieldName: [String], predicate : NSPredicate?, handler: ((NSError!) -> Void)) -> [Double] {
return function(context, function: "average:", fieldName: fieldName, predicate: predicate, handler: handler);
}
class func avg(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, fieldName: String, predicate : NSPredicate? = nil, handler: ((NSError!) -> Void)! = nil) -> Double! {
var results = avg(context, fieldName: [fieldName], predicate: predicate, handler: handler)
return results.isEmpty ? 0 : results[0];
}
class func avg(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, fieldName: [String], predicate : NSPredicate?, groupByField:[String], handler: ((NSError!) -> Void))-> [AnyObject] {
return function(context, function: "average:", fieldName: fieldName, predicate: predicate, groupByFieldName: groupByField, handler: handler)
}
} | ac0c9c0830a26fe2d9d51a40ec0a7b0b | 46.725434 | 299 | 0.703731 | false | false | false | false |
LoopKit/LoopKit | refs/heads/dev | LoopKit/InsulinKit/ManualBolusRecommendation.swift | mit | 1 | //
// ManualBolusRecommendation.swift
// LoopKit
//
// Created by Pete Schwamb on 1/2/17.
// Copyright © 2017 LoopKit Authors. All rights reserved.
//
import Foundation
import HealthKit
public enum BolusRecommendationNotice {
case glucoseBelowSuspendThreshold(minGlucose: GlucoseValue)
case currentGlucoseBelowTarget(glucose: GlucoseValue)
case predictedGlucoseBelowTarget(minGlucose: GlucoseValue)
case predictedGlucoseInRange
case allGlucoseBelowTarget(minGlucose: GlucoseValue)
}
extension BolusRecommendationNotice: Codable {
public init(from decoder: Decoder) throws {
if let string = try? decoder.singleValueContainer().decode(String.self) {
switch string {
case CodableKeys.predictedGlucoseInRange.rawValue:
self = .predictedGlucoseInRange
default:
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "invalid enumeration"))
}
} else {
let container = try decoder.container(keyedBy: CodableKeys.self)
if let glucoseBelowSuspendThreshold = try container.decodeIfPresent(GlucoseBelowSuspendThreshold.self, forKey: .glucoseBelowSuspendThreshold) {
self = .glucoseBelowSuspendThreshold(minGlucose: glucoseBelowSuspendThreshold.minGlucose)
} else if let currentGlucoseBelowTarget = try container.decodeIfPresent(CurrentGlucoseBelowTarget.self, forKey: .currentGlucoseBelowTarget) {
self = .currentGlucoseBelowTarget(glucose: currentGlucoseBelowTarget.glucose)
} else if let predictedGlucoseBelowTarget = try container.decodeIfPresent(PredictedGlucoseBelowTarget.self, forKey: .predictedGlucoseBelowTarget) {
self = .predictedGlucoseBelowTarget(minGlucose: predictedGlucoseBelowTarget.minGlucose)
} else if let allGlucoseBelowTarget = try container.decodeIfPresent(AllGlucoseBelowTarget.self, forKey: .allGlucoseBelowTarget) {
self = .allGlucoseBelowTarget(minGlucose: allGlucoseBelowTarget.minGlucose)
} else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "invalid enumeration"))
}
}
}
public func encode(to encoder: Encoder) throws {
switch self {
case .glucoseBelowSuspendThreshold(let minGlucose):
var container = encoder.container(keyedBy: CodableKeys.self)
try container.encode(GlucoseBelowSuspendThreshold(minGlucose: SimpleGlucoseValue(minGlucose)), forKey: .glucoseBelowSuspendThreshold)
case .currentGlucoseBelowTarget(let glucose):
var container = encoder.container(keyedBy: CodableKeys.self)
try container.encode(CurrentGlucoseBelowTarget(glucose: SimpleGlucoseValue(glucose)), forKey: .currentGlucoseBelowTarget)
case .predictedGlucoseBelowTarget(let minGlucose):
var container = encoder.container(keyedBy: CodableKeys.self)
try container.encode(PredictedGlucoseBelowTarget(minGlucose: SimpleGlucoseValue(minGlucose)), forKey: .predictedGlucoseBelowTarget)
case .predictedGlucoseInRange:
var container = encoder.singleValueContainer()
try container.encode(CodableKeys.predictedGlucoseInRange.rawValue)
case .allGlucoseBelowTarget(minGlucose: let minGlucose):
var container = encoder.container(keyedBy: CodableKeys.self)
try container.encode(AllGlucoseBelowTarget(minGlucose: SimpleGlucoseValue(minGlucose)), forKey: .allGlucoseBelowTarget)
}
}
private struct GlucoseBelowSuspendThreshold: Codable {
let minGlucose: SimpleGlucoseValue
}
private struct CurrentGlucoseBelowTarget: Codable {
let glucose: SimpleGlucoseValue
}
private struct PredictedGlucoseBelowTarget: Codable {
let minGlucose: SimpleGlucoseValue
}
private struct AllGlucoseBelowTarget: Codable {
let minGlucose: SimpleGlucoseValue
}
private enum CodableKeys: String, CodingKey {
case glucoseBelowSuspendThreshold
case currentGlucoseBelowTarget
case predictedGlucoseBelowTarget
case predictedGlucoseInRange
case allGlucoseBelowTarget
}
}
public struct ManualBolusRecommendation {
public let amount: Double
public let pendingInsulin: Double
public var notice: BolusRecommendationNotice?
public init(amount: Double, pendingInsulin: Double, notice: BolusRecommendationNotice? = nil) {
self.amount = amount
self.pendingInsulin = pendingInsulin
self.notice = notice
}
}
extension ManualBolusRecommendation: Codable {}
| 2a5a65370d8d53f76ec121a5a6d2b828 | 45.647059 | 159 | 0.729508 | false | false | false | false |
FengDeng/RXGitHub | refs/heads/master | Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift | apache-2.0 | 35 | //
// VirtualTimeConverterType.swift
// Rx
//
// Created by Krunoslav Zaher on 12/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Parametrization for virtual time used by `VirtualTimeScheduler`s.
*/
public protocol VirtualTimeConverterType {
/**
Virtual time unit used that represents ticks of virtual clock.
*/
typealias VirtualTimeUnit
/**
Virtual time unit used to represent differences of virtual times.
*/
typealias VirtualTimeIntervalUnit
/**
Converts virtual time to real time.
- parameter virtualTime: Virtual time to convert to `NSDate`.
- returns: `NSDate` corresponding to virtual time.
*/
func convertFromVirtualTime(virtualTime: VirtualTimeUnit) -> RxTime
/**
Converts real time to virtual time.
- parameter time: `NSDate` to convert to virtual time.
- returns: Virtual time corresponding to `NSDate`.
*/
func convertToVirtualTime(time: RxTime) -> VirtualTimeUnit
/**
Converts from virtual time interval to `NSTimeInterval`.
- parameter virtualTimeInterval: Virtual time interval to convert to `NSTimeInterval`.
- returns: `NSTimeInterval` corresponding to virtual time interval.
*/
func convertFromVirtualTimeInterval(virtualTimeInterval: VirtualTimeIntervalUnit) -> RxTimeInterval
/**
Converts from virtual time interval to `NSTimeInterval`.
- parameter timeInterval: `NSTimeInterval` to convert to virtual time interval.
- returns: Virtual time interval corresponding to time interval.
*/
func convertToVirtualTimeInterval(timeInterval: RxTimeInterval) -> VirtualTimeIntervalUnit
/**
Offsets virtual time by virtual time interval.
- parameter time: Virtual time.
- parameter offset: Virtual time interval.
- returns: Time corresponding to time offsetted by virtual time interval.
*/
func offsetVirtualTime(time time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit
/**
This is aditional abstraction because `NSDate` is unfortunately not comparable.
Extending `NSDate` with `Comparable` would be too risky because of possible collisions with other libraries.
*/
func compareVirtualTime(lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison
}
/**
Virtual time comparison result.
This is aditional abstraction because `NSDate` is unfortunately not comparable.
Extending `NSDate` with `Comparable` would be too risky because of possible collisions with other libraries.
*/
public enum VirtualTimeComparison {
/**
lhs < rhs.
*/
case LessThan
/**
lhs == rhs.
*/
case Equal
/**
lhs > rhs.
*/
case GreaterThan
}
extension VirtualTimeComparison {
/**
lhs < rhs.
*/
var lessThen: Bool {
if case .LessThan = self {
return true
}
return false
}
/**
lhs > rhs
*/
var greaterThan: Bool {
if case .GreaterThan = self {
return true
}
return false
}
/**
lhs == rhs
*/
var equal: Bool {
if case .Equal = self {
return true
}
return false
}
}
| 6f3e9db68b9e6c0333e36b7bb21803e4 | 24.913386 | 113 | 0.662109 | false | false | false | false |
castial/Quick-Start-iOS | refs/heads/master | Quick-Start-iOS/Controllers/Location/Protocol/EmptyPresenter.swift | mit | 1 | //
// EmptyPresenter.swift
// Quick-Start-iOS
//
// Created by work on 2016/12/10.
// Copyright © 2016年 hyyy. All rights reserved.
//
import UIKit
struct EmptyOptions {
let message: String
let messageFont: UIFont
let messageColor: UIColor
let backgroundColor: UIColor
init(message: String = "暂无数据", messageFont: UIFont = UIFont.systemFont(ofSize: 16), messageColor: UIColor = UIColor.black, backgroundColor: UIColor = UIColor.white) {
self.message = message
self.messageFont = messageFont
self.messageColor = messageColor
self.backgroundColor = backgroundColor
}
}
protocol EmptyPresenter {
func presentEmpty(emptyOptions: EmptyOptions)
}
extension EmptyPresenter where Self: UIView {
func presentEmpty(emptyOptions: EmptyOptions = EmptyOptions()) {
let emptyView = defaultEmptyView(emptyOptions: emptyOptions)
self.addSubview(emptyView)
}
}
extension EmptyPresenter where Self: UIViewController {
func presentEmpty(emptyOptions: EmptyOptions = EmptyOptions()) {
let emptyView = defaultEmptyView(emptyOptions: emptyOptions)
self.view.addSubview(emptyView)
}
}
extension EmptyPresenter {
// default empty view
fileprivate func defaultEmptyView(emptyOptions: EmptyOptions) -> UIView {
let emptyView = UIView (frame: CGRect (x: 0,
y: 0,
width: UIScreen.main.bounds.size.width,
height: UIScreen.main.bounds.size.height))
emptyView.backgroundColor = emptyOptions.backgroundColor
// add a message label
let messageLabel = UILabel()
messageLabel.text = emptyOptions.message
messageLabel.font = emptyOptions.messageFont
messageLabel.textColor = emptyOptions.messageColor
messageLabel.textAlignment = .center
messageLabel.sizeToFit()
messageLabel.center = emptyView.center
emptyView.addSubview(messageLabel)
return emptyView
}
}
| 44905fdce059992566e6fe41d1347514 | 31.569231 | 170 | 0.651393 | false | false | false | false |
lingoslinger/SwiftLibraries | refs/heads/master | SwiftLibraries/View Controllers/LibraryTableViewController.swift | mit | 1 | //
// LibraryTableViewController.swift
// SwiftLibraries
//
// Created by Allan Evans on 7/21/16.
// Copyright © 2016 - 2021 Allan Evans. All rights reserved. Seriously.
//
import UIKit
import Foundation
typealias SessionCompletionHandler = (_ data : Data?, _ response : URLResponse?, _ error : Error?) -> Void
class LibraryTableViewController: UITableViewController {
var libraryArray = [Library]()
var sectionDictionary = Dictionary<String, [Library]>()
var sectionTitles = [String]()
// MARK: - view lifecycle
override func viewDidLoad() {
super.viewDidLoad()
let libraryURLSession = LibraryURLSession();
let completionHander : SessionCompletionHandler = {(data : Data?, response : URLResponse?, error : Error?) -> Void in
if (error == nil) {
let decoder = JSONDecoder()
guard let libraryArray = try? decoder.decode([Library].self, from: data!) else {
fatalError("Unable to decode JSON library data")
}
self.libraryArray = libraryArray
DispatchQueue.main.async(execute: {
self.setupSectionsWithLibraryArray()
self.tableView.reloadData()
})
} else {
DispatchQueue.main.async {
self.showErrorDialogWithMessage(message: error?.localizedDescription ?? "Unknown network error")
}
}
}
libraryURLSession.sendRequest(completionHander)
}
// MARK: - UITableViewDataSource and UITableViewDelegate methods
override func numberOfSections(in tableView: UITableView) -> Int {
return sectionTitles.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionTitle = self.sectionTitles[section]
let sectionArray = self.sectionDictionary[sectionTitle]
return sectionArray?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LibraryTableViewCell")
let sectionTitle = self.sectionTitles[indexPath.section]
let sectionArray = self.sectionDictionary[sectionTitle]
let library = sectionArray?[indexPath.row]
cell?.textLabel?.text = library?.name
return cell!
}
override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return index
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionTitles[section]
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return self.sectionTitles
}
// MARK: - navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "LibraryDetailViewController" {
guard let indexPath = self.tableView.indexPathForSelectedRow else { return }
let detailViewController = segue.destination as! LibraryDetailViewController
let sectionTitle = self.sectionTitles[indexPath.section]
let sectionArray = self.sectionDictionary[sectionTitle]
detailViewController.detailLibrary = sectionArray?[indexPath.row]
}
}
// MARK: - private methods
func setupSectionsWithLibraryArray() {
for library in libraryArray {
let firstLetterOfName = String.init(library.name?.first ?? Character.init(""))
if (sectionDictionary[firstLetterOfName] == nil) {
let sectionArray = [Library]()
sectionDictionary[firstLetterOfName] = sectionArray
}
sectionDictionary[firstLetterOfName]?.append(library)
}
let unsortedLetters = self.sectionDictionary.keys
sectionTitles = unsortedLetters.sorted()
}
}
| 96375ef7270cb70fb848cdad8e067086 | 39.68 | 125 | 0.646755 | false | false | false | false |
jcbages/seneca | refs/heads/master | seneca/AboutWindow.swift | mit | 1 | import Cocoa
let APP_VERSION = "1.0.0"
let NAME_LABEL_TEXT = "seneca"
let CONTACT_EMAIL = "[email protected]"
let SUPPORT_MESSAGE = "Si tienes algúna duda, escríbenos a alguno de estos correos"
let SUPPORT_EMAIL = "[email protected]"
let REPOSITORY_MESSAGE = "Si nos quieres apoyar, entra a"
let REPOSITORY_LINK = "https://github.com/jcbages/seneca"
let MAIN_FONT = "Helvetica Neue Light"
class AboutWindow: NSWindowController {
/*
* The UI components related to this particular view, specified
* to handle them in this controller
*/
@IBOutlet weak var logoIcon: NSImageView!
@IBOutlet weak var nameLabel: NSTextField!
@IBOutlet weak var versionLabel: NSTextField!
@IBOutlet weak var contactEmailLabel: NSTextField!
@IBOutlet weak var emailLabel: NSTextField!
@IBOutlet weak var supportEmailLabel: NSTextField!
@IBOutlet weak var supportRepositoryLabel: NSTextField!
@IBOutlet weak var repositoryLabel: NSTextField!
override var windowNibName : String! {
return "AboutWindow"
}
override func windowDidLoad() {
super.windowDidLoad()
self.window?.center()
self.window?.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps: true)
// Handling the logo image
self.logoIcon.image = NSImage(named: "logo")
// Handling the project name label
self.nameLabel.font = NSFont(name: MAIN_FONT, size: 16)
// Handling the project version label
self.versionLabel.stringValue = "Versión \(APP_VERSION)"
self.versionLabel.font = NSFont(name: MAIN_FONT, size: 10)
self.contactEmailLabel.stringValue = SUPPORT_MESSAGE
self.contactEmailLabel.font = NSFont(name: MAIN_FONT, size: 12)
self.emailLabel.stringValue = CONTACT_EMAIL
self.emailLabel.font = NSFont(name: MAIN_FONT, size: 12)
self.supportEmailLabel.stringValue = SUPPORT_EMAIL
self.supportEmailLabel.font = NSFont(name: MAIN_FONT, size: 12)
self.supportRepositoryLabel.stringValue = REPOSITORY_MESSAGE
self.supportRepositoryLabel.font = NSFont(name: MAIN_FONT, size: 12)
self.repositoryLabel.stringValue = REPOSITORY_LINK
self.repositoryLabel.font = NSFont(name: MAIN_FONT, size: 12)
}
}
| 9dd4e51891177b9751e41b5923fdbb59 | 29.525 | 83 | 0.662981 | false | false | false | false |
rudkx/swift | refs/heads/main | test/Interop/Cxx/operators/member-inline-typechecker.swift | apache-2.0 | 1 | // RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-cxx-interop
import MemberInline
var lhs = LoadableIntWrapper(value: 42)
let rhs = LoadableIntWrapper(value: 23)
let resultPlus = lhs - rhs
let resultCall0 = lhs()
let resultCall1 = lhs(1)
let resultCall2 = lhs(1, 2)
var boolWrapper = LoadableBoolWrapper(value: true)
let notBoolResult = !boolWrapper
var addressOnly = AddressOnlyIntWrapper(42)
let addressOnlyResultCall0 = addressOnly()
let addressOnlyResultCall1 = addressOnly(1)
let addressOnlyResultCall2 = addressOnly(1, 2)
var readWriteIntArray = ReadWriteIntArray()
readWriteIntArray[2] = 321
let readWriteValue = readWriteIntArray[2]
var readOnlyIntArray = ReadOnlyIntArray(3)
let readOnlyValue = readOnlyIntArray[1]
var writeOnlyIntArray = WriteOnlyIntArray()
writeOnlyIntArray[2] = 654
let writeOnlyValue = writeOnlyIntArray[2]
var diffTypesArray = DifferentTypesArray()
let diffTypesResultInt: Int32 = diffTypesArray[0]
let diffTypesResultDouble: Double = diffTypesArray[0.5]
var nonTrivialIntArrayByVal = NonTrivialIntArrayByVal(3)
let nonTrivialValueByVal = nonTrivialIntArrayByVal[1]
var diffTypesArrayByVal = DifferentTypesArrayByVal()
let diffTypesResultIntByVal: Int32 = diffTypesArrayByVal[0]
let diffTypesResultDoubleByVal: Double = diffTypesArrayByVal[0.5]
| e2f0f4988d889843ebd0fc21f892e561 | 29.904762 | 71 | 0.809707 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/Sema/diag_mismatched_magic_literals.swift | apache-2.0 | 19 | // RUN: %target-typecheck-verify-swift
// RUN: %target-typecheck-verify-swift -enable-experimental-concise-pound-file
// The test cases in this file work the same in both Swift 5 and "Swift 6" mode.
// See the _swift5 and _swift6 files for version-specific test cases.
func callee(file: String = #file) {} // expected-note {{'file' declared here}}
func callee(optFile: String? = #file) {} // expected-note {{'optFile' declared here}}
func callee(fileID: String = #fileID) {} // expected-note {{'fileID' declared here}}
func callee(filePath: String = #filePath) {} // expected-note {{'filePath' declared here}}
func callee(arbitrary: String) {}
class SomeClass {
static func callee(file: String = #file) {} // expected-note 2{{'file' declared here}}
static func callee(optFile: String? = #file) {} // expected-note {{'optFile' declared here}}
static func callee(arbitrary: String) {}
func callee(file: String = #file) {} // expected-note 2{{'file' declared here}}
func callee(optFile: String? = #file) {} // expected-note {{'optFile' declared here}}
func callee(arbitrary: String) {}
}
//
// Basic functionality
//
// We should warn when we we pass a `#function`-defaulted argument to a
// `#file`-defaulted argument.
func bad(function: String = #function) {
// expected-note@-1 3{{did you mean for parameter 'function' to default to '#file'?}} {{29-38=#file}}
// expected-note@-2 {{did you mean for parameter 'function' to default to '#fileID'?}} {{29-38=#fileID}}
// expected-note@-3 {{did you mean for parameter 'function' to default to '#filePath'?}} {{29-38=#filePath}}
callee(file: function)
// expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'file', whose default argument is '#file'}}
// expected-note@-2 {{add parentheses to silence this warning}} {{16-16=(}} {{24-24=)}}
SomeClass.callee(file: function)
// expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'file', whose default argument is '#file'}}
// expected-note@-2 {{add parentheses to silence this warning}} {{26-26=(}} {{34-34=)}}
SomeClass().callee(file: function)
// expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'file', whose default argument is '#file'}}
// expected-note@-2 {{add parentheses to silence this warning}} {{28-28=(}} {{36-36=)}}
callee(fileID: function)
// expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'fileID', whose default argument is '#fileID'}}
// expected-note@-2 {{add parentheses to silence this warning}} {{18-18=(}} {{26-26=)}}
callee(filePath: function)
// expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'filePath', whose default argument is '#filePath'}}
// expected-note@-2 {{add parentheses to silence this warning}} {{20-20=(}} {{28-28=)}}
}
// We should not warn when we pass a `#file`-defaulted argument to a
// `#file`-defaulted argument.
func good(file: String = #file, fileID: String = #fileID, filePath: String = #filePath) {
callee(file: file)
SomeClass.callee(file: file)
SomeClass().callee(file: file)
callee(fileID: fileID)
callee(filePath: filePath)
}
// We should not warn when we surround the `#function`-defaulted argument
// with parentheses, which explicitly silences the warning.
func disabled(function: String = #function) {
callee(file: (function))
SomeClass.callee(file: (function))
SomeClass().callee(file: (function))
callee(fileID: (function))
callee(filePath: (function))
}
//
// With implicit instance `self`
//
extension SomeClass {
// We should warn when we we pass a `#function`-defaulted argument to a
// `#file`-defaulted argument.
func bad(function: String = #function) {
// expected-note@-1 1{{did you mean for parameter 'function' to default to '#file'?}} {{31-40=#file}}
callee(file: function)
// expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'file', whose default argument is '#file'}}
// expected-note@-2 {{add parentheses to silence this warning}} {{18-18=(}} {{26-26=)}}
}
// We should not warn when we pass a `#file`-defaulted argument to a
// `#file`-defaulted argument.
func good(file: String = #file) {
callee(file: file)
}
// We should not warn when we surround the `#function`-defaulted argument
// with parentheses, which explicitly silences the warning.
func disabled(function: String = #function) {
callee(file: (function))
}
}
//
// With implicit type `self`
//
extension SomeClass {
// We should warn when we we pass a `#function`-defaulted argument to a
// `#file`-defaulted argument.
static func bad(function: String = #function) {
// expected-note@-1 1{{did you mean for parameter 'function' to default to '#file'?}} {{38-47=#file}}
callee(file: function)
// expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'file', whose default argument is '#file'}}
// expected-note@-2 {{add parentheses to silence this warning}} {{18-18=(}} {{26-26=)}}
}
// We should not warn when we pass a `#file`-defaulted argument to a
// `#file`-defaulted argument.
static func good(file: String = #file) {
callee(file: file)
}
// We should not warn when we surround the `#function`-defaulted argument
// with parentheses, which explicitly silences the warning.
static func disabled(function: String = #function) {
callee(file: (function))
}
}
//
// Looking through implicit conversions
//
// Same as above, but these lift the argument from `String` to `String?`, so
// the compiler has to look through the implicit conversion.
//
// We should warn when we we pass a `#function`-defaulted argument to a
// `#file`-defaulted argument.
func optionalBad(function: String = #function) {
// expected-note@-1 3{{did you mean for parameter 'function' to default to '#file'?}} {{37-46=#file}}
callee(optFile: function)
// expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'optFile', whose default argument is '#file'}}
// expected-note@-2 {{add parentheses to silence this warning}} {{19-19=(}} {{27-27=)}}
SomeClass.callee(optFile: function)
// expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'optFile', whose default argument is '#file'}}
// expected-note@-2 {{add parentheses to silence this warning}} {{29-29=(}} {{37-37=)}}
SomeClass().callee(optFile: function)
// expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'optFile', whose default argument is '#file'}}
// expected-note@-2 {{add parentheses to silence this warning}} {{31-31=(}} {{39-39=)}}
}
// We should not warn when we pass a `#file`-defaulted argument to a
// `#file`-defaulted argument.
func optionalGood(file: String = #file) {
callee(optFile: file)
SomeClass.callee(optFile: file)
SomeClass().callee(optFile: file)
}
// We should not warn when we surround the `#function`-defaulted argument
// with parentheses, which explicitly silences the warning.
func optionalDisabled(function: String = #function) {
callee(optFile: (function))
SomeClass.callee(optFile: (function))
SomeClass().callee(optFile: (function))
}
//
// More negative cases
//
// We should not warn if the caller's parameter has no default.
func explicit(arbitrary: String) {
callee(file: arbitrary)
SomeClass.callee(file: arbitrary)
SomeClass().callee(file: arbitrary)
}
// We should not warn if the caller's parameter has a non-magic-identifier
// default.
func empty(arbitrary: String = "") {
callee(file: arbitrary)
SomeClass.callee(file: arbitrary)
SomeClass().callee(file: arbitrary)
}
// We should not warn if the callee's parameter has no default.
func ineligible(function: String = #function) {
callee(arbitrary: function)
SomeClass.callee(arbitrary: function)
SomeClass().callee(arbitrary: function)
}
| 45eefac9f20359d56e8cb249dc2c68bb | 37.49763 | 153 | 0.693463 | false | false | false | false |
jacobwhite/firefox-ios | refs/heads/master | Client/Frontend/Browser/TopTabsViews.swift | mpl-2.0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
struct TopTabsSeparatorUX {
static let Identifier = "Separator"
static let Color = UIColor.Photon.Grey70
static let Width: CGFloat = 1
}
class TopTabsSeparator: UICollectionReusableView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = TopTabsSeparatorUX.Color
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class TopTabsHeaderFooter: UICollectionReusableView {
let line = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
line.semanticContentAttribute = .forceLeftToRight
addSubview(line)
line.backgroundColor = TopTabsSeparatorUX.Color
}
func arrangeLine(_ kind: String) {
line.snp.removeConstraints()
switch kind {
case UICollectionElementKindSectionHeader:
line.snp.makeConstraints { make in
make.trailing.equalTo(self)
}
case UICollectionElementKindSectionFooter:
line.snp.makeConstraints { make in
make.leading.equalTo(self)
}
default:
break
}
line.snp.makeConstraints { make in
make.height.equalTo(TopTabsUX.SeparatorHeight)
make.width.equalTo(TopTabsUX.SeparatorWidth)
make.top.equalTo(self).offset(TopTabsUX.SeparatorYOffset)
}
}
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
layer.zPosition = CGFloat(layoutAttributes.zIndex)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class TopTabCell: UICollectionViewCell {
enum Style {
case light
case dark
}
static let Identifier = "TopTabCellIdentifier"
static let ShadowOffsetSize: CGFloat = 2 //The shadow is used to hide the tab separator
var style: Style = .light {
didSet {
if style != oldValue {
applyStyle(style)
}
}
}
var selectedTab = false {
didSet {
backgroundColor = selectedTab ? UIColor.Photon.Grey10 : UIColor.Photon.Grey80
titleText.textColor = selectedTab ? UIColor.Photon.Grey90 : UIColor.Photon.Grey40
highlightLine.isHidden = !selectedTab
closeButton.tintColor = selectedTab ? UIColor.Photon.Grey80 : UIColor.Photon.Grey40
// restyle if we are in PBM
if style == .dark && selectedTab {
backgroundColor = UIColor.Photon.Grey70
titleText.textColor = UIColor.Photon.Grey10
closeButton.tintColor = UIColor.Photon.Grey10
}
closeButton.backgroundColor = backgroundColor
closeButton.layer.shadowColor = backgroundColor?.cgColor
if selectedTab {
drawShadow()
}
}
}
let titleText: UILabel = {
let titleText = UILabel()
titleText.textAlignment = .left
titleText.isUserInteractionEnabled = false
titleText.numberOfLines = 1
titleText.lineBreakMode = .byCharWrapping
titleText.font = DynamicFontHelper.defaultHelper.DefaultSmallFont
titleText.semanticContentAttribute = .forceLeftToRight
return titleText
}()
let favicon: UIImageView = {
let favicon = UIImageView()
favicon.layer.cornerRadius = 2.0
favicon.layer.masksToBounds = true
favicon.semanticContentAttribute = .forceLeftToRight
return favicon
}()
let closeButton: UIButton = {
let closeButton = UIButton()
closeButton.setImage(UIImage.templateImageNamed("menu-CloseTabs"), for: [])
closeButton.tintColor = UIColor.Photon.Grey40
closeButton.imageEdgeInsets = UIEdgeInsets(top: 15, left: TopTabsUX.TabTitlePadding, bottom: 15, right: TopTabsUX.TabTitlePadding)
closeButton.layer.shadowOpacity = 0.8
closeButton.layer.masksToBounds = false
closeButton.layer.shadowOffset = CGSize(width: -TopTabsUX.TabTitlePadding, height: 0)
closeButton.semanticContentAttribute = .forceLeftToRight
return closeButton
}()
let highlightLine: UIView = {
let line = UIView()
line.backgroundColor = UIColor.Photon.Blue60
line.isHidden = true
line.semanticContentAttribute = .forceLeftToRight
return line
}()
weak var delegate: TopTabCellDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
closeButton.addTarget(self, action: #selector(closeTab), for: .touchUpInside)
contentView.addSubview(titleText)
contentView.addSubview(closeButton)
contentView.addSubview(favicon)
contentView.addSubview(highlightLine)
favicon.snp.makeConstraints { make in
make.centerY.equalTo(self).offset(TopTabsUX.TabNudge)
make.size.equalTo(TabTrayControllerUX.FaviconSize)
make.leading.equalTo(self).offset(TopTabsUX.TabTitlePadding)
}
titleText.snp.makeConstraints { make in
make.centerY.equalTo(self)
make.height.equalTo(self)
make.trailing.equalTo(closeButton.snp.leading).offset(TopTabsUX.TabTitlePadding)
make.leading.equalTo(favicon.snp.trailing).offset(TopTabsUX.TabTitlePadding)
}
closeButton.snp.makeConstraints { make in
make.centerY.equalTo(self).offset(TopTabsUX.TabNudge)
make.height.equalTo(self)
make.width.equalTo(self.snp.height).offset(-TopTabsUX.TabTitlePadding)
make.trailing.equalTo(self.snp.trailing)
}
highlightLine.snp.makeConstraints { make in
make.top.equalTo(self)
make.leading.equalTo(self).offset(-TopTabCell.ShadowOffsetSize)
make.trailing.equalTo(self).offset(TopTabCell.ShadowOffsetSize)
make.height.equalTo(TopTabsUX.HighlightLineWidth)
}
self.clipsToBounds = false
applyStyle(style)
}
fileprivate func applyStyle(_ style: Style) {
switch style {
case Style.light:
titleText.textColor = UIColor.darkText
backgroundColor = UIConstants.AppBackgroundColor
highlightLine.backgroundColor = UIColor.Photon.Blue60
case Style.dark:
titleText.textColor = UIColor.lightText
backgroundColor = UIColor.Photon.Grey70
highlightLine.backgroundColor = UIColor.Photon.Purple50
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
self.layer.shadowOpacity = 0
}
@objc func closeTab() {
delegate?.tabCellDidClose(self)
}
// When a tab is selected the shadow prevents the tab separators from showing.
func drawShadow() {
self.layer.masksToBounds = false
self.layer.shadowColor = backgroundColor?.cgColor
self.layer.shadowOpacity = 1
self.layer.shadowRadius = 0
self.layer.shadowPath = UIBezierPath(roundedRect: CGRect(width: self.frame.size.width + (TopTabCell.ShadowOffsetSize * 2), height: self.frame.size.height), cornerRadius: 0).cgPath
self.layer.shadowOffset = CGSize(width: -TopTabCell.ShadowOffsetSize, height: 0)
}
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
layer.zPosition = CGFloat(layoutAttributes.zIndex)
}
}
class TopTabFader: UIView {
lazy var hMaskLayer: CAGradientLayer = {
let innerColor: CGColor = UIColor(white: 1, alpha: 1.0).cgColor
let outerColor: CGColor = UIColor(white: 1, alpha: 0.0).cgColor
let hMaskLayer = CAGradientLayer()
hMaskLayer.colors = [outerColor, innerColor, innerColor, outerColor]
hMaskLayer.locations = [0.00, 0.005, 0.995, 1.0]
hMaskLayer.startPoint = CGPoint(x: 0, y: 0.5)
hMaskLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
hMaskLayer.anchorPoint = .zero
return hMaskLayer
}()
init() {
super.init(frame: .zero)
layer.mask = hMaskLayer
}
internal override func layoutSubviews() {
super.layoutSubviews()
let widthA = NSNumber(value: Float(CGFloat(8) / frame.width))
let widthB = NSNumber(value: Float(1 - CGFloat(8) / frame.width))
hMaskLayer.locations = [0.00, widthA, widthB, 1.0]
hMaskLayer.frame = CGRect(width: frame.width, height: frame.height)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class TopTabsViewLayoutAttributes: UICollectionViewLayoutAttributes {
override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? TopTabsViewLayoutAttributes else {
return false
}
return super.isEqual(object)
}
}
| e160eeea2d815783834eca4e04fd494f | 34.680608 | 187 | 0.642583 | false | false | false | false |
gavinpardoe/OfficeUpdateHelper | refs/heads/master | officeUpdateHelper/AppDelegate.swift | mit | 1 | /*
AppDelegate.swift
officeUpdateHelper
Created by Gavin Pardoe on 03/03/2016.
Updated 15/03/2016.
Designed for Use with JAMF Casper Suite.
The MIT License (MIT)
Copyright (c) 2016 Gavin Pardoe
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 Cocoa
import WebKit
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var webView: WebView!
@IBOutlet weak var activityWheel: NSProgressIndicator!
@IBOutlet weak var label: NSTextField!
@IBOutlet weak var deferButtonDisable: NSButton!
@IBOutlet weak var installButtonDisable: NSButton!
var appCheckTimer = NSTimer()
func applicationDidFinishLaunching(aNotification: NSNotification) {
let htmlPage = NSBundle.mainBundle().URLForResource("index", withExtension: "html")
webView.mainFrame.loadRequest(NSURLRequest(URL: htmlPage!))
activityWheel.displayedWhenStopped = false
self.window.makeKeyAndOrderFront(nil)
self.window.level = Int(CGWindowLevelForKey(.FloatingWindowLevelKey))
self.window.level = Int(CGWindowLevelForKey(.MaximumWindowLevelKey))
label.allowsEditingTextAttributes = true
label.stringValue = "Checking for Running Office Apps"
installButtonDisable.enabled = false
NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self
appCheck()
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool {
return true
}
func appCheck() {
appCheckTimer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: #selector(AppDelegate.officeAppsRunning), userInfo: nil, repeats: true)
}
func officeAppsRunning() {
for runningApps in NSWorkspace.sharedWorkspace().runningApplications {
if let _ = runningApps.localizedName {
}
}
let appName = NSWorkspace.sharedWorkspace().runningApplications.flatMap { $0.localizedName }
if appName.contains("Microsoft Word") {
label.textColor = NSColor.redColor()
label.stringValue = "Please Quit All Office Apps to Continue!"
} else if appName.contains("Microsoft Excel") {
label.textColor = NSColor.redColor()
label.stringValue = "Please Quit All Office Apps to Continue!"
} else if appName.contains("Microsoft PowerPoint") {
label.textColor = NSColor.redColor()
label.stringValue = "Please Quit All Office Apps to Continue!"
} else if appName.contains("Microsoft Outlook") {
label.textColor = NSColor.redColor()
label.stringValue = "Please Quit All Office Apps to Continue!"
} else if appName.contains("Microsoft OneNote") {
label.textColor = NSColor.redColor()
label.stringValue = "Please Quit All Office Apps to Continue!"
} else {
installUpdates()
}
}
func installUpdates() {
appCheckTimer.invalidate()
label.textColor = NSColor.blackColor()
label.stringValue = "Click Install to Begin Updating Office"
installButtonDisable.enabled = true
}
@IBAction func installButton(sender: AnyObject) {
installButtonDisable.enabled = false
deferButtonDisable.enabled = false
self.activityWheel.startAnimation(self)
let notification = NSUserNotification()
notification.title = "Office Updater"
notification.informativeText = "Installing Updates..."
notification.soundName = NSUserNotificationDefaultSoundName
NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification)
label.stringValue = "Installing Updates, Window will Close Once Completed"
NSAppleScript(source: "do shell script \"/usr/local/jamf/bin/jamf policy -event officeUpdate\" with administrator " + "privileges")!.executeAndReturnError(nil)
// For Testing
//let alert = NSAlert()
//alert.messageText = "Testing Completed..!"
//alert.addButtonWithTitle("OK")
//alert.runModal()
}
@IBAction func deferButton(sender: AnyObject) {
let notification = NSUserNotification()
notification.title = "Office Updater"
notification.informativeText = "Installation has Been Defered..."
notification.soundName = NSUserNotificationDefaultSoundName
NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification)
NSApplication.sharedApplication().terminate(self)
}
}
| 641b94ed571a36646e97af682caa4d83 | 36.047904 | 170 | 0.674317 | false | false | false | false |
SirapatBoonyasiwapong/grader | refs/heads/master | Sources/App/Admin/Commands/RedisWorker.swift | mit | 2 | import VaporRedisClient
import Redis
import RedisClient
import Reswifq
import Console
class RedisWorker {
let console: ConsoleProtocol
public init(console: ConsoleProtocol) {
self.console = console
}
func run() {
console.print("Preparing redis client pool...")
let client = RedisClientPool(maxElementCount: 10) { () -> RedisClient in
self.console.print("Create client")
return VaporRedisClient(try! TCPClient(hostname: "redis", port: 6379))
}
let queue = Reswifq(client: client)
queue.jobMap[String(describing: DemoJob.self)] = DemoJob.self
queue.jobMap[String(describing: SubmissionJob.self)] = SubmissionJob.self
console.print("Starting worker...")
let worker = Worker(queue: queue, maxConcurrentJobs: 4, averagePollingInterval: 0)
worker.run()
console.print("Finished")
}
}
| 7bae119dbd80bfe85b76cd094fd7577e | 26.628571 | 90 | 0.625646 | false | false | false | false |
alex-alex/S2Geometry | refs/heads/master | Sources/S1Interval.swift | mit | 1 | //
// S1Interval.swift
// S2Geometry
//
// Created by Alex Studnicka on 7/1/16.
// Copyright © 2016 Alex Studnicka. MIT License.
//
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
/**
An S1Interval represents a closed interval on a unit circle (also known as a
1-dimensional sphere). It is capable of representing the empty interval
(containing no points), the full interval (containing all points), and
zero-length intervals (containing a single point).
Points are represented by the angle they make with the positive x-axis in
the range [-Pi, Pi]. An interval is represented by its lower and upper bounds
(both inclusive, since the interval is closed). The lower bound may be
greater than the upper bound, in which case the interval is "inverted" (i.e.
it passes through the point (-1, 0)).
Note that the point (-1, 0) has two valid representations, Pi and -Pi. The
normalized representation of this point internally is Pi, so that endpoints
of normal intervals are in the range (-Pi, Pi]. However, we take advantage of
the point -Pi to construct two special intervals: the Full() interval is
[-Pi, Pi], and the Empty() interval is [Pi, -Pi].
*/
public struct S1Interval: Equatable {
public let lo: Double
public let hi: Double
/**
Both endpoints must be in the range -Pi to Pi inclusive. The value -Pi is
converted internally to Pi except for the Full() and Empty() intervals.
*/
public init(lo: Double, hi: Double) {
self.init(lo: lo, hi: hi, checked: false)
}
/**
Internal constructor that assumes that both arguments are in the correct
range, i.e. normalization from -Pi to Pi is already done.
*/
private init(lo: Double, hi: Double, checked: Bool) {
var newLo = lo
var newHi = hi
if !checked {
if lo == -M_PI && hi != M_PI {
newLo = M_PI
}
if hi == -M_PI && lo != M_PI {
newHi = M_PI
}
}
self.lo = newLo
self.hi = newHi
}
public static let empty = S1Interval(lo: M_PI, hi: -M_PI, checked: true)
public static let full = S1Interval(lo: -M_PI, hi: M_PI, checked: true)
/// Convenience method to construct an interval containing a single point.
public init(point p: Double) {
var p = p
if p == -M_PI { p = M_PI }
self.init(lo: p, hi: p)
}
/**
Convenience method to construct the minimal interval containing the two
given points. This is equivalent to starting with an empty interval and
calling AddPoint() twice, but it is more efficient.
*/
public init(p1: Double, p2: Double) {
var p1 = p1, p2 = p2
if p1 == -M_PI { p1 = M_PI }
if p2 == -M_PI { p2 = M_PI }
if S1Interval.positiveDistance(p1, p2) <= M_PI {
self.init(lo: p1, hi: p2, checked: true)
} else {
self.init(lo: p2, hi: p1, checked: true)
}
}
/**
An interval is valid if neither bound exceeds Pi in absolute value, and the
value -Pi appears only in the empty and full intervals.
*/
public var isValid: Bool {
return (abs(lo) <= M_PI && abs(hi) <= M_PI && !(lo == -M_PI && hi != M_PI) && !(hi == -M_PI && lo != M_PI))
}
/// Return true if the interval contains all points on the unit circle.
public var isFull: Bool {
return hi - lo == 2 * M_PI
}
/// Return true if the interval is empty, i.e. it contains no points.
public var isEmpty: Bool {
return lo - hi == 2 * M_PI
}
/// Return true if lo() > hi(). (This is true for empty intervals.)
public var isInverted: Bool {
return lo > hi
}
/// Return the midpoint of the interval. For full and empty intervals, the result is arbitrary.
public var center: Double {
let center = 0.5 * (lo + hi)
if !isInverted { return center }
// Return the center in the range (-Pi, Pi].
return (center <= 0) ? (center + M_PI) : (center - M_PI)
}
/// Return the length of the interval. The length of an empty interval is negative.
public var length: Double {
var length = hi - lo
if length >= 0 { return length }
length += 2 * M_PI
// Empty intervals have a negative length.
return (length > 0) ? length : -1
}
/**
Return the complement of the interior of the interval. An interval and its
complement have the same boundary but do not share any interior values. The
complement operator is not a bijection, since the complement of a singleton
interval (containing a single value) is the same as the complement of an
empty interval.
*/
public var complement: S1Interval {
if lo == hi {
return S1Interval.full // Singleton.
} else {
return S1Interval(lo: hi, hi: lo, checked: true) // Handles empty and full.
}
}
/// Return true if the interval (which is closed) contains the point 'p'.
public func contains(point p: Double) -> Bool {
// Works for empty, full, and singleton intervals.
// assert (Math.abs(p) <= S2.M_PI);
var p = p
if (p == -M_PI) { p = M_PI }
return fastContains(point: p)
}
/**
Return true if the interval (which is closed) contains the point 'p'. Skips
the normalization of 'p' from -Pi to Pi.
*/
public func fastContains(point p: Double) -> Bool {
if isInverted {
return (p >= lo || p <= hi) && !isEmpty
} else {
return p >= lo && p <= hi
}
}
/// Return true if the interval contains the given interval 'y'. Works for empty, full, and singleton intervals.
public func contains(interval y: S1Interval) -> Bool {
// It might be helpful to compare the structure of these tests to
// the simpler Contains(double) method above.
if isInverted {
if y.isInverted {
return y.lo >= lo && y.hi <= hi
}
return (y.lo >= lo || y.hi <= hi) && !isEmpty
} else {
if y.isInverted {
return isFull || y.isEmpty
}
return y.lo >= lo && y.hi <= hi
}
}
/**
Returns true if the interior of this interval contains the entire interval
'y'. Note that x.InteriorContains(x) is true only when x is the empty or
full interval, and x.InteriorContains(S1Interval(p,p)) is equivalent to
x.InteriorContains(p).
*/
public func interiorContains(interval y: S1Interval) -> Bool {
if isInverted {
if !y.isInverted {
return y.lo > lo || y.hi < hi
}
return (y.lo > lo && y.hi < hi) || y.isEmpty
} else {
if y.isInverted {
return isFull || y.isEmpty
}
return (y.lo > lo && y.hi < hi) || isFull
}
}
/// Return true if the interior of the interval contains the point 'p'.
public func interiorContains(point p: Double) -> Bool {
// Works for empty, full, and singleton intervals.
// assert (Math.abs(p) <= S2.M_PI);
var p = p
if (p == -M_PI) { p = M_PI }
if isInverted {
return p > lo || p < hi
} else {
return (p > lo && p < hi) || isFull
}
}
/**
Return true if the two intervals contain any points in common. Note that
the point +/-Pi has two representations, so the intervals [-Pi,-3] and
[2,Pi] intersect, for example.
*/
public func intersects(with y: S1Interval) -> Bool {
if isEmpty || y.isEmpty {
return false
}
if isInverted {
// Every non-empty inverted interval contains Pi.
return y.isInverted || y.lo <= hi || y.hi >= lo
} else {
if y.isInverted {
return y.lo <= hi || y.hi >= lo
}
return y.lo <= hi && y.hi >= lo
}
}
/**
Return true if the interior of this interval contains any point of the
interval 'y' (including its boundary). Works for empty, full, and singleton
intervals.
*/
public func interiorIntersects(with y: S1Interval) -> Bool {
if isEmpty || y.isEmpty || lo == hi {
return false
}
if isInverted {
return y.isInverted || y.lo < hi || y.hi > lo
} else {
if y.isInverted {
return y.lo < hi || y.hi > lo
}
return (y.lo < hi && y.hi > lo) || isFull
}
}
/**
Expand the interval by the minimum amount necessary so that it contains the
given point "p" (an angle in the range [-Pi, Pi]).
*/
public func add(point p: Double) -> S1Interval {
// assert (Math.abs(p) <= S2.M_PI);
var p = p
if p == -M_PI {
p = M_PI
}
if fastContains(point: p) {
return self
}
if isEmpty {
return S1Interval(point: p)
} else {
// Compute distance from p to each endpoint.
let dlo = S1Interval.positiveDistance(p, lo)
let dhi = S1Interval.positiveDistance(hi, p)
if dlo < dhi {
return S1Interval(lo: p, hi: hi)
} else {
return S1Interval(lo: lo, hi: p)
}
// Adding a point can never turn a non-full interval into a full one.
}
}
/**
Return an interval that contains all points within a distance "radius" of
a point in this interval. Note that the expansion of an empty interval is
always empty. The radius must be non-negative.
*/
public func expanded(radius: Double) -> S1Interval {
// assert (radius >= 0)
guard !isEmpty else { return self }
// Check whether this interval will be full after expansion, allowing
// for a 1-bit rounding error when computing each endpoint.
if length + 2 * radius >= 2 * M_PI - 1e-15 {
return .full
}
// NOTE(dbeaumont): Should this remainder be 2 * M_PI or just M_PI ??
var lo = remainder(self.lo - radius, 2 * M_PI)
let hi = remainder(self.hi + radius, 2 * M_PI)
if lo == -M_PI {
lo = M_PI
}
return S1Interval(lo: lo, hi: hi)
}
/// Return the smallest interval that contains this interval and the given interval "y".
public func union(with y: S1Interval) -> S1Interval {
// The y.is_full() case is handled correctly in all cases by the code
// below, but can follow three separate code paths depending on whether
// this interval is inverted, is non-inverted but contains Pi, or neither.
if y.isEmpty {
return self
}
if fastContains(point: y.lo) {
if fastContains(point: y.hi) {
// Either this interval contains y, or the union of the two
// intervals is the Full() interval.
if contains(interval: y) {
return self // is_full() code path
}
return .full
}
return S1Interval(lo: lo, hi: y.hi, checked: true)
}
if (fastContains(point: y.hi)) {
return S1Interval(lo: y.lo, hi: hi, checked: true)
}
// This interval contains neither endpoint of y. This means that either y
// contains all of this interval, or the two intervals are disjoint.
if isEmpty || y.fastContains(point: lo) {
return y
}
// Check which pair of endpoints are closer together.
let dlo = S1Interval.positiveDistance(y.hi, lo)
let dhi = S1Interval.positiveDistance(hi, y.lo)
if dlo < dhi {
return S1Interval(lo: y.lo, hi: hi, checked: true)
} else {
return S1Interval(lo: lo, hi: y.hi, checked: true)
}
}
/**
Compute the distance from "a" to "b" in the range [0, 2*Pi). This is
equivalent to (drem(b - a - S2.M_PI, 2 * S2.M_PI) + S2.M_PI), except that
it is more numerically stable (it does not lose precision for very small
positive distances).
*/
public static func positiveDistance(_ a: Double, _ b: Double) -> Double {
let d = b - a
if d >= 0 { return d }
// We want to ensure that if b == Pi and a == (-Pi + eps),
// the return result is approximately 2*Pi and not zero.
return (b + M_PI) - (a - M_PI)
}
}
public func ==(lhs: S1Interval, rhs: S1Interval ) -> Bool {
return (lhs.lo == rhs.lo && lhs.hi == rhs.hi) || (lhs.isEmpty && rhs.isEmpty)
}
| 4d4570a06674050f4cd62a854a2c6477 | 29 | 113 | 0.645642 | false | false | false | false |
NoryCao/zhuishushenqi | refs/heads/master | zhuishushenqi/RightSide/Search/QSSearchAutoCompleteTable.swift | mit | 1 | //
// QSSearchAutoCompleteTable.swift
// zhuishushenqi
//
// Created by Nory Cao on 2017/4/13.
// Copyright © 2017年 QS. All rights reserved.
//
import UIKit
class ZSSearchAutoCompleteController: ZSBaseTableViewController ,UISearchResultsUpdating{
var books:[String] = [] { didSet{ self.tableView.reloadData() } }
var selectRow:DidSelectRow?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: 1.0, green: 0.98, blue: 0.82, alpha: 1.0)
tableView.qs_registerCellClass(UITableViewCell.self)
// automaticallyAdjustsScrollViewInsets = false
if #available(iOS 11.0, *) {
self.tableView.contentInsetAdjustmentBehavior = .automatic
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.frame = CGRect(x: 0, y: kNavgationBarHeight, width: ScreenWidth, height: ScreenHeight - kNavgationBarHeight)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return books.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell? = tableView.qs_dequeueReusableCell(UITableViewCell.self)
cell?.backgroundColor = UIColor.white
cell?.selectionStyle = .none
cell?.textLabel?.text = self.books.count > indexPath.row ? books[indexPath.row]:""
return cell!
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.0001
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return UIView()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let select = selectRow {
select(indexPath)
}
}
//MARK: - UISearchBarDelegate
func updateSearchResults(for searchController: UISearchController) {
}
}
class QSSearchAutoCompleteTable: UIView,UITableViewDataSource,UITableViewDelegate {
var books:[String]? {
didSet{
self.tableView.reloadData()
}
}
var selectRow:DidSelectRow?
lazy var tableView:UITableView = {
let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: self.bounds.height), style: .grouped)
tableView.dataSource = self
tableView.delegate = self
tableView.sectionHeaderHeight = CGFloat.leastNonzeroMagnitude
tableView.rowHeight = 44
tableView.qs_registerCellClass(UITableViewCell.self)
return tableView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor(red: 1.0, green: 0.98, blue: 0.82, alpha: 1.0)
self.addSubview(self.tableView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return books?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell? = tableView.qs_dequeueReusableCell(UITableViewCell.self)
cell?.backgroundColor = UIColor.white
cell?.selectionStyle = .none
cell?.textLabel?.text = self.books?.count ?? 0 > indexPath.row ? books?[indexPath.row]:""
return cell!
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.0001
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let select = selectRow {
select(indexPath)
}
}
}
| c1eef906120edd3f08094ab6b5aecb4c | 33.068966 | 131 | 0.657136 | false | false | false | false |
objcio/issue-21-photo-extensions-Filtster | refs/heads/master | FiltsterPack/FiltsterFilter.swift | apache-2.0 | 2 | /*
* Copyright 2015 Sam Davies
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
public protocol FiltsterFilterDelegate {
func outputImageDidUpdate(outputImage: CIImage)
}
public class FiltsterFilter {
// MARK:- Filter info
public let filterIdentifier: String = "com.shinobicontrols.filster"
public let filterVersion: String = "1.0"
// MARK:- Public properties
public var delegate: FiltsterFilterDelegate?
public init() {
}
public var inputImage: CIImage! {
didSet {
performFilter()
}
}
// MARK:- Filter Parameters
public var vignetteIntensity: Double = 1.0 {
didSet {
performFilter()
}
}
public var vignetteRadius: Double = 0.5 {
didSet {
performFilter()
}
}
public var sepiaIntensity: Double = 1.0 {
didSet {
performFilter()
}
}
// MARK:- Output images
public var outputImage: CIImage {
let filter = vignette(vignetteRadius, vignetteIntensity)
>>> sepia(sepiaIntensity)
return filter(inputImage)
}
// MARK:- Private methods
private func performFilter() {
delegate?.outputImageDidUpdate(outputImage)
}
}
// MARK:- Filter Serialization
extension FiltsterFilter {
public func supportsFilterIdentifier(identifier: String, version: String) -> Bool {
return identifier == filterIdentifier && version == filterVersion
}
public func importFilterParameters(data: NSData?) {
if let data = data {
if let dataDict = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [String : AnyObject] {
vignetteIntensity = dataDict["vignetteIntensity"] as? Double ?? vignetteIntensity
vignetteRadius = dataDict["vignetteRadius"] as? Double ?? vignetteRadius
sepiaIntensity = dataDict["sepiaIntensity"] as? Double ?? sepiaIntensity
}
}
}
public func encodeFilterParameters() -> NSData {
var dataDict = [String : AnyObject]()
dataDict["vignetteIntensity"] = vignetteIntensity
dataDict["vignetteRadius"] = vignetteRadius
dataDict["sepiaIntensity"] = sepiaIntensity
return NSKeyedArchiver.archivedDataWithRootObject(dataDict)
}
} | baadbdeb5f941346cd7987ae1fbd932e | 27.410526 | 98 | 0.691994 | false | false | false | false |
shu223/watchOS-2-Sampler | refs/heads/master | watchOS2Sampler WatchKit Extension/AudioRecAndPlayInterfaceController.swift | mit | 1 | //
// AudioRecAndPlayInterfaceController.swift
// watchOS2Sampler
//
// Created by Shuichi Tsutsumi on 2015/06/10.
// Copyright © 2015 Shuichi Tsutsumi. All rights reserved.
//
import WatchKit
import Foundation
class AudioRecAndPlayInterfaceController: WKInterfaceController {
@IBOutlet weak var recLabel: WKInterfaceLabel!
@IBOutlet weak var playLabel: WKInterfaceLabel!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
// =========================================================================
// MARK: - Private
func recFileURL() -> URL? {
// Must use a shared container
let fileManager = FileManager.default
let container = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.shu223.watchos2sampler") // replace with your own identifier!!!!
if let container = container {
return container.appendingPathComponent("rec.mp4")
}
else {
return nil
}
}
// =========================================================================
// MARK: - Actions
@IBAction func recBtnTapped() {
if let recFileUrl = recFileURL() {
presentAudioRecorderController(
withOutputURL: recFileUrl,
preset: WKAudioRecorderPreset.highQualityAudio,
options: nil,
completion:
{ (didSave, error) -> Void in
print("error:\(String(describing: error))\n")
self.recLabel.setText("didSave:\(didSave), error:\(String(describing: error))")
})
}
}
@IBAction func playBtnTapped() {
if let recFileUrl = recFileURL() {
presentMediaPlayerController(
with: recFileUrl,
options: nil) { (didPlayToEnd, endTime, error) -> Void in
self.playLabel.setText("didPlayToEnd:\(didPlayToEnd), endTime:\(endTime), error:\(String(describing: error))")
}
}
}
}
| 63005f43cebffd77d42901a00c36695c | 27.641975 | 163 | 0.536207 | false | false | false | false |
yonekawa/SwiftFlux | refs/heads/master | SwiftFluxTests/ActionCreatorSpec.swift | mit | 1 | //
// ActionCreatorSpec.swift
// SwiftFlux
//
// Created by Kenichi Yonekawa on 8/11/15.
// Copyright (c) 2015 mog2dev. All rights reserved.
//
import Quick
import Nimble
import Result
import SwiftFlux
class ActionCreatorSpec: QuickSpec {
struct ActionCreatorTestModel {
let name: String
}
struct ActionCreatorTestAction: Action {
typealias Payload = ActionCreatorTestModel
func invoke(dispatcher: Dispatcher) {
dispatcher.dispatch(self, result: Result(value: ActionCreatorTestModel(name: "test")))
}
}
struct ActionCreatorDefaultErrorAction: Action {
typealias Payload = ActionCreatorTestModel
func invoke(dispatcher: Dispatcher) {
dispatcher.dispatch(self, result: Result(error: NSError(domain: "TEST00000", code: -1, userInfo: [:])))
}
}
enum ActionError: ErrorType {
case UnexpectedError(NSError)
}
struct ActionCreatorErrorAction: Action {
typealias Payload = ActionCreatorTestModel
typealias Error = ActionError
func invoke(dispatcher: Dispatcher) {
let error = ActionError.UnexpectedError(
NSError(domain: "TEST00000", code: -1, userInfo: [:])
)
dispatcher.dispatch(self, result: Result(error: error))
}
}
override func spec() {
describe("invoke", { () in
var results = [String]()
var fails = [String]()
var callbacks = [String]()
beforeEach({ () -> () in
results = []
fails = []
callbacks = []
let id1 = ActionCreator.dispatcher.register(ActionCreatorTestAction.self) { (result) in
switch result {
case .Success(let box):
results.append("\(box.name)1")
case .Failure(_):
fails.append("fail1")
}
}
let id2 = ActionCreator.dispatcher.register(ActionCreatorErrorAction.self) { (result) in
switch result {
case .Success(let box):
results.append("\(box.name)2")
case .Failure(let error):
fails.append("fail2 \(error.dynamicType)")
}
}
let id3 = ActionCreator.dispatcher.register(ActionCreatorDefaultErrorAction.self) { (result) in
switch result {
case .Success(let box):
results.append("\(box.name)3")
case .Failure(let error):
fails.append("fail3 \(error.dynamicType)")
}
}
callbacks.append(id1)
callbacks.append(id2)
callbacks.append(id3)
})
afterEach({ () -> () in
for id in callbacks {
ActionCreator.dispatcher.unregister(id)
}
})
context("when action succeeded") {
it("should dispatch to registered callback handlers") {
let action = ActionCreatorTestAction()
ActionCreator.invoke(action)
expect(results.count).to(equal(1))
expect(fails.isEmpty).to(beTruthy())
expect(results).to(contain("test1"))
}
}
context("when action failed with error type") {
it("should dispatch to registered callback handlers") {
let action = ActionCreatorErrorAction()
ActionCreator.invoke(action)
expect(fails.count).to(equal(1))
expect(results.isEmpty).to(beTruthy())
expect(fails).to(contain("fail2 ActionError"))
}
}
context("when action failed") {
it("should dispatch to registered callback handlers") {
let action = ActionCreatorDefaultErrorAction()
ActionCreator.invoke(action)
expect(fails.count).to(equal(1))
expect(results.isEmpty).to(beTruthy())
expect(fails).to(contain("fail3 NSError"))
}
}
})
}
}
| 5dd6380b180eab240cca6745261e03f4 | 34.25 | 115 | 0.500443 | false | true | false | false |
segabor/OSCCore | refs/heads/master | Source/OSCCore/conversion/MIDI+OSCMessageArgument.swift | mit | 1 | //
// MIDI+OSCType.swift
// OSCCore
//
// Created by Sebestyén Gábor on 2017. 12. 30..
//
extension MIDI: OSCMessageArgument {
public init?(data: ArraySlice<Byte>) {
let binary: [Byte] = [Byte](data)
guard let flatValue = UInt32(data: binary) else {
return nil
}
let portId = UInt8(flatValue >> 24)
let status = UInt8( (flatValue >> 16) & 0xFF)
let data1 = UInt8( (flatValue >> 8) & 0xFF)
let data2 = UInt8(flatValue & 0xFF)
self.init(portId: portId, status: status, data1: data1, data2: data2)
}
public var oscType: TypeTagValues { .MIDI_MESSAGE_TYPE_TAG }
public var oscValue: [Byte]? {
let portId: UInt32 = UInt32(self.portId)
let statusByte: UInt32 = UInt32(self.status)
let data1: UInt32 = UInt32(self.data1)
let data2: UInt32 = UInt32(self.data2)
let flatValue: UInt32 = portId << 24 | statusByte << 16 | data1 << 8 | data2
return flatValue.oscValue
}
public var packetSize: Int { MemoryLayout<UInt32>.size }
}
| 21e97b3816c4342ae8b618dc68aa0087 | 28.081081 | 84 | 0.60316 | false | false | false | false |
JGiola/swift | refs/heads/main | benchmark/single-source/RandomTree.swift | apache-2.0 | 10 | //===--- RandomTree.swift -------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// This test implements three competing versions of randomized binary trees,
// indirectly testing reference counting performance.
import TestsUtils
var rng = SplitMix64(seed: 0)
let count = 400
let input = (0 ..< count).shuffled(using: &rng)
public let benchmarks = [
BenchmarkInfo(
name: "RandomTree.insert.ADT",
runFunction: run_ADT_insert,
tags: [.validation, .algorithm, .refcount],
setUpFunction: { blackHole(input) }),
BenchmarkInfo(
name: "RandomTree.insert.Unmanaged.slow",
runFunction: run_SlowUnmanaged_insert,
tags: [.validation, .algorithm, .refcount],
setUpFunction: { blackHole(input) }),
BenchmarkInfo(
name: "RandomTree.insert.Unmanaged.fast",
runFunction: run_FastUnmanaged_insert,
tags: [.validation, .algorithm, .refcount],
setUpFunction: { blackHole(input) }),
BenchmarkInfo(
name: "RandomTree.insert.UnsafePointer",
runFunction: run_UnsafePointer_insert,
tags: [.validation, .algorithm, .refcount],
setUpFunction: { blackHole(input) }),
]
enum EnumSearchTree<Element: Comparable> {
case empty
indirect case node(EnumSearchTree<Element>, Element, EnumSearchTree<Element>)
}
extension EnumSearchTree {
func forEach(_ body: (Element) -> Void) {
switch self {
case .empty:
break
case let .node(left, value, right):
left.forEach(body)
body(value)
right.forEach(body)
}
}
func contains(_ value: Element) -> Bool {
switch self {
case .empty:
return false
case let .node(left, v, right):
if value == v { return true }
return value < v ? left.contains(value) : right.contains(value)
}
}
func inserting(_ value: __owned Element) -> EnumSearchTree {
switch self {
case .empty:
return .node(.empty, value, .empty)
case let .node(left, root, right):
if value == root {
return self
} else if value < root {
return .node(left.inserting(value), root, right)
} else {
return .node(left, root, right.inserting(value))
}
}
}
}
struct SlowUnmanagedSearchTree<Element: Comparable> {
class Node {
var value: Element
var left: SlowUnmanagedSearchTree
var right: SlowUnmanagedSearchTree
init(
value: Element,
left: SlowUnmanagedSearchTree = .empty,
right: SlowUnmanagedSearchTree = .empty
) {
self.left = left
self.right = right
self.value = value
}
}
static var empty: SlowUnmanagedSearchTree<Element> { SlowUnmanagedSearchTree() }
var root: Unmanaged<Node>?
init() {
self.root = nil
}
init(_root: Unmanaged<Node>?) {
self.root = _root
}
}
extension SlowUnmanagedSearchTree {
mutating func deallocate() {
guard let root = root?.takeRetainedValue() else { return }
root.left.deallocate()
root.right.deallocate()
}
}
extension SlowUnmanagedSearchTree {
func forEach(_ body: (Element) -> Void) {
guard let root = root?.takeUnretainedValue() else { return }
root.left.forEach(body)
body(root.value)
root.right.forEach(body)
}
func contains(_ value: Element) -> Bool {
guard let root = root?.takeUnretainedValue() else { return false }
if value == root.value { return true }
return value < root.value
? root.left.contains(value)
: root.right.contains(value)
}
mutating func insert(_ value: __owned Element) {
guard let root = root?.takeUnretainedValue() else {
self.root = Unmanaged.passRetained(Node(value: value))
return
}
if value == root.value {
return
} else if value < root.value {
root.left.insert(value)
} else {
root.right.insert(value)
}
}
}
struct FastUnmanagedSearchTree<Element: Comparable> {
class Node {
var value: Element
var left: FastUnmanagedSearchTree
var right: FastUnmanagedSearchTree
init(
value: Element,
left: FastUnmanagedSearchTree = .empty,
right: FastUnmanagedSearchTree = .empty
) {
self.left = left
self.right = right
self.value = value
}
}
static var empty: FastUnmanagedSearchTree<Element> { FastUnmanagedSearchTree() }
var root: Unmanaged<Node>?
init() {
self.root = nil
}
init(_root: Unmanaged<Node>?) {
self.root = _root
}
}
extension FastUnmanagedSearchTree {
mutating func deallocate() {
guard let root = root else { return }
root._withUnsafeGuaranteedRef { root in
root.left.deallocate()
root.right.deallocate()
}
root.release()
}
}
extension FastUnmanagedSearchTree {
func forEach(_ body: (Element) -> Void) {
guard let root = root else { return }
root._withUnsafeGuaranteedRef { root in
root.left.forEach(body)
body(root.value)
root.right.forEach(body)
}
}
func contains(_ value: Element) -> Bool {
guard let root = root else { return false }
return root._withUnsafeGuaranteedRef { root in
if value == root.value { return true }
return value < root.value
? root.left.contains(value)
: root.right.contains(value)
}
}
mutating func insert(_ value: __owned Element) {
guard let root = root else {
self.root = Unmanaged.passRetained(Node(value: value))
return
}
root._withUnsafeGuaranteedRef { root in
if value == root.value {
return
} else if value < root.value {
root.left.insert(value)
} else {
root.right.insert(value)
}
}
}
}
struct PointerSearchTree<Element: Comparable> {
struct Node {
var value: Element
var left: PointerSearchTree = .empty
var right: PointerSearchTree = .empty
}
static var empty: PointerSearchTree<Element> { PointerSearchTree() }
var root: UnsafeMutablePointer<Node>?
init() {
self.root = nil
}
init(_root: UnsafeMutablePointer<Node>?) {
self.root = _root
}
}
extension PointerSearchTree {
mutating func deallocate() {
guard let root = root else { return }
root.pointee.left.deallocate()
root.pointee.right.deallocate()
root.deallocate()
}
}
extension PointerSearchTree {
func forEach(_ body: (Element) -> Void) {
guard let root = root else { return }
root.pointee.left.forEach(body)
body(root.pointee.value)
root.pointee.right.forEach(body)
}
func contains(_ value: Element) -> Bool {
guard let root = root else { return false }
if value == root.pointee.value { return true }
if value < root.pointee.value { return root.pointee.left.contains(value) }
return root.pointee.right.contains(value)
}
mutating func insert(_ value: __owned Element) {
guard let root = root else {
let node = UnsafeMutablePointer<Node>.allocate(capacity: 1)
node.initialize(to: Node(value: value))
self.root = node
return
}
if value == root.pointee.value {
return
} else if value < root.pointee.value {
root.pointee.left.insert(value)
} else {
root.pointee.right.insert(value)
}
}
}
func run_ADT_insert(_ iterations: Int) {
for _ in 0 ..< iterations {
var tree = identity(EnumSearchTree<Int>.empty)
for value in input {
tree = tree.inserting(value)
}
blackHole(tree)
}
}
func run_SlowUnmanaged_insert(_ iterations: Int) {
for _ in 0 ..< iterations {
var tree = identity(SlowUnmanagedSearchTree<Int>.empty)
for value in input {
tree.insert(value)
}
blackHole(tree)
tree.deallocate()
}
}
func run_FastUnmanaged_insert(_ iterations: Int) {
for _ in 0 ..< iterations {
var tree = identity(FastUnmanagedSearchTree<Int>.empty)
for value in input {
tree.insert(value)
}
blackHole(tree)
tree.deallocate()
}
}
func run_UnsafePointer_insert(_ iterations: Int) {
for _ in 0 ..< iterations {
var tree = identity(PointerSearchTree<Int>.empty)
for value in input {
tree.insert(value)
}
blackHole(tree)
tree.deallocate()
}
}
| 611217b0f46b3458b8e1ee28e572e6d5 | 24.005882 | 82 | 0.636909 | false | false | false | false |
skyfe79/TIL | refs/heads/master | about.iOS/about.Concurrency/04_Dependency/LoadAndFilter.playground/Contents.swift | mit | 1 | import Compressor
import UIKit
//: # Dependencies
//: You've now created operations for loading a file over a network, and decompressing a file into an image. These should work together - with the decompression happening only when the file has loaded. That's precisely what dependencies offer within `NSOperation`
//: Input and output variables
let compressedFilePaths = ["01", "02", "03", "04", "05"].map {
NSBundle.mainBundle().URLForResource("sample_\($0)_small", withExtension: "compressed")
}
var decompressedImages = [UIImage]()
//: `ImageDecompressionOperation` is familiar
class ImageDecompressionOperation: NSOperation {
var inputData: NSData?
var outputImage: UIImage?
override func main() {
// TODO: Find out whether a dependency has input data if we don't
if let dependencyData = dependencies
.filter({ $0 is ImageDecompressionOperationDataProvider })
.first as? ImageDecompressionOperationDataProvider where inputData == .None { // start-if
inputData = dependencyData.compressedData
}
guard let inputData = inputData else { return }
if let decompressedData = Compressor.decompressData(inputData) {
outputImage = UIImage(data: decompressedData)
}
}
}
//: `DataLoadOperation` is also familiar
class DataLoadOperation: ConcurrentOperation {
private let url: NSURL
var loadedData: NSData?
init(url: NSURL) {
self.url = url
super.init()
}
override func main() {
NetworkSimulator.asyncLoadDataAtURL(url) {
data in
self.loadedData = data
self.state = .Finished
}
}
}
//: Dependency data transfer
// TODO: Transfer data between dependent operations
protocol ImageDecompressionOperationDataProvider {
var compressedData : NSData? { get }
}
extension DataLoadOperation : ImageDecompressionOperationDataProvider {
var compressedData : NSData? {
return loadedData
}
}
//: Showing off with custom operators
// TODO create custom dependency operator
infix operator |> { associativity left precedence 160 }
func |>(lhs: NSOperation, rhs: NSOperation) -> NSOperation {
rhs.addDependency(lhs)
return rhs
}
//: Create the queue with the default constructor
let queue = NSOperationQueue()
let appendQueue = NSOperationQueue()
appendQueue.maxConcurrentOperationCount = 1
//: Create operations for each of the compresed files, and set up dependencies
for compressedFile in compressedFilePaths {
guard let inputURL = compressedFile else { continue }
let loadingOperation = DataLoadOperation(url: inputURL)
let decompressionOp = ImageDecompressionOperation()
decompressionOp.completionBlock = {
guard let output = decompressionOp.outputImage else { return }
appendQueue.addOperationWithBlock {
decompressedImages.append(output)
}
}
// TODO: Link and enqueue these operations
//decompressionOp.addDependency(loadingOperation)
loadingOperation |> decompressionOp
queue.addOperations([loadingOperation, decompressionOp], waitUntilFinished: false)
}
//: Need to wait for the queue to finish before checking the results
queue.waitUntilAllOperationsAreFinished()
//: Inspect the decompressed images
decompressedImages
| 672169e5227492987f3ab26ea5c86c17 | 30.281553 | 263 | 0.738361 | false | false | false | false |
zmeyc/GRDB.swift | refs/heads/master | Tests/GRDBTests/FetchedRecordsControllerTests.swift | mit | 1 | import XCTest
#if USING_SQLCIPHER
import GRDBCipher
#elseif USING_CUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private class ChangesRecorder<Record: RowConvertible> {
var changes: [(record: Record, change: FetchedRecordChange)] = []
var recordsBeforeChanges: [Record]!
var recordsAfterChanges: [Record]!
var countBeforeChanges: Int?
var countAfterChanges: Int?
var recordsOnFirstEvent: [Record]!
var transactionExpectation: XCTestExpectation? {
didSet {
changes = []
recordsBeforeChanges = nil
recordsAfterChanges = nil
countBeforeChanges = nil
countAfterChanges = nil
recordsOnFirstEvent = nil
}
}
func controllerWillChange(_ controller: FetchedRecordsController<Record>, count: Int? = nil) {
recordsBeforeChanges = controller.fetchedRecords
countBeforeChanges = count
}
/// The default implementation does nothing.
func controller(_ controller: FetchedRecordsController<Record>, didChangeRecord record: Record, with change: FetchedRecordChange) {
if recordsOnFirstEvent == nil {
recordsOnFirstEvent = controller.fetchedRecords
}
changes.append((record: record, change: change))
}
/// The default implementation does nothing.
func controllerDidChange(_ controller: FetchedRecordsController<Record>, count: Int? = nil) {
recordsAfterChanges = controller.fetchedRecords
countAfterChanges = count
if let transactionExpectation = transactionExpectation {
transactionExpectation.fulfill()
}
}
}
private class Person : Record {
var id: Int64?
let name: String
let email: String?
let bookCount: Int?
init(id: Int64? = nil, name: String, email: String? = nil) {
self.id = id
self.name = name
self.email = email
self.bookCount = nil
super.init()
}
required init(row: Row) {
id = row.value(named: "id")
name = row.value(named: "name")
email = row.value(named: "email")
bookCount = row.value(named: "bookCount")
super.init(row: row)
}
override class var databaseTableName: String {
return "persons"
}
override var persistentDictionary: [String : DatabaseValueConvertible?] {
return ["id": id, "name": name, "email": email]
}
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
private struct Book : RowConvertible {
var id: Int64
var authorID: Int64
var title: String
init(row: Row) {
id = row.value(named: "id")
authorID = row.value(named: "authorID")
title = row.value(named: "title")
}
}
class FetchedRecordsControllerTests: GRDBTestCase {
override func setup(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(table: "persons") { t in
t.column("id", .integer).primaryKey()
t.column("name", .text)
t.column("email", .text)
}
try db.create(table: "books") { t in
t.column("id", .integer).primaryKey()
t.column("authorId", .integer).notNull().references("persons", onDelete: .cascade, onUpdate: .cascade)
t.column("title", .text)
}
try db.create(table: "flowers") { t in
t.column("id", .integer).primaryKey()
t.column("name", .text)
}
}
}
func testControllerFromSQL() throws {
let dbQueue = try makeDatabaseQueue()
let authorId: Int64 = try dbQueue.inDatabase { db in
let plato = Person(name: "Plato")
try plato.insert(db)
try db.execute("INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [plato.id, "Symposium"])
let cervantes = Person(name: "Cervantes")
try cervantes.insert(db)
try db.execute("INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [cervantes.id, "Don Quixote"])
return cervantes.id!
}
let controller = try FetchedRecordsController<Book>(dbQueue, sql: "SELECT * FROM books WHERE authorID = ?", arguments: [authorId])
try controller.performFetch()
XCTAssertEqual(controller.fetchedRecords.count, 1)
XCTAssertEqual(controller.fetchedRecords[0].title, "Don Quixote")
}
func testControllerFromSQLWithAdapter() throws {
let dbQueue = try makeDatabaseQueue()
let authorId: Int64 = try dbQueue.inDatabase { db in
let plato = Person(name: "Plato")
try plato.insert(db)
try db.execute("INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [plato.id, "Symposium"])
let cervantes = Person(name: "Cervantes")
try cervantes.insert(db)
try db.execute("INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [cervantes.id, "Don Quixote"])
return cervantes.id!
}
let adapter = ColumnMapping(["id": "_id", "authorId": "_authorId", "title": "_title"])
let controller = try FetchedRecordsController<Book>(dbQueue, sql: "SELECT id AS _id, authorId AS _authorId, title AS _title FROM books WHERE authorID = ?", arguments: [authorId], adapter: adapter)
try controller.performFetch()
XCTAssertEqual(controller.fetchedRecords.count, 1)
XCTAssertEqual(controller.fetchedRecords[0].title, "Don Quixote")
}
func testControllerFromRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try Person(name: "Plato").insert(db)
try Person(name: "Cervantes").insert(db)
}
let request = Person.order(Column("name"))
let controller = try FetchedRecordsController(dbQueue, request: request)
try controller.performFetch()
XCTAssertEqual(controller.fetchedRecords.count, 2)
XCTAssertEqual(controller.fetchedRecords[0].name, "Cervantes")
XCTAssertEqual(controller.fetchedRecords[1].name, "Plato")
}
func testSections() throws {
let dbQueue = try makeDatabaseQueue()
let arthur = Person(name: "Arthur")
try dbQueue.inDatabase { db in
try arthur.insert(db)
}
let request = Person.all()
let controller = try FetchedRecordsController(dbQueue, request: request)
try controller.performFetch()
XCTAssertEqual(controller.sections.count, 1)
XCTAssertEqual(controller.sections[0].numberOfRecords, 1)
XCTAssertEqual(controller.sections[0].records.count, 1)
XCTAssertEqual(controller.sections[0].records[0].name, "Arthur")
XCTAssertEqual(controller.fetchedRecords.count, 1)
XCTAssertEqual(controller.fetchedRecords[0].name, "Arthur")
XCTAssertEqual(controller.record(at: IndexPath(indexes: [0, 0])).name, "Arthur")
XCTAssertEqual(controller.indexPath(for: arthur), IndexPath(indexes: [0, 0]))
}
func testEmptyRequestGivesOneSection() throws {
let dbQueue = try makeDatabaseQueue()
let request = Person.all()
let controller = try FetchedRecordsController(dbQueue, request: request)
try controller.performFetch()
XCTAssertEqual(controller.fetchedRecords.count, 0)
// Just like NSFetchedResultsController
XCTAssertEqual(controller.sections.count, 1)
}
func testDatabaseChangesAreNotReReflectedUntilPerformFetchAndDelegateIsSet() {
// TODO: test that controller.fetchedRecords does not eventually change
// after a database change. The difficulty of this test lies in the
// "eventually" word.
}
func testSimpleInsert() throws {
let dbQueue = try makeDatabaseQueue()
let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id")))
let recorder = ChangesRecorder<Person>()
controller.trackChanges(
willChange: { recorder.controllerWillChange($0) },
onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
didChange: { recorder.controllerDidChange($0) })
try controller.performFetch()
// First insert
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try synchronizePersons(db, [
Person(id: 1, name: "Arthur")])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 0)
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Arthur"])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 1)
XCTAssertEqual(recorder.changes[0].record.name, "Arthur")
switch recorder.changes[0].change {
case .insertion(let indexPath):
XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
default:
XCTFail()
}
// Second insert
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try synchronizePersons(db, [
Person(id: 1, name: "Arthur"),
Person(id: 2, name: "Barbara")])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 1)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur"])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Arthur", "Barbara"])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 2)
XCTAssertEqual(recorder.changes[0].record.name, "Barbara")
switch recorder.changes[0].change {
case .insertion(let indexPath):
XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1]))
default:
XCTFail()
}
}
func testSimpleUpdate() throws {
let dbQueue = try makeDatabaseQueue()
let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id")))
let recorder = ChangesRecorder<Person>()
controller.trackChanges(
willChange: { recorder.controllerWillChange($0) },
onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
didChange: { recorder.controllerDidChange($0) })
try controller.performFetch()
// Insert
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try synchronizePersons(db, [
Person(id: 1, name: "Arthur"),
Person(id: 2, name: "Barbara")])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
// First update
recorder.transactionExpectation = expectation(description: "expectation")
// No change should be recorded
try dbQueue.inTransaction { db in
try db.execute("UPDATE persons SET name = ? WHERE id = ?", arguments: ["Arthur", 1])
return .commit
}
// One change should be recorded
try dbQueue.inTransaction { db in
try synchronizePersons(db, [
Person(id: 1, name: "Craig"),
Person(id: 2, name: "Barbara")])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Craig", "Barbara"])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 1)
XCTAssertEqual(recorder.changes[0].record.name, "Craig")
switch recorder.changes[0].change {
case .update(let indexPath, let changes):
XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
XCTAssertEqual(changes, ["name": "Arthur".databaseValue])
default:
XCTFail()
}
// Second update
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try synchronizePersons(db, [
Person(id: 1, name: "Craig"),
Person(id: 2, name: "Danielle")])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Craig", "Barbara"])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Craig", "Danielle"])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 2)
XCTAssertEqual(recorder.changes[0].record.name, "Danielle")
switch recorder.changes[0].change {
case .update(let indexPath, let changes):
XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1]))
XCTAssertEqual(changes, ["name": "Barbara".databaseValue])
default:
XCTFail()
}
}
func testSimpleDelete() throws {
let dbQueue = try makeDatabaseQueue()
let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id")))
let recorder = ChangesRecorder<Person>()
controller.trackChanges(
willChange: { recorder.controllerWillChange($0) },
onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
didChange: { recorder.controllerDidChange($0) })
try controller.performFetch()
// Insert
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try synchronizePersons(db, [
Person(id: 1, name: "Arthur"),
Person(id: 2, name: "Barbara")])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
// First delete
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try synchronizePersons(db, [
Person(id: 2, name: "Barbara")])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Barbara"])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 1)
XCTAssertEqual(recorder.changes[0].record.name, "Arthur")
switch recorder.changes[0].change {
case .deletion(let indexPath):
XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
default:
XCTFail()
}
// Second delete
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try synchronizePersons(db, [])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 1)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Barbara"])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 0)
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 2)
XCTAssertEqual(recorder.changes[0].record.name, "Barbara")
switch recorder.changes[0].change {
case .deletion(let indexPath):
XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
default:
XCTFail()
}
}
func testSimpleMove() throws {
let dbQueue = try makeDatabaseQueue()
let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name")))
let recorder = ChangesRecorder<Person>()
controller.trackChanges(
willChange: { recorder.controllerWillChange($0) },
onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
didChange: { recorder.controllerDidChange($0) })
try controller.performFetch()
// Insert
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try synchronizePersons(db, [
Person(id: 1, name: "Arthur"),
Person(id: 2, name: "Barbara")])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
// Move
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try synchronizePersons(db, [
Person(id: 1, name: "Craig"),
Person(id: 2, name: "Barbara")])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Barbara", "Craig"])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 1)
XCTAssertEqual(recorder.changes[0].record.name, "Craig")
switch recorder.changes[0].change {
case .move(let indexPath, let newIndexPath, let changes):
XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
XCTAssertEqual(newIndexPath, IndexPath(indexes: [0, 1]))
XCTAssertEqual(changes, ["name": "Arthur".databaseValue])
default:
XCTFail()
}
}
func testSideTableChange() throws {
let dbQueue = try makeDatabaseQueue()
let controller = try FetchedRecordsController<Person>(
dbQueue,
sql: ("SELECT persons.*, COUNT(books.id) AS bookCount " +
"FROM persons " +
"LEFT JOIN books ON books.authorId = persons.id " +
"GROUP BY persons.id " +
"ORDER BY persons.name"))
let recorder = ChangesRecorder<Person>()
controller.trackChanges(
willChange: { recorder.controllerWillChange($0) },
onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
didChange: { recorder.controllerDidChange($0) })
try controller.performFetch()
// Insert
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
try db.execute("INSERT INTO books (authorId, title) VALUES (?, ?)", arguments: [1, "Moby Dick"])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
// Change books
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try db.execute("DELETE FROM books")
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 1)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur"])
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.bookCount! }, [1])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Arthur"])
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.bookCount! }, [0])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 1)
XCTAssertEqual(recorder.changes[0].record.name, "Arthur")
XCTAssertEqual(recorder.changes[0].record.bookCount, 0)
switch recorder.changes[0].change {
case .update(let indexPath, let changes):
XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
XCTAssertEqual(changes, ["bookCount": 1.databaseValue])
default:
XCTFail()
}
}
func testComplexChanges() throws {
let dbQueue = try makeDatabaseQueue()
let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name")))
let recorder = ChangesRecorder<Person>()
controller.trackChanges(
willChange: { recorder.controllerWillChange($0) },
onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
didChange: { recorder.controllerDidChange($0) })
try controller.performFetch()
enum EventTest {
case I(String, Int) // insert string at index
case M(String, Int, Int, String) // move string from index to index with changed string
case D(String, Int) // delete string at index
case U(String, Int, String) // update string at index with changed string
func match(name: String, event: FetchedRecordChange) -> Bool {
switch self {
case .I(let s, let i):
switch event {
case .insertion(let indexPath):
return s == name && i == indexPath[1]
default:
return false
}
case .M(let s, let i, let j, let c):
switch event {
case .move(let indexPath, let newIndexPath, let changes):
return s == name && i == indexPath[1] && j == newIndexPath[1] && c == String.fromDatabaseValue(changes["name"]!)!
default:
return false
}
case .D(let s, let i):
switch event {
case .deletion(let indexPath):
return s == name && i == indexPath[1]
default:
return false
}
case .U(let s, let i, let c):
switch event {
case .update(let indexPath, let changes):
return s == name && i == indexPath[1] && c == String.fromDatabaseValue(changes["name"]!)!
default:
return false
}
}
}
}
// A list of random updates. We hope to cover most cases if not all cases here.
let steps: [(word: String, events: [EventTest])] = [
(word: "B", events: [.I("B",0)]),
(word: "BA", events: [.I("A",0)]),
(word: "ABF", events: [.M("B",0,1,"A"), .M("A",1,0,"B"), .I("F",2)]),
(word: "AB", events: [.D("F",2)]),
(word: "A", events: [.D("B",1)]),
(word: "C", events: [.U("C",0,"A")]),
(word: "", events: [.D("C",0)]),
(word: "C", events: [.I("C",0)]),
(word: "CD", events: [.I("D",1)]),
(word: "B", events: [.D("D",1), .U("B",0,"C")]),
(word: "BCAEFD", events: [.I("A",0), .I("C",2), .I("D",3), .I("E",4), .I("F",5)]),
(word: "CADBE", events: [.M("A",2,0,"C"), .D("D",3), .M("C",1,2,"B"), .M("B",4,1,"E"), .M("D",0,3,"A"), .M("E",5,4,"F")]),
(word: "EB", events: [.D("B",1), .D("D",3), .D("E",4), .M("E",2,1,"C"), .U("B",0,"A")]),
(word: "BEC", events: [.I("C",1), .M("B",1,0,"E"), .M("E",0,2,"B")]),
(word: "AB", events: [.D("C",1), .M("B",2,1,"E"), .U("A",0,"B")]),
(word: "ADEFCB", events: [.I("B",1), .I("C",2), .I("E",4), .M("D",1,3,"B"), .I("F",5)]),
(word: "DA", events: [.D("B",1), .D("C",2), .D("E",4), .M("A",3,0,"D"), .D("F",5), .M("D",0,1,"A")]),
(word: "BACEF", events: [.I("C",2), .I("E",3), .I("F",4), .U("B",1,"D")]),
(word: "BACD", events: [.D("F",4), .U("D",3,"E")]),
(word: "EABDFC", events: [.M("B",2,1,"C"), .I("C",2), .M("E",1,4,"B"), .I("F",5)]),
(word: "CAB", events: [.D("C",2), .D("D",3), .D("F",5), .M("C",4,2,"E")]),
(word: "CBAD", events: [.M("A",1,0,"B"), .M("B",0,1,"A"), .I("D",3)]),
(word: "BAC", events: [.M("A",1,0,"B"), .M("B",2,1,"C"), .D("D",3), .M("C",0,2,"A")]),
(word: "CBEADF", events: [.I("A",0), .M("B",0,1,"A"), .I("D",3), .M("C",1,2,"B"), .M("E",2,4,"C"), .I("F",5)]),
(word: "CBA", events: [.D("A",0), .D("D",3), .M("A",4,0,"E"), .D("F",5)]),
(word: "CBDAF", events: [.I("A",0), .M("D",0,3,"A"), .I("F",4)]),
(word: "B", events: [.D("A",0), .D("B",1), .D("D",3), .D("F",4), .M("B",2,0,"C")]),
(word: "BDECAF", events: [.I("A",0), .I("C",2), .I("D",3), .I("E",4), .I("F",5)]),
(word: "ABCDEF", events: [.M("A",1,0,"B"), .M("B",3,1,"D"), .M("D",2,3,"C"), .M("C",4,2,"E"), .M("E",0,4,"A")]),
(word: "ADBCF", events: [.M("B",2,1,"C"), .M("C",3,2,"D"), .M("D",1,3,"B"), .D("F",5), .U("F",4,"E")]),
(word: "A", events: [.D("B",1), .D("C",2), .D("D",3), .D("F",4)]),
(word: "AEBDCF", events: [.I("B",1), .I("C",2), .I("D",3), .I("E",4), .I("F",5)]),
(word: "B", events: [.D("B",1), .D("C",2), .D("D",3), .D("E",4), .D("F",5), .U("B",0,"A")]),
(word: "ABCDF", events: [.I("B",1), .I("C",2), .I("D",3), .I("F",4), .U("A",0,"B")]),
(word: "CAB", events: [.M("A",1,0,"B"), .D("D",3), .M("B",2,1,"C"), .D("F",4), .M("C",0,2,"A")]),
(word: "AC", events: [.D("B",1), .M("A",2,0,"C"), .M("C",0,1,"A")]),
(word: "DABC", events: [.I("B",1), .I("C",2), .M("A",1,0,"C"), .M("D",0,3,"A")]),
(word: "BACD", events: [.M("C",1,2,"B"), .M("B",3,1,"D"), .M("D",2,3,"C")]),
(word: "D", events: [.D("A",0), .D("C",2), .D("D",3), .M("D",1,0,"B")]),
(word: "CABDFE", events: [.I("A",0), .I("B",1), .I("D",3), .I("E",4), .M("C",0,2,"D"), .I("F",5)]),
(word: "BACDEF", events: [.M("B",2,1,"C"), .M("C",1,2,"B"), .M("E",5,4,"F"), .M("F",4,5,"E")]),
(word: "AB", events: [.D("C",2), .D("D",3), .D("E",4), .M("A",1,0,"B"), .D("F",5), .M("B",0,1,"A")]),
(word: "BACDE", events: [.I("C",2), .M("B",0,1,"A"), .I("D",3), .M("A",1,0,"B"), .I("E",4)]),
(word: "E", events: [.D("A",0), .D("C",2), .D("D",3), .D("E",4), .M("E",1,0,"B")]),
(word: "A", events: [.U("A",0,"E")]),
(word: "ABCDE", events: [.I("B",1), .I("C",2), .I("D",3), .I("E",4)]),
(word: "BA", events: [.D("C",2), .D("D",3), .M("A",1,0,"B"), .D("E",4), .M("B",0,1,"A")]),
(word: "A", events: [.D("A",0), .M("A",1,0,"B")]),
(word: "CAB", events: [.I("A",0), .I("B",1), .M("C",0,2,"A")]),
(word: "EA", events: [.D("B",1), .M("E",2,1,"C")]),
(word: "B", events: [.D("A",0), .M("B",1,0,"E")]),
]
for step in steps {
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try synchronizePersons(db, step.word.characters.enumerated().map { Person(id: Int64($0), name: String($1)) })
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.changes.count, step.events.count)
for (change, event) in zip(recorder.changes, step.events) {
XCTAssertTrue(event.match(name: change.record.name, event: change.change))
}
}
}
func testExternalTableChange() {
// TODO: test that delegate is not notified after a database change in a
// table not involved in the fetch request. The difficulty of this test
// lies in the "not" word.
}
func testCustomRecordIdentity() {
// TODO: test record comparison not based on primary key but based on
// custom function
}
func testRequestChange() throws {
let dbQueue = try makeDatabaseQueue()
let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name")))
let recorder = ChangesRecorder<Person>()
controller.trackChanges(
willChange: { recorder.controllerWillChange($0) },
onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
didChange: { recorder.controllerDidChange($0) })
try controller.performFetch()
// Insert
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try synchronizePersons(db, [
Person(id: 1, name: "Arthur"),
Person(id: 2, name: "Barbara")])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
// Change request with Request
recorder.transactionExpectation = expectation(description: "expectation")
try controller.setRequest(Person.order(Column("name").desc))
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Barbara", "Arthur"])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 2)
XCTAssertEqual(recorder.changes[0].record.name, "Barbara")
switch recorder.changes[0].change {
case .move(let indexPath, let newIndexPath, let changes):
XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1]))
XCTAssertEqual(newIndexPath, IndexPath(indexes: [0, 0]))
XCTAssertTrue(changes.isEmpty)
default:
XCTFail()
}
// Change request with SQL and arguments
recorder.transactionExpectation = expectation(description: "expectation")
try controller.setRequest(sql: "SELECT ? AS id, ? AS name", arguments: [1, "Craig"])
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Barbara", "Arthur"])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Craig"])
XCTAssertEqual(recorder.changes.count, 2)
XCTAssertEqual(recorder.changes[0].record.id, 2)
XCTAssertEqual(recorder.changes[0].record.name, "Barbara")
XCTAssertEqual(recorder.changes[1].record.id, 1)
XCTAssertEqual(recorder.changes[1].record.name, "Craig")
switch recorder.changes[0].change {
case .deletion(let indexPath):
XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
default:
XCTFail()
}
switch recorder.changes[1].change {
case .move(let indexPath, let newIndexPath, let changes):
// TODO: is it really what we should expect? Wouldn't an update fit better?
// What does UITableView think?
XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1]))
XCTAssertEqual(newIndexPath, IndexPath(indexes: [0, 0]))
XCTAssertEqual(changes, ["name": "Arthur".databaseValue])
default:
XCTFail()
}
// Change request with a different set of tracked columns
recorder.transactionExpectation = expectation(description: "expectation")
try controller.setRequest(Person.select(Column("id"), Column("name"), Column("email")).order(Column("name")))
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 1)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Craig"])
XCTAssertEqual(recorder.recordsAfterChanges.count, 2)
XCTAssertEqual(recorder.recordsAfterChanges.map { $0.name }, ["Arthur", "Barbara"])
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try db.execute("UPDATE persons SET email = ? WHERE name = ?", arguments: ["[email protected]", "Arthur"])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"])
XCTAssertEqual(recorder.recordsAfterChanges.count, 2)
XCTAssertEqual(recorder.recordsAfterChanges.map { $0.name }, ["Arthur", "Barbara"])
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try db.execute("UPDATE PERSONS SET EMAIL = ? WHERE NAME = ?", arguments: ["[email protected]", "Barbara"])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"])
XCTAssertEqual(recorder.recordsAfterChanges.count, 2)
XCTAssertEqual(recorder.recordsAfterChanges.map { $0.name }, ["Arthur", "Barbara"])
}
func testSetCallbacksAfterUpdate() throws {
let dbQueue = try makeDatabaseQueue()
let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name")))
let recorder = ChangesRecorder<Person>()
try controller.performFetch()
// Insert
try dbQueue.inTransaction { db in
try synchronizePersons(db, [
Person(id: 1, name: "Arthur")])
return .commit
}
// Set callbacks
recorder.transactionExpectation = expectation(description: "expectation")
controller.trackChanges(
willChange: { recorder.controllerWillChange($0) },
onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
didChange: { recorder.controllerDidChange($0) })
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 0)
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Arthur"])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 1)
XCTAssertEqual(recorder.changes[0].record.name, "Arthur")
switch recorder.changes[0].change {
case .insertion(let indexPath):
XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0]))
default:
XCTFail()
}
}
func testTrailingClosureCallback() throws {
let dbQueue = try makeDatabaseQueue()
let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name")))
var persons: [Person] = []
try controller.performFetch()
let expectation = self.expectation(description: "expectation")
controller.trackChanges {
persons = $0.fetchedRecords
expectation.fulfill()
}
try dbQueue.inTransaction { db in
try synchronizePersons(db, [
Person(id: 1, name: "Arthur")])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(persons.map { $0.name }, ["Arthur"])
}
func testFetchAlongside() throws {
let dbQueue = try makeDatabaseQueue()
let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id")))
let recorder = ChangesRecorder<Person>()
controller.trackChanges(
fetchAlongside: { db in try Person.fetchCount(db) },
willChange: { (controller, count) in recorder.controllerWillChange(controller, count: count) },
onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) },
didChange: { (controller, count) in recorder.controllerDidChange(controller, count: count) })
try controller.performFetch()
// First insert
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try synchronizePersons(db, [
Person(id: 1, name: "Arthur")])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 0)
XCTAssertEqual(recorder.recordsAfterChanges.count, 1)
XCTAssertEqual(recorder.recordsAfterChanges.map { $0.name }, ["Arthur"])
XCTAssertEqual(recorder.countBeforeChanges!, 1)
XCTAssertEqual(recorder.countAfterChanges!, 1)
// Second insert
recorder.transactionExpectation = expectation(description: "expectation")
try dbQueue.inTransaction { db in
try synchronizePersons(db, [
Person(id: 1, name: "Arthur"),
Person(id: 2, name: "Barbara")])
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 1)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur"])
XCTAssertEqual(recorder.recordsAfterChanges.count, 2)
XCTAssertEqual(recorder.recordsAfterChanges.map { $0.name }, ["Arthur", "Barbara"])
XCTAssertEqual(recorder.countBeforeChanges!, 2)
XCTAssertEqual(recorder.countAfterChanges!, 2)
}
func testFetchErrors() throws {
let dbQueue = try makeDatabaseQueue()
let controller = try FetchedRecordsController(dbQueue, request: Person.all())
let expectation = self.expectation(description: "expectation")
var error: Error?
controller.trackErrors {
error = $1
expectation.fulfill()
}
controller.trackChanges { _ in }
try controller.performFetch()
try dbQueue.inTransaction { db in
try synchronizePersons(db, [
Person(id: 1, name: "Arthur")])
try db.drop(table: "persons")
return .commit
}
waitForExpectations(timeout: 1, handler: nil)
if let error = error as? DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, "no such table: persons")
XCTAssertEqual(error.sql!, "SELECT * FROM \"persons\"")
XCTAssertEqual(error.description, "SQLite error 1 with statement `SELECT * FROM \"persons\"`: no such table: persons")
} else {
XCTFail("Expected DatabaseError")
}
}
}
// Synchronizes the persons table with a JSON payload
private func synchronizePersons(_ db: Database, _ newPersons: [Person]) throws {
// Sort new persons and database persons by id:
let newPersons = newPersons.sorted { $0.id! < $1.id! }
let databasePersons = try Person.fetchAll(db, "SELECT * FROM persons ORDER BY id")
// Now that both lists are sorted by id, we can compare them with
// the sortedMerge() function.
//
// We'll delete, insert or update persons, depending on their presence
// in either lists.
for mergeStep in sortedMerge(
left: databasePersons,
right: newPersons,
leftKey: { $0.id! },
rightKey: { $0.id! })
{
switch mergeStep {
case .left(let databasePerson):
try databasePerson.delete(db)
case .right(let newPerson):
try newPerson.insert(db)
case .common(_, let newPerson):
try newPerson.update(db)
}
}
}
/// Given two sorted sequences (left and right), this function emits "merge steps"
/// which tell whether elements are only found on the left, on the right, or on
/// both sides.
///
/// Both sequences do not have to share the same element type. Yet elements must
/// share a common comparable *key*.
///
/// Both sequences must be sorted by this key.
///
/// Keys must be unique in both sequences.
///
/// The example below compare two sequences sorted by integer representation,
/// and prints:
///
/// - Left: 1
/// - Common: 2, 2
/// - Common: 3, 3
/// - Right: 4
///
/// for mergeStep in sortedMerge(
/// left: [1,2,3],
/// right: ["2", "3", "4"],
/// leftKey: { $0 },
/// rightKey: { Int($0)! })
/// {
/// switch mergeStep {
/// case .left(let left):
/// print("- Left: \(left)")
/// case .right(let right):
/// print("- Right: \(right)")
/// case .common(let left, let right):
/// print("- Common: \(left), \(right)")
/// }
/// }
///
/// - parameters:
/// - left: The left sequence.
/// - right: The right sequence.
/// - leftKey: A function that returns the key of a left element.
/// - rightKey: A function that returns the key of a right element.
/// - returns: A sequence of MergeStep
private func sortedMerge<LeftSequence: Sequence, RightSequence: Sequence, Key: Comparable>(
left lSeq: LeftSequence,
right rSeq: RightSequence,
leftKey: @escaping (LeftSequence.Iterator.Element) -> Key,
rightKey: @escaping (RightSequence.Iterator.Element) -> Key) -> AnySequence<MergeStep<LeftSequence.Iterator.Element, RightSequence.Iterator.Element>>
{
return AnySequence { () -> AnyIterator<MergeStep<LeftSequence.Iterator.Element, RightSequence.Iterator.Element>> in
var (lGen, rGen) = (lSeq.makeIterator(), rSeq.makeIterator())
var (lOpt, rOpt) = (lGen.next(), rGen.next())
return AnyIterator {
switch (lOpt, rOpt) {
case (let lElem?, let rElem?):
let (lKey, rKey) = (leftKey(lElem), rightKey(rElem))
if lKey > rKey {
rOpt = rGen.next()
return .right(rElem)
} else if lKey == rKey {
(lOpt, rOpt) = (lGen.next(), rGen.next())
return .common(lElem, rElem)
} else {
lOpt = lGen.next()
return .left(lElem)
}
case (nil, let rElem?):
rOpt = rGen.next()
return .right(rElem)
case (let lElem?, nil):
lOpt = lGen.next()
return .left(lElem)
case (nil, nil):
return nil
}
}
}
}
/**
Support for sortedMerge()
*/
private enum MergeStep<LeftElement, RightElement> {
/// An element only found in the left sequence:
case left(LeftElement)
/// An element only found in the right sequence:
case right(RightElement)
/// Left and right elements share a common key:
case common(LeftElement, RightElement)
}
| 03a07ba56c46aae3a491b4ee91866ddc | 44.269697 | 204 | 0.581766 | false | false | false | false |
Bouke/HAP | refs/heads/master | Sources/HAP/Base/Predefined/Characteristics/Characteristic.AdministratorOnlyAccess.swift | mit | 1 | import Foundation
public extension AnyCharacteristic {
static func administratorOnlyAccess(
_ value: Bool = false,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Administrator Only Access",
format: CharacteristicFormat? = .bool,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.administratorOnlyAccess(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func administratorOnlyAccess(
_ value: Bool = false,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Administrator Only Access",
format: CharacteristicFormat? = .bool,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Bool> {
GenericCharacteristic<Bool>(
type: .administratorOnlyAccess,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| 2ce9a86ce3d92c82535f5895c96a3af4 | 33.737705 | 75 | 0.588957 | false | false | false | false |
vulgur/WeeklyFoodPlan | refs/heads/master | WeeklyFoodPlan/WeeklyFoodPlan/Models/Managers/DailyPlanManager.swift | mit | 1 | //
// DailyPlanManager.swift
// WeeklyFoodPlan
//
// Created by vulgur on 2017/3/3.
// Copyright © 2017年 MAD. All rights reserved.
//
import Foundation
import RealmSwift
class DailyPlanManager {
static let shared = DailyPlanManager()
let realm = try! Realm()
func fakePlan() -> DailyPlan {
let breakfastObject = realm.objects(WhenObject.self).first { (when) -> Bool in
when.value == Food.When.breakfast.rawValue
}
let lunchObject = realm.objects(WhenObject.self).first { (when) -> Bool in
when.value == Food.When.lunch.rawValue
}
let dinnerObject = realm.objects(WhenObject.self).first { (when) -> Bool in
when.value == Food.When.dinner.rawValue
}
let breakfastResults = realm.objects(Food.self).filter("%@ IN whenObjects", breakfastObject!)
let lunchResults = realm.objects(Food.self).filter("%@ IN whenObjects", lunchObject!)
let dinnerResults = realm.objects(Food.self).filter("%@ IN whenObjects", dinnerObject!)
let plan = DailyPlan()
plan.date = Date()
let breakfastMeal = Meal()
breakfastMeal.name = Food.When.breakfast.rawValue
let randomBreakfastList = breakfastResults.shuffled()
for i in 0..<2 {
let food = randomBreakfastList[i]
let breakfast = MealFood(food: food)
BaseManager.shared.transaction {
food.addNeedIngredientCount()
}
breakfastMeal.mealFoods.append(breakfast)
}
let lunchMeal = Meal()
lunchMeal.name = Food.When.lunch.rawValue
let randomLunchList = lunchResults.shuffled()
for i in 0..<2 {
let food = randomLunchList[i]
let lunch = MealFood(food: food)
BaseManager.shared.transaction {
food.addNeedIngredientCount()
}
lunchMeal.mealFoods.append(lunch)
}
let dinnerMeal = Meal()
dinnerMeal.name = Food.When.dinner.rawValue
let randomDinnerList = dinnerResults.shuffled()
for i in 0..<2 {
let food = randomDinnerList[i]
let dinner = MealFood(food: food)
BaseManager.shared.transaction {
food.addNeedIngredientCount()
}
dinnerMeal.mealFoods.append(dinner)
}
plan.meals.append(breakfastMeal)
plan.meals.append(lunchMeal)
plan.meals.append(dinnerMeal)
return plan
}
}
| f55b16fa9a10c61ea7c077d8697973e5 | 32.584416 | 101 | 0.588167 | false | false | false | false |
freak4pc/netfox | refs/heads/master | netfox/Core/NFXHTTPModelManager.swift | mit | 1 | //
// NFXHTTPModelManager.swift
// netfox
//
// Copyright © 2016 netfox. All rights reserved.
//
import Foundation
private let _sharedInstance = NFXHTTPModelManager()
final class NFXHTTPModelManager: NSObject
{
static let sharedInstance = NFXHTTPModelManager()
fileprivate var models = [NFXHTTPModel]()
private let syncQueue = DispatchQueue(label: "NFXSyncQueue")
func add(_ obj: NFXHTTPModel)
{
syncQueue.async {
self.models.insert(obj, at: 0)
NotificationCenter.default.post(name: NSNotification.Name.NFXAddedModel, object: obj)
}
}
func clear()
{
syncQueue.async {
self.models.removeAll()
NotificationCenter.default.post(name: NSNotification.Name.NFXClearedModels, object: nil)
}
}
func getModels() -> [NFXHTTPModel]
{
var predicates = [NSPredicate]()
let filterValues = NFX.sharedInstance().getCachedFilters()
let filterNames = HTTPModelShortType.allValues
var index = 0
for filterValue in filterValues {
if filterValue {
let filterName = filterNames[index].rawValue
let predicate = NSPredicate(format: "shortType == '\(filterName)'")
predicates.append(predicate)
}
index += 1
}
let searchPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: predicates)
let array = (self.models as NSArray).filtered(using: searchPredicate)
return array as! [NFXHTTPModel]
}
}
| 3f952326f099b81fc4290698e067bedc | 27 | 100 | 0.611453 | false | false | false | false |
irisapp/das-quadrat | refs/heads/master | Source/Shared/Endpoints/Updates.swift | bsd-2-clause | 1 | //
// Updates.swift
// Quadrat
//
// Created by Constantine Fry on 06/11/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
public class Updates: Endpoint {
override var endpoint: String {
return "updates"
}
/** https://developer.foursquare.com/docs/updates/updates */
public func get(updateId: String, completionHandler: ResponseClosure? = nil) -> Task {
return self.getWithPath(updateId, parameters: nil, completionHandler: completionHandler)
}
// MARK: - General
/** https://developer.foursquare.com/docs/updates/notifications */
public func notifications(limit: String?, completionHandler: ResponseClosure? = nil) -> Task {
let path = "notifications"
var parameters: Parameters?
if let limit = limit {
parameters = [Parameter.limit:limit]
}
return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler)
}
// MARK: - Actions
/** https://developer.foursquare.com/docs/updates/marknotificationsread */
public func notifications(highWatermark: String, completionHandler: ResponseClosure? = nil) -> Task {
let path = "marknotificationsread"
let parameters = [Parameter.highWatermark: highWatermark]
return self.postWithPath(path, parameters: parameters, completionHandler: completionHandler)
}
}
| 88c361f75eeaac0438983096d1e82324 | 33.97561 | 105 | 0.67643 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin | refs/heads/master | Pod/Classes/Sources.Api/RotationEvent.swift | apache-2.0 | 1 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Object for reporting orientation change events for device and display.
@author Carlos Lozano Diez
@since v2.0.5
@version 1.0
*/
public class RotationEvent : APIBean {
/**
The orientation we're rotating to. This is the future orientation when the state of the event is
WillStartRotation. This will be the current orientation when the rotation is finished with the state
DidFinishRotation.
*/
var destination : ICapabilitiesOrientation?
/**
The orientation we're rotating from. This is the current orientation when the state of the event is
WillStartRotation. This will be the previous orientation when the rotation is finished with the state
DidFinishRotation.
*/
var origin : ICapabilitiesOrientation?
/**
The state of the event to indicate the start of the rotation and the end of the rotation event. This allows
for functions to be pre-emptively performed (veto change, re-layout, etc.) before rotation is effected and
concluded.
*/
var state : RotationEventState?
/**
The timestamps in milliseconds when the event was fired.
*/
var timestamp : Int64?
/**
Default constructor.
@since v2.0.5
*/
public override init() {
super.init()
}
/**
Convenience constructor.
@param origin Source orientation when the event was fired.
@param destination Destination orientation when the event was fired.
@param state State of the event (WillBegin, DidFinish).
@param timestamp Timestamp in milliseconds when the event was fired.
@since v2.0.5
*/
public init(origin: ICapabilitiesOrientation, destination: ICapabilitiesOrientation, state: RotationEventState, timestamp: Int64) {
super.init()
self.origin = origin
self.destination = destination
self.state = state
self.timestamp = timestamp
}
/**
Gets the destination orientation of the event.
@return Destination orientation.
@since v2.0.5
*/
public func getDestination() -> ICapabilitiesOrientation? {
return self.destination
}
/**
Sets the destination orientation of the event.
@param destination Destination orientation.
@since v2.0.5
*/
public func setDestination(destination: ICapabilitiesOrientation) {
self.destination = destination
}
/**
Get the origin orientation of the event.
@return Origin orientation.
@since v2.0.5
*/
public func getOrigin() -> ICapabilitiesOrientation? {
return self.origin
}
/**
Set the origin orientation of the event.
@param origin Origin orientation
@since v2.0.5
*/
public func setOrigin(origin: ICapabilitiesOrientation) {
self.origin = origin
}
/**
Gets the current state of the event.
@return State of the event.
@since v2.0.5
*/
public func getState() -> RotationEventState? {
return self.state
}
/**
Sets the current state of the event.
@param state The state of the event.
@since v2.0.5
*/
public func setState(state: RotationEventState) {
self.state = state
}
/**
Gets the timestamp in milliseconds of the event.
@return Timestamp of the event.
@since v2.0.5
*/
public func getTimestamp() -> Int64? {
return self.timestamp
}
/**
Sets the timestamp in milliseconds of the event.
@param timestamp Timestamp of the event.
@since v2.0.5
*/
public func setTimestamp(timestamp: Int64) {
self.timestamp = timestamp
}
/**
JSON Serialization and deserialization support.
*/
public struct Serializer {
public static func fromJSON(json : String) -> RotationEvent {
let data:NSData = json.dataUsingEncoding(NSUTF8StringEncoding)!
let dict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
return fromDictionary(dict!)
}
static func fromDictionary(dict : NSDictionary) -> RotationEvent {
let resultObject : RotationEvent = RotationEvent()
if let value : AnyObject = dict.objectForKey("destination") {
if "\(value)" as NSString != "<null>" {
resultObject.destination = ICapabilitiesOrientation.toEnum(((value as! NSDictionary)["value"]) as? String)
}
}
if let value : AnyObject = dict.objectForKey("origin") {
if "\(value)" as NSString != "<null>" {
resultObject.origin = ICapabilitiesOrientation.toEnum(((value as! NSDictionary)["value"]) as? String)
}
}
if let value : AnyObject = dict.objectForKey("state") {
if "\(value)" as NSString != "<null>" {
resultObject.state = RotationEventState.toEnum(((value as! NSDictionary)["value"]) as? String)
}
}
if let value : AnyObject = dict.objectForKey("timestamp") {
if "\(value)" as NSString != "<null>" {
let numValue = value as? NSNumber
resultObject.timestamp = numValue?.longLongValue
}
}
return resultObject
}
public static func toJSON(object: RotationEvent) -> String {
let jsonString : NSMutableString = NSMutableString()
// Start Object to JSON
jsonString.appendString("{ ")
// Fields.
object.destination != nil ? jsonString.appendString("\"destination\": { \"value\": \"\(object.destination!.toString())\"}, ") : jsonString.appendString("\"destination\": null, ")
object.origin != nil ? jsonString.appendString("\"origin\": { \"value\": \"\(object.origin!.toString())\"}, ") : jsonString.appendString("\"origin\": null, ")
object.state != nil ? jsonString.appendString("\"state\": { \"value\": \"\(object.state!.toString())\"}, ") : jsonString.appendString("\"state\": null, ")
object.timestamp != nil ? jsonString.appendString("\"timestamp\": \(object.timestamp!)") : jsonString.appendString("\"timestamp\": null")
// End Object to JSON
jsonString.appendString(" }")
return jsonString as String
}
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
| 3cbf8226eb50453b48f4c1242a5b61bd | 32.552743 | 190 | 0.603873 | false | false | false | false |
silt-lang/silt | refs/heads/master | Sources/Lithosphere/DiagnosticConsumer.swift | mit | 1 | //===---------- DiagnosticConsumer.swift - Diagnostic Consumer ------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// This file provides the DiagnosticConsumer protocol.
//===----------------------------------------------------------------------===//
//
// This file contains modifications from the Silt Langauge project. These
// modifications are released under the MIT license, a copy of which is
// available in the repository.
//
//===----------------------------------------------------------------------===//
/// An object that intends to receive notifications when diagnostics are
/// emitted.
public protocol DiagnosticConsumer {
/// Handle the provided diagnostic which has just been registered with the
/// DiagnosticEngine.
func handle(_ diagnostic: Diagnostic)
/// Finalize the consumption of diagnostics, flushing to disk if necessary.
func finalize()
}
| ee74b6b8bc83c0e719baf4d76274035c | 41.8 | 80 | 0.598131 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/CryptoAssets/Sources/BitcoinCashKit/Domain/Models/Coincore/BitcoinCashCryptoAccount.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BitcoinChainKit
import Combine
import DIKit
import Localization
import MoneyKit
import PlatformKit
import RxSwift
import ToolKit
import WalletPayloadKit
final class BitcoinCashCryptoAccount: BitcoinChainCryptoAccount {
let coinType: BitcoinChainCoin = .bitcoinCash
private(set) lazy var identifier: AnyHashable = "BitcoinCashCryptoAccount.\(xPub.address).\(xPub.derivationType)"
let label: String
let asset: CryptoCurrency = .bitcoinCash
let isDefault: Bool
let hdAccountIndex: Int
func createTransactionEngine() -> Any {
BitcoinOnChainTransactionEngineFactory<BitcoinCashToken>()
}
var pendingBalance: AnyPublisher<MoneyValue, Error> {
.just(.zero(currency: .bitcoinCash))
}
var balance: AnyPublisher<MoneyValue, Error> {
balanceService
.balance(for: xPub)
.map(\.moneyValue)
.eraseToAnyPublisher()
}
var actionableBalance: AnyPublisher<MoneyValue, Error> {
balance
}
var receiveAddress: AnyPublisher<ReceiveAddress, Error> {
nativeWalletEnabled()
.flatMap { [receiveAddressProvider, bridge, hdAccountIndex, xPub] isEnabled
-> AnyPublisher<String, Error> in
guard isEnabled else {
return bridge
.receiveAddress(forXPub: xPub.address)
.asPublisher()
.eraseToAnyPublisher()
}
return receiveAddressProvider
.receiveAddressProvider(UInt32(hdAccountIndex))
.map { $0.replacingOccurrences(of: "bitcoincash:", with: "") }
.eraseError()
.eraseToAnyPublisher()
}
.map { [label, onTxCompleted] address -> ReceiveAddress in
BitcoinChainReceiveAddress<BitcoinCashToken>(
address: address,
label: label,
onTxCompleted: onTxCompleted
)
}
.eraseToAnyPublisher()
}
var firstReceiveAddress: AnyPublisher<ReceiveAddress, Error> {
nativeWalletEnabled()
.flatMap { [receiveAddressProvider, bridge, hdAccountIndex, xPub] isEnabled
-> AnyPublisher<String, Error> in
guard isEnabled else {
return bridge
.firstReceiveAddress(forXPub: xPub.address)
.asPublisher()
.eraseToAnyPublisher()
}
return receiveAddressProvider
.firstReceiveAddressProvider(UInt32(hdAccountIndex))
.map { $0.replacingOccurrences(of: "bitcoincash:", with: "") }
.eraseError()
.eraseToAnyPublisher()
}
.map { [label, onTxCompleted] address -> ReceiveAddress in
BitcoinChainReceiveAddress<BitcoinCashToken>(
address: address,
label: label,
onTxCompleted: onTxCompleted
)
}
.eraseToAnyPublisher()
}
var activity: AnyPublisher<[ActivityItemEvent], Error> {
nonCustodialActivity.zip(swapActivity)
.map { nonCustodialActivity, swapActivity in
Self.reconcile(swapEvents: swapActivity, noncustodial: nonCustodialActivity)
}
.eraseError()
.eraseToAnyPublisher()
}
private var isInterestTransferAvailable: AnyPublisher<Bool, Never> {
guard asset.supports(product: .interestBalance) else {
return .just(false)
}
return isInterestWithdrawAndDepositEnabled
.zip(canPerformInterestTransfer)
.map { isEnabled, canPerform in
isEnabled && canPerform
}
.replaceError(with: false)
.eraseToAnyPublisher()
}
private var nonCustodialActivity: AnyPublisher<[TransactionalActivityItemEvent], Never> {
transactionsService
.transactions(publicKeys: [xPub])
.map { response in
response
.map(\.activityItemEvent)
}
.replaceError(with: [])
.eraseToAnyPublisher()
}
private var swapActivity: AnyPublisher<[SwapActivityItemEvent], Never> {
swapTransactionsService
.fetchActivity(cryptoCurrency: asset, directions: custodialDirections)
.replaceError(with: [])
.eraseToAnyPublisher()
}
private var isInterestWithdrawAndDepositEnabled: AnyPublisher<Bool, Never> {
featureFlagsService
.isEnabled(.interestWithdrawAndDeposit)
.replaceError(with: false)
.eraseToAnyPublisher()
}
let xPub: XPub
private let featureFlagsService: FeatureFlagsServiceAPI
private let balanceService: BalanceServiceAPI
private let priceService: PriceServiceAPI
private let bridge: BitcoinCashWalletBridgeAPI
private let transactionsService: BitcoinCashHistoricalTransactionServiceAPI
private let swapTransactionsService: SwapActivityServiceAPI
private let nativeWalletEnabled: () -> AnyPublisher<Bool, Never>
private let receiveAddressProvider: BitcoinChainReceiveAddressProviderAPI
init(
xPub: XPub,
label: String?,
isDefault: Bool,
hdAccountIndex: Int,
priceService: PriceServiceAPI = resolve(),
transactionsService: BitcoinCashHistoricalTransactionServiceAPI = resolve(),
swapTransactionsService: SwapActivityServiceAPI = resolve(),
balanceService: BalanceServiceAPI = resolve(tag: BitcoinChainCoin.bitcoinCash),
bridge: BitcoinCashWalletBridgeAPI = resolve(),
featureFlagsService: FeatureFlagsServiceAPI = resolve(),
nativeWalletEnabled: @escaping () -> AnyPublisher<Bool, Never> = { nativeWalletFlagEnabled() },
receiveAddressProvider: BitcoinChainReceiveAddressProviderAPI = resolve(
tag: BitcoinChainKit.BitcoinChainCoin.bitcoinCash
)
) {
self.xPub = xPub
self.label = label ?? CryptoCurrency.bitcoinCash.defaultWalletName
self.isDefault = isDefault
self.hdAccountIndex = hdAccountIndex
self.priceService = priceService
self.balanceService = balanceService
self.transactionsService = transactionsService
self.swapTransactionsService = swapTransactionsService
self.bridge = bridge
self.featureFlagsService = featureFlagsService
self.nativeWalletEnabled = nativeWalletEnabled
self.receiveAddressProvider = receiveAddressProvider
}
func can(perform action: AssetAction) -> AnyPublisher<Bool, Error> {
switch action {
case .receive,
.send,
.buy,
.linkToDebitCard,
.viewActivity:
return .just(true)
case .deposit,
.sign,
.withdraw,
.interestWithdraw:
return .just(false)
case .interestTransfer:
return isInterestTransferAvailable
.flatMap { [isFunded] isEnabled in
isEnabled ? isFunded : .just(false)
}
.eraseToAnyPublisher()
case .sell, .swap:
return hasPositiveDisplayableBalance
}
}
func balancePair(
fiatCurrency: FiatCurrency,
at time: PriceTime
) -> AnyPublisher<MoneyValuePair, Error> {
balancePair(
priceService: priceService,
fiatCurrency: fiatCurrency,
at: time
)
}
func updateLabel(_ newLabel: String) -> Completable {
bridge.update(accountIndex: hdAccountIndex, label: newLabel)
}
func invalidateAccountBalance() {
balanceService
.invalidateBalanceForWallet(xPub)
}
}
| 675d97a3fa04faa9660e7f3b52e1ac65 | 34.663717 | 117 | 0.612655 | false | false | false | false |
mzyy94/TesSoMe | refs/heads/master | TesSoMe/SearchViewController.swift | gpl-3.0 | 1 | //
// SearchViewController.swift
// TesSoMe
//
// Created by Yuki Mizuno on 2014/10/03.
// Copyright (c) 2014年 Yuki Mizuno. All rights reserved.
//
import UIKit
class SearchValue: NSObject {
enum SearchTarget {
case User, Post, Reply, Hashtag
}
let formatString: [SearchTarget: String] = [
.User: NSLocalizedString("Go to user \"%@\"", comment: "Search user format"),
.Post: NSLocalizedString("Post by \"%@\"", comment: "Search post format"),
.Reply: NSLocalizedString("Reply to @%@", comment: "Search reply format"),
.Hashtag: NSLocalizedString("Hashtag #%@", comment: "Search hashtag format")
]
var target: SearchTarget
var words: [String] = []
var formatedString: String
init(target t: SearchTarget, words w: String) {
target = t
words.append(w)
formatedString = NSString(format: formatString[t]!, w)
}
class func matchUsernameFormat(string: String) -> Bool {
return string.rangeOfString("^@?[0-9a-z]{1,16}$", options: .RegularExpressionSearch) != nil
}
class func matchHashtagFormat(string: String) -> Bool {
return string.rangeOfString("^#?[0-9a-zA-Z]{1,1023}$", options: .RegularExpressionSearch) != nil
}
func setSearchValue(inout resultView: SearchResultViewController, withType type: TesSoMeSearchType) {
switch target {
case .Post:
resultView.username = words.first
case .Reply:
resultView.tag = "at_\(words.first!)"
case .Hashtag:
resultView.tag = "hash_\(words.first!)"
default:
return
}
resultView.type = type
}
}
class SearchViewController: UITableViewController, UISearchBarDelegate {
var searchBookmark: [String] = []
var searchWords: [SearchValue] = []
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var searchTypeSegmentedControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.delegate = self
self.navigationItem.rightBarButtonItem = self.editButtonItem()
let inputAccessoryView = UIToolbar()
inputAccessoryView.barStyle = .Default
inputAccessoryView.sizeToFit()
let spacer = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil)
let doneBtn = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: Selector("closeKeyboard"))
let toolBarItems:[UIBarButtonItem] = [spacer, doneBtn]
inputAccessoryView.setItems(toolBarItems, animated: true)
self.searchBar.inputAccessoryView = inputAccessoryView
}
func closeKeyboard() {
self.searchBar.endEditing(true)
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
let searchWords = searchText.componentsSeparatedByString(" ")
switch searchWords.count {
case 0:
self.searchWords.removeAll(keepCapacity: true)
case 1:
self.searchWords.removeAll(keepCapacity: true)
if let searchWord = searchWords.first {
if SearchValue.matchUsernameFormat(searchWord) {
self.searchWords.append(SearchValue(target: .User, words: searchWord))
self.searchWords.append(SearchValue(target: .Post, words: searchWord))
self.searchWords.append(SearchValue(target: .Reply, words: searchWord))
}
if SearchValue.matchHashtagFormat(searchWord) {
self.searchWords.append(SearchValue(target: .Hashtag, words: searchWord))
}
}
default:
return
}
self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: .None)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
switch section {
case 0:
return searchWords.count
default:
return searchBookmark.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SearchBtnCell", forIndexPath: indexPath) as UITableViewCell
switch indexPath.section {
case 0:
let searchValue = searchWords[indexPath.row]
cell.textLabel?.text = searchValue.formatedString
return cell
default:
return cell
}
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return indexPath.section == 1
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return nil
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 0.0
}
return 44.0
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.0
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 1 {
return NSLocalizedString("Bookmark", comment: "Bookmark")
}
return nil
}
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView!, moveRowAtIndexPath fromIndexPath: NSIndexPath!, toIndexPath: NSIndexPath!) {
}
*/
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if searchWords[indexPath.row].target == .User {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let userViewController = storyboard.instantiateViewControllerWithIdentifier("UserView") as UserViewController
userViewController.username = searchWords[indexPath.row].words.first!
self.navigationController?.pushViewController(userViewController, animated: true)
closeKeyboard()
}
}
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool {
let indexPath = tableView.indexPathForCell(sender as UITableViewCell)!
if searchWords[indexPath.row].target == .User {
return false
}
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
let indexPath = tableView.indexPathForCell(sender as UITableViewCell)!
if indexPath.section == 0 {
let searchValue = searchWords[indexPath.row]
let type = TesSoMeSearchType(rawValue: self.searchTypeSegmentedControl.selectedSegmentIndex - 1)!
var resultView = segue.destinationViewController as SearchResultViewController
searchValue.setSearchValue(&resultView, withType: type)
}
closeKeyboard()
}
}
| 75abca7dab2a8f7f521e6e6d43f79be1 | 32.278261 | 159 | 0.7208 | false | false | false | false |
lukesutton/olpej | refs/heads/master | Olpej/Olpej/Property.swift | mit | 1 | import Foundation
public protocol PropertyType: Hashable {
var hashValue: Int { get }
}
public enum PropertyAction {
case remove
case update
}
public struct Property<View: UIView>: PropertyType, Equatable, Hashable {
public let tag: String
public let hashValue: Int
public let update: (ComponentIdentifier<View>, PropertyAction, View) -> Void
public init(_ tag: String, _ hashValue: Int, update: (ComponentIdentifier<View>, PropertyAction, View) -> Void) {
self.tag = tag
self.hashValue = hashValue
self.update = update
}
}
public func ==<A, B>(lhs: Property<A>, rhs: Property<B>) -> Bool {
return false
}
public func ==<A>(lhs: Property<A>, rhs: Property<A>) -> Bool {
return lhs.tag == rhs.tag && lhs.hashValue == rhs.hashValue
}
| 2d73f8f03b62e869744005db8fa7379f | 25.866667 | 117 | 0.66005 | false | false | false | false |
debugsquad/metalic | refs/heads/master | metalic/Controller/Home/CHomePickerLibrary.swift | mit | 1 | import UIKit
class CHomePickerLibrary:UIImagePickerController, UINavigationControllerDelegate, UIImagePickerControllerDelegate
{
weak var controller:CHome!
convenience init(controller:CHome)
{
self.init()
sourceType = UIImagePickerControllerSourceType.photoLibrary
delegate = self
allowsEditing = false
self.controller = controller
}
//MARK: imagePicker delegate
func imagePickerController(_ picker:UIImagePickerController, didFinishPickingMediaWithInfo info:[String:Any])
{
let image:UIImage? = info[UIImagePickerControllerOriginalImage] as? UIImage
controller.dismiss(animated:true)
{ [weak self] in
self?.controller.imageSelected(image:image)
}
}
}
| 2dc6b7f7f69f0087234f18017d639285 | 27.785714 | 113 | 0.677419 | false | false | false | false |
mokriya/tvos-sample-mokriyans | refs/heads/master | TVSample/App/TVSample/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// TVSample
//
// Created by Diogo Brito on 01/10/15.
// Copyright © 2015 Mokriya. All rights reserved.
//
import UIKit
import TVMLKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, TVApplicationControllerDelegate {
var window: UIWindow?
var appController: TVApplicationController?
static let BaseURL = "http://localhost:1906/"
static let BootURL = "\(BaseURL)js/application.js"
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
// Create Controller Context
let appControllerContext = TVApplicationControllerContext()
//Create the NSURL for the landing javascript path
guard let javaScriptURL = NSURL(string: AppDelegate.BootURL) else {
fatalError("unable to create NSURL")
}
//Set the javascript path and base url
appControllerContext.javaScriptApplicationURL = javaScriptURL
appControllerContext.launchOptions["BASEURL"] = AppDelegate.BaseURL
//Create the controller
appController = TVApplicationController(context: appControllerContext, window: window, delegate: self)
return true
}
}
| b879edaa639f89dd4353d1c2c858ebae | 30.204545 | 127 | 0.685361 | false | false | false | false |
haranicle/MemoryLeaks | refs/heads/master | MemoryLeaks/SwiftObject.swift | apache-2.0 | 1 | //
// SwiftObject.swift
// MemoryLeaks
//
// Created by kazushi.hara on 2015/11/11.
// Copyright © 2015年 haranicle. All rights reserved.
//
import UIKit
class SwiftObject: NSObject {
var title = "Swift Object"
var completion:(()->())?
override init() {
super.init()
}
// リークしない
func doSomethingAsync() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
print(self.title)
}
}
// selfがリークする
func doSomething() {
completion = { () in
print(self.title)
}
completion?()
// completion = nil // これがあるとちゃんとreleaseされていることになる
}
// リークしない
func doSomethingWithWeakSelf() {
weak var weakSelf = self
completion = {() in
print(weakSelf!.title)
}
completion?()
}
// リークしない
func doSomethingWithCaptureList() {
completion = {[weak self] () in
print(self!.title)
}
completion?()
}
}
| f29b0562efed1dd6fcb34d5d43316f79 | 19.480769 | 101 | 0.533333 | false | false | false | false |
lyft/SwiftLint | refs/heads/master | Source/SwiftLintFramework/Rules/ColonRule.swift | mit | 1 | import Foundation
import SourceKittenFramework
private enum ColonKind {
case type
case dictionary
case functionCall
}
public struct ColonRule: CorrectableRule, ConfigurationProviderRule {
public var configuration = ColonConfiguration()
public init() {}
public static let description = RuleDescription(
identifier: "colon",
name: "Colon",
description: "Colons should be next to the identifier when specifying a type " +
"and next to the key in dictionary literals.",
kind: .style,
nonTriggeringExamples: [
"let abc: Void\n",
"let abc: [Void: Void]\n",
"let abc: (Void, Void)\n",
"let abc: ([Void], String, Int)\n",
"let abc: [([Void], String, Int)]\n",
"let abc: String=\"def\"\n",
"let abc: Int=0\n",
"let abc: Enum=Enum.Value\n",
"func abc(def: Void) {}\n",
"func abc(def: Void, ghi: Void) {}\n",
"// 周斌佳年周斌佳\nlet abc: String = \"abc:\"",
"let abc = [Void: Void]()\n",
"let abc = [1: [3: 2], 3: 4]\n",
"let abc = [\"string\": \"string\"]\n",
"let abc = [\"string:string\": \"string\"]\n",
"let abc: [String: Int]\n",
"func foo(bar: [String: Int]) {}\n",
"func foo() -> [String: Int] { return [:] }\n",
"let abc: Any\n",
"let abc: [Any: Int]\n",
"let abc: [String: Any]\n",
"class Foo: Bar {}\n",
"class Foo<T: Equatable> {}\n",
"switch foo {\n" +
"case .bar:\n" +
" _ = something()\n" +
"}\n",
"object.method(x: 5, y: \"string\")\n",
"object.method(x: 5, y:\n" +
" \"string\")",
"object.method(5, y: \"string\")\n",
"func abc() { def(ghi: jkl) }",
"func abc(def: Void) { ghi(jkl: mno) }",
"class ABC { let def = ghi(jkl: mno) } }",
"func foo() { let dict = [1: 1] }"
],
triggeringExamples: [
"let ↓abc:Void\n",
"let ↓abc: Void\n",
"let ↓abc :Void\n",
"let ↓abc : Void\n",
"let ↓abc : [Void: Void]\n",
"let ↓abc : (Void, String, Int)\n",
"let ↓abc : ([Void], String, Int)\n",
"let ↓abc : [([Void], String, Int)]\n",
"let ↓abc: (Void, String, Int)\n",
"let ↓abc: ([Void], String, Int)\n",
"let ↓abc: [([Void], String, Int)]\n",
"let ↓abc :String=\"def\"\n",
"let ↓abc :Int=0\n",
"let ↓abc :Int = 0\n",
"let ↓abc:Int=0\n",
"let ↓abc:Int = 0\n",
"let ↓abc:Enum=Enum.Value\n",
"func abc(↓def:Void) {}\n",
"func abc(↓def: Void) {}\n",
"func abc(↓def :Void) {}\n",
"func abc(↓def : Void) {}\n",
"func abc(def: Void, ↓ghi :Void) {}\n",
"let abc = [Void↓:Void]()\n",
"let abc = [Void↓ : Void]()\n",
"let abc = [Void↓: Void]()\n",
"let abc = [Void↓ : Void]()\n",
"let abc = [1: [3↓ : 2], 3: 4]\n",
"let abc = [1: [3↓ : 2], 3↓: 4]\n",
"let abc: [↓String : Int]\n",
"let abc: [↓String:Int]\n",
"func foo(bar: [↓String : Int]) {}\n",
"func foo(bar: [↓String:Int]) {}\n",
"func foo() -> [↓String : Int] { return [:] }\n",
"func foo() -> [↓String:Int] { return [:] }\n",
"let ↓abc : Any\n",
"let abc: [↓Any : Int]\n",
"let abc: [↓String : Any]\n",
"class ↓Foo : Bar {}\n",
"class ↓Foo:Bar {}\n",
"class Foo<↓T:Equatable> {}\n",
"class Foo<↓T : Equatable> {}\n",
"object.method(x: 5, y↓ : \"string\")\n",
"object.method(x↓:5, y: \"string\")\n",
"object.method(x↓: 5, y: \"string\")\n",
"func abc() { def(ghi↓:jkl) }",
"func abc(def: Void) { ghi(jkl↓:mno) }",
"class ABC { let def = ghi(jkl↓:mno) } }",
"func foo() { let dict = [1↓ : 1] }"
],
corrections: [
"let ↓abc:Void\n": "let abc: Void\n",
"let ↓abc: Void\n": "let abc: Void\n",
"let ↓abc :Void\n": "let abc: Void\n",
"let ↓abc : Void\n": "let abc: Void\n",
"let ↓abc : [Void: Void]\n": "let abc: [Void: Void]\n",
"let ↓abc : (Void, String, Int)\n": "let abc: (Void, String, Int)\n",
"let ↓abc : ([Void], String, Int)\n": "let abc: ([Void], String, Int)\n",
"let ↓abc : [([Void], String, Int)]\n": "let abc: [([Void], String, Int)]\n",
"let ↓abc: (Void, String, Int)\n": "let abc: (Void, String, Int)\n",
"let ↓abc: ([Void], String, Int)\n": "let abc: ([Void], String, Int)\n",
"let ↓abc: [([Void], String, Int)]\n": "let abc: [([Void], String, Int)]\n",
"let ↓abc :String=\"def\"\n": "let abc: String=\"def\"\n",
"let ↓abc :Int=0\n": "let abc: Int=0\n",
"let ↓abc :Int = 0\n": "let abc: Int = 0\n",
"let ↓abc:Int=0\n": "let abc: Int=0\n",
"let ↓abc:Int = 0\n": "let abc: Int = 0\n",
"let ↓abc:Enum=Enum.Value\n": "let abc: Enum=Enum.Value\n",
"func abc(↓def:Void) {}\n": "func abc(def: Void) {}\n",
"func abc(↓def: Void) {}\n": "func abc(def: Void) {}\n",
"func abc(↓def :Void) {}\n": "func abc(def: Void) {}\n",
"func abc(↓def : Void) {}\n": "func abc(def: Void) {}\n",
"func abc(def: Void, ↓ghi :Void) {}\n": "func abc(def: Void, ghi: Void) {}\n",
"let abc = [Void↓:Void]()\n": "let abc = [Void: Void]()\n",
"let abc = [Void↓ : Void]()\n": "let abc = [Void: Void]()\n",
"let abc = [Void↓: Void]()\n": "let abc = [Void: Void]()\n",
"let abc = [Void↓ : Void]()\n": "let abc = [Void: Void]()\n",
"let abc = [1: [3↓ : 2], 3: 4]\n": "let abc = [1: [3: 2], 3: 4]\n",
"let abc = [1: [3↓ : 2], 3↓: 4]\n": "let abc = [1: [3: 2], 3: 4]\n",
"let abc: [↓String : Int]\n": "let abc: [String: Int]\n",
"let abc: [↓String:Int]\n": "let abc: [String: Int]\n",
"func foo(bar: [↓String : Int]) {}\n": "func foo(bar: [String: Int]) {}\n",
"func foo(bar: [↓String:Int]) {}\n": "func foo(bar: [String: Int]) {}\n",
"func foo() -> [↓String : Int] { return [:] }\n": "func foo() -> [String: Int] { return [:] }\n",
"func foo() -> [↓String:Int] { return [:] }\n": "func foo() -> [String: Int] { return [:] }\n",
"let ↓abc : Any\n": "let abc: Any\n",
"let abc: [↓Any : Int]\n": "let abc: [Any: Int]\n",
"let abc: [↓String : Any]\n": "let abc: [String: Any]\n",
"class ↓Foo : Bar {}\n": "class Foo: Bar {}\n",
"class ↓Foo:Bar {}\n": "class Foo: Bar {}\n",
"class Foo<↓T:Equatable> {}\n": "class Foo<T: Equatable> {}\n",
"class Foo<↓T : Equatable> {}\n": "class Foo<T: Equatable> {}\n",
"object.method(x: 5, y↓ : \"string\")\n": "object.method(x: 5, y: \"string\")\n",
"object.method(x↓:5, y: \"string\")\n": "object.method(x: 5, y: \"string\")\n",
"object.method(x↓: 5, y: \"string\")\n": "object.method(x: 5, y: \"string\")\n",
"func abc() { def(ghi↓:jkl) }": "func abc() { def(ghi: jkl) }",
"func abc(def: Void) { ghi(jkl↓:mno) }": "func abc(def: Void) { ghi(jkl: mno) }",
"class ABC { let def = ghi(jkl↓:mno) } }": "class ABC { let def = ghi(jkl: mno) } }",
"func foo() { let dict = [1↓ : 1] }": "func foo() { let dict = [1: 1] }",
"class Foo {\n #if false\n #else\n let bar = [\"key\"↓ : \"value\"]\n #endif\n}":
"class Foo {\n #if false\n #else\n let bar = [\"key\": \"value\"]\n #endif\n}"
]
)
public func validate(file: File) -> [StyleViolation] {
let violations = typeColonViolationRanges(in: file, matching: pattern).compactMap { range in
return StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severityConfiguration.severity,
location: Location(file: file, characterOffset: range.location))
}
let dictionaryViolations: [StyleViolation]
if configuration.applyToDictionaries {
dictionaryViolations = validate(file: file, dictionary: file.structure.dictionary)
} else {
dictionaryViolations = []
}
return (violations + dictionaryViolations).sorted { $0.location < $1.location }
}
public func correct(file: File) -> [Correction] {
let violations = correctionRanges(in: file)
let matches = violations.filter {
!file.ruleEnabled(violatingRanges: [$0.range], for: self).isEmpty
}
guard !matches.isEmpty else { return [] }
let regularExpression = regex(pattern)
let description = type(of: self).description
var corrections = [Correction]()
var contents = file.contents
for (range, kind) in matches.reversed() {
switch kind {
case .type:
contents = regularExpression.stringByReplacingMatches(in: contents,
options: [],
range: range,
withTemplate: "$1: $2")
case .dictionary, .functionCall:
contents = contents.bridge().replacingCharacters(in: range, with: ": ")
}
let location = Location(file: file, characterOffset: range.location)
corrections.append(Correction(ruleDescription: description, location: location))
}
file.write(contents)
return corrections
}
private typealias RangeWithKind = (range: NSRange, kind: ColonKind)
private func correctionRanges(in file: File) -> [RangeWithKind] {
let violations: [RangeWithKind] = typeColonViolationRanges(in: file, matching: pattern).map {
(range: $0, kind: ColonKind.type)
}
let dictionary = file.structure.dictionary
let contents = file.contents.bridge()
let dictViolations: [RangeWithKind] = dictionaryColonViolationRanges(in: file,
dictionary: dictionary).compactMap {
guard let range = contents.byteRangeToNSRange(start: $0.location, length: $0.length) else {
return nil
}
return (range: range, kind: .dictionary)
}
let functionViolations: [RangeWithKind] = functionCallColonViolationRanges(in: file,
dictionary: dictionary).compactMap {
guard let range = contents.byteRangeToNSRange(start: $0.location, length: $0.length) else {
return nil
}
return (range: range, kind: .functionCall)
}
return (violations + dictViolations + functionViolations).sorted {
$0.range.location < $1.range.location
}
}
}
extension ColonRule: ASTRule {
/// Only returns dictionary and function calls colon violations
public func validate(file: File, kind: SwiftExpressionKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
let ranges = dictionaryColonViolationRanges(in: file, kind: kind, dictionary: dictionary) +
functionCallColonViolationRanges(in: file, kind: kind, dictionary: dictionary)
return ranges.map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severityConfiguration.severity,
location: Location(file: file, byteOffset: $0.location))
}
}
}
| 70b43a6df2d5968e33a629225ed28232 | 47.523622 | 119 | 0.474158 | false | false | false | false |
mansoor92/MaksabComponents | refs/heads/master | MaksabComponents/Classes/Payment/PaymentCardView.swift | mit | 1 | //
// AddPaymentMethodView.swift
// Pods
//
// Created by Incubasys on 15/08/2017.
//
//
import UIKit
import StylingBoilerPlate
public struct PaymentCardInfo{
public var title: String
public var cardNo: String
public var expiryDate: String
public var cvv: String
public var cardHolderName: String
public var expiryYear: Int = 0
public var expiryMonth: Int = 0
public init(title: String, cardNo: String, expiryDate: String, cvv: String, cardHolderName: String) {
self.title = title
self.cardNo = cardNo
self.expiryDate = expiryDate
self.cvv = cvv
self.cardHolderName = cardHolderName
}
public func encodeToJSON() -> [String:Any] {
var dictionary = [String:Any]()
dictionary["name"] = cardHolderName
dictionary["number"] = cardNo
dictionary["exp_month"] = expiryMonth
dictionary["exp_year"] = expiryYear
dictionary["cvc"] = cvv
return dictionary
}
}
public class PaymentCardView: UIView, CustomView, NibLoadableView, UITextFieldDelegate {
@IBOutlet weak public var staticLabelCardNo: UILabel!
@IBOutlet weak public var staticLabelExpiryDate: UILabel!
@IBOutlet weak public var staticLabelCvv: UILabel!
@IBOutlet weak public var staticLabelCardHolderName: UILabel!
@IBOutlet weak var cardImg: UIImageView!
@IBOutlet weak public var fieldTitle: UITextField!
@IBOutlet weak public var fieldCardNo: UITextField!
@IBOutlet weak public var fieldExpiryDate: UITextField!
@IBOutlet weak public var fieldCvv: UITextField!
@IBOutlet weak public var fieldCardHolderName: UITextField!
let bundle = Bundle(for: PaymentCardView.classForCoder())
var view: UIView!
public static let height: CGFloat = 277
// 188+16
public var errors = [String]()
public var errorTitle = String()
static public func createInstance(x: CGFloat, y: CGFloat = 0, width: CGFloat) -> PaymentCardView{
let inst = PaymentCardView(frame: CGRect(x: x, y: y, width: width, height: PaymentCardView.height))
return inst
}
override required public init(frame: CGRect) {
super.init(frame: frame)
let bundle = Bundle(for: type(of: self))
view = self.commonInit(bundle: bundle)
configView()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let bundle = Bundle(for: type(of: self))
view = self.commonInit(bundle: bundle)
configView()
}
func configView() {
backgroundColor = UIColor.appColor(color: .Light)
let color = UIColor(netHex: 0x777777)
staticLabelCardNo.textColor = color
staticLabelExpiryDate.textColor = color
staticLabelCvv.textColor = color
staticLabelCardHolderName.textColor = color
fieldTitle.font = UIFont.appFont(font: .RubikMedium, pontSize: 17)
fieldCardNo.delegate = self
fieldExpiryDate.delegate = self
fieldCvv.delegate = self
fieldCardHolderName.delegate = self
staticLabelCardNo.text = Bundle.localizedStringFor(key: "payment-add-card-no")
staticLabelExpiryDate.text = Bundle.localizedStringFor(key: "payment-add-expiry-date")
staticLabelCvv.text = Bundle.localizedStringFor(key: "payment-add-cvv")
staticLabelCardHolderName.text = Bundle.localizedStringFor(key: "payment-add-carholder-name")
fieldTitle.attributedPlaceholder = NSAttributedString(string: Bundle.localizedStringFor(key: "constant-title"), attributes: [NSFontAttributeName: UIFont.appFont(font: .RubikMedium, pontSize: 17)])
fieldTitle.font = UIFont.appFont(font: .RubikMedium, pontSize: 17)
fieldCardNo.placeholder = Bundle.localizedStringFor(key: "payment-add-cardno-placeholder")
fieldExpiryDate.placeholder = Bundle.localizedStringFor(key: "payment-add-date-placeholder")
fieldCvv.placeholder = Bundle.localizedStringFor(key: "payment-add-fieldcvv-placeholder")
fieldCardHolderName.placeholder = Bundle.localizedStringFor(key: "payment-add-field-cardno-placeholder")
errorTitle = Bundle.localizedStringFor(key: "payment-add-error-invalid-input")
errors = [String]()
errors.append(Bundle.localizedStringFor(key: "payment-add-eror-title-req"))
errors.append(Bundle.localizedStringFor(key: "payment-add-eror-invalid-card-no"))
errors.append(Bundle.localizedStringFor(key: "payment-add-eror-invalid-expiry-date"))
errors.append(Bundle.localizedStringFor(key: "payment-add-eror-invalid-cvv"))
errors.append(Bundle.localizedStringFor(key: "payment-add-eror-invalid-cardholder-name"))
}
public func getCardInfo(completion:@escaping((_ err:ResponseError?,_ cardInfo: PaymentCardInfo?)->Void)){
let err = ResponseError()
err.errorTitle = errorTitle
err.reason = ""
// if deliveryItems.count == 1 && deliveryItems[0].itemName.isEmpty && deliveryItems[0].quantity < 0{
// err.reason = "Please enter valid name and quantity."
//
// }
if fieldTitle.text!.isEmpty{
err.reason = errors[0]
}else if fieldCardNo.text!.count != 19{
err.reason = errors[1]
}else if fieldExpiryDate.text!.count != 5{
err.reason = errors[2]
}else if fieldCvv.text!.count < 3 {
err.reason = errors[3]
}else if fieldCardHolderName.text!.isEmpty{
err.reason = errors[4]
}
var cardInfo = PaymentCardInfo(title: fieldTitle.text!, cardNo: fieldCardNo.text!, expiryDate: fieldExpiryDate.text!, cvv: fieldCvv.text!, cardHolderName: fieldCardHolderName.text!)
guard !fieldExpiryDate.text!.isEmpty else {
err.errorTitle = errorTitle
err.reason = errors[2]
completion(err, nil)
return
}
let expDate = fieldExpiryDate.text!
let yearStr = expDate.substring(from: expDate.index(expDate.startIndex, offsetBy: 3))
let monthStr = expDate.substring(to: expDate.index(expDate.startIndex, offsetBy: 2))
if let year = Int("20\(yearStr)"){
cardInfo.expiryYear = year
}else{
err.reason = errors[0]
}
if let month = Int(monthStr),month <= 12, month >= 1 {
cardInfo.expiryMonth = month
}else{
err.reason = errors[0]
}
if err.reason.isEmpty{
cardInfo.cardNo = cardInfo.cardNo.replacingOccurrences(of: " ", with: "")
completion(nil, cardInfo)
}else{
completion(err, nil)
}
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == fieldCardNo{
return handleCardInput(textField: textField, shouldChangeCharactersInRange: range, replacementString: string)
}else if textField == fieldExpiryDate{
return handleDateInput(textField: textField, shouldChangeCharactersInRange: range, replacementString: string)
}else if textField == fieldCvv{
return handleCvvInput(textField: textField, shouldChangeCharactersInRange: range, replacementString: string)
}else {
return !(textField.text!.count > 128 && (string.count) > range.length)
}
}
func handleCardInput(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// check the chars length dd -->2 at the same time calculate the dd-MM --> 5
let replaced = (textField.text! as NSString).replacingCharacters(in: range, with: string)
setCardImage(string: replaced)
if (textField.text!.count == 4) || (textField.text!.count == 9 ) || (textField.text!.count == 14) {
//Handle backspace being pressed
if !(string == "") {
// append the text
textField.text = textField.text! + " "
}
}
return !(textField.text!.count > 18 && (string.count ) > range.length)
}
func setCardImage(string: String) {
guard string.count <= 2 , let digit = Int(string) else {
return
}
if digit == 4 || (digit >= 40 && digit <= 49){
//first digit 4 visa
cardImg.setImg(named: "visacard")
}else if digit >= 51 && digit <= 55{
//first two digits 5x x can be 1-5 matercard
cardImg.setImg(named: "mastercard")
}else if digit == 34 || digit == 37{
//first two digits 34 or 37 american express
cardImg.setImg(named: "americanexpersscard")
}else{
cardImg.image = nil
}
}
func handleDateInput(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// check the chars length dd -->2 at the same time calculate the dd-MM --> 5
// || (textField.text!.characters.count == 5)
if (textField.text!.count == 2) {
//Handle backspace being pressed
if !(string == "") {
// append the text
textField.text = textField.text! + "/"
}
}
// check the condition not exceed 9 chars
return !(textField.text!.count > 4 && (string.count ) > range.length)
}
func handleCvvInput(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newLength = textField.text!.count + string.count - range.length
// let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string)
// if newString.characters.count == 5 {
// textField.rightView = UIImageView(image: #imageLiteral(resourceName: "smallGreenTick"))
// }else{
// textField.rightView = UIImageView(image: nil)
// }
return newLength <= 4
}
}
| aa8c97d6b75ff94c4cc0f7b654b21b29 | 40.918367 | 204 | 0.631451 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet | refs/heads/good | SwiftGL-Demo/Source/Common/ImageFile.swift | mit | 1 | //
// ImageFile.swift
// SwiftGL
//
// Created by jerry on 2015/10/28.
// Copyright © 2015年 Jerry Chan. All rights reserved.
//
import Foundation
import SwiftHttp
public class ImageFile: File {
public override init()
{
}
public func loadImg(_ filename:String)->UIImage!
{
if let img = UIImage(contentsOfFile: File.dirpath+"/"+NSString(string: filename).deletingPathExtension+".png")
{
return img
}
return nil
}
public func loadImgWithExtension(_ filename:String,ext:String)->UIImage!
{
if let img = UIImage(contentsOfFile: File.dirpath+"/"+NSString(string: filename).deletingPathExtension+ext)
{
return img
}
return nil
}
public func loadImg(_ filename:String, attribute:String = "original")->UIImage!
{
switch attribute {
case "original":
return loadImgWithExtension(filename, ext: ".png")
case "thumb":
return loadImgWithExtension(filename, ext: "thumb.png")
case "gif":
return loadImgWithExtension(filename, ext: ".gif")
default:
return loadImgWithExtension(filename, ext: ".png")
}
}
public func saveImg(_ img:UIImage,filename:String)
{
let imageData:Data = UIImagePNGRepresentation(img)!;
let filePath = File.dirpath+"/"+filename+".png"
try? imageData.write(to: URL(fileURLWithPath: filePath), options: [.atomic])
}
override public func delete(_ filename: String) {
super.delete(filename+".png")
}
}
| a7212620ebea12347ef7d1399b2534bc | 26.5 | 118 | 0.590909 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.