repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
peferron/algo | EPI/Strings/Replace and remove/swift/main.swift | 1 | 1380 | // "a" becomes "dd", "b" is removed.
public func replaceAndRemove(characters: inout [Character], count: Int) -> Int {
// The first pass removes "b" and counts "a".
let (aCount, bCount) = removeB(characters: &characters, count: count)
// After the first pass, there are (count - bCount) characters that still matter.
// The second pass goes backwards from there, replacing "a" with "dd".
replaceA(characters: &characters, count: count - bCount, aCount: aCount)
return count - bCount + aCount
}
func removeB(characters: inout [Character], count: Int) -> (Int, Int) {
var aCount = 0
var bCount = 0
for i in 0..<count {
let character = characters[i]
if character == "b" {
bCount += 1
} else {
if character == "a" {
aCount += 1
}
characters[i - bCount] = characters[i]
}
}
return (aCount, bCount)
}
func replaceA(characters: inout [Character], count: Int, aCount: Int) {
var remainingACount = aCount
for i in (0..<count).reversed() {
let character = characters[i]
if character == "a" {
characters[i + remainingACount] = "d"
characters[i + remainingACount - 1] = "d"
remainingACount -= 1
} else {
characters[i + remainingACount] = character
}
}
}
| mit | 1f92be7f9b07e1bf9c906f044a16695a | 29.666667 | 85 | 0.571014 | 3.780822 | false | false | false | false |
rechsteiner/Parchment | ParchmentTests/PagingDataStructureTests.swift | 1 | 1494 | import Foundation
@testable import Parchment
import XCTest
final class PagingDataTests: XCTestCase {
var visibleItems: PagingItems!
override func setUp() {
visibleItems = PagingItems(items: [
Item(index: 0),
Item(index: 1),
Item(index: 2),
])
}
func testIndexPathForPagingItemFound() {
let indexPath = visibleItems.indexPath(for: Item(index: 0))!
XCTAssertEqual(indexPath.item, 0)
}
func testIndexPathForPagingItemMissing() {
let indexPath = visibleItems.indexPath(for: Item(index: -1))
XCTAssertNil(indexPath)
}
func testPagingItemForIndexPath() {
let indexPath = IndexPath(item: 0, section: 0)
let pagingItem = visibleItems.pagingItem(for: indexPath) as! Item
XCTAssertEqual(pagingItem, Item(index: 0))
}
func testDirectionForIndexPathForward() {
let currentPagingItem = Item(index: 0)
let upcomingPagingItem = Item(index: 1)
let direction = visibleItems.direction(from: currentPagingItem, to: upcomingPagingItem)
XCTAssertEqual(direction, PagingDirection.forward(sibling: true))
}
func testDirectionForIndexPathReverse() {
let currentPagingItem = Item(index: 1)
let upcomingPagingItem = Item(index: 0)
let direction = visibleItems.direction(from: currentPagingItem, to: upcomingPagingItem)
XCTAssertEqual(direction, PagingDirection.reverse(sibling: true))
}
}
| mit | 5eb10a567523307cef5725ccd496caa3 | 32.2 | 95 | 0.672691 | 4.596923 | false | true | false | false |
denisprokopchuk/DPTransparentEdgesTableView | Classes/DPTransparentEdgesTableView.swift | 1 | 4081 | //
// DPTransparentEdgesTableView.swift
// DPTransparentEdgesScrollViewExample
//
// Created by Denis Prokopchuk on 03.07.14.
// Copyright (c) 2014 Denis Prokopchuk. All rights reserved.
//
import UIKit
import QuartzCore
class DPTransparentEdgesTableView: UITableView {
var showTopMask = false
var showBottomMask = false
var bottomMaskDisabled = false
var topMaskDisabled = false
// Factor that describe length of the gradient
// length = viewHeight * gradientFactor
var gradientLengthFactor = 0.1
init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
addObserver(self, forKeyPath: "contentOffset", options: nil, context: nil)
}
init(frame: CGRect) {
super.init(frame: frame)
addObserver(self, forKeyPath: "contentOffset", options: nil, context: nil)
}
init(coder aDecoder: NSCoder!)
{
super.init(coder: aDecoder)
addObserver(self, forKeyPath: "contentOffset", options: nil, context: nil)
}
override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: NSDictionary!, context: CMutableVoidPointer) {
let offsetY = contentOffset.y;
if offsetY > 0 {
if !showTopMask {
showTopMask = true;
}
} else {
showTopMask = false;
}
let bottomEdge = contentOffset.y + frame.size.height
if bottomEdge >= contentSize.height {
showBottomMask = false
} else {
if !showBottomMask {
showBottomMask = true
}
}
refreshGradient()
}
func refreshGradient() {
// Creating our gradient mask
let maskLayer = CAGradientLayer()
// This is the anchor point for our gradient, in our case top left. setting it in the middle (.5, .5) will produce a radial gradient. our startPoint and endPoints are based off the anchorPoint
maskLayer.anchorPoint = CGPointZero
// The line between these two points is the line our gradient uses as a guide
// Starts in bottom left
maskLayer.startPoint = CGPointMake(0, 0)
// Ends in top left
maskLayer.endPoint = CGPointMake(0, 1)
// Setting our colors - since this is a mask the color itself is irrelevant - all that matters is the alpha. A clear color will completely hide the layer we're masking, an alpha of 1.0 will completely show the masked view
let outerColor = UIColor(white: 1.0, alpha: 0.0)
let innerColor = UIColor(white: 1.0, alpha: 1.0)
// Setting colors for maskLayer for each scrollView state
if !showTopMask && !showBottomMask {
maskLayer.colors = [innerColor.CGColor, innerColor.CGColor, innerColor.CGColor, innerColor.CGColor]
} else if showTopMask && !showBottomMask {
maskLayer.colors = [outerColor.CGColor, innerColor.CGColor, innerColor.CGColor, innerColor.CGColor]
} else if !showTopMask && showBottomMask {
maskLayer.colors = [innerColor.CGColor, innerColor.CGColor, innerColor.CGColor, outerColor.CGColor]
} else if showTopMask && showBottomMask {
maskLayer.colors = [outerColor.CGColor, innerColor.CGColor, innerColor.CGColor, outerColor.CGColor]
}
// Defining the location of each gradient stop. Top gradient runs from 0 to gradientLengthFactor, bottom gradient from 1 - gradientLengthFactor to 1.0
if bottomMaskDisabled {
maskLayer.locations = [0, gradientLengthFactor]
} else if topMaskDisabled {
maskLayer.locations = [0, 0, 1 - gradientLengthFactor, 1]
}
else {
maskLayer.locations = [0, gradientLengthFactor, 1 - gradientLengthFactor, 1]
}
maskLayer.frame = bounds
layer.masksToBounds = true;
layer.mask = maskLayer
}
override func layoutSubviews() {
super.layoutSubviews()
}
} | mit | 3c0faee022a8b2055a5b1cecf4901141 | 37.509434 | 229 | 0.639304 | 4.728853 | false | false | false | false |
twostraws/HackingWithSwift | Classic/project28/Project28/KeychainWrapper.swift | 2 | 21823 | //
// KeychainWrapper.swift
// KeychainWrapper
//
// Created by Jason Rendel on 9/23/14.
// Copyright (c) 2014 Jason Rendel. All rights reserved.
//
// The MIT License (MIT)
//
// 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
private let SecMatchLimit: String! = kSecMatchLimit as String
private let SecReturnData: String! = kSecReturnData as String
private let SecReturnPersistentRef: String! = kSecReturnPersistentRef as String
private let SecValueData: String! = kSecValueData as String
private let SecAttrAccessible: String! = kSecAttrAccessible as String
private let SecClass: String! = kSecClass as String
private let SecAttrService: String! = kSecAttrService as String
private let SecAttrGeneric: String! = kSecAttrGeneric as String
private let SecAttrAccount: String! = kSecAttrAccount as String
private let SecAttrAccessGroup: String! = kSecAttrAccessGroup as String
private let SecReturnAttributes: String = kSecReturnAttributes as String
/// KeychainWrapper is a class to help make Keychain access in Swift more straightforward. It is designed to make accessing the Keychain services more like using NSUserDefaults, which is much more familiar to people.
open class KeychainWrapper {
@available(*, deprecated, message: "KeychainWrapper.defaultKeychainWrapper is deprecated, use KeychainWrapper.standard instead")
public static let defaultKeychainWrapper = KeychainWrapper.standard
/// Default keychain wrapper access
public static let standard = KeychainWrapper()
/// ServiceName is used for the kSecAttrService property to uniquely identify this keychain accessor. If no service name is specified, KeychainWrapper will default to using the bundleIdentifier.
private (set) public var serviceName: String
/// AccessGroup is used for the kSecAttrAccessGroup property to identify which Keychain Access Group this entry belongs to. This allows you to use the KeychainWrapper with shared keychain access between different applications.
private (set) public var accessGroup: String?
private static let defaultServiceName: String = {
return Bundle.main.bundleIdentifier ?? "SwiftKeychainWrapper"
}()
private convenience init() {
self.init(serviceName: KeychainWrapper.defaultServiceName)
}
/// Create a custom instance of KeychainWrapper with a custom Service Name and optional custom access group.
///
/// - parameter serviceName: The ServiceName for this instance. Used to uniquely identify all keys stored using this keychain wrapper instance.
/// - parameter accessGroup: Optional unique AccessGroup for this instance. Use a matching AccessGroup between applications to allow shared keychain access.
public init(serviceName: String, accessGroup: String? = nil) {
self.serviceName = serviceName
self.accessGroup = accessGroup
}
// MARK:- Public Methods
/// Checks if keychain data exists for a specified key.
///
/// - parameter forKey: The key to check for.
/// - parameter withAccessibility: Optional accessibility to use when retrieving the keychain item.
/// - returns: True if a value exists for the key. False otherwise.
open func hasValue(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Bool {
if let _ = data(forKey: key, withAccessibility: accessibility) {
return true
} else {
return false
}
}
open func accessibilityOfKey(_ key: String) -> KeychainItemAccessibility? {
var keychainQueryDictionary = setupKeychainQueryDictionary(forKey: key)
// Remove accessibility attribute
keychainQueryDictionary.removeValue(forKey: SecAttrAccessible)
// Limit search results to one
keychainQueryDictionary[SecMatchLimit] = kSecMatchLimitOne
// Specify we want SecAttrAccessible returned
keychainQueryDictionary[SecReturnAttributes] = kCFBooleanTrue
// Search
var result: AnyObject?
let status = SecItemCopyMatching(keychainQueryDictionary as CFDictionary, &result)
guard status == noErr, let resultsDictionary = result as? [String:AnyObject], let accessibilityAttrValue = resultsDictionary[SecAttrAccessible] as? String else {
return nil
}
return KeychainItemAccessibility.accessibilityForAttributeValue(accessibilityAttrValue as CFString)
}
/// Get the keys of all keychain entries matching the current ServiceName and AccessGroup if one is set.
open func allKeys() -> Set<String> {
var keychainQueryDictionary: [String:Any] = [
SecClass: kSecClassGenericPassword,
SecAttrService: serviceName,
SecReturnAttributes: kCFBooleanTrue!,
SecMatchLimit: kSecMatchLimitAll,
]
if let accessGroup = self.accessGroup {
keychainQueryDictionary[SecAttrAccessGroup] = accessGroup
}
var result: AnyObject?
let status = SecItemCopyMatching(keychainQueryDictionary as CFDictionary, &result)
guard status == errSecSuccess else { return [] }
var keys = Set<String>()
if let results = result as? [[AnyHashable: Any]] {
for attributes in results {
if let accountData = attributes[SecAttrAccount] as? Data,
let account = String(data: accountData, encoding: String.Encoding.utf8) {
keys.insert(account)
}
}
}
return keys
}
// MARK: Public Getters
open func integer(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Int? {
guard let numberValue = object(forKey: key, withAccessibility: accessibility) as? NSNumber else {
return nil
}
return numberValue.intValue
}
open func float(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Float? {
guard let numberValue = object(forKey: key, withAccessibility: accessibility) as? NSNumber else {
return nil
}
return numberValue.floatValue
}
open func double(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Double? {
guard let numberValue = object(forKey: key, withAccessibility: accessibility) as? NSNumber else {
return nil
}
return numberValue.doubleValue
}
open func bool(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Bool? {
guard let numberValue = object(forKey: key, withAccessibility: accessibility) as? NSNumber else {
return nil
}
return numberValue.boolValue
}
/// Returns a string value for a specified key.
///
/// - parameter forKey: The key to lookup data for.
/// - parameter withAccessibility: Optional accessibility to use when retrieving the keychain item.
/// - returns: The String associated with the key if it exists. If no data exists, or the data found cannot be encoded as a string, returns nil.
open func string(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> String? {
guard let keychainData = data(forKey: key, withAccessibility: accessibility) else {
return nil
}
return String(data: keychainData, encoding: String.Encoding.utf8) as String?
}
/// Returns an object that conforms to NSCoding for a specified key.
///
/// - parameter forKey: The key to lookup data for.
/// - parameter withAccessibility: Optional accessibility to use when retrieving the keychain item.
/// - returns: The decoded object associated with the key if it exists. If no data exists, or the data found cannot be decoded, returns nil.
open func object(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> NSCoding? {
guard let keychainData = data(forKey: key, withAccessibility: accessibility) else {
return nil
}
return try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(keychainData) as? NSCoding
}
/// Returns a Data object for a specified key.
///
/// - parameter forKey: The key to lookup data for.
/// - parameter withAccessibility: Optional accessibility to use when retrieving the keychain item.
/// - returns: The Data object associated with the key if it exists. If no data exists, returns nil.
open func data(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Data? {
var keychainQueryDictionary = setupKeychainQueryDictionary(forKey: key, withAccessibility: accessibility)
// Limit search results to one
keychainQueryDictionary[SecMatchLimit] = kSecMatchLimitOne
// Specify we want Data/CFData returned
keychainQueryDictionary[SecReturnData] = kCFBooleanTrue
// Search
var result: AnyObject?
let status = SecItemCopyMatching(keychainQueryDictionary as CFDictionary, &result)
return status == noErr ? result as? Data : nil
}
/// Returns a persistent data reference object for a specified key.
///
/// - parameter forKey: The key to lookup data for.
/// - parameter withAccessibility: Optional accessibility to use when retrieving the keychain item.
/// - returns: The persistent data reference object associated with the key if it exists. If no data exists, returns nil.
open func dataRef(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Data? {
var keychainQueryDictionary = setupKeychainQueryDictionary(forKey: key, withAccessibility: accessibility)
// Limit search results to one
keychainQueryDictionary[SecMatchLimit] = kSecMatchLimitOne
// Specify we want persistent Data/CFData reference returned
keychainQueryDictionary[SecReturnPersistentRef] = kCFBooleanTrue
// Search
var result: AnyObject?
let status = SecItemCopyMatching(keychainQueryDictionary as CFDictionary, &result)
return status == noErr ? result as? Data : nil
}
// MARK: Public Setters
@discardableResult open func set(_ value: Int, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Bool {
return set(NSNumber(value: value), forKey: key, withAccessibility: accessibility)
}
@discardableResult open func set(_ value: Float, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Bool {
return set(NSNumber(value: value), forKey: key, withAccessibility: accessibility)
}
@discardableResult open func set(_ value: Double, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Bool {
return set(NSNumber(value: value), forKey: key, withAccessibility: accessibility)
}
@discardableResult open func set(_ value: Bool, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Bool {
return set(NSNumber(value: value), forKey: key, withAccessibility: accessibility)
}
/// Save a String value to the keychain associated with a specified key. If a String value already exists for the given key, the string will be overwritten with the new value.
///
/// - parameter value: The String value to save.
/// - parameter forKey: The key to save the String under.
/// - parameter withAccessibility: Optional accessibility to use when setting the keychain item.
/// - returns: True if the save was successful, false otherwise.
@discardableResult open func set(_ value: String, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Bool {
if let data = value.data(using: .utf8) {
return set(data, forKey: key, withAccessibility: accessibility)
} else {
return false
}
}
/// Save an NSCoding compliant object to the keychain associated with a specified key. If an object already exists for the given key, the object will be overwritten with the new value.
///
/// - parameter value: The NSCoding compliant object to save.
/// - parameter forKey: The key to save the object under.
/// - parameter withAccessibility: Optional accessibility to use when setting the keychain item.
/// - returns: True if the save was successful, false otherwise.
@discardableResult open func set(_ value: NSCoding, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Bool {
let data = try! NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: false)
return set(data, forKey: key, withAccessibility: accessibility)
}
/// Save a Data object to the keychain associated with a specified key. If data already exists for the given key, the data will be overwritten with the new value.
///
/// - parameter value: The Data object to save.
/// - parameter forKey: The key to save the object under.
/// - parameter withAccessibility: Optional accessibility to use when setting the keychain item.
/// - returns: True if the save was successful, false otherwise.
@discardableResult open func set(_ value: Data, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Bool {
var keychainQueryDictionary: [String:Any] = setupKeychainQueryDictionary(forKey: key, withAccessibility: accessibility)
keychainQueryDictionary[SecValueData] = value
if let accessibility = accessibility {
keychainQueryDictionary[SecAttrAccessible] = accessibility.keychainAttrValue
} else {
// Assign default protection - Protect the keychain entry so it's only valid when the device is unlocked
keychainQueryDictionary[SecAttrAccessible] = KeychainItemAccessibility.whenUnlocked.keychainAttrValue
}
let status: OSStatus = SecItemAdd(keychainQueryDictionary as CFDictionary, nil)
if status == errSecSuccess {
return true
} else if status == errSecDuplicateItem {
return update(value, forKey: key, withAccessibility: accessibility)
} else {
return false
}
}
@available(*, deprecated, message: "remove is deprecated, use removeObject instead")
@discardableResult open func remove(key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Bool {
return removeObject(forKey: key, withAccessibility: accessibility)
}
/// Remove an object associated with a specified key. If re-using a key but with a different accessibility, first remove the previous key value using removeObjectForKey(:withAccessibility) using the same accessibilty it was saved with.
///
/// - parameter forKey: The key value to remove data for.
/// - parameter withAccessibility: Optional accessibility level to use when looking up the keychain item.
/// - returns: True if successful, false otherwise.
@discardableResult open func removeObject(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Bool {
let keychainQueryDictionary: [String:Any] = setupKeychainQueryDictionary(forKey: key, withAccessibility: accessibility)
// Delete
let status: OSStatus = SecItemDelete(keychainQueryDictionary as CFDictionary)
if status == errSecSuccess {
return true
} else {
return false
}
}
/// Remove all keychain data added through KeychainWrapper. This will only delete items matching the currnt ServiceName and AccessGroup if one is set.
open func removeAllKeys() -> Bool {
// Setup dictionary to access keychain and specify we are using a generic password (rather than a certificate, internet password, etc)
var keychainQueryDictionary: [String:Any] = [SecClass:kSecClassGenericPassword]
// Uniquely identify this keychain accessor
keychainQueryDictionary[SecAttrService] = serviceName
// Set the keychain access group if defined
if let accessGroup = self.accessGroup {
keychainQueryDictionary[SecAttrAccessGroup] = accessGroup
}
let status: OSStatus = SecItemDelete(keychainQueryDictionary as CFDictionary)
if status == errSecSuccess {
return true
} else {
return false
}
}
/// Remove all keychain data, including data not added through keychain wrapper.
///
/// - Warning: This may remove custom keychain entries you did not add via SwiftKeychainWrapper.
///
open class func wipeKeychain() {
deleteKeychainSecClass(kSecClassGenericPassword) // Generic password items
deleteKeychainSecClass(kSecClassInternetPassword) // Internet password items
deleteKeychainSecClass(kSecClassCertificate) // Certificate items
deleteKeychainSecClass(kSecClassKey) // Cryptographic key items
deleteKeychainSecClass(kSecClassIdentity) // Identity items
}
// MARK:- Private Methods
/// Remove all items for a given Keychain Item Class
///
///
@discardableResult private class func deleteKeychainSecClass(_ secClass: AnyObject) -> Bool {
let query = [SecClass: secClass]
let status: OSStatus = SecItemDelete(query as CFDictionary)
if status == errSecSuccess {
return true
} else {
return false
}
}
/// Update existing data associated with a specified key name. The existing data will be overwritten by the new data.
private func update(_ value: Data, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> Bool {
var keychainQueryDictionary: [String:Any] = setupKeychainQueryDictionary(forKey: key, withAccessibility: accessibility)
let updateDictionary = [SecValueData:value]
// on update, only set accessibility if passed in
if let accessibility = accessibility {
keychainQueryDictionary[SecAttrAccessible] = accessibility.keychainAttrValue
}
// Update
let status: OSStatus = SecItemUpdate(keychainQueryDictionary as CFDictionary, updateDictionary as CFDictionary)
if status == errSecSuccess {
return true
} else {
return false
}
}
/// Setup the keychain query dictionary used to access the keychain on iOS for a specified key name. Takes into account the Service Name and Access Group if one is set.
///
/// - parameter forKey: The key this query is for
/// - parameter withAccessibility: Optional accessibility to use when setting the keychain item. If none is provided, will default to .WhenUnlocked
/// - returns: A dictionary with all the needed properties setup to access the keychain on iOS
private func setupKeychainQueryDictionary(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> [String:Any] {
// Setup default access as generic password (rather than a certificate, internet password, etc)
var keychainQueryDictionary: [String:Any] = [SecClass:kSecClassGenericPassword]
// Uniquely identify this keychain accessor
keychainQueryDictionary[SecAttrService] = serviceName
// Only set accessibiilty if its passed in, we don't want to default it here in case the user didn't want it set
if let accessibility = accessibility {
keychainQueryDictionary[SecAttrAccessible] = accessibility.keychainAttrValue
}
// Set the keychain access group if defined
if let accessGroup = self.accessGroup {
keychainQueryDictionary[SecAttrAccessGroup] = accessGroup
}
// Uniquely identify the account who will be accessing the keychain
let encodedIdentifier: Data? = key.data(using: String.Encoding.utf8)
keychainQueryDictionary[SecAttrGeneric] = encodedIdentifier
keychainQueryDictionary[SecAttrAccount] = encodedIdentifier
return keychainQueryDictionary
}
}
| unlicense | b162b84ba4dcc7a659ab121a9b0e86e9 | 48.150901 | 239 | 0.696284 | 5.424559 | false | false | false | false |
zullevig/ZAStyles | ZAStyles/UIProgressView+ZAStyles.swift | 1 | 1235 | //
// UIProgressView+ZAStyles.swift
// ZAStyles
//
// Created by Zachary Ullevig on 7/11/15.
// Copyright (c) 2015 Zachary Ullevig. All rights reserved.
//
import UIKit
// buttons have a couple unique styles to apply at the UIButton class level
extension UIProgressView {
override func applyStyle() {
super.applyStyle()
if let styles = self.assignedSyles() {
for styleDictionary:[ZASStyleKeys:Any] in styles {
processStyleDictionary(styleDictionary)
}
}
}
override func clearStyle() {
super.clearStyle()
self.trackTintColor = UIColor(hexColor: ZASSystemBlueHexColor)
self.progressTintColor = UIColor.clearColor()
}
// TODO: if this can be made an override without getting a not yet supported error, the applyStyle method can be collapsed into the superclass
private func processStyleDictionary(styleDictionary:[ZASStyleKeys:Any]) {
if let tintColor:HexColor = styleDictionary[ZASStyleKeys.TintColor] as? HexColor {
self.trackTintColor = UIColor(hexColor: tintColor)
}
if let progressTintColor:HexColor = styleDictionary[ZASStyleKeys.ProgressTintColor] as? HexColor {
self.progressTintColor = UIColor(hexColor: progressTintColor)
}
}
}
| mit | 01557c7e916cb00dedc83c5d7fb6c39a | 27.72093 | 143 | 0.728745 | 3.996764 | false | false | false | false |
oguntli/swift-grant-o-meter | Sources/libgrumpy/Models/Users.swift | 2 | 4065 | //
// Copyright 2016-2017 Oliver Guntli
//
// 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 Vapor
import Fluent
import Foundation
import Turnstile
import TurnstileCrypto
import Auth
/// MARK: User
public final class User: Model, Auth.User {
public var id: Node?
var userName: Valid<OnlyAlphanumeric>
var eMail: Valid<Email>
var password: String
var lastActive: Double
var token: String?
var expiration: Double?
var failedLogins: Int?
var ip: String?
public var exists: Bool = false
/// Init from node
public init(node: Node, in context: Context) throws {
id = node["id"]
let userNameString = try node.extract("user_name") as String
userName = try userNameString.validated()
let eMailString = try node.extract("email") as String
eMail = try eMailString.validated()
password = try node.extract("password") as String
lastActive = try node.extract("last_active")
token = try node.extract("token")
expiration = try node.extract("expiration")
failedLogins = try node.extract("failed_logins")
ip = try node.extract("ip")
}
/// Initialize the user with a username, email address and a password.
/// Note: the parameters are validated prior to create a user.
public init(username: String, email: String, rawPassword: String) throws {
// Generate a salt for the password
let date = Date()
self.userName = try username.validated()
self.eMail = try email.validated()
let validatedPassword: Valid<PasswordValidator> = try rawPassword.validated()
// salt the password
self.password = BCrypt.hash(password: validatedPassword.value, salt: BCryptSalt.init())
self.lastActive = date.doubleSince1970()
}
public func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"user_name": userName.value,
"email": eMail.value,
"password": password,
"last_active": lastActive,
"token": token,
"expiration": expiration,
"failed_logins": failedLogins,
])
}
public static func prepare(_ database: Database) throws {
try database.create("users") { users in
users.id()
users.string("user_name")
users.string("email")
users.string("password")
users.double("last_active")
users.string("token", optional: true)
users.double("expiration", optional: true)
users.int("failed_logins", optional: true)
users.string("ip", optional: true)
}
}
public static func revert(_ database: Database) throws {
try database.delete("users")
}
/// Registers a new user
/// - parameter name: The desired username
/// - parameter email: Email address
/// - parameter rawPassword: the password
/// - returns: The newly created user
public static func register(name: String, email: String, rawPassword: String) throws -> User {
var newUser = try User(username: name, email: email, rawPassword: rawPassword)
if try User.query().filter("user_name", newUser.userName.value).first() == nil {
try newUser.save()
return newUser
} else {
throw AccountTakenError()
}
}
}
extension User {
/// MARK: relations children
/// Returns the grumpiness of each user
public func posts() throws -> Children<GrumpyMeasurement> {
return children()
}
/// Returns the user found by name.
public static func find(by name: String) throws -> User {
guard let u = try User.query().filter("user_name", name).first() else {
throw Abort.badRequest
}
return u
}
}
| mpl-2.0 | e8024cff8a9a125bcad290ef1d963779 | 32.595041 | 98 | 0.6123 | 4.418478 | false | false | false | false |
LoopKit/LoopKit | LoopKit/GlucoseValue.swift | 1 | 3169 | //
// GlucoseValue.swift
// LoopKit
//
// Created by Nathan Racklyeft on 3/2/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import HealthKit
public protocol GlucoseValue: SampleValue {
}
public struct SimpleGlucoseValue: Equatable, GlucoseValue {
public let startDate: Date
public let endDate: Date
public let quantity: HKQuantity
public init(startDate: Date, endDate: Date? = nil, quantity: HKQuantity) {
self.startDate = startDate
self.endDate = endDate ?? startDate
self.quantity = quantity
}
public init(_ glucoseValue: GlucoseValue) {
self.startDate = glucoseValue.startDate
self.endDate = glucoseValue.endDate
self.quantity = glucoseValue.quantity
}
}
extension SimpleGlucoseValue: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.startDate = try container.decode(Date.self, forKey: .startDate)
self.endDate = try container.decode(Date.self, forKey: .endDate)
self.quantity = HKQuantity(unit: HKUnit(from: try container.decode(String.self, forKey: .quantityUnit)),
doubleValue: try container.decode(Double.self, forKey: .quantity))
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(startDate, forKey: .startDate)
try container.encode(endDate, forKey: .endDate)
try container.encode(quantity.doubleValue(for: .milligramsPerDeciliter), forKey: .quantity)
try container.encode(HKUnit.milligramsPerDeciliter.unitString, forKey: .quantityUnit)
}
private enum CodingKeys: String, CodingKey {
case startDate
case endDate
case quantity
case quantityUnit
}
}
public struct PredictedGlucoseValue: Equatable, GlucoseValue {
public let startDate: Date
public let quantity: HKQuantity
public init(startDate: Date, quantity: HKQuantity) {
self.startDate = startDate
self.quantity = quantity
}
}
extension PredictedGlucoseValue: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.startDate = try container.decode(Date.self, forKey: .startDate)
self.quantity = HKQuantity(unit: HKUnit(from: try container.decode(String.self, forKey: .quantityUnit)),
doubleValue: try container.decode(Double.self, forKey: .quantity))
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(startDate, forKey: .startDate)
try container.encode(quantity.doubleValue(for: .milligramsPerDeciliter), forKey: .quantity)
try container.encode(HKUnit.milligramsPerDeciliter.unitString, forKey: .quantityUnit)
}
private enum CodingKeys: String, CodingKey {
case startDate
case quantity
case quantityUnit
}
}
extension HKQuantitySample: GlucoseValue { }
| mit | 102558af0cbb3ce0ad02afd94d178342 | 33.813187 | 112 | 0.688131 | 4.665685 | false | false | false | false |
ifels/swiftDemo | DragDropGridviewDemo/DragDropGridviewDemo/gridview/ReorderableView.swift | 1 | 3633 | //
// ReorderableView.swift
// mdx-audio
//
// Created by ifels on 2016/11/14.
// Copyright © 2016年 ifels. All rights reserved.
//
import Foundation
import UIKit
class ReorderableView: UIView, UIGestureRecognizerDelegate {
// MARK: Properties
var delegate: Reorderable! = nil
var pan: UIPanGestureRecognizer?
var gridPosition: GridPosition?
var curScale: CGFloat = 1.0
let animationDuration: TimeInterval = 0.2
let reorderModeScale: CGFloat = 1.1
let reorderModeAlpha: CGFloat = 0.6
var isReordering : Bool = false {
didSet {
if isReordering {
startReorderMode()
} else {
endReorderMode()
}
}
}
// MARK: Lifecycle
convenience init (x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) {
self.init (frame: CGRect (x: x, y: y, width: w, height: h))
}
override init(frame: CGRect) {
super.init(frame: frame)
let doubleTap = UITapGestureRecognizer (target: self, action: #selector(ReorderableView.doubleTapped(_:)))
doubleTap.numberOfTapsRequired = 1
doubleTap.numberOfTouchesRequired = 1
doubleTap.delegate = self
self.addGestureRecognizer(doubleTap)
let longPress = UILongPressGestureRecognizer (target: self, action: #selector(ReorderableView.longPressed(_:)))
longPress.numberOfTouchesRequired = 1
longPress.delegate = self
self.addGestureRecognizer(longPress)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Animations
func startReorderMode () {
addPan()
superview?.bringSubview(toFront: self)
UIView.animate(withDuration: animationDuration, animations: { () -> Void in
self.alpha = self.reorderModeAlpha
self.setScale(self.reorderModeScale, y: self.reorderModeScale, z: self.reorderModeScale)
self.curScale = self.reorderModeScale
})
}
func endReorderMode () {
UIView.animate(withDuration: animationDuration, animations: { () -> Void in
self.alpha = 1
self.setScale(1, y: 1, z: 1)
self.curScale = 1.0
}, completion: { finished -> Void in
self.removePan()
})
}
// MARK: Gestures
func addPan () {
pan = UIPanGestureRecognizer (target: self, action: #selector(ReorderableView.pan(_:)))
self.addGestureRecognizer(pan!)
}
func removePan () {
self.removeGestureRecognizer(pan!)
}
func longPressed (_ gesture: UITapGestureRecognizer) {
if isReordering { return } else { isReordering = true }
delegate?.didReorderStartedForView(self)
}
func doubleTapped (_ gesture: UITapGestureRecognizer) {
isReordering = !isReordering
if isReordering {
delegate?.didReorderStartedForView(self)
}
}
func pan (_ gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .ended:
isReordering = false
delegate.didReorderEndForView(self, pan: pan!)
case .changed:
delegate.didReorderedView(self, pan: pan!)
default:
return
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
}
| apache-2.0 | 43d9be506d6e0172bce5a8af42ac6084 | 28.04 | 157 | 0.6 | 4.938776 | false | false | false | false |
AnneBlair/Aphrodite | Aphrodite/ChainSet.swift | 1 | 3106 | //
// ChainSet.swift
// Aphrodite
//
// Created by AnneBlair on 2017/11/2.
// Copyright © 2017年 blog.aiyinyu.com. All rights reserved.
//
import Foundation
fileprivate enum ListNode<Element> {
case end
indirect case node(Element, next: ListNode<Element>)
func cons(_ x: Element) -> ListNode<Element> {
return .node(x, next: self)
}
}
public struct ListIndex<Element>: CustomStringConvertible {
fileprivate let node: ListNode<Element>
fileprivate let tag: Int
public var description: String {
return "ListIndex((\(tag))"
}
}
extension ListIndex: Comparable {
public static func == <T>(lhs: ListIndex<T>,rhs: ListIndex<T>) -> Bool {
return lhs.tag == rhs.tag
}
public static func <<T>(lhs: ListIndex<T>,rhs: ListIndex<T>) -> Bool {
return lhs.tag > rhs.tag
}
}
public struct List<Element>: Collection {
public typealias Index = ListIndex<Element>
public let startIndex: Index
public let endIndex: Index
public subscript(position: Index) -> Element {
switch position.node {
case .end: fatalError("Subscript out of range")
case let .node(x, _): return x
}
}
public func index(after idx: Index) -> Index {
switch idx.node {
case .end: fatalError("Subscript out of range")
case let .node(_, next): return Index(node: next, tag: idx.tag - 1)
}
}
}
extension List: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Element...) {
startIndex = ListIndex(node: elements.reversed().reduce(.end) {
partiaList, element in
partiaList.cons(element)
}, tag: elements.count)
endIndex = ListIndex(node: .end, tag: 0)
}
}
extension List: CustomStringConvertible {
public var description: String {
let elements = self.map { String(describing: $0) }.joined(separator: ",")
return "List:(\(elements))"
}
}
extension List {
public var count: Int {
return startIndex.tag - endIndex.tag
}
}
extension List {
public subscript(bounds: Range<Index>) -> List<Element> {
return List(startIndex: bounds.lowerBound, endIndex: bounds.upperBound)
}
}
public struct APrefixIterator<Base: Collection>: IteratorProtocol, Sequence {
let base: Base
var offect: Base.Index
init(_ base: Base) {
self.base = base
self.offect = base.startIndex
}
mutating public func next() -> Base.SubSequence? {
guard offect != base.endIndex else { return nil }
return base.prefix(upTo: offect)
}
}
extension List {
public func reversed() -> List<Element> {
let reversedNodes: ListNode<Element> = self.reduce(.end) { $0.cons($1) }
return List(startIndex: ListIndex(node: reversedNodes, tag: self.count), endIndex: ListIndex(node: .end, tag: 0))
}
}
public extension BidirectionalCollection {
public var last: Iterator.Element? {
return isEmpty ? nil: self[index(before: endIndex)]
}
}
| mit | 7b8fdc425087b1a30f4436e707b309a6 | 24.227642 | 121 | 0.621979 | 4.009044 | false | false | false | false |
tempestrock/CarPlayer | CarPlayer/MainViewController.swift | 1 | 12899 | //
// ViewController.swift
// CarPlayer
//
// Created by Peter Störmer on 21.11.14.
// Copyright (c) 2014 Tempest Rock Studios. All rights reserved.
//
import UIKit
import MediaPlayer
class MainViewController: BasicViewController, UIScrollViewDelegate {
required init?(coder aDecoder: NSCoder) {
// Call superclass initializer:
super.init(coder: aDecoder)
} // init
//
// The initializing function that is called as soon as the view has finished loading
//
override func viewDidLoad() {
super.viewDidLoad()
// DEBUG print("MainViewController.viewDidLoad()")
// Tell the controller about this:
_controller.setCurrentlyVisibleView(self)
view.backgroundColor = UIColor.blackColor()
// Set a notification for the case that the app is closed an opened later:
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(MainViewController.handleApplicationDidBecomeActiveNotification(_:)),
name: UIApplicationDidBecomeActiveNotification, // name: UIApplicationWillEnterForegroundNotification,
object: nil)
// Create the actual main view.
createMainView()
// Just for debugging:
// DEBUG let wakeyTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "sayHi", userInfo: nil, repeats: true)
}
//
// DEBUG function
//
func sayHi() {
print("Still awake!")
}
//
// Creates all the stuff that is necessary for the nice main view.
//
func createMainView() {
// Create the two main parts of the view, i.e., the scrollview and the letter line:
createScrollview()
createLetterLine()
}
//
// This handler is called whenever this view becomes visible.
//
override func viewDidAppear(animated: Bool) {
// DEBUG print("MainViewController.viewDidAppear()")
// Tell the controller about this:
_controller.setCurrentlyVisibleView(self)
}
//
// Handles a notification of the app being (re-)opened.
//
func handleApplicationDidBecomeActiveNotification(notification: NSNotification) {
// DEBUG print("MainViewController.handleApplicationDidBecomeActiveNotification()")
_controller.checkIfMusicIsPlaying()
checkWhetherToJumpToPlayerView()
}
//
// Checks whether the view should jump directly to the player view.
// This function is called whenever the app is started or restarted.
//
func checkWhetherToJumpToPlayerView() {
// DEBUG print("MainViewController.checkWhetherToJumpToPlayerView()")
if _controller.musicPlayerIsPlaying() {
let visbileViewTitle = _controller.currentlyVisibleView().title!
// Find out whether or not we're already in the player view:
if visbileViewTitle == MyBasics.nameOfPlayerView {
// We are at the right place already.
return
}
// Store in the contoller the information that a direct jump to the player is intended:
_controller.setFlagOfDirectJump()
if visbileViewTitle == MyBasics.nameOfMainView {
// Switch over to the player view using the respective segue:
performSegueWithIdentifier(MyBasics.nameOfSegue_mainToPlayer, sender: self)
} else {
if visbileViewTitle == MyBasics.nameOfAlbumView {
// Tell the album view controller to switch to the player view (this often doesn't work):
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let albumView = storyboard.instantiateViewControllerWithIdentifier(MyBasics.nameOfAlbumView) as! AlbumViewController
albumView.performSegueWithIdentifier(MyBasics.nameOfSegue_albumToPlayer, sender: albumView)
} else {
print("MainViewController.checkWhetherToJumpToPlayerView(): Unknown visible view \"\(visbileViewTitle)\".")
}
}
} else {
// DEBUG print("--> Nope.")
}
}
//
// Creates the scrollview with all the artist buttons on it.
//
func createScrollview() {
// DEBUG print("MainViewController.createScrollview(): Starting")
let widthOfEntry = MyBasics.ArtWork_Width
let heightOfEntry = MyBasics.ArtWork_Height
let heightOfLabel = MyBasics.ArtWork_LabelHeight
let yPos = MyBasics.ArtWork_YPos
var xPos = MyBasics.ArtWork_InitialXPos
let xGap = MyBasics.ArtWork_InitialXPos
var previousLetter: Character = "Z"
for artistShortName in _controller.sortedArtistShortNames() {
// DEBUG print("artistShortName: \"\(artistShortName)\".")
// Get the long version of the short artist name:
let artistLongName = _controller.longArtistName(artistShortName)
// Get the first letter out of the artist name:
let firstLetter = Array(artistShortName.characters)[0] as Character
if firstLetter != previousLetter {
// The found letter is different to the on of the previous artist name.
// --> Store the position of the found letter.
_letterToPos[firstLetter] = CGFloat(xPos-10)
// DEBUG let tmp = _letterToPos[firstLetter]
// DEBUG print("Setting pos of \(firstLetter) to \(tmp)")
previousLetter = firstLetter
}
// Make a button:
// let button = UIButtonWithFeatures.buttonWithType(UIButtonType.System)
let button = UIButtonWithFeatures(type: UIButtonType.System)
button.frame = CGRect(x: xPos, y: yPos, width: widthOfEntry, height: heightOfEntry)
let albumArtwork: MPMediaItemArtwork?? = _controller.artwork(artistLongName)
if (albumArtwork != nil) && (albumArtwork! != nil) {
// An image for the artist does exist.
let sizeOfArtistImage = CGSize(width: albumArtwork!!.imageCropRect.width,
height: albumArtwork!!.imageCropRect.height)
// var uiImage = albumArtwork!.imageWithSize(sizeOfArtistImage)
button.setBackgroundImage(albumArtwork!!.imageWithSize(sizeOfArtistImage), forState: .Normal)
button.setBackgroundImage(albumArtwork!!.imageWithSize(sizeOfArtistImage), forState: .Highlighted)
} else {
// Create some colorful button as no artwork exists.
button.backgroundColor = UIColor.randomDarkColor()
button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
button.titleLabel!.font = MyBasics.fontForHugeText
button.setTitle(">", forState: UIControlState.Normal)
}
// Create the caption to be used under the button:
let numberOfAlbums = _controller.numberOfAlbumsForArtist(artistLongName)
let numberOfTracks = _controller.numberOfTracksForArtist(artistLongName)
let artistCaption = artistLongName + " (" +
((numberOfAlbums > 1) ? (numberOfAlbums.description + ", ") : "") +
numberOfTracks.description + ")"
// DEBUG print("\(artistCaption)")
// Create a label underneath the button that shows the artist name and the number of albums:
let artistLabel = UILabel()
artistLabel.text = artistCaption
artistLabel.frame = CGRect(x: xPos, y: yPos + heightOfEntry, width: widthOfEntry, height: heightOfLabel)
artistLabel.textAlignment = NSTextAlignment.Center
artistLabel.textColor = UIColor.whiteColor()
artistLabel.font = MyBasics.fontForVerySmallText
_scrollView.addSubview(artistLabel)
button.setArtistName(artistLongName)
button.addTarget(self, action: #selector(MainViewController.buttonPressed(_:)), forControlEvents: .TouchUpInside)
_scrollView.addSubview(button)
xPos += (widthOfEntry + xGap)
// Adjust the size of the scroll view:
_scrollView.contentSize = CGSizeMake(CGFloat(xPos), CGFloat(heightOfEntry/2))
}
// Scroll to some random place initially:
let initialXPos = Int(arc4random_uniform(UInt32(xPos - MyBasics.screenWidth)))
_scrollView.contentOffset = CGPoint(x: initialXPos, y: 0)
// DEBUG print("MainViewController.createScrollview(): Finished")
}
//
// Handles the event of an artist name tapped.
//
func buttonPressed(button: UIButtonWithFeatures!) {
_controller.setCurrentArtist(button.artistName())
// Animate the pressed button and switch over to the album view:
UIView.animateSlightShrink(
button,
completion: { finished in
// Switch over to the album view:
self.performSegueWithIdentifier(MyBasics.nameOfSegue_mainToAlbum, sender: self)
})
}
//
// This function is called shortly before a switch from this view to another.
//
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// DEBUG print("MainViewController.prepareForSegue()")
if segue.identifier == MyBasics.nameOfSegue_mainToAlbum {
// DEBUG print("MainView --> AlbumView")
// this gets a reference to the screen that we're about to transition to
let albumView = segue.destinationViewController as! AlbumViewController
// Instead of using the default transition animation, we'll ask
// the segue to use our custom TransitionManager object to manage the transition animation:
albumView.transitioningDelegate = _rotatingTransition
} else if segue.identifier == MyBasics.nameOfSegue_mainToPlayer {
// DEBUG print("MainView --> PlayerView")
// this gets a reference to the screen that we're about to transition to
let playerView = segue.destinationViewController as! PlayerViewController
// Instead of using the default transition animation, we'll ask
// the segue to use our custom TransitionManager object to manage the transition animation:
playerView.transitioningDelegate = _rotatingTransition
} else if segue.identifier == MyBasics.nameOfSegue_mainToSpeed {
// We are switching to the speed view.
// Tell the speed view which background color to take and keep the background color setter in mind for later updates:
let speedView = segue.destinationViewController as! SpeedViewController
speedView.setBackgroundColor(UIColor.darkBlueColor())
// Animate the transition from this view to the speed view and tell the speed view which swipe leads back to this view:
_slidingTransition.setDirectionToStartWith(TransitionManager_Sliding.DirectionToStartWith.Down)
speedView.setDirectionToSwipeBack(SpeedViewController.DirectionToSwipeBack.Up)
speedView.transitioningDelegate = _slidingTransition
}
}
//
// This handler is called when the user has swiped up on the main view.
// If music is currently playing, this leady to the PlayerViewController.
//
@IBAction func userHasSwipedUp(sender: UISwipeGestureRecognizer) {
if !_controller.nowPlayingItemExists() {
// Nothing to be done here.
return
}
// Store in the contoller the information that a direct jump to the player is intended:
_controller.setFlagOfDirectJump()
// Switch over to the player view:
performSegueWithIdentifier(MyBasics.nameOfSegue_mainToPlayer, sender: self)
}
//
// Handles the user's down-swiping and switches to the speed view.
//
@IBAction func userHasSwipedDown(sender: UISwipeGestureRecognizer) {
// Switch over to the speed view:
performSegueWithIdentifier(MyBasics.nameOfSegue_mainToSpeed, sender: self)
}
//
// This handler is called whenever someone is getting back to this view ("Exit")
//
@IBAction func unwindToViewController (sender: UIStoryboardSegue){
// print("MainViewController.unwindToViewController()")
}
//
// Handles the users pinching which changes the brightness of the screen.
//
@IBAction func userHasPinched(sender: UIPinchGestureRecognizer) {
_controller.setBrightness(sender.scale)
}
}
| gpl-3.0 | a358955158e3c479e93c6f6f9e9b4784 | 35.435028 | 140 | 0.641882 | 5.260196 | false | false | false | false |
leoru/Brainstorage | Brainstorage-iOS/Vendor/SwiftLoader/SwiftLoader.swift | 1 | 9814 | //
// BSLoader.swift
// Brainstorage
//
// Created by Kirill Kunst on 07.02.15.
// Copyright (c) 2015 Kirill Kunst. All rights reserved.
//
import UIKit
import QuartzCore
import CoreGraphics
let loaderSpinnerMarginSide : CGFloat = 35.0
let loaderSpinnerMarginTop : CGFloat = 20.0
let loaderTitleMargin : CGFloat = 5.0
class SwiftLoader: UIView {
private var coverView : UIView?
private var titleLabel : UILabel?
private var loadingView : SwiftLoadingView?
private var animated : Bool?
private var canUpdated = false
private var title: String?
private var config : Config = Config() {
didSet {
self.loadingView?.config = config
}
}
override var frame : CGRect {
didSet {
self.update()
}
}
class var sharedInstance: SwiftLoader {
struct Singleton {
static let instance = SwiftLoader(frame: CGRectMake(0,0,Config().size,Config().size))
}
return Singleton.instance
}
class func show(#animated: Bool) {
self.show(title: nil, animated: animated)
}
class func show(#title: String?, animated : Bool) {
var currentWindow : UIWindow = UIApplication.sharedApplication().keyWindow!
let loader = SwiftLoader.sharedInstance
loader.canUpdated = true
loader.animated = animated
loader.title = title
loader.update()
var height : CGFloat = UIScreen.mainScreen().bounds.size.height
var width : CGFloat = UIScreen.mainScreen().bounds.size.width
var center : CGPoint = CGPointMake(width / 2.0, height / 2.0)
loader.center = center
loader.coverView = UIView(frame: currentWindow.bounds)
loader.coverView?.backgroundColor = UIColor.clearColor()
if (loader.superview == nil) {
currentWindow.addSubview(loader.coverView!)
currentWindow.addSubview(loader)
loader.start()
} else {
loader.coverView?.removeFromSuperview()
}
}
class func hide() {
let loader = SwiftLoader.sharedInstance
loader.stop()
}
class func setConfig(config : Config) {
let loader = SwiftLoader.sharedInstance
loader.config = config
loader.frame = CGRectMake(0,0,loader.config.size,loader.config.size)
}
/**
Private methods
*/
private func setup() {
self.alpha = 0
self.update()
}
private func start() {
self.loadingView?.start()
if (self.animated!) {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.alpha = 1
}, completion: { (finished) -> Void in
});
} else {
self.alpha = 1
}
}
private func stop() {
if (self.animated!) {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.alpha = 0
}, completion: { (finished) -> Void in
self.removeFromSuperview()
self.coverView?.removeFromSuperview()
self.loadingView?.stop()
});
} else {
self.alpha = 0
self.removeFromSuperview()
self.coverView?.removeFromSuperview()
self.loadingView?.stop()
}
}
private func update() {
self.backgroundColor = self.config.backgroundColor
self.layer.cornerRadius = self.config.cornerRadius
var loadingViewSize = self.frame.size.width - (loaderSpinnerMarginSide * 2)
if (self.loadingView == nil) {
self.loadingView = SwiftLoadingView(frame: self.frameForSpinner())
self.addSubview(self.loadingView!)
} else {
self.loadingView?.frame = self.frameForSpinner()
}
if (self.titleLabel == nil) {
self.titleLabel = UILabel(frame: CGRectMake(loaderTitleMargin, loaderSpinnerMarginTop + loadingViewSize, self.frame.width - loaderTitleMargin*2, 42.0))
self.addSubview(self.titleLabel!)
self.titleLabel?.numberOfLines = 1
self.titleLabel?.textAlignment = NSTextAlignment.Center
self.titleLabel?.adjustsFontSizeToFitWidth = true
} else {
self.titleLabel?.frame = CGRectMake(loaderTitleMargin, loaderSpinnerMarginTop + loadingViewSize, self.frame.width - loaderTitleMargin*2, 42.0)
}
self.titleLabel?.font = self.config.titleTextFont
self.titleLabel?.textColor = self.config.titleTextColor
self.titleLabel?.text = self.title
self.titleLabel?.hidden = self.title == nil
}
func frameForSpinner() -> CGRect {
var loadingViewSize = self.frame.size.width - (loaderSpinnerMarginSide * 2)
if (self.title == nil) {
var yOffset = (self.frame.size.height - loadingViewSize) / 2
return CGRectMake(loaderSpinnerMarginSide, yOffset, loadingViewSize, loadingViewSize)
}
return CGRectMake(loaderSpinnerMarginSide, loaderSpinnerMarginTop, loadingViewSize, loadingViewSize)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
* Loader View
*/
class SwiftLoadingView : UIView {
private var lineWidth : Float?
private var lineTintColor : UIColor?
private var backgroundLayer : CAShapeLayer?
private var isSpinning : Bool?
private var config : Config = Config() {
didSet {
self.update()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
Setup loading view
*/
private func setup() {
self.backgroundColor = UIColor.clearColor()
self.lineWidth = fmaxf(Float(self.frame.size.width) * 0.025, 1)
self.backgroundLayer = CAShapeLayer()
self.backgroundLayer?.strokeColor = self.config.spinnerColor.CGColor
self.backgroundLayer?.fillColor = self.backgroundColor?.CGColor
self.backgroundLayer?.lineCap = kCALineCapRound
self.backgroundLayer?.lineWidth = CGFloat(self.lineWidth!)
self.layer.addSublayer(self.backgroundLayer!)
}
private func update() {
self.lineWidth = self.config.spinnerLineWidth
self.backgroundLayer?.lineWidth = CGFloat(self.lineWidth!)
self.backgroundLayer?.strokeColor = self.config.spinnerColor.CGColor
}
/**
Draw Circle
*/
override func drawRect(rect: CGRect) {
self.backgroundLayer?.frame = self.bounds
}
private func drawBackgroundCircle(partial : Bool) {
var startAngle : CGFloat = CGFloat(M_PI) / CGFloat(2.0)
var endAngle : CGFloat = (2.0 * CGFloat(M_PI)) + startAngle
var center : CGPoint = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2)
var radius : CGFloat = (CGFloat(self.bounds.size.width) - CGFloat(self.lineWidth!)) / CGFloat(2.0)
var processBackgroundPath : UIBezierPath = UIBezierPath()
processBackgroundPath.lineWidth = CGFloat(self.lineWidth!)
if (partial) {
endAngle = (1.8 * CGFloat(M_PI)) + startAngle
}
processBackgroundPath.addArcWithCenter(center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
self.backgroundLayer?.path = processBackgroundPath.CGPath;
}
/**
Start and stop spinning
*/
private func start() {
self.isSpinning? = true
self.drawBackgroundCircle(true)
var rotationAnimation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(double: M_PI * 2.0)
rotationAnimation.duration = 1;
rotationAnimation.cumulative = true;
rotationAnimation.repeatCount = HUGE;
self.backgroundLayer?.addAnimation(rotationAnimation, forKey: "rotationAnimation")
}
private func stop() {
self.drawBackgroundCircle(false)
self.backgroundLayer?.removeAllAnimations()
self.isSpinning? = false
}
}
/**
* Loader config
*/
struct Config {
/**
* Size of loader
*/
var size : CGFloat = 120.0
/**
* Color of spinner view
*/
var spinnerColor = UIColor.blackColor()
/**
* S
*/
var spinnerLineWidth :Float = 1.0
/**
* Color of title text
*/
var titleTextColor = UIColor.blackColor()
/**
* Font for title text in loader
*/
var titleTextFont : UIFont = UIFont.boldSystemFontOfSize(16.0)
/**
* Background color for loader
*/
var backgroundColor = UIColor.whiteColor()
/**
* Corner radius for loader
*/
var cornerRadius : CGFloat = 10.0
}
}
| mit | c67ff315a11bc445d3d8aea4a1f12d52 | 30.155556 | 163 | 0.564398 | 5.132845 | false | true | false | false |
hfutrell/BezierKit | BezierKit/Library/CubicCurve.swift | 1 | 11989 | //
// CubicCurve.swift
// BezierKit
//
// Created by Holmes Futrell on 10/28/16.
// Copyright © 2016 Holmes Futrell. All rights reserved.
//
#if canImport(CoreGraphics)
import CoreGraphics
#endif
import Foundation
/**
Cubic Bézier Curve
*/
public struct CubicCurve: NonlinearBezierCurve, Equatable {
public var p0, p1, p2, p3: CGPoint
public var points: [CGPoint] {
return [p0, p1, p2, p3]
}
public var order: Int {
return 3
}
public var startingPoint: CGPoint {
get {
return p0
}
set(newValue) {
p0 = newValue
}
}
public var endingPoint: CGPoint {
get {
return p3
}
set(newValue) {
p3 = newValue
}
}
// MARK: - Initializers
public init(points: [CGPoint]) {
precondition(points.count == 4)
self.p0 = points[0]
self.p1 = points[1]
self.p2 = points[2]
self.p3 = points[3]
}
public init(p0: CGPoint, p1: CGPoint, p2: CGPoint, p3: CGPoint) {
self.p0 = p0
self.p1 = p1
self.p2 = p2
self.p3 = p3
}
public init(lineSegment: LineSegment) {
let oneThird: CGFloat = 1.0 / 3.0
let twoThirds: CGFloat = 2.0 / 3.0
self.init(p0: lineSegment.p0,
p1: twoThirds * lineSegment.p0 + oneThird * lineSegment.p1,
p2: oneThird * lineSegment.p0 + twoThirds * lineSegment.p1,
p3: lineSegment.p1)
}
public init(quadratic: QuadraticCurve) {
let oneThird: CGFloat = 1.0 / 3.0
let twoThirds: CGFloat = 2.0 / 3.0
self.init(p0: quadratic.p0,
p1: twoThirds * quadratic.p1 + oneThird * quadratic.p0,
p2: oneThird * quadratic.p2 + twoThirds * quadratic.p1,
p3: quadratic.p2)
}
var downgradedToQuadratic: (quadratic: QuadraticCurve, error: CGFloat) {
let line = LineSegment(p0: self.startingPoint, p1: self.endingPoint)
let d1 = self.p1 - line.point(at: 1.0 / 3.0)
let d2 = self.p2 - line.point(at: 2.0 / 3.0)
let d = 0.5 * d1 + 0.5 * d2
let p1 = 1.5 * d + line.point(at: 0.5)
let error = 0.144334 * (d1 - d2).length
let quadratic = QuadraticCurve(p0: line.startingPoint,
p1: p1,
p2: line.endingPoint)
return (quadratic: quadratic, error: error)
}
var downgradedToLineSegment: (lineSegment: LineSegment, error: CGFloat) {
let line = LineSegment(p0: self.startingPoint, p1: self.endingPoint)
let d1 = self.p1 - line.point(at: 1.0 / 3.0)
let d2 = self.p2 - line.point(at: 2.0 / 3.0)
let dmaxx = max(d1.x * d1.x, d2.x * d2.x)
let dmaxy = max(d1.y * d1.y, d2.y * d2.y)
let error = 3 / 4 * sqrt(dmaxx + dmaxy)
return (lineSegment: line, error: error)
}
/**
Returns a CubicCurve which passes through three provided points: a starting point `start`, and ending point `end`, and an intermediate point `mid` at an optional t-value `t`.
- parameter start: the starting point of the curve
- parameter end: the ending point of the curve
- parameter mid: an intermediate point falling on the curve
- parameter t: optional t-value at which the curve will pass through the point `mid` (default = 0.5)
- parameter d: optional strut length with the full strut being length d * (1-t)/t. If omitted or `nil` the distance from `mid` to the baseline (line from `start` to `end`) is used.
*/
public init(start: CGPoint, end: CGPoint, mid: CGPoint, t: CGFloat = 0.5, d: CGFloat? = nil) {
let s = start
let b = mid
let e = end
let oneMinusT = 1.0 - t
let abc = Utils.getABC(n: 3, S: s, B: b, E: e, t: t)
let d1 = d ?? distance(b, abc.C)
let d2 = d1 * oneMinusT / t
let selen = distance(start, end)
let l = (1.0 / selen) * (e - s)
let b1 = d1 * l
let b2 = d2 * l
// derivation of new hull coordinates
let e1 = b - b1
let e2 = b + b2
let A = abc.A
let v1 = A + (e1 - A) / oneMinusT
let v2 = A + (e2 - A) / t
let nc1 = s + (v1 - s) / t
let nc2 = e + (v2 - e) / oneMinusT
// ...done
self.init(p0: s, p1: nc1, p2: nc2, p3: e)
}
// MARK: -
public var simple: Bool {
guard p0 != p1 || p1 != p2 || p2 != p3 else { return true }
let a1 = Utils.angle(o: self.p0, v1: self.p3, v2: self.p1)
let a2 = Utils.angle(o: self.p0, v1: self.p3, v2: self.p2)
if a1>0 && a2<0 || a1<0 && a2>0 {
return false
}
let n1 = self.normal(at: 0)
let n2 = self.normal(at: 1)
let s = Utils.clamp(n1.dot(n2), -1.0, 1.0)
let angle: CGFloat = CGFloat(abs(acos(Double(s))))
return angle < (CGFloat.pi / 3.0)
}
public func normal(at t: CGFloat) -> CGPoint {
var d = self.derivative(at: t)
if d == CGPoint.zero, t == 0.0 || t == 1.0 {
if t == 0.0 {
d = p2 - p0
} else {
d = p3 - p1
}
if d == CGPoint.zero {
d = p3 - p0
}
}
return d.perpendicular.normalize()
}
public func derivative(at t: CGFloat) -> CGPoint {
let mt: CGFloat = 1-t
let k: CGFloat = 3
let p0 = k * (self.p1 - self.p0)
let p1 = k * (self.p2 - self.p1)
let p2 = k * (self.p3 - self.p2)
let a = mt*mt
let b = mt*t*2
let c = t*t
// making the final sum one line of code makes XCode take forever to compiler! Hence the temporary variables.
let temp1 = a*p0
let temp2 = b*p1
let temp3 = c*p2
return temp1 + temp2 + temp3
}
public func split(from t1: CGFloat, to t2: CGFloat) -> CubicCurve {
guard t1 != 0.0 || t2 != 1.0 else { return self }
let k = (t2 - t1) / 3.0
let p0 = self.point(at: t1)
let p3 = self.point(at: t2)
let p1 = p0 + k * self.derivative(at: t1)
let p2 = p3 - k * self.derivative(at: t2)
return CubicCurve(p0: p0, p1: p1, p2: p2, p3: p3)
}
public func split(at t: CGFloat) -> (left: CubicCurve, right: CubicCurve) {
let h0 = self.p0
let h1 = self.p1
let h2 = self.p2
let h3 = self.p3
let h4 = Utils.linearInterpolate(h0, h1, t)
let h5 = Utils.linearInterpolate(h1, h2, t)
let h6 = Utils.linearInterpolate(h2, h3, t)
let h7 = Utils.linearInterpolate(h4, h5, t)
let h8 = Utils.linearInterpolate(h5, h6, t)
let h9 = Utils.linearInterpolate(h7, h8, t)
let leftCurve = CubicCurve(p0: h0, p1: h4, p2: h7, p3: h9)
let rightCurve = CubicCurve(p0: h9, p1: h8, p2: h6, p3: h3)
return (left: leftCurve, right: rightCurve)
}
public func project(_ point: CGPoint) -> (point: CGPoint, t: CGFloat) {
func mul(_ a: CGPoint, _ b: CGPoint) -> CGPoint {
return CGPoint(x: a.x * b.x, y: a.y * b.y)
}
let c = self.copy(using: CGAffineTransform(translationX: -point.x, y: -point.y))
let q = QuadraticCurve(p0: self.p1 - self.p0, p1: self.p2 - self.p1, p2: self.p3 - self.p2)
// p0, p1, p2, p3 form the control points of a Cubic Bezier Curve formed
// by multiplying the polynomials q and l
let p0 = 10 * mul(c.p0, q.p0)
let p1 = p0 + 4 * mul(c.p0, q.p1 - q.p0) + 6 * mul(c.p1 - c.p0, q.p0)
let dd0 = 3 * mul(c.p2 - 2 * c.p1 + c.p0, q.p0) + 6 * mul(c.p1 - c.p0, q.p1 - q.p0) + mul(c.p0, q.p2 - 2 * q.p1 + q.p0)
let p2 = 2 * p1 - p0 + dd0
//
let p5 = 10 * mul(c.p3, q.p2)
let p4 = p5 - 4 * mul(c.p3, q.p2 - q.p1) - 6 * mul(c.p3 - c.p2, q.p2)
let dd1 = 3 * mul(c.p1 - 2 * c.p2 + c.p3, q.p2) + 6 * mul(c.p3 - c.p2, q.p2 - q.p1) + mul(c.p3, q.p2 - 2 * q.p1 + q.p0)
let p3 = 2 * p4 - p5 + dd1
let lengthSquaredStart = c.p0.lengthSquared
let lengthSquaredEnd = c.p3.lengthSquared
var minimumT: CGFloat = 0.0
var minimumDistanceSquared = lengthSquaredStart
if lengthSquaredEnd < lengthSquaredStart {
minimumT = 1.0
minimumDistanceSquared = lengthSquaredEnd
}
// the roots represent the values at which the curve and its derivative are perpendicular
// ie, the dot product of c and q is equal to zero
let polynomial = BernsteinPolynomial5(b0: p0.x + p0.y,
b1: p1.x + p1.y,
b2: p2.x + p2.y,
b3: p3.x + p3.y,
b4: p4.x + p4.y,
b5: p5.x + p5.y)
for t in findDistinctRootsInUnitInterval(of: polynomial) {
guard t > 0.0, t < 1.0 else { break }
let point = c.point(at: CGFloat(t))
let distanceSquared = point.lengthSquared
if distanceSquared < minimumDistanceSquared {
minimumDistanceSquared = distanceSquared
minimumT = CGFloat(t)
}
}
return (point: self.point(at: minimumT), t: minimumT)
}
public var boundingBox: BoundingBox {
let p0: CGPoint = self.p0
let p1: CGPoint = self.p1
let p2: CGPoint = self.p2
let p3: CGPoint = self.p3
var mmin = CGPoint.min(p0, p3)
var mmax = CGPoint.max(p0, p3)
let d0 = p1 - p0
let d1 = p2 - p1
let d2 = p3 - p2
for d in 0..<CGPoint.dimensions {
let mmind = mmin[d]
let mmaxd = mmax[d]
let value1 = p1[d]
let value2 = p2[d]
guard value1 < mmind || value1 > mmaxd || value2 < mmind || value2 > mmaxd else {
continue
}
Utils.droots(d0[d], d1[d], d2[d]) {(t: CGFloat) in
guard t > 0.0, t < 1.0 else { return }
let value = self.point(at: t)[d]
if value < mmind {
mmin[d] = value
} else if value > mmaxd {
mmax[d] = value
}
}
}
return BoundingBox(min: mmin, max: mmax)
}
public func point(at t: CGFloat) -> CGPoint {
if t == 0 {
return self.p0
} else if t == 1 {
return self.p3
}
let mt = 1.0 - t
let mt2: CGFloat = mt*mt
let t2: CGFloat = t*t
let a = mt2 * mt
let b = mt2 * t * 3.0
let c = mt * t2 * 3.0
let d = t * t2
// usage of temp variables are because of Swift Compiler error 'Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub extpressions'
let temp1 = a * self.p0
let temp2 = b * self.p1
let temp3 = c * self.p2
let temp4 = d * self.p3
return temp1 + temp2 + temp3 + temp4
}
}
extension CubicCurve: Transformable {
public func copy(using t: CGAffineTransform) -> CubicCurve {
return CubicCurve(p0: self.p0.applying(t), p1: self.p1.applying(t), p2: self.p2.applying(t), p3: self.p3.applying(t))
}
}
extension CubicCurve: Reversible {
public func reversed() -> CubicCurve {
return CubicCurve(p0: self.p3, p1: self.p2, p2: self.p1, p3: self.p0)
}
}
extension CubicCurve: Flatness {
public var flatnessSquared: CGFloat {
let a: CGPoint = 3.0 * self.p1 - 2.0 * self.p0 - self.p3
let b: CGPoint = 3.0 * self.p2 - self.p0 - 2.0 * self.p3
let temp1 = max(a.x * a.x, b.x * b.x)
let temp2 = max(a.y * a.y, b.y * b.y)
return (1.0 / 16.0) * ( temp1 + temp2 )
}
}
| mit | 64ce920a626db0606de33853bc0eb117 | 33.947522 | 199 | 0.52023 | 3.150329 | false | false | false | false |
lllyyy/LY | JZLocationConverter-Swift-master(经纬度转换)/JZLocationConverterDemo/JZLocationConverter/JZLocationConverter.swift | 1 | 6305 | //
// JZLocationConverter.swift
// JZLocationConverter-Swift
//
// Created by jack zhou on 21/07/2017.
// Copyright © 2017 Jack. All rights reserved.
//
import Foundation
import CoreLocation
extension CLLocationCoordinate2D {
struct JZConstant {
static let A = 6378245.0
static let EE = 0.00669342162296594323
}
func gcj02Offset() -> CLLocationCoordinate2D {
let x = self.longitude - 105.0
let y = self.latitude - 35.0
let latitude = (-100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(fabs(x))) +
((20.0 * sin(6.0 * x * .pi) + 20.0 * sin(2.0 * x * .pi)) * 2.0 / 3.0) +
((20.0 * sin(y * .pi) + 40.0 * sin(y / 3.0 * .pi)) * 2.0 / 3.0) +
((160.0 * sin(y / 12.0 * .pi) + 320 * sin(y * .pi / 30.0)) * 2.0 / 3.0)
let longitude = (300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(fabs(x))) +
((20.0 * sin(6.0 * x * .pi) + 20.0 * sin(2.0 * x * .pi)) * 2.0 / 3.0) +
((20.0 * sin(x * .pi) + 40.0 * sin(x / 3.0 * .pi)) * 2.0 / 3.0) +
((150.0 * sin(x / 12.0 * .pi) + 300.0 * sin(x / 30.0 * .pi)) * 2.0 / 3.0)
let radLat = 1 - self.latitude / 180.0 * .pi;
var magic = sin(radLat);
magic = 1 - JZConstant.EE * magic * magic
let sqrtMagic = sqrt(magic);
let dLat = (latitude * 180.0) / ((JZConstant.A * (1 - JZConstant.EE)) / (magic * sqrtMagic) * .pi);
let dLon = (longitude * 180.0) / (JZConstant.A / sqrtMagic * cos(radLat) * .pi);
return CLLocationCoordinate2DMake(dLat, dLon);
}
}
open class JZLocationConverter {
fileprivate let queue = DispatchQueue(label: "JZ.LocationConverter.Converter")
public static let `default`: JZLocationConverter = {
return JZLocationConverter()
}()
open static func start(filePath:String!,finished:((_ error:JZFileError?) -> Void)?) {
JZAreaManager.start(filePath: filePath, finished: finished)
}
}
//GCJ02
extension JZLocationConverter {
fileprivate func gcj02Encrypt(_ wgs84Point:CLLocationCoordinate2D,result:@escaping (_ gcj02Point:CLLocationCoordinate2D) -> Void) {
self.queue.async {
let offsetPoint = wgs84Point.gcj02Offset()
let resultPoint = CLLocationCoordinate2DMake(wgs84Point.latitude + offsetPoint.latitude, wgs84Point.longitude + offsetPoint.longitude)
JZAreaManager.default.isOutOfArea(gcj02Point: resultPoint, result: { (isOut:Bool) in
DispatchQueue.main.async {
if isOut {
result(wgs84Point)
}else {
result(resultPoint)
}
}
})
}
}
fileprivate func gcj02Decrypt(_ gcj02Point:CLLocationCoordinate2D,result:@escaping (_ wgs84Point:CLLocationCoordinate2D) -> Void) {
JZAreaManager.default.isOutOfArea(gcj02Point: gcj02Point, result: { (isOut:Bool) in
if isOut {
DispatchQueue.main.async {
result(gcj02Point)
}
}else {
self.gcj02Encrypt(gcj02Point) { (mgPoint:CLLocationCoordinate2D) in
self.queue.async {
let resultPoint = CLLocationCoordinate2DMake(gcj02Point.latitude * 2 - mgPoint.latitude,gcj02Point.longitude * 2 - mgPoint.longitude)
DispatchQueue.main.async {
result(resultPoint)
}
}
}
}
})
}
}
//BD09
extension JZLocationConverter {
fileprivate func bd09Encrypt(_ gcj02Point:CLLocationCoordinate2D,result:@escaping (_ bd09Point:CLLocationCoordinate2D) -> Void) {
self.queue.async {
let x = gcj02Point.longitude
let y = gcj02Point.latitude
let z = sqrt(x * x + y * y) + 0.00002 * sin(y * .pi);
let theta = atan2(y, x) + 0.000003 * cos(x * .pi);
let resultPoint = CLLocationCoordinate2DMake(z * sin(theta) + 0.006, z * cos(theta) + 0.0065)
DispatchQueue.main.async {
result(resultPoint)
}
}
}
fileprivate func bd09Decrypt(_ bd09Point:CLLocationCoordinate2D,result:@escaping (_ gcj02Point:CLLocationCoordinate2D) -> Void) {
self.queue.async {
let x = bd09Point.longitude - 0.0065
let y = bd09Point.latitude - 0.006
let z = sqrt(x * x + y * y) - 0.00002 * sin(y * .pi);
let theta = atan2(y, x) - 0.000003 * cos(x * .pi);
let resultPoint = CLLocationCoordinate2DMake(z * sin(theta), z * cos(theta))
DispatchQueue.main.async {
result(resultPoint)
}
}
}
}
extension JZLocationConverter {
public func wgs84ToGcj02(_ wgs84Point:CLLocationCoordinate2D,result:@escaping (_ gcj02Point:CLLocationCoordinate2D) -> Void) {
self.gcj02Encrypt(wgs84Point, result: result)
}
public func wgs84ToBd09(_ wgs84Point:CLLocationCoordinate2D,result:@escaping (_ bd09Point:CLLocationCoordinate2D) -> Void) {
self.gcj02Encrypt(wgs84Point) { (gcj02Point:CLLocationCoordinate2D) in
self.bd09Encrypt(gcj02Point, result: result);
}
}
public func gcj02ToWgs84(_ gcj02Point:CLLocationCoordinate2D,result:@escaping (_ wgs84Point:CLLocationCoordinate2D) -> Void) {
self.gcj02Decrypt(gcj02Point, result: result)
}
public func gcj02ToBd09(_ gcj02Point:CLLocationCoordinate2D,result:@escaping (_ bd09Point:CLLocationCoordinate2D) -> Void) {
self.bd09Encrypt(gcj02Point, result: result);
}
public func bd09ToGcj02(_ bd09Point:CLLocationCoordinate2D,result:@escaping (_ gcj02Point:CLLocationCoordinate2D) -> Void) {
self.bd09Decrypt(bd09Point, result: result)
}
public func bd09ToWgs84(_ bd09Point:CLLocationCoordinate2D,result:@escaping (_ wgs84Point:CLLocationCoordinate2D) -> Void) {
self.bd09Decrypt(bd09Point) { (gcj02Point:CLLocationCoordinate2D) in
self.gcj02Decrypt(gcj02Point, result: result);
}
}
}
| mit | 563788072ba22d4093572863b3307c25 | 41.884354 | 157 | 0.574397 | 3.610538 | false | false | false | false |
Stamates/30-Days-of-Swift | src/Day 17 - Segue/Day 17 - Segue/ViewController.swift | 2 | 1135 | //
// ViewController.swift
// Day 17 - Segue
//
// Created by Justin Mitchel on 11/23/14.
// Copyright (c) 2014 Coding For Entrepreneurs. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var theTextField: UITextField!
@IBAction func goToPage2(sender: AnyObject) {
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "page2" {
let vc = segue.destinationViewController as PageTwoViewController
vc.newPageTitle = self.theTextField.text
} else if segue.identifier == "page3" {
let vc = segue.destinationViewController as PageTwoViewController
vc.newPageTitle = "\(self.theTextField.text) and Hi there"
}
}
}
| apache-2.0 | c3d4ba6cc43874d0b5e6d6f585b1112e | 27.375 | 81 | 0.647577 | 4.709544 | false | false | false | false |
renzifeng/ZFZhiHuDaily | ZFZhiHuDaily/Other/NetWork/ZFNetworkTool.swift | 1 | 2635 | //
// ZFNetworkTool.swift
// baiduCourse
//
// Created by 任子丰 on 15/9/13.
// Copyright © 2015年 任子丰. All rights reserved.
//
import Foundation
import Alamofire
class ZFNetworkTool: NSObject {
/**
* get方式获取数据
* url : 请求地址
* params : 传入参数
* success : 请求成功回调函数
* fail : 请求失败回调函数
*/
static func get( url : String, params :[String : AnyObject]?, success :(json : AnyObject) -> Void , fail:(error : Any) -> Void) {
let httpUrl : String = BASE_URL + url
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
if let parameters = params {
Alamofire.request(.GET, httpUrl, parameters: parameters , encoding: .JSON, headers: nil).responseJSON(completionHandler: { (response) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if let JSON = response.result.value {
success(json: JSON)
}
})
}else {
Alamofire.request(.GET, httpUrl).responseJSON { (response) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if let JSON = response.result.value {
success(json: JSON)
}
}
}
}
/**
* post方式获取数据
* url : 请求地址
* params : 传入参数
* success : 请求成功回调函数
* fail : 请求失败回调函数
*/
static func post(url : String, params : [String : AnyObject]?, success:(json : Any) -> Void , fail:(error : Any) -> Void) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let httpUrl : String = BASE_URL + url
if let parameters = params {
Alamofire.request(.POST, httpUrl, parameters: parameters, encoding: .JSON, headers: nil).responseJSON(completionHandler: { (response) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if let JSON = response.result.value {
success(json: JSON)
}
})
}else {
Alamofire.request(.POST, httpUrl).responseJSON { (response) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if let JSON = response.result.value {
success(json: JSON)
}
}
}
}
}
| apache-2.0 | 8df3d262f60d1ce7b1ecb1e63def6ba8 | 33.722222 | 156 | 0.5612 | 4.911591 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/SpeechToTextV1/WebSockets/RecognitionSettings.swift | 1 | 13787 | /**
* (C) Copyright IBM Corp. 2016, 2020.
*
* 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
/**
The settings associated with a Speech to Text recognition request. Any `nil` parameters will
use a default value provided by the Watson Speech to Text service.
For more information about the Speech to Text service parameters, visit:
https://cloud.ibm.com/docs/services/speech-to-text/input.html
*/
public struct RecognitionSettings: Codable, Equatable {
/// The action to perform. Must be `start` to begin the request.
private let action = "start"
/// The format of the audio data. Endianness is automatically detected by the Speech to Text
/// service. For more information about the supported formats, visit:
/// https://cloud.ibm.com/docs/services/speech-to-text/audio-formats.html
public var contentType: String?
/// If you specify a customization ID when you open the connection, you can use the customization
/// weight to tell the service how much weight to give to words from the custom language model
/// compared to those from the base model for the current request.
public var customizationWeight: Double?
/// The number of seconds after which the connection is to time out due to inactivity.
/// Use `-1` to set the timeout to infinity. The default is `30` seconds.
public var inactivityTimeout: Int?
/// An array of keyword strings to be matched in the input audio. By default, the service
/// does not perform any keyword spotting.
public var keywords: [String]?
/// A minimum level of confidence that the service must have to report a matching keyword
/// in the input audio. The threshold must be a probability value between `0` and `1`
/// inclusive. A match must have at least the specified confidence to be returned. If you
/// specify a valid threshold, you must also specify at least one keyword. By default, the
/// service does not perform any keyword spotting.
public var keywordsThreshold: Double?
/// The maximum number of alternative transcriptions to receive. The default is 1.
public var maxAlternatives: Int?
/// If `true`, then interim results (i.e. results that are not final) will be received
/// for the transcription. The default is `false`.
public var interimResults: Bool?
/// A minimum level of confidence that the service must have to report a hypothesis for a
/// word from the input audio. The threshold must be a probability value between `0` and `1`
/// inclusive. A hypothesis must have at least the specified confidence to be returned as a
/// word alternative. By default, the service does not return any word alternatives.
public var wordAlternativesThreshold: Double?
/// If `true`, then a confidence score will be received for each word of the transcription.
/// The default is `false`.
public var wordConfidence: Bool?
/// If `true`, then per-word start and end times relative to the beginning of the audio will
/// be received. The default is `false`.
public var timestamps: Bool?
/// If `true`, then profanity will be censored from the service's output, obscuring each
/// occurrence with a set of asterisks. The default is `true`.
public var filterProfanity: Bool?
/// Indicates whether dates, times, series of digits and numbers, phone numbers, currency values,
/// and Internet addresses are to be converted into more readable, conventional representations
/// in the final transcript of a recognition request. If true, smart formatting is performed;
/// if false (the default), no formatting is performed. Applies to US English transcription only.
public var smartFormatting: Bool?
/// If `true`, then speaker labels will be returned for each timestamp. The default is `false`.
public var speakerLabels: Bool?
/// The name of a grammar that is to be used with the recognition request. If you specify a
/// grammar, you must also use the `language_customization_id` parameter to specify the name of the custom language
/// model for which the grammar is defined. The service recognizes only strings that are recognized by the specified
/// grammar; it does not recognize other custom words from the model's words resource. See
/// [Grammars](https://cloud.ibm.com/docs/services/speech-to-text/output.html).
public var grammarName: String?
/// If `true`, the service redacts, or masks, numeric data from final transcripts. The feature
/// redacts any number that has three or more consecutive digits by replacing each digit with an `X` character. It is
/// intended to redact sensitive numeric data, such as credit card numbers. By default, the service performs no
/// redaction.
/// When you enable redaction, the service automatically enables smart formatting, regardless of whether you
/// explicitly disable that feature. To ensure maximum security, the service also disables keyword spotting (ignores
/// the `keywords` and `keywords_threshold` parameters) and returns only a single final transcript (forces the
/// `max_alternatives` parameter to be `1`).
/// **Note:** Applies to US English, Japanese, and Korean transcription only.
/// See [Numeric redaction](https://cloud.ibm.com/docs/services/speech-to-text/output.html#redaction).
public var redaction: Bool?
// If `true`, requests processing metrics about the service's transcription of the input audio. The service returns
// processing metrics at the interval specified by the `processing_metrics_interval` property. It also returns
// processing metrics for transcription events, for example, for final and interim results. By default, the service
// returns no processing metrics.
public var processingMetrics: Bool?
// Specifies the interval in real wall-clock seconds at which the service is to return processing metrics. The
// parameter is ignored unless the `processing_metrics` property is set to `true`. The property accepts a minimum
// value of 0.1 seconds. The level of precision is not restricted, so you can specify values such as 0.25 and 0.125.
// The service does not impose a maximum value. If you want to receive processing metrics only for transcription
// events instead of at periodic intervals, set the value to a large number. If the value is larger than the
// duration of the audio, the service returns processing metrics only for transcription events.
public var processingMetricsInterval: Double?
// If `true`, requests detailed information about the signal characteristics of the input audio. The service returns
// audio metrics with the final transcription results. By default, the service returns no audio metrics.
public var audioMetrics: Bool?
/// If `true`, specifies the duration of the pause interval at which the service
/// splits a transcript into multiple final results. If the service detects pauses or extended silence before it
/// reaches the end of the audio stream, its response can include multiple final results. Silence indicates a point
/// at which the speaker pauses between spoken words or phrases.
/// Specify a value for the pause interval in the range of 0.0 to 120.0.
/// * A value greater than 0 specifies the interval that the service is to use for speech recognition.
/// * A value of 0 indicates that the service is to use the default interval. It is equivalent to omitting the
/// parameter.
/// The default pause interval for most languages is 0.8 seconds; the default for Chinese is 0.6 seconds.
/// See [End of phrase silence time](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#silence_time).
public var endOfPhraseSilenceTime: Double?
/// If `true`, directs the service to split the transcript into multiple
/// final results based on semantic features of the input, for example, at the conclusion of meaningful phrases such
/// as sentences. The service bases its understanding of semantic features on the base language model that you use
/// with a request. Custom language models and grammars can also influence how and where the service splits a
/// transcript. By default, the service splits transcripts based solely on the pause interval.
/// See [Split transcript at phrase](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#split_transcript).
public var splitTranscriptAtPhraseEnd: Bool?
/// The sensitivity of speech activity detection that the service is to
/// perform. Use the parameter to suppress word insertions from music, coughing, and other non-speech events. The
/// service biases the audio it passes for speech recognition by evaluating the input audio against prior models of
/// speech and non-speech activity.
/// Specify a value between 0.0 and 1.0:
/// * 0.0 suppresses all audio (no speech is transcribed).
/// * 0.5 (the default) provides a reasonable compromise for the level of sensitivity.
/// * 1.0 suppresses no audio (speech detection sensitivity is disabled).
/// The values increase on a monotonic curve. See [Speech Activity
/// Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection).
public var speechDetectorSensitivity: Double?
/// The level to which the service is to suppress background audio based on
/// its volume to prevent it from being transcribed as speech. Use the parameter to suppress side conversations or
/// background noise.
/// Specify a value in the range of 0.0 to 1.0:
/// * 0.0 (the default) provides no suppression (background audio suppression is disabled).
/// * 0.5 provides a reasonable level of audio suppression for general usage.
/// * 1.0 suppresses all audio (no audio is transcribed).
/// The values increase on a monotonic curve. See [Speech Activity
/// Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection).
public var backgroundAudioSuppression: Double?
// If `true` for next-generation `Multimedia` and `Telephony` models that support low
// latency, directs the service to produce results even more quickly than it usually does. Next-generation models
// produce transcription results faster than previous-generation models. The `low_latency` parameter causes the
// models to produce results even more quickly, though the results might be less accurate when the parameter is used.
// **Note:** The parameter is beta functionality. It is not available for previous-generation `Broadband` and
// `Narrowband` models. It is available only for some next-generation models.
// * For a list of next-generation models that support low latency, see [Supported language
// models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported) for
// next-generation models.
// * For more information about the `low_latency` parameter, see [Low
// latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency).
public var lowLatency: Bool?
/**
Initialize a `RecognitionSettings` object to set the parameters of a Watson Speech to
Text recognition request.
- parameter contentType: The format of the audio data. Endianness is automatically detected
by the Speech to Text service. For more information about the supported formats, visit:
https://cloud.ibm.com/docs/services/speech-to-text/audio-formats.html
- returns: An initialized `RecognitionSettings` object with the given `contentType`.
Configure additional parameters for the recognition request by directly modifying
the returned object's properties.
*/
public init(contentType: String? = nil) {
self.contentType = contentType
}
private enum CodingKeys: String, CodingKey {
case action = "action"
case contentType = "content-type"
case customizationWeight = "customization_weight"
case inactivityTimeout = "inactivity_timeout"
case keywords = "keywords"
case keywordsThreshold = "keywords_threshold"
case maxAlternatives = "max_alternatives"
case interimResults = "interim_results"
case wordAlternativesThreshold = "word_alternatives_threshold"
case wordConfidence = "word_confidence"
case timestamps = "timestamps"
case filterProfanity = "profanity_filter"
case smartFormatting = "smart_formatting"
case speakerLabels = "speaker_labels"
case grammarName = "grammar_name"
case redaction = "redaction"
case processingMetrics = "processing_metrics"
case processingMetricsInterval = "processing_metrics_interval"
case audioMetrics = "audio_metrics"
case endOfPhraseSilenceTime = "end_of_phrase_silence_time"
case splitTranscriptAtPhraseEnd = "split_transcript_at_phrase_end"
case speechDetectorSensitivity = "speech_detector_sensitivity"
case backgroundAudioSuppression = "background_audio_suppression"
case lowLatency = "low_latency"
}
}
| apache-2.0 | 65ab60bdb58a24cd6d6f900030189001 | 60.825112 | 129 | 0.728657 | 4.607955 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/API/Clients/UploadClient.swift | 1 | 3534 | //
// UploadClient.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 12/14/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
@objc class UploadClient: NSObject, APIClient, URLSessionTaskDelegate {
typealias Progress = (Double) -> Void
typealias Completion = (Bool) -> Void
struct Callbacks {
let progress: Progress?
let completion: Completion?
}
let api: AnyAPIFetcher
var tasks: [URLSessionTask: (callbacks: Callbacks, request: UploadMessageRequest)] = [:]
required init(api: AnyAPIFetcher) {
self.api = api
}
func uploadMessage(roomId: String, data: Data, filename: String, mimetype: String, description: String, progress: Progress? = nil, completion: Completion? = nil) {
let req = UploadMessageRequest(
roomId: roomId,
data: data,
filename: filename,
mimetype: mimetype,
description: description
)
uploadRequest(req, callbacks: Callbacks(progress: progress, completion: completion))
}
func uploadRequest(_ request: UploadMessageRequest, callbacks: Callbacks) {
let task = api.fetch(request, options: [], sessionDelegate: self) { response in
switch response {
case .resource(let resource):
if let error = resource.error {
Alert(key: "alert.upload_error").withMessage(error).present()
callbacks.completion?(false)
}
callbacks.completion?(true)
case .error(let error):
if case let .error(error) = error, (error as NSError).code == NSURLErrorCancelled {
callbacks.completion?(true)
} else {
Alert(key: "alert.upload_error").present()
callbacks.completion?(false)
}
}
}
if let task = task {
tasks.updateValue((callbacks, request), forKey: task)
}
}
func uploadAvatar(data: Data, filename: String, mimetype: String, completion: Completion? = nil) {
let req = UploadAvatarRequest(
data: data,
filename: filename,
mimetype: mimetype
)
api.fetch(req) { _ in
completion?(true)
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
DispatchQueue.main.async { [weak self] in
let total = Double(totalBytesSent)/Double(totalBytesExpectedToSend)
self?.tasks[task]?.callbacks.progress?(total)
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
DispatchQueue.main.async { [weak self] in
self?.tasks[task]?.callbacks.progress?(1.0)
if error == nil {
self?.tasks.removeValue(forKey: task)
} else if let error = error, (error as NSError).code == NSURLErrorCancelled {
self?.tasks.removeValue(forKey: task)
}
}
}
func cancelUploads() {
tasks.keys.forEach { $0.cancel() }
}
func retryUploads() {
tasks.keys.filter { $0.error != nil }.forEach { key in
guard let (callbacks, request) = tasks[key] else {
return
}
uploadRequest(request, callbacks: callbacks)
}
}
}
| mit | a694dace382781a3b4e7394dc134d4cb | 31.712963 | 167 | 0.580526 | 4.826503 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/DAO/HubSubmitter/HubSubmitter.swift | 1 | 3401 | //
// HubSubmitter.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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.
//
class HubSubmitter: Cancelable {
private let requestSender: RequestSender
private let creationId: String
private let hubIdentifiers: Array<String>
private let completion: ErrorClosure?
private var operationQueue: OperationQueue?
private var errors: Array<APIClientError>
init(requestSender: RequestSender, creationId: String, hubIdentifiers: Array<String>, completion: ErrorClosure?) {
self.requestSender = requestSender
self.creationId = creationId
self.hubIdentifiers = hubIdentifiers
self.completion = completion
self.errors = Array<APIClientError>()
}
func cancel() {
operationQueue?.cancelAllOperations()
}
func submit() -> RequestHandler {
guard operationQueue == nil
else {
assert(false) //Fetch should be called only once
return RequestHandler(object: self)
}
operationQueue = OperationQueue()
operationQueue!.maxConcurrentOperationCount = 4
let finishOperation = BlockOperation()
finishOperation.addExecutionBlock {
[unowned finishOperation, weak self] in
guard let strongSelf = self, !finishOperation.isCancelled else { return }
let error = strongSelf.errors.first
DispatchQueue.main.async {
[weak self] in
self?.completion?(error)
}
}
hubIdentifiers.forEach {
(hubId) in
let operation = HubSubmitOperation(requestSender: requestSender, hubId: hubId, creationId: creationId) {
[weak self](operation, error) in
guard operation is HubSubmitOperation,
let error = error as? APIClientError,
let strongSelf = self
else { return }
strongSelf.errors.append(error)
}
finishOperation.addDependency(operation)
operationQueue!.addOperation(operation)
}
operationQueue!.addOperation(finishOperation)
return RequestHandler(object: self)
}
}
| mit | e09f0d4c51721c1610336ec572c9ad42 | 38.091954 | 118 | 0.652161 | 5.184451 | false | false | false | false |
creatubbles/ctb-api-swift | Pods/ObjectMapper/Sources/EnumOperators.swift | 4 | 2638 | //
// EnumOperators.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2016-09-26.
// Copyright © 2016 hearst. All rights reserved.
//
import Foundation
// MARK:- Raw Representable types
/// Object of Raw Representable type
public func <- <T: RawRepresentable>(left: inout T, right: Map) {
left <- (right, EnumTransform())
}
public func >>> <T: RawRepresentable>(left: T, right: Map) {
left >>> (right, EnumTransform())
}
/// Optional Object of Raw Representable type
public func <- <T: RawRepresentable>(left: inout T?, right: Map) {
left <- (right, EnumTransform())
}
public func >>> <T: RawRepresentable>(left: T?, right: Map) {
left >>> (right, EnumTransform())
}
// Code targeting the Swift 4.1 compiler and below.
#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0)))
/// Implicitly Unwrapped Optional Object of Raw Representable type
public func <- <T: RawRepresentable>(left: inout T!, right: Map) {
left <- (right, EnumTransform())
}
#endif
// MARK:- Arrays of Raw Representable type
/// Array of Raw Representable object
public func <- <T: RawRepresentable>(left: inout [T], right: Map) {
left <- (right, EnumTransform())
}
public func >>> <T: RawRepresentable>(left: [T], right: Map) {
left >>> (right, EnumTransform())
}
/// Array of Raw Representable object
public func <- <T: RawRepresentable>(left: inout [T]?, right: Map) {
left <- (right, EnumTransform())
}
public func >>> <T: RawRepresentable>(left: [T]?, right: Map) {
left >>> (right, EnumTransform())
}
// Code targeting the Swift 4.1 compiler and below.
#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0)))
/// Array of Raw Representable object
public func <- <T: RawRepresentable>(left: inout [T]!, right: Map) {
left <- (right, EnumTransform())
}
#endif
// MARK:- Dictionaries of Raw Representable type
/// Dictionary of Raw Representable object
public func <- <T: RawRepresentable>(left: inout [String: T], right: Map) {
left <- (right, EnumTransform())
}
public func >>> <T: RawRepresentable>(left: [String: T], right: Map) {
left >>> (right, EnumTransform())
}
/// Dictionary of Raw Representable object
public func <- <T: RawRepresentable>(left: inout [String: T]?, right: Map) {
left <- (right, EnumTransform())
}
public func >>> <T: RawRepresentable>(left: [String: T]?, right: Map) {
left >>> (right, EnumTransform())
}
// Code targeting the Swift 4.1 compiler and below.
#if !(swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0)))
/// Dictionary of Raw Representable object
public func <- <T: RawRepresentable>(left: inout [String: T]!, right: Map) {
left <- (right, EnumTransform())
}
#endif
| mit | 60ff7f5d8a24ded754f276e642ba0ad8 | 25.37 | 76 | 0.656807 | 3.501992 | false | false | false | false |
vselpublic/booksheet | clients/booksheet-ios/Rectrec/BookmarkTableViewCell.swift | 1 | 961 | //
// BookmarkTableViewCell.swift
// Rectrec
//
// Created by Volodymyr Selyukh on 26.04.15.
// Copyright (c) 2015 D4F. All rights reserved.
//
import UIKit
class BookmarkTableViewCell: UITableViewCell{
//Poizvonit Andruhe i sdelat tak chtob ne xranitr sostoyqnie
var bookmark:Bookmark?{
didSet {
updateUI()
}
}
@IBOutlet weak var bookmarkText: UILabel!
@IBOutlet weak var bookname: UILabel!
@IBOutlet weak var date: UILabel!
@IBOutlet weak var page: UILabel!
func updateUI() {
//reset All
bookmarkText.text = nil
bookname.text = nil
date.text = nil
page.text = nil
//Add Bookmark
if let bookmark = self.bookmark{
bookmarkText.text = bookmark["bookmarkText"]
bookname.text = bookmark["bookname"]
date.text = bookmark["date"]
page.text = "Page "+bookmark["page"]
}
}
}
| apache-2.0 | 95f34ed64343613c686627986841f71c | 23.641026 | 64 | 0.594173 | 3.987552 | false | false | false | false |
frootloops/swift | test/SILGen/witness_tables.swift | 1 | 41512 | // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module > %t.sil
// RUN: %FileCheck -check-prefix=TABLE -check-prefix=TABLE-ALL %s < %t.sil
// RUN: %FileCheck -check-prefix=SYMBOL %s < %t.sil
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-testing > %t.testable.sil
// RUN: %FileCheck -check-prefix=TABLE-TESTABLE -check-prefix=TABLE-ALL %s < %t.testable.sil
// RUN: %FileCheck -check-prefix=SYMBOL-TESTABLE %s < %t.testable.sil
import witness_tables_b
struct Arg {}
@objc class ObjCClass {}
infix operator <~>
protocol AssocReqt {
func requiredMethod()
}
protocol ArchetypeReqt {
func requiredMethod()
}
protocol AnyProtocol {
associatedtype AssocType
associatedtype AssocWithReqt: AssocReqt
func method(x: Arg, y: Self)
func generic<A: ArchetypeReqt>(x: A, y: Self)
func assocTypesMethod(x: AssocType, y: AssocWithReqt)
static func staticMethod(x: Self)
static func <~>(x: Self, y: Self)
}
protocol ClassProtocol : class {
associatedtype AssocType
associatedtype AssocWithReqt: AssocReqt
func method(x: Arg, y: Self)
func generic<B: ArchetypeReqt>(x: B, y: Self)
func assocTypesMethod(x: AssocType, y: AssocWithReqt)
static func staticMethod(x: Self)
static func <~>(x: Self, y: Self)
}
@objc protocol ObjCProtocol {
func method(x: ObjCClass)
static func staticMethod(y: ObjCClass)
}
class SomeAssoc {}
struct ConformingAssoc : AssocReqt {
func requiredMethod() {}
}
// TABLE-LABEL: sil_witness_table hidden ConformingAssoc: AssocReqt module witness_tables {
// TABLE-TESTABLE-LABEL: sil_witness_table [serialized] ConformingAssoc: AssocReqt module witness_tables {
// TABLE-ALL-NEXT: method #AssocReqt.requiredMethod!1: {{.*}} : @_T014witness_tables15ConformingAssocVAA0D4ReqtA2aDP14requiredMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-ALL-NEXT: }
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables15ConformingAssocVAA0D4ReqtA2aDP14requiredMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AssocReqt) (@in_guaranteed ConformingAssoc) -> ()
// SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] @_T014witness_tables15ConformingAssocVAA0D4ReqtA2aDP14requiredMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AssocReqt) (@in_guaranteed ConformingAssoc) -> ()
struct ConformingStruct : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: ConformingStruct) {}
func generic<D: ArchetypeReqt>(x: D, y: ConformingStruct) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x: ConformingStruct) {}
}
func <~>(x: ConformingStruct, y: ConformingStruct) {}
// TABLE-LABEL: sil_witness_table hidden ConformingStruct: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW {{.*}}: ArchetypeReqt> (@in τ_0_0, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in ConformingStruct, @thick ConformingStruct.Type) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> ()
// SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingStruct) -> ()
// SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in ConformingStruct, @thick ConformingStruct.Type) -> ()
// SYMBOL-TESTABLE: sil shared [transparent] [serialized] [thunk] @_T014witness_tables16ConformingStructVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> ()
protocol AddressOnly {}
struct ConformingAddressOnlyStruct : AnyProtocol {
var p: AddressOnly // force address-only layout with a protocol-type field
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: ConformingAddressOnlyStruct) {}
func generic<E: ArchetypeReqt>(x: E, y: ConformingAddressOnlyStruct) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x: ConformingAddressOnlyStruct) {}
}
func <~>(x: ConformingAddressOnlyStruct, y: ConformingAddressOnlyStruct) {}
// TABLE-LABEL: sil_witness_table hidden ConformingAddressOnlyStruct: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in ConformingAddressOnlyStruct, @in_guaranteed ConformingAddressOnlyStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformingAddressOnlyStruct, @in_guaranteed ConformingAddressOnlyStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingAddressOnlyStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in ConformingAddressOnlyStruct, @thick ConformingAddressOnlyStruct.Type) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables27ConformingAddressOnlyStructVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in ConformingAddressOnlyStruct, @in ConformingAddressOnlyStruct, @thick ConformingAddressOnlyStruct.Type) -> ()
class ConformingClass : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: ConformingClass) {}
func generic<F: ArchetypeReqt>(x: F, y: ConformingClass) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
class func staticMethod(x: ConformingClass) {}
}
func <~>(x: ConformingClass, y: ConformingClass) {}
// TABLE-LABEL: sil_witness_table hidden ConformingClass: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in ConformingClass, @in_guaranteed ConformingClass) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformingClass, @in_guaranteed ConformingClass) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingClass) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in ConformingClass, @thick ConformingClass.Type) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables15ConformingClassCAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in ConformingClass, @in ConformingClass, @thick ConformingClass.Type) -> ()
struct ConformsByExtension {}
extension ConformsByExtension : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: ConformsByExtension) {}
func generic<G: ArchetypeReqt>(x: G, y: ConformsByExtension) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x: ConformsByExtension) {}
}
func <~>(x: ConformsByExtension, y: ConformsByExtension) {}
// TABLE-LABEL: sil_witness_table hidden ConformsByExtension: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in ConformsByExtension, @in_guaranteed ConformsByExtension) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformsByExtension, @in_guaranteed ConformsByExtension) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformsByExtension) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in ConformsByExtension, @thick ConformsByExtension.Type) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables19ConformsByExtensionVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in ConformsByExtension, @in ConformsByExtension, @thick ConformsByExtension.Type) -> ()
extension OtherModuleStruct : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: OtherModuleStruct) {}
func generic<H: ArchetypeReqt>(x: H, y: OtherModuleStruct) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x: OtherModuleStruct) {}
}
func <~>(x: OtherModuleStruct, y: OtherModuleStruct) {}
// TABLE-LABEL: sil_witness_table hidden OtherModuleStruct: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in OtherModuleStruct, @in_guaranteed OtherModuleStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in OtherModuleStruct, @in_guaranteed OtherModuleStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed OtherModuleStruct) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in OtherModuleStruct, @thick OtherModuleStruct.Type) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T016witness_tables_b17OtherModuleStructV0a1_B011AnyProtocolA2dEP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in OtherModuleStruct, @in OtherModuleStruct, @thick OtherModuleStruct.Type) -> ()
protocol OtherProtocol {}
struct ConformsWithMoreGenericWitnesses : AnyProtocol, OtherProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method<I, J>(x: I, y: J) {}
func generic<K, L>(x: K, y: L) {}
func assocTypesMethod<M, N>(x: M, y: N) {}
static func staticMethod<O>(x: O) {}
}
func <~> <P: OtherProtocol>(x: P, y: P) {}
// TABLE-LABEL: sil_witness_table hidden ConformsWithMoreGenericWitnesses: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in ConformsWithMoreGenericWitnesses, @in_guaranteed ConformsWithMoreGenericWitnesses) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @in ConformsWithMoreGenericWitnesses, @in_guaranteed ConformsWithMoreGenericWitnesses) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformsWithMoreGenericWitnesses) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in ConformsWithMoreGenericWitnesses, @thick ConformsWithMoreGenericWitnesses.Type) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables32ConformsWithMoreGenericWitnessesVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: AnyProtocol) (@in ConformsWithMoreGenericWitnesses, @in ConformsWithMoreGenericWitnesses, @thick ConformsWithMoreGenericWitnesses.Type) -> ()
class ConformingClassToClassProtocol : ClassProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: ConformingClassToClassProtocol) {}
func generic<Q: ArchetypeReqt>(x: Q, y: ConformingClassToClassProtocol) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
class func staticMethod(x: ConformingClassToClassProtocol) {}
}
func <~>(x: ConformingClassToClassProtocol,
y: ConformingClassToClassProtocol) {}
// TABLE-LABEL: sil_witness_table hidden ConformingClassToClassProtocol: ClassProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #ClassProtocol.method!1: {{.*}} : @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #ClassProtocol.generic!1: {{.*}} : @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #ClassProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #ClassProtocol.staticMethod!1: {{.*}} : @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #ClassProtocol."<~>"!1: {{.*}} : @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: ClassProtocol) (Arg, @owned ConformingClassToClassProtocol, @guaranteed ConformingClassToClassProtocol) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP7generic{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: ClassProtocol) <τ_0_0 where τ_0_0 : ArchetypeReqt> (@in τ_0_0, @owned ConformingClassToClassProtocol, @guaranteed ConformingClassToClassProtocol) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: ClassProtocol) (@in SomeAssoc, @in ConformingAssoc, @guaranteed ConformingClassToClassProtocol) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: ClassProtocol) (@owned ConformingClassToClassProtocol, @thick ConformingClassToClassProtocol.Type) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables017ConformingClassToD8ProtocolCAA0dF0A2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW : $@convention(witness_method: ClassProtocol) (@owned ConformingClassToClassProtocol, @owned ConformingClassToClassProtocol, @thick ConformingClassToClassProtocol.Type) -> ()
class ConformingClassToObjCProtocol : ObjCProtocol {
@objc func method(x: ObjCClass) {}
@objc class func staticMethod(y: ObjCClass) {}
}
// TABLE-NOT: sil_witness_table hidden ConformingClassToObjCProtocol
struct ConformingGeneric<R: AssocReqt> : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = R
func method(x: Arg, y: ConformingGeneric) {}
func generic<Q: ArchetypeReqt>(x: Q, y: ConformingGeneric) {}
func assocTypesMethod(x: SomeAssoc, y: R) {}
static func staticMethod(x: ConformingGeneric) {}
}
func <~> <R: AssocReqt>(x: ConformingGeneric<R>, y: ConformingGeneric<R>) {}
// TABLE-LABEL: sil_witness_table hidden <R where R : AssocReqt> ConformingGeneric<R>: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: R
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): dependent
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables17ConformingGenericVyxGAA11AnyProtocolA2aEP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables17ConformingGenericVyxGAA11AnyProtocolA2aEP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables17ConformingGenericVyxGAA11AnyProtocolA2aEP16assocTypesMetho{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables17ConformingGenericVyxGAA11AnyProtocolA2aEP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables17ConformingGenericVyxGAA11AnyProtocolA2aEP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
protocol AnotherProtocol {}
struct ConformingGenericWithMoreGenericWitnesses<S: AssocReqt>
: AnyProtocol, AnotherProtocol
{
typealias AssocType = SomeAssoc
typealias AssocWithReqt = S
func method<T, U>(x: T, y: U) {}
func generic<V, W>(x: V, y: W) {}
func assocTypesMethod<X, Y>(x: X, y: Y) {}
static func staticMethod<Z>(x: Z) {}
}
func <~> <AA: AnotherProtocol, BB: AnotherProtocol>(x: AA, y: BB) {}
// TABLE-LABEL: sil_witness_table hidden <S where S : AssocReqt> ConformingGenericWithMoreGenericWitnesses<S>: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: S
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): dependent
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolA2aEP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolA2aEP7{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolA2aEP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolA2aEP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables025ConformingGenericWithMoreD9WitnessesVyxGAA11AnyProtocolA2aEP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
protocol InheritedProtocol1 : AnyProtocol {
func inheritedMethod()
}
protocol InheritedProtocol2 : AnyProtocol {
func inheritedMethod()
}
protocol InheritedClassProtocol : class, AnyProtocol {
func inheritedMethod()
}
struct InheritedConformance : InheritedProtocol1 {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: InheritedConformance) {}
func generic<H: ArchetypeReqt>(x: H, y: InheritedConformance) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x: InheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: InheritedConformance, y: InheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden InheritedConformance: InheritedProtocol1 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: InheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: {{.*}} : @_T014witness_tables20InheritedConformanceVAA0C9Protocol1A2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden InheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables20InheritedConformanceVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables20InheritedConformanceVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables20InheritedConformanceVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables20InheritedConformanceVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables20InheritedConformanceVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
struct RedundantInheritedConformance : InheritedProtocol1, AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: RedundantInheritedConformance) {}
func generic<H: ArchetypeReqt>(x: H, y: RedundantInheritedConformance) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x: RedundantInheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: RedundantInheritedConformance, y: RedundantInheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden RedundantInheritedConformance: InheritedProtocol1 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: RedundantInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: {{.*}} : @_T014witness_tables29RedundantInheritedConformanceVAA0D9Protocol1A2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden RedundantInheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables29RedundantInheritedConformanceVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables29RedundantInheritedConformanceVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables29RedundantInheritedConformanceVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables29RedundantInheritedConformanceVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables29RedundantInheritedConformanceVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
struct DiamondInheritedConformance : InheritedProtocol1, InheritedProtocol2 {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: DiamondInheritedConformance) {}
func generic<H: ArchetypeReqt>(x: H, y: DiamondInheritedConformance) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x: DiamondInheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: DiamondInheritedConformance, y: DiamondInheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: InheritedProtocol1 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: DiamondInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: {{.*}} : @_T014witness_tables27DiamondInheritedConformanceVAA0D9Protocol1A2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: InheritedProtocol2 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: DiamondInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol2.inheritedMethod!1: {{.*}} : @_T014witness_tables27DiamondInheritedConformanceVAA0D9Protocol2A2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables27DiamondInheritedConformanceVAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables27DiamondInheritedConformanceVAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables27DiamondInheritedConformanceVAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables27DiamondInheritedConformanceVAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables27DiamondInheritedConformanceVAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
class ClassInheritedConformance : InheritedClassProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x: Arg, y: ClassInheritedConformance) {}
func generic<H: ArchetypeReqt>(x: H, y: ClassInheritedConformance) {}
func assocTypesMethod(x: SomeAssoc, y: ConformingAssoc) {}
class func staticMethod(x: ClassInheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: ClassInheritedConformance, y: ClassInheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden ClassInheritedConformance: InheritedClassProtocol module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: ClassInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedClassProtocol.inheritedMethod!1: {{.*}} : @_T014witness_tables25ClassInheritedConformanceCAA0dC8ProtocolA2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden ClassInheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: {{.*}} : @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.generic!1: {{.*}} : @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP7generic{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: {{.*}} : @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP16assocTypesMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: {{.*}} : @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: method #AnyProtocol."<~>"!1: {{.*}} : @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP3ltgoi{{[_0-9a-zA-Z]*}}FZTW
// TABLE-NEXT: }
// -- Witnesses have the 'self' abstraction level of their protocol.
// AnyProtocol has no class bound, so its witnesses treat Self as opaque.
// InheritedClassProtocol has a class bound, so its witnesses treat Self as
// a reference value.
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables25ClassInheritedConformanceCAA0dC8ProtocolA2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: InheritedClassProtocol) (@guaranteed ClassInheritedConformance) -> ()
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables25ClassInheritedConformanceCAA11AnyProtocolA2aDP6method{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: AnyProtocol) (Arg, @in ClassInheritedConformance, @in_guaranteed ClassInheritedConformance) -> ()
struct GenericAssocType<T> : AssocReqt {
func requiredMethod() {}
}
protocol AssocTypeWithReqt {
associatedtype AssocType : AssocReqt
}
struct ConformsWithDependentAssocType1<CC: AssocReqt> : AssocTypeWithReqt {
typealias AssocType = CC
}
// TABLE-LABEL: sil_witness_table hidden <CC where CC : AssocReqt> ConformsWithDependentAssocType1<CC>: AssocTypeWithReqt module witness_tables {
// TABLE-NEXT: associated_type AssocType: CC
// TABLE-NEXT: associated_type_protocol (AssocType: AssocReqt): dependent
// TABLE-NEXT: }
struct ConformsWithDependentAssocType2<DD> : AssocTypeWithReqt {
typealias AssocType = GenericAssocType<DD>
}
// TABLE-LABEL: sil_witness_table hidden <DD> ConformsWithDependentAssocType2<DD>: AssocTypeWithReqt module witness_tables {
// TABLE-NEXT: associated_type AssocType: GenericAssocType<DD>
// TABLE-NEXT: associated_type_protocol (AssocType: AssocReqt): <T> GenericAssocType<T>: AssocReqt module witness_tables
// TABLE-NEXT: }
protocol InheritedFromObjC : ObjCProtocol {
func inheritedMethod()
}
class ConformsInheritedFromObjC : InheritedFromObjC {
@objc func method(x: ObjCClass) {}
@objc class func staticMethod(y: ObjCClass) {}
func inheritedMethod() {}
}
// TABLE-LABEL: sil_witness_table hidden ConformsInheritedFromObjC: InheritedFromObjC module witness_tables {
// TABLE-NEXT: method #InheritedFromObjC.inheritedMethod!1: {{.*}} : @_T014witness_tables25ConformsInheritedFromObjCCAA0deF1CA2aDP15inheritedMethod{{[_0-9a-zA-Z]*}}FTW
// TABLE-NEXT: }
protocol ObjCAssoc {
associatedtype AssocType : ObjCProtocol
}
struct HasObjCAssoc : ObjCAssoc {
typealias AssocType = ConformsInheritedFromObjC
}
// TABLE-LABEL: sil_witness_table hidden HasObjCAssoc: ObjCAssoc module witness_tables {
// TABLE-NEXT: associated_type AssocType: ConformsInheritedFromObjC
// TABLE-NEXT: }
protocol Initializer {
init(arg: Arg)
}
// TABLE-LABEL: sil_witness_table hidden HasInitializerStruct: Initializer module witness_tables {
// TABLE-NEXT: method #Initializer.init!allocator.1: {{.*}} : @_T014witness_tables20HasInitializerStructVAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables20HasInitializerStructVAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method: Initializer) (Arg, @thick HasInitializerStruct.Type) -> @out HasInitializerStruct
struct HasInitializerStruct : Initializer {
init(arg: Arg) { }
}
// TABLE-LABEL: sil_witness_table hidden HasInitializerClass: Initializer module witness_tables {
// TABLE-NEXT: method #Initializer.init!allocator.1: {{.*}} : @_T014witness_tables19HasInitializerClassCAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables19HasInitializerClassCAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method: Initializer) (Arg, @thick HasInitializerClass.Type) -> @out HasInitializerClass
class HasInitializerClass : Initializer {
required init(arg: Arg) { }
}
// TABLE-LABEL: sil_witness_table hidden HasInitializerEnum: Initializer module witness_tables {
// TABLE-NEXT: method #Initializer.init!allocator.1: {{.*}} : @_T014witness_tables18HasInitializerEnumOAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW
// TABLE-NEXT: }
// SYMBOL: sil private [transparent] [thunk] @_T014witness_tables18HasInitializerEnumOAA0D0A2aDP{{[_0-9a-zA-Z]*}}fCTW : $@convention(witness_method: Initializer) (Arg, @thick HasInitializerEnum.Type) -> @out HasInitializerEnum
enum HasInitializerEnum : Initializer {
case A
init(arg: Arg) { self = .A }
}
| apache-2.0 | 4fd55a9779a004606fe18b9c94047abe | 74.436364 | 338 | 0.75987 | 3.647793 | false | false | false | false |
parkera/swift-corelibs-foundation | Foundation/Date.swift | 2 | 11842 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
/**
`Date` represents a single point in time.
A `Date` is independent of a particular calendar or time zone. To represent a `Date` to a user, you must interpret it in the context of a `Calendar`.
*/
public struct Date : ReferenceConvertible, Comparable, Equatable {
public typealias ReferenceType = NSDate
fileprivate var _time: TimeInterval
/// The number of seconds from 1 January 1970 to the reference date, 1 January 2001.
public static let timeIntervalBetween1970AndReferenceDate: TimeInterval = 978307200.0
/// The interval between 00:00:00 UTC on 1 January 2001 and the current date and time.
public static var timeIntervalSinceReferenceDate: TimeInterval {
return CFAbsoluteTimeGetCurrent()
}
/// Returns a `Date` initialized to the current date and time.
public init() {
_time = CFAbsoluteTimeGetCurrent()
}
/// Returns a `Date` initialized relative to the current date and time by a given number of seconds.
public init(timeIntervalSinceNow: TimeInterval) {
self.init(timeIntervalSinceReferenceDate: timeIntervalSinceNow + CFAbsoluteTimeGetCurrent())
}
/// Returns a `Date` initialized relative to 00:00:00 UTC on 1 January 1970 by a given number of seconds.
public init(timeIntervalSince1970: TimeInterval) {
self.init(timeIntervalSinceReferenceDate: timeIntervalSince1970 - Date.timeIntervalBetween1970AndReferenceDate)
}
/**
Returns a `Date` initialized relative to another given date by a given number of seconds.
- Parameter timeInterval: The number of seconds to add to `date`. A negative value means the receiver will be earlier than `date`.
- Parameter date: The reference date.
*/
public init(timeInterval: TimeInterval, since date: Date) {
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate + timeInterval)
}
/// Returns a `Date` initialized relative to 00:00:00 UTC on 1 January 2001 by a given number of seconds.
public init(timeIntervalSinceReferenceDate ti: TimeInterval) {
_time = ti
}
/**
Returns the interval between the date object and 00:00:00 UTC on 1 January 2001.
This property's value is negative if the date object is earlier than the system's absolute reference date (00:00:00 UTC on 1 January 2001).
*/
public var timeIntervalSinceReferenceDate: TimeInterval {
return _time
}
/**
Returns the interval between the receiver and another given date.
- Parameter another: The date with which to compare the receiver.
- Returns: The interval between the receiver and the `another` parameter. If the receiver is earlier than `anotherDate`, the return value is negative. If `anotherDate` is `nil`, the results are undefined.
- SeeAlso: `timeIntervalSince1970`
- SeeAlso: `timeIntervalSinceNow`
- SeeAlso: `timeIntervalSinceReferenceDate`
*/
public func timeIntervalSince(_ date: Date) -> TimeInterval {
return self.timeIntervalSinceReferenceDate - date.timeIntervalSinceReferenceDate
}
/**
The time interval between the date and the current date and time.
If the date is earlier than the current date and time, this property's value is negative.
- SeeAlso: `timeIntervalSince(_:)`
- SeeAlso: `timeIntervalSince1970`
- SeeAlso: `timeIntervalSinceReferenceDate`
*/
public var timeIntervalSinceNow: TimeInterval {
return self.timeIntervalSinceReferenceDate - CFAbsoluteTimeGetCurrent()
}
/**
The interval between the date object and 00:00:00 UTC on 1 January 1970.
This property's value is negative if the date object is earlier than 00:00:00 UTC on 1 January 1970.
- SeeAlso: `timeIntervalSince(_:)`
- SeeAlso: `timeIntervalSinceNow`
- SeeAlso: `timeIntervalSinceReferenceDate`
*/
public var timeIntervalSince1970: TimeInterval {
return self.timeIntervalSinceReferenceDate + Date.timeIntervalBetween1970AndReferenceDate
}
/// Return a new `Date` by adding a `TimeInterval` to this `Date`.
///
/// - parameter timeInterval: The value to add, in seconds.
/// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more.
public func addingTimeInterval(_ timeInterval: TimeInterval) -> Date {
return self + timeInterval
}
/// Add a `TimeInterval` to this `Date`.
///
/// - parameter timeInterval: The value to add, in seconds.
/// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more.
public mutating func addTimeInterval(_ timeInterval: TimeInterval) {
self += timeInterval
}
/**
Creates and returns a Date value representing a date in the distant future.
The distant future is in terms of centuries.
*/
public static let distantFuture = Date(timeIntervalSinceReferenceDate: 63113904000.0)
/**
Creates and returns a Date value representing a date in the distant past.
The distant past is in terms of centuries.
*/
public static let distantPast = Date(timeIntervalSinceReferenceDate: -63114076800.0)
public var hashValue: Int {
return Int(bitPattern: __CFHashDouble(_time))
}
/// Compare two `Date` values.
public func compare(_ other: Date) -> ComparisonResult {
if _time < other.timeIntervalSinceReferenceDate {
return .orderedAscending
} else if _time > other.timeIntervalSinceReferenceDate {
return .orderedDescending
} else {
return .orderedSame
}
}
/// Returns true if the two `Date` values represent the same point in time.
public static func ==(lhs: Date, rhs: Date) -> Bool {
return lhs.timeIntervalSinceReferenceDate == rhs.timeIntervalSinceReferenceDate
}
/// Returns true if the left hand `Date` is earlier in time than the right hand `Date`.
public static func <(lhs: Date, rhs: Date) -> Bool {
return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate
}
/// Returns true if the left hand `Date` is later in time than the right hand `Date`.
public static func >(lhs: Date, rhs: Date) -> Bool {
return lhs.timeIntervalSinceReferenceDate > rhs.timeIntervalSinceReferenceDate
}
/// Returns a `Date` with a specified amount of time added to it.
public static func +(lhs: Date, rhs: TimeInterval) -> Date {
return Date(timeIntervalSinceReferenceDate: lhs.timeIntervalSinceReferenceDate + rhs)
}
/// Returns a `Date` with a specified amount of time subtracted from it.
public static func -(lhs: Date, rhs: TimeInterval) -> Date {
return Date(timeIntervalSinceReferenceDate: lhs.timeIntervalSinceReferenceDate - rhs)
}
/// Add a `TimeInterval` to a `Date`.
///
/// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more.
public static func +=(lhs: inout Date, rhs: TimeInterval) {
lhs = lhs + rhs
}
/// Subtract a `TimeInterval` from a `Date`.
///
/// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more.
public static func -=(lhs: inout Date, rhs: TimeInterval) {
lhs = lhs - rhs
}
}
extension Date : CustomDebugStringConvertible, CustomStringConvertible, CustomReflectable {
/**
A string representation of the date object (read-only).
The representation is useful for debugging only.
There are a number of options to acquire a formatted string for a date including: date formatters (see
[NSDateFormatter](//apple_ref/occ/cl/NSDateFormatter) and [Data Formatting Guide](//apple_ref/doc/uid/10000029i)), and the `Date` function `description(locale:)`.
*/
public var description: String {
// Defer to NSDate for description
return NSDate(timeIntervalSinceReferenceDate: _time).description
}
/**
Returns a string representation of the receiver using the given
locale.
- Parameter locale: A `Locale`. If you pass `nil`, `Date` formats the date in the same way as the `description` property.
- Returns: A string representation of the `Date`, using the given locale, or if the locale argument is `nil`, in the international format `YYYY-MM-DD HH:MM:SS ±HHMM`, where `±HHMM` represents the time zone offset in hours and minutes from UTC (for example, "`2001-03-24 10:45:32 +0600`").
*/
public func description(with locale: Locale?) -> String {
return NSDate(timeIntervalSinceReferenceDate: _time).description(with: locale)
}
public var debugDescription: String {
return description
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "timeIntervalSinceReferenceDate", value: timeIntervalSinceReferenceDate))
return Mirror(self, children: c, displayStyle: .struct)
}
}
extension Date : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSDate {
return NSDate(timeIntervalSinceReferenceDate: _time)
}
public static func _forceBridgeFromObjectiveC(_ x: NSDate, result: inout Date?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge \(NSDate.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSDate, result: inout Date?) -> Bool {
result = Date(timeIntervalSinceReferenceDate: x.timeIntervalSinceReferenceDate)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDate?) -> Date {
var result: Date? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension Date : CustomPlaygroundDisplayConvertible {
public var playgroundDescription: Any {
let df = DateFormatter()
df.dateStyle = .medium
df.timeStyle = .short
return df.string(from: self)
}
}
extension Date : Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let timestamp = try container.decode(Double.self)
self.init(timeIntervalSinceReferenceDate: timestamp)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.timeIntervalSinceReferenceDate)
}
}
| apache-2.0 | 8a151bb98cdaca2b5895e638ff4e41c6 | 41.743682 | 293 | 0.689443 | 5.083727 | false | false | false | false |
saiyuujob/CryptoWithSwift | Demo/Demo/ViewController.swift | 1 | 1441 | //
// ViewController.swift
// Demo
//
// Created by iosdev on 2017/07/18.
// Copyright © 2017年 iosdev. All rights reserved.
//
import UIKit
import CryptoWithSwift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let testText = "Hello. CryptoWithSwfit"
let key = "D8DDA1ED-BFFC-47E6-8393-2941F8FB0E6D" //UUID().uuidString
let iv = "Rhm9BB36QA8=" //CryptoWithSwift.generateRandomBytes(byteCount: 8)
var afterEncryption: String?
// Encryption
if let retEncryption = CryptoWithSwift.AES256CBCEncryption(target: testText, key: key, iv: iv) {
print("encryption success: \(retEncryption)")
afterEncryption = retEncryption
} else {
print("encryption failure.")
}
// Decrypt
if let encryption = afterEncryption {
if let retDecrypt = CryptoWithSwift.AES256CBCDecrypt(target: encryption, key: key, iv: iv) {
print("decrypt success: \(retDecrypt)")
} else {
print("decrypt failure.")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | d6ea2bcd173df29895c432ecf0fd6169 | 29.595745 | 111 | 0.59249 | 4.594249 | false | false | false | false |
chanhx/iGithub | iGithub/ViewModels/SearchViewModel.swift | 2 | 4498 | //
// SearchViewModel.swift
// iGithub
//
// Created by Chan Hocheung on 8/16/16.
// Copyright © 2016 Hocheung. All rights reserved.
//
import Foundation
import RxSwift
import RxMoya
import ObjectMapper
class SearchViewModel {
enum SearchObject {
case repository
case user
}
let repoTVM = RepositoriesSearchViewModel()
let userTVM = UsersSearchViewModel()
var searchObject: SearchObject = .repository
func search(query: String) {
switch searchObject {
case .repository:
repoTVM.query = query
repoTVM.isLoading = true
repoTVM.dataSource.value.removeAll()
repoTVM.refresh()
case .user:
userTVM.query = query
userTVM.isLoading = true
userTVM.dataSource.value.removeAll()
userTVM.refresh()
}
}
@objc func fetchNextPage() {
switch searchObject {
case .repository:
repoTVM.fetchData()
case .user:
userTVM.fetchData()
}
}
func clean() {
repoTVM.query = nil
userTVM.query = nil
repoTVM.dataSource.value = []
userTVM.dataSource.value = []
}
}
// MARK: SubViewModels
class RepositoriesSearchViewModel: BaseTableViewModel<Repository> {
var query: String?
var sort: RepositoriesSearchSort = .bestMatch
var language = "All Languages"
var isLoading = false
let sortOptions: [RepositoriesSearchSort] = [
.bestMatch, .stars, .forks, .updated
]
var token: GitHubAPI {
var q = query!
switch sort {
case .stars:
q += " sort:stars"
case .forks:
q += " sort:forks"
case .updated:
q += " sort:updated"
default:
break
}
let lan = languagesDict[language]!
if lan.count > 0 {
q += " language:\(lan)"
}
return GitHubAPI.searchRepositories(query: q, after: endCursor)
}
override func fetchData() {
GitHubProvider
.request(token)
.filterSuccessfulStatusCodes()
.mapJSON()
.subscribe(onSuccess: { [unowned self] in
guard
let json = ($0 as? [String: [String: Any]])?["data"]?["search"],
let connection = Mapper<EntityConnection<Repository>>().map(JSONObject: json),
let newRepos = connection.nodes
else {
// deal with error
return
}
self.hasNextPage = connection.pageInfo!.hasNextPage!
if self.endCursor == nil {
self.dataSource.value = newRepos
} else {
self.dataSource.value.append(contentsOf: newRepos)
}
self.endCursor = connection.pageInfo?.endCursor
})
.disposed(by: disposeBag)
}
}
class UsersSearchViewModel: BaseTableViewModel<User> {
var query: String?
var sort: UsersSearchSort = .bestMatch
var isLoading = false
let sortOptions: [UsersSearchSort] = [
.bestMatch, .followers, .repositories, .joined
]
var token: GitHubAPI {
return GitHubAPI.searchUsers(q: query!, sort: sort, page: page)
}
override func fetchData() {
GitHubProvider
.request(token)
.do(onNext: { [unowned self] in
self.isLoading = false
if let headers = $0.response?.allHeaderFields {
self.hasNextPage = (headers["Link"] as? String)?.range(of: "rel=\"next\"") != nil
}
})
.mapJSON()
.subscribe(onSuccess: { [unowned self] in
if let results = Mapper<User>().mapArray(JSONObject: ($0 as! [String: Any])["items"]) {
if self.page == 1 {
self.dataSource.value = results
} else {
self.dataSource.value.append(contentsOf: results)
}
self.page += 1
} else {
// deal with error
}
})
.disposed(by: disposeBag)
}
}
| gpl-3.0 | f7524fa877b9e2a20d35026c80c9f74b | 26.420732 | 103 | 0.501001 | 4.991121 | false | false | false | false |
tkremenek/swift | stdlib/public/core/Mirrors.swift | 15 | 9251 | //===--- Mirrors.swift - Common _Mirror implementations -------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
extension Float: CustomReflectable {
/// A mirror that reflects the `Float` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension Float: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `Float` instance.
@available(*, deprecated, message: "Float.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .float(self)
}
}
extension Double: CustomReflectable {
/// A mirror that reflects the `Double` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension Double: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `Double` instance.
@available(*, deprecated, message: "Double.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .double(self)
}
}
extension Bool: CustomReflectable {
/// A mirror that reflects the `Bool` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension Bool: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `Bool` instance.
@available(*, deprecated, message: "Bool.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .bool(self)
}
}
extension String: CustomReflectable {
/// A mirror that reflects the `String` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension String: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `String` instance.
@available(*, deprecated, message: "String.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .text(self)
}
}
extension Character: CustomReflectable {
/// A mirror that reflects the `Character` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension Character: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `Character` instance.
@available(*, deprecated, message: "Character.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .text(String(self))
}
}
extension Unicode.Scalar: CustomReflectable {
/// A mirror that reflects the `Unicode.Scalar` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension Unicode.Scalar: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `Unicode.Scalar` instance.
@available(*, deprecated, message: "Unicode.Scalar.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .uInt(UInt64(self))
}
}
extension UInt8: CustomReflectable {
/// A mirror that reflects the `UInt8` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension UInt8: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `UInt8` instance.
@available(*, deprecated, message: "UInt8.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .uInt(UInt64(self))
}
}
extension Int8: CustomReflectable {
/// A mirror that reflects the `Int8` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension Int8: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `Int8` instance.
@available(*, deprecated, message: "Int8.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .int(Int64(self))
}
}
extension UInt16: CustomReflectable {
/// A mirror that reflects the `UInt16` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension UInt16: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `UInt16` instance.
@available(*, deprecated, message: "UInt16.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .uInt(UInt64(self))
}
}
extension Int16: CustomReflectable {
/// A mirror that reflects the `Int16` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension Int16: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `Int16` instance.
@available(*, deprecated, message: "Int16.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .int(Int64(self))
}
}
extension UInt32: CustomReflectable {
/// A mirror that reflects the `UInt32` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension UInt32: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `UInt32` instance.
@available(*, deprecated, message: "UInt32.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .uInt(UInt64(self))
}
}
extension Int32: CustomReflectable {
/// A mirror that reflects the `Int32` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension Int32: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `Int32` instance.
@available(*, deprecated, message: "Int32.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .int(Int64(self))
}
}
extension UInt64: CustomReflectable {
/// A mirror that reflects the `UInt64` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension UInt64: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `UInt64` instance.
@available(*, deprecated, message: "UInt64.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .uInt(UInt64(self))
}
}
extension Int64: CustomReflectable {
/// A mirror that reflects the `Int64` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension Int64: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `Int64` instance.
@available(*, deprecated, message: "Int64.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .int(Int64(self))
}
}
extension UInt: CustomReflectable {
/// A mirror that reflects the `UInt` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension UInt: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `UInt` instance.
@available(*, deprecated, message: "UInt.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .uInt(UInt64(self))
}
}
extension Int: CustomReflectable {
/// A mirror that reflects the `Int` instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
extension Int: _CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for the `Int` instance.
@available(*, deprecated, message: "Int.customPlaygroundQuickLook will be removed in a future Swift version")
public var customPlaygroundQuickLook: _PlaygroundQuickLook {
return .int(Int64(self))
}
}
#if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64))
extension Float80: CustomReflectable {
/// A mirror that reflects the Float80 instance.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: EmptyCollection<Void>())
}
}
#endif
| apache-2.0 | 27057dd0e547a3b9855183b60156fe48 | 34.580769 | 122 | 0.74165 | 4.808212 | false | false | false | false |
rayfix/Quizr | Quizr/Quiz.swift | 1 | 1933 | //
// Quiz.swift
// Quizr
//
// Created by Ray Fix on 12/7/15.
// Copyright © 2015 Pelfunc, Inc. All rights reserved.
//
// This is the model for our quizing app.
import Foundation
struct Question {
let question: String
let choices: [String]
let answerIndex: Int
var answer: String {
return choices[answerIndex]
}
}
struct Quiz {
let title: String
let author: String
let questions: [Question]
}
struct QuizRun {
let quiz: Quiz
private(set) var wrongAnswers = 0
private(set) var index = 0
init(quiz: Quiz) {
self.quiz = quiz
}
var current: Question? {
guard !isDone else { return nil }
return quiz.questions[index]
}
var isDone: Bool { return index >= quiz.questions.count }
mutating func next() {
index += 1
}
mutating func restart() {
index = 0
wrongAnswers = 0
}
mutating func advance(answer: String) -> Bool {
if answer == current!.answer {
next()
return true
}
else {
wrongAnswers += 1
return false
}
}
}
import SwiftyJSON
typealias JSONDictionary = [String: AnyObject]
protocol JSONConvertible {
init(json: JSON) throws
}
extension Question : JSONConvertible {
init(json: JSON) throws {
question = json["question"].stringValue
answerIndex = json["answer"].intValue
var choices: [String] = []
for choice in json["choices"].arrayValue {
choices.append(choice.stringValue)
}
self.choices = choices
}
}
extension Quiz : JSONConvertible {
enum Error : ErrorType {
case NoTitle
}
init(json: JSON) throws {
guard let title = json["title"].string else { throw Error.NoTitle }
self.title = title
self.author = json["author"].stringValue
var questions: [Question] = []
for question in json["questions"].arrayValue {
questions.append(try Question(json: question))
}
self.questions = questions
}
}
| mit | 6eb001682cf3dfbe7f9e469237731203 | 17.576923 | 71 | 0.636128 | 3.895161 | false | false | false | false |
debugsquad/Hyperborea | Hyperborea/Model/Main/MSession.swift | 1 | 1567 | import Foundation
class MSession
{
static let sharedInstance:MSession = MSession()
let modelOxfordCredentials:MOxfordCredentials
let modelUrls:MUrls
private(set) var settings:DSettings?
private init()
{
modelOxfordCredentials = MOxfordCredentials()
modelUrls = MUrls()
}
//MARK: private
private func asyncLoadSession()
{
DManager.sharedInstance?.fetchData(
entityName:DSettings.entityName,
limit:1)
{ (data) in
guard
let settings:DSettings = data?.first as? DSettings
else
{
self.createSession()
return
}
settings.addTtl()
self.settings = settings
}
}
private func createSession()
{
DManager.sharedInstance?.createData(
entityName:DSettings.entityName)
{ (data) in
guard
let settings:DSettings = data as? DSettings
else
{
return
}
self.settings = settings
settings.froobShots = DSettings.kMaxFroobShots
DManager.sharedInstance?.save()
}
}
//MARK: public
func loadSession()
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{
self.asyncLoadSession()
}
}
}
| mit | b046ac2840a5c24acfabce4484f509e0 | 21.070423 | 71 | 0.490108 | 5.556738 | false | false | false | false |
Eric217/-OnSale | 打折啦/打折啦/ESTabBarItem_Detail.swift | 1 | 6412 | //
// ContentView.swift
// Application
//
// Created by Eric on 7/15/17.
// Copyright © 2017 Eric. All rights reserved.
//
import Foundation
import pop
//TODO: - 设置tabbar背景色后,修改Step2及Step2‘,三级子类及大圆类中高度定制颜色
//MARK: - Step1
///一级子类
class ExampleBouncesContentView: ESTabBarItemContentView {
public var duration = 0.3
override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func selectAnimation(animated: Bool, completion: (() -> ())?) {
self.bounceAnimation()
completion?()
}
override func reselectAnimation(animated: Bool, completion: (() -> ())?) {
self.bounceAnimation()
completion?()
}
func bounceAnimation() {
let impliesAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
impliesAnimation.values = [1.0 ,1.4, 0.9, 1.15, 0.95, 1.02, 1.0]
impliesAnimation.duration = duration * 2
impliesAnimation.calculationMode = kCAAnimationCubic
imageView.layer.add(impliesAnimation, forKey: nil)
}
}
//MARK: - Step2
///二级子类
class ExampleIrregularityBasicContentView: ExampleBouncesContentView {
override init(frame: CGRect) {
super.init(frame: frame)
let color1 = Config.themeColor
let color2 = UIColor.orange
textColor = color1
highlightTextColor = color2
iconColor = color1
highlightIconColor = color2
//backdropColor = UIColor.init(red: 10/255.0, green: 66/255.0, blue: 91/255.0, alpha: 1.0)
//highlightBackdropColor = UIColor.init(red: 10/255.0, green: 66/255.0, blue: 91/255.0, alpha: 1.0)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - Step2'
///中间大圆View,一级子类
class ExampleIrregularityContentView: ESTabBarItemContentView {
override init(frame: CGRect) {
super.init(frame: frame)
//imageView.backgroundColor = UIColor.white
self.imageView.backgroundColor = UIColor.init(red: 23/255.0, green: 149/255.0, blue: 158/255.0, alpha: 1.0)
self.imageView.layer.borderWidth = 3.0
self.imageView.layer.borderColor = UIColor.init(white: 235 / 255.0, alpha: 1.0).cgColor
self.imageView.layer.cornerRadius = 35
self.insets = UIEdgeInsetsMake(-32, 0, 0, 0)
let transform = CGAffineTransform.identity
self.imageView.transform = transform
self.superview?.bringSubview(toFront: self)
let color1 = Config.themeColor
let color2 = UIColor.orange
textColor = color1
highlightTextColor = color2
iconColor = color1
highlightIconColor = color2
backdropColor = .clear
highlightBackdropColor = .clear
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let p = CGPoint.init(x: point.x - imageView.frame.origin.x, y: point.y - imageView.frame.origin.y)
return sqrt(pow(imageView.bounds.size.width / 2.0 - p.x, 2) + pow(imageView.bounds.size.height / 2.0 - p.y, 2)) < imageView.bounds.size.width / 2.0
}
public override func selectAnimation(animated: Bool, completion: (() -> ())?) {
let view = UIView.init(frame: CGRect.init(origin: CGPoint.zero, size: CGSize(width: 2.0, height: 2.0)))
view.layer.cornerRadius = 1.0
view.layer.opacity = 0.5
view.backgroundColor = UIColor.init(red: 10/255.0, green: 66/255.0, blue: 91/255.0, alpha: 1.0)
self.addSubview(view)
playMaskAnimation(animateView: view, target: self.imageView, completion: {
[weak view] in
view?.removeFromSuperview()
completion?()
})
}
public override func reselectAnimation(animated: Bool, completion: (() -> ())?) {
completion?()
}
public override func deselectAnimation(animated: Bool, completion: (() -> ())?) {
completion?()
}
public override func highlightAnimation(animated: Bool, completion: (() -> ())?) {
UIView.beginAnimations("small", context: nil)
UIView.setAnimationDuration(0.2)
let transform = self.imageView.transform.scaledBy(x: 0.8, y: 0.8)
self.imageView.transform = transform
UIView.commitAnimations()
completion?()
}
public override func dehighlightAnimation(animated: Bool, completion: (() -> ())?) {
UIView.beginAnimations("big", context: nil)
UIView.setAnimationDuration(0.2)
let transform = CGAffineTransform.identity
self.imageView.transform = transform
UIView.commitAnimations()
completion?()
}
private func playMaskAnimation(animateView view: UIView, target: UIView, completion: (() -> ())?) {
view.center = CGPoint.init(x: target.frame.origin.x + target.frame.size.width / 2.0, y: target.frame.origin.y + target.frame.size.height / 2.0)
let scale = POPBasicAnimation.init(propertyNamed: kPOPLayerScaleXY)
scale?.fromValue = NSValue.init(cgSize: CGSize.init(width: 1.0, height: 1.0))
scale?.toValue = NSValue.init(cgSize: CGSize.init(width: 36.0, height: 36.0))
scale?.beginTime = CACurrentMediaTime()
scale?.duration = 0.3
scale?.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut)
scale?.removedOnCompletion = true
let alpha = POPBasicAnimation.init(propertyNamed: kPOPLayerOpacity)
alpha?.fromValue = 0.6
alpha?.toValue = 0.6
alpha?.beginTime = CACurrentMediaTime()
alpha?.duration = 0.25
alpha?.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut)
alpha?.removedOnCompletion = true
view.layer.pop_add(scale, forKey: "scale")
view.layer.pop_add(alpha, forKey: "alpha")
scale?.completionBlock = ({ animation, finished in
completion?()
})
}
}
| apache-2.0 | 654f3cefb120a1897e2726dec8250a0c | 34.335196 | 155 | 0.628933 | 4.227941 | false | false | false | false |
timd/ProiOSTableCollectionViews | Ch12/DragAndDrop/Final state/DragAndDrop/DragAndDrop/CollectionViewController.swift | 1 | 3067 | //
// CollectionViewController.swift
// DragAndDrop
//
// Created by Tim on 20/07/15.
// Copyright © 2015 Tim Duckett. All rights reserved.
//
import UIKit
private let reuseIdentifier = "ReuseIdentifier"
class CollectionViewController: UICollectionViewController {
private let reuseIdentifier = "ReuseIdentifier"
private var dataArray = [String]()
private var selectedCell: UICollectionViewCell?
override func viewDidLoad() {
super.viewDidLoad()
// Allow drag-and-drop interaction
self.installsStandardGestureForInteractiveMovement = true
// Set up data
for index in 0...100 {
dataArray.append("\(index)")
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
collectionView?.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: -
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataArray.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
// Configure the cell
let label: UILabel = cell.viewWithTag(1000) as! UILabel
label.text = "Cell \(dataArray[indexPath.row])"
cell.contentView.layer.borderColor = UIColor.lightGrayColor().CGColor
cell.contentView.layer.borderWidth = 2.0
return cell
}
// MARK: -
// MARK: UICollectionViewDelegate
override func collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool {
// Highlight the cell
selectedCell = collectionView.cellForItemAtIndexPath(indexPath)
selectedCell?.contentView.layer.borderColor = UIColor.redColor().CGColor
return true
}
override func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
// Find object to move
let thingToMove = dataArray[sourceIndexPath.row]
// Remove old object
dataArray.removeAtIndex(sourceIndexPath.row)
// insert new copy of thing to move
dataArray.insert(thingToMove, atIndex: destinationIndexPath.row)
// Set the cell's background to the original light grey
selectedCell?.contentView.layer.borderColor = UIColor.lightGrayColor().CGColor
// Reload the data
collectionView.reloadData()
}
}
| mit | 9f728a477efe6713062d720eb958ae6d | 29.969697 | 165 | 0.673516 | 5.988281 | false | false | false | false |
FilipDolnik/KnightMovesProblem | KnightMovesProblem/KnightMoves.swift | 1 | 2717 | //
// KnightMoves.swift
// KnightMovesProblem
//
// Created by Filip Dolnik on 25.08.16.
// Copyright © 2016 Filip Dolnik. All rights reserved.
//
public struct KnightMoves {
public static func getNumberOfKnightMoves(x: Int, _ y: Int) -> Int {
let (a, b) = normalizeCoordinates(x, y)
if a < 7 {
return getNumberOfKnightMovesIn7x7(a, b)
} else {
return getNumberOfKnightMovesOutside7x7(a, b)
}
}
private static func normalizeCoordinates(x: Int, _ y: Int) -> (Int, Int) {
let ax = abs(x)
let ay = abs(y)
return (max(ax, ay), min(ax, ay))
}
private static func getNumberOfKnightMovesIn7x7(x: Int, _ y: Int) -> Int {
var a = x
var b = y
var moves = 0
while true {
(a, b) = normalizeCoordinates(a, b)
switch (a, b) {
case (0, 0):
break
case (1, 1), (2, 0), (3, 1):
moves += 2
case (4, 3), (1, 0):
moves += 3
default:
a -= 2
b -= 1
moves += 1
continue
}
return moves
}
}
private static func getNumberOfKnightMovesOutside7x7(x: Int, _ y: Int) -> Int {
let offset = 7
let dx = x - offset
let dy = y - offset
let a: Int
let b: Int
var moves: Int
if x == y {
(a, b, moves) = diagonalSuperMove(dx)
} else if y == 0 {
(a, b, moves) = horizontalSuperMove(dx, offset)
// Move 2x, y until y == 0
} else if dx / 2 > y {
let transientX = dx - (y * 2)
(a, b, moves) = horizontalSuperMove(transientX, offset)
moves += y
// Move 2x, y until x == y
} else if dx / 2 < dy {
let firstMoves = dx - dy
let transientX = dy - firstMoves
(a, b, moves) = diagonalSuperMove(transientX)
moves += firstMoves
// Move 2x, y until x < offset
} else {
moves = (dx / 2) + 1
a = dx - (moves * 2)
b = dy - moves
}
return getNumberOfKnightMovesIn7x7(a + offset, b + offset) + moves
}
private static func diagonalSuperMove(x: Int) -> (Int, Int, Int) {
let doubleMoves = (x / 3) + 1
let resultX = x - (doubleMoves * 3)
return (resultX, resultX, doubleMoves * 2)
}
private static func horizontalSuperMove(x: Int, _ offset: Int) -> (Int, Int, Int) {
let doubleMoves = (x / 4) + 1
return (x - (doubleMoves * 4), -offset, doubleMoves * 2)
}
}
| mit | b82d1dc880be0c63f276784dd842179b | 29.177778 | 87 | 0.476436 | 3.725652 | false | false | false | false |
git-hushuai/MOMO | MMHSMeterialProject/UINavigationController/BusinessFile/资讯 主界面/首页/View/CellItem/TableViewlthreeImageCell.swift | 1 | 6423 | //
// TableViewlthreeImageCell.swift
// MMHSMeterialProject
//
// Created by supin-tech on 16/4/15.
// Copyright © 2016年 hushuaike. All rights reserved.
//
import UIKit
class TableViewlthreeImageCell: UITableViewCell {
var contentLabel = UILabel();
var imageView1 = UIImageView();
var imageView2 = UIImageView();
var imageView3 = UIImageView();
var tag1Label = UILabel();
var tag2Label = UILabel();
var timeLabel = UILabel();
var sourceLLabel = UILabel();
var viewNumImageView = UIImageView();
var viewNumLabel = UILabel();
var caverViewBottom = UILabel()
var caverViewTop = UILabel();
var titleModel : TKTitleItemModel?{
didSet{
self.refreshWithTitleModel();
}
}
func refreshWithTitleModel(){
print("refreshWithTitleModel");
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.addSubview(self.caverViewTop)
self.caverViewTop.sd_layout()
.heightIs(0.5)
.topSpaceToView(self.contentView,0)
.leftSpaceToView(self.contentView,0)
.rightSpaceToView(self.contentView,0);
self.caverViewTop.backgroundColor = RGBA(0xda, g: 0xe2, b: 0xea, a: 1.0);
self.contentView.addSubview(self.contentLabel)
self.contentLabel.numberOfLines = 0;
self.contentLabel.sd_layout()
.leftSpaceToView(self.contentView,10)
.topSpaceToView(self.contentView,8)
.autoHeightRatio(0)
.rightSpaceToView(self.contentView,10);
self.contentLabel.isAttributedContent = true;
self.contentView.sd_addSubviews([self.imageView1,self.imageView2,self.imageView3]);
self.contentView.sd_equalWidthSubviews = [self.imageView1,self.imageView2,self.imageView3];
self.imageView1.sd_layout()
.topSpaceToView(self.contentLabel,5)
.leftSpaceToView(self.contentView,10)
.heightIs(58.0);
self.imageView2.sd_layout()
.topSpaceToView(self.contentLabel,5)
.leftSpaceToView(self.imageView1,3)
.heightIs(58.0);
self.imageView3.sd_layout()
.topSpaceToView(self.contentLabel,5)
.leftSpaceToView(self.imageView2,3)
.heightIs(58.0)
.rightSpaceToView(self.contentView,10);
self.contentView.addSubview(self.tag1Label)
self.tag1Label.sd_layout()
.leftSpaceToView(self.contentView,10)
.topSpaceToView(self.contentLabel,8)
.heightIs(11);
self.tag1Label.sd_cornerRadiusFromHeightRatio = NSNumber.init(float: 0.5);
self.tag1Label.layer.borderWidth = 0.5;
self.tag1Label.layer.borderColor = RGBA(0xda, g: 0xe2, b: 0xea, a: 1.0).CGColor
self.tag1Label.setSingleLineAutoResizeWithMaxWidth(100);
self.tag1Label.textColor = RGBA(0xe7, g: 0x4e, b: 0x4e, a: 1.0)
self.tag1Label.font = UIFont.systemFontOfSize(8);
self.contentView.addSubview(self.tag2Label)
self.tag2Label.sd_layout()
.topEqualToView(self.tag1Label)
.heightIs(11);
self.tag2Label.sd_cornerRadiusFromHeightRatio = NSNumber.init(float: 0.5);
self.tag2Label.layer.borderWidth = 0.5;
self.tag2Label.layer.borderColor = RGBA(0xda, g: 0xe2, b: 0xea, a: 1.0).CGColor
self.tag2Label.setSingleLineAutoResizeWithMaxWidth(100)
self.tag2Label.textColor = RGBA(0xe7, g: 0x4e, b: 0x4e, a: 1.0)
self.tag1Label.setupAutoWidthWithRightView(self.tag2Label, rightMargin: 3);
self.contentView.addSubview(self.timeLabel)
self.timeLabel.sd_layout()
.topSpaceToView(self.contentLabel,8)
.heightIs(11);
self.timeLabel.textAlignment = .Left;
self.timeLabel.setSingleLineAutoResizeWithMaxWidth(80);
self.tag2Label.setupAutoWidthWithRightView(self.timeLabel, rightMargin: 3);
self.timeLabel.font = UIFont.systemFontOfSize(8)
self.timeLabel.textColor = RGBA(0x99, g: 0x99, b: 0x99, a: 1.0)
self.contentView.addSubview(self.viewNumLabel)
self.viewNumLabel.sd_layout()
.rightSpaceToView(self.contentView,10)
.heightIs(11)
.topEqualToView(self.tag1Label)
self.viewNumLabel.textAlignment = .Right;
self.viewNumLabel.font = UIFont.systemFontOfSize(8);
self.viewNumLabel.textColor = RGBA(0x99, g: 0x99, b: 0x99, a: 1.0)
self.contentView.addSubview(self.viewNumImageView)
self.viewNumImageView.sd_layout()
.rightSpaceToView(self.viewNumLabel,3)
.topEqualToView(self.tag1Label)
.widthIs(14.0)
.heightIs(14.0);
self.viewNumImageView.image = UIImage.init(named: "阅读量@3x")
self.contentView.addSubview(self.sourceLLabel)
self.sourceLLabel.font = UIFont.systemFontOfSize(8);
self.sourceLLabel.textColor = RGBA(0x99, g: 0x99, b: 0x99, a: 1.0)
self.sourceLLabel.sd_layout()
.rightSpaceToView(self.viewNumImageView,3)
.topEqualToView(self.viewNumLabel)
.heightIs(11);
self.sourceLLabel.textAlignment = .Right;
self.sourceLLabel.setSingleLineAutoResizeWithMaxWidth(100);
self.contentView.addSubview(self.caverViewBottom)
self.caverViewBottom.sd_layout()
.heightIs(0.5)
.topSpaceToView(self.tag1Label,10)
.leftSpaceToView(self.contentView,0)
.rightSpaceToView(self.contentView,0);
self.caverViewBottom.backgroundColor = RGBA(0xda, g: 0xe2, b: 0xea, a: 1.0);
self.setupAutoHeightWithBottomView(self.caverViewBottom, bottomMargin: 0);
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
// MARK: rgb
func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat)->UIColor {
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) }
}
| mit | 9e0ced6b951c7e83a8c7fc56b56eae02 | 37.860606 | 99 | 0.639114 | 3.980137 | false | false | false | false |
sudeepunnikrishnan/ios-sdk | Instamojo/Card.swift | 1 | 2095 | //
// Card.swift
// Instamojo
//
// Created by Sukanya Raj on 15/02/17.
// Copyright © 2017 Sukanya Raj. All rights reserved.
//
import UIKit
public class Card: NSObject {
public var cardHolderName: String
public var cardNumber: String
public var date: String
public var cvv: String
public var savedCard: Bool
override init() {
self.cardNumber = ""
self.cvv = ""
self.date = ""
self.cardHolderName = ""
self.savedCard = false
}
public init(cardHolderName: String, cardNumber: String, date: String, cvv: String, savedCard: Bool) {
self.cardHolderName = cardHolderName
self.cardNumber = cardNumber
self.date = date
self.cvv = cvv
self.savedCard = savedCard
}
public func getExpiryMonth() -> String {
return self.date.components(separatedBy: "/")[0]
}
public func getExpiryYear() -> String {
return self.date.components(separatedBy: "/")[1]
}
public func isValidCard() -> Bool {
return isValidCVV() && isValidDate() && isValidCardNumber() && isValidCardHolderName()
}
public func isValidCardNumber() -> Bool {
return self.cardNumber.isValidCardNumber() && self.cardNumber.validLength() != self.cardNumber.characters.count
}
public func isValidCardHolderName() -> Bool {
if self.cardHolderName.isEmpty {
return false
} else {
return true
}
}
public func isValidDate() -> Bool {
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let currentYear = components.year
let month = getExpiryMonth()
let year = getExpiryYear()
if Int(month)! > 12 || Int(year)! < currentYear! {
return false
} else {
return false
}
}
public func isValidCVV() -> Bool {
if self.cvv.isEmpty {
return false
} else {
return true
}
}
}
| lgpl-3.0 | 25b1e30b387b63b13c3e546f89c8adac | 23.928571 | 119 | 0.585005 | 4.512931 | false | false | false | false |
jcavar/refresher | PullToRefreshDemo/PullToRefreshViewController.swift | 1 | 3985 | //
// ViewController.swift
//
// Copyright (c) 2014 Josip Cavar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import Refresher
enum ExampleMode {
case `default`
case beat
case pacman
case custom
}
class PullToRefreshViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var exampleMode = ExampleMode.default
override func viewDidLoad() {
super.viewDidLoad()
switch exampleMode {
case .default:
tableView.addPullToRefreshWithAction {
OperationQueue().addOperation {
sleep(2)
OperationQueue.main.addOperation {
self.tableView.stopPullToRefresh()
}
}
}
case .beat:
let beatAnimator = BeatAnimator(frame: CGRect(x: 0, y: 0, width: 320, height: 80))
tableView.addPullToRefreshWithAction({
OperationQueue().addOperation {
sleep(2)
OperationQueue.main.addOperation {
self.tableView.stopPullToRefresh()
}
}
}, withAnimator: beatAnimator)
case .pacman:
let pacmanAnimator = PacmanAnimator(frame: CGRect(x: 0, y: 0, width: 320, height: 80))
tableView.addPullToRefreshWithAction({
OperationQueue().addOperation {
sleep(2)
OperationQueue.main.addOperation {
self.tableView.stopPullToRefresh()
}
}
}, withAnimator: pacmanAnimator)
case .custom:
if let customSubview = Bundle.main.loadNibNamed("CustomSubview", owner: self, options: nil)?.first as? CustomSubview {
tableView.addPullToRefreshWithAction({
OperationQueue().addOperation {
sleep(2)
OperationQueue.main.addOperation {
self.tableView.stopPullToRefresh()
}
}
}, withAnimator: customSubview)
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.startPullToRefresh()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func tableView(_ tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return 50
}
@objc func tableView(_ tableView: UITableView!, cellForRowAtIndexPath indexPath: IndexPath!) -> UITableViewCell! {
let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
cell.textLabel?.text = "Row " + String(indexPath.row + 1)
return cell
}
}
| mit | d701925b2b23bba46de5cad3731d0de5 | 36.59434 | 130 | 0.606775 | 5.511757 | false | false | false | false |
talk2junior/iOSND-Beginning-iOS-Swift-3.0 | Playground Collection/Part 7 - Alien Adventure 4/FadeExtensionDemo/FadeExtensionDemo/ViewController.swift | 2 | 1315 | //
// ViewController.swift
// FadeExtensionDemo
//
// Created by Gabrielle Miller-Messner on 6/26/15.
// Copyright (c) 2015 Gabrielle Miller-Messner. All rights reserved.
//
import UIKit
// MARK: - ViewController: UIViewController
class ViewController: UIViewController {
// MARK: Outlets
@IBOutlet weak var imageView: UIImageView!
// MARK: Actions
@IBAction func sunRiseAndSet(_ sender: AnyObject) {
// Fade out
UIView.animate(withDuration: 1.0, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.imageView.alpha = 0.0
}, completion: {
(finished: Bool) -> Void in
//Once the label is completely invisible, set the text and fade it back in
if (self.imageView.image == UIImage(named: "sunrise")) {
self.imageView.image = UIImage(named:"sunset")!
} else {
self.imageView.image = UIImage(named:"sunrise")!
}
// Fade in
UIView.animate(withDuration: 1.0, delay:0.0, options:UIViewAnimationOptions.curveEaseIn, animations: {
self.imageView.alpha = 1.0
}, completion: nil)
})
}
}
| mit | 977e01dc4c2c063926709c217d857862 | 31.073171 | 118 | 0.562738 | 4.781818 | false | false | false | false |
daviwiki/Gourmet_Swift | Gourmet/Gourmet/View/Main/MainFactory.swift | 1 | 1071 | //
// LoginFactory.swift
// Gourmet
//
// Created by David Martinez on 08/12/2016.
// Copyright © 2016 Atenea. All rights reserved.
//
import Foundation
import GourmetModel
class MainFactory : NSObject {
private static let factory = MainFactory()
override private init() {
super.init()
}
open class var `default`: MainFactory {
get {
return factory
}
}
func getLoginVC () -> LoginVC {
return LoginVC(nibName: "LoginVC", bundle: nil)
}
func getSignUpView () -> SignUpVC {
return SignUpVC(nibName: "SignUpVC", bundle: nil)
}
func getMainPresenter () -> MainPresenter {
let storedInteractor = GetStoredAccount()
let accountObserver = StoreAccountObserver()
let mapper = MapAccountToAccountVM()
let presenter = MainPresenter(getAccount: storedInteractor,
accountObserver: accountObserver,
mapper: mapper)
return presenter
}
}
| mit | 5a2dd8e91ea491e133f799b9102fd3fd | 23.883721 | 71 | 0.581308 | 4.798206 | false | false | false | false |
matthewpurcell/firefox-ios | Storage/SQL/BrowserTable.swift | 1 | 21525 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
let BookmarksFolderTitleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let BookmarksFolderTitleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let BookmarksFolderTitleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let BookmarksFolderTitleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let TableBookmarks = "bookmarks"
let TableBookmarksMirror = "bookmarksMirror" // Added in v9.
let TableBookmarksMirrorStructure = "bookmarksMirrorStructure" // Added in v10.
let TableFavicons = "favicons"
let TableHistory = "history"
let TableCachedTopSites = "cached_top_sites"
let TableDomains = "domains"
let TableVisits = "visits"
let TableFaviconSites = "favicon_sites"
let TableQueuedTabs = "queue"
let ViewWidestFaviconsForSites = "view_favicons_widest"
let ViewHistoryIDsWithWidestFavicons = "view_history_id_favicon"
let ViewIconForURL = "view_icon_for_url"
let IndexHistoryShouldUpload = "idx_history_should_upload"
let IndexVisitsSiteIDDate = "idx_visits_siteID_date" // Removed in v6.
let IndexVisitsSiteIDIsLocalDate = "idx_visits_siteID_is_local_date" // Added in v6.
let IndexBookmarksMirrorStructureParentIdx = "idx_bookmarksMirrorStructure_parent_idx" // Added in v10.
private let AllTables: [String] = [
TableDomains,
TableFavicons,
TableFaviconSites,
TableHistory,
TableVisits,
TableCachedTopSites,
TableBookmarks,
TableBookmarksMirror,
TableBookmarksMirrorStructure,
TableQueuedTabs,
]
private let AllViews: [String] = [
ViewHistoryIDsWithWidestFavicons,
ViewWidestFaviconsForSites,
ViewIconForURL,
]
private let AllIndices: [String] = [
IndexHistoryShouldUpload,
IndexVisitsSiteIDIsLocalDate,
IndexBookmarksMirrorStructureParentIdx,
]
private let AllTablesIndicesAndViews: [String] = AllViews + AllIndices + AllTables
private let log = Logger.syncLogger
/**
* The monolithic class that manages the inter-related history etc. tables.
* We rely on SQLiteHistory having initialized the favicon table first.
*/
public class BrowserTable: Table {
static let DefaultVersion = 11
// TableInfo fields.
var name: String { return "BROWSER" }
var version: Int { return BrowserTable.DefaultVersion }
let sqliteVersion: Int32
let supportsPartialIndices: Bool
public init() {
let v = sqlite3_libversion_number()
self.sqliteVersion = v
self.supportsPartialIndices = v >= 3008000 // 3.8.0.
let ver = String.fromCString(sqlite3_libversion())!
log.info("SQLite version: \(ver) (\(v)).")
}
func run(db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool {
let err = db.executeChange(sql, withArgs: args)
if err != nil {
log.error("Error running SQL in BrowserTable. \(err?.localizedDescription)")
log.error("SQL was \(sql)")
}
return err == nil
}
// TODO: transaction.
func run(db: SQLiteDBConnection, queries: [(String, Args?)]) -> Bool {
for (sql, args) in queries {
if !run(db, sql: sql, args: args) {
return false
}
}
return true
}
func run(db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql) {
return false
}
}
return true
}
func runValidQueries(db: SQLiteDBConnection, queries: [(String?, Args?)]) -> Bool {
for (sql, args) in queries {
if let sql = sql {
if !run(db, sql: sql, args: args) {
return false
}
}
}
return true
}
func runValidQueries(db: SQLiteDBConnection, queries: [String?]) -> Bool {
return self.run(db, queries: optFilter(queries))
}
func prepopulateRootFolders(db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.Folder.rawValue
let root = BookmarkRoots.RootID
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, BookmarksFolderTitleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, BookmarksFolderTitleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, BookmarksFolderTitleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, BookmarksFolderTitleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
let topSitesTableCreate =
"CREATE TABLE IF NOT EXISTS \(TableCachedTopSites) (" +
"historyID INTEGER, " +
"url TEXT NOT NULL, " +
"title TEXT NOT NULL, " +
"guid TEXT NOT NULL UNIQUE, " +
"domain_id INTEGER, " +
"domain TEXT NO NULL, " +
"localVisitDate REAL, " +
"remoteVisitDate REAL, " +
"localVisitCount INTEGER, " +
"remoteVisitCount INTEGER, " +
"iconID INTEGER, " +
"iconURL TEXT, " +
"iconDate REAL, " +
"iconType INTEGER, " +
"iconWidth INTEGER, " +
"frecencies REAL" +
")"
let domainsTableCreate =
"CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
let queueTableCreate =
"CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
func getBookmarksMirrorTableCreationString() -> String {
// The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry.
// For now we have the simplest possible schema: everything in one.
let sql =
"CREATE TABLE IF NOT EXISTS \(TableBookmarksMirror) " +
// Shared fields.
"( id INTEGER PRIMARY KEY AUTOINCREMENT" +
", guid TEXT NOT NULL UNIQUE" +
", type TINYINT NOT NULL" + // Type enum. TODO: BookmarkNodeType needs to be extended.
// Record/envelope metadata that'll allow us to do merges.
", server_modified INTEGER NOT NULL" + // Milliseconds.
", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean
", hasDupe TINYINT NOT NULL DEFAULT 0" + // Boolean, 0 (false) if deleted.
", parentid TEXT" + // GUID
", parentName TEXT" +
// Type-specific fields. These should be NOT NULL in many cases, but we're going
// for a sparse schema, so this'll do for now. Enforce these in the application code.
", feedUri TEXT, siteUri TEXT" + // LIVEMARKS
", pos INT" + // SEPARATORS
", title TEXT, description TEXT" + // FOLDERS, BOOKMARKS, QUERIES
", bmkUri TEXT, tags TEXT, keyword TEXT" + // BOOKMARKS, QUERIES
", folderName TEXT, queryId TEXT" + // QUERIES
", CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1)" +
", CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1)" +
")"
return sql
}
/**
* We need to explicitly store what's provided by the server, because we can't rely on
* referenced child nodes to exist yet!
*/
func getBookmarksMirrorStructureTableCreationString() -> String {
// TODO: index me.
let sql =
"CREATE TABLE IF NOT EXISTS \(TableBookmarksMirrorStructure) " +
"( parent TEXT NOT NULL REFERENCES \(TableBookmarksMirror)(guid) ON DELETE CASCADE" +
", child TEXT NOT NULL" + // Should be the GUID of a child.
", idx INTEGER NOT NULL" + // Should advance from 0.
")"
return sql
}
func create(db: SQLiteDBConnection) -> Bool {
let favicons =
"CREATE TABLE IF NOT EXISTS \(TableFavicons) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" +
") "
let history =
"CREATE TABLE IF NOT EXISTS \(TableHistory) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS \(TableVisits) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON \(TableVisits) (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES \(TableFavicons)(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"\(TableFavicons).id AS iconID, " +
"\(TableFavicons).url AS iconURL, " +
"\(TableFavicons).date AS iconDate, " +
"\(TableFavicons).type AS iconType, " +
"MAX(\(TableFavicons).width) AS iconWidth " +
"FROM \(TableFaviconSites), \(TableFavicons) WHERE " +
"\(TableFaviconSites).faviconID = \(TableFavicons).id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT \(TableHistory).id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM \(TableHistory) " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " +
"\(TableHistory).id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS \(TableBookmarks) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES \(TableBookmarks)(id) NOT NULL, " +
"faviconID INTEGER REFERENCES \(TableFavicons)(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let bookmarksMirror = getBookmarksMirrorTableCreationString()
let bookmarksMirrorStructure = getBookmarksMirrorStructureTableCreationString()
let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " +
"ON \(TableBookmarksMirrorStructure) (parent, idx)"
let queries: [String] = [
self.domainsTableCreate,
history,
favicons,
visits,
bookmarks,
bookmarksMirror,
bookmarksMirrorStructure,
indexStructureParentIdx,
faviconSites,
indexShouldUpload,
indexSiteIDDate,
widestFavicons,
historyIDsWithIcon,
iconForURL,
self.queueTableCreate,
self.topSitesTableCreate,
]
assert(queries.count == AllTablesIndicesAndViews.count, "Did you forget to add your table, index, or view to the list?")
log.debug("Creating \(queries.count) tables, views, and indices.")
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
func updateTable(db: SQLiteDBConnection, from: Int) -> Bool {
let to = BrowserTable.DefaultVersion
if from == to {
log.debug("Skipping update from \(from) to \(to).")
return true
}
if from == 0 {
// This is likely an upgrade from before Bug 1160399.
log.debug("Updating browser tables from zero. Assuming drop and recreate.")
return drop(db) && create(db)
}
if from > to {
// This is likely an upgrade from before Bug 1160399.
log.debug("Downgrading browser tables. Assuming drop and recreate.")
return drop(db) && create(db)
}
log.debug("Updating browser tables from \(from) to \(to).")
if from < 4 && to >= 4 {
return drop(db) && create(db)
}
if from < 5 && to >= 5 {
if !self.run(db, sql: self.queueTableCreate) {
return false
}
}
if from < 6 && to >= 6 {
if !self.run(db, queries: [
"DROP INDEX IF EXISTS \(IndexVisitsSiteIDDate)",
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) ON \(TableVisits) (siteID, is_local, date)",
self.domainsTableCreate,
"ALTER TABLE \(TableHistory) ADD COLUMN domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE",
]) {
return false
}
let urls = db.executeQuery("SELECT DISTINCT url FROM \(TableHistory) WHERE url IS NOT NULL",
factory: { $0["url"] as! String })
if !fillDomainNamesFromCursor(urls, db: db) {
return false
}
}
if from < 8 && to == 8 {
// Nothing to do: we're just shifting the favicon table to be owned by this class.
return true
}
if from < 9 && to >= 9 {
if !self.run(db, sql: getBookmarksMirrorTableCreationString()) {
return false
}
}
if from < 10 && to >= 10 {
if !self.run(db, sql: getBookmarksMirrorStructureTableCreationString()) {
return false
}
let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " +
"ON \(TableBookmarksMirrorStructure) (parent, idx)"
if !self.run(db, sql: indexStructureParentIdx) {
return false
}
}
if from < 11 && to >= 11 {
if !self.run(db, sql: self.topSitesTableCreate) {
return false
}
}
return true
}
private func fillDomainNamesFromCursor(cursor: Cursor<String>, db: SQLiteDBConnection) -> Bool {
if cursor.count == 0 {
return true
}
// URL -> hostname, flattened to make args.
var pairs = Args()
pairs.reserveCapacity(cursor.count * 2)
for url in cursor {
if let url = url, host = url.asURL?.normalizedHost() {
pairs.append(url)
pairs.append(host)
}
}
cursor.close()
let tmpTable = "tmp_hostnames"
let table = "CREATE TEMP TABLE \(tmpTable) (url TEXT NOT NULL UNIQUE, domain TEXT NOT NULL, domain_id INT)"
if !self.run(db, sql: table, args: nil) {
log.error("Can't create temporary table. Unable to migrate domain names. Top Sites is likely to be broken.")
return false
}
// Now insert these into the temporary table. Chunk by an even number, for obvious reasons.
let chunks = chunk(pairs, by: BrowserDB.MaxVariableNumber - (BrowserDB.MaxVariableNumber % 2))
for chunk in chunks {
let ins = "INSERT INTO \(tmpTable) (url, domain) VALUES " +
Array<String>(count: chunk.count / 2, repeatedValue: "(?, ?)").joinWithSeparator(", ")
if !self.run(db, sql: ins, args: Array(chunk)) {
log.error("Couldn't insert domains into temporary table. Aborting migration.")
return false
}
}
// Now make those into domains.
let domains = "INSERT OR IGNORE INTO \(TableDomains) (domain) SELECT DISTINCT domain FROM \(tmpTable)"
// … and fill that temporary column.
let domainIDs = "UPDATE \(tmpTable) SET domain_id = (SELECT id FROM \(TableDomains) WHERE \(TableDomains).domain = \(tmpTable).domain)"
// Update the history table from the temporary table.
let updateHistory = "UPDATE \(TableHistory) SET domain_id = (SELECT domain_id FROM \(tmpTable) WHERE \(tmpTable).url = \(TableHistory).url)"
// Clean up.
let dropTemp = "DROP TABLE \(tmpTable)"
// Now run these.
if !self.run(db, queries: [domains,
domainIDs,
updateHistory,
dropTemp]) {
log.error("Unable to migrate domains.")
return false
}
return true
}
/**
* The Table mechanism expects to be able to check if a 'table' exists. In our (ab)use
* of Table, that means making sure that any of our tables and views exist.
* We do that by fetching all tables from sqlite_master with matching names, and verifying
* that we get back more than one.
* Note that we don't check for views -- trust to luck.
*/
func exists(db: SQLiteDBConnection) -> Bool {
return db.tablesExist(AllTables)
}
func drop(db: SQLiteDBConnection) -> Bool {
log.debug("Dropping all browser tables.")
let additional = [
"DROP TABLE IF EXISTS faviconSites" // We renamed it to match naming convention.
]
let views = AllViews.map { "DROP VIEW IF EXISTS \($0)" }
let indices = AllIndices.map { "DROP INDEX IF EXISTS \($0)" }
let tables = AllTables.map { "DROP TABLE IF EXISTS \($0)" }
let queries = Array([views, indices, tables, additional].flatten())
return self.run(db, queries: queries)
}
} | mpl-2.0 | 1740c5ce677a39fdf49b949e6c577699 | 39.382739 | 238 | 0.592018 | 4.687064 | false | false | false | false |
Jigsaw-Code/outline-client | src/cordova/plugin/apple/src/OutlinePlugin.swift | 1 | 14949 | // Copyright 2018 The Outline Authors
//
// 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 CocoaLumberjack
import CocoaLumberjackSwift
import NetworkExtension
import Sentry
@objcMembers
class OutlinePlugin: CDVPlugin {
private enum Action {
static let start = "start"
static let stop = "stop"
static let onStatusChange = "onStatusChange"
}
public static let kAppQuitNotification = "outlinePluginAppQuitNotification"
public static let kVpnConnectedNotification = "outlineVpnConnected"
public static let kVpnDisconnectedNotification = "outlineVpnDisconnected"
public static let kMaxBreadcrumbs: UInt = 100
private var callbacks: [String: String]!
#if os(macOS)
// cordova-osx does not support URL interception. Until it does, we have version-controlled
// AppDelegate.m (intercept) and Outline-Info.plist (register protocol) to handle ss:// URLs.
private var urlHandler: CDVMacOsUrlHandler?
private static let kPlatform = "macOS"
#else
private static let kPlatform = "iOS"
#endif
override func pluginInitialize() {
OutlineSentryLogger.sharedInstance.initializeLogging()
callbacks = [String: String]()
OutlineVpn.shared.onVpnStatusChange(onVpnStatusChange)
#if os(macOS)
self.urlHandler = CDVMacOsUrlHandler.init(self.webView)
NotificationCenter.default.addObserver(
self, selector: #selector(self.stopVpnOnAppQuit),
name: NSNotification.Name(rawValue: OutlinePlugin.kAppQuitNotification),
object: nil)
#endif
#if os(iOS)
self.migrateLocalStorage()
#endif
}
/**
Starts the VPN. This method is idempotent for a given tunnel.
- Parameters:
- command: CDVInvokedUrlCommand, where command.arguments
- tunnelId: string, ID of the tunnel
- config: [String: Any], represents a server configuration
*/
func start(_ command: CDVInvokedUrlCommand) {
guard let tunnelId = command.argument(at: 0) as? String else {
return sendError("Missing tunnel ID", callbackId: command.callbackId,
errorCode: OutlineVpn.ErrorCode.illegalServerConfiguration)
}
DDLogInfo("\(Action.start) \(tunnelId)")
guard let config = command.argument(at: 1) as? [String: Any], containsExpectedKeys(config) else {
return sendError("Invalid configuration", callbackId: command.callbackId,
errorCode: OutlineVpn.ErrorCode.illegalServerConfiguration)
}
let tunnel = OutlineTunnel(id: tunnelId, config: config)
OutlineVpn.shared.start(tunnel) { errorCode in
if errorCode == OutlineVpn.ErrorCode.noError {
#if os(macOS)
NotificationCenter.default.post(
name: NSNotification.Name(rawValue: OutlinePlugin.kVpnConnectedNotification), object: nil)
#endif
self.sendSuccess(callbackId: command.callbackId)
} else {
self.sendError("Failed to start VPN", callbackId: command.callbackId,
errorCode: errorCode)
}
}
}
/**
Stops the VPN. Sends an error if the given tunnel is not running.
- Parameters:
- command: CDVInvokedUrlCommand, where command.arguments
- tunnelId: string, ID of the tunnel
*/
func stop(_ command: CDVInvokedUrlCommand) {
guard let tunnelId = command.argument(at: 0) as? String else {
return sendError("Missing tunnel ID", callbackId: command.callbackId)
}
DDLogInfo("\(Action.stop) \(tunnelId)")
OutlineVpn.shared.stop(tunnelId)
sendSuccess(callbackId: command.callbackId)
#if os(macOS)
NotificationCenter.default.post(
name: NSNotification.Name(rawValue: OutlinePlugin.kVpnDisconnectedNotification), object: nil)
#endif
}
func isRunning(_ command: CDVInvokedUrlCommand) {
guard let tunnelId = command.argument(at: 0) as? String else {
return sendError("Missing tunnel ID", callbackId: command.callbackId)
}
DDLogInfo("isRunning \(tunnelId)")
sendSuccess(OutlineVpn.shared.isActive(tunnelId), callbackId: command.callbackId)
}
func isServerReachable(_ command: CDVInvokedUrlCommand) {
DDLogInfo("isServerReachable")
guard let host = command.argument(at: 0) as? String else {
return sendError("Missing host address" , callbackId: command.callbackId)
}
guard let port = command.argument(at: 1) as? UInt16 else {
return sendError("Missing host port", callbackId: command.callbackId)
}
OutlineVpn.shared.isServerReachable(host: host, port: port) { errorCode in
self.sendSuccess(errorCode == OutlineVpn.ErrorCode.noError, callbackId: command.callbackId)
}
}
func onStatusChange(_ command: CDVInvokedUrlCommand) {
guard let tunnelId = command.argument(at: 0) as? String else {
return sendError("Missing tunnel ID", callbackId: command.callbackId)
}
DDLogInfo("\(Action.onStatusChange) \(tunnelId)")
setCallbackId(command.callbackId!, action: Action.onStatusChange, tunnelId: tunnelId)
}
// MARK: Error reporting
func initializeErrorReporting(_ command: CDVInvokedUrlCommand) {
DDLogInfo("initializeErrorReporting")
guard let sentryDsn = command.argument(at: 0) as? String else {
return sendError("Missing error reporting API key.", callbackId: command.callbackId)
}
SentrySDK.start { options in
options.dsn = sentryDsn
options.maxBreadcrumbs = OutlinePlugin.kMaxBreadcrumbs
// Remove device identifier, timezone, and memory stats.
options.beforeSend = { event in
event.context?["app"]?.removeValue(forKey: "device_app_hash")
if var device = event.context?["device"] {
device.removeValue(forKey: "timezone")
device.removeValue(forKey: "memory_size")
device.removeValue(forKey: "free_memory")
device.removeValue(forKey: "usable_memory")
device.removeValue(forKey: "storage_size")
event.context?["device"] = device
}
return event
}
}
sendSuccess(true, callbackId: command.callbackId)
}
func reportEvents(_ command: CDVInvokedUrlCommand) {
var uuid: String
if let eventId = command.argument(at: 0) as? String {
// Associate this event with the one reported from JS.
SentrySDK.configureScope { scope in
scope.setTag(value: eventId, key: "user_event_id")
}
uuid = eventId
} else {
uuid = NSUUID().uuidString
}
OutlineSentryLogger.sharedInstance.addVpnExtensionLogsToSentry()
SentrySDK.capture(message: "\(OutlinePlugin.kPlatform) report (\(uuid))") { scope in
scope.setLevel(.info)
}
self.sendSuccess(true, callbackId: command.callbackId)
}
#if os(macOS)
func quitApplication(_ command: CDVInvokedUrlCommand) {
NSApplication.shared.terminate(self)
}
#endif
// MARK: Helpers
@objc private func stopVpnOnAppQuit() {
if let activeTunnelId = OutlineVpn.shared.activeTunnelId {
OutlineVpn.shared.stop(activeTunnelId)
}
}
// Receives NEVPNStatusDidChange notifications. Calls onTunnelStatusChange for the active
// tunnel.
func onVpnStatusChange(vpnStatus: NEVPNStatus, tunnelId: String) {
var tunnelStatus: Int
switch vpnStatus {
case .connected:
#if os(macOS)
NotificationCenter.default.post(
name: NSNotification.Name(rawValue: OutlinePlugin.kVpnConnectedNotification), object: nil)
#endif
tunnelStatus = OutlineTunnel.TunnelStatus.connected.rawValue
case .disconnected:
#if os(macOS)
NotificationCenter.default.post(
name: NSNotification.Name(rawValue: OutlinePlugin.kVpnDisconnectedNotification), object: nil)
#endif
tunnelStatus = OutlineTunnel.TunnelStatus.disconnected.rawValue
case .reasserting:
tunnelStatus = OutlineTunnel.TunnelStatus.reconnecting.rawValue
default:
return; // Do not report transient or invalid states.
}
DDLogDebug("Calling onStatusChange (\(tunnelStatus)) for tunnel \(tunnelId)")
if let callbackId = getCallbackIdFor(action: Action.onStatusChange,
tunnelId: tunnelId,
keepCallback: true) {
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: Int32(tunnelStatus))
send(pluginResult: result, callbackId: callbackId, keepCallback: true)
}
}
// Returns whether |config| contains all the expected keys
private func containsExpectedKeys(_ config: [String: Any]?) -> Bool {
return config?["host"] != nil && config?["port"] != nil &&
config?["password"] != nil && config?["method"] != nil
}
// MARK: Callback helpers
private func sendSuccess(callbackId: String, keepCallback: Bool = false) {
let result = CDVPluginResult(status: CDVCommandStatus_OK)
send(pluginResult: result, callbackId: callbackId, keepCallback: keepCallback)
}
private func sendSuccess(_ operationResult: Bool, callbackId: String, keepCallback: Bool = false) {
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: operationResult)
send(pluginResult: result, callbackId: callbackId, keepCallback: keepCallback)
}
private func sendError(_ message: String, callbackId: String,
errorCode: OutlineVpn.ErrorCode = OutlineVpn.ErrorCode.undefined,
keepCallback: Bool = false) {
DDLogError(message)
let result = CDVPluginResult(status: CDVCommandStatus_ERROR,
messageAs: Int32(errorCode.rawValue))
send(pluginResult: result, callbackId: callbackId, keepCallback: keepCallback)
}
private func send(pluginResult: CDVPluginResult?, callbackId: String, keepCallback: Bool) {
guard let result = pluginResult else {
return DDLogWarn("Missing plugin result");
}
result.setKeepCallbackAs(keepCallback)
self.commandDelegate?.send(result, callbackId: callbackId)
}
// Maps |action| and |tunnelId| to |callbackId| in the callbacks dictionary.
private func setCallbackId(_ callbackId: String, action: String, tunnelId: String) {
DDLogDebug("\(action):\(tunnelId):\(callbackId)")
callbacks["\(action):\(tunnelId)"] = callbackId
}
// Retrieves the callback ID for |action| and |tunnelId|. Unmaps the entry if |keepCallback|
// is false.
private func getCallbackIdFor(action: String, tunnelId: String?,
keepCallback: Bool = false) -> String? {
guard let tunnelId = tunnelId else {
return nil
}
let key = "\(action):\(tunnelId)"
guard let callbackId = callbacks[key] else {
DDLogWarn("Callback id not found for action \(action) and tunnel \(tunnelId)")
return nil
}
if (!keepCallback) {
callbacks.removeValue(forKey: key)
}
return callbackId
}
// Migrates local storage files from UIWebView to WKWebView.
private func migrateLocalStorage() {
// Local storage backing files have the following naming format: $scheme_$hostname_$port.localstorage
// With UIWebView, the app used the file:// scheme with no hostname and any port.
let kUIWebViewLocalStorageFilename = "file__0.localstorage"
// With WKWebView, the app uses the app:// scheme with localhost as a hostname and any port.
let kWKWebViewLocalStorageFilename = "app_localhost_0.localstorage"
let fileManager = FileManager.default
let appLibraryDir = fileManager.urls(for: .libraryDirectory, in: .userDomainMask)[0]
var uiWebViewLocalStorageDir: URL
if fileManager.fileExists(atPath: appLibraryDir.appendingPathComponent(
"WebKit/LocalStorage/\(kUIWebViewLocalStorageFilename)").relativePath) {
uiWebViewLocalStorageDir = appLibraryDir.appendingPathComponent("WebKit/LocalStorage")
} else {
uiWebViewLocalStorageDir = appLibraryDir.appendingPathComponent("Caches")
}
let uiWebViewLocalStorage = uiWebViewLocalStorageDir.appendingPathComponent(kUIWebViewLocalStorageFilename)
if !fileManager.fileExists(atPath: uiWebViewLocalStorage.relativePath) {
return DDLogInfo("Not migrating, UIWebView local storage files missing.")
}
let wkWebViewLocalStorageDir = appLibraryDir.appendingPathComponent("WebKit/WebsiteData/LocalStorage/")
let wkWebViewLocalStorage = wkWebViewLocalStorageDir.appendingPathComponent(kWKWebViewLocalStorageFilename)
// Only copy the local storage files if they don't exist for WKWebView.
if fileManager.fileExists(atPath: wkWebViewLocalStorage.relativePath) {
return DDLogInfo("Not migrating, WKWebView local storage files present.")
}
DDLogInfo("Migrating UIWebView local storage to WKWebView")
// Create the WKWebView local storage directory; this is safe if the directory already exists.
do {
try fileManager.createDirectory(at: wkWebViewLocalStorageDir, withIntermediateDirectories: true)
} catch {
return DDLogError("Failed to create WKWebView local storage directory")
}
// Create a tmp directory and copy onto it the local storage files.
guard let tmpDir = try? fileManager.url(for: .itemReplacementDirectory, in: .userDomainMask,
appropriateFor: wkWebViewLocalStorage, create: true) else {
return DDLogError("Failed to create tmp dir")
}
do {
try fileManager.copyItem(at: uiWebViewLocalStorage,
to: tmpDir.appendingPathComponent(wkWebViewLocalStorage.lastPathComponent))
try fileManager.copyItem(at: URL.init(fileURLWithPath: "\(uiWebViewLocalStorage.relativePath)-shm"),
to: tmpDir.appendingPathComponent("\(kWKWebViewLocalStorageFilename)-shm"))
try fileManager.copyItem(at: URL.init(fileURLWithPath: "\(uiWebViewLocalStorage.relativePath)-wal"),
to: tmpDir.appendingPathComponent("\(kWKWebViewLocalStorageFilename)-wal"))
} catch {
return DDLogError("Local storage migration failed.")
}
// Atomically move the tmp directory to the WKWebView local storage directory.
guard let _ = try? fileManager.replaceItemAt(wkWebViewLocalStorageDir, withItemAt: tmpDir,
backupItemName: nil, options: .usingNewMetadataOnly) else {
return DDLogError("Failed to copy tmp dir to WKWebView local storage dir")
}
DDLogInfo("Local storage migration succeeded")
}
}
| apache-2.0 | a9bbf930e2a7fe21df6fb3f094e52bfc | 40.991573 | 111 | 0.700114 | 4.700943 | false | false | false | false |
natestedman/Endpoint | Endpoint/Internal.swift | 1 | 1147 | // Endpoint
// Written in 2016 by Nate Stedman <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all copyright and
// related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with
// this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
import Foundation
extension URL
{
internal func transformWithComponents(_ transform: (inout URLComponents) -> ()) -> URL?
{
guard var components = URLComponents(url: self, resolvingAgainstBaseURL: true) else {
return nil
}
transform(&components)
return components.url
}
internal func buildRequest(httpMethod: HTTPMethod, headerFields: [String:String]? = nil, body: HTTPBody? = nil)
-> URLRequest
{
var request = URLRequest(url: self)
request.httpMethod = httpMethod.rawValue
request.allHTTPHeaderFields = headerFields
body?.apply(to: &request)
return request
}
}
| cc0-1.0 | 65ef1625567e27a734e169265a13ee62 | 30.861111 | 115 | 0.68701 | 4.739669 | false | false | false | false |
eggswift/pull-to-refresh | Sources/ESPullToRefresh.swift | 1 | 19329 | //
// ESPullToRefresh.swift
//
// Created by egg swift on 16/4/7.
// Copyright (c) 2013-2016 ESPullToRefresh (https://github.com/eggswift/pull-to-refresh)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import UIKit
private var kESRefreshHeaderKey: Void?
private var kESRefreshFooterKey: Void?
public extension UIScrollView {
/// Pull-to-refresh associated property
var header: ESRefreshHeaderView? {
get { return (objc_getAssociatedObject(self, &kESRefreshHeaderKey) as? ESRefreshHeaderView) }
set(newValue) { objc_setAssociatedObject(self, &kESRefreshHeaderKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }
}
/// Infinitiy scroll associated property
var footer: ESRefreshFooterView? {
get { return (objc_getAssociatedObject(self, &kESRefreshFooterKey) as? ESRefreshFooterView) }
set(newValue) { objc_setAssociatedObject(self, &kESRefreshFooterKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }
}
}
public extension ES where Base: UIScrollView {
/// Add pull-to-refresh
@discardableResult
func addPullToRefresh(handler: @escaping ESRefreshHandler) -> ESRefreshHeaderView {
removeRefreshHeader()
let header = ESRefreshHeaderView(frame: CGRect.zero, handler: handler)
let headerH = header.animator.executeIncremental
header.frame = CGRect.init(x: 0.0, y: -headerH /* - contentInset.top */, width: self.base.bounds.size.width, height: headerH)
self.base.addSubview(header)
self.base.header = header
return header
}
@discardableResult
func addPullToRefresh(animator: ESRefreshProtocol & ESRefreshAnimatorProtocol, handler: @escaping ESRefreshHandler) -> ESRefreshHeaderView {
removeRefreshHeader()
let header = ESRefreshHeaderView(frame: CGRect.zero, handler: handler, animator: animator)
let headerH = animator.executeIncremental
header.frame = CGRect.init(x: 0.0, y: -headerH /* - contentInset.top */, width: self.base.bounds.size.width, height: headerH)
self.base.addSubview(header)
self.base.header = header
return header
}
/// Add infinite-scrolling
@discardableResult
func addInfiniteScrolling(handler: @escaping ESRefreshHandler) -> ESRefreshFooterView {
removeRefreshFooter()
let footer = ESRefreshFooterView(frame: CGRect.zero, handler: handler)
let footerH = footer.animator.executeIncremental
footer.frame = CGRect.init(x: 0.0, y: self.base.contentSize.height + self.base.contentInset.bottom, width: self.base.bounds.size.width, height: footerH)
self.base.addSubview(footer)
self.base.footer = footer
return footer
}
@discardableResult
func addInfiniteScrolling(animator: ESRefreshProtocol & ESRefreshAnimatorProtocol, handler: @escaping ESRefreshHandler) -> ESRefreshFooterView {
removeRefreshFooter()
let footer = ESRefreshFooterView(frame: CGRect.zero, handler: handler, animator: animator)
let footerH = footer.animator.executeIncremental
footer.frame = CGRect.init(x: 0.0, y: self.base.contentSize.height + self.base.contentInset.bottom, width: self.base.bounds.size.width, height: footerH)
self.base.footer = footer
self.base.addSubview(footer)
return footer
}
/// Remove
func removeRefreshHeader() {
self.base.header?.stopRefreshing()
self.base.header?.removeFromSuperview()
self.base.header = nil
}
func removeRefreshFooter() {
self.base.footer?.stopRefreshing()
self.base.footer?.removeFromSuperview()
self.base.footer = nil
}
/// Manual refresh
func startPullToRefresh() {
DispatchQueue.main.async { [weak base] in
base?.header?.startRefreshing(isAuto: false)
}
}
/// Auto refresh if expired.
func autoPullToRefresh() {
if self.base.expired == true {
DispatchQueue.main.async { [weak base] in
base?.header?.startRefreshing(isAuto: true)
}
}
}
/// Stop pull to refresh
func stopPullToRefresh(ignoreDate: Bool = false, ignoreFooter: Bool = false) {
self.base.header?.stopRefreshing()
if ignoreDate == false {
if let key = self.base.header?.refreshIdentifier {
ESRefreshDataManager.sharedManager.setDate(Date(), forKey: key)
}
self.base.footer?.resetNoMoreData()
}
self.base.footer?.isHidden = ignoreFooter
}
/// Footer notice method
func noticeNoMoreData() {
self.base.footer?.stopRefreshing()
self.base.footer?.noMoreData = true
}
func resetNoMoreData() {
self.base.footer?.noMoreData = false
}
func stopLoadingMore() {
self.base.footer?.stopRefreshing()
}
}
public extension UIScrollView /* Date Manager */ {
/// Identifier for cache expired timeinterval and last refresh date.
var refreshIdentifier: String? {
get { return self.header?.refreshIdentifier }
set { self.header?.refreshIdentifier = newValue }
}
/// If you setted refreshIdentifier and expiredTimeInterval, return nearest refresh expired or not. Default is false.
var expired: Bool {
get {
if let key = self.header?.refreshIdentifier {
return ESRefreshDataManager.sharedManager.isExpired(forKey: key)
}
return false
}
}
var expiredTimeInterval: TimeInterval? {
get {
if let key = self.header?.refreshIdentifier {
let interval = ESRefreshDataManager.sharedManager.expiredTimeInterval(forKey: key)
return interval
}
return nil
}
set {
if let key = self.header?.refreshIdentifier {
ESRefreshDataManager.sharedManager.setExpiredTimeInterval(newValue, forKey: key)
}
}
}
/// Auto cached last refresh date when you setted refreshIdentifier.
var lastRefreshDate: Date? {
get {
if let key = self.header?.refreshIdentifier {
return ESRefreshDataManager.sharedManager.date(forKey: key)
}
return nil
}
}
}
open class ESRefreshHeaderView: ESRefreshComponent {
fileprivate var previousOffset: CGFloat = 0.0
fileprivate var scrollViewInsets: UIEdgeInsets = UIEdgeInsets.zero
fileprivate var scrollViewBounces: Bool = true
open var lastRefreshTimestamp: TimeInterval?
open var refreshIdentifier: String?
public convenience init(frame: CGRect, handler: @escaping ESRefreshHandler) {
self.init(frame: frame)
self.handler = handler
self.animator = ESRefreshHeaderAnimator.init()
}
open override func didMoveToSuperview() {
super.didMoveToSuperview()
DispatchQueue.main.async {
[weak self] in
self?.scrollViewBounces = self?.scrollView?.bounces ?? true
self?.scrollViewInsets = self?.scrollView?.contentInset ?? UIEdgeInsets.zero
}
}
open override func offsetChangeAction(object: AnyObject?, change: [NSKeyValueChangeKey : Any]?) {
guard let scrollView = scrollView else {
return
}
super.offsetChangeAction(object: object, change: change)
guard self.isRefreshing == false && self.isAutoRefreshing == false else {
let top = scrollViewInsets.top
let offsetY = scrollView.contentOffset.y
let height = self.frame.size.height
var scrollingTop = (-offsetY > top) ? -offsetY : top
scrollingTop = (scrollingTop > height + top) ? (height + top) : scrollingTop
scrollView.contentInset.top = scrollingTop
return
}
// Check needs re-set animator's progress or not.
var isRecordingProgress = false
defer {
if isRecordingProgress == true {
let percent = -(previousOffset + scrollViewInsets.top) / self.animator.trigger
self.animator.refresh(view: self, progressDidChange: percent)
}
}
let offsets = previousOffset + scrollViewInsets.top
if offsets < -self.animator.trigger {
// Reached critical
if isRefreshing == false && isAutoRefreshing == false {
if scrollView.isDragging == false {
// Start to refresh...
self.startRefreshing(isAuto: false)
self.animator.refresh(view: self, stateDidChange: .refreshing)
} else {
// Release to refresh! Please drop down hard...
self.animator.refresh(view: self, stateDidChange: .releaseToRefresh)
isRecordingProgress = true
}
}
} else if offsets < 0 {
// Pull to refresh!
if isRefreshing == false && isAutoRefreshing == false {
self.animator.refresh(view: self, stateDidChange: .pullToRefresh)
isRecordingProgress = true
}
} else {
// Normal state
}
previousOffset = scrollView.contentOffset.y
}
open override func start() {
guard let scrollView = scrollView else {
return
}
// ignore observer
self.ignoreObserver(true)
// stop scroll view bounces for animation
scrollView.bounces = false
// call super start
super.start()
self.animator.refreshAnimationBegin(view: self)
// 缓存scrollview当前的contentInset, 并根据animator的executeIncremental属性计算刷新时所需要的contentInset,它将在接下来的动画中应用。
// Tips: 这里将self.scrollViewInsets.top更新,也可以将scrollViewInsets整个更新,因为left、right、bottom属性都没有用到,如果接下来的迭代需要使用这三个属性的话,这里可能需要额外的处理。
var insets = scrollView.contentInset
self.scrollViewInsets.top = insets.top
insets.top += animator.executeIncremental
// We need to restore previous offset because we will animate scroll view insets and regular scroll view animating is not applied then.
scrollView.contentInset = insets
scrollView.contentOffset.y = previousOffset
previousOffset -= animator.executeIncremental
UIView.animate(withDuration: 0.2, delay: 0.0, options: .curveLinear, animations: {
scrollView.contentOffset.y = -insets.top
}, completion: { (finished) in
self.handler?()
// un-ignore observer
self.ignoreObserver(false)
scrollView.bounces = self.scrollViewBounces
})
}
open override func stop() {
guard let scrollView = scrollView else {
return
}
// ignore observer
self.ignoreObserver(true)
self.animator.refreshAnimationEnd(view: self)
// Back state
scrollView.contentInset.top = self.scrollViewInsets.top
scrollView.contentOffset.y = self.previousOffset
UIView.animate(withDuration: 0.2, delay: 0, options: .curveLinear, animations: {
scrollView.contentOffset.y = -self.scrollViewInsets.top
}, completion: { (finished) in
self.animator.refresh(view: self, stateDidChange: .pullToRefresh)
super.stop()
scrollView.contentInset.top = self.scrollViewInsets.top
self.previousOffset = scrollView.contentOffset.y
// un-ignore observer
self.ignoreObserver(false)
})
}
}
open class ESRefreshFooterView: ESRefreshComponent {
fileprivate var scrollViewInsets: UIEdgeInsets = UIEdgeInsets.zero
open var noMoreData = false {
didSet {
if noMoreData != oldValue {
self.animator.refresh(view: self, stateDidChange: noMoreData ? .noMoreData : .pullToRefresh)
}
}
}
open override var isHidden: Bool {
didSet {
if isHidden == true {
scrollView?.contentInset.bottom = scrollViewInsets.bottom
var rect = self.frame
rect.origin.y = scrollView?.contentSize.height ?? 0.0
self.frame = rect
} else {
scrollView?.contentInset.bottom = scrollViewInsets.bottom + animator.executeIncremental
var rect = self.frame
rect.origin.y = scrollView?.contentSize.height ?? 0.0
self.frame = rect
}
}
}
public convenience init(frame: CGRect, handler: @escaping ESRefreshHandler) {
self.init(frame: frame)
self.handler = handler
self.animator = ESRefreshFooterAnimator.init()
}
/**
In didMoveToSuperview, it will cache superview(UIScrollView)'s contentInset and update self's frame.
It called ESRefreshComponent's didMoveToSuperview.
*/
open override func didMoveToSuperview() {
super.didMoveToSuperview()
DispatchQueue.main.async {
[weak self] in
self?.scrollViewInsets = self?.scrollView?.contentInset ?? UIEdgeInsets.zero
self?.scrollView?.contentInset.bottom = (self?.scrollViewInsets.bottom ?? 0) + (self?.bounds.size.height ?? 0)
var rect = self?.frame ?? CGRect.zero
rect.origin.y = self?.scrollView?.contentSize.height ?? 0.0
self?.frame = rect
}
}
open override func sizeChangeAction(object: AnyObject?, change: [NSKeyValueChangeKey : Any]?) {
guard let scrollView = scrollView else { return }
super.sizeChangeAction(object: object, change: change)
let targetY = scrollView.contentSize.height + scrollViewInsets.bottom
if self.frame.origin.y != targetY {
var rect = self.frame
rect.origin.y = targetY
self.frame = rect
}
}
open override func offsetChangeAction(object: AnyObject?, change: [NSKeyValueChangeKey : Any]?) {
guard let scrollView = scrollView else {
return
}
super.offsetChangeAction(object: object, change: change)
guard isRefreshing == false && isAutoRefreshing == false && noMoreData == false && isHidden == false else {
// 正在loading more或者内容为空时不相应变化
return
}
if scrollView.contentSize.height <= 0.0 || scrollView.contentOffset.y + scrollView.contentInset.top <= 0.0 {
self.alpha = 0.0
return
} else {
self.alpha = 1.0
}
if scrollView.contentSize.height + scrollView.contentInset.top > scrollView.bounds.size.height {
// 内容超过一个屏幕 计算公式,判断是不是在拖在到了底部
if scrollView.contentSize.height - scrollView.contentOffset.y + scrollView.contentInset.bottom <= scrollView.bounds.size.height {
self.animator.refresh(view: self, stateDidChange: .refreshing)
self.startRefreshing()
}
} else {
//内容没有超过一个屏幕,这时拖拽高度大于1/2footer的高度就表示请求上拉
if scrollView.contentOffset.y + scrollView.contentInset.top >= animator.trigger / 2.0 {
self.animator.refresh(view: self, stateDidChange: .refreshing)
self.startRefreshing()
}
}
}
open override func start() {
guard let scrollView = scrollView else {
return
}
super.start()
self.animator.refreshAnimationBegin(view: self)
let x = scrollView.contentOffset.x
let y = max(0.0, scrollView.contentSize.height - scrollView.bounds.size.height + scrollView.contentInset.bottom)
// Call handler
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveLinear, animations: {
scrollView.contentOffset = CGPoint.init(x: x, y: y)
}, completion: { (animated) in
self.handler?()
})
}
open override func stop() {
guard let scrollView = scrollView else {
return
}
self.animator.refreshAnimationEnd(view: self)
// Back state
UIView.animate(withDuration: 0.3, delay: 0, options: .curveLinear, animations: {
}, completion: { (finished) in
if self.noMoreData == false {
self.animator.refresh(view: self, stateDidChange: .pullToRefresh)
}
super.stop()
})
// Stop deceleration of UIScrollView. When the button tap event is caught, you read what the [scrollView contentOffset].x is, and set the offset to this value with animation OFF.
// http://stackoverflow.com/questions/2037892/stop-deceleration-of-uiscrollview
if scrollView.isDecelerating {
var contentOffset = scrollView.contentOffset
contentOffset.y = min(contentOffset.y, scrollView.contentSize.height - scrollView.frame.size.height)
if contentOffset.y < 0.0 {
contentOffset.y = 0.0
UIView.animate(withDuration: 0.1, animations: {
scrollView.setContentOffset(contentOffset, animated: false)
})
} else {
scrollView.setContentOffset(contentOffset, animated: false)
}
}
}
/// Change to no-more-data status.
open func noticeNoMoreData() {
self.noMoreData = true
}
/// Reset no-more-data status.
open func resetNoMoreData() {
self.noMoreData = false
}
}
| mit | e24d8e4a75de352f4a20772697a4cce6 | 37.320565 | 186 | 0.62114 | 4.94974 | false | false | false | false |
AboutObjectsTraining/swift-comp-reston-2017-02 | examples/swift-tool/swift-tool/Serializable.swift | 1 | 2052 | import Foundation
// Ideally, this would be a protocol rather than a class.
// As of Swift 2, we can implement the behavior in a protocol extension. That way,
// a class can opt in for the behavior by simply adopting the protocol.
open class Serializable
{
// public func dictionaryRepresentation() -> [String: AnyObject]
// {
// var dict = [String: AnyObject]()
// let mirror = Mirror(reflecting: self)
//
// for child in mirror.children
// {
// print(child)
// }
//
// for i in 1..<mirror.children.count
// {
// let (key, childMirror) = mirror[i]
//
// if let unwrappedVal: AnyObject = self.unwrap(childMirror.value) as? AnyObject
// {
// var value: AnyObject = unwrappedVal
//
// if let object = value as? Serializable
// {
// value = object.dictionaryRepresentation()
// }
// else if let objects = value as? [Serializable]
// {
// var dicts = [[String: AnyObject]]()
// for item in objects {
// dicts.append(item.dictionaryRepresentation())
// }
// value = dicts
// }
//
// dict[key] = value
// }
// }
//
// return dict
// }
//
open func value(_ key: String) -> Any?
{
let mirror = Mirror(reflecting: self)
for child in mirror.children
{
if (child.label == key) {
return child.value
}
}
return .none
}
// private func unwrap(value: Any) -> Any?
// {
// let mirror = Mirror(reflecting: self)
//
// if mirror.children.count == 0 {
// return nil
// }
//
// return mirror.subjectType != .Optional ? value : mirror[0].1.value
// }
}
| mit | 2851b72743e2da010df1b464d72137c0 | 27.5 | 91 | 0.457602 | 4.356688 | false | false | false | false |
erikmartens/NearbyWeather | NearbyWeather/Scenes/Weather Station Meteorology Details Scene/Table Cells/Weather Station Meteorology Details Map/Map Annotations/Weather Station Location Map Annotation/WeatherStationLocationAnnotationView.swift | 1 | 4421 | //
// WeatherStationLocationAnnotationView.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 01.04.22.
// Copyright © 2022 Erik Maximilian Martens. All rights reserved.
//
import MapKit
import RxSwift
// MARK: - Definitions
private extension WeatherStationLocationAnnotationView {
struct Definitions {
static let margin: CGFloat = 4
static let width: CGFloat = 48
static let height: CGFloat = 56
static let triangleHeight: CGFloat = 10
static let radius: CGFloat = 10
static let borderWidth: CGFloat = 4
static let stationSymbolImageViewWidthHeight: CGFloat = Definitions.height - 6*Definitions.margin - Definitions.triangleHeight
}
}
// MARK: - Class Definition
final class WeatherStationLocationAnnotationView: MKAnnotationView, BaseAnnotationView {
typealias AnnotationViewModel = WeatherStationLocationMapAnnotationViewModel
// MARK: - UIComponents
private lazy var circleLayer = Factory.ShapeLayer.make(fromType: .circle(radius: Definitions.radius, borderWidth: Definitions.borderWidth))
private lazy var speechBubbleLayer = Factory.ShapeLayer.make(fromType: .speechBubble(
size: CGSize(width: Definitions.width, height: Definitions.height),
radius: Definitions.radius,
borderWidth: Definitions.borderWidth,
margin: Definitions.margin,
triangleHeight: Definitions.triangleHeight
))
private lazy var stationSymbolImageView = Factory.ImageView.make(fromType: .weatherConditionSymbol)
// MARK: - Assets
private var disposeBag = DisposeBag()
// MARK: - Properties
var annotationViewModel: AnnotationViewModel?
// MARK: - Initialization
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
layoutUserInterface()
setupAppearance()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Cell Life Cycle
override func prepareForDisplay() {
super.prepareForDisplay()
annotationViewModel?.observeEvents()
}
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
}
func configure(with annotationViewModel: BaseAnnotationViewModelProtocol?) {
guard let annotationViewModel = annotationViewModel as? WeatherStationLocationMapAnnotationViewModel else {
return
}
self.annotationViewModel = annotationViewModel
annotationViewModel.observeEvents()
bindContentFromViewModel(annotationViewModel)
bindUserInputToViewModel(annotationViewModel)
}
}
// MARK: - ViewModel Bindings
extension WeatherStationLocationAnnotationView {
func bindContentFromViewModel(_ annotationViewModel: AnnotationViewModel) {
annotationViewModel.annotationModelDriver
.drive(onNext: { [setContent] in setContent($0) })
.disposed(by: disposeBag)
}
func bindUserInputToViewModel(_ annotationViewModel: AnnotationViewModel) {
// nothing to do
}
}
// MARK: - Annotation Composition
private extension WeatherStationLocationAnnotationView {
func setContent(for annotationModel: WeatherStationLocationAnnotationModel) {
circleLayer.fillColor = annotationModel.backgroundColor?.cgColor
circleLayer.strokeColor = annotationModel.tintColor?.cgColor
speechBubbleLayer.fillColor = annotationModel.backgroundColor?.cgColor
speechBubbleLayer.strokeColor = annotationModel.tintColor?.cgColor
stationSymbolImageView.image = annotationModel.stationSymbol
}
func layoutUserInterface() {
// set frame
frame = CGRect(origin: .zero, size: CGSize(width: Definitions.width, height: Definitions.height))
// add UI components
circleLayer.bounds.origin = CGPoint(x: -frame.width/2 + Definitions.radius, y: -frame.height/2 + Definitions.radius)
layer.addSublayer(circleLayer)
layer.addSublayer(speechBubbleLayer)
// station symbol image
stationSymbolImageView.frame = CGRect(
x: 0,
y: 0,
width: Definitions.stationSymbolImageViewWidthHeight,
height: Definitions.stationSymbolImageViewWidthHeight
)
stationSymbolImageView.center = CGPoint(
x: frame.size.width/2,
y: -Definitions.margin
)
addSubview(stationSymbolImageView)
}
func setupAppearance() {
clipsToBounds = false
backgroundColor = .clear
}
}
| mit | 334d6caeb1c4af1055bfc7dc1ee3f46e | 29.068027 | 141 | 0.743665 | 5.092166 | false | false | false | false |
tomriley/ZeroTier-Status-Menu | ZeroTier Status Menu/AppDelegate.swift | 1 | 3226 | //
// AppDelegate.swift
// ZerotierMenuStatus
//
// Created by Tom on 11/3/15.
// Copyright © 2015 Tom Riley. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSSquareStatusItemLength)
let menu = NSMenu()
@IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(aNotification: NSNotification) {
statusItem.menu = menu
menu.autoenablesItems = false
updateStatus()
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateStatus", userInfo: nil, repeats: true)
}
func updateStatus() {
let info = ZeroTier.getInfo()
let networks = ZeroTier.getNetworks()
menu.removeAllItems()
// Add item for online/offline status
let online = info["online"].boolValue
let mitem = NSMenuItem(title: "ZeroTier Status: \(online ? "ONLINE" : "OFFLINE")", action: Selector(), keyEquivalent: "")
mitem.enabled = false
menu.addItem(mitem)
menu.addItem(NSMenuItem.separatorItem())
var aNetworkIsOkay = false
for (_, network) in networks {
var name = network["name"].stringValue
if name.isEmpty { name = network["nwid"].stringValue }
let type = network["type"].stringValue
let status = network["status"].stringValue
let label = "\(name) - \(status) - \(type)"
var mitem = NSMenuItem(title: label, action: Selector(), keyEquivalent: "")
mitem.enabled = false
menu.addItem(mitem)
let ips = network["assignedAddresses"].map { $0.1.stringValue }.joinWithSeparator(", ")
mitem = NSMenuItem(title: ips, action: Selector(), keyEquivalent: "")
mitem.enabled = false
menu.addItem(mitem)
menu.addItem(NSMenuItem.separatorItem())
if network["status"] == "OK" {
aNetworkIsOkay = true
}
}
if networks.count == 0 {
let mitem = NSMenuItem(title: "No Networks Joined", action: Selector(), keyEquivalent: "")
mitem.enabled = false
menu.addItem(mitem)
menu.addItem(NSMenuItem.separatorItem())
}
// Insert code here to initialize your application
if let button = statusItem.button {
if online && aNetworkIsOkay {
button.image = NSImage(named: "StatusBarButtonImage")
} else {
button.image = NSImage(named: "StatusBarButtonImageDisabled")
}
}
menu.addItem(NSMenuItem(title: "Quit ZeroTier Status Menu", action: Selector("terminate:"), keyEquivalent: "q"))
menu.addItem(NSMenuItem.separatorItem())
menu.addItem(NSMenuItem(title: "About…", action: Selector("orderFrontStandardAboutPanel:"), keyEquivalent: ""))
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
| mit | a0a887043a344e3223c92cc69854be8a | 34.811111 | 129 | 0.595718 | 5.012442 | false | false | false | false |
RicardoTores/XmppMessenger | Example/Pods/xmpp-messenger-ios/Pod/Classes/OneLastActivity.swift | 3 | 4083 | //
// OneLastActivity.swift
// XMPP-Messenger-iOS
//
// Created by Sean Batson on 2015-09-18.
// Edited by Paul LEMAIRE on 2015-10-09.
// Copyright © 2015 ProcessOne. All rights reserved.
//
import Foundation
import XMPPFramework
public typealias OneMakeLastCallCompletionHandler = (response: XMPPIQ?, forJID:XMPPJID?, error: DDXMLElement?) -> Void
public class OneLastActivity: NSObject {
var didMakeLastCallCompletionBlock: OneMakeLastCallCompletionHandler?
// MARK: Singleton
public class var sharedInstance : OneLastActivity {
struct OneLastActivitySingleton {
static let instance = OneLastActivity()
}
return OneLastActivitySingleton.instance
}
// MARK: Public Functions
public func getStringFormattedDateFrom(second: UInt) -> NSString {
if second > 0 {
let time = NSNumber(unsignedLong: second)
let interval = time.doubleValue
let elapsedTime = NSDate(timeIntervalSince1970: interval)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
return dateFormatter.stringFromDate(elapsedTime)
} else {
return ""
}
}
public func getStringFormattedElapsedTimeFrom(date: NSDate!) -> String {
var elapsedTime = "nc"
let startDate = NSDate()
let components = NSCalendar.currentCalendar().components(NSCalendarUnit.Day, fromDate: date, toDate: startDate, options: NSCalendarOptions.MatchStrictly)
if nil == date {
return elapsedTime
}
if 52 < components.weekOfYear {
elapsedTime = "more than a year"
} else if 1 <= components.weekOfYear {
if 1 < components.weekOfYear {
elapsedTime = "\(components.weekOfYear) weeks"
} else {
elapsedTime = "\(components.weekOfYear) week"
}
} else if 1 <= components.day {
if 1 < components.day {
elapsedTime = "\(components.day) days"
} else {
elapsedTime = "\(components.day) day"
}
} else if 1 <= components.hour {
if 1 < components.hour {
elapsedTime = "\(components.hour) hours"
} else {
elapsedTime = "\(components.hour) hour"
}
} else if 1 <= components.minute {
if 1 < components.minute {
elapsedTime = "\(components.minute) minutes"
} else {
elapsedTime = "\(components.minute) minute"
}
} else if 1 <= components.second {
if 1 < components.second {
elapsedTime = "\(components.second) seconds"
} else {
elapsedTime = "\(components.second) second"
}
} else {
elapsedTime = "now"
}
return elapsedTime
}
public class func sendLastActivityQueryToJID(userName: String, sender: XMPPLastActivity? = nil, completionHandler completion:OneMakeLastCallCompletionHandler) {
sharedInstance.didMakeLastCallCompletionBlock = completion
let userJID = XMPPJID.jidWithString(userName)
sender?.sendLastActivityQueryToJID(userJID)
}
}
extension OneLastActivity: XMPPLastActivityDelegate {
public func xmppLastActivity(sender: XMPPLastActivity!, didNotReceiveResponse queryID: String!, dueToTimeout timeout: NSTimeInterval) {
if let callback = OneLastActivity.sharedInstance.didMakeLastCallCompletionBlock {
callback(response: nil, forJID:nil ,error: DDXMLElement(name: "TimeOut"))
}
}
public func xmppLastActivity(sender: XMPPLastActivity!, didReceiveResponse response: XMPPIQ!) {
if let callback = OneLastActivity.sharedInstance.didMakeLastCallCompletionBlock {
if let resp = response {
if resp.elementForName("error") != nil {
if let from = resp.valueForKey("from") {
callback(response: resp, forJID: XMPPJID.jidWithString("\(from)"), error: resp.elementForName("error"))
} else {
callback(response: resp, forJID: nil, error: resp.elementForName("error"))
}
} else {
if let from = resp.attributeForName("from") {
callback(response: resp, forJID: XMPPJID.jidWithString("\(from)"), error: nil)
} else {
callback(response: resp, forJID: nil, error: nil)
}
}
}
}
}
public func numberOfIdleTimeSecondsForXMPPLastActivity(sender: XMPPLastActivity!, queryIQ iq: XMPPIQ!, currentIdleTimeSeconds idleSeconds: UInt) -> UInt {
return 30
}
} | mit | e64608ce5d237999e855ceecdd8f4d7f | 30.167939 | 161 | 0.710436 | 3.928778 | false | false | false | false |
stephencelis/SQLite.swift | Tests/SQLiteTests/Core/ConnectionTests.swift | 1 | 15943 | import XCTest
import Foundation
import Dispatch
@testable import SQLite
#if SQLITE_SWIFT_STANDALONE
import sqlite3
#elseif SQLITE_SWIFT_SQLCIPHER
import SQLCipher
#elseif os(Linux)
import CSQLite
#else
import SQLite3
#endif
class ConnectionTests: SQLiteTestCase {
override func setUpWithError() throws {
try super.setUpWithError()
try createUsersTable()
}
func test_init_withInMemory_returnsInMemoryConnection() throws {
let db = try Connection(.inMemory)
XCTAssertEqual("", db.description)
}
func test_init_returnsInMemoryByDefault() throws {
let db = try Connection()
XCTAssertEqual("", db.description)
}
func test_init_withTemporary_returnsTemporaryConnection() throws {
let db = try Connection(.temporary)
XCTAssertEqual("", db.description)
}
func test_init_withURI_returnsURIConnection() throws {
let db = try Connection(.uri("\(NSTemporaryDirectory())/SQLite.swift Tests.sqlite3"))
let url = URL(fileURLWithPath: db.description)
XCTAssertEqual(url.lastPathComponent, "SQLite.swift Tests.sqlite3")
}
func test_init_withString_returnsURIConnection() throws {
let db = try Connection("\(NSTemporaryDirectory())/SQLite.swift Tests.sqlite3")
let url = URL(fileURLWithPath: db.description)
XCTAssertEqual(url.lastPathComponent, "SQLite.swift Tests.sqlite3")
}
func test_init_with_Uri_and_Parameters() throws {
let testDb = fixture("test", withExtension: "sqlite")
_ = try Connection(.uri(testDb, parameters: [.cache(.shared)]))
}
func test_location_without_Uri_parameters() {
let location: Connection.Location = .uri("foo")
XCTAssertEqual(location.description, "foo")
}
func test_location_with_Uri_parameters() {
let location: Connection.Location = .uri("foo", parameters: [.mode(.readOnly), .cache(.private)])
XCTAssertEqual(location.description, "file:foo?mode=ro&cache=private")
}
func test_readonly_returnsFalseOnReadWriteConnections() {
XCTAssertFalse(db.readonly)
}
func test_readonly_returnsTrueOnReadOnlyConnections() throws {
let db = try Connection(readonly: true)
XCTAssertTrue(db.readonly)
}
func test_changes_returnsZeroOnNewConnections() {
XCTAssertEqual(0, db.changes)
}
func test_lastInsertRowid_returnsLastIdAfterInserts() throws {
try insertUser("alice")
XCTAssertEqual(1, db.lastInsertRowid)
}
func test_lastInsertRowid_doesNotResetAfterError() throws {
XCTAssert(db.lastInsertRowid == 0)
try insertUser("alice")
XCTAssertEqual(1, db.lastInsertRowid)
XCTAssertThrowsError(
try db.run("INSERT INTO \"users\" (email, age, admin) values ('[email protected]', 12, 'invalid')")
) { error in
if case SQLite.Result.error(_, let code, _) = error {
XCTAssertEqual(SQLITE_CONSTRAINT, code)
} else {
XCTFail("expected error")
}
}
XCTAssertEqual(1, db.lastInsertRowid)
}
func test_changes_returnsNumberOfChanges() throws {
try insertUser("alice")
XCTAssertEqual(1, db.changes)
try insertUser("betsy")
XCTAssertEqual(1, db.changes)
}
func test_totalChanges_returnsTotalNumberOfChanges() throws {
XCTAssertEqual(0, db.totalChanges)
try insertUser("alice")
XCTAssertEqual(1, db.totalChanges)
try insertUser("betsy")
XCTAssertEqual(2, db.totalChanges)
}
func test_prepare_preparesAndReturnsStatements() throws {
_ = try db.prepare("SELECT * FROM users WHERE admin = 0")
_ = try db.prepare("SELECT * FROM users WHERE admin = ?", 0)
_ = try db.prepare("SELECT * FROM users WHERE admin = ?", [0])
_ = try db.prepare("SELECT * FROM users WHERE admin = $admin", ["$admin": 0])
}
func test_run_preparesRunsAndReturnsStatements() throws {
try db.run("SELECT * FROM users WHERE admin = 0")
try db.run("SELECT * FROM users WHERE admin = ?", 0)
try db.run("SELECT * FROM users WHERE admin = ?", [0])
try db.run("SELECT * FROM users WHERE admin = $admin", ["$admin": 0])
assertSQL("SELECT * FROM users WHERE admin = 0", 4)
}
func test_vacuum() throws {
try db.vacuum()
}
func test_scalar_preparesRunsAndReturnsScalarValues() throws {
XCTAssertEqual(0, try db.scalar("SELECT count(*) FROM users WHERE admin = 0") as? Int64)
XCTAssertEqual(0, try db.scalar("SELECT count(*) FROM users WHERE admin = ?", 0) as? Int64)
XCTAssertEqual(0, try db.scalar("SELECT count(*) FROM users WHERE admin = ?", [0]) as? Int64)
XCTAssertEqual(0, try db.scalar("SELECT count(*) FROM users WHERE admin = $admin", ["$admin": 0]) as? Int64)
assertSQL("SELECT count(*) FROM users WHERE admin = 0", 4)
}
func test_execute_comment() throws {
try db.run("-- this is a comment\nSELECT 1")
assertSQL("-- this is a comment", 0)
assertSQL("SELECT 1", 0)
}
func test_transaction_executesBeginDeferred() throws {
try db.transaction(.deferred) {}
assertSQL("BEGIN DEFERRED TRANSACTION")
}
func test_transaction_executesBeginImmediate() throws {
try db.transaction(.immediate) {}
assertSQL("BEGIN IMMEDIATE TRANSACTION")
}
func test_transaction_executesBeginExclusive() throws {
try db.transaction(.exclusive) {}
assertSQL("BEGIN EXCLUSIVE TRANSACTION")
}
func test_backup_copiesDatabase() throws {
let target = try Connection()
try insertUsers("alice", "betsy")
let backup = try db.backup(usingConnection: target)
try backup.step()
let users = try target.prepare("SELECT email FROM users ORDER BY email")
XCTAssertEqual(users.map { $0[0] as? String }, ["[email protected]", "[email protected]"])
}
func test_transaction_beginsAndCommitsTransactions() throws {
let stmt = try db.prepare("INSERT INTO users (email) VALUES (?)", "[email protected]")
try db.transaction {
try stmt.run()
}
assertSQL("BEGIN DEFERRED TRANSACTION")
assertSQL("INSERT INTO users (email) VALUES ('[email protected]')")
assertSQL("COMMIT TRANSACTION")
assertSQL("ROLLBACK TRANSACTION", 0)
}
func test_transaction_rollsBackTransactionsIfCommitsFail() throws {
let sqliteVersion = String(describing: try db.scalar("SELECT sqlite_version()")!)
.split(separator: ".").compactMap { Int($0) }
// PRAGMA defer_foreign_keys only supported in SQLite >= 3.8.0
guard sqliteVersion[0] == 3 && sqliteVersion[1] >= 8 else {
NSLog("skipping test for SQLite version \(sqliteVersion)")
return
}
// This test case needs to emulate an environment where the individual statements succeed, but committing the
// transaction fails. Using deferred foreign keys is one option to achieve this.
try db.execute("PRAGMA foreign_keys = ON;")
try db.execute("PRAGMA defer_foreign_keys = ON;")
let stmt = try db.prepare("INSERT INTO users (email, manager_id) VALUES (?, ?)", "[email protected]", 100)
do {
try db.transaction {
try stmt.run()
}
XCTFail("expected error")
} catch let Result.error(_, code, _) {
XCTAssertEqual(SQLITE_CONSTRAINT, code)
} catch let error {
XCTFail("unexpected error: \(error)")
}
assertSQL("BEGIN DEFERRED TRANSACTION")
assertSQL("INSERT INTO users (email, manager_id) VALUES ('[email protected]', 100)")
assertSQL("COMMIT TRANSACTION")
assertSQL("ROLLBACK TRANSACTION")
// Run another transaction to ensure that a subsequent transaction does not fail with an "cannot start a
// transaction within a transaction" error.
let stmt2 = try db.prepare("INSERT INTO users (email) VALUES (?)", "[email protected]")
try db.transaction {
try stmt2.run()
}
}
func test_transaction_beginsAndRollsTransactionsBack() throws {
let stmt = try db.prepare("INSERT INTO users (email) VALUES (?)", "[email protected]")
do {
try db.transaction {
try stmt.run()
try stmt.run()
}
} catch {
}
assertSQL("BEGIN DEFERRED TRANSACTION")
assertSQL("INSERT INTO users (email) VALUES ('[email protected]')", 2)
assertSQL("ROLLBACK TRANSACTION")
assertSQL("COMMIT TRANSACTION", 0)
}
func test_savepoint_beginsAndCommitsSavepoints() throws {
try db.savepoint("1") {
try db.savepoint("2") {
try db.run("INSERT INTO users (email) VALUES (?)", "[email protected]")
}
}
assertSQL("SAVEPOINT '1'")
assertSQL("SAVEPOINT '2'")
assertSQL("INSERT INTO users (email) VALUES ('[email protected]')")
assertSQL("RELEASE SAVEPOINT '2'")
assertSQL("RELEASE SAVEPOINT '1'")
assertSQL("ROLLBACK TO SAVEPOINT '2'", 0)
assertSQL("ROLLBACK TO SAVEPOINT '1'", 0)
}
func test_savepoint_beginsAndRollsSavepointsBack() throws {
let stmt = try db.prepare("INSERT INTO users (email) VALUES (?)", "[email protected]")
do {
try db.savepoint("1") {
try db.savepoint("2") {
try stmt.run()
try stmt.run()
try stmt.run()
}
try db.savepoint("2") {
try stmt.run()
try stmt.run()
try stmt.run()
}
}
} catch {
}
assertSQL("SAVEPOINT '1'")
assertSQL("SAVEPOINT '2'")
assertSQL("INSERT INTO users (email) VALUES ('[email protected]')", 2)
assertSQL("ROLLBACK TO SAVEPOINT '2'")
assertSQL("ROLLBACK TO SAVEPOINT '1'")
assertSQL("RELEASE SAVEPOINT '2'", 0)
assertSQL("RELEASE SAVEPOINT '1'", 0)
}
func test_updateHook_setsUpdateHook_withInsert() throws {
try async { done in
db.updateHook { operation, db, table, rowid in
XCTAssertEqual(Connection.Operation.insert, operation)
XCTAssertEqual("main", db)
XCTAssertEqual("users", table)
XCTAssertEqual(1, rowid)
done()
}
try insertUser("alice")
}
}
func test_updateHook_setsUpdateHook_withUpdate() throws {
try insertUser("alice")
try async { done in
db.updateHook { operation, db, table, rowid in
XCTAssertEqual(Connection.Operation.update, operation)
XCTAssertEqual("main", db)
XCTAssertEqual("users", table)
XCTAssertEqual(1, rowid)
done()
}
try db.run("UPDATE users SET email = '[email protected]'")
}
}
func test_updateHook_setsUpdateHook_withDelete() throws {
try insertUser("alice")
try async { done in
db.updateHook { operation, db, table, rowid in
XCTAssertEqual(Connection.Operation.delete, operation)
XCTAssertEqual("main", db)
XCTAssertEqual("users", table)
XCTAssertEqual(1, rowid)
done()
}
try db.run("DELETE FROM users WHERE id = 1")
}
}
func test_commitHook_setsCommitHook() throws {
try async { done in
db.commitHook {
done()
}
try db.transaction {
try insertUser("alice")
}
XCTAssertEqual(1, try db.scalar("SELECT count(*) FROM users") as? Int64)
}
}
func test_rollbackHook_setsRollbackHook() throws {
try async { done in
db.rollbackHook(done)
do {
try db.transaction {
try insertUser("alice")
try insertUser("alice") // throw
}
} catch {
}
XCTAssertEqual(0, try db.scalar("SELECT count(*) FROM users") as? Int64)
}
}
func test_commitHook_withRollback_rollsBack() throws {
try async { done in
db.commitHook {
throw NSError(domain: "com.stephencelis.SQLiteTests", code: 1, userInfo: nil)
}
db.rollbackHook(done)
do {
try db.transaction {
try insertUser("alice")
}
} catch {
}
XCTAssertEqual(0, try db.scalar("SELECT count(*) FROM users") as? Int64)
}
}
// https://github.com/stephencelis/SQLite.swift/issues/1071
#if !os(Linux)
func test_createFunction_withArrayArguments() throws {
db.createFunction("hello") { $0[0].map { "Hello, \($0)!" } }
XCTAssertEqual("Hello, world!", try db.scalar("SELECT hello('world')") as? String)
XCTAssert(try db.scalar("SELECT hello(NULL)") == nil)
}
func test_createFunction_createsQuotableFunction() throws {
db.createFunction("hello world") { $0[0].map { "Hello, \($0)!" } }
XCTAssertEqual("Hello, world!", try db.scalar("SELECT \"hello world\"('world')") as? String)
XCTAssert(try db.scalar("SELECT \"hello world\"(NULL)") == nil)
}
func test_createCollation_createsCollation() throws {
try db.createCollation("NODIACRITIC") { lhs, rhs in
lhs.compare(rhs, options: .diacriticInsensitive)
}
XCTAssertEqual(1, try db.scalar("SELECT ? = ? COLLATE NODIACRITIC", "cafe", "café") as? Int64)
}
func test_createCollation_createsQuotableCollation() throws {
try db.createCollation("NO DIACRITIC") { lhs, rhs in
lhs.compare(rhs, options: .diacriticInsensitive)
}
XCTAssertEqual(1, try db.scalar("SELECT ? = ? COLLATE \"NO DIACRITIC\"", "cafe", "café") as? Int64)
}
func XXX_test_interrupt_interruptsLongRunningQuery() throws {
let semaphore = DispatchSemaphore(value: 0)
db.createFunction("sleep") { _ in
DispatchQueue.global(qos: .background).async {
self.db.interrupt()
semaphore.signal()
}
semaphore.wait()
return nil
}
let stmt = try db.prepare("SELECT sleep()")
XCTAssertThrowsError(try stmt.run()) { error in
if case Result.error(_, let code, _) = error {
XCTAssertEqual(code, SQLITE_INTERRUPT)
} else {
XCTFail("unexpected error: \(error)")
}
}
}
#endif
func test_concurrent_access_single_connection() throws {
// test can fail on iOS/tvOS 9.x: SQLite compile-time differences?
guard #available(iOS 10.0, OSX 10.10, tvOS 10.0, watchOS 2.2, *) else { return }
let conn = try Connection("\(NSTemporaryDirectory())/\(UUID().uuidString)")
try conn.execute("DROP TABLE IF EXISTS test; CREATE TABLE test(value);")
try conn.run("INSERT INTO test(value) VALUES(?)", 0)
let queue = DispatchQueue(label: "Readers", attributes: [.concurrent])
let nReaders = 5
let semaphores = Array(repeating: DispatchSemaphore(value: 100), count: nReaders)
for index in 0..<nReaders {
queue.async {
while semaphores[index].signal() == 0 {
_ = try! conn.scalar("SELECT value FROM test")
}
}
}
semaphores.forEach { $0.wait() }
}
}
| mit | 0b0de1ff0fb88328b3f69b5cc11da70b | 34.984199 | 117 | 0.587479 | 4.565006 | false | true | false | false |
utahiosmac/jobs | Sources/JobState.swift | 2 | 6176 | //
// JobState.swift
// Jobs
//
import Foundation
internal final class JobState {
internal let enqueuedDate = Date()
internal let job: JobType
fileprivate enum State {
case idle
case evaluating
case executing
case finished([NSError])
var isFinished: Bool {
if case .finished(_) = self { return true }
return false
}
}
fileprivate let lock = NSLock()
// underscored properties must only be accessed within the lock
fileprivate var _state = State.idle
fileprivate var _cancelled = false
fileprivate var _observers = [Observer]()
internal var jobProductionHandler: (JobType) -> Ticket
internal fileprivate(set) var cancellationError: NSError?
init(job: JobType, productionHandler: @escaping (JobType) -> Ticket) {
self.job = job
self.jobProductionHandler = productionHandler
add(observers: job.observers)
}
internal var isCancelled: Bool { return lock.withCriticalScope { _cancelled } }
internal func add(observer: Observer) {
add(observers: [observer])
}
internal func ticket() -> Ticket {
return Ticket(state: self)
}
}
extension JobState { /* Actions */
internal func evaluateConditions(completion: @escaping ([NSError]) -> Void) {
let shouldEvaluate = lock.withCriticalScope { _ -> Bool in
if _state == .idle {
_state = .evaluating
return true
}
return false
}
guard shouldEvaluate == true else {
fatalError("Attempting to evaluate conditions on a non-idle JobState")
}
let group = DispatchGroup()
var results = Array<NSError?>(repeating: nil, count: job.conditions.count)
let q = DispatchQueue(label: "JobConditions", attributes: [], target: nil)
let ticket = self.ticket()
for (index, condition) in job.conditions.enumerated() {
group.enter()
condition.evaluate(ticket: ticket) { error in
q.async {
results[index] = error
group.leave()
}
}
}
group.notify(queue: q) {
var errors = results.flatMap { $0 }
if self.isCancelled {
let error: NSError
if let cancellationError = self.cancellationError {
error = cancellationError
} else {
error = NSError(jobError: .cancelled)
}
// make the cancellation error first, because it must have been done manually
// and manually-done things are more important
errors.insert(error, at: 0)
}
completion(errors)
if errors.isEmpty == false {
self.finish(errors: errors)
}
}
}
internal func execute() {
let handlers = lock.withCriticalScope { _ -> [Observer]? in
if _state == .evaluating && _cancelled == false {
_state = .executing
return _observers
} else {
return nil
}
}
if let handlers = handlers {
let t = ticket()
handlers.forEach { $0.jobDidStart(job: t) }
let c = JobContext(state: self)
job.block(c)
}
}
internal func finish(errors: [NSError] = []) {
let handlers = lock.withCriticalScope { _ -> [Observer] in
if _state == .executing {
_state = .finished(errors)
let returnValue = _observers
_observers = []
return returnValue
}
return []
}
let t = ticket()
handlers.forEach { $0.job(job: t, didFinishWithErrors: errors) }
}
internal func cancel(error: NSError? = nil) {
let handlers = lock.withCriticalScope { _ -> [Observer] in
// we can only cancel the job if it's not finished
if _cancelled == false && _state.isFinished == false {
_cancelled = true
cancellationError = error
return _observers
}
return []
}
let t = ticket()
handlers.forEach { $0.jobDidCancel(job: t) }
}
internal func produce(job: JobType) -> Ticket {
let newTicket = jobProductionHandler(job)
let handlers = lock.withCriticalScope { _observers }
let t = ticket()
handlers.forEach { $0.job(job: t, didProduce: newTicket) }
return newTicket
}
}
extension JobState { /* Observation */
func add(observers: [Observer]) {
var actions = [() -> Void]()
let t = ticket()
lock.withCriticalScope {
// we won't add observers to a job that has finished
if _state.isFinished == false {
_observers.append(contentsOf: observers)
}
if _cancelled == true && _state.isFinished == false {
// we may need to notify of cancellation
actions.append({
observers.forEach { $0.jobDidCancel(job: t) }
})
} else if case .finished(let errors) = _state {
// we may need to notify of finishing
actions.append({
observers.forEach { $0.job(job: t, didFinishWithErrors: errors) }
})
}
}
actions.forEach { $0() }
}
}
private func ==(lhs: JobState.State, rhs: JobState.State) -> Bool {
switch (lhs, rhs) {
case (.idle, .idle): return true
case (.evaluating, .evaluating): return true
case (.executing, .executing): return true
case (.finished(let lErrors), .finished(let rErrors)): return lErrors == rErrors
default: return false
}
}
| mit | e00a15163e95ca79618985ee082da664 | 29.726368 | 93 | 0.517487 | 5.008921 | false | false | false | false |
Chris-Perkins/Lifting-Buddy | Lifting Buddy/ExerciseHistoryTableView.swift | 1 | 8537 | //
// ExerciseHistoryTableView.swift
// Lifting Buddy
//
// Created by Christopher Perkins on 10/16/17.
// Copyright © 2017 Christopher Perkins. All rights reserved.
//
import UIKit
import RealmSwift
import CDAlertView
class ExerciseHistoryTableView: UITableView {
// MARK: View Properties
// A delegate to inform for tableview actions
public var tableViewDelegate: ExerciseHistoryEntryTableViewDelegate?
// The tableview should function differently depending on if it's in a session view or not
public var isInSessionView: Bool {
// If the superview is a workoutsessiontableviewcell, we know this view is in a session view.
if let _ = superview as? WorkoutSessionTableViewCell {
return true
}
return false
}
// holds the progressionmethods for this history piece
private let progressionMethods: List<ProgressionMethod>
// holds all the values for data
private var data: [ExerciseHistoryEntry]
// a label we use to display if there is no history in it
private var overlayLabel: UILabel?
// MARK: Static functions
static func heightPerCell(forHistoryEntry historyEntry: ExerciseHistoryEntry) -> CGFloat {
return ExerciseHistoryTableViewCell.baseHeight +
CGFloat(historyEntry.exerciseInfo.count) *
ExerciseHistoryTableViewCell.heightPerProgressionMethod
}
static func heightPerExercise(forExercise exercise: Exercise) -> CGFloat {
return ExerciseHistoryTableViewCell.baseHeight +
CGFloat(exercise.getProgressionMethods().count) *
ExerciseHistoryTableViewCell.heightPerProgressionMethod
}
// MARK: Initializers
init(forExercise exercise: Exercise, style: UITableView.Style) {
progressionMethods = exercise.getProgressionMethods()
data = [ExerciseHistoryEntry]()
super.init(frame: .zero, style: style)
setupTableView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View functions
override func layoutSubviews() {
super.layoutSubviews()
backgroundColor = .primaryBlackWhiteColor
overlayLabel?.setDefaultProperties()
overlayLabel?.text = NSLocalizedString(isInSessionView ?
"HistoryView.Label.NoSetData":
"HistoryView.Label.NoRecordedData", comment: "")
overlayLabel?.backgroundColor = .lightestBlackWhiteColor
}
// MARK: Custom functions
// Append some data to the tableView
public func appendDataToTableView(data: ExerciseHistoryEntry) {
self.data.insert(data, at: 0)
reloadData()
}
// Sets the data in reverse order (newest first)
public func setData(_ data: List<ExerciseHistoryEntry>) {
self.data.removeAll()
for dataEntry in data.reversed() {
self.data.append(dataEntry)
}
reloadData()
}
// Retrieve workouts
public func getData() -> [ExerciseHistoryEntry] {
return data
}
public func getTotalHeight() -> CGFloat {
var totalHeight: CGFloat = 0.0;
for historyEntry in getData() {
totalHeight += ExerciseHistoryTableView.heightPerCell(forHistoryEntry: historyEntry)
}
return totalHeight
}
// Determines whether or not we can modify the data at the given index path
public func canModifyDataAtIndexPath(_ indexPath: IndexPath) -> Bool {
// If we're in a session view, we can always modify it.
// Otherwise, if the entry was entered in a time less than the session start date
// This prevents the user from modifying the same data in two different places.
// We can never modify it if the exercise was deleted.
if data[indexPath.row].isInvalidated {
return false
}
else if let sessionStartDate = sessionStartDate {
return isInSessionView || data[indexPath.row].date!.seconds(from: sessionStartDate) < 0
} else {
return true
}
}
// Sets up basic table info
private func setupTableView() {
delegate = self
dataSource = self
allowsSelection = false
register(ExerciseHistoryTableViewCell.self, forCellReuseIdentifier: "cell")
backgroundColor = .clear
}
}
// MARK: TableView Delegate extension
extension ExerciseHistoryTableView: UITableViewDelegate {
// Each cell's height depends on the number of progression methods, but there is a flat height
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return ExerciseHistoryTableView.heightPerCell(forHistoryEntry: data[indexPath.row])
}
// allow cell deletion
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle,
forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if canModifyDataAtIndexPath(indexPath) {
let deletionData = data[indexPath.row]
let realm = try! Realm()
try! realm.write {
realm.delete(deletionData)
}
// Have to remove data beforehand otherwise the cell completestatus doesn't update properly.
data.remove(at: indexPath.row)
tableViewDelegate?.dataDeleted(deletedData: deletionData)
reloadData()
} else {
let alert = CDAlertView(title: NSLocalizedString("Message.CannotDeleteEntry.Title",
comment: ""),
message: NSLocalizedString("Message.CannotDeleteEntry.Desc",
comment: ""),
type: CDAlertViewType.error)
alert.add(action: CDAlertViewAction(title: NSLocalizedString("Button.OK", comment: ""),
font: nil,
textColor: UIColor.white,
backgroundColor: UIColor.niceBlue,
handler: nil))
alert.show()
}
}
}
func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
self.reloadData()
}
}
// MARK: Data Source extension
extension ExerciseHistoryTableView: UITableViewDataSource {
// Create our custom cell class
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ExerciseHistoryTableViewCell
// update the label in case of deletion
if isInSessionView {
cell.entryNumberLabel.text = "Set #\(data.count - (indexPath.row))"
cell.isUserInteractionEnabled = true
} else {
let dateFormatter = NSDate.getDateFormatter()
cell.entryNumberLabel.text = dateFormatter.string(from: data[indexPath.row].date!)
cell.isUserInteractionEnabled = canModifyDataAtIndexPath(indexPath)
}
cell.setData(data: data[indexPath.row].exerciseInfo)
return cell
}
// Data is what we use to fill in the table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if data.count == 0 && !isInSessionView {
// We should only display the overlay label if we're not in a session view
// Done because I don't think it looks nice in the session view.
if overlayLabel == nil {
overlayLabel = UILabel()
overlayLabel?.layer.zPosition = 1001
addSubview(overlayLabel!)
NSLayoutConstraint.clingViewToView(view: overlayLabel!, toView: superview!)
}
} else {
overlayLabel?.removeFromSuperview()
overlayLabel = nil
}
return data.count
}
}
| mit | 6f3d8857470299a21102e0515921983b | 36.438596 | 108 | 0.600281 | 5.638045 | false | false | false | false |
szk-atmosphere/SAParallaxViewControllerSwift | SAParallaxViewControllerSwift/SATransitionManager.swift | 2 | 3788 | //
// SATransitionManager.swift
// SAParallaxViewControllerSwift
//
// Created by 鈴木大貴 on 2015/02/05.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
open class SATransitionManager: NSObject, UIViewControllerAnimatedTransitioning {
open var animationDuration = 0.25
//MARK: - UIViewControllerAnimatedTransitioning
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return animationDuration
}
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to),
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
else { return }
let containerView = transitionContext.containerView
let duration = transitionDuration(using: transitionContext)
switch (toViewController, fromViewController) {
case (let _ as SAParallaxViewController, let fromVC as SADetailViewController):
guard let transitionContainer = fromVC.trantisionContainerView else { break }
containerView.addSubview(transitionContainer)
UIView.animate(withDuration: duration, delay: 0.0, options: .curveEaseIn, animations: {
transitionContainer.closeAnimation()
}, completion: { (finished) in
UIView.animate(withDuration: duration, delay: 0.0, options: .curveEaseIn, animations: {
transitionContainer.containerView?.blurContainerView.alpha = 1.0
}, completion: { (finished) in
let cancelled = transitionContext.transitionWasCancelled
if cancelled {
transitionContainer.removeFromSuperview()
} else {
containerView.addSubview(toViewController.view)
}
transitionContext.completeTransition(!cancelled)
})
})
return
case (let toVC as SADetailViewController, let _ as SAParallaxViewController):
guard let transitionContainer = toVC.trantisionContainerView else { break }
containerView.addSubview(transitionContainer)
UIView.animate(withDuration: duration, delay: 0.0, options: .curveEaseIn, animations: {
transitionContainer.containerView?.blurContainerView.alpha = 0.0
}, completion: { (finished) in
UIView.animate(withDuration: duration, delay: 0.0, options: .curveEaseIn, animations: {
transitionContainer.openAnimation()
}, completion: { (finished) in
let cancelled = transitionContext.transitionWasCancelled
if cancelled {
transitionContainer.removeFromSuperview()
} else {
containerView.addSubview(toViewController.view)
}
transitionContext.completeTransition(!cancelled)
})
})
return
default:
break
}
transitionContext.completeTransition(true)
}
}
| mit | 52b31668973083d9b556a6d5ec92c831 | 40.428571 | 120 | 0.563926 | 7.140152 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/Course Alerts/Views/CourseAlertCell.swift | 1 | 7007 | //
// CourseAlertCell.swift
// PennMobile
//
// Created by Raunaq Singh on 10/25/20.
// Copyright © 2020 PennLabs. All rights reserved.
//
import Foundation
import UIKit
class CourseAlertCell: UITableViewCell {
static let cellHeight: CGFloat = 100
static let identifier = "courseAlertCell"
fileprivate var detailLabel: UILabel!
fileprivate var courseLabel: UILabel!
fileprivate var activeLabel: UILabel!
fileprivate var courseStatusLabel: UILabel!
fileprivate var activeDot: UIView!
fileprivate var statusDot: UIView!
fileprivate var moreView: UIImageView!
var courseAlert: CourseAlert! {
didSet {
setupCell()
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Setup Cell
extension CourseAlertCell {
fileprivate func setupCell() {
if detailLabel == nil || courseLabel == nil || courseStatusLabel == nil || activeLabel == nil || activeDot == nil || statusDot == nil || moreView == nil {
setupUI()
} else {
detailLabel.text = "Alert Until Cancelled"
if !courseAlert.autoResubscribe {
detailLabel.text = "One-Time Alert"
if var alertNotifDateString = courseAlert.notificationSentAt {
if let index = (alertNotifDateString.range(of: ".")?.lowerBound) {
alertNotifDateString = String(alertNotifDateString.prefix(upTo: index))
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
if let alertNotifDate = dateFormatter.date(from: alertNotifDateString) {
dateFormatter.dateFormat = "MM/dd/YY"
detailLabel.text = "One-Time Alert - Last Notified on \(dateFormatter.string(from: alertNotifDate))"
} else {
detailLabel.text = "One-Time Alert"
}
}
}
courseLabel.text = courseAlert.section
activeDot.backgroundColor = courseAlert.isActive ? UIColor.baseGreen : UIColor.grey1
activeLabel.text = courseAlert.isActive ? "ACTIVE" : "INACTIVE"
activeLabel.textColor = courseAlert.isActive ? UIColor.baseGreen : UIColor.grey1
statusDot.backgroundColor = courseAlert.sectionStatus == "O" ? UIColor.blueLight : UIColor.grey1
statusDot.isHidden = !courseAlert.isActive
courseStatusLabel.text = courseAlert.sectionStatus == "O" ? "COURSE OPEN" : "COURSE CLOSED"
courseStatusLabel.textColor = courseAlert.sectionStatus == "O" ? UIColor.blueLight : UIColor.grey1
courseStatusLabel.isHidden = !courseAlert.isActive
}
}
}
// MARK: - Setup UI
extension CourseAlertCell {
fileprivate func setupUI() {
prepareCourseLabel()
prepareActiveDot()
prepareActiveLabel()
prepareStatusDot()
prepareCourseStatusLabel()
prepareDetailLabel()
prepareMoreView()
}
fileprivate func prepareCourseLabel() {
courseLabel = UILabel()
courseLabel.font = UIFont.primaryTitleFont
addSubview(courseLabel)
courseLabel.translatesAutoresizingMaskIntoConstraints = false
courseLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 15).isActive = true
courseLabel.topAnchor.constraint(equalTo: centerYAnchor, constant: -10).isActive = true
}
fileprivate func prepareActiveDot() {
activeDot = UIView()
activeDot.layer.cornerRadius = 4
addSubview(activeDot)
activeDot.translatesAutoresizingMaskIntoConstraints = false
activeDot.widthAnchor.constraint(equalToConstant: 8).isActive = true
activeDot.heightAnchor.constraint(equalToConstant: 8).isActive = true
activeDot.leadingAnchor.constraint(equalTo: courseLabel.leadingAnchor).isActive = true
activeDot.topAnchor.constraint(equalTo: courseLabel.topAnchor, constant: -20).isActive = true
}
fileprivate func prepareActiveLabel() {
activeLabel = UILabel()
activeLabel.font = UIFont.primaryInformationFont
addSubview(activeLabel)
activeLabel.translatesAutoresizingMaskIntoConstraints = false
activeLabel.leadingAnchor.constraint(equalTo: activeDot.trailingAnchor, constant: 3).isActive = true
activeLabel.centerYAnchor.constraint(equalTo: activeDot.centerYAnchor, constant: 0).isActive = true
}
fileprivate func prepareStatusDot() {
statusDot = UIView()
statusDot.layer.cornerRadius = 4
addSubview(statusDot)
statusDot.translatesAutoresizingMaskIntoConstraints = false
statusDot.widthAnchor.constraint(equalToConstant: 8).isActive = true
statusDot.heightAnchor.constraint(equalToConstant: 8).isActive = true
statusDot.leadingAnchor.constraint(equalTo: activeLabel.trailingAnchor, constant: 8).isActive = true
statusDot.topAnchor.constraint(equalTo: courseLabel.topAnchor, constant: -20).isActive = true
}
fileprivate func prepareCourseStatusLabel() {
courseStatusLabel = UILabel()
courseStatusLabel.font = UIFont.primaryInformationFont
addSubview(courseStatusLabel)
courseStatusLabel.translatesAutoresizingMaskIntoConstraints = false
courseStatusLabel.leadingAnchor.constraint(equalTo: statusDot.trailingAnchor, constant: 3).isActive = true
courseStatusLabel.centerYAnchor.constraint(equalTo: statusDot.centerYAnchor, constant: 0).isActive = true
}
fileprivate func prepareDetailLabel() {
detailLabel = UILabel()
detailLabel.font = UIFont.secondaryInformationFont
detailLabel.textColor = UIColor.grey1
addSubview(detailLabel)
detailLabel.translatesAutoresizingMaskIntoConstraints = false
detailLabel.leadingAnchor.constraint(equalTo: courseLabel.leadingAnchor).isActive = true
detailLabel.topAnchor.constraint(equalTo: courseLabel.bottomAnchor, constant: 6).isActive = true
}
fileprivate func prepareMoreView() {
moreView = UIImageView(image: UIImage(named: "More_Grey"))
moreView.contentMode = .scaleAspectFit
addSubview(moreView)
moreView.translatesAutoresizingMaskIntoConstraints = false
moreView.widthAnchor.constraint(equalToConstant: 20).isActive = true
moreView.heightAnchor.constraint(equalToConstant: 20).isActive = true
moreView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20).isActive = true
moreView.centerYAnchor.constraint(equalTo: courseLabel.centerYAnchor).isActive = true
moreView.isHidden = true
}
}
| mit | 5bbd2fe4d572e2f0bc082912a1a72173 | 41.981595 | 162 | 0.68213 | 5.185788 | false | false | false | false |
practicalswift/swift | stdlib/public/core/Map.swift | 5 | 7239 | //===--- Map.swift - Lazily map over a Sequence ---------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A `Sequence` whose elements consist of those in a `Base`
/// `Sequence` passed through a transform function returning `Element`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
@_fixed_layout
public struct LazyMapSequence<Base : Sequence, Element> {
public typealias Elements = LazyMapSequence
@usableFromInline
internal var _base: Base
@usableFromInline
internal let _transform: (Base.Element) -> Element
/// Creates an instance with elements `transform(x)` for each element
/// `x` of base.
@inlinable
internal init(_base: Base, transform: @escaping (Base.Element) -> Element) {
self._base = _base
self._transform = transform
}
}
extension LazyMapSequence {
@_fixed_layout
public struct Iterator {
@usableFromInline
internal var _base: Base.Iterator
@usableFromInline
internal let _transform: (Base.Element) -> Element
@inlinable
public var base: Base.Iterator { return _base }
@inlinable
internal init(
_base: Base.Iterator,
_transform: @escaping (Base.Element) -> Element
) {
self._base = _base
self._transform = _transform
}
}
}
extension LazyMapSequence.Iterator: IteratorProtocol, Sequence {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made.
@inlinable
public mutating func next() -> Element? {
return _base.next().map(_transform)
}
}
extension LazyMapSequence: LazySequenceProtocol {
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@inlinable
public __consuming func makeIterator() -> Iterator {
return Iterator(_base: _base.makeIterator(), _transform: _transform)
}
/// A value less than or equal to the number of elements in the sequence,
/// calculated nondestructively.
///
/// The default implementation returns 0. If you provide your own
/// implementation, make sure to compute the value nondestructively.
///
/// - Complexity: O(1), except if the sequence also conforms to `Collection`.
/// In this case, see the documentation of `Collection.underestimatedCount`.
@inlinable
public var underestimatedCount: Int {
return _base.underestimatedCount
}
}
/// A `Collection` whose elements consist of those in a `Base`
/// `Collection` passed through a transform function returning `Element`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
public typealias LazyMapCollection<T: Collection,U> = LazyMapSequence<T,U>
extension LazyMapCollection: Collection {
public typealias Index = Base.Index
public typealias Indices = Base.Indices
public typealias SubSequence = LazyMapCollection<Base.SubSequence, Element>
@inlinable
public var startIndex: Base.Index { return _base.startIndex }
@inlinable
public var endIndex: Base.Index { return _base.endIndex }
@inlinable
public func index(after i: Index) -> Index { return _base.index(after: i) }
@inlinable
public func formIndex(after i: inout Index) { _base.formIndex(after: &i) }
/// Accesses the element at `position`.
///
/// - Precondition: `position` is a valid position in `self` and
/// `position != endIndex`.
@inlinable
public subscript(position: Base.Index) -> Element {
return _transform(_base[position])
}
@inlinable
public subscript(bounds: Range<Base.Index>) -> SubSequence {
return SubSequence(_base: _base[bounds], transform: _transform)
}
@inlinable
public var indices: Indices {
return _base.indices
}
/// A Boolean value indicating whether the collection is empty.
@inlinable
public var isEmpty: Bool { return _base.isEmpty }
/// The number of elements in the collection.
///
/// To check whether the collection is empty, use its `isEmpty` property
/// instead of comparing `count` to zero. Unless the collection guarantees
/// random-access performance, calculating `count` can be an O(*n*)
/// operation.
///
/// - Complexity: O(1) if `Index` conforms to `RandomAccessIndex`; O(*n*)
/// otherwise.
@inlinable
public var count: Int {
return _base.count
}
@inlinable
public func index(_ i: Index, offsetBy n: Int) -> Index {
return _base.index(i, offsetBy: n)
}
@inlinable
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
return _base.index(i, offsetBy: n, limitedBy: limit)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
return _base.distance(from: start, to: end)
}
}
extension LazyMapCollection : BidirectionalCollection
where Base : BidirectionalCollection {
/// A value less than or equal to the number of elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
@inlinable
public func index(before i: Index) -> Index { return _base.index(before: i) }
@inlinable
public func formIndex(before i: inout Index) {
_base.formIndex(before: &i)
}
}
extension LazyMapCollection: LazyCollectionProtocol { }
extension LazyMapCollection : RandomAccessCollection
where Base : RandomAccessCollection { }
//===--- Support for s.lazy -----------------------------------------------===//
extension LazySequenceProtocol {
/// Returns a `LazyMapSequence` over this `Sequence`. The elements of
/// the result are computed lazily, each time they are read, by
/// calling `transform` function on a base element.
@inlinable
public func map<U>(
_ transform: @escaping (Element) -> U
) -> LazyMapSequence<Elements, U> {
return LazyMapSequence(_base: elements, transform: transform)
}
}
extension LazyMapSequence {
@inlinable
@available(swift, introduced: 5)
public func map<ElementOfResult>(
_ transform: @escaping (Element) -> ElementOfResult
) -> LazyMapSequence<Base, ElementOfResult> {
return LazyMapSequence<Base, ElementOfResult>(
_base: _base,
transform: { transform(self._transform($0)) })
}
}
extension LazyMapCollection {
@inlinable
@available(swift, introduced: 5)
public func map<ElementOfResult>(
_ transform: @escaping (Element) -> ElementOfResult
) -> LazyMapCollection<Base, ElementOfResult> {
return LazyMapCollection<Base, ElementOfResult>(
_base: _base,
transform: {transform(self._transform($0))})
}
}
| apache-2.0 | 658daf114340b9e8601e0d7c28f397ac | 30.611354 | 80 | 0.678961 | 4.374018 | false | false | false | false |
ingresse/ios-sdk | IngresseSDKTests/Services/TransactionServiceTests.swift | 1 | 10281 | //
// Copyright © 2018 Ingresse. All rights reserved.
//
import XCTest
@testable import IngresseSDK
class TransactionServiceTests: XCTestCase {
var restClient: MockClient!
var client: IngresseClient!
var service: TransactionService!
override func setUp() {
super.setUp()
restClient = MockClient()
client = IngresseClient(apiKey: "1234", userAgent: "", restClient: restClient)
service = IngresseService(client: client).transaction
}
}
// MARK: - Transaction Details
extension TransactionServiceTests {
func testGetTransactionDetails() {
// Given
let asyncExpectation = expectation(description: "transactionDetails")
var response = [String: Any]()
response["data"] = []
restClient.response = response
restClient.shouldFail = false
var success = false
var result: TransactionData?
// When
service.getTransactionDetails("transactionId", userToken: "1234-token", onSuccess: { (data) in
success = true
result = data
asyncExpectation.fulfill()
}, onError: { (_) in })
// Then
waitForExpectations(timeout: 1) { (_) in
XCTAssert(success)
XCTAssertNotNil(result)
}
}
func testGetTransactionDetailsFail() {
// Given
let asyncExpectation = expectation(description: "transactionDetails")
let error = APIError()
error.code = 1
error.message = "message"
error.category = "category"
restClient.error = error
restClient.shouldFail = true
var success = false
var apiError: APIError?
// When
service.getTransactionDetails("transactionId", userToken: "1234-token", onSuccess: { (_) in }, onError: { (error) in
success = false
apiError = error
asyncExpectation.fulfill()
})
// Then
waitForExpectations(timeout: 1) { (_) in
XCTAssertFalse(success)
XCTAssertNotNil(apiError)
XCTAssertEqual(apiError?.code, 1)
XCTAssertEqual(apiError?.message, "message")
XCTAssertEqual(apiError?.category, "category")
}
}
func testCreateTransaction() {
// Given
let asyncExpectation = expectation(description: "createTransaction")
var response = [String: Any]()
let card = ["CartaoCredito": ["paymentType": "credito"]]
response["data"] = [
"transactionId": "transactionId",
"availablePaymentMethods": card
]
restClient.response = response
restClient.shouldFail = false
var success = false
var result: Response.Shop.Transaction?
var ticket = PaymentTicket()
ticket.guestTypeId = "0"
ticket.quantity = 1
ticket.holder = []
let sessionTickets = [ticket]
var request = Request.Shop.Create()
request.userId = "userId"
request.eventId = "eventId"
request.passkey = "passkey"
request.tickets = sessionTickets
// When
service.createTransaction(request: request, userToken: "1234-token", onSuccess: { (transaction) in
success = true
result = transaction
asyncExpectation.fulfill()
}, onError: { (_) in })
// Then
waitForExpectations(timeout: 1) { (_) in
XCTAssert(success)
XCTAssertNotNil(result)
}
}
func testCreateTransactionWrongData() {
// Given
let asyncExpectation = expectation(description: "createTransaction")
var response = [String: Any]()
response["data"] = []
restClient.response = response
restClient.shouldFail = false
var success = false
var apiError: APIError?
var ticket = PaymentTicket()
ticket.guestTypeId = "0"
ticket.quantity = 1
ticket.holder = []
let sessionTickets = [ticket]
var request = Request.Shop.Create()
request.userId = "userId"
request.eventId = "eventId"
request.passkey = "passkey"
request.tickets = sessionTickets
// When
service.createTransaction(request: request, userToken: "1234-token", onSuccess: { (_) in }, onError: { (error) in
success = false
apiError = error
asyncExpectation.fulfill()
})
// Then
waitForExpectations(timeout: 1) { (_) in
XCTAssertFalse(success)
XCTAssertNotNil(apiError)
let defaultError = APIError.getDefaultError()
XCTAssertEqual(apiError?.code, defaultError.code)
XCTAssertEqual(apiError?.message, defaultError.message)
}
}
func testCreateTransactionFail() {
// Given
let asyncExpectation = expectation(description: "createTransaction")
let error = APIError()
error.code = 1
error.message = "message"
error.category = "category"
restClient.error = error
restClient.shouldFail = true
var success = false
var apiError: APIError?
var request = Request.Shop.Create()
request.userId = "userId"
request.eventId = "eventId"
request.passkey = "passkey"
request.tickets = []
// When
service.createTransaction(request: request, userToken: "1234-token", onSuccess: { (_) in }, onError: { (error) in
success = false
apiError = error
asyncExpectation.fulfill()
})
// Then
waitForExpectations(timeout: 1) { (_) in
XCTAssertFalse(success)
XCTAssertNotNil(apiError)
XCTAssertEqual(apiError?.code, 1)
XCTAssertEqual(apiError?.message, "message")
XCTAssertEqual(apiError?.category, "category")
}
}
}
// MARK: - Checkin Status
extension TransactionServiceTests {
func testGetCheckinStatus() {
// Given
let asyncExpectation = expectation(description: "checkinStatus")
var response = [String: Any]()
response["data"] = []
restClient.response = response
restClient.shouldFail = false
var success = false
var result: [CheckinSession]?
// When
service.getCheckinStatus("123456", userToken: "1234-token", onSuccess: { (data) in
success = true
result = data
asyncExpectation.fulfill()
}, onError: { (_) in })
// Then
waitForExpectations(timeout: 1) { (_) in
XCTAssert(success)
XCTAssertNotNil(result)
}
}
func testGetCheckinStatusWrongData() {
// Given
let asyncExpectation = expectation(description: "checkinStatus")
var response = [String: Any]()
response["advertisement"] = nil
restClient.response = response
restClient.shouldFail = false
var success = false
var apiError: APIError?
// When
service.getCheckinStatus("123456", userToken: "1234-token", onSuccess: { (_) in }, onError: { (error) in
success = false
apiError = error
asyncExpectation.fulfill()
})
// Then
waitForExpectations(timeout: 1) { (_) in
XCTAssertFalse(success)
XCTAssertNotNil(apiError)
let defaultError = APIError.getDefaultError()
XCTAssertEqual(apiError?.code, defaultError.code)
XCTAssertEqual(apiError?.message, defaultError.message)
}
}
func testGetCheckinStatusFail() {
// Given
let asyncExpectation = expectation(description: "checkinStatus")
let error = APIError()
error.code = 1
error.message = "message"
error.category = "category"
restClient.error = error
restClient.shouldFail = true
var success = false
var apiError: APIError?
// When
service.getCheckinStatus("123456", userToken: "1234-token", onSuccess: { (_) in }, onError: { (error) in
success = false
apiError = error
asyncExpectation.fulfill()
})
// Then
waitForExpectations(timeout: 1) { (_) in
XCTAssertFalse(success)
XCTAssertNotNil(apiError)
XCTAssertEqual(apiError?.code, 1)
XCTAssertEqual(apiError?.message, "message")
XCTAssertEqual(apiError?.category, "category")
}
}
}
// MARK: - Cancel Transaction
extension TransactionServiceTests {
func testCancelTransaction() {
// Given
let asyncExpectation = expectation(description: "cancelTransaction")
var response = [String: Any]()
response["data"] = []
restClient.response = response
restClient.shouldFail = false
var success = false
// When
service.cancelTransaction("transactionId", userToken: "1234-token", onSuccess: {
success = true
asyncExpectation.fulfill()
}, onError: { (_) in })
// Then
waitForExpectations(timeout: 1) { (_) in
XCTAssert(success)
}
}
func testCancelTransactionFail() {
// Given
let asyncExpectation = expectation(description: "cancelTransaction")
let error = APIError()
error.code = 1
error.message = "message"
error.category = "category"
restClient.error = error
restClient.shouldFail = true
var success = false
var apiError: APIError?
// When
service.cancelTransaction("transactionId", userToken: "1234-token", onSuccess: {}, onError: { (error) in
success = false
apiError = error
asyncExpectation.fulfill()
})
// Then
waitForExpectations(timeout: 1) { (_) in
XCTAssertFalse(success)
XCTAssertNotNil(apiError)
XCTAssertEqual(apiError?.code, 1)
XCTAssertEqual(apiError?.message, "message")
XCTAssertEqual(apiError?.category, "category")
}
}
}
| mit | f09dbd3e0a23be941328778454f34e4e | 27.715084 | 124 | 0.580253 | 5.271795 | false | false | false | false |
sora0077/QiitaKit | QiitaKit/src/Endpoint/Project/CreateProject.swift | 1 | 2117 | //
// CreateProject.swift
// QiitaKit
//
// Created on 2015/06/08.
// Copyright (c) 2015年 林達也. All rights reserved.
//
import Foundation
import APIKit
import Result
/**
* プロジェクトを新たに作成します。
*/
public struct CreateProject {
/// このプロジェクトが進行中かどうか
///
public let archived: Bool
/// Markdown形式の本文
/// example: # Example
///
public let body: String
/// プロジェクト名
/// example: Kobiro Project
///
public let name: String
/// 投稿に付いたタグ一覧
/// example: [{"name"=>"Ruby", "versions"=>["0.0.1"]}]
///
public let tags: Array<Tagging>
public init(archived: Bool, body: String, name: String, tags: Array<Tagging>) {
self.archived = archived
self.body = body
self.name = name
self.tags = tags
}
}
extension CreateProject: QiitaRequestToken {
public typealias Response = Project
public typealias SerializedObject = [String: AnyObject]
public var method: HTTPMethod {
return .POST
}
public var path: String {
return "/api/v2/projects"
}
public var parameters: [String: AnyObject]? {
return [
"archived": archived,
"body": body,
"name": name,
"tags": tags.map({ ["name": $0.name, "versions": $0.versions] }),
]
}
public var encoding: RequestEncoding {
return .JSON
}
}
public extension CreateProject {
func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response {
let project = Project(
rendered_body: object["rendered_body"] as! String,
archived: object["archived"] as! Bool,
body: object["body"] as! String,
created_at: object["created_at"] as! String,
id: object["id"] as! Int,
name: object["name"] as! String,
updated_at: object["updated_at"] as! String
)
return project
}
}
| mit | 168e14a935c77691fb28406f3f396842 | 22 | 119 | 0.570215 | 3.986056 | false | false | false | false |
armadsen/CocoaHeads-SLC-Presentations | KVO-and-Related-Patterns-In-Swift/BasicSwiftKVODemo.playground/Contents.swift | 1 | 1235 | import Foundation
// To make your objects observable, inherit from an ObjC class, and mark observable properties `dynamic`:
class Foo : NSObject {
dynamic var bar = 0
}
// To observe using KVO, the observer must also inherit from an ObjC class.
class Observer : NSObject {
var ObserverKVOContext: Int = 0
let foo: Foo
override init() {
foo = Foo()
super.init()
foo.addObserver(self, forKeyPath: "bar", options: [], context: &ObserverKVOContext)
}
// You must remove yourself as an observer before being deallocated
deinit {
foo.removeObserver(self, forKeyPath: "bar")
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath, let object = object else { return }
// Make sure the notification is intended for us, and not a superclass
if context != &ObserverKVOContext {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
print("\(object)'s \(keyPath) changed to \((object as AnyObject).value(forKeyPath: keyPath)!)")
}
}
// Let's try it out
let observer = Observer()
let foo = observer.foo
foo.bar = 42
foo.bar = 27
| mit | f0d33587cedff2f9cbb488665fc69680 | 25.847826 | 148 | 0.710121 | 3.895899 | false | false | false | false |
chrisjmendez/swift-exercises | Walkthroughs/MyPresentation/Carthage/Checkouts/Presentation/Pod/Tests/Specs/ContentSpec.swift | 8 | 1358 | import Quick
import Nimble
import UIKit
import Presentation
class ContentSpec: QuickSpec {
override func spec() {
describe("Content") {
var content: Content!
var position: Position!
var superview: UIView!
beforeEach {
position = Position(left: 0.5, top: 0.5)
content = Content(view: SpecHelper.imageView(), position: position)
superview = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 300.0, height: 200.0))
}
describe("#layout") {
context("with superview") {
beforeEach {
superview.addSubview(content.view)
}
it("changes center correctly") {
let center = position.originInFrame(superview.bounds)
content.layout()
expect(content.view.center).to(equal(center))
}
it("changes origin correctly") {
content.centered = false
let origin = position.originInFrame(superview.bounds)
content.layout()
expect(content.view.frame.origin).to(equal(origin))
}
}
context("without superview") {
it("doesn't change origin") {
let origin = content.view.frame.origin
content.layout()
expect(content.view.frame.origin).to(equal(origin))
}
}
}
}
}
}
| mit | 7da34e81940d520f1f0bc7cdc9ff6ed0 | 24.622642 | 86 | 0.564065 | 4.452459 | false | false | false | false |
Turistforeningen/SjekkUT | ios/SjekkUt/network/TurbasenApi.swift | 1 | 10834 | //
// Turbasen.swift
// SjekkUt
//
// Created by Henrik Hartz on 26/07/16.
// Copyright © 2016 Den Norske Turistforening. All rights reserved.
//
import Foundation
import Alamofire
open class TurbasenApi: DntManager {
static let instance = TurbasenApi()
// singletons
lazy var locationController: Location = {
Location.instance
}()
lazy var modelController: ModelController = {
ModelController.instance
}()
lazy var defaults: UserDefaults = {
UserDefaults.standard
}()
var lastUpdatedDistanceLocation: CLLocation? {
get {
if let locationData = defaults.data(forKey: #function) {
let location = NSKeyedUnarchiver.unarchiveObject(with: locationData) as? CLLocation
return location
}
return nil
}
set {
if let location = newValue {
let locationData = NSKeyedArchiver.archivedData(withRootObject: location)
defaults.set(locationData, forKey: #function)
} else {
defaults.removeObject(forKey: #function)
}
defaults.synchronize()
}
}
var apiKey: String!
var isObserving: Bool = false
// paging support
@objc dynamic var projectHasMore:Bool = false
@objc dynamic var projectTotal:Int = 0
var projectSkip:Int? {
didSet {
projectHasMore = (projectSkip ?? 0) < projectTotal
}
}
required public init(forDomain aDomain: String = "api.nasjonalturbase.no") {
super.init(forDomain:aDomain)
self.apiKey = (aDomain + ".api_key").stringContents(inClass:type(of: self))
let notificationName = kSjekkUtNotificationLocationChanged.Name()
NotificationCenter.default.addObserver(self, selector: #selector(updateDistance), name: notificationName,
object: nil)
}
// MARK: place
func getPlace(_ aPlace: Place, finishHandler:(()->Void)? = nil) {
guard let placeId = aPlace.identifier else {
showErrorMessage(String.localizedStringWithFormat("No place id"))
return
}
request(PlaceRouter.Retrieve(placeId: placeId))
.validate().responseJSON { response in
switch response.result {
case .success:
if let aJSON = response.result.value as? [AnyHashable: Any] {
self.modelController.save {
Place.insertOrUpdate(aJSON)
}
}
case .failure(let error):
self.failHandler(error as NSError, for: response)
}
if let finished = finishHandler {
finished()
}
}
}
func getPlaces(matchingName: String) {
// ignore searches with fewer than n characters
if matchingName.count < kSjekkUtConstantSearchCharacterLimit {
return
}
request(PlaceRouter.Find(name: matchingName))
.validate().responseJSON { response in
switch response.result {
case .success(let value):
guard let placesJSON = (value as? [AnyHashable: Any])?["documents"] as? [[AnyHashable: Any]] else {
break
}
self.modelController.save {
for placeJSON in placesJSON {
_ = Place.insertOrUpdate(placeJSON)
}
}
case .failure(let error):
self.failHandler(error, for: response, retry: false)
}
}
}
// MARK: projects
func getProjects(_ aFinishHandler: (() -> Void)? = nil ) {
request(ProjectRouter.List(skip: projectSkip)).validate().responseJSON { response in
switch response.result {
case .success(let value):
if let json = value as? [AnyHashable: Any] {
self.updateProjectsUsing(json)
if let countString = response.response?.allHeaderFields["count-return"] as? String,
let count = Int(countString),
let total = Int(response.response?.allHeaderFields["count-total"] as! String) {
self.projectTotal = total
self.projectSkip = (self.projectSkip ?? 0) + count
}
else {
print("Getting projects - could not update pagination details for headers: \(response.response?.allHeaderFields)")
}
}
case .failure(let error):
self.failHandler(error as NSError, for: response)
}
if let finishHandler = aFinishHandler {
finishHandler()
}
}
}
func updateProjectsUsing(_ json:[AnyHashable:Any]) {
if let someProjects = json["documents"] as? [[AnyHashable: Any]] {
// update or insert entities from API
modelController.save {
// prevent upstream deleted projects from showing
if self.projectSkip == nil,
let projects = Project.allEntities() as? [Project] {
for aProject: Project in projects {
// ignore projects we participate in, they update via SjekkUtApi.getProfile
if aProject.isParticipating?.boolValue ?? false {
continue
}
aProject.isHidden = NSNumber.init(value: true)
}
}
for aProjectDict in someProjects {
let aProject = Project.insertOrUpdate(aProjectDict)
aProject.isHidden = NSNumber(value: aProject.isExpired)
if let projectId = aProject.identifier {
self.getProjectAnd(projectId, {_ in }, aFailHandler: {})
}
}
}
}
}
// MARK: project
open func getProjectAnd( _ projectId: String, _ projectHandler:@escaping (Project) -> Void,
aFailHandler:@escaping () -> Void) {
request(ProjectRouter.Retrieve(id: projectId))
.validate()
.responseJSON { response in
switch response.result {
case .success:
if let aJSON = response.result.value as? [AnyHashable: Any] {
self.modelController.save {
// update or insert project from API
let theProject: Project = Project.insertOrUpdate(aJSON)
projectHandler(theProject)
}
}
case .failure(let error as NSError):
if response.response?.statusCode == 404 {
let missingProject = Project.find(withId: projectId)
var userInfo = error.userInfo
userInfo["path"] = response.request?.url?.path ?? "unknown URL"
userInfo[NSLocalizedDescriptionKey] = error.localizedDescription
let nsError = NSError.init(domain: error.domain, code: error.code, userInfo: userInfo)
DntManager.logError(nsError, for: response)
self.modelController.save {
missingProject.isHidden = true
}
} else {
aFailHandler()
self.failHandler(error, for: response)
}
default:
break
}
}
}
open func getProjectAndPlaces(_ projectId: String, finishHandler:@escaping (() -> (Void))) {
getProjectAnd(projectId, { (theProject: Project) -> Void in
if let places = theProject.places?.array as? [Place] {
for place in places {
// fetch place with images
self.getPlace(place)
}
}
finishHandler()
}, aFailHandler: finishHandler)
}
func getProjects(matchingName: String) {
// don't search unless we have at least n characters
if matchingName.count < kSjekkUtConstantSearchCharacterLimit {
return
}
request(ProjectRouter.Find(name: matchingName))
.validate()
.responseJSON { response in
switch response.result {
case .success:
if let aJSON = response.result.value as? [AnyHashable: Any],
let projects = aJSON["documents"] as? [[AnyHashable: Any]] {
self.modelController.save {
// update or insert project from API
for projectDict in projects {
let project = Project.insertOrUpdate(projectDict)
// hide any new projects that have not been made visisble in main view
if project.isHidden == nil {
project.isHidden = true
}
}
}
}
case .failure(let error as NSError):
self.failHandler(error, for: response, retry: false)
default:
break
}
}
}
// MARK: distance
@objc func updateDistance() {
// check if distance to last update is above threshold
if let current = locationController.currentLocation, let last = lastUpdatedDistanceLocation, last.distance(from: current) < kSjekkUtConstantUpdateDistanceLimit {
return
}
if let current = locationController.currentLocation {
lastUpdatedDistanceLocation = current
}
modelController.save {
if let projects = Project.allEntities() as? [Project] {
for aProject in projects {
aProject.updateDistance()
}
}
for aPlace in Place.placesWithoutProject() {
aPlace.updateDistance()
}
NotificationCenter.default.post(name: kSjekkUtNotificationDistanceChanged.Name(), object: nil)
}
}
}
| mit | 109d85ee8c65d696081b5b10280dd0b1 | 36.614583 | 169 | 0.506969 | 5.612953 | false | false | false | false |
haawa799/WaniKit2 | Sources/WaniKit/Apple NSOperation/NetworkObserver.swift | 2 | 3259 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Contains the code to manage the visibility of the network activity indicator
*/
import Foundation
#if os(iOS)
import UIKit
#endif
/**
An `OperationObserver` that will cause the network activity indicator to appear
as long as the `Operation` to which it is attached is executing.
*/
struct NetworkObserver: OperationObserver {
// MARK: Initilization
init() { }
func operationDidStart(operation: Operation) {
dispatch_async(dispatch_get_main_queue()) {
// Increment the network indicator's "reference count"
NetworkIndicatorController.sharedIndicatorController.networkActivityDidStart()
}
}
func operation(operation: Operation, didProduceOperation newOperation: NSOperation) { }
func operationDidFinish(operation: Operation, errors: [NSError]) {
dispatch_async(dispatch_get_main_queue()) {
// Decrement the network indicator's "reference count".
NetworkIndicatorController.sharedIndicatorController.networkActivityDidEnd()
}
}
}
/// A singleton to manage a visual "reference count" on the network activity indicator.
private class NetworkIndicatorController {
// MARK: Properties
static let sharedIndicatorController = NetworkIndicatorController()
private var activityCount = 0
private var visibilityTimer: Timer?
// MARK: Methods
func networkActivityDidStart() {
assert(NSThread.isMainThread(), "Altering network activity indicator state can only be done on the main thread.")
activityCount++
updateIndicatorVisibility()
}
func networkActivityDidEnd() {
assert(NSThread.isMainThread(), "Altering network activity indicator state can only be done on the main thread.")
activityCount--
updateIndicatorVisibility()
}
private func updateIndicatorVisibility() {
if activityCount > 0 {
showIndicator()
}
else {
/*
To prevent the indicator from flickering on and off, we delay the
hiding of the indicator by one second. This provides the chance
to come in and invalidate the timer before it fires.
*/
visibilityTimer = Timer(interval: 1.0) {
self.hideIndicator()
}
}
}
private func showIndicator() {
visibilityTimer?.cancel()
visibilityTimer = nil
showHideIndicator(true)
}
private func hideIndicator() {
visibilityTimer?.cancel()
visibilityTimer = nil
showHideIndicator(false)
}
private func showHideIndicator(show: Bool) {
#if os(iOS)
UIApplication.sharedApplication().networkActivityIndicatorVisible = show
#endif
}
}
/// Essentially a cancellable `dispatch_after`.
class Timer {
// MARK: Properties
private var isCancelled = false
// MARK: Initialization
init(interval: NSTimeInterval, handler: dispatch_block_t) {
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(interval * Double(NSEC_PER_SEC)))
dispatch_after(when, dispatch_get_main_queue()) { [weak self] in
if self?.isCancelled == false {
handler()
}
}
}
func cancel() {
isCancelled = true
}
} | mit | 3d33098de8ab4060652f20aa01c4b196 | 23.681818 | 117 | 0.691434 | 4.761696 | false | false | false | false |
thesecretlab/ultimate-swift-video | UIDocuments/UIDocuments/MasterViewController.swift | 1 | 4100 | //
// MasterViewController.swift
// UIDocuments
//
// Created by Jon Manning on 21/11/2014.
// Copyright (c) 2014 Secret Lab. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var documents: [NSURL] = []
var documentsFolderURL : NSURL? {
get {
return NSFileManager.defaultManager().URLsForDirectory(
NSSearchPathDirectory.DocumentDirectory,
inDomains: NSSearchPathDomainMask.UserDomainMask).first as? NSURL
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
}
func refreshFileList() {
var error : NSError?
self.documents = NSFileManager.defaultManager().contentsOfDirectoryAtURL(self.documentsFolderURL!, includingPropertiesForKeys: [NSURLNameKey], options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: &error) as [NSURL]
self.tableView.reloadData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
refreshFileList()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
let fileName = "New Document \(Int(NSDate.timeIntervalSinceReferenceDate())).fancyDocument"
if let fileURL = self.documentsFolderURL?.URLByAppendingPathComponent(fileName) {
let newDocument = FancyDocument(fileURL: fileURL)
newDocument.saveToURL(fileURL, forSaveOperation: UIDocumentSaveOperation.ForCreating, completionHandler: { (success) -> Void in
self.refreshFileList()
})
}
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let URL = documents[indexPath.row] as NSURL
(segue.destinationViewController as DetailViewController).documentURL = URL
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return documents.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let object = documents[indexPath.row] as NSURL
cell.textLabel.text = object.lastPathComponent
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let url = documents[indexPath.row]
NSFileManager.defaultManager().removeItemAtURL(url, error: nil)
self.refreshFileList()
} 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.
}
}
}
| mit | d1be52cedf87db8d941f6d600540ef69 | 32.064516 | 233 | 0.648293 | 5.840456 | false | false | false | false |
tuarua/Swift-IOS-ANE | starter_projects/native_library/mac/HelloWorldANE/HelloWorldANE/SwiftController+FreSwift.swift | 1 | 1301 | import Foundation
import FreSwift
extension SwiftController: FreSwiftMainController {
// Must have this function. It exposes the methods to our entry ObjC.
@objc public func getFunctions(prefix: String) -> [String] {
functionsToSet["\(prefix)init"] = initController
functionsToSet["\(prefix)sayHello"] = sayHello
var arr: [String] = []
for key in functionsToSet.keys {
arr.append(key)
}
return arr
}
// Must have these 4 functions.
@objc public func dispose() {
}
//Exposes the methods to our entry ObjC.
@objc public func callSwiftFunction(name: String, ctx: FREContext, argc: FREArgc, argv: FREArgv) -> FREObject? {
if let fm = functionsToSet[name] {
return fm(ctx, argc, argv)
}
return nil
}
//Here we set our FREContext
@objc public func setFREContext(ctx: FREContext) {
self.context = FreContextSwift(freContext: ctx)
// Turn on FreSwift logging
FreSwiftLogger.shared.context = context
}
// Here we add observers for any app delegate stuff
// Observers are independant of other ANEs and cause no conflicts
// DO NOT OVERRIDE THE DEFAULT !!
@objc public func onLoad() {
}
}
| apache-2.0 | 26c7facac03e69a6a0ec88f24f5356f5 | 29.97619 | 116 | 0.623367 | 4.42517 | false | false | false | false |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/Internal/API Bindings/Link/ConsumerSession+LookupResponse.swift | 1 | 2510 | //
// ConsumerSession+LookupResponse.swift
// StripePaymentSheet
//
// Created by Cameron Sabol on 11/2/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import UIKit
@_spi(STP) import StripePayments
extension ConsumerSession {
struct Preferences {
let publishableKey: String
}
class LookupResponse: NSObject, STPAPIResponseDecodable {
let allResponseFields: [AnyHashable: Any]
enum ResponseType {
case found(
consumerSession: ConsumerSession,
preferences: ConsumerSession.Preferences
)
// errorMessage can be used internally to differentiate between
// a not found because of an unrecognized email or a not found
// due to an invalid cookie
case notFound(errorMessage: String)
/// Lookup call was not provided an email and no cookies stored
case noAvailableLookupParams
}
let responseType: ResponseType
init(_ responseType: ResponseType,
allResponseFields: [AnyHashable: Any]) {
self.responseType = responseType
self.allResponseFields = allResponseFields
super.init()
}
static func decodedObject(fromAPIResponse response: [AnyHashable : Any]?) -> Self? {
guard let response = response,
let exists = response["exists"] as? Bool else {
return nil
}
if exists {
if let consumerSession = ConsumerSession.decodedObject(fromAPIResponse: response),
let publishableKey = response["publishable_key"] as? String {
return LookupResponse(
.found(
consumerSession: consumerSession,
preferences: .init(publishableKey: publishableKey)
),
allResponseFields: response
) as? Self
} else {
return nil
}
} else {
if let errorMessage = response["error_message"] as? String {
return LookupResponse(.notFound(errorMessage: errorMessage),
allResponseFields: response) as? Self
} else {
return nil
}
}
}
}
}
| mit | fb27b1ff02e0ebb47fbb5b4c137f3aab | 33.369863 | 98 | 0.528896 | 6.089806 | false | false | false | false |
jcwcheng/aeire-ios | SmartDoorBell/IndexCollectionViewController.swift | 1 | 2466 | //
// IndexCollectionViewController.swift
// SmartDoorBell
//
// Created by Archerwind on 5/23/17.
// Copyright © 2017 Archerwind. All rights reserved.
//
import UIKit
import Spring
extension IndexViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView( _ collectionView: UICollectionView, numberOfItemsInSection section: Int ) -> Int {
return 15
}
func collectionView( _ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath ) {
if collectionView == self.sceneCollectionView {
let current = collectionView.cellForItem( at: indexPath ) as! SceneCollectionCell
current.toggleUI()
}
else if collectionView == self.deviceCollectionView {
let current = collectionView.cellForItem( at: indexPath ) as! DeviceCollectionCell
current.toggleUI()
}
}
func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath ) -> UICollectionViewCell {
if collectionView == self.deviceCollectionView {
let cell = collectionView.dequeueReusableCell( withReuseIdentifier: "deviceCell", for: indexPath as IndexPath ) as! DeviceCollectionCell
cell.loadCell( indexPath: indexPath )
return cell
}
else if collectionView == self.roomCollectionView {
let cell = collectionView.dequeueReusableCell( withReuseIdentifier: "roomCell", for: indexPath as IndexPath ) as! RoomCollectionCell
cell.loadCell( indexPath: indexPath )
return cell
}
else {
let cell = collectionView.dequeueReusableCell( withReuseIdentifier: "sceneCell", for: indexPath as IndexPath ) as! SceneCollectionCell
cell.loadCell( indexPath: indexPath )
return cell
}
}
// func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath ) -> CGSize {
// if collectionView == self.favoriteCollectionView {
// let width = self.favoriteCollectionView.bounds.width
// let height = self.favoriteCollectionView.bounds.height
// return CGSize(width: (width - 10)/5.5, height: (height-20) )
// }
// let width = self.giftCollectionView.bounds.width
// let height = self.giftCollectionView.bounds.height
// return CGSize( width: (width - 40), height: (height-10) )
// }
}
| mit | 1baa89ab654c93b16ae0e6e4fc6022a9 | 42.245614 | 162 | 0.705071 | 5.156904 | false | false | false | false |
danielmartin/swift | test/IRGen/mixed_mode_class_with_unimportable_fields.swift | 2 | 5218 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t/UsingObjCStuff.swiftmodule -module-name UsingObjCStuff -I %t -I %S/Inputs/mixed_mode -swift-version 5 %S/Inputs/mixed_mode/UsingObjCStuff.swift
// RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/mixed_mode -module-name main -swift-version 4 %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-V4 -DWORD=i%target-ptrsize
// RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/mixed_mode -module-name main -swift-version 5 %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-V5 -DWORD=i%target-ptrsize
// REQUIRES: objc_interop
import UsingObjCStuff
public class SubButtHolder: ButtHolder {
final var w: Float = 0
override public func virtual() {}
public func subVirtual() {}
}
public class SubSubButtHolder: SubButtHolder {
public override func virtual() {}
public override func subVirtual() {}
}
// CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc void @"$s4main17accessFinalFields2ofyp_ypt14UsingObjCStuff10ButtHolderC_tF"
public func accessFinalFields(of holder: ButtHolder) -> (Any, Any) {
// ButtHolder.y cannot be imported in Swift 4 mode, so make sure we use field
// offset globals here.
// CHECK-V4: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$s14UsingObjCStuff10ButtHolderC1xSivpWvd"
// CHECK-V4: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8*
// CHECK-V4: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]]
// CHECK-V4: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$s14UsingObjCStuff10ButtHolderC1zSSvpWvd"
// CHECK-V4: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8*
// CHECK-V4: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]]
// ButtHolder.y is correctly imported in Swift 5 mode, so we can use fixed offsets.
// CHECK-V5: [[OFFSET:%.*]] = getelementptr inbounds %T14UsingObjCStuff10ButtHolderC, %T14UsingObjCStuff10ButtHolderC* %2, i32 0, i32 1
// CHECK-V5: [[OFFSET:%.*]] = getelementptr inbounds %T14UsingObjCStuff10ButtHolderC, %T14UsingObjCStuff10ButtHolderC* %2, i32 0, i32 3
return (holder.x, holder.z)
}
// CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc void @"$s4main17accessFinalFields5ofSubyp_ypyptAA0F10ButtHolderC_tF"
public func accessFinalFields(ofSub holder: SubButtHolder) -> (Any, Any, Any) {
// We should use the runtime-adjusted ivar offsets since we may not have
// a full picture of the layout in mixed Swift language version modes.
// ButtHolder.y cannot be imported in Swift 4 mode, so make sure we use field
// offset globals here.
// CHECK-V4: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$s14UsingObjCStuff10ButtHolderC1xSivpWvd"
// CHECK-V4: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8*
// CHECK-V4: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]]
// CHECK-V4: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$s14UsingObjCStuff10ButtHolderC1zSSvpWvd"
// CHECK-V4: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8*
// CHECK-V4: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]]
// CHECK-V4: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$s4main13SubButtHolderC1wSfvpWvd"
// CHECK-V4: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8*
// CHECK-V4: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]]
// ButtHolder.y is correctly imported in Swift 5 mode, so we can use fixed offsets.
// CHECK-V5: [[SELF:%.*]] = bitcast %T4main13SubButtHolderC* %3 to %T14UsingObjCStuff10ButtHolderC*
// CHECK-V5: [[OFFSET:%.*]] = getelementptr inbounds %T14UsingObjCStuff10ButtHolderC, %T14UsingObjCStuff10ButtHolderC* [[SELF]], i32 0, i32 1
// CHECK-V5: [[SELF:%.*]] = bitcast %T4main13SubButtHolderC* %3 to %T14UsingObjCStuff10ButtHolderC*
// CHECK-V5: [[OFFSET:%.*]] = getelementptr inbounds %T14UsingObjCStuff10ButtHolderC, %T14UsingObjCStuff10ButtHolderC* [[SELF]], i32 0, i32 3
// CHECK-V5: [[OFFSET:%.*]] = getelementptr inbounds %T4main13SubButtHolderC, %T4main13SubButtHolderC* %3, i32 0, i32 4
return (holder.x, holder.z, holder.w)
}
// CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc void @"$s4main12invokeMethod2onyAA13SubButtHolderC_tF"
public func invokeMethod(on holder: SubButtHolder) {
// CHECK-64: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 13
// CHECK-32: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 16
// CHECK: [[IMPL:%.*]] = load {{.*}} [[IMPL_ADDR]]
// CHECK: call swiftcc void [[IMPL]]
holder.virtual()
// CHECK-64: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 16
// CHECK-32: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 19
// CHECK: [[IMPL:%.*]] = load {{.*}} [[IMPL_ADDR]]
// CHECK: call swiftcc void [[IMPL]]
holder.subVirtual()
}
// CHECK-V4-LABEL: define internal swiftcc %swift.metadata_response @"$s4main13SubButtHolderCMr"(%swift.type*, i8*, i8**)
// CHECK-V4: call void @swift_initClassMetadata(
// CHECK-V4-LABEL: define internal swiftcc %swift.metadata_response @"$s4main03SubB10ButtHolderCMr"(%swift.type*, i8*, i8**)
// CHECK-V4: call void @swift_initClassMetadata(
| apache-2.0 | 38d8a98e866710fa8627f861f6cb1558 | 51.707071 | 229 | 0.678421 | 3.419397 | false | false | false | false |
hollance/swift-algorithm-club | Treap/TreapCollectionType.swift | 9 | 3160 | //
// TreapCollectionType.swift
// Treap
//
// Created by Robert Thompson on 2/18/16.
// Copyright © 2016 Robert Thompson
/* Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
import Foundation
extension Treap: MutableCollection {
public typealias Index = TreapIndex<Key>
public subscript(index: TreapIndex<Key>) -> Element {
get {
guard let result = self.get(index.keys[index.keyIndex]) else {
fatalError("Invalid index!")
}
return result
}
mutating set {
let key = index.keys[index.keyIndex]
self = self.set(key: key, val: newValue)
}
}
public subscript(key: Key) -> Element? {
get {
return self.get(key)
}
mutating set {
guard let value = newValue else {
_ = try? self.delete(key: key)
return
}
self = self.set(key: key, val: value)
}
}
public var startIndex: TreapIndex<Key> {
return TreapIndex<Key>(keys: keys, keyIndex: 0)
}
public var endIndex: TreapIndex<Key> {
let keys = self.keys
return TreapIndex<Key>(keys: keys, keyIndex: keys.count)
}
public func index(after i: TreapIndex<Key>) -> TreapIndex<Key> {
return i.successor()
}
fileprivate var keys: [Key] {
var results: [Key] = []
if case let .node(key, _, _, left, right) = self {
results.append(contentsOf: left.keys)
results.append(key)
results.append(contentsOf: right.keys)
}
return results
}
}
public struct TreapIndex<Key: Comparable>: Comparable {
public static func < (lhs: TreapIndex<Key>, rhs: TreapIndex<Key>) -> Bool {
return lhs.keyIndex < rhs.keyIndex
}
fileprivate let keys: [Key]
fileprivate let keyIndex: Int
public func successor() -> TreapIndex {
return TreapIndex(keys: keys, keyIndex: keyIndex + 1)
}
public func predecessor() -> TreapIndex {
return TreapIndex(keys: keys, keyIndex: keyIndex - 1)
}
fileprivate init(keys: [Key] = [], keyIndex: Int = 0) {
self.keys = keys
self.keyIndex = keyIndex
}
}
public func ==<Key: Comparable>(lhs: TreapIndex<Key>, rhs: TreapIndex<Key>) -> Bool {
return lhs.keys == rhs.keys && lhs.keyIndex == rhs.keyIndex
}
| mit | 6750e2bdbb46b1550f77ab164b49821e | 27.459459 | 85 | 0.687243 | 4.113281 | false | false | false | false |
michalciurus/KatanaRouter | Pods/Katana/Katana/Plastic/Size.swift | 1 | 3715 | //
// Size.swift
// Katana
//
// Copyright © 2016 Bending Spoons.
// Distributed under the MIT License.
// See the LICENSE file for more information.
import CoreGraphics
/// `Size` is the scalable counterpart of `CGSize`
public struct Size: Equatable {
/// The width value
public let width: Value
/// The height value
public let height: Value
/// an instance of `Size` where both the width and the height are zero
public static let zero: Size = .scalable(0, 0)
/**
Creates an instance of `Size` where both widht and height are fixed
- parameter width: the value of the width
- parameter height: the value of the height
- returns: an instance of `Size` where both width and height are fixed
*/
public static func fixed(_ width: CGFloat, _ height: CGFloat) -> Size {
return Size(width: .fixed(width), height: .fixed(height))
}
/**
Creates an instance of `Size` where both widht and height are scalable
- parameter width: the value of the width
- parameter height: the value of the height
- returns: an instance of `Size` where both width and height are scalable
*/
public static func scalable(_ width: CGFloat, _ height: CGFloat) -> Size {
return Size(width: .scalable(width), height: .scalable(height))
}
/**
Creates an instance of `Size` with the given value
- parameter width: the width to use
- parameter height: the height to use
- returns: an instance of `Size` with the given value
*/
public init(width: Value, height: Value) {
self.width = width
self.height = height
}
/**
Scales the size using a multiplier
- parameter multiplier: the multiplier to use to scale the size
- returns: an instance of `CGSize` that is the result of the scaling process
*/
public func scale(by multiplier: CGFloat) -> CGSize {
return CGSize(
width: self.width.scale(by: multiplier),
height: self.height.scale(by: multiplier)
)
}
/**
Implements the multiplication for the `Size` instances
- parameter lhs: the `Size` instance
- parameter rhs: the the mutliplier to apply
- returns: an instance of `Size` where the values are multiplied by `rhs`
- warning: this method is different from `scale(by:)` since it scales both
scalable and fixed values, whereas `scale(by:)` scales only the scalable
values
*/
public static func * (lhs: Size, rhs: CGFloat) -> Size {
return Size(width: lhs.width * rhs, height: lhs.height * rhs)
}
/**
Implements the addition for the `Size` instances
- parameter lhs: the first instance
- parameter rhs: the second instance
- returns: an instance of `Size` where the width and the height are the sum of the insets of
the two operators
*/
public static func + (lhs: Size, rhs: Size) -> Size {
return Size(width: lhs.width + rhs.width, height: lhs.height + rhs.height)
}
/**
Implements the division for the `Size` instances
- parameter lhs: the first instance
- parameter rhs: the value that will be used in the division
- returns: an instance of `Size` where the insets are divided by `rhs`
*/
public static func / (lhs: Size, rhs: CGFloat) -> Size {
return Size(width: lhs.width / rhs, height: lhs.height / rhs)
}
/**
Imlementation of the `Equatable` protocol.
- parameter lhs: the first instance
- parameter rhs: the second instance
- returns: true if the two instances are equal, which means that both width and height are equal
*/
public static func == (lhs: Size, rhs: Size) -> Bool {
return lhs.width == rhs.width && lhs.height == rhs.height
}
}
| mit | add7076007de8d94776b2984b1f8ce3b | 29.694215 | 101 | 0.66182 | 4.085809 | false | false | false | false |
maple1994/RxZhiHuDaily | RxZhiHuDaily/View/BannerView.swift | 1 | 6107 | //
// BannerView.swift
// MPZhiHuDaily
//
// Created by Maple on 2017/8/20.
// Copyright © 2017年 Maple. All rights reserved.
//
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
import RxCocoa
import Kingfisher
/// 轮播图View
class BannerView: UIView {
fileprivate let itemH: CGFloat = 200
var topStories: [MPStoryModel]? {
didSet {
if let arr = topStories {
if arr.count > 1 {
imgUrlArr.value = [arr.last!] + arr + [arr.first!]
}else {
imgUrlArr.value = arr
}
}
}
}
fileprivate let imgUrlArr = Variable([MPStoryModel]())
let dispose = DisposeBag()
// 监听tableView的滚动
var offY: Variable<CGFloat> = Variable(0.0)
var selectedIndex: Variable<Int> = Variable(0)
fileprivate var index: Int = 0
init() {
super.init(frame: CGRect.zero)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("")
}
fileprivate func setupUI() {
addSubview(collectionView)
addSubview(pageControl)
collectionView.snp.makeConstraints { (make) in
make.left.right.top.bottom.equalToSuperview()
}
pageControl.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.bottom.equalToSuperview().offset(0)
}
let ID = "BannerCellID"
collectionView.register(BannerCell.self, forCellWithReuseIdentifier: ID)
// 给collectionView的cell赋值
imgUrlArr
.asObservable()
.bindTo(collectionView.rx.items(cellIdentifier: ID, cellType: BannerCell.self)) {
row, model, cell in
cell.model = model
}.addDisposableTo(dispose)
// 设置pageControl的数量
imgUrlArr
.asObservable()
.subscribe (onNext: { models in
self.pageControl.numberOfPages = models.count - 2
self.collectionView.contentOffset.x = screenW
}).addDisposableTo(dispose)
// 监听滚动,设置图片的拉伸效果
offY
.asObservable()
.subscribe(onNext: {
offY in
self.collectionView.visibleCells.forEach({ (cell) in
let myCell = cell as! BannerCell
myCell.imgView.frame.origin.y = offY
myCell.imgView.frame.size.height = 200 - offY
})
}).addDisposableTo(dispose)
collectionView.rx.setDelegate(self).addDisposableTo(dispose)
collectionView.rx.itemSelected
.subscribe(onNext: { ip in
let index = (ip.row - 1) >= 0 ? ip.row - 1 : 0
self.selectedIndex.value = index
})
.addDisposableTo(dispose)
}
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: screenW, height: self.itemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let view = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
view.isPagingEnabled = true
view.backgroundColor = UIColor.white
view.showsHorizontalScrollIndicator = false
view.clipsToBounds = false
view.scrollsToTop = false
return view
}()
fileprivate lazy var pageControl: UIPageControl = {
let page = UIPageControl()
return page
}()
}
extension BannerView: UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 滚动最后一个图片时,回到第一张图片
if scrollView.contentOffset.x == CGFloat(imgUrlArr.value.count - 1) * screenW {
scrollView.contentOffset.x = screenW
}else if scrollView.contentOffset.x == 0 {
// 滚动到第一张图片时,回到最后一张图片
scrollView.contentOffset.x = CGFloat(imgUrlArr.value.count - 2) * screenW
}
let index = Int(scrollView.contentOffset.x / screenW) - 1
self.pageControl.currentPage = index
}
}
class BannerCell: UICollectionViewCell {
var model: MPStoryModel? {
didSet {
if let path = model?.image {
imgView.kf.setImage(with: URL.init(string: path))
}
titleLabel.text = model?.title
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("")
}
fileprivate func setupUI() {
contentView.addSubview(imgView)
contentView.addSubview(maskImageView)
contentView.addSubview(titleLabel)
imgView.snp.makeConstraints { (make) in
make.top.left.right.bottom.equalToSuperview()
}
titleLabel.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(10)
make.right.equalToSuperview().offset(-10)
make.bottom.equalToSuperview().offset(-20)
}
maskImageView.snp.makeConstraints { (make) in
make.leading.trailing.bottom.equalToSuperview()
make.height.equalTo(100)
}
}
lazy var imgView: UIImageView = {
let iv = UIImageView()
iv.contentMode = .scaleAspectFill
iv.clipsToBounds = true
return iv
}()
fileprivate lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 20)
label.textColor = UIColor.white
label.numberOfLines = 2
return label
}()
fileprivate lazy var maskImageView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "Home_Image_Mask")
return iv
}()
}
| mit | 4bbebe8e8e26ed4723927c2848a32255 | 29.01005 | 93 | 0.576691 | 4.931462 | false | false | false | false |
gmunhoz/CollieGallery | Pod/Classes/CollieGalleryAppearance.swift | 1 | 1820 | //
// CollieGalleryAppearance.swift
//
// Copyright (c) 2016 Guilherme Munhoz <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/// Class used to customize the appearance
open class CollieGalleryAppearance: NSObject {
/// Shared appearance between all new instances of the gallery
open static var sharedAppearance = CollieGalleryAppearance()
/// The background color of the gallery
var backgroundColor = UIColor.black
/// The color of current progress in the progress bar
var progressBarColor = UIColor.white
/// The color of the activity indicator
var activityIndicatorColor = UIColor.white
/// The color of the close button icon
var closeButtonColor = UIColor.white
}
| mit | 4148daab738a3274dd111b38e1b0853c | 41.325581 | 81 | 0.740659 | 4.55 | false | false | false | false |
dinhchitrung/SAParallaxViewControllerSwift | SAParallaxViewControllerSwift/SAParallaxViewLayout.swift | 2 | 1242 | //
// SAParallaxViewLayout.swift
// SAParallaxViewControllerSwift
//
// Created by 鈴木大貴 on 2015/01/30.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
public class SAParallaxViewLayout: UICollectionViewFlowLayout {
private let kDefaultHeight: CGFloat = 220.0
public override init() {
super.init()
initialize()
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
minimumInteritemSpacing = 0.0
minimumLineSpacing = 0.0
sectionInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)
let width = UIScreen.mainScreen().bounds.size.width
let height = width / 320.0 * kDefaultHeight
itemSize = CGSize(width: width, height: height)
}
public override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
return super.layoutAttributesForElementsInRect(rect)
}
public override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
return super.layoutAttributesForItemAtIndexPath(indexPath)
}
}
| mit | a4cca1d8e490c7710a6880718825b273 | 28.853659 | 122 | 0.673203 | 4.8 | false | false | false | false |
zisko/swift | test/SILOptimizer/exclusivity_static_diagnostics.swift | 1 | 21085 | // RUN: %target-swift-frontend -enforce-exclusivity=checked -swift-version 4 -emit-sil -primary-file %s -o /dev/null -verify
import Swift
func takesTwoInouts<T>(_ p1: inout T, _ p2: inout T) { }
func simpleInoutDiagnostic() {
var i = 7
// FIXME: This diagnostic should be removed if static enforcement is
// turned on by default.
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
takesTwoInouts(&i, &i)
}
func inoutOnInoutParameter(p: inout Int) {
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'p', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
takesTwoInouts(&p, &p)
}
func swapNoSuppression(_ i: Int, _ j: Int) {
var a: [Int] = [1, 2, 3]
// expected-error@+2{{overlapping accesses to 'a', but modification requires exclusive access; consider calling MutableCollection.swapAt(_:_:)}}
// expected-note@+1{{conflicting access is here}}
swap(&a[i], &a[j])
}
class SomeClass { }
struct StructWithMutatingMethodThatTakesSelfInout {
var f = SomeClass()
mutating func mutate(_ other: inout StructWithMutatingMethodThatTakesSelfInout) { }
mutating func mutate(_ other: inout SomeClass) { }
mutating func callMutatingMethodThatTakesSelfInout() {
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'self', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
mutate(&self)
}
mutating func callMutatingMethodThatTakesSelfStoredPropInout() {
// expected-error@+2{{overlapping accesses to 'self', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
mutate(&self.f)
}
}
var globalStruct1 = StructWithMutatingMethodThatTakesSelfInout()
func callMutatingMethodThatTakesGlobalStoredPropInout() {
// expected-error@+2{{overlapping accesses to 'globalStruct1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
globalStruct1.mutate(&globalStruct1.f)
}
class ClassWithFinalStoredProp {
final var s1: StructWithMutatingMethodThatTakesSelfInout = StructWithMutatingMethodThatTakesSelfInout()
final var s2: StructWithMutatingMethodThatTakesSelfInout = StructWithMutatingMethodThatTakesSelfInout()
final var i = 7
func callMutatingMethodThatTakesClassStoredPropInout() {
s1.mutate(&s2.f) // no-warning
// expected-error@+2{{overlapping accesses to 's1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
s1.mutate(&s1.f)
let local1 = self
// expected-error@+2{{overlapping accesses to 's1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
local1.s1.mutate(&local1.s1.f)
}
}
func violationWithGenericType<T>(_ p: T) {
var local = p
// expected-error@+4{{inout arguments are not allowed to alias each other}}
// expected-note@+3{{previous aliasing argument}}
// expected-error@+2{{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@+1{{conflicting access is here}}
takesTwoInouts(&local, &local)
}
// Helper.
struct StructWithTwoStoredProp {
var f1: Int = 7
var f2: Int = 8
}
// Take an unsafe pointer to a stored property while accessing another stored property.
func violationWithUnsafePointer(_ s: inout StructWithTwoStoredProp) {
withUnsafePointer(to: &s.f1) { (ptr) in
// expected-warning@-1 {{overlapping accesses to 's.f1', but modification requires exclusive access; consider copying to a local variable}}
_ = s.f1
// expected-note@-1 {{conflicting access is here}}
}
// Statically treat accesses to separate stored properties in structs as
// accessing separate storage.
withUnsafePointer(to: &s.f1) { (ptr) in // no-error
_ = s.f2
}
}
// Tests for Fix-Its to replace swap(&collection[a], &collection[b]) with
// collection.swapAt(a, b)
struct StructWithField {
var f = 12
}
struct StructWithFixits {
var arrayProp: [Int] = [1, 2, 3]
var dictionaryProp: [Int : Int] = [0 : 10, 1 : 11]
mutating
func shouldHaveFixIts<T>(_ i: Int, _ j: Int, _ param: T, _ paramIndex: T.Index) where T : MutableCollection {
var array1 = [1, 2, 3]
// expected-error@+2{{overlapping accesses}}{{5-41=array1.swapAt(i + 5, j - 2)}}
// expected-note@+1{{conflicting access is here}}
swap(&array1[i + 5], &array1[j - 2])
// expected-error@+2{{overlapping accesses}}{{5-49=self.arrayProp.swapAt(i, j)}}
// expected-note@+1{{conflicting access is here}}
swap(&self.arrayProp[i], &self.arrayProp[j])
var localOfGenericType = param
// expected-error@+2{{overlapping accesses}}{{5-75=localOfGenericType.swapAt(paramIndex, paramIndex)}}
// expected-note@+1{{conflicting access is here}}
swap(&localOfGenericType[paramIndex], &localOfGenericType[paramIndex])
// expected-error@+2{{overlapping accesses}}{{5-39=array1.swapAt(i, j)}}
// expected-note@+1{{conflicting access is here}}
Swift.swap(&array1[i], &array1[j]) // no-crash
}
mutating
func shouldHaveNoFixIts(_ i: Int, _ j: Int) {
var s = StructWithField()
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
swap(&s.f, &s.f)
var array1 = [1, 2, 3]
var array2 = [1, 2, 3]
// Swapping between different arrays should cannot have the
// Fix-It.
swap(&array1[i], &array2[j]) // no-warning no-fixit
swap(&array1[i], &self.arrayProp[j]) // no-warning no-fixit
// Dictionaries aren't MutableCollections so don't support swapAt().
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
swap(&dictionaryProp[i], &dictionaryProp[j])
// We could safely Fix-It this but don't now because the left and
// right bases are not textually identical.
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
swap(&self.arrayProp[i], &arrayProp[j])
// We could safely Fix-It this but we're not that heroic.
// We don't suppress when swap() is used as a value
let mySwap: (inout Int, inout Int) -> () = swap
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
mySwap(&array1[i], &array1[j])
func myOtherSwap<T>(_ a: inout T, _ b: inout T) {
swap(&a, &b) // no-warning
}
// expected-error@+2{{overlapping accesses}}{{none}}
// expected-note@+1{{conflicting access is here}}
mySwap(&array1[i], &array1[j])
}
}
func takesInoutAndNoEscapeClosure<T>(_ p: inout T, _ c: () -> ()) { }
func callsTakesInoutAndNoEscapeClosure() {
var local = 5
takesInoutAndNoEscapeClosure(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
local = 8 // expected-note {{conflicting access is here}}
}
}
func callsTakesInoutAndNoEscapeClosureWithRead() {
var local = 5
takesInoutAndNoEscapeClosure(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
_ = local // expected-note {{conflicting access is here}}
}
}
func takesInoutAndNoEscapeClosureThatThrows<T>(_ p: inout T, _ c: () throws -> ()) { }
func callsTakesInoutAndNoEscapeClosureThatThrowsWithNonThrowingClosure() {
var local = 5
takesInoutAndNoEscapeClosureThatThrows(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
local = 8 // expected-note {{conflicting access is here}}
}
}
func takesInoutAndNoEscapeClosureAndThrows<T>(_ p: inout T, _ c: () -> ()) throws { }
func callsTakesInoutAndNoEscapeClosureAndThrows() {
var local = 5
try! takesInoutAndNoEscapeClosureAndThrows(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
local = 8 // expected-note {{conflicting access is here}}
}
}
func takesTwoNoEscapeClosures(_ c1: () -> (), _ c2: () -> ()) { }
func callsTakesTwoNoEscapeClosures() {
var local = 7
takesTwoNoEscapeClosures({local = 8}, {local = 9}) // no-error
_ = local
}
func takesInoutAndEscapingClosure<T>(_ p: inout T, _ c: @escaping () -> ()) { }
func callsTakesInoutAndEscapingClosure() {
var local = 5
takesInoutAndEscapingClosure(&local) { // no-error
local = 8
}
}
func callsClosureLiteralImmediately() {
var i = 7;
// Closure literals that are called immediately are considered nonescaping
_ = ({ (p: inout Int) in
i
// expected-note@-1 {{conflicting access is here}}
}
)(&i)
// expected-error@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
}
func callsStoredClosureLiteral() {
var i = 7;
let c = { (p: inout Int) in i}
// Closure literals that are stored and later called are treated as escaping
// We don't expect a static exclusivity diagnostic here, but the issue
// will be caught at run time
_ = c(&i) // no-error
}
// Calling this with an inout expression for the first parameter performs a
// read access for the duration of a call
func takesUnsafePointerAndNoEscapeClosure<T>(_ p: UnsafePointer<T>, _ c: () -> ()) { }
// Calling this with an inout expression for the first parameter performs a
// modify access for the duration of a call
func takesUnsafeMutablePointerAndNoEscapeClosure<T>(_ p: UnsafeMutablePointer<T>, _ c: () -> ()) { }
func callsTakesUnsafePointerAndNoEscapeClosure() {
var local = 1
takesUnsafePointerAndNoEscapeClosure(&local) { // expected-note {{conflicting access is here}}
local = 2 // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
}
}
func callsTakesUnsafePointerAndNoEscapeClosureThatReads() {
var local = 1
// Overlapping reads
takesUnsafePointerAndNoEscapeClosure(&local) {
_ = local // no-error
}
}
func callsTakesUnsafeMutablePointerAndNoEscapeClosureThatReads() {
var local = 1
// Overlapping modify and read
takesUnsafeMutablePointerAndNoEscapeClosure(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
_ = local // expected-note {{conflicting access is here}}
}
}
func takesThrowingAutoClosureReturningGeneric<T: Equatable>(_ : @autoclosure () throws -> T) { }
func takesInoutAndClosure<T>(_: inout T, _ : () -> ()) { }
func callsTakesThrowingAutoClosureReturningGeneric() {
var i = 0
takesInoutAndClosure(&i) { // expected-error {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
takesThrowingAutoClosureReturningGeneric(i) // expected-note {{conflicting access is here}}
}
}
struct StructWithMutatingMethodThatTakesAutoclosure {
var f = 2
mutating func takesAutoclosure(_ p: @autoclosure () throws -> ()) rethrows { }
}
func conflictOnSubPathInNoEscapeAutoclosure() {
var s = StructWithMutatingMethodThatTakesAutoclosure()
s.takesAutoclosure(s.f = 2)
// expected-error@-1 {{overlapping accesses to 's', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2 {{conflicting access is here}}
}
func conflictOnWholeInNoEscapeAutoclosure() {
var s = StructWithMutatingMethodThatTakesAutoclosure()
takesInoutAndNoEscapeClosure(&s.f) {
// expected-error@-1 {{overlapping accesses to 's.f', but modification requires exclusive access; consider copying to a local variable}}
s = StructWithMutatingMethodThatTakesAutoclosure()
// expected-note@-1 {{conflicting access is here}}
}
}
struct ParameterizedStruct<T> {
mutating func takesFunctionWithGenericReturnType(_ f: (Int) -> T) {}
}
func testReabstractionThunk(p1: inout ParameterizedStruct<Int>,
p2: inout ParameterizedStruct<Int>) {
// Since takesFunctionWithGenericReturnType() takes a closure with a generic
// return type it expects the value to be returned @out. But the closure
// here has an 'Int' return type, so the compiler uses a reabstraction thunk
// to pass the closure to the method.
// This tests that we still detect access violations for closures passed
// using a reabstraction thunk.
p1.takesFunctionWithGenericReturnType { _ in
// expected-warning@-1 {{overlapping accesses to 'p1', but modification requires exclusive access; consider copying to a local variable}}
p2 = p1
// expected-note@-1 {{conflicting access is here}}
return 3
}
}
func takesNoEscapeBlockClosure
(
_ p: inout Int, _ c: @convention(block) () -> ()
) { }
func takesEscapingBlockClosure
(
_ p: inout Int, _ c: @escaping @convention(block) () -> ()
) { }
func testCallNoEscapeBlockClosure() {
var i = 7
takesNoEscapeBlockClosure(&i) {
// expected-warning@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
i = 7
// expected-note@-1 {{conflicting access is here}}
}
}
func testCallEscapingBlockClosure() {
var i = 7
takesEscapingBlockClosure(&i) { // no-warning
i = 7
}
}
func testCallNonEscapingWithEscapedBlock() {
var i = 7
let someBlock : @convention(block) () -> () = {
i = 8
}
takesNoEscapeBlockClosure(&i, someBlock) // no-warning
}
func takesInoutAndClosureWithGenericArg<T>(_ p: inout Int, _ c: (T) -> Int) { }
func callsTakesInoutAndClosureWithGenericArg() {
var i = 7
takesInoutAndClosureWithGenericArg(&i) { (p: Int) in
// expected-warning@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
return i + p
// expected-note@-1 {{conflicting access is here}}
}
}
func takesInoutAndClosureTakingNonOptional(_ p: inout Int, _ c: (Int) -> ()) { }
func callsTakesInoutAndClosureTakingNonOptionalWithClosureTakingOptional() {
var i = 7
// Test for the thunk converting an (Int?) -> () to an (Int) -> ()
takesInoutAndClosureTakingNonOptional(&i) { (p: Int?) in
// expected-warning@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}}
i = 8
// expected-note@-1 {{conflicting access is here}}
}
}
func inoutSeparateStructStoredProperties() {
var s = StructWithTwoStoredProp()
takesTwoInouts(&s.f1, &s.f2) // no-error
}
func inoutSameStoredProperty() {
var s = StructWithTwoStoredProp()
takesTwoInouts(&s.f1, &s.f1)
// expected-error@-1{{overlapping accesses to 's.f1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
func inoutSeparateTupleElements() {
var t = (1, 4)
takesTwoInouts(&t.0, &t.1) // no-error
}
func inoutSameTupleElement() {
var t = (1, 4)
takesTwoInouts(&t.0, &t.0)
// expected-error@-1{{overlapping accesses to 't.0', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
func inoutSameTupleNamedElement() {
var t = (name1: 1, name2: 4)
takesTwoInouts(&t.name2, &t.name2)
// expected-error@-1{{overlapping accesses to 't.name2', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
func inoutSamePropertyInSameTuple() {
var t = (name1: 1, name2: StructWithTwoStoredProp())
takesTwoInouts(&t.name2.f1, &t.name2.f1)
// expected-error@-1{{overlapping accesses to 't.name2.f1', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
// Noescape closures and separate stored structs
func callsTakesInoutAndNoEscapeClosureNoWarningOnSeparateStored() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local.f1) {
local.f2 = 8 // no-error
}
}
func callsTakesInoutAndNoEscapeClosureWarningOnSameStoredProp() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}}
local.f1 = 8 // expected-note {{conflicting access is here}}
}
}
func callsTakesInoutAndNoEscapeClosureWarningOnAggregateAndStoredProp() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
local.f1 = 8 // expected-note {{conflicting access is here}}
}
}
func callsTakesInoutAndNoEscapeClosureWarningOnStoredPropAndAggregate() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}}
local = StructWithTwoStoredProp() // expected-note {{conflicting access is here}}
}
}
func callsTakesInoutAndNoEscapeClosureWarningOnStoredPropAndBothPropertyAndAggregate() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}}
local.f1 = 8
// We want the diagnostic on the access for the aggregate and not the projection.
local = StructWithTwoStoredProp() // expected-note {{conflicting access is here}}
}
}
func callsTakesInoutAndNoEscapeClosureWarningOnStoredPropAndBothAggregateAndProperty() {
var local = StructWithTwoStoredProp()
takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}}
// We want the diagnostic on the access for the aggregate and not the projection.
local = StructWithTwoStoredProp() // expected-note {{conflicting access is here}}
local.f1 = 8
}
}
struct MyStruct<T> {
var prop = 7
mutating func inoutBoundGenericStruct() {
takesTwoInouts(&prop, &prop)
// expected-error@-1{{overlapping accesses to 'self.prop', but modification requires exclusive access; consider copying to a local variable}}
// expected-note@-2{{conflicting access is here}}
}
}
func testForLoopCausesReadAccess() {
var a: [Int] = [1]
takesInoutAndNoEscapeClosure(&a) { // expected-error {{overlapping accesses to 'a', but modification requires exclusive access; consider copying to a local variable}}
for _ in a { // expected-note {{conflicting access is here}}
}
}
}
func testKeyPathStructField() {
let getF = \StructWithField.f
var local = StructWithField()
takesInoutAndNoEscapeClosure(&local[keyPath: getF]) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}}
local.f = 17 // expected-note {{conflicting access is here}}
}
}
func testKeyPathWithClassFinalStoredProperty() {
let getI = \ClassWithFinalStoredProp.i
let local = ClassWithFinalStoredProp()
// Ideally we would diagnose statically here, but it is not required by the
// model.
takesTwoInouts(&local[keyPath: getI], &local[keyPath: getI])
}
func takesInoutAndOptionalClosure(_: inout Int, _ f: (()->())?) {
f!()
}
// An optional closure is not considered @noescape:
// This violation will only be caught dynamically.
//
// apply %takesInoutAndOptionalClosure(%closure)
// : $@convention(thin) (@inout Int, @owned Optional<@callee_guaranteed () -> ()>) -> ()
func testOptionalClosure() {
var x = 0
takesInoutAndOptionalClosure(&x) { x += 1 }
}
func takesInoutAndOptionalBlock(_: inout Int, _ f: (@convention(block) ()->())?) {
f!()
}
// An optional block is not be considered @noescape.
// This violation will only be caught dynamically.
func testOptionalBlock() {
var x = 0
takesInoutAndOptionalBlock(&x) { x += 1 }
}
| apache-2.0 | 623fdddab415ee3788fca96fa1b95881 | 37.059567 | 191 | 0.714774 | 4.238191 | false | false | false | false |
mrdepth/EVEUniverse | Legacy/Neocom/Neocom/NCAccountsViewController.swift | 2 | 10101 | //
// NCAccountsViewController.swift
// Neocom
//
// Created by Artem Shimanski on 01.05.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import CoreData
import EVEAPI
import Futures
class NCAccountsViewController: NCTreeViewController {
@IBOutlet var panGestureRecognizer: UIPanGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = editButtonItem
tableView.register([Prototype.NCActionTableViewCell.default,
Prototype.NCAccountTableViewCell.default,
Prototype.NCHeaderTableViewCell.default,
Prototype.NCHeaderTableViewCell.empty,
Prototype.NCDefaultTableViewCell.noImage])
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
navigationController?.transitioningDelegate = self
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
guard let context = NCStorage.sharedStorage?.viewContext else {return}
if context.hasChanges {
try? context.save()
}
}
@IBAction func onDelete(_ sender: UIBarButtonItem) {
guard let selected = treeController?.selectedNodes().compactMap ({$0 as? NCAccountRow}) else {return}
guard !selected.isEmpty else {return}
let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: String(format: NSLocalizedString("Delete %d Accounts", comment: ""), selected.count), style: .destructive) { [weak self] _ in
selected.forEach {
$0.object.managedObjectContext?.delete($0.object)
}
if let context = selected.first?.object.managedObjectContext, context.hasChanges {
try? context.save()
}
self?.updateTitle()
})
controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil))
present(controller, animated: true, completion: nil)
controller.popoverPresentationController?.barButtonItem = sender
}
@IBAction func onMoveTo(_ sender: Any) {
guard let selected = treeController?.selectedNodes().compactMap ({$0 as? NCAccountRow}) else {return}
guard !selected.isEmpty else {return}
Router.Account.AccountsFolderPicker { [weak self] (controller, folder) in
controller.dismiss(animated: true, completion: nil)
selected.forEach {
$0.object.folder = folder
}
let account: NCAccount?
if let folder = folder {
account = folder.managedObjectContext?.fetch("Account", limit: 1, sortedBy: [NSSortDescriptor(key: "order", ascending: false)], where: "folder == %@", folder)
}
else {
account = selected.first?.object.managedObjectContext?.fetch("Account", limit: 1, sortedBy: [NSSortDescriptor(key: "order", ascending: false)], where: "folder == nil")
}
var order = account != nil ? account!.order : 0
selected.forEach {
$0.object.order = order
order += 1
}
if let context = selected.first?.object.managedObjectContext, context.hasChanges {
try? context.save()
}
self?.updateTitle()
}.perform(source: self, sender: sender)
}
@IBAction func onFolders(_ sender: Any) {
guard let selected = treeController?.selectedNodes().compactMap ({$0 as? NCAccountRow}) else {return}
if selected.isEmpty {
Router.Account.Folders().perform(source: self, sender: sender)
}
else {
Router.Account.AccountsFolderPicker { [weak self] (controller, folder) in
controller.dismiss(animated: true, completion: nil)
selected.forEach {
$0.object.folder = folder
}
let account: NCAccount?
if let folder = folder {
account = folder.managedObjectContext?.fetch("Account", limit: 1, sortedBy: [NSSortDescriptor(key: "order", ascending: false)], where: "folder == %@", folder)
}
else {
account = selected.first?.object.managedObjectContext?.fetch("Account", limit: 1, sortedBy: [NSSortDescriptor(key: "order", ascending: false)], where: "folder == nil")
}
var order = account != nil ? account!.order : 0
selected.forEach {
$0.object.order = order
order += 1
}
if let context = selected.first?.object.managedObjectContext, context.hasChanges {
try? context.save()
}
self?.updateTitle()
}.perform(source: self, sender: sender)
}
}
@IBAction func onClose(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
if !editing {
guard let context = NCStorage.sharedStorage?.viewContext else {return}
if context.hasChanges {
try? context.save()
}
}
navigationController?.setToolbarHidden(!editing, animated: true)
updateTitle()
}
// override func scrollViewDidScroll(_ scrollView: UIScrollView) {
// guard !isEditing else {return}
//
// let bottom = max(scrollView.contentSize.height - scrollView.bounds.size.height, 0)
// let y = scrollView.contentOffset.y - bottom
// if (y > 40 && transitionCoordinator == nil && scrollView.isTracking) {
// self.isInteractive = true
// dismiss(animated: true, completion: nil)
// self.isInteractive = false
// }
// }
private var cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy
override func content() -> Future<TreeNode?> {
guard let context = NCStorage.sharedStorage?.viewContext else {return .init(nil)}
let row = NCActionRow(title: NSLocalizedString("SIGN IN", comment: ""))
let space = DefaultTreeSection(prototype: Prototype.NCHeaderTableViewCell.empty)
return .init(RootNode([NCAccountsNode<NCAccountRow>(context: context, cachePolicy: cachePolicy), space, row], collapseIdentifier: "NCAccountsViewController"))
}
override func load(cachePolicy: URLRequest.CachePolicy) -> Future<[NCCacheRecord]> {
self.cachePolicy = cachePolicy
return .init([])
}
// MARK: TreeControllerDelegate
override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) {
super.treeController(treeController, didSelectCellWithNode: node)
if isEditing {
if !(node is NCAccountRow) {
treeController.deselectCell(for: node, animated: true)
}
updateTitle()
}
else {
treeController.deselectCell(for: node, animated: true)
if node is NCActionRow {
ESI.performAuthorization(from: self)
// if #available(iOS 10.0, *) {
// UIApplication.shared.open(url, options: [:], completionHandler: nil)
// } else {
// UIApplication.shared.openURL(url)
// }
}
else if let node = node as? NCAccountRow {
NCAccount.current = node.object
dismiss(animated: true, completion: nil)
}
}
}
override func treeController(_ treeController: TreeController, didDeselectCellWithNode node: TreeNode) {
super.treeController(treeController, didDeselectCellWithNode: node)
if isEditing {
updateTitle()
}
}
func treeController(_ treeController: TreeController, didCollapseCellWithNode node: TreeNode) {
updateTitle()
}
func treeController(_ treeController: TreeController, didExpandCellWithNode node: TreeNode) {
updateTitle()
}
func treeController(_ treeController: TreeController, editActionsForNode node: TreeNode) -> [UITableViewRowAction]? {
guard let node = node as? NCAccountRow else {return nil}
return [UITableViewRowAction(style: .destructive, title: NSLocalizedString("Delete", comment: ""), handler: { [weak self] (_,_) in
let account = node.object
account.managedObjectContext?.delete(account)
try? account.managedObjectContext?.save()
self?.updateTitle()
})]
}
func treeController(_ treeController: TreeController, didMoveNode node: TreeNode, at: Int, to: Int) {
var order: Int32 = 0
(node.parent?.children as? [NCAccountRow])?.forEach {
if $0.object.order != order {
$0.object.order = order
}
order += 1
}
}
@IBAction func onPan(_ sender: UIPanGestureRecognizer) {
if sender.state == .began && sender.translation(in: view).y < 0 {
dismiss(animated: true, completion: nil)
}
}
// MARK: UIViewControllerTransitioningDelegate
private var isInteractive: Bool = false
//MARK: - Private
private func updateTitle() {
if isEditing {
let n = treeController?.selectedNodes().count ?? 0
title = n > 0 ? String(format: NSLocalizedString("Selected %d Accounts", comment: ""), n) : NSLocalizedString("Accounts", comment: "")
// toolbarItems?.first?.isEnabled = n > 0
// toolbarItems?.last?.isEnabled = n > 0
toolbarItems?[0].title = n > 0 ? NSLocalizedString("Move To", comment: "") : NSLocalizedString("Folders", comment: "")
}
else {
title = NSLocalizedString("Accounts", comment: "")
}
}
}
extension NCAccountsViewController: UIViewControllerTransitioningDelegate {
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return NCSlideDownAnimationController()
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
let isInteractive = panGestureRecognizer.state == .changed || panGestureRecognizer.state == .began
return isInteractive ? NCSlideDownInteractiveTransition(panGestureRecognizer: panGestureRecognizer) : nil
}
}
extension NCAccountsViewController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard !isEditing else {return false}
guard let t = (gestureRecognizer as? UIPanGestureRecognizer)?.translation(in: view) else {return true}
if #available(iOS 11.0, *) {
if tableView.bounds.maxY < tableView.contentSize.height + tableView.adjustedContentInset.bottom {
return false
}
} else {
if tableView.bounds.maxY < tableView.contentSize.height + tableView.contentInset.bottom {
return false
}
}
return t.y < 0
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| lgpl-2.1 | 377e148ae3cc0c8451c1e757df6bd246 | 32.554817 | 172 | 0.714455 | 4.173554 | false | false | false | false |
apple/swift-format | Tests/SwiftFormatRulesTests/FileScopedDeclarationPrivacyTests.swift | 1 | 8102 | import SwiftFormatConfiguration
import SwiftFormatCore
import SwiftFormatRules
import SwiftSyntax
private typealias TestConfiguration = (
original: String,
desired: FileScopedDeclarationPrivacyConfiguration.AccessLevel,
expected: String
)
/// Test configurations for file-scoped declarations, which should be changed if the access level
/// does not match the desired level in the formatter configuration.
private let changingTestConfigurations: [TestConfiguration] = [
(original: "private", desired: .fileprivate, expected: "fileprivate"),
(original: "private", desired: .private, expected: "private"),
(original: "fileprivate", desired: .fileprivate, expected: "fileprivate"),
(original: "fileprivate", desired: .private, expected: "private"),
]
/// Test configurations for declarations that should not have their access level changed; extensions
/// and nested declarations (i.e., not at file scope).
private let unchangingTestConfigurations: [TestConfiguration] = [
(original: "private", desired: .fileprivate, expected: "private"),
(original: "private", desired: .private, expected: "private"),
(original: "fileprivate", desired: .fileprivate, expected: "fileprivate"),
(original: "fileprivate", desired: .private, expected: "fileprivate"),
]
final class FileScopedDeclarationPrivacyTests: LintOrFormatRuleTestCase {
func testFileScopeDecls() {
runWithMultipleConfigurations(
source: """
$access$ class Foo {}
$access$ struct Foo {}
$access$ enum Foo {}
$access$ protocol Foo {}
$access$ typealias Foo = Bar
$access$ func foo() {}
$access$ var foo: Bar
""",
testConfigurations: changingTestConfigurations
) { assertDiagnosticWasEmittedOrNot in
assertDiagnosticWasEmittedOrNot(1, 1)
assertDiagnosticWasEmittedOrNot(2, 1)
assertDiagnosticWasEmittedOrNot(3, 1)
assertDiagnosticWasEmittedOrNot(4, 1)
assertDiagnosticWasEmittedOrNot(5, 1)
assertDiagnosticWasEmittedOrNot(6, 1)
assertDiagnosticWasEmittedOrNot(7, 1)
}
}
func testFileScopeExtensionsAreNotChanged() {
runWithMultipleConfigurations(
source: """
$access$ extension Foo {}
""",
testConfigurations: unchangingTestConfigurations
) { assertDiagnosticWasEmittedOrNot in
assertDiagnosticWasEmittedOrNot(1, 1)
}
}
func testNonFileScopeDeclsAreNotChanged() {
runWithMultipleConfigurations(
source: """
enum Namespace {
$access$ class Foo {}
$access$ struct Foo {}
$access$ enum Foo {}
$access$ typealias Foo = Bar
$access$ func foo() {}
$access$ var foo: Bar
}
""",
testConfigurations: unchangingTestConfigurations
) { assertDiagnosticWasEmittedOrNot in
assertDiagnosticWasEmittedOrNot(1, 1)
assertDiagnosticWasEmittedOrNot(2, 1)
assertDiagnosticWasEmittedOrNot(3, 1)
assertDiagnosticWasEmittedOrNot(4, 1)
assertDiagnosticWasEmittedOrNot(5, 1)
assertDiagnosticWasEmittedOrNot(6, 1)
assertDiagnosticWasEmittedOrNot(7, 1)
}
}
func testFileScopeDeclsInsideConditionals() {
runWithMultipleConfigurations(
source: """
#if FOO
$access$ class Foo {}
$access$ struct Foo {}
$access$ enum Foo {}
$access$ protocol Foo {}
$access$ typealias Foo = Bar
$access$ func foo() {}
$access$ var foo: Bar
#elseif BAR
$access$ class Foo {}
$access$ struct Foo {}
$access$ enum Foo {}
$access$ protocol Foo {}
$access$ typealias Foo = Bar
$access$ func foo() {}
$access$ var foo: Bar
#else
$access$ class Foo {}
$access$ struct Foo {}
$access$ enum Foo {}
$access$ protocol Foo {}
$access$ typealias Foo = Bar
$access$ func foo() {}
$access$ var foo: Bar
#endif
""",
testConfigurations: changingTestConfigurations
) { assertDiagnosticWasEmittedOrNot in
assertDiagnosticWasEmittedOrNot(2, 3)
assertDiagnosticWasEmittedOrNot(3, 3)
assertDiagnosticWasEmittedOrNot(4, 3)
assertDiagnosticWasEmittedOrNot(5, 3)
assertDiagnosticWasEmittedOrNot(6, 3)
assertDiagnosticWasEmittedOrNot(7, 3)
assertDiagnosticWasEmittedOrNot(8, 3)
assertDiagnosticWasEmittedOrNot(10, 3)
assertDiagnosticWasEmittedOrNot(11, 3)
assertDiagnosticWasEmittedOrNot(12, 3)
assertDiagnosticWasEmittedOrNot(13, 3)
assertDiagnosticWasEmittedOrNot(14, 3)
assertDiagnosticWasEmittedOrNot(15, 3)
assertDiagnosticWasEmittedOrNot(16, 3)
assertDiagnosticWasEmittedOrNot(18, 3)
assertDiagnosticWasEmittedOrNot(19, 3)
assertDiagnosticWasEmittedOrNot(20, 3)
assertDiagnosticWasEmittedOrNot(21, 3)
assertDiagnosticWasEmittedOrNot(22, 3)
assertDiagnosticWasEmittedOrNot(23, 3)
assertDiagnosticWasEmittedOrNot(24, 3)
}
}
func testFileScopeDeclsInsideNestedConditionals() {
runWithMultipleConfigurations(
source: """
#if FOO
#if BAR
$access$ class Foo {}
$access$ struct Foo {}
$access$ enum Foo {}
$access$ protocol Foo {}
$access$ typealias Foo = Bar
$access$ func foo() {}
$access$ var foo: Bar
#endif
#endif
""",
testConfigurations: changingTestConfigurations
) { assertDiagnosticWasEmittedOrNot in
assertDiagnosticWasEmittedOrNot(3, 5)
assertDiagnosticWasEmittedOrNot(4, 5)
assertDiagnosticWasEmittedOrNot(5, 5)
assertDiagnosticWasEmittedOrNot(6, 5)
assertDiagnosticWasEmittedOrNot(7, 5)
assertDiagnosticWasEmittedOrNot(8, 5)
assertDiagnosticWasEmittedOrNot(9, 5)
}
}
func testLeadingTriviaIsPreserved() {
runWithMultipleConfigurations(
source: """
/// Some doc comment
$access$ class Foo {}
@objc /* comment */ $access$ class Bar {}
""",
testConfigurations: changingTestConfigurations
) { assertDiagnosticWasEmittedOrNot in
assertDiagnosticWasEmittedOrNot(2, 1)
assertDiagnosticWasEmittedOrNot(4, 21)
}
}
func testModifierDetailIsPreserved() {
runWithMultipleConfigurations(
source: """
public $access$(set) var foo: Int
""",
testConfigurations: changingTestConfigurations
) { assertDiagnosticWasEmittedOrNot in
assertDiagnosticWasEmittedOrNot(1, 8)
}
}
/// Runs a test for this rule in multiple configurations.
private func runWithMultipleConfigurations(
source: String,
testConfigurations: [TestConfiguration],
file: StaticString = #file,
line: UInt = #line,
completion: ((Int, Int) -> Void) -> Void
) {
for testConfig in testConfigurations {
var configuration = Configuration()
configuration.fileScopedDeclarationPrivacy.accessLevel = testConfig.desired
let substitutedInput = source.replacingOccurrences(of: "$access$", with: testConfig.original)
let substitutedExpected =
source.replacingOccurrences(of: "$access$", with: testConfig.expected)
XCTAssertFormatting(
FileScopedDeclarationPrivacy.self,
input: substitutedInput,
expected: substitutedExpected,
checkForUnassertedDiagnostics: true,
configuration: configuration,
file: file,
line: line)
let message: Finding.Message =
testConfig.desired == .private
? .replaceFileprivateWithPrivate
: .replacePrivateWithFileprivate
if testConfig.original == testConfig.expected {
completion { _, _ in
XCTAssertNotDiagnosed(message, file: file, line: line)
}
} else {
completion { diagnosticLine, diagnosticColumn in
XCTAssertDiagnosed(
message, line: diagnosticLine, column: diagnosticColumn, file: file, line: line)
}
}
}
}
}
| apache-2.0 | 993d2d66c5b3c4c587d96369b43bf1e2 | 32.899582 | 100 | 0.662059 | 4.667051 | false | true | false | false |
wireapp/wire-ios-data-model | Tests/Source/Model/Observer/ObjectObserverToken/LabelObserverTests.swift | 1 | 2887 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
final class TestLabelObserver: NSObject, LabelObserver {
var notifications = [LabelChangeInfo]()
func clearNotifications() {
notifications = []
}
func labelDidChange(_ changeInfo: LabelChangeInfo) {
notifications.append(changeInfo)
}
}
final class LabelObserverTests: NotificationDispatcherTestBase {
var labelObserver: TestLabelObserver!
override func setUp() {
super.setUp()
labelObserver = TestLabelObserver()
}
override func tearDown() {
labelObserver = nil
super.tearDown()
}
var userInfoKeys: Set<String> {
return [
#keyPath(LabelChangeInfo.nameChanged)
]
}
func checkThatItNotifiesTheObserverOfAChange(_ team: Label, modifier: (Label) -> Void, expectedChangedFields: Set<String>, customAffectedKeys: AffectedKeys? = nil) {
// given
self.uiMOC.saveOrRollback()
self.token = LabelChangeInfo.add(observer: labelObserver, for: team, managedObjectContext: self.uiMOC)
// when
modifier(team)
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
self.uiMOC.saveOrRollback()
// then
let changeCount = labelObserver.notifications.count
XCTAssertEqual(changeCount, 1)
// and when
self.uiMOC.saveOrRollback()
// then
XCTAssertEqual(labelObserver.notifications.count, changeCount, "Should not have changed further once")
guard let changes = labelObserver.notifications.first else { return }
changes.checkForExpectedChangeFields(userInfoKeys: userInfoKeys, expectedChangedFields: expectedChangedFields)
}
func testThatItNotifiesTheObserverOfChangedName() {
// given
let label = Label.insertNewObject(in: self.uiMOC)
label.name = "bar"
self.uiMOC.saveOrRollback()
// when
self.checkThatItNotifiesTheObserverOfAChange(label,
modifier: { $0.name = "foo"},
expectedChangedFields: [#keyPath(LabelChangeInfo.nameChanged)]
)
}
}
| gpl-3.0 | c3659b7ec7bbbc45294e1ed5e40ed110 | 29.389474 | 169 | 0.66124 | 4.787728 | false | true | false | false |
chrislzm/TimeAnalytics | Time Analytics/TAModelHealthKitExtensions.swift | 1 | 11570 | //
// TAModelHealthKitExtensions.swift
// Time Analytics
//
// Extensions to the Time Analytics Model (TAModel) class for supporting Apple HealthKit data import
// -Implements Time Analytics data generation of TAActivitySegment entities from HealthKit data
//
// Created by Chris Leung on 5/23/17.
// Copyright © 2017 Chris Leung. All rights reserved.
//
import CoreData
import HealthKit
import UIKit
extension TAModel {
// MARK: Constants
static let HealthKitDataChunks = 4 // DO NOT CHANGE THIS VALUE. We process HealthKit data in 4 stages
// MARK: Time Analytics Data Creation Methods
// Creates a "TAActivitySegment" managed object -- the Time Analytics representation of a HealthKit activity
// Since this method gets called repeatedly, we pass the movesFirstTime in as a parameter so that we don't have to keep fetching it from TANetConstants and unwrapping it.
func createNewTAActivitySegment(_ startTime:Date,_ endTime:Date,_ type:String, _ name:String,_ movesFirstTime:Date, _ context:NSManagedObjectContext) {
// Delete existing object if one exists, so we can update/don't have duplicates
if(containsObjectWhere("TAActivitySegment","startTime",equals: startTime,context)) {
deleteObjectWhere("TAActivitySegment","startTime",equals: startTime,context)
}
let taActivitySegmentEntity = NSEntityDescription.entity(forEntityName: "TAActivitySegment", in: context)!
let taActivitySegment = NSManagedObject(entity: taActivitySegmentEntity, insertInto: context)
taActivitySegment.setValue(startTime, forKey:"startTime")
taActivitySegment.setValue(endTime, forKey: "endTime")
taActivitySegment.setValue(type, forKey:"type")
taActivitySegment.setValue(name, forKey:"name")
// If this activity occurs during an existing Place Segment
if startTime >= movesFirstTime, let place = getTAPlaceThatContains(startTime,endTime, context) {
// Save this place information into the activity data (since this activity occurs at this place)
taActivitySegment.setValue(place.startTime,forKey:"placeStartTime")
taActivitySegment.setValue(place.endTime,forKey:"placeEndTime")
taActivitySegment.setValue(place.lat,forKey:"placeLat")
taActivitySegment.setValue(place.lon,forKey:"placeLon")
taActivitySegment.setValue(place.name,forKey:"placeName")
}
save(context)
}
// Manages the import of HealthKit data to Time Analytics: Reads HealthKit data and creates TAActivity objects for them
func updateHealthKitData() {
notifyWillGenerateHKData()
let stack = getCoreDataStack()
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyyMMdd"
let firstMovesDataDate = dateFormatter.date(from: TANetClient.sharedInstance.movesUserFirstDate!)! as Date
// The date from which we should begin importing
var fromDate:Date? = nil
// If we have imported data before, then use the startTime of the newest activity as our fromDate
if let latestActivity = getLastTAActivityBefore(Date() as NSDate,stack.context) {
fromDate = latestActivity.endTime! as Date
}
// Retrieve Sleep Data
let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis)!
retrieveHealthStoreData(sleepType,fromDate) { (query,result,error) in
guard error == nil else {
self.notifyHealthDataReadError()
return
}
// Generate TAActivitySegment objects for the data
stack.performBackgroundBatchOperation() { (context) in
self.notifyDidProcessHealthKitDataChunk()
for item in result! {
let sample = item as! HKCategorySample
if sample.value == HKCategoryValueSleepAnalysis.inBed.rawValue {
self.createNewTAActivitySegment(sample.startDate, sample.endDate, "Sleep", "In Bed",firstMovesDataDate, context)
}
}
stack.save()
self.notifyDidProcessHealthKitDataChunk()
}
}
// Retrieve Workout Data
let workoutType = HKWorkoutType.workoutType()
retrieveHealthStoreData(workoutType,fromDate) { (query,result,error) in
guard error == nil else {
self.notifyHealthDataReadError()
return
}
stack.performBackgroundBatchOperation() { (context) in
self.notifyDidProcessHealthKitDataChunk()
for item in result! {
let workout = item as! HKWorkout
let workoutType = self.getHealthKitWorkoutTypeString(workout.workoutActivityType.rawValue)
self.createNewTAActivitySegment(item.startDate, item.endDate, "Workout", workoutType, firstMovesDataDate, context)
}
stack.save()
self.notifyDidProcessHealthKitDataChunk()
}
}
// Retrieve Mindfulness Data
let mindfulType = HKObjectType.categoryType(forIdentifier: .mindfulSession)!
retrieveHealthStoreData(mindfulType, fromDate) { (query,result,error) in
guard error == nil else {
self.notifyHealthDataReadError()
return
}
stack.performBackgroundBatchOperation() { (context) in
self.notifyDidProcessHealthKitDataChunk()
for item in result! {
self.createNewTAActivitySegment(item.startDate, item.endDate, "Mindfulness",item.sourceRevision.source.name,firstMovesDataDate, context)
}
stack.save()
self.notifyDidProcessHealthKitDataChunk()
}
}
}
// MARK: HealthKit Store Methods
func getHealthStore() -> HKHealthStore {
let delegate = UIApplication.shared.delegate as! AppDelegate
return delegate.healthStore
}
// Used to get authorization to the user's Health Store
func authorizeHealthKit(completion: ((_ success: Bool, _ error: Error?) -> Void)!) {
let healthKitStore = getHealthStore()
// State the health data type(s) we want to read from HealthKit.
let readableTypes: Set<HKSampleType> = [HKWorkoutType.workoutType(), HKObjectType.categoryType(forIdentifier: .sleepAnalysis)!, HKObjectType.categoryType(forIdentifier: .mindfulSession)!]
healthKitStore.requestAuthorization(toShare: nil, read: readableTypes) { (success, error) -> Void in
if( completion != nil ) {
completion(success,error)
}
}
}
// General purpose function for retrieving data from the HealthKit "Health Store"
func retrieveHealthStoreData(_ type:HKSampleType,_ fromDate:Date?, completionHandler: @escaping (HKSampleQuery, [HKSample]?, Error?) -> Void) {
let healthStore = getHealthStore()
var predicate:NSPredicate! = nil
if let fromDate = fromDate {
predicate = HKQuery.predicateForSamples(withStart: fromDate, end: Date(), options: [])
}
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true)
let query = HKSampleQuery(sampleType: type, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [sortDescriptor], resultsHandler: completionHandler)
healthStore.execute(query)
}
// Translate HealthKit enum values for workout types into strings
func getHealthKitWorkoutTypeString(_ activityType:UInt) -> String {
switch activityType {
case 1:
return "American Football"
case 2:
return "Archery"
case 3:
return "Australian Football"
case 4:
return "Badminton"
case 5:
return "Baseball"
case 6:
return "Basketball"
case 7:
return "Bowling"
case 8:
return "Boxing"
case 9:
return "Climbing"
case 10:
return "Cricket"
case 11:
return "Cross Training"
case 12:
return "Curling"
case 13:
return "Cycling"
case 14:
return "Dance"
case 15:
return "Dance Inspired Training"
case 16:
return "Elliptical"
case 17:
return "Equestrian Sports"
case 18:
return "Fencing"
case 19:
return "Fishing"
case 20:
return "Functional Strength Training"
case 21:
return "Golf"
case 22:
return "Gymnastics"
case 23:
return "Handball"
case 24:
return "Hiking"
case 25:
return "Hockey"
case 26:
return "Hunting"
case 27:
return "Lacrosse"
case 28:
return "Martial Arts"
case 29:
return "Mind And Body"
case 30:
return "Mixed Metabolic Cardio Training"
case 31:
return "Paddle Sports"
case 32:
return "Play"
case 33:
return "Preparation And Recovery"
case 34:
return "Racquetball"
case 35:
return "Rowing"
case 36:
return "Rugby"
case 37:
return "Running"
case 38:
return "Sailing"
case 39:
return "Skating Sports"
case 40:
return "SnowSports"
case 41:
return "Soccer"
case 42:
return "Softball"
case 43:
return "Squash"
case 44:
return "Stair Climbing"
case 45:
return "Surfing Sports"
case 46:
return "Swimming"
case 47:
return "Table Tennis"
case 48:
return "Tennis"
case 49:
return "Track And Field"
case 50:
return "Traditional Strength Training"
case 51:
return "Volleyball"
case 52:
return "Walking"
case 53:
return "Water Fitness"
case 54:
return "Water Polo"
case 55:
return "Water Sports"
case 56:
return "Wrestling"
case 57:
return "Yoga"
case 58:
return "Barre"
case 59:
return "Core Training"
case 60:
return "Cross Country Skiing"
case 61:
return "Downhill Skiing"
case 62:
return "Flexibility"
case 63:
return "High Intensity Interval Training"
case 64:
return "Jump Rope"
case 65:
return "Kick Boxing"
case 66:
return "Pilates"
case 67:
return "Snowboarding"
case 68:
return "Stairs"
case 69:
return "Step Training"
case 70:
return "Wheelchair Walk Pace"
case 71:
return "Wheelchair Run Pace"
default:
return "Other"
}
}
}
| mit | d97b455517c5b950a38978a33cdb3b92 | 35.843949 | 195 | 0.591062 | 5.034378 | false | false | false | false |
Wakup/Wakup-iOS-SDK | Wakup/CodeIconButton.swift | 1 | 2772 | //
// CodeIconButton.swift
// Wuakup
//
// Created by Guillermo Gutiérrez on 11/02/15.
// Copyright (c) 2015 Yellow Pineapple. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable open class CodeIconButton: CustomBorderButton {
@IBInspectable open dynamic var iconIdentifier: String? { didSet { refreshIcons() } }
@IBInspectable open dynamic var iconColor: UIColor? { didSet { refreshNormal() } }
@IBInspectable open dynamic var highlightedIconColor: UIColor? { didSet { refreshHighlighted() } }
@IBInspectable open dynamic var selectedIconColor: UIColor? { didSet { refreshSelected() } }
@IBInspectable open dynamic var disabledIconColor: UIColor? { didSet { refreshDisabled() } }
@IBInspectable open dynamic var highlightedSelectedIconColor: UIColor? { didSet { refreshHighlightedSelected() } }
@IBInspectable open dynamic var highlightedDisabledIconColor: UIColor? { didSet { refreshHighlightedDisabled() } }
@IBInspectable open dynamic var iconSize: CGSize = CGSize(width: 20, height: 20) { didSet { refreshIcons() } }
@IBInspectable open dynamic var iconFillsButton: Bool = false { didSet { refreshIcons() } }
fileprivate var codeIcon: CodeIcon?
fileprivate var iconFrame: CGRect { get { return iconFillsButton ? bounds : CGRect(origin: CGPoint.zero, size: iconSize) } }
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
func refreshIcons() {
codeIcon = iconIdentifier.map { CodeIcon(iconIdentifier: $0) }
refreshNormal()
refreshHighlighted()
refreshSelected()
refreshDisabled()
refreshHighlightedDisabled()
refreshHighlightedDisabled()
}
func refreshNormal() {
setImage(getIcon(color: iconColor), for: UIControl.State())
}
func refreshHighlighted() {
setImage(getIcon(color: highlightedIconColor), for: .highlighted)
}
func refreshSelected() {
setImage(getIcon(color: selectedIconColor), for: .selected)
}
func refreshDisabled() {
setImage(getIcon(color: disabledIconColor), for: .disabled)
}
func refreshHighlightedSelected() {
if let color = highlightedSelectedIconColor {
setImage(getIcon(color: color), for: [.selected, .highlighted])
}
}
func refreshHighlightedDisabled() {
if let color = highlightedDisabledIconColor {
setImage(getIcon(color: color), for: [.disabled, .highlighted])
}
}
func getIcon(color: UIColor?) -> UIImage? {
return codeIcon?.getImage(iconFrame, color: color)
}
}
| mit | f0fe6d2592f5879d24e99728c959174a | 34.987013 | 128 | 0.669433 | 4.736752 | false | false | false | false |
ylovesy/CodeFun | wuzhentao/canConstruct.swift | 1 | 702 | class Solution {
func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool {
var collections: [Character: Int] = [:]
for ch in magazine.characters {
if let count = collections[ch] {
collections[ch] = count + 1
}else {
collections[ch] = 1
}
}
for ch in ransomNote.characters {
if let count = collections[ch] {
if count <= 0 {
return false
} else {
collections[ch] = count - 1
}
} else {
return false
}
}
return true
}
}
| apache-2.0 | caef71721ddf189cfe244edcb3e92325 | 27.08 | 73 | 0.41453 | 5.014286 | false | false | false | false |
josherick/DailySpend | DailySpend/DatePickerTableViewCell.swift | 1 | 1177 | //
// DatePickerTableViewCell.swift
// DailySpend
//
// Created by Josh Sherick on 9/9/17.
// Copyright © 2017 Josh Sherick. All rights reserved.
//
import UIKit
class DatePickerTableViewCell: UITableViewCell {
var datePicker: UIDatePicker!
private var changedCallback: ((UIDatePicker) -> ())?
override func layoutSubviews() {
super.layoutSubviews()
if datePicker != nil {
datePicker.frame = bounds
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
datePicker = UIDatePicker()
self.addSubview(datePicker)
datePicker.addTarget(self, action: #selector(datePickerChanged(picker:)),
for: .valueChanged)
self.clipsToBounds = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@objc func datePickerChanged(picker: UIDatePicker!) {
changedCallback?(picker)
}
func setCallback(_ cb: @escaping ((UIDatePicker) -> ())) {
changedCallback = cb
}
}
| mit | 7b16950417062150f4dad4617f4490ee | 24.565217 | 81 | 0.614796 | 5.004255 | false | false | false | false |
IGRSoft/IGRPhotoTweaks | IGRPhotoTweaks/PhotoTweakView/CropView/IGRCropView+UITouch.swift | 1 | 3611 | //
// IGRCropView+UITouch.swift
// Pods
//
// Created by Vitalii Parovishnyk on 4/26/17.
//
//
import Foundation
extension IGRCropView {
override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.count == 1 {
self.updateCropLines(animate: false)
}
self.delegate?.cropViewDidStartCrop(self)
}
override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.count == 1 {
let location: CGPoint = (touches.first?.location(in: self))!
var frame: CGRect = self.frame
let p0 = CGPoint(x: CGFloat.zero, y: CGFloat.zero)
let p1 = CGPoint(x: self.frame.size.width, y: CGFloat.zero)
let p2 = CGPoint(x: CGFloat.zero, y: self.frame.size.height)
let p3 = CGPoint(x: self.frame.size.width, y: self.frame.size.height)
if location.distanceTo(point: p0) < kCropViewHotArea {
frame.origin.x += location.x
frame.size.width -= location.x
frame.origin.y += location.y
frame.size.height -= location.y
}
else if location.distanceTo(point: p1) < kCropViewHotArea {
frame.size.width = location.x
frame.origin.y += location.y
frame.size.height -= location.y
}
else if location.distanceTo(point: p2) < kCropViewHotArea {
frame.origin.x += location.x
frame.size.width -= location.x
frame.size.height = location.y
}
else if location.distanceTo(point: p3) < kCropViewHotArea {
frame.size.width = location.x
frame.size.height = location.y
}
else if abs(location.x - p0.x) < kCropViewHotArea {
frame.origin.x += location.x
frame.size.width -= location.x
}
else if abs(location.x - p1.x) < kCropViewHotArea {
frame.size.width = location.x
}
else if abs(location.y - p0.y) < kCropViewHotArea {
frame.origin.y += location.y
frame.size.height -= location.y
}
else if abs(location.y - p2.y) < kCropViewHotArea {
frame.size.height = location.y
}
// If Aspect ratio is Freezed reset frame as per the aspect ratio
if self.isAspectRatioLocked {
let newHeight = (self.aspectRatioHeight / self.aspectRatioWidth) * frame.size.width
frame = CGRect(x: frame.origin.x,
y: frame.origin.y,
width: frame.size.width,
height: newHeight)
}
//TODO: Added test cropViewInsideValidFrame
if (frame.size.width > self.cornerBorderLength
&& frame.size.height > self.cornerBorderLength) {
self.frame = frame
// update crop lines
self.updateCropLines(animate: false)
self.delegate?.cropViewDidMove(self)
}
}
}
override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.delegate?.cropViewDidStopCrop(self)
}
override public func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
self.delegate?.cropViewDidStopCrop(self)
}
}
| mit | f86d67c6688d50e39845eccc909d0539 | 37.414894 | 99 | 0.531155 | 4.366385 | false | false | false | false |
1985apps/PineKit | Pod/Classes/PineBarGraph.swift | 2 | 4222 | //
// BarGraph.swift
// Pods
//
// Created by Prakash Raman on 19/02/16.
//
//
import UIKit
import Foundation
open class PineBarGraph: UIView {
open var barColor = PineConfig.Color.purple
var yDivisions : CGFloat = 5
var axisMargin : CGFloat = 20
var xSet : [Dictionary<String, String>] = []
var ySet : PineBarGraphYSet?
let labelsView = UIView()
var canvas = UIView()
let yAxisView = UIView()
public init(xSet: [Dictionary<String, String>], ySet: PineBarGraphYSet){
super.init(frame: CGRect.zero)
self.ySet = ySet
self.xSet = xSet
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open func setup(){
setupCanvas()
setupXAxis()
setupYAxis()
}
func setupCanvas(){
self.addSubview(self.canvas)
var frame = CGRect.zero
frame.origin.x = self.axisMargin
frame.size.width = self.frame.width - self.axisMargin - 10
frame.size.height = self.frame.height - self.axisMargin
self.canvas.frame = frame
}
func setupXAxis(){
self.addSubview(self.labelsView)
var frame = self.canvas.frame
frame.size.height = 20
frame.origin.y = self.frame.size.height - frame.height
labelsView.frame = frame
let count : CGFloat = CGFloat(self.xSet.count)
let labelWidth = frame.width / count
var x : CGFloat = 0
print(labelsView.frame.width)
for item in self.xSet {
let label = item["text"]!
let l = PineLabel(text: label)
l.font = PineConfig.Font.get(PineConfig.Font.LIGHT, size: 11)
l.textAlignment = .center
labelsView.addSubview(l)
let f = CGRect(x: x, y: 0, width: labelWidth, height: frame.height)
l.frame = f
x = x + labelWidth
}
}
func setupYAxis(){
let r = self.ySet?.range
let sectionSize = ((r?.upperBound)! - (r?.lowerBound)!) / Int(yDivisions)
print(sectionSize)
self.addSubview(yAxisView)
self.yAxisView.frame = CGRect(x: 0, y: 0, width:CGFloat(self.axisMargin), height: self.frame.height - 30)
var y = yAxisView.frame.height
let sectionHeight = yAxisView.frame.height / yDivisions
var value = Int((r?.lowerBound)!)
for _ in 0...(Int(self.yDivisions) - 1) {
let line = PineBarGraphHorizonalGridLine(text: String(value))
self.addSubview(line)
line.frame = CGRect(x: 0, y: y, width: self.frame.width, height: 10)
y = y - sectionHeight
value = value + sectionSize
}
}
open func applyLayer(_ values: [CGFloat]){
for (index, value) in values.enumerated() {
let bar = UIView()
var frame = self.getFrameForColumn(number: CGFloat(index), value: value)
let animateToHeight = frame.height
let animateToY = frame.origin.y
frame.size.height = 0
frame.origin.y = self.canvas.frame.height
bar.frame = frame
self.canvas.addSubview(bar)
UIView.animate(withDuration: 0.5, animations: { () -> Void in
frame.size.height = animateToHeight
frame.origin.y = animateToY
bar.frame = frame
bar.backgroundColor = self.barColor
})
}
}
func getFrameForColumn(number: CGFloat, value: CGFloat) -> CGRect {
let canvasWidth = self.canvas.frame.width
let sectionWidth = canvasWidth / CGFloat(self.xSet.count)
let barWidth = sectionWidth * 0.66
let diff = sectionWidth - barWidth
let height = self.canvas.frame.height * value / 100
let y = self.canvas.frame.height - height
let x = (number * sectionWidth) + (diff / 2)
return CGRect(x: x, y: y, width: barWidth, height: height)
}
}
| mit | ed37cd09f3fa8eaa1507a9c7069a4063 | 28.524476 | 113 | 0.555424 | 4.286294 | false | false | false | false |
avario/ChainKit | ChainKit/ChainKit/UIButton+ChainKit.swift | 1 | 2467 | //
// UIButton+ChainKit.swift
// ChainKit
//
// Created by Avario.
//
import UIKit
public extension UIButton {
public func contentEdgeInsets(_ contentEdgeInsets: UIEdgeInsets) -> Self {
self.contentEdgeInsets = contentEdgeInsets
return self
}
public func titleEdgeInsets(_ titleEdgeInsets: UIEdgeInsets) -> Self {
self.titleEdgeInsets = titleEdgeInsets
return self
}
public func reversesTitleShadowWhenHighlighted(_ reversesTitleShadowWhenHighlighted: Bool) -> Self {
self.reversesTitleShadowWhenHighlighted = reversesTitleShadowWhenHighlighted
return self
}
public func imageEdgeInsets(_ imageEdgeInsets: UIEdgeInsets) -> Self {
self.imageEdgeInsets = imageEdgeInsets
return self
}
public func adjustsImageWhenHighlighted(_ adjustsImageWhenHighlighted: Bool) -> Self {
self.adjustsImageWhenHighlighted = adjustsImageWhenHighlighted
return self
}
public func adjustsImageWhenDisabled(_ adjustsImageWhenDisabled: Bool) -> Self {
self.adjustsImageWhenDisabled = adjustsImageWhenDisabled
return self
}
public func showsTouchWhenHighlighted(_ showsTouchWhenHighlighted: Bool) -> Self {
self.showsTouchWhenHighlighted = showsTouchWhenHighlighted
return self
}
public func title(_ title: String?, for state: UIControlState = .normal) -> Self {
self.setTitle(title, for: state)
return self
}
public func titleColor(_ color: UIColor?, for state: UIControlState = .normal) -> Self {
self.setTitleColor(color, for: state)
return self
}
public func titleShadowColor(_ color: UIColor?, for state: UIControlState = .normal) -> Self {
self.setTitleShadowColor(color, for: state)
return self
}
public func titleFont(_ font: UIFont) -> Self {
titleLabel?.font = font
return self
}
public func image(_ image: UIImage?, for state: UIControlState = .normal) -> Self {
self.setImage(image, for: state)
return self
}
public func backgroundImage(_ image: UIImage?, for state: UIControlState = .normal) -> Self {
self.setBackgroundImage(image, for: state)
return self
}
public func attributedTitle(_ title: NSAttributedString?, for state: UIControlState = .normal) -> Self {
self.setAttributedTitle(title, for: state)
return self
}
}
| mit | 9209a3327fe0dacc05ba14186cc2b9be | 29.085366 | 108 | 0.673287 | 5.374728 | false | false | false | false |
brennanMKE/StravaKit | Sources/SegmentEffort.swift | 2 | 3221 | //
// SegmentEffort.swift
// StravaKit
//
// Created by Brennan Stehling on 8/31/16.
// Copyright © 2016 SmallSharpTools LLC. All rights reserved.
//
import Foundation
/**
Model Representation of a segment effort.
*/
public struct SegmentEffort {
public let effortId: Int
public let resourceState: Int
public let name: String
public let activity: ResourceSummary
public let athlete: ResourceSummary
public let elapsedTime: Int
public let movingTime: Int
public let distance: Double
public let startIndex: Int
public let endIndex: Int
public let deviceWatts: Bool
public let averageWatts: Double
public let segment: Segment
public let prRank: Int?
public let komRank: Int?
internal let startDateString: String
internal let startDateLocalString: String
/**
Failable initializer.
*/
init?(dictionary: JSONDictionary) {
guard let s = JSONSupport(dictionary: dictionary),
let effortId: Int = s.value("id"),
let resourceState: Int = s.value("resource_state"),
let name: String = s.value("name"),
let activityDictionary: JSONDictionary = s.value("activity"),
let activity = ResourceSummary(dictionary: activityDictionary),
let athleteDictionary: JSONDictionary = s.value("athlete"),
let athlete = ResourceSummary(dictionary: athleteDictionary),
let elapsedTime: Int = s.value("elapsed_time"),
let movingTime: Int = s.value("moving_time"),
let startDate: String = s.value("start_date"),
let startDateLocal: String = s.value("start_date_local"),
let distance: Double = s.value("distance"),
let startIndex: Int = s.value("start_index"),
let endIndex: Int = s.value("end_index"),
let deviceWatts: Bool = s.value("device_watts"),
let averageWatts: Double = s.value("average_watts"),
let segmentDictionary: JSONDictionary = s.value("segment"),
let segment = Segment(dictionary: segmentDictionary) else {
return nil
}
self.effortId = effortId
self.resourceState = resourceState
self.name = name
self.activity = activity
self.athlete = athlete
self.elapsedTime = elapsedTime
self.movingTime = movingTime
self.startDateString = startDate
self.startDateLocalString = startDateLocal
self.distance = distance
self.startIndex = startIndex
self.endIndex = endIndex
self.deviceWatts = deviceWatts
self.averageWatts = averageWatts
self.segment = segment
self.prRank = s.value("pr_rank", required: false)
self.komRank = s.value("kom_rank", required: false)
}
public static func efforts(_ dictionaries: [JSONDictionary]) -> [SegmentEffort] {
return dictionaries.flatMap { (d) in
return SegmentEffort(dictionary: d)
}
}
public var startDate: Date? {
return Strava.dateFromString(startDateString)
}
public var startDateLocal: Date? {
return Strava.dateFromString(startDateLocalString)
}
}
| mit | f8166fe2a52fb6e9831e664364d2d96e | 33.255319 | 85 | 0.640373 | 4.619799 | false | false | false | false |
huangboju/Moots | Examples/Lumia/Lumia/Component/Transitions/FluidPhoto/Core/ZoomDismissalInteractionController.swift | 1 | 7665 | //
// ZoomDismissalInteractionController.swift
// FluidPhoto
//
// Created by Masamichi Ueta on 2016/12/29.
// Copyright © 2016 Masmichi Ueta. All rights reserved.
//
import UIKit
class ZoomDismissalInteractionController: NSObject {
var transitionContext: UIViewControllerContextTransitioning?
var animator: UIViewControllerAnimatedTransitioning?
var fromReferenceImageViewFrame: CGRect?
var toReferenceImageViewFrame: CGRect?
func didPan(with gestureRecognizer: UIPanGestureRecognizer) {
guard let transitionContext = self.transitionContext,
let animator = self.animator as? ZoomAnimator,
let transitionImageView = animator.transitionImageView,
let fromVC = transitionContext.viewController(forKey: .from),
let toVC = transitionContext.viewController(forKey: .to),
let fromReferenceImageView = animator.fromDelegate?.referenceImageView(for: animator),
let toReferenceImageView = animator.toDelegate?.referenceImageView(for: animator),
let fromReferenceImageViewFrame = self.fromReferenceImageViewFrame,
let toReferenceImageViewFrame = self.toReferenceImageViewFrame else {
return
}
fromReferenceImageView.isHidden = true
let anchorPoint = CGPoint(x: fromReferenceImageViewFrame.midX, y: fromReferenceImageViewFrame.midY)
let translatedPoint = gestureRecognizer.translation(in: fromReferenceImageView)
let verticalDelta : CGFloat = translatedPoint.y < 0 ? 0 : translatedPoint.y
let backgroundAlpha = self.backgroundAlpha(for: fromVC.view, withPanningVerticalDelta: verticalDelta)
let scale = self.scale(for: fromVC.view, withPanningVerticalDelta: verticalDelta)
fromVC.view.alpha = backgroundAlpha
transitionImageView.transform = CGAffineTransform(scaleX: scale, y: scale)
let newCenter = CGPoint(x: anchorPoint.x + translatedPoint.x, y: anchorPoint.y + translatedPoint.y - transitionImageView.frame.height * (1 - scale) / 2.0)
transitionImageView.center = newCenter
toReferenceImageView.isHidden = true
transitionContext.updateInteractiveTransition(1 - scale)
toVC.tabBarController?.tabBar.alpha = 1 - backgroundAlpha
if gestureRecognizer.state == .ended {
let velocity = gestureRecognizer.velocity(in: fromVC.view)
if velocity.y < 0 || newCenter.y < anchorPoint.y {
//cancel
UIView.animate(
withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.9,
initialSpringVelocity: 0,
options: [],
animations: {
transitionImageView.frame = fromReferenceImageViewFrame
fromVC.view.alpha = 1.0
toVC.tabBarController?.tabBar.alpha = 0
},
completion: { completed in
toReferenceImageView.isHidden = false
fromReferenceImageView.isHidden = false
transitionImageView.removeFromSuperview()
animator.transitionImageView = nil
transitionContext.cancelInteractiveTransition()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
animator.toDelegate?.transitionDidEnd(with: animator)
animator.fromDelegate?.transitionDidEnd(with: animator)
self.transitionContext = nil
})
return
}
//start animation
let finalTransitionSize = toReferenceImageViewFrame
UIView.animate(withDuration: 0.25,
delay: 0,
options: [],
animations: {
fromVC.view.alpha = 0
transitionImageView.frame = finalTransitionSize
toVC.tabBarController?.tabBar.alpha = 1
}, completion: { completed in
transitionImageView.removeFromSuperview()
toReferenceImageView.isHidden = false
fromReferenceImageView.isHidden = false
self.transitionContext?.finishInteractiveTransition()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
animator.toDelegate?.transitionDidEnd(with: animator)
animator.fromDelegate?.transitionDidEnd(with: animator)
self.transitionContext = nil
})
}
}
func backgroundAlpha(for view: UIView, withPanningVerticalDelta verticalDelta: CGFloat) -> CGFloat {
let startingAlpha:CGFloat = 1.0
let finalAlpha: CGFloat = 0.0
let totalAvailableAlpha = startingAlpha - finalAlpha
let maximumDelta = view.bounds.height / 4.0
let deltaAsPercentageOfMaximun = min(abs(verticalDelta) / maximumDelta, 1.0)
return startingAlpha - (deltaAsPercentageOfMaximun * totalAvailableAlpha)
}
func scale(for view: UIView, withPanningVerticalDelta verticalDelta: CGFloat) -> CGFloat {
let startingScale: CGFloat = 1.0
let finalScale: CGFloat = 0.5
let totalAvailableScale = startingScale - finalScale
let maximumDelta = view.bounds.height / 2.0
let deltaAsPercentageOfMaximun = min(abs(verticalDelta) / maximumDelta, 1.0)
return startingScale - (deltaAsPercentageOfMaximun * totalAvailableScale)
}
}
extension ZoomDismissalInteractionController: UIViewControllerInteractiveTransitioning {
func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) {
self.transitionContext = transitionContext
let containerView = transitionContext.containerView
guard let animator = self.animator as? ZoomAnimator,
let fromVC = transitionContext.viewController(forKey: .from),
let toVC = transitionContext.viewController(forKey: .to),
let fromReferenceImageViewFrame = animator.fromDelegate?.targetFrame(for: animator),
let toReferenceImageViewFrame = animator.toDelegate?.targetFrame(for: animator),
let fromReferenceImageView = animator.fromDelegate?.referenceImageView(for: animator)
else {
return
}
animator.fromDelegate?.transitionWillStart(with: animator)
animator.toDelegate?.transitionWillStart(with: animator)
self.fromReferenceImageViewFrame = fromReferenceImageViewFrame
self.toReferenceImageViewFrame = toReferenceImageViewFrame
let referenceImage = fromReferenceImageView.image!
containerView.insertSubview(toVC.view, belowSubview: fromVC.view)
if animator.transitionImageView == nil {
let transitionImageView = UIImageView(image: referenceImage)
transitionImageView.contentMode = .scaleAspectFill
transitionImageView.frame = fromReferenceImageViewFrame
animator.transitionImageView = transitionImageView
containerView.addSubview(transitionImageView)
}
}
}
| mit | ad147fbea0bd8a469bf04951dfa7360b | 44.349112 | 162 | 0.62761 | 6.175665 | false | false | false | false |
mercadopago/sdk-ios | MercadoPagoSDK/MercadoPagoSDK/GatewayService.swift | 3 | 982 | //
// GatewayService.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 29/12/14.
// Copyright (c) 2014 com.mercadopago. All rights reserved.
//
import Foundation
public class GatewayService : MercadoPagoService {
public func getToken(url : String = "/v1/card_tokens", method : String = "POST", public_key : String, savedCardToken : SavedCardToken, success: (jsonResult: AnyObject?) -> Void, failure: ((error: NSError) -> Void)?) {
self.request(url, params: "public_key=" + public_key, body: savedCardToken.toJSONString(), method: method, success: success, failure: failure)
}
public func getToken(url : String = "/v1/card_tokens", method : String = "POST", public_key : String, cardToken : CardToken, success: (jsonResult: AnyObject?) -> Void, failure: ((error: NSError) -> Void)?) {
self.request(url, params: "public_key=" + public_key, body: cardToken.toJSONString(), method: method, success: success, failure: failure)
}
} | mit | 547f1c0c7b862f6528d0380ca0390b84 | 48.15 | 221 | 0.682281 | 3.866142 | false | false | false | false |
devincoughlin/swift | test/Sema/diag_ambiguous_overloads.swift | 1 | 4164 | // RUN: %target-typecheck-verify-swift
enum E : String {
case foo = "foo"
case bar = "bar" // expected-note {{'bar' declared here}}
}
func fe(_: E) {}
func fe(_: Int) {}
func fe(_: Int, _: E) {}
func fe(_: Int, _: Int) {}
fe(E.baz) // expected-error {{type 'E' has no member 'baz'; did you mean 'bar'?}}
fe(.baz) // expected-error {{reference to member 'baz' cannot be resolved without a contextual type}}
// FIXME: maybe complain about .nope also?
fe(.nope, .nyet) // expected-error {{reference to member 'nyet' cannot be resolved without a contextual type}}
func fg<T>(_ f: (T) -> T) -> Void {} // expected-note {{in call to function 'fg'}}
fg({x in x}) // expected-error {{generic parameter 'T' could not be inferred}}
struct S {
func f<T>(_ i: (T) -> T, _ j: Int) -> Void {} // expected-note {{in call to function 'f'}}
func f(_ d: (Double) -> Double) -> Void {}
func test() -> Void {
f({x in x}, 2) // expected-error {{generic parameter 'T' could not be inferred}}
}
func g<T>(_ a: T, _ b: Int) -> Void {} // expected-note {{in call to function 'g'}}
func g(_ a: String) -> Void {}
func test2() -> Void {
g(.notAThing, 7) // expected-error {{generic parameter 'T' could not be inferred}}
}
func h(_ a: Int, _ b: Int) -> Void {}
func h(_ a: String) -> Void {}
func test3() -> Void {
h(.notAThing, 3) // expected-error {{type 'Int' has no member 'notAThing'}}
h(.notAThing) // expected-error {{type 'String' has no member 'notAThing'}}
}
}
class DefaultValue {
static func foo(_ a: Int) {}
static func foo(_ a: Int, _ b: Int = 1) {}
static func foo(_ a: Int, _ b: Int = 1, _ c: Int = 2) {}
}
DefaultValue.foo(1.0, 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
class Variadic {
static func foo(_ a: Int) {}
static func foo(_ a: Int, _ b: Double...) {}
}
Variadic.foo(1.0, 2.0, 3.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
//=-------------- SR-7918 --------------=/
class sr7918_Suit {
static func foo<T: Any>(_ :inout T) {}
static func foo() {}
}
class sr7918_RandomNumberGenerator {}
let myRNG = sr7918_RandomNumberGenerator() // expected-note {{change 'let' to 'var' to make it mutable}}
_ = sr7918_Suit.foo(&myRNG) // expected-error {{cannot pass immutable value as inout argument: 'myRNG' is a 'let' constant}}
//=-------------- SR-7786 --------------=/
struct sr7786 {
func foo() -> UInt { return 0 }
func foo<T: UnsignedInteger>(bar: T) -> T { // expected-note {{where 'T' = 'Int'}}
return bar
}
}
let s = sr7786()
let a = s.foo()
let b = s.foo(bar: 123) // expected-error {{instance method 'foo(bar:)' requires that 'Int' conform to 'UnsignedInteger'}}
let c: UInt = s.foo(bar: 123)
let d = s.foo(bar: 123 as UInt)
//=-------------- SR-7440 --------------=/
struct sr7440_ITunesGenre {
let genre: Int // expected-note {{'genre' declared here}}
let name: String
}
class sr7440_Genre {
static func fetch<B: BinaryInteger>(genreID: B, name: String) {}
static func fetch(_ iTunesGenre: sr7440_ITunesGenre) -> sr7440_Genre {
return sr7440_Genre.fetch(genreID: iTunesGenre.genreID, name: iTunesGenre.name)
// expected-error@-1 {{value of type 'sr7440_ITunesGenre' has no member 'genreID'; did you mean 'genre'?}}
// expected-error@-2 {{cannot convert return expression of type '()' to return type 'sr7440_Genre'}}
}
}
//=-------------- SR-5154 --------------=/
protocol sr5154_Scheduler {
func inBackground(run task: @escaping () -> Void)
}
extension sr5154_Scheduler {
func inBackground(run task: @escaping () -> [Count], completedBy resultHandler: @escaping ([Count]) -> Void) {}
}
struct Count { // expected-note {{'init(title:)' declared here}}
let title: String
}
func getCounts(_ scheduler: sr5154_Scheduler, _ handler: @escaping ([Count]) -> Void) {
scheduler.inBackground(run: {
return [Count()] // expected-error {{missing argument for parameter 'title' in call}}
}, completedBy: { // expected-error {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{20-20= _ in}}
})
}
| apache-2.0 | f9d7ec47b851d7f01dac0cf64069cca4 | 33.7 | 154 | 0.619356 | 3.333867 | false | false | false | false |
tlax/looper | looper/Controller/Loops/CLoops.swift | 1 | 5882 | import UIKit
import ImageIO
import MobileCoreServices
class CLoops:CController
{
weak var viewLoops:VLoops!
let model:MLoops
private let kFilename:String = "looper.gif"
private let kLoopCount:Int = 0
override init()
{
model = MLoops()
super.init()
}
required init?(coder:NSCoder)
{
return nil
}
override func viewDidAppear(_ animated:Bool)
{
super.viewDidLoad()
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.loadFromDB()
}
}
override func loadView()
{
let viewLoops:VLoops = VLoops(controller:self)
self.viewLoops = viewLoops
view = viewLoops
}
//MARK: private
private func loadFromDB()
{
model.loadFromDb
{
DispatchQueue.main.async
{ [weak self] in
self?.loadedFromDB()
}
}
}
private func loadedFromDB()
{
viewLoops.stopLoading()
}
private func confirmDelete(model:MLoopsItem)
{
model.delete()
loadFromDB()
}
private func asyncShare(model:MLoopsItem)
{
let images:[UIImage] = model.images.imageLists()
let directoryUrl:URL = URL(fileURLWithPath:NSTemporaryDirectory())
let fileUrl:URL = directoryUrl.appendingPathComponent(kFilename)
let totalImages:Int = images.count
guard
let destination:CGImageDestination = CGImageDestinationCreateWithURL(
fileUrl as CFURL,
kUTTypeGIF,
totalImages,
nil)
else
{
return
}
let duration:TimeInterval = model.loop.duration
let timePerItem:TimeInterval = duration / TimeInterval(totalImages)
let destinationPropertiesRaw:[String:Any] = [
kCGImagePropertyGIFDictionary as String:[
kCGImagePropertyGIFLoopCount as String:kLoopCount]]
let gifPropertiesRaw:[String:Any] = [
kCGImagePropertyGIFDictionary as String:[
kCGImagePropertyGIFDelayTime as String:timePerItem]]
let destinationProperties:CFDictionary = destinationPropertiesRaw as CFDictionary
let gifProperties:CFDictionary = gifPropertiesRaw as CFDictionary
CGImageDestinationSetProperties(
destination,
destinationProperties)
for image:UIImage in images
{
guard
let cgImage:CGImage = image.cgImage
else
{
continue
}
CGImageDestinationAddImage(
destination,
cgImage,
gifProperties)
}
CGImageDestinationFinalize(destination)
DispatchQueue.main.async
{ [weak self] in
self?.finishShare(gif:fileUrl)
}
}
private func finishShare(gif:URL)
{
let activity:UIActivityViewController = UIActivityViewController(
activityItems:[gif],
applicationActivities:nil)
if activity.popoverPresentationController != nil
{
activity.popoverPresentationController!.sourceView = viewLoops
activity.popoverPresentationController!.sourceRect = CGRect.zero
activity.popoverPresentationController!.permittedArrowDirections = UIPopoverArrowDirection.up
}
present(
activity,
animated:true)
{ [weak self] in
self?.viewLoops.stopLoading()
}
}
//MARK: public
func delete(model:MLoopsItem)
{
let alert:UIAlertController = UIAlertController(
title:
NSLocalizedString("CLoops_alertTitle", comment:""),
message:nil,
preferredStyle:UIAlertControllerStyle.actionSheet)
let actionCancel:UIAlertAction = UIAlertAction(
title:
NSLocalizedString("CLoops_alertCancel", comment:""),
style:
UIAlertActionStyle.cancel)
let actionDelete:UIAlertAction = UIAlertAction(
title:
NSLocalizedString("CLoops_alertDelete", comment:""),
style:
UIAlertActionStyle.destructive)
{ [weak self] (action:UIAlertAction) in
self?.viewLoops.startLoading()
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.confirmDelete(model:model)
}
}
alert.addAction(actionDelete)
alert.addAction(actionCancel)
if let popover:UIPopoverPresentationController = alert.popoverPresentationController
{
popover.sourceView = viewLoops
popover.sourceRect = CGRect.zero
popover.permittedArrowDirections = UIPopoverArrowDirection.up
}
present(alert, animated:true, completion:nil)
}
func share(model:MLoopsItem)
{
viewLoops.startLoading()
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.asyncShare(model:model)
}
}
func help()
{
let helpGeneral:MHelpGeneral = MHelpGeneral()
let controllerHelp:CHelp = CHelp(model:helpGeneral)
parentController.push(
controller:controllerHelp,
vertical:CParent.TransitionVertical.fromTop)
}
}
| mit | 10d8cb2eb2317ca7063b4a621b78ee14 | 26.231481 | 105 | 0.561034 | 5.870259 | false | false | false | false |
sora0077/iTunesMusic | Sources/Entity/EntityReview.swift | 1 | 2001 | //
// EntityReview.swift
// iTunesMusic
//
// Created by 林達也 on 2016/07/27.
// Copyright © 2016年 jp.sora0077. All rights reserved.
//
import Foundation
import RealmSwift
import Himotoki
public protocol Review {
var auther: String { get }
var title: String { get }
var content: String { get }
var rating: Int { get }
}
extension Review {
var impl: _Review {
// swiftlint:disable:next force_cast
return self as! _Review
}
}
@objc
final class _Review: RealmSwift.Object, Review {
@objc fileprivate(set) dynamic var id = 0
@objc fileprivate(set) dynamic var auther = ""
@objc fileprivate(set) dynamic var title = ""
@objc fileprivate(set) dynamic var content = ""
@objc fileprivate(set) dynamic var rating = 0
@objc fileprivate(set) dynamic var voteCount = 0
@objc fileprivate(set) dynamic var voteSum = 0
@objc fileprivate(set) dynamic var postedAt = Date.distantPast
override class func primaryKey() -> String? { return "id" }
}
private let intTransformer = Transformer<String, Int> {
guard let val = Int($0) else {
throw DecodeError.typeMismatch(expected: "Int", actual: "String", keyPath: "")
}
return val
}
private let postedAtTransformer = Transformer<String, Date> { string in
// 2016-06-29T07:00:00-07:00
return string.dateFromFormat("yyyy-MM-dd'T'HH:mm:sszzzz")!
}
extension _Review: Decodable {
static func decode(_ e: Extractor) throws -> Self {
let obj = self.init()
obj.id = try intTransformer.apply(e.value("id"))
obj.auther = try e.value("auther")
obj.title = try e.value("title")
obj.content = try e.value("content")
obj.rating = try intTransformer.apply(e.value("rating"))
obj.voteCount = try intTransformer.apply(e.value("voteCount"))
obj.voteSum = try intTransformer.apply(e.value("voteSum"))
obj.postedAt = try postedAtTransformer.apply(e.value("updated"))
return obj
}
}
| mit | 70f08d14a796e97b5679079d861534f3 | 29.646154 | 86 | 0.656124 | 3.702602 | false | false | false | false |
gokulgovind/GLNotificationBar | Example/GLNotificationBar/ViewController.swift | 1 | 6283 | //
// ViewController.swift
// GLNotificationBar
//
// Created by gokul on 11/11/2016.
// Copyright (c) 2016 gokul. All rights reserved.
//
import UIKit
import AVFoundation
import GLNotificationBar
class ViewController: UIViewController {
var colorStyle:GLNotificationColorType = .extraLight
@IBOutlet weak var notificationTitle: UITextField!
@IBOutlet weak var notificationMessage: UITextField!
@IBOutlet weak var soundName: UITextField!
@IBOutlet weak var soundType: UITextField!
@IBOutlet weak var vibrate: UISwitch!
@IBOutlet weak var sound: UISwitch!
@IBOutlet weak var notificationAction: UISwitch!
@IBOutlet weak var timeOutLabel: UILabel!
@IBOutlet weak var stepper: UIStepper!
@IBOutlet weak var notificationBarType: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard(_:)))
self.view .addGestureRecognizer(tap)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showNotification(_ sender: AnyObject) {
var style:GLNotificationStyle!
if notificationBarType.selectedSegmentIndex == 0 {
style = .detailedBanner
}else{
style = .simpleBanner
}
let notificationBar = GLNotificationBar(title: notificationTitle.text!, message:notificationMessage.text! , preferredStyle:style) { (bool) in
let alert = UIAlertController(title: "Handler", message: "Catch didSelectNotification action in GLNotificationBar completion handler.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
// Set visual effectview style.
notificationBar.setColorStyle(colorStyle)
notificationBar.setShadow(true)
if notificationAction.isOn {
//Type: .Cancel
notificationBar.addAction(GLNotifyAction(title: "Cancel", style: .cancel, handler: { (result) in
let alert = UIAlertController(title: result.actionTitle, message: "Apply a style that indicates the action cancels the operation and leaves things unchanged.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
//Type: .Destructive
notificationBar.addAction(GLNotifyAction(title: "Destructive", style: .destructive, handler: { (result) in
let alert = UIAlertController(title: result.actionTitle, message: " Apply a style that indicates the action might change or delete data.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
//Type: .Default
notificationBar.addAction(GLNotifyAction(title: "Default", style: .default, handler: { (result) in
let alert = UIAlertController(title: result.actionTitle, message: "Apply the default style to the action’s button.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
//Type: .TextInput
notificationBar.addAction(GLNotifyAction(title: "Text Input", style: .textInput, handler: { (result) in
let alert = UIAlertController(title: result.actionTitle, message: "Apply a style that indicates the action opens an textinput field helps to respond notification as string.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}))
// //Type: .OnlyTextInput
//
// notificationBar.addAction(GLNotifyAction(title: "Reply", style: .OnlyTextInput, handler: { (result) in
// let alert = UIAlertController(title: result.actionTitle, message: " Apply a style which removes all other action added and simply adds text field as input to respond notification.", preferredStyle: .Alert)
// alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
// self.presentViewController(alert, animated: true, completion: nil)
// }))
}
notificationBar.showTime(stepper.value)
if sound.isOn {
notificationBar.notificationSound(soundName.text, ofType: soundType.text, vibrate: vibrate.isOn)
}
}
@IBAction func hideKeyboard(_ sender: UIButton!) {
self.view.endEditing(true)
}
@IBAction func timeOutInterval(_ sender: UIStepper) {
timeOutLabel.text = "Time out interval \(String(sender.value))"
}
@IBAction func selectColorType(_ sender: UIButton) {
let actionSheet = UIAlertController(title: "Color Type", message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "light", style: .default, handler: { (action) in
self.colorStyle = .light
}))
actionSheet.addAction(UIAlertAction(title: "extra light", style: .default, handler: { (action) in
self.colorStyle = .extraLight
}))
actionSheet.addAction(UIAlertAction(title: "dark", style: .default, handler: { (action) in
self.colorStyle = .dark
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(actionSheet, animated: true, completion: nil)
}
}
extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | 45739fcf0ec9ac936e59d5e983fc7a48 | 43.232394 | 223 | 0.642254 | 4.949567 | false | false | false | false |
rexmas/RealmCrust | Pods/RealmSwift/RealmSwift/Realm.swift | 3 | 24759 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
A Realm instance (also referred to as "a realm") represents a Realm
database.
Realms can either be stored on disk (see `init(path:)`) or in
memory (see `Configuration`).
Realm instances are cached internally, and constructing equivalent Realm
objects (with the same path or identifier) produces limited overhead.
If you specifically want to ensure a Realm object is
destroyed (for example, if you wish to open a realm, check some property, and
then possibly delete the realm file and re-open it), place the code which uses
the realm within an `autoreleasepool {}` and ensure you have no other
strong references to it.
- warning: Realm instances are not thread safe and can not be shared across
threads or dispatch queues. You must construct a new instance on each thread you want
to interact with the realm on. For dispatch queues, this means that you must
call it in each block which is dispatched, as a queue is not guaranteed to run
on a consistent thread.
*/
public final class Realm {
// MARK: Properties
/// Path to the file where this Realm is persisted.
public var path: String { return rlmRealm.path }
/// Indicates if this Realm was opened in read-only mode.
public var readOnly: Bool { return rlmRealm.readOnly }
/// The Schema used by this realm.
public var schema: Schema { return Schema(rlmRealm.schema) }
/// Returns the `Configuration` that was used to create this `Realm` instance.
public var configuration: Configuration { return Configuration.fromRLMRealmConfiguration(rlmRealm.configuration) }
/// Indicates if this Realm contains any objects.
public var isEmpty: Bool { return rlmRealm.isEmpty }
// MARK: Initializers
/**
Obtains a Realm instance with the given configuration. Defaults to the default Realm configuration,
which can be changed by setting `Realm.Configuration.defaultConfiguration`.
- parameter configuration: The configuration to use when creating the Realm instance.
- throws: An NSError if the Realm could not be initialized.
*/
public convenience init(configuration: Configuration = Configuration.defaultConfiguration) throws {
let rlmRealm = try RLMRealm(configuration: configuration.rlmConfiguration)
self.init(rlmRealm)
}
/**
Obtains a Realm instance persisted at the specified file path.
- parameter path: Path to the realm file.
- throws: An NSError if the Realm could not be initialized.
*/
public convenience init(path: String) throws {
var configuration = Configuration.defaultConfiguration
configuration.path = path
try self.init(configuration: configuration)
}
// MARK: Transactions
/**
Performs actions contained within the given block inside a write transation.
Write transactions cannot be nested, and trying to execute a write transaction
on a `Realm` which is already in a write transaction will throw an exception.
Calls to `write` from `Realm` instances in other threads will block
until the current write transaction completes.
Before executing the write transaction, `write` updates the `Realm` to the
latest Realm version, as if `refresh()` was called, and generates notifications
if applicable. This has no effect if the `Realm` was already up to date.
- parameter block: The block to be executed inside a write transaction.
- throws: An NSError if the transaction could not be written.
*/
public func write(@noescape block: (() -> Void)) throws {
try rlmRealm.transactionWithBlock(block)
}
/**
Begins a write transaction in a `Realm`.
Only one write transaction can be open at a time. Write transactions cannot be
nested, and trying to begin a write transaction on a `Realm` which is
already in a write transaction will throw an exception. Calls to
`beginWrite` from `Realm` instances in other threads will block
until the current write transaction completes.
Before beginning the write transaction, `beginWrite` updates the
`Realm` to the latest Realm version, as if `refresh()` was called, and
generates notifications if applicable. This has no effect if the `Realm`
was already up to date.
It is rarely a good idea to have write transactions span multiple cycles of
the run loop, but if you do wish to do so you will need to ensure that the
`Realm` in the write transaction is kept alive until the write transaction
is committed.
*/
public func beginWrite() {
rlmRealm.beginWriteTransaction()
}
/**
Commits all writes operations in the current write transaction, and ends
the transaction.
Calling this when not in a write transaction will throw an exception.
- throws: An NSError if the transaction could not be written.
*/
public func commitWrite() throws {
try rlmRealm.commitWriteTransaction()
}
/**
Reverts all writes made in the current write transaction and end the transaction.
This rolls back all objects in the Realm to the state they were in at the
beginning of the write transaction, and then ends the transaction.
This restores the data for deleted objects, but does not revive invalidated
object instances. Any `Object`s which were added to the Realm will be
invalidated rather than switching back to standalone objects.
Given the following code:
```swift
let oldObject = objects(ObjectType).first!
let newObject = ObjectType()
realm.beginWrite()
realm.add(newObject)
realm.delete(oldObject)
realm.cancelWrite()
```
Both `oldObject` and `newObject` will return `true` for `invalidated`,
but re-running the query which provided `oldObject` will once again return
the valid object.
Calling this when not in a write transaction will throw an exception.
*/
public func cancelWrite() {
rlmRealm.cancelWriteTransaction()
}
/**
Indicates if this Realm is currently in a write transaction.
- warning: Wrapping mutating operations in a write transaction if this property returns `false`
may cause a large number of write transactions to be created, which could negatively
impact Realm's performance. Always prefer performing multiple mutations in a single
transaction when possible.
*/
public var inWriteTransaction: Bool {
return rlmRealm.inWriteTransaction
}
// MARK: Adding and Creating objects
/**
Adds or updates an object to be persisted it in this Realm.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
When added, all (child) relationships referenced by this object will also be
added to the Realm if they are not already in it. If the object or any related
objects already belong to a different Realm an exception will be thrown. Use one
of the `create` functions to insert a copy of a persisted object into a different
Realm.
The object to be added must be valid and cannot have been previously deleted
from a Realm (i.e. `invalidated` must be false).
- parameter object: Object to be added to this Realm.
- parameter update: If true will try to update existing objects with the same primary key.
*/
public func add(object: Object, update: Bool = false) {
if update && object.objectSchema.primaryKeyProperty == nil {
throwRealmException("'\(object.objectSchema.className)' does not have a primary key and can not be updated")
}
RLMAddObjectToRealm(object, rlmRealm, update)
}
/**
Adds or updates objects in the given sequence to be persisted it in this Realm.
- see: add(_:update:)
- warning: This method can only be called during a write transaction.
- parameter objects: A sequence which contains objects to be added to this Realm.
- parameter update: If true will try to update existing objects with the same primary key.
*/
public func add<S: SequenceType where S.Generator.Element: Object>(objects: S, update: Bool = false) {
for obj in objects {
add(obj, update: update)
}
}
/**
Create an `Object` with the given value.
Creates or updates an instance of this object and adds it to the `Realm` populating
the object with the given value.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
- warning: This method can only be called during a write transaction.
- parameter type: The object type to create.
- parameter value: The value used to populate the object. This can be any key/value coding compliant
object, or a JSON dictionary such as those returned from the methods in `NSJSONSerialization`,
or an `Array` with one object for each persisted property. An exception will be
thrown if any required properties are not present and no default is set.
When passing in an `Array`, all properties must be present,
valid and in the same order as the properties defined in the model.
- parameter update: If true will try to update existing objects with the same primary key.
- returns: The created object.
*/
public func create<T: Object>(type: T.Type, value: AnyObject = [:], update: Bool = false) -> T {
let className = (type as Object.Type).className()
if update && schema[className]?.primaryKeyProperty == nil {
throwRealmException("'\(className)' does not have a primary key and can not be updated")
}
return unsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, className, value, update), T.self)
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `create(_:value:update:)`.
Creates or updates an object with the given class name and adds it to the `Realm`, populating
the object with the given value.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
- warning: This method can only be called during a write transaction.
- parameter className: The class name of the object to create.
- parameter value: The value used to populate the object. This can be any key/value coding compliant
object, or a JSON dictionary such as those returned from the methods in `NSJSONSerialization`,
or an `Array` with one object for each persisted property. An exception will be
thrown if any required properties are not present and no default is set.
When passing in an `Array`, all properties must be present,
valid and in the same order as the properties defined in the model.
- parameter update: If true will try to update existing objects with the same primary key.
- returns: The created object.
:nodoc:
*/
public func dynamicCreate(className: String, value: AnyObject = [:], update: Bool = false) -> DynamicObject {
if update && schema[className]?.primaryKeyProperty == nil {
throwRealmException("'\(className)' does not have a primary key and can not be updated")
}
return unsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, className, value, update), DynamicObject.self)
}
// MARK: Deleting objects
/**
Deletes the given object from this Realm.
- warning: This method can only be called during a write transaction.
- parameter object: The object to be deleted.
*/
public func delete(object: Object) {
RLMDeleteObjectFromRealm(object, rlmRealm)
}
/**
Deletes the given objects from this Realm.
- warning: This method can only be called during a write transaction.
- parameter objects: The objects to be deleted. This can be a `List<Object>`, `Results<Object>`,
or any other enumerable SequenceType which generates Object.
*/
public func delete<S: SequenceType where S.Generator.Element: Object>(objects: S) {
for obj in objects {
delete(obj)
}
}
/**
Deletes the given objects from this Realm.
- warning: This method can only be called during a write transaction.
- parameter objects: The objects to be deleted. Must be `List<Object>`.
:nodoc:
*/
public func delete<T: Object>(objects: List<T>) {
rlmRealm.deleteObjects(objects._rlmArray)
}
/**
Deletes the given objects from this Realm.
- warning: This method can only be called during a write transaction.
- parameter objects: The objects to be deleted. Must be `Results<Object>`.
:nodoc:
*/
public func delete<T: Object>(objects: Results<T>) {
rlmRealm.deleteObjects(objects.rlmResults)
}
/**
Deletes all objects from this Realm.
- warning: This method can only be called during a write transaction.
*/
public func deleteAll() {
RLMDeleteAllObjectsFromRealm(rlmRealm)
}
// MARK: Object Retrieval
/**
Returns all objects of the given type in the Realm.
- parameter type: The type of the objects to be returned.
- returns: All objects of the given type in Realm.
*/
public func objects<T: Object>(type: T.Type) -> Results<T> {
return Results<T>(RLMGetObjects(rlmRealm, (type as Object.Type).className(), nil))
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `objects(type:)`.
Returns all objects for a given class name in the Realm.
- warning: This method is useful only in specialized circumstances.
- parameter className: The class name of the objects to be returned.
- returns: All objects for the given class name as dynamic objects
:nodoc:
*/
public func dynamicObjects(className: String) -> Results<DynamicObject> {
return Results<DynamicObject>(RLMGetObjects(rlmRealm, className, nil))
}
/**
Get an object with the given primary key.
Returns `nil` if no object exists with the given primary key.
This method requires that `primaryKey()` be overridden on the given subclass.
- see: Object.primaryKey()
- parameter type: The type of the objects to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `type` or `nil` if an object with the given primary key does not exist.
*/
public func objectForPrimaryKey<T: Object>(type: T.Type, key: AnyObject) -> T? {
return unsafeBitCast(RLMGetObject(rlmRealm, (type as Object.Type).className(), key), Optional<T>.self)
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `objectForPrimaryKey(_:key:)`.
Get a dynamic object with the given class name and primary key.
Returns `nil` if no object exists with the given class name and primary key.
This method requires that `primaryKey()` be overridden on the given subclass.
- see: Object.primaryKey()
- warning: This method is useful only in specialized circumstances.
- parameter className: The class name of the object to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `DynamicObject` or `nil` if an object with the given primary key does not exist.
:nodoc:
*/
public func dynamicObjectForPrimaryKey(className: String, key: AnyObject) -> DynamicObject? {
return unsafeBitCast(RLMGetObject(rlmRealm, className, key), Optional<DynamicObject>.self)
}
// MARK: Notifications
/**
Add a notification handler for changes in this Realm.
Notification handlers are called after each write transaction is committed,
either on the current thread or other threads. The block is called on the
same thread as they were added on, and can only be added on threads which
are currently within a run loop. Unless you are specifically creating and
running a run loop on a background thread, this normally will only be the
main thread.
- parameter block: A block which is called to process Realm notifications.
It receives the following parameters:
- `Notification`: The incoming notification.
- `Realm`: The realm for which this notification occurred.
- returns: A notification token which can later be passed to `removeNotification(_:)`
to remove this notification.
*/
public func addNotificationBlock(block: NotificationBlock) -> NotificationToken {
return rlmRealm.addNotificationBlock(rlmNotificationBlockFromNotificationBlock(block))
}
/**
Remove a previously registered notification handler using the token returned
from `addNotificationBlock(_:)`
- parameter notificationToken: The token returned from `addNotificationBlock(_:)`
corresponding to the notification block to remove.
*/
public func removeNotification(notificationToken: NotificationToken) {
rlmRealm.removeNotification(notificationToken)
}
// MARK: Autorefresh and Refresh
/**
Whether this Realm automatically updates when changes happen in other threads.
If set to `true` (the default), changes made on other threads will be reflected
in this Realm on the next cycle of the run loop after the changes are
committed. If set to `false`, you must manually call `refresh()` on the Realm to
update it to get the latest version.
Note that by default, background threads do not have an active run loop and you
will need to manually call `refresh()` in order to update to the latest version,
even if `autorefresh` is set to `true`.
Even with this enabled, you can still call `refresh()` at any time to update the
Realm before the automatic refresh would occur.
Notifications are sent when a write transaction is committed whether or not
this is enabled.
Disabling this on a `Realm` without any strong references to it will not
have any effect, and it will switch back to YES the next time the `Realm`
object is created. This is normally irrelevant as it means that there is
nothing to refresh (as persisted `Object`s, `List`s, and `Results` have strong
references to the containing `Realm`), but it means that setting
`Realm().autorefresh = false` in
`application(_:didFinishLaunchingWithOptions:)` and only later storing Realm
objects will not work.
Defaults to true.
*/
public var autorefresh: Bool {
get {
return rlmRealm.autorefresh
}
set {
rlmRealm.autorefresh = newValue
}
}
/**
Update a `Realm` and outstanding objects to point to the most recent
data for this `Realm`.
- returns: Whether the realm had any updates.
Note that this may return true even if no data has actually changed.
*/
public func refresh() -> Bool {
return rlmRealm.refresh()
}
// MARK: Invalidation
/**
Invalidate all `Object`s and `Results` read from this Realm.
A Realm holds a read lock on the version of the data accessed by it, so
that changes made to the Realm on different threads do not modify or delete the
data seen by this Realm. Calling this method releases the read lock,
allowing the space used on disk to be reused by later write transactions rather
than growing the file. This method should be called before performing long
blocking operations on a background thread on which you previously read data
from the Realm which you no longer need.
All `Object`, `Results` and `List` instances obtained from this
`Realm` on the current thread are invalidated, and can not longer be used.
The `Realm` itself remains valid, and a new read transaction is implicitly
begun the next time data is read from the Realm.
Calling this method multiple times in a row without reading any data from the
Realm, or before ever reading any data from the Realm is a no-op. This method
cannot be called on a read-only Realm.
*/
public func invalidate() {
rlmRealm.invalidate()
}
// MARK: Writing a Copy
/**
Write an encrypted and compacted copy of the Realm to the given path.
The destination file cannot already exist.
Note that if this is called from within a write transaction it writes the
*current* data, and not data when the last write transaction was committed.
- parameter path: Path to save the Realm to.
- parameter encryptionKey: Optional 64-byte encryption key to encrypt the new file with.
- throws: An NSError if the copy could not be written.
*/
public func writeCopyToPath(path: String, encryptionKey: NSData? = nil) throws {
if let encryptionKey = encryptionKey {
try rlmRealm.writeCopyToPath(path, encryptionKey: encryptionKey)
} else {
try rlmRealm.writeCopyToPath(path)
}
}
// MARK: Internal
internal var rlmRealm: RLMRealm
internal init(_ rlmRealm: RLMRealm) {
self.rlmRealm = rlmRealm
}
}
// MARK: Equatable
extension Realm: Equatable { }
/// Returns whether the two realms are equal.
public func == (lhs: Realm, rhs: Realm) -> Bool { // swiftlint:disable:this valid_docs
return lhs.rlmRealm == rhs.rlmRealm
}
// MARK: Notifications
/// A notification due to changes to a realm.
public enum Notification: String {
/**
Posted when the data in a realm has changed.
DidChange is posted after a realm has been refreshed to reflect a write transaction, i.e. when
an autorefresh occurs, `refresh()` is called, after an implicit refresh from
`write(_:)`/`beginWrite()`, and after a local write transaction is committed.
*/
case DidChange = "RLMRealmDidChangeNotification"
/**
Posted when a write transaction has been committed to a Realm on a different thread for the same
file. This is not posted if `autorefresh` is enabled or if the Realm is refreshed before the
notification has a chance to run.
Realms with autorefresh disabled should normally have a handler for this notification which
calls `refresh()` after doing some work.
While not refreshing is allowed, it may lead to large Realm files as Realm has to keep an extra
copy of the data for the un-refreshed Realm.
*/
case RefreshRequired = "RLMRealmRefreshRequiredNotification"
}
/// Closure to run when the data in a Realm was modified.
public typealias NotificationBlock = (notification: Notification, realm: Realm) -> Void
internal func rlmNotificationBlockFromNotificationBlock(notificationBlock: NotificationBlock) -> RLMNotificationBlock {
return { rlmNotification, rlmRealm in
return notificationBlock(notification: Notification(rawValue: rlmNotification)!, realm: Realm(rlmRealm))
}
}
| mit | c2a1a0a8ece9fc8a68b09b0e28a6bf6c | 38.488038 | 120 | 0.697363 | 4.936005 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/WalletPayload/Sources/WalletPayloadDataKit/Network/Clients/CreateWallletClient.swift | 1 | 3552 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Foundation
import NetworkKit
import WalletPayloadKit
protocol CreateWalletClientAPI {
func createWallet(
email: String,
payload: WalletCreationPayload,
recaptchaToken: String?,
siteKey: String
) -> AnyPublisher<Void, NetworkError>
}
final class CreateWalletClient: CreateWalletClientAPI {
private let networkAdapter: NetworkAdapterAPI
private let requestBuilder: RequestBuilder
private let apiCodeProvider: () -> String
init(
networkAdapter: NetworkAdapterAPI,
requestBuilder: RequestBuilder,
apiCodeProvider: @escaping () -> String
) {
self.networkAdapter = networkAdapter
self.requestBuilder = requestBuilder
self.apiCodeProvider = apiCodeProvider
}
func createWallet(
email: String,
payload: WalletCreationPayload,
recaptchaToken: String?,
siteKey: String
) -> AnyPublisher<Void, NetworkError> {
var parameters = provideDefaultParameters(
with: email,
time: Int(Date().timeIntervalSince1970 * 1000.0)
)
if let recaptchaToken = recaptchaToken {
parameters.append(
URLQueryItem(
name: "captcha",
value: recaptchaToken
)
)
parameters.append(
URLQueryItem(
name: "siteKey",
value: siteKey
)
)
}
let wrapperParameters = provideWrapperParameters(from: payload)
let body = RequestBuilder.body(from: parameters + wrapperParameters)
let request = requestBuilder.post(
path: ["wallet"],
body: body,
contentType: .formUrlEncoded
)!
return networkAdapter.perform(request: request)
}
func provideDefaultParameters(with email: String, time: Int) -> [URLQueryItem] {
[
URLQueryItem(
name: "method",
value: "insert"
),
URLQueryItem(
name: "ct",
value: String(time)
),
URLQueryItem(
name: "email",
value: email
),
URLQueryItem(
name: "format",
value: "plain"
),
URLQueryItem(
name: "api_code",
value: apiCodeProvider()
)
]
}
func provideWrapperParameters(from payload: WalletCreationPayload) -> [URLQueryItem] {
[
URLQueryItem(
name: "guid",
value: payload.guid
),
URLQueryItem(
name: "sharedKey",
value: payload.sharedKey
),
URLQueryItem(
name: "checksum",
value: payload.checksum
),
URLQueryItem(
name: "language",
value: payload.language
),
URLQueryItem(
name: "length",
value: String(payload.length)
),
URLQueryItem(
name: "old_checksum",
value: payload.oldChecksum
),
URLQueryItem(
name: "payload",
value: String(decoding: payload.innerPayload, as: UTF8.self)
)
]
}
}
| lgpl-3.0 | 0b8d62fa0efc1a44d28a50beded00c44 | 27.869919 | 90 | 0.511405 | 5.636508 | false | false | false | false |
kaojohnny/CoreStore | Sources/Migrating/MigrationChain.swift | 1 | 9049 | //
// MigrationChain.swift
// CoreStore
//
// Copyright © 2015 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - MigrationChain
/**
A `MigrationChain` indicates the sequence of model versions to be used as the order for progressive migrations. This is typically passed to the `DataStack` initializer and will be applied to all stores added to the `DataStack` with `addSQLiteStore(...)` and its variants.
Initializing with empty values (either `nil`, `[]`, or `[:]`) instructs the `DataStack` to use the .xcdatamodel's current version as the final version, and to disable progressive migrations:
```
let dataStack = DataStack(migrationChain: nil)
```
This means that the mapping model will be computed from the store's version straight to the `DataStack`'s model version.
To support progressive migrations, specify the linear order of versions:
```
let dataStack = DataStack(migrationChain:
["MyAppModel", "MyAppModelV2", "MyAppModelV3", "MyAppModelV4"])
```
or for more complex migration paths, a version tree that maps the key-values to the source-destination versions:
```
let dataStack = DataStack(migrationChain: [
"MyAppModel": "MyAppModelV3",
"MyAppModelV2": "MyAppModelV4",
"MyAppModelV3": "MyAppModelV4"
])
```
This allows for different migration paths depending on the starting version. The example above resolves to the following paths:
- MyAppModel-MyAppModelV3-MyAppModelV4
- MyAppModelV2-MyAppModelV4
- MyAppModelV3-MyAppModelV4
The `MigrationChain` is validated when passed to the `DataStack` and unless it is empty, will raise an assertion if any of the following conditions are met:
- a version appears twice in an array
- a version appears twice as a key in a dictionary literal
- a loop is found in any of the paths
*/
public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, DictionaryLiteralConvertible, ArrayLiteralConvertible, Equatable {
/**
Initializes the `MigrationChain` with empty values, which instructs the `DataStack` to use the .xcdatamodel's current version as the final version, and to disable progressive migrations.
*/
public init() {
self.versionTree = [:]
self.rootVersions = []
self.leafVersions = []
self.valid = true
}
/**
Initializes the `MigrationChain` with a single model version, which instructs the `DataStack` to use the the specified version as the final version, and to disable progressive migrations.
*/
public init(_ value: String) {
self.versionTree = [:]
self.rootVersions = [value]
self.leafVersions = [value]
self.valid = true
}
/**
Initializes the `MigrationChain` with a linear order of versions, which becomes the order of the `DataStack`'s progressive migrations.
*/
public init<T: CollectionType where T.Generator.Element == String, T.Index: BidirectionalIndexType>(_ elements: T) {
CoreStore.assert(Set(elements).count == Array(elements).count, "\(cs_typeName(MigrationChain))'s migration chain could not be created due to duplicate version strings.")
var lastVersion: String?
var versionTree = [String: String]()
var valid = true
for version in elements {
if let lastVersion = lastVersion,
let _ = versionTree.updateValue(version, forKey: lastVersion) {
valid = false
}
lastVersion = version
}
self.versionTree = versionTree
self.rootVersions = Set([elements.first].flatMap { $0 == nil ? [] : [$0!] })
self.leafVersions = Set([elements.last].flatMap { $0 == nil ? [] : [$0!] })
self.valid = valid
}
/**
Initializes the `MigrationChain` with a version tree, which becomes the order of the `DataStack`'s progressive migrations.
*/
public init(_ elements: [(String, String)]) {
var valid = true
var versionTree = [String: String]()
elements.forEach { (sourceVersion, destinationVersion) in
guard let _ = versionTree.updateValue(destinationVersion, forKey: sourceVersion) else {
return
}
CoreStore.assert(false, "\(cs_typeName(MigrationChain))'s migration chain could not be created due to ambiguous version paths.")
valid = false
}
let leafVersions = Set(
elements
.filter { versionTree[$1] == nil }
.map { $1 }
)
let isVersionAmbiguous = { (start: String) -> Bool in
var checklist: Set<String> = [start]
var version = start
while let nextVersion = versionTree[version] where nextVersion != version {
if checklist.contains(nextVersion) {
CoreStore.assert(false, "\(cs_typeName(MigrationChain))'s migration chain could not be created due to looping version paths.")
return true
}
checklist.insert(nextVersion)
version = nextVersion
}
return false
}
self.versionTree = versionTree
self.rootVersions = Set(versionTree.keys).subtract(versionTree.values)
self.leafVersions = leafVersions
self.valid = valid && Set(versionTree.keys).union(versionTree.values).filter { isVersionAmbiguous($0) }.count <= 0
}
/**
Initializes the `MigrationChain` with a version tree, which becomes the order of the `DataStack`'s progressive migrations.
*/
public init(_ dictionary: [String: String]) {
self.init(dictionary.map { $0 })
}
// MARK: NilLiteralConvertible
public init(nilLiteral: ()) {
self.init()
}
// MARK: StringLiteralConvertible
public init(stringLiteral value: String) {
self.init(value)
}
// MARK: ExtendedGraphemeClusterLiteralConvertible
public init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
// MARK: UnicodeScalarLiteralConvertible
public init(unicodeScalarLiteral value: String) {
self.init(value)
}
// MARK: DictionaryLiteralConvertible
public init(dictionaryLiteral elements: (String, String)...) {
self.init(elements)
}
// MARK: ArrayLiteralConvertible
public init(arrayLiteral elements: String...) {
self.init(elements)
}
// MARK: Internal
internal let rootVersions: Set<String>
internal let leafVersions: Set<String>
internal let valid: Bool
internal var empty: Bool {
return self.versionTree.count <= 0
}
internal func contains(version: String) -> Bool {
return self.rootVersions.contains(version)
|| self.leafVersions.contains(version)
|| self.versionTree[version] != nil
}
internal func nextVersionFrom(version: String) -> String? {
guard let nextVersion = self.versionTree[version] where nextVersion != version else {
return nil
}
return nextVersion
}
// MARK: Private
private let versionTree: [String: String]
}
// MARK: - MigrationChain: Equatable
@warn_unused_result
public func == (lhs: MigrationChain, rhs: MigrationChain) -> Bool {
return lhs.versionTree == rhs.versionTree
&& lhs.rootVersions == rhs.rootVersions
&& lhs.leafVersions == rhs.leafVersions
&& lhs.valid == rhs.valid
}
| mit | 023e6e0ae0ae560a78eedba2aa3281ba | 33.403042 | 272 | 0.632515 | 5.120543 | false | false | false | false |
openium/SwiftiumKit | Tests/SwiftiumKitTests/Additions/UIKit/UIFontExtensionsTests.swift | 3 | 1059 | //
// UIFontExtensionsTests.swift
// SwiftiumKit
//
// Created by Richard Bergoin on 19/10/2016.
// Copyright © 2016 Openium. All rights reserved.
//
import XCTest
import SwiftiumKit
class UIFontExtensionsTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testFindFontHavingNameLike_shouldReturnEmptyList() {
// Given
let unavailableFontName = "An Unavailable Font Name"
// When
let findedFonts = UIFont.findFont(havingNameLike: unavailableFontName)
// Expect
XCTAssertEqual(findedFonts, [String]())
}
func testFindFontHavingNameLike_shouldReturnSomeNames() {
// Given
let fontName = "Helvetica Bold"
let expectedFoundName = "Helvetica-Bold"
// When
let findedFonts = UIFont.findFont(havingNameLike: fontName)
// Expect
XCTAssertTrue(findedFonts.contains(expectedFoundName))
}
}
| apache-2.0 | 3d5b61dc8624944fbc3ebb10d8bae5bf | 22.511111 | 78 | 0.619093 | 4.681416 | false | true | false | false |
Acidburn0zzz/firefox-ios | SyncTests/HistorySynchronizerTests.swift | 1 | 10424 | /* 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 Shared
import Account
import Storage
@testable import Sync
import XCGLogger
import XCTest
import SwiftyJSON
private let log = Logger.syncLogger
class MockSyncDelegate: SyncDelegate {
func displaySentTab(for url: URL, title: String, from deviceName: String?) {
}
}
class DBPlace: Place {
var isDeleted = false
var shouldUpload = false
var serverModified: Timestamp?
var localModified: Timestamp?
}
class MockSyncableHistory {
var wasReset: Bool = false
var places = [GUID: DBPlace]()
var remoteVisits = [GUID: Set<Visit>]()
var localVisits = [GUID: Set<Visit>]()
init() {
}
fileprivate func placeForURL(url: String) -> DBPlace? {
return findOneValue(places) { $0.url == url }
}
}
extension MockSyncableHistory: ResettableSyncStorage {
func resetClient() -> Success {
self.wasReset = true
return succeed()
}
}
extension MockSyncableHistory: SyncableHistory {
// TODO: consider comparing the timestamp to local visits, perhaps opting to
// not delete the local place (and instead to give it a new GUID) if the visits
// are newer than the deletion.
// Obviously this'll behave badly during reconciling on other devices:
// they might apply our new record first, renaming their local copy of
// the old record with that URL, and thus bring all the old visits back to life.
// Desktop just finds by GUID then deletes by URL.
func deleteByGUID(_ guid: GUID, deletedAt: Timestamp) -> Deferred<Maybe<()>> {
self.remoteVisits.removeValue(forKey: guid)
self.localVisits.removeValue(forKey: guid)
self.places.removeValue(forKey: guid)
return succeed()
}
func hasSyncedHistory() -> Deferred<Maybe<Bool>> {
let has = self.places.values.contains(where: { $0.serverModified != nil })
return deferMaybe(has)
}
/**
* This assumes that the provided GUID doesn't already map to a different URL!
*/
func ensurePlaceWithURL(_ url: String, hasGUID guid: GUID) -> Success {
// Find by URL.
if let existing = self.placeForURL(url: url) {
let p = DBPlace(guid: guid, url: url, title: existing.title)
p.isDeleted = existing.isDeleted
p.serverModified = existing.serverModified
p.localModified = existing.localModified
self.places.removeValue(forKey: existing.guid)
self.places[guid] = p
}
return succeed()
}
func storeRemoteVisits(_ visits: [Visit], forGUID guid: GUID) -> Success {
// Strip out existing local visits.
// We trust that an identical timestamp and type implies an identical visit.
var remote = Set<Visit>(visits)
if let local = self.localVisits[guid] {
remote.subtract(local)
}
// Visits are only ever added.
if var r = self.remoteVisits[guid] {
r.formUnion(remote)
} else {
self.remoteVisits[guid] = remote
}
return succeed()
}
func insertOrUpdatePlace(_ place: Place, modified: Timestamp) -> Deferred<Maybe<GUID>> {
// See if we've already applied this one.
if let existingModified = self.places[place.guid]?.serverModified {
if existingModified == modified {
log.debug("Already seen unchanged record \(place.guid).")
return Deferred(value: Maybe(success: place.guid))
}
}
// Make sure that we collide with any matching URLs -- whether locally
// modified or not. Then overwrite the upstream and merge any local changes.
return self.ensurePlaceWithURL(place.url, hasGUID: place.guid)
>>> {
if let existingLocal = self.places[place.guid] {
if existingLocal.shouldUpload {
log.debug("Record \(existingLocal.guid) modified locally and remotely.")
log.debug("Local modified: \(existingLocal.localModified ??? "nil"); remote: \(modified).")
// Should always be a value if marked as changed.
if let localModified = existingLocal.localModified, localModified > modified {
// Nothing to do: it's marked as changed.
log.debug("Discarding remote non-visit changes!")
self.places[place.guid]?.serverModified = modified
return Deferred(value: Maybe(success: place.guid))
} else {
log.debug("Discarding local non-visit changes!")
self.places[place.guid]?.shouldUpload = false
}
} else {
log.debug("Remote record exists, but has no local changes.")
}
} else {
log.debug("Remote record doesn't exist locally.")
}
// Apply the new remote record.
let p = DBPlace(guid: place.guid, url: place.url, title: place.title)
p.localModified = Date.now()
p.serverModified = modified
p.isDeleted = false
self.places[place.guid] = p
return Deferred(value: Maybe(success: place.guid))
}
}
func getModifiedHistoryToUpload() -> Deferred<Maybe<[(Place, [Visit])]>> {
// TODO.
return deferMaybe([])
}
func getDeletedHistoryToUpload() -> Deferred<Maybe<[GUID]>> {
// TODO.
return deferMaybe([])
}
func markAsSynchronized(_: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> {
// TODO
return deferMaybe(0)
}
func markAsDeleted(_: [GUID]) -> Success {
// TODO
return succeed()
}
func onRemovedAccount() -> Success {
// TODO
return succeed()
}
func doneApplyingRecordsAfterDownload() -> Success {
return succeed()
}
func doneUpdatingMetadataAfterUpload() -> Success {
return succeed()
}
}
class HistorySynchronizerTests: XCTestCase {
private func applyRecords(records: [Record<HistoryPayload>], toStorage storage: SyncableHistory & ResettableSyncStorage) -> (synchronizer: HistorySynchronizer, prefs: Prefs, scratchpad: Scratchpad) {
let delegate = MockSyncDelegate()
// We can use these useless values because we're directly injecting decrypted
// payloads; no need for real keys etc.
let prefs = MockProfilePrefs()
let scratchpad = Scratchpad(b: KeyBundle.random(), persistingTo: prefs)
let synchronizer = HistorySynchronizer(scratchpad: scratchpad, delegate: delegate, basePrefs: prefs, why: .scheduled)
let expectation = self.expectation(description: "Waiting for application.")
var succeeded = false
synchronizer.applyIncomingToStorage(storage, records: records)
.upon({ result in
succeeded = result.isSuccess
expectation.fulfill()
})
waitForExpectations(timeout: 10, handler: nil)
XCTAssertTrue(succeeded, "Application succeeded.")
return (synchronizer, prefs, scratchpad)
}
func testRecordSerialization() {
let id = "abcdefghi"
let modified: Timestamp = 0 // Ignored in upload serialization.
let sortindex = 1
let ttl = 12345
let json: JSON = JSON([
"id": id,
"visits": [],
"histUri": "http://www.slideshare.net/swadpasc/bpm-edu-netseminarscepwithreactionrulemlprova",
"title": "Semantic Complex Event Processing with \(Character(UnicodeScalar(11)))Reaction RuleML 1.0 and Prova",
])
let payload = HistoryPayload(json)
let record = Record<HistoryPayload>(id: id, payload: payload, modified: modified, sortindex: sortindex, ttl: ttl)
let k = KeyBundle.random()
let s = keysPayloadSerializer(keyBundle: k, { (x: HistoryPayload) -> JSON in x.json })
let converter = { (x: JSON) -> HistoryPayload in HistoryPayload(x) }
let f = keysPayloadFactory(keyBundle: k, converter)
let serialized = s(record)!
let envelope = EnvelopeJSON(serialized)
// With a badly serialized payload, we get null JSON!
let p = f(envelope.payload)
XCTAssertFalse(p!.json.isNull())
// When we round-trip, the payload should be valid, and we'll get a record here.
let roundtripped = Record<HistoryPayload>.fromEnvelope(envelope, payloadFactory: f)
XCTAssertNotNil(roundtripped)
}
func testApplyRecords() {
let earliest = Date.now()
let empty = MockSyncableHistory()
let noRecords = [Record<HistoryPayload>]()
// Apply no records.
let _ = self.applyRecords(records: noRecords, toStorage: empty)
// Hey look! Nothing changed.
XCTAssertTrue(empty.places.isEmpty)
XCTAssertTrue(empty.remoteVisits.isEmpty)
XCTAssertTrue(empty.localVisits.isEmpty)
// Apply one remote record.
let jA = "{\"id\":\"aaaaaa\",\"histUri\":\"http://foo.com/\",\"title\": \"ñ\",\"visits\":[{\"date\":1222222222222222,\"type\":1}]}"
let pA = HistoryPayload.fromJSON(JSON(parseJSON: jA))!
let rA = Record<HistoryPayload>(id: "aaaaaa", payload: pA, modified: earliest + 10000, sortindex: 123, ttl: 1000000)
let (_, prefs, _) = self.applyRecords(records: [rA], toStorage: empty)
// The record was stored. This is checking our mock implementation, but real storage should work, too!
XCTAssertEqual(1, empty.places.count)
XCTAssertEqual(1, empty.remoteVisits.count)
XCTAssertEqual(1, empty.remoteVisits["aaaaaa"]!.count)
XCTAssertTrue(empty.localVisits.isEmpty)
// Test resetting now that we have a timestamp.
XCTAssertFalse(empty.wasReset)
XCTAssertTrue(HistorySynchronizer.resetSynchronizerWithStorage(empty, basePrefs: prefs, collection: "history").value.isSuccess)
XCTAssertTrue(empty.wasReset)
}
}
| mpl-2.0 | 058674d200e4abd8bec0832ce8528169 | 37.747212 | 203 | 0.616425 | 4.796595 | false | false | false | false |
Acidburn0zzz/firefox-ios | Client/Frontend/Intro/IntroScreenWelcomeView.swift | 1 | 8755 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import SnapKit
import Shared
class IntroScreenWelcomeView: UIView, CardTheme {
// Private vars
private var fxTextThemeColour: UIColor {
// For dark theme we want to show light colours and for light we want to show dark colours
return theme == .dark ? .white : .black
}
private var fxBackgroundThemeColour: UIColor {
return theme == .dark ? UIColor.Firefox.DarkGrey10 : .white
}
// Orientation independent screen size
private let screenSize = DeviceInfo.screenSizeOrientationIndependent()
// Views
private lazy var titleImageViewPage1: UIImageView = {
let imgView = UIImageView(image: UIImage(named: "tour-Welcome"))
imgView.contentMode = .center
imgView.clipsToBounds = true
return imgView
}()
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.text = Strings.CardTitleWelcome
label.textColor = fxTextThemeColour
label.font = UIFont.systemFont(ofSize: 32, weight: .bold)
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
return label
}()
private lazy var subTitleLabelPage1: UILabel = {
let fontSize: CGFloat = screenSize.width <= 320 ? 16 : 20
let label = UILabel()
label.text = Strings.CardTextWelcome
label.textColor = fxTextThemeColour
label.font = UIFont.systemFont(ofSize: fontSize)
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
label.numberOfLines = 2
return label
}()
private var closeButton: UIButton = {
let closeButton = UIButton()
closeButton.setImage(UIImage(named: "close-large"), for: .normal)
if #available(iOS 13, *) {
closeButton.tintColor = .secondaryLabel
} else {
closeButton.tintColor = .black
}
return closeButton
}()
private lazy var signUpButton: UIButton = {
let button = UIButton()
button.accessibilityIdentifier = "signUpOnboardingButton"
button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .bold)
button.layer.cornerRadius = 10
button.backgroundColor = UIColor.Photon.Blue50
button.setTitle(Strings.IntroSignUpButtonTitle, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.textAlignment = .center
return button
}()
private lazy var signInButton: UIButton = {
let button = UIButton()
button.accessibilityIdentifier = "signInOnboardingButton"
button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .bold)
button.layer.cornerRadius = 10
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.gray.cgColor
button.backgroundColor = .clear
button.setTitle(Strings.IntroSignInButtonTitle, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
button.setTitleColor(UIColor.Photon.Blue50, for: .normal)
button.titleLabel?.textAlignment = .center
return button
}()
private lazy var nextButton: UIButton = {
let button = UIButton()
button.setTitle(Strings.IntroNextButtonTitle, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
button.setTitleColor(UIColor.Photon.Blue50, for: .normal)
button.titleLabel?.textAlignment = .center
button.accessibilityIdentifier = "nextOnboardingButton"
return button
}()
// Helper views
let main2panel = UIStackView()
let imageHolder = UIView()
let bottomHolder = UIView()
// Closure delegates
var closeClosure: (() -> Void)?
var nextClosure: (() -> Void)?
var signUpClosure: (() -> Void)?
var signInClosure: (() -> Void)?
// Basic variables
private var currentPage = 0
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Initializer
override init(frame: CGRect) {
super.init(frame: frame)
initialViewSetup()
}
// MARK: View setup
private func initialViewSetup() {
// Background colour setup
backgroundColor = fxBackgroundThemeColour
// View setup
main2panel.axis = .vertical
main2panel.distribution = .fillEqually
addSubview(main2panel)
main2panel.snp.makeConstraints { make in
make.left.right.equalToSuperview()
make.top.equalTo(safeArea.top)
make.bottom.equalTo(safeArea.bottom)
}
main2panel.addArrangedSubview(imageHolder)
imageHolder.addSubview(titleImageViewPage1)
titleImageViewPage1.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
main2panel.addArrangedSubview(bottomHolder)
[titleLabel, subTitleLabelPage1, signUpButton, signInButton, nextButton].forEach {
bottomHolder.addSubview($0)
}
titleLabel.snp.makeConstraints { make in
make.left.right.equalToSuperview().inset(10)
make.top.equalToSuperview()
}
subTitleLabelPage1.snp.makeConstraints { make in
make.left.right.equalToSuperview().inset(35)
make.top.equalTo(titleLabel.snp.bottom)
}
let buttonEdgeInset = 15
let buttonHeight = 46
let buttonSpacing = 16
signUpButton.addTarget(self, action: #selector(showSignUpFlow), for: .touchUpInside)
signUpButton.snp.makeConstraints { make in
make.left.right.equalToSuperview().inset(buttonEdgeInset)
make.bottom.equalTo(signInButton.snp.top).offset(-buttonSpacing)
make.height.equalTo(buttonHeight)
}
signInButton.addTarget(self, action: #selector(showEmailLoginFlow), for: .touchUpInside)
signInButton.snp.makeConstraints { make in
make.left.right.equalToSuperview().inset(buttonEdgeInset)
make.bottom.equalTo(nextButton.snp.top).offset(-buttonSpacing)
make.height.equalTo(buttonHeight)
}
nextButton.addTarget(self, action: #selector(nextAction), for: .touchUpInside)
nextButton.snp.makeConstraints { make in
make.left.right.equalToSuperview().inset(buttonEdgeInset)
// On large iPhone screens, bump this up from the bottom
let offset: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 20 : (screenSize.height > 800 ? 60 : 20)
make.bottom.equalToSuperview().inset(offset)
make.height.equalTo(buttonHeight)
}
addSubview(closeButton)
closeButton.addTarget(self, action: #selector(startBrowsing), for: .touchUpInside)
closeButton.snp.makeConstraints { make in
make.top.equalToSuperview().offset(buttonEdgeInset)
make.right.equalToSuperview().inset(buttonEdgeInset)
}
if #available(iOS 13, *) {
closeButton.tintColor = .secondaryLabel
} else {
closeButton.tintColor = .black
}
}
// MARK: Button Actions
@objc func startBrowsing() {
LeanPlumClient.shared.track(event: .dismissedOnboarding, withParameters: ["dismissedOnSlide": String(currentPage)])
TelemetryWrapper.recordEvent(category: .action, method: .press, object: .dismissedOnboarding, extras: ["slide-num": currentPage])
closeClosure?()
}
@objc func showEmailLoginFlow() {
LeanPlumClient.shared.track(event: .dismissedOnboardingShowLogin, withParameters: ["dismissedOnSlide": String(currentPage)])
TelemetryWrapper.recordEvent(category: .action, method: .press, object: .dismissedOnboardingEmailLogin, extras: ["slide-num": currentPage])
signInClosure?()
}
@objc func showSignUpFlow() {
LeanPlumClient.shared.track(event: .dismissedOnboardingShowSignUp, withParameters: ["dismissedOnSlide": String(currentPage)])
TelemetryWrapper.recordEvent(category: .action, method: .press, object: .dismissedOnboardingSignUp, extras: ["slide-num": currentPage])
signUpClosure?()
}
@objc private func nextAction() {
nextClosure?()
}
@objc private func dismissAnimated() {
closeClosure?()
}
}
| mpl-2.0 | 70afe30dbb077f15b126a74b08e11466 | 39.72093 | 147 | 0.653569 | 4.902016 | false | false | false | false |
nathawes/swift | test/IRGen/protocol_metadata.swift | 10 | 4157 | // RUN: %target-swift-frontend -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s -DINT=i%target-ptrsize
// REQUIRES: CPU=x86_64
protocol A { func a() }
protocol B { func b() }
protocol C : class { func c() }
@objc protocol O { func o() }
@objc protocol OPT {
@objc optional func opt()
@objc optional static func static_opt()
@objc optional var prop: O { get }
@objc optional subscript (x: O) -> O { get }
}
protocol AB : A, B { func ab() }
protocol ABO : A, B, O { func abo() }
// CHECK: [[A_NAME:@.*]] = private constant [2 x i8] c"A\00"
// CHECK-LABEL: @"$s17protocol_metadata1AMp" = hidden constant
// CHECK-SAME: i32 65603,
// CHECK-SAME: @"$s17protocol_metadataMXM"
// CHECK-SAME: [[A_NAME]]
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1,
// CHECK-SAME: i32 0,
// CHECK-SAME: }
// CHECK: [[B_NAME:@.*]] = private constant [2 x i8] c"B\00"
// CHECK-LABEL: @"$s17protocol_metadata1BMp" = hidden constant
// CHECK-SAME: i32 65603,
// CHECK-SAME: @"$s17protocol_metadataMXM"
// CHECK-SAME: i32 0,
// CHECK-SAME: [[B_NAME]]
// CHECK-SAME: i32 1,
// CHECK: }
// CHECK: [[C_NAME:@.*]] = private constant [2 x i8] c"C\00"
// CHECK-LABEL: @"$s17protocol_metadata1CMp" = hidden constant
// CHECK-SAME: i32 67,
// CHECK-SAME: @"$s17protocol_metadataMXM"
// CHECK-SAME: [[C_NAME]]
// CHECK-SAME: i32 1,
// CHECK-SAME: i32 1,
// CHECK-SAME: i32 0,
// AnyObject layout constraint
// CHECK-SAME: i32 31,
// CHECK-SAME: @"symbolic x"
// CHECK-SAME: i32 0
// CHECK-SAME: }
// -- @objc protocol O uses ObjC symbol mangling and layout
// CHECK-LABEL: @_PROTOCOL__TtP17protocol_metadata1O_ = internal constant
// CHECK-SAME: @_PROTOCOL_INSTANCE_METHODS__TtP17protocol_metadata1O_,
// -- size, flags: 1 = Swift
// CHECK-SAME: i32 96, i32 1
// CHECK-SAME: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata1O_
// CHECK-SAME: }
// -- @objc protocol OPT uses ObjC symbol mangling and layout
// CHECK: @_PROTOCOL__TtP17protocol_metadata3OPT_ = internal constant { {{.*}} i32, [4 x i8*]*, i8*, i8* } {
// CHECK-SAME: @_PROTOCOL_INSTANCE_METHODS_OPT__TtP17protocol_metadata3OPT_,
// CHECK-SAME: @_PROTOCOL_CLASS_METHODS_OPT__TtP17protocol_metadata3OPT_,
// -- size, flags: 1 = Swift
// CHECK-SAME: i32 96, i32 1
// CHECK-SAME: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata3OPT_
// CHECK-SAME: }
// -- inheritance lists for refined protocols
// CHECK: [[AB_NAME:@.*]] = private constant [3 x i8] c"AB\00"
// CHECK: @"$s17protocol_metadata2ABMp" = hidden constant
// CHECK-SAME: i32 65603,
// CHECK-SAME: @"$s17protocol_metadataMXM"
// CHECK-SAME: [[AB_NAME]]
// CHECK-SAME: i32 2, i32 3, i32 0
// Inheritance from A
// CHECK-SAME: i32 128,
// CHECK-SAME: @"symbolic x"
// CHECK-SAME: @"$s17protocol_metadata1AMp"
// Inheritance from B
// CHECK-SAME: i32 128,
// CHECK-SAME: @"symbolic x"
// CHECK-SAME: @"$s17protocol_metadata1BMp"
// CHECK: }
protocol Comprehensive {
associatedtype Assoc : A
init()
func instanceMethod()
static func staticMethod()
var instance: Assoc { get set }
static var global: Assoc { get set }
}
// CHECK: [[COMPREHENSIVE_ASSOC_NAME:@.*]] = private constant [6 x i8] c"Assoc\00"
// CHECK: @"$s17protocol_metadata13ComprehensiveMp" = hidden constant
// CHECK-SAME: i32 65603
// CHECK-SAME: i32 1
// CHECK-SAME: i32 11,
// CHECK-SAME: i32 trunc
// CHECK-SAME: [6 x i8]* [[COMPREHENSIVE_ASSOC_NAME]]
// CHECK-SAME: %swift.protocol_requirement { i32 8, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 7, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 2, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 17, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 1, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 19, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 20, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 22, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 3, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 4, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 6, i32 0 }
| apache-2.0 | 3761ff5097991cde3db279d2801f50a0 | 33.932773 | 162 | 0.651431 | 2.925405 | false | false | false | false |
poetmountain/MotionMachine | Sources/EasingTypes/EasingBounce.swift | 1 | 3742 | //
// EasingBounce.swift
// MotionMachine
//
// Created by Brett Walker on 5/3/16.
// Copyright © 2016-2018 Poet & Mountain, LLC. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/**
* EasingBounce provides easing equations that have successively smaller value peaks, like a bouncing ball.
*
* - remark: See http://easings.net for visual examples.
*
*/
public struct EasingBounce {
static let magic100 = 1.70158 * 10
public static func easeIn() -> EasingUpdateClosure {
func easing (_ elapsedTime: TimeInterval, startValue: Double, valueRange: Double, duration: TimeInterval) -> Double {
let easing_closure = EasingBounce.easeOut()
let time = duration - elapsedTime
let easing_value = valueRange - easing_closure(time, 0.0, valueRange, duration) + startValue
return easing_value
}
return easing
}
public static func easeOut() -> EasingUpdateClosure {
func easing (_ elapsedTime: TimeInterval, startValue: Double, valueRange: Double, duration: TimeInterval) -> Double {
var time = elapsedTime / duration
let easing_value: Double
if (time < (1/2.75)) {
easing_value = valueRange * (7.5625 * time*time) + startValue;
} else if (time < (2 / 2.75)) {
time -= (1.5 / 2.75);
easing_value = valueRange * (7.5625 * time*time + 0.75) + startValue;
} else if (time < (2.5/2.75)) {
time -= (2.25/2.75);
easing_value = valueRange * (7.5625 * time*time + 0.9375) + startValue;
} else {
time -= (2.625/2.75);
easing_value = valueRange * (7.5625 * time*time + 0.984375) + startValue;
}
return easing_value
}
return easing
}
public static func easeInOut() -> EasingUpdateClosure {
func easing (_ elapsedTime: TimeInterval, startValue: Double, valueRange: Double, duration: TimeInterval) -> Double {
let easing_value: Double
let easing_closure = EasingBounce.easeOut()
if (elapsedTime < (duration * 0.5)) {
easing_value = easing_closure((elapsedTime*2), 0, valueRange, duration) * 0.5 + startValue;
} else {
easing_value = easing_closure((elapsedTime*2-duration), 0, valueRange, duration) * 0.5 + (valueRange*0.5) + startValue;
}
return easing_value
}
return easing
}
}
| mit | ba7dce61a64463dcde8f886c8f96a9c1 | 37.96875 | 135 | 0.612136 | 4.48024 | false | false | false | false |
Powermash/Ultron | Ultron/main.swift | 1 | 2071 | //
// main.swift
// Ultron
//
// Created by Romain Pouclet on 2014-12-08.
// Copyright (c) 2014 Romain Pouclet. All rights reserved.
//
import Foundation
let app = Application()
app.run()
//let endpoint = NSURL(string: "https://young-tundra-4558.herokuapp.com/index.php/match")!
//let keyboard = NSFileHandle.fileHandleWithStandardInput();
//
//func fetchMatch() {
// let task = NSURLSession.sharedSession().dataTaskWithURL(endpoint, completionHandler: { (data, response, error) -> Void in
// if (error != nil) {
// println("Got error fetching match \(error.localizedDescription)")
// return;
// }
//
// var error: NSError?
//
// if let fetchedMatch: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? NSDictionary! {
// let a = fetchedMatch.valueForKeyPath("character_a.name") as NSString!
// let b = fetchedMatch.valueForKeyPath("character_b.name") as NSString!
//
// println("\(a) (1) vs \(b) (2). Who wins?")
// print("> ")
//
// let inputData = keyboard.availableData
// var input: NSString
//
// if let input = NSString(data: inputData, encoding: NSUTF8StringEncoding) {
// println("Input was \(input)")
// switch input {
// case "1":
// println("User voted for \(a)")
// case "2":
// println("User voted for \(b)")
// default:
// println("Invalid answer")
// }
//
// // TODO send match
// fetchMatch()
// }
// } else {
// println("Unable to fetch match, got error \(error)")
// }
// })
//
// task.resume()
//}
//
//fetchMatch()
//
//// Meh?
//while NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as NSDate) {}
| mit | 43c7b25bc4ccb5f9e9bde14b41dd706d | 32.95082 | 166 | 0.531144 | 4.158635 | false | false | false | false |
anzfactory/TwitterClientCLI | Sources/TwitterClientCore/Extension/URL.swift | 1 | 373 | //
// URL.swift
// Spectre
//
// Created by shingo asato on 2017/10/05.
//
import Foundation
extension URL {
init(tweet: Tweet) {
var components = URLComponents()
components.scheme = "https"
components.host = "twitter.com"
components.path = "/\(tweet.user.screenName)/status/\(tweet.id)"
self = components.url!
}
}
| mit | 83350d31a05b7bd79891e1cfb1c367cc | 18.631579 | 72 | 0.592493 | 3.656863 | false | false | false | false |
msdgwzhy6/iOS8-day-by-day | 25-notification-actions/NotifyTimely/NotifyTimely/PaddedLabel.swift | 22 | 958 | //
// Copyright 2014 Scott Logic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
@IBDesignable
class PaddedLabel : UILabel {
@IBInspectable
var verticalPadding: CGFloat = 20.0
@IBInspectable
var horizontalPadding: CGFloat = 20.0
override func intrinsicContentSize() -> CGSize {
var size = super.intrinsicContentSize()
size.height += verticalPadding
size.width += horizontalPadding
return size
}
} | apache-2.0 | c8570f81046307ab42aa3d0f0558e73a | 27.205882 | 75 | 0.730689 | 4.476636 | false | false | false | false |
xiaomudegithub/iosstar | iOSStar/AppAPI/DisCoverAPI/DiscoverSocketAPI.swift | 3 | 3791 | //
// DiscoverSocketAPI.swift
// iOSStar
//
// Created by J-bb on 17/7/8.
// Copyright © 2017年 YunDian. All rights reserved.
//
import Foundation
class DiscoverSocketAPI:BaseSocketAPI, DiscoverAPI{
//明星互动和热度
func requestStarList(requestModel:StarSortListRequestModel,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .starList, model: requestModel)
startModelsRequest(packet, listName: "symbol_info", modelClass: StarSortListModel.self, complete: complete, error: error)
}
//抢购明星列表
func requestScrollStarList(requestModel:StarSortListRequestModel,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .starScrollList, model: requestModel)
startModelRequest(packet, modelClass: DiscoverListModel.self, complete: complete, error: error)
}
//请求剩余时间
func requestBuyRemainingTime(requestModel:BuyRemainingTimeRequestModel,complete: CompleteBlock?, error: ErrorBlock?) {
let packt = SocketDataPacket(opcode: .remainingTime, model: requestModel)
startModelRequest(packt, modelClass: BuyRemainingTimeModel.self, complete: complete, error: error)
}
//抢购明星信息
func requsetPanicBuyStarInfo(requestModel:PanicBuyRequestModel,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .panicBuyStarInfo, model: requestModel)
startModelRequest(packet, modelClass: PanicBuyInfoModel.self, complete: complete, error: error)
}
//明星介绍页信息
func requestStarDetailInfo(requestModel:StarDetaiInfoRequestModel,complete: CompleteBlock?, error: ErrorBlock? ) {
let packet = SocketDataPacket(opcode: .starDetailInfo, model: requestModel)
startModelRequest(packet, modelClass: StarIntroduceResult.self, complete: complete, error: error)
}
//抢购明星
func buyStarTime(requestModel:BuyStarTimeRequestModel,complete: CompleteBlock?, error: ErrorBlock?) {
let packet = SocketDataPacket(opcode: .panicBuy, model: requestModel)
startResultIntRequest(packet, complete: complete, error: error)
}
//视频问答
func videoAskQuestion(requestModel:AskRequestModel, complete: CompleteBlock?, error: ErrorBlock?){
let packet = SocketDataPacket(opcode: .askVideo, model: requestModel)
startModelRequest(packet, modelClass: ResultModel.self, complete: complete, error: error)
}
//语音问答
func useraskQuestion(requestModel:UserAskRequestModel, complete: CompleteBlock?, error: ErrorBlock?){
let packet = SocketDataPacket(opcode: .userask, model: requestModel)
startModelRequest(packet, modelClass: UserAskList.self, complete: complete, error: error)
}
func staraskQuestion(requestModel:StarAskRequestModel, complete: CompleteBlock?, error: ErrorBlock?){
let packet = SocketDataPacket(opcode: .starask, model: requestModel)
startModelRequest(packet, modelClass: UserAskList.self, complete: complete, error: error)
}
func peepAnswer(requestModel:PeepVideoOrvoice, complete: CompleteBlock?, error: ErrorBlock?){
let packet = SocketDataPacket(opcode: .qeepask, model: requestModel)
startModelRequest(packet, modelClass: ResultModel.self, complete: complete, error: error)
}
func requestStarDetail(requestModel:CirCleStarDetail,complete: CompleteBlock?, error: ErrorBlock?){
let packet = SocketDataPacket(opcode: .circleListdetail, model: requestModel)
startModelRequest(packet, modelClass: StarDetailCircle.self, complete: complete, error: error)
}
}
| gpl-3.0 | ef714d9d3316372be50b84d4d4452cb6 | 45.25 | 129 | 0.723243 | 4.373522 | false | false | false | false |
dnpp73/SimpleCamera | Sources/View/Parts/ZoomIndicatorButton.swift | 1 | 4182 | #if canImport(UIKit)
import UIKit
private extension UIImage {
convenience init?(color: UIColor, size: CGSize) {
if size.width <= 0 || size.height <= 0 {
self.init()
return nil
}
UIGraphicsBeginImageContext(size)
defer {
UIGraphicsEndImageContext()
}
let rect = CGRect(origin: CGPoint.zero, size: size)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
context.setFillColor(color.cgColor)
context.fill(rect)
guard let image = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else {
return nil
}
self.init(cgImage: image)
}
}
internal final class ZoomIndicatorButton: UIButton {
// MARK: - UIView Extension
@IBInspectable dynamic var cornerRadius: CGFloat {
get {
layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable dynamic var borderColor: UIColor? {
get {
if let cgColor = layer.borderColor {
return UIColor(cgColor: cgColor)
} else {
return nil
}
}
set {
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable dynamic var borderWidth: CGFloat {
get {
layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
// MARK: - UIButton Extension
private func setBackgroundColor(_ color: UIColor?, for state: UIControl.State) {
if let color = color {
let image = UIImage(color: color, size: bounds.size)
setBackgroundImage(image, for: state)
} else {
setBackgroundImage(nil, for: state)
}
}
@IBInspectable dynamic var normalBackgroundColor: UIColor? {
get {
nil // dummy
}
set {
setBackgroundColor(newValue, for: .normal)
}
}
@IBInspectable dynamic var highlightedBackgroundColor: UIColor? {
get {
nil // dummy
}
set {
setBackgroundColor(newValue, for: .highlighted)
}
}
@IBInspectable dynamic var disabledBackgroundColor: UIColor? {
get {
nil // dummy
}
set {
setBackgroundColor(newValue, for: .disabled)
}
}
// MARK: - Initializer
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
updateTitleForCurrentZoomFactor()
SimpleCamera.shared.add(simpleCameraObserver: self)
}
// MARK: -
func updateTitleForCurrentZoomFactor() {
let zoomFactor = SimpleCamera.shared.zoomFactor
let zoomFactorString = String(format: "%.1f", zoomFactor)
let title: String
if zoomFactorString.hasSuffix(".0") {
let l = zoomFactorString.count - 2
title = zoomFactorString.prefix(l) + "x"
} else {
title = zoomFactorString + "x"
}
setTitle(title, for: .normal)
}
}
import AVFoundation
extension ZoomIndicatorButton: SimpleCameraObservable {
func simpleCameraDidStartRunning(simpleCamera: SimpleCamera) {}
func simpleCameraDidStopRunning(simpleCamera: SimpleCamera) {}
func simpleCameraDidChangeFocusPointOfInterest(simpleCamera: SimpleCamera) {}
func simpleCameraDidChangeExposurePointOfInterest(simpleCamera: SimpleCamera) {}
func simpleCameraDidResetFocusAndExposure(simpleCamera: SimpleCamera) {}
func simpleCameraDidSwitchCameraInput(simpleCamera: SimpleCamera) {}
// func simpleCameraSessionRuntimeError(simpleCamera: SimpleCamera, error: AVError) {}
// @available(iOS 9.0, *)
// func simpleCameraSessionWasInterrupted(simpleCamera: SimpleCamera, reason: AVCaptureSession.InterruptionReason) {}
func simpleCameraSessionInterruptionEnded(simpleCamera: SimpleCamera) {}
internal func simpleCameraDidChangeZoomFactor(simpleCamera: SimpleCamera) {
updateTitleForCurrentZoomFactor()
}
}
#endif
| mit | cbdcecea897819b9bbb7baf169cc0479 | 27.067114 | 120 | 0.611908 | 5.075243 | false | false | false | false |
noppoMan/SwiftKnex | Sources/Mysql/PacketStream.swift | 1 | 917 | //
// PacketStream.swift
// SwiftKnex
//
// Created by Yuki Takei on 2017/01/10.
//
//
import Foundation
typealias PacketStream = TCPStream
extension PacketStream {
func readHeader() throws -> (UInt32, Int) {
let b = try read(upTo: 3).uInt24()
let pn = try read(upTo: 1)[0]
return (b, Int(pn))
}
func readPacket() throws -> (Bytes, Int) {
let (len, packnr) = try readHeader()
var bytes = Bytes()
while bytes.count < Int(len) {
bytes.append(contentsOf: try read(upTo: Int(len)))
}
return (bytes, packnr)
}
func writeHeader(_ len: UInt32, pn: UInt8) throws {
try self.write([UInt8].UInt24Array(len) + [pn])
}
func writePacket(_ bytes: [UInt8], packnr: Int) throws {
try writeHeader(UInt32(bytes.count), pn: UInt8(packnr + 1))
try self.write(bytes)
}
}
| mit | c41d1a8fc6968bebe808b45c5bd9d91f | 22.512821 | 67 | 0.561614 | 3.434457 | false | false | false | false |
kantega/tech-ex-2015 | ios/TechEx/services/KeychainService.swift | 1 | 4497 | /**
* Inspired by: http://matthewpalmer.net/blog/2014/06/21/example-ios-keychain-swift-save-query/
*/
import UIKit
import Security
// Arguments for the keychain queries
let kSecClassValue = NSString(format: kSecClass)
let kSecAttrAccountValue = NSString(format: kSecAttrAccount)
let kSecValueDataValue = NSString(format: kSecValueData)
let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword)
let kSecAttrServiceValue = NSString(format: kSecAttrService)
let kSecMatchLimitValue = NSString(format: kSecMatchLimit)
let kSecReturnDataValue = NSString(format: kSecReturnData)
let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne)
class KeychainService: NSObject {
enum KeychainKey {
case Username;
case PlayerId;
}
/**
* Exposed methods to perform queries.
*/
internal class func save(key: KeychainKey, value: NSString) {
// NSUserDefaults.standardUserDefaults().setValue(value, forKey: keyAsString(key))
let serviceIdentifier = NSBundle.mainBundle().bundleIdentifier!
self.save(serviceIdentifier, key: key, value: value)
}
internal class func load(key: KeychainKey) -> NSString? {
// return NSUserDefaults.standardUserDefaults().objectForKey(keyAsString(key)) as? String
let serviceIdentifier = NSBundle.mainBundle().bundleIdentifier!
var token = self.load(serviceIdentifier, key: key)
return token
}
internal class func deleteAll() {
let serviceIdentifier = NSBundle.mainBundle().bundleIdentifier!
delete(serviceIdentifier, key: .Username)
delete(serviceIdentifier, key: .PlayerId)
}
/**
* Internal methods for querying the keychain.
*/
private class func save(service: NSString, key: KeychainKey, value: NSString) {
let valueData: NSData = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let keyData: NSData = keyAsString(key).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
// Instantiate a new default keychain query
var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, keyData, valueData], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecValueDataValue])
NSLog("Deleting exising items in Keychain")
// Delete any existing items
SecItemDelete(keychainQuery as CFDictionaryRef)
// Add the new keychain item
var status: OSStatus = SecItemAdd(keychainQuery as CFDictionaryRef, nil)
NSLog("Item \(key) saved in Keychain. Status: \(status)")
}
private class func load(service: NSString, key: KeychainKey) -> NSString? {
// Instantiate a new default keychain query
// Tell the query to return a result
// Limit our results to one item
let keyString = keyAsString(key) as String;
NSLog("Loading \(keyString) from Keychain")
let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, keyString, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])
var dataTypeRef :Unmanaged<AnyObject>?
var contentsOfKeychain: NSString?
var result: AnyObject?
var status = withUnsafeMutablePointer(&result) {
SecItemCopyMatching(keychainQuery, UnsafeMutablePointer($0))
}
if status == errSecSuccess {
let data = result as NSData?
contentsOfKeychain = NSString(data: data!, encoding: NSUTF8StringEncoding)
}
return contentsOfKeychain
}
private class func delete(service: String, key: KeychainKey) {
let keyData: NSData = keyAsString(key).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, keyData], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue])
// Delete any existing items
SecItemDelete(keychainQuery as CFDictionaryRef)
}
private class func keyAsString(key: KeychainKey) -> String {
switch key {
case .Username: return "username";
case .PlayerId: return "id";
}
}
} | mit | 63c15151942015da085be240ced226ea | 42.669903 | 283 | 0.704692 | 5.44431 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/01297-swift-type-walk.swift | 11 | 814 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
func ^(r: l, k) -> k {
? {
h (s : t?) q u {
g let d = s {
}
}
e}
let u : [Int?] = [n{
c v: j t.v == m>(n: o<t>) {
}
}
class a<f : g, g : g where f.f == g> {
}
protocol g {
typealias f
}
struct c<h : g> : g {
typealias e = a<c<h>, f>
func r<t>() {
f f {
}
}
struct i<o : u> {
}
func r<o>() -> [i<o>] {
}
class g<t : g> {
}
class g: g {
}
class n : h {
}
func i() -> l func o() -> m {
}
class d<c>: NSObject {
}
func c<b:c
| apache-2.0 | f8199037fe9cc819d212a788491b9c00 | 17.088889 | 78 | 0.58231 | 2.520124 | false | false | false | false |
lzpfmh/actor-platform | actor-apps/app-ios/ActorSwift/Localization.swift | 1 | 613 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
// Shorter helper for localized strings
func localized(text: String?) -> String! {
if text == nil {
return nil
}
return NSLocalizedString(text!, comment: "")
}
// Extensions on various UIView
extension UILabel {
var textLocalized: String? {
get {
return self.text
}
set (value) {
if value != nil {
self.text = localized(value!)
} else {
self.text = nil
}
}
}
} | mit | afc503f5b107f78333a86b8897a09e03 | 17.606061 | 57 | 0.492659 | 4.442029 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.