repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mukeshydv/JSONParserSwift | Source/Serialization.swift | 2 | 3975 | //
// Serialization.swift
// Copyright (c) 2017 Mukesh Yadav <[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 Foundation
class Serialization {
static func getDictionaryFromArray(array: [Any]) -> [Any] {
var resultingArray: [Any] = []
for element in array {
let elementValue = getValue(value: element)
resultingArray.append(elementValue)
}
return resultingArray
}
static func getDictionaryFromObject(object: Any) -> [String: Any] {
var dictionary: [String: Any] = [:]
var mirror: Mirror? = Mirror(reflecting: object)
repeat {
for property in mirror!.children {
if let propertyName = property.label {
if propertyName == "some" {
var mirror: Mirror? = Mirror(reflecting: property.value)
repeat {
for childProperty in mirror!.children {
if let propertyName = childProperty.label {
if let value = property.value as? JSONKeyCoder {
if let userDefinedKeyName = value.key(for: propertyName) {
dictionary[userDefinedKeyName] = getValue(value: childProperty.value)
} else {
dictionary[propertyName] = getValue(value: childProperty.value)
}
} else {
dictionary[propertyName] = getValue(value: childProperty.value)
}
}
}
mirror = mirror?.superclassMirror
} while mirror != nil
} else {
if let value = object as? JSONKeyCoder {
if let userDefinedKeyName = value.key(for: propertyName) {
dictionary[userDefinedKeyName] = getValue(value: property.value)
} else {
dictionary[propertyName] = getValue(value: property.value)
}
} else {
dictionary[propertyName] = getValue(value: property.value)
}
}
}
}
mirror = mirror?.superclassMirror
} while mirror != nil
return dictionary
}
private static func getValue(value: Any) -> Any {
if let numericValue = value as? NSNumber {
return numericValue
} else if let boolValue = value as? Bool {
return boolValue
} else if let stringValue = value as? String {
return stringValue
} else if let arrayValue = value as? Array<Any> {
return getDictionaryFromArray(array: arrayValue)
} else {
let dictionary = getDictionaryFromObject(object: value)
if dictionary.count == 0 {
return NSNull()
} else {
return dictionary
}
}
}
}
| mit | 994b7ad481e0142f8538cbf303575650 | 37.970588 | 113 | 0.591447 | 4.80653 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Sources/FeatureTransactionData/Core/Network/Model/Response/CustodialTransferResponse.swift | 1 | 1756 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import MoneyKit
import PlatformKit
/// The response object returned after submitting a custodial transfer to a non custodial address.
/// At the time of writing, `Status`/`State` is not exposed to clients.
struct CustodialTransferResponse: Decodable {
enum Status: String {
case none
case pending
case refunded
case complete
case rejected
}
let identifier: String
let userId: String
let cryptoValue: CryptoValue
/// NOTE: `State`/`Status` is not mapped yet as it is not exposed
/// by the API. However, it may well be in the future so as
/// we can show the status of the withdrawal after submission.
enum CodingKeys: String, CodingKey {
case id
case user
case amount
case symbol
case value
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
identifier = try values.decode(String.self, forKey: .id)
userId = try values.decode(String.self, forKey: .user)
let amountContainer = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .amount)
let symbol = try amountContainer.decode(String.self, forKey: .symbol)
guard let currency = CryptoCurrency(code: symbol) else {
throw DecodingError.dataCorruptedError(
forKey: .symbol,
in: values,
debugDescription: "CryptoCurrency not recognised."
)
}
let value = try amountContainer.decode(String.self, forKey: .value)
cryptoValue = CryptoValue.create(major: value, currency: currency) ?? .zero(currency: currency)
}
}
| lgpl-3.0 | 03bf9f731b2050b52ce93be6695357d6 | 34.816327 | 103 | 0.652991 | 4.756098 | false | false | false | false |
denizsokmen/Raid | Raid/Project.swift | 1 | 1615 | //
// Project.swift
// Raid
//
// Created by student7 on 30/12/14.
// Copyright (c) 2014 student7. All rights reserved.
//
import Foundation
class Project {
var bugcounter: Int = 0
var bugs: [BugReport]!
var users: [Int]!
var name: String!
init(nm : String) {
bugs = []
users = []
name = nm
}
init(dict: [String:AnyObject]) {
bugs = []
users = []
let nm: AnyObject? = dict["name"]
let bugc: AnyObject? = dict["bugcounter"]
let memberDict: AnyObject? = dict["users"]
let bugDict = dict["bugs"] as [[String:AnyObject]]
name = nm as String
bugcounter = bugc as Int
for i in memberDict as [Int] {
users.append(i)
}
for i in bugDict {
let bug = BugReport(dict: i)
bugs.append(bug)
}
}
func addBug(title: String, priority : Int, desc: String, assgn: Int) {
var bug = BugReport(nm: title, prio: priority)
bug.id = bugcounter++
bug.description = desc
bug.assignee = assgn
bug.assigner = Database.sharedInstance.currentUser.id
bugs.append(bug)
}
func convertToDict() -> [String: AnyObject] {
var bugsArray = [[String:AnyObject]]()
for bug in bugs {
bugsArray.append(bug.convertToDict())
}
var dict : [String: AnyObject] = ["name": self.name, "bugcounter": self.bugcounter, "bugs": bugsArray, "users": self.users]
return dict
}
}
| gpl-2.0 | fd63dda401431c0c92feca4e8c218070 | 23.104478 | 131 | 0.521981 | 3.968059 | false | false | false | false |
ivlevAstef/DITranquillity | Sources/UI/Storyboard/StoryboardResolver.swift | 1 | 1324 | //
// StoryboardResolver.swift
// DITranquillity
//
// Created by Alexander Ivlev on 05/01/17.
// Copyright © 2016 Alexander Ivlev. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
#if os(iOS) || os(tvOS) || os(OSX)
/// The class responsible for injecting dependencies in the view/window controller.
final class StoryboardResolver {
init(container: DIContainer, framework: DIFramework.Type?) {
self.container = container
self.framework = framework
}
#if os(iOS) || os(tvOS)
func inject(into viewController: UIViewController) {
self.container.inject(into: viewController, from: framework)
for childVC in viewController.children {
inject(into: childVC)
}
}
#elseif os(OSX)
func inject(into viewController: Any) {
self.container.inject(into: viewController, from: framework)
if let windowController = viewController as? NSWindowController, let viewController = windowController.contentViewController {
inject(into: viewController)
}
if let nsViewController = viewController as? NSViewController {
for childVC in nsViewController.children {
inject(into: childVC)
}
}
}
#endif
private let container: DIContainer
private let framework: DIFramework.Type?
}
#endif
| mit | 21d97e78c81321437e8e5858940f8274 | 23.054545 | 130 | 0.70446 | 4.147335 | false | false | false | false |
skerkewitz/SwignalR | SwignalR/Classes/Hubs/HubConnection.swift | 1 | 6446 | //
// HubConnection.swift
// SignalR
//
// Created by Alex Billingsley on 10/31/11.
// Copyright (c) 2011 DyKnow LLC. (http://dyknow.com/)
// Created by Stefan Kerkewitz on 01/03/2017.
//
// 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
/**
* An `SRHubConnection` object provides an abstraction over `SRConnection` and provides support for publishing and subscribing to custom events
*/
public class SRHubConnection: SRConnection, SRHubConnectionInterface {
private struct CallbackData {
let id: Int
let url: String
let block: SRHubConnectionHubResultBlock
let timestamp = Int(Date().timeIntervalSince1970)
}
private var hubs = [String: SRHubProxy]()
private var callbacks = [String : CallbackData]()
private var callbackId: Int = 1
/* --- Initialization --- */
public init(urlString url: String, useDefault: Bool = true) {
super.init(urlString: SRHubConnection.getUrl(URL: url, useDefault: useDefault))
}
public init(urlString url: String, queryString: [String: String], useDefault: Bool = true) {
super.init(urlString: SRHubConnection.getUrl(URL: url, useDefault: useDefault), queryString: queryString)
}
/**
* Creates a client side proxy to the hub on the server side.
*
* <code>
* SRHubProxy *myHub = [connection createProxy:@"MySite.MyHub"];
* </code>
* @warning *Important:* The name of this hub needs to be the full type name of the hub.
*
* @param hubName hubName the name of the hub
* @return SRHubProxy object
*/
public func createHubProxy(_ hubName: String) -> SRHubProxyInterface {
if self.state != .disconnected {
fatalError(NSLocalizedString("Proxies cannot be added after the connection has been started.", comment: "NSInternalInconsistencyException"))
}
SRLogDebug("will create proxy \(hubName)")
let name = hubName.lowercased()
if let hubProxy = self.hubs[name] {
return hubProxy
}
let hubProxy = SRHubProxy(connection: self, hubName: name)
self.hubs[name] = hubProxy;
return hubProxy;
}
public func registerCallback(url: String, callback: @escaping SRHubConnectionHubResultBlock) -> String {
let newId = "\(callbackId)"
self.callbacks[newId] = CallbackData(id: callbackId, url: url, block: callback)
self.callbackId += 1
/* Check for old hanging calls. */
if self.callbackId % 10 == 0 {
let now = Int(Date().timeIntervalSince1970)
let threshold = 30
self.callbacks.values.forEach { value in
if value.timestamp + threshold < now {
SRLogWarn("Hanging call for \(value.id) \(value.url), elapsed time \(value.timestamp - now) seconds)")
}
}
}
return newId
}
class func getUrl(URL: String, useDefault: Bool) -> String {
var _url = URL
if URL.hasSuffix("/") == false {
_url = URL + "/"
}
if (useDefault) {
return _url + "signalr"
}
return _url;
}
/* --- Sending data --- */
public override func onSending() -> String? {
var dataArray = [[String: Any]]()
for key in self.hubs.keys {
let registration = SRHubRegistrationData(name: key)
dataArray.append(registration.proxyForJson())
}
let data = try? JSONSerialization.data(withJSONObject: dataArray)
return String(data: data!, encoding: .utf8)!
}
/* --- Received Data --- */
public override func didReceiveData(_ data: Any) {
if let data = data as? [String: Any] {
if data["I"] != nil {
let result = SRHubResult(dictionary: data)
self.invokeCallback(with: result)
} else {
let invocation = SRHubInvocation(dictionary: data)
if let hubProxy = self.hubs[invocation.hub.lowercased()] {
if let state = invocation.state, state.count > 0 {
for key in state.keys {
hubProxy.state[key] = state[key]
}
}
hubProxy.invokeEvent(invocation.method, withArgs:invocation.args)
}
super.didReceiveData(data)
}
}
}
public override func willReconnect() {
self.clearInvocationCallbacks(errorMessage: "Connection started reconnecting before invocation result was received.")
super.willReconnect()
}
private func invokeCallback(with result: SRHubResult) {
/* Remove the callback and invoke the callback block. */
if let idKey = result.id, let callback = self.callbacks.removeValue(forKey: idKey) {
callback.block(result)
}
}
private func clearInvocationCallbacks(errorMessage error: String) {
let hubErrorResult = SRHubResult(error: error)
for callback in self.callbacks.values {
callback.block(hubErrorResult);
}
self.callbacks.removeAll()
}
public override func didClose() {
self.clearInvocationCallbacks(errorMessage: "Connection was disconnected before invocation result was received.")
super.didClose()
}
}
| mit | 5127b39a52aa45d1da27e4e9bc8c43d3 | 35.418079 | 152 | 0.628297 | 4.558699 | false | false | false | false |
danielsaidi/iExtra | iExtra/UI/Extensions/UIView/UIView+Copy.swift | 1 | 1228 | //
// UIView+Copy.swift
// iExtra
//
// Created by Daniel Saidi on 2016-03-20.
// Copyright © 2018 Daniel Saidi. All rights reserved.
//
import UIKit
public extension UIView {
func createImageCopy() -> UIImage {
UIGraphicsBeginImageContext(frame.size)
layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
func createImageSilhouetteCopy() -> UIImage {
let image = createImageCopy()
let ciContext = CIContext(options: nil)
let ciInput = CIImage(cgImage: image.cgImage!)
let filter = CIFilter(name: "CIFalseColor")
let color0 = CIColor(red: 0, green: 0, blue: 0, alpha: 1)
let color1 = CIColor(red: 0, green: 0, blue: 0, alpha: 0)
filter?.setValue(color0, forKey: "inputColor0")
filter?.setValue(color1, forKey: "inputColor1")
filter?.setValue(ciInput, forKey: kCIInputImageKey)
let outImage = filter?.value(forKey: kCIOutputImageKey) as? CIImage ?? CIImage()
let result = ciContext.createCGImage(outImage, from: ciInput.extent)
return UIImage(cgImage: result!)
}
}
| mit | 2fc7f365e8fc1a900569cf112a5dd86f | 34.057143 | 88 | 0.655257 | 4.366548 | false | false | false | false |
urbanthings/urbanthings-sdk-apple | UrbanThingsAPI/Internal/Response/UTStopBoardMessage.swift | 1 | 1469 | //
// UTStopBoardMessage.swift
// UrbanThingsAPI
//
// Created by Mark Woollard on 03/05/2016.
// Copyright © 2016 UrbanThings. All rights reserved.
//
import Foundation
class UTStopBoardMessage : UTObject, StopBoardMessage {
let headerText:String?
let mainText:String?
let iconURL:URL?
let linkURL:URL?
let linkText:String?
let severity:DisruptionSeverity
let color:UTColor?
let colorCompliment:UTColor?
override init(json: [String : Any]) throws {
self.headerText = try parse(optional: json, key: .HeaderText, type: UTStopBoardMessage.self)
self.mainText = try parse(optional: json, key: .MainText, type: UTStopBoardMessage.self)
self.linkText = try parse(optional: json, key: .LinkText, type: UTStopBoardMessage.self)
self.iconURL = try parse(optional:json, key:. IconURL, type: UTStopBoardMessage.self) { try URL.fromJSON(optional:$0) }
self.linkURL = try parse(optional:json, key:. LinkURL, type: UTStopBoardMessage.self) { try URL.fromJSON(optional:$0) }
self.color = try parse(optional: json, key: .Color, type: UTStopBoardMessage.self) { try UTColor.fromJSON(optional: $0) }
self.colorCompliment = try parse(optional: json, key: .ColorCompliment, type: UTStopBoardMessage.self) { try UTColor.fromJSON(optional: $0) }
self.severity = try parse(required: json, key: .Severity, type: UTStopBoardMessage.self)
try super.init(json: json)
}
}
| apache-2.0 | 86742f2bf73ea910b6c44ff36705b951 | 43.484848 | 149 | 0.702316 | 3.571776 | false | false | false | false |
nikrad/ios | FiveCalls/FiveCalls/BaseOperation.swift | 4 | 1069 | //
// BaseOperation.swift
// FiveCalls
//
// Created by Ben Scheirman on 1/30/17.
// Copyright © 2017 5calls. All rights reserved.
//
import Foundation
class BaseOperation : Operation {
override var isAsynchronous: Bool {
return true
}
private var _executing = false {
willSet {
willChangeValue(forKey: "isExecuting")
}
didSet {
didChangeValue(forKey: "isExecuting")
}
}
override var isExecuting: Bool {
return _executing
}
private var _finished = false {
willSet {
willChangeValue(forKey: "isFinished")
}
didSet {
didChangeValue(forKey: "isFinished")
}
}
override var isFinished: Bool {
return _finished
}
override func start() {
_executing = true
execute()
}
func execute() {
fatalError("You must override this")
}
func finish() {
_executing = false
_finished = true
}
}
| mit | 5ed89584f520df859a72f6736ce32af9 | 17.736842 | 50 | 0.527154 | 4.944444 | false | false | false | false |
apple/swift-corelibs-foundation | Darwin/Foundation-swiftoverlay/Measurement.swift | 1 | 16564 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if DEPLOYMENT_RUNTIME_SWIFT
import CoreFoundation
#else
@_exported import Foundation // Clang module
@_implementationOnly import _CoreFoundationOverlayShims
#endif
/// A `Measurement` is a model type that holds a `Double` value associated with a `Unit`.
///
/// Measurements support a large set of operators, including `+`, `-`, `*`, `/`, and a full set of comparison operators.
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public struct Measurement<UnitType : Unit> : ReferenceConvertible, Comparable, Equatable {
public typealias ReferenceType = NSMeasurement
/// The unit component of the `Measurement`.
public let unit: UnitType
/// The value component of the `Measurement`.
public var value: Double
/// Create a `Measurement` given a specified value and unit.
public init(value: Double, unit: UnitType) {
self.value = value
self.unit = unit
}
public func hash(into hasher: inout Hasher) {
// Warning: The canonicalization performed here needs to be kept in
// perfect sync with the definition of == below. The floating point
// values that are compared there must match exactly with the values fed
// to the hasher here, or hashing would break.
if let dimension = unit as? Dimension {
// We don't need to feed the base unit to the hasher here; all
// dimensional measurements of the same type share the same unit.
hasher.combine(dimension.converter.baseUnitValue(fromValue: value))
} else {
hasher.combine(unit)
hasher.combine(value)
}
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return "\(value) \(unit.symbol)"
}
public var debugDescription: String {
return "\(value) \(unit.symbol)"
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "value", value: value))
c.append((label: "unit", value: unit.symbol))
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
}
/// When a `Measurement` contains a `Dimension` unit, it gains the ability to convert between the kinds of units in that dimension.
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement where UnitType : Dimension {
/// Returns a new measurement created by converting to the specified unit.
///
/// - parameter otherUnit: A unit of the same `Dimension`.
/// - returns: A converted measurement.
public func converted(to otherUnit: UnitType) -> Measurement<UnitType> {
if unit.isEqual(otherUnit) {
return Measurement(value: value, unit: otherUnit)
} else {
let valueInTermsOfBase = unit.converter.baseUnitValue(fromValue: value)
if otherUnit.isEqual(type(of: unit).baseUnit()) {
return Measurement(value: valueInTermsOfBase, unit: otherUnit)
} else {
let otherValueFromTermsOfBase = otherUnit.converter.value(fromBaseUnitValue: valueInTermsOfBase)
return Measurement(value: otherValueFromTermsOfBase, unit: otherUnit)
}
}
}
/// Converts the measurement to the specified unit.
///
/// - parameter otherUnit: A unit of the same `Dimension`.
public mutating func convert(to otherUnit: UnitType) {
self = converted(to: otherUnit)
}
/// Add two measurements of the same Dimension.
///
/// If the `unit` of the `lhs` and `rhs` are `isEqual`, then this returns the result of adding the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit.
/// - returns: The result of adding the two measurements.
public static func +(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value + rhs.value, unit: lhs.unit)
} else {
let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value)
return Measurement(value: lhsValueInTermsOfBase + rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit())
}
}
/// Subtract two measurements of the same Dimension.
///
/// If the `unit` of the `lhs` and `rhs` are `==`, then this returns the result of subtracting the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit.
/// - returns: The result of adding the two measurements.
public static func -(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit == rhs.unit {
return Measurement(value: lhs.value - rhs.value, unit: lhs.unit)
} else {
let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value)
return Measurement(value: lhsValueInTermsOfBase - rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit())
}
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement {
/// Add two measurements of the same Unit.
/// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`.
/// - returns: A measurement of value `lhs.value + rhs.value` and unit `lhs.unit`.
public static func +(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value + rhs.value, unit: lhs.unit)
} else {
fatalError("Attempt to add measurements with non-equal units")
}
}
/// Subtract two measurements of the same Unit.
/// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`.
/// - returns: A measurement of value `lhs.value - rhs.value` and unit `lhs.unit`.
public static func -(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value - rhs.value, unit: lhs.unit)
} else {
fatalError("Attempt to subtract measurements with non-equal units")
}
}
/// Multiply a measurement by a scalar value.
/// - returns: A measurement of value `lhs.value * rhs` with the same unit as `lhs`.
public static func *(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
return Measurement(value: lhs.value * rhs, unit: lhs.unit)
}
/// Multiply a scalar value by a measurement.
/// - returns: A measurement of value `lhs * rhs.value` with the same unit as `rhs`.
public static func *(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
return Measurement(value: lhs * rhs.value, unit: rhs.unit)
}
/// Divide a measurement by a scalar value.
/// - returns: A measurement of value `lhs.value / rhs` with the same unit as `lhs`.
public static func /(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
return Measurement(value: lhs.value / rhs, unit: lhs.unit)
}
/// Divide a scalar value by a measurement.
/// - returns: A measurement of value `lhs / rhs.value` with the same unit as `rhs`.
public static func /(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
return Measurement(value: lhs / rhs.value, unit: rhs.unit)
}
/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value == rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if the measurements are equal.
public static func ==<LeftHandSideType, RightHandSideType>(lhs: Measurement<LeftHandSideType>, rhs: Measurement<RightHandSideType>) -> Bool {
// Warning: This defines an equivalence relation that needs to be kept
// in perfect sync with the hash(into:) definition above. The floating
// point values that are fed to the hasher there must match exactly with
// the values compared here, or hashing would break.
if lhs.unit == rhs.unit {
return lhs.value == rhs.value
} else {
if let lhsDimensionalUnit = lhs.unit as? Dimension,
let rhsDimensionalUnit = rhs.unit as? Dimension {
if type(of: lhsDimensionalUnit).baseUnit() == type(of: rhsDimensionalUnit).baseUnit() {
let lhsValueInTermsOfBase = lhsDimensionalUnit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhsDimensionalUnit.converter.baseUnitValue(fromValue: rhs.value)
return lhsValueInTermsOfBase == rhsValueInTermsOfBase
}
}
return false
}
}
/// Compare two measurements of the same `Unit`.
/// - returns: `true` if the measurements can be compared and the `lhs` is less than the `rhs` converted value.
public static func <<LeftHandSideType, RightHandSideType>(lhs: Measurement<LeftHandSideType>, rhs: Measurement<RightHandSideType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value < rhs.value
} else {
if let lhsDimensionalUnit = lhs.unit as? Dimension,
let rhsDimensionalUnit = rhs.unit as? Dimension {
if type(of: lhsDimensionalUnit).baseUnit() == type(of: rhsDimensionalUnit).baseUnit() {
let lhsValueInTermsOfBase = lhsDimensionalUnit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhsDimensionalUnit.converter.baseUnitValue(fromValue: rhs.value)
return lhsValueInTermsOfBase < rhsValueInTermsOfBase
}
}
fatalError("Attempt to compare measurements with non-equal dimensions")
}
}
}
// Implementation note: similar to NSArray, NSDictionary, etc., NSMeasurement's import as an ObjC generic type is suppressed by the importer. Eventually we will need a more general purpose mechanism to correctly import generic types.
// FIXME: Remove @usableFromInline from MeasurementBridgeType once
// rdar://problem/44662501 is fixed. (The Radar basically just says "look
// through typealiases and inherited protocols when printing extensions".)
#if DEPLOYMENT_RUNTIME_SWIFT
@usableFromInline
internal typealias MeasurementBridgeType = _ObjectTypeBridgeable
#else
@usableFromInline
internal typealias MeasurementBridgeType = _ObjectiveCBridgeable
#endif
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : MeasurementBridgeType {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSMeasurement {
return NSMeasurement(doubleValue: value, unit: unit)
}
public static func _forceBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) {
result = Measurement(value: source.doubleValue, unit: source.unit as! UnitType)
}
public static func _conditionallyBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) -> Bool {
if let u = source.unit as? UnitType {
result = Measurement(value: source.doubleValue, unit: u)
return true
} else {
return false
}
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSMeasurement?) -> Measurement {
let u = source!.unit as! UnitType
return Measurement(value: source!.doubleValue, unit: u)
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension NSMeasurement : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
#if DEPLOYMENT_RUNTIME_SWIFT
return AnyHashable(Measurement._unconditionallyBridgeFromObjectiveC(self))
#else
return AnyHashable(self as Measurement)
#endif
}
}
// This workaround is required for the time being, because Swift doesn't support covariance for Measurement (26607639)
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension MeasurementFormatter {
public func string<UnitType>(from measurement: Measurement<UnitType>) -> String {
if let result = string(for: measurement) {
return result
} else {
return ""
}
}
}
// @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
// extension Unit : Codable {
// public convenience init(from decoder: Decoder) throws {
// let container = try decoder.singleValueContainer()
// let symbol = try container.decode(String.self)
// self.init(symbol: symbol)
// }
// public func encode(to encoder: Encoder) throws {
// var container = encoder.singleValueContainer()
// try container.encode(self.symbol)
// }
// }
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : Codable {
private enum CodingKeys : Int, CodingKey {
case value
case unit
}
private enum UnitCodingKeys : Int, CodingKey {
case symbol
case converter
}
private enum LinearConverterCodingKeys : Int, CodingKey {
case coefficient
case constant
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let value = try container.decode(Double.self, forKey: .value)
let unitContainer = try container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit)
let symbol = try unitContainer.decode(String.self, forKey: .symbol)
let unit: UnitType
if UnitType.self is Dimension.Type {
let converterContainer = try unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter)
let coefficient = try converterContainer.decode(Double.self, forKey: .coefficient)
let constant = try converterContainer.decode(Double.self, forKey: .constant)
let unitMetaType = (UnitType.self as! Dimension.Type)
unit = (unitMetaType.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient, constant: constant)) as! UnitType)
} else {
unit = UnitType(symbol: symbol)
}
self.init(value: value, unit: unit)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.value, forKey: .value)
var unitContainer = container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit)
try unitContainer.encode(self.unit.symbol, forKey: .symbol)
if UnitType.self is Dimension.Type {
guard type(of: (self.unit as! Dimension).converter) is UnitConverterLinear.Type else {
preconditionFailure("Cannot encode a Measurement whose UnitType has a non-linear unit converter.")
}
let converter = (self.unit as! Dimension).converter as! UnitConverterLinear
var converterContainer = unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter)
try converterContainer.encode(converter.coefficient, forKey: .coefficient)
try converterContainer.encode(converter.constant, forKey: .constant)
}
}
}
| apache-2.0 | 3c3b4c4838ff714811a2431704c407e9 | 45.268156 | 280 | 0.662763 | 4.705682 | false | false | false | false |
fabiomassimo/eidolon | Kiosk/App/Networking/ArtsyAPI.swift | 1 | 12267 | import Foundation
import ReactiveCocoa
import Moya
public enum ArtsyAPI {
case XApp
case XAuth(email: String, password: String)
case TrustToken(number: String, auctionPIN: String)
case SystemTime
case Ping
case Me
case MyCreditCards
case CreatePINForBidder(bidderID: String)
case FindBidderRegistration(auctionID: String, phone: String)
case RegisterToBid(auctionID: String)
case Artwork(id: String)
case Artist(id: String)
case Auctions
case AuctionListings(id: String, page: Int, pageSize: Int)
case AuctionInfo(auctionID: String)
case AuctionInfoForArtwork(auctionID: String, artworkID: String)
case ActiveAuctions
case MyBiddersForAuction(auctionID: String)
case MyBidPositionsForAuctionArtwork(auctionID: String, artworkID: String)
case PlaceABid(auctionID: String, artworkID: String, maxBidCents: String)
case UpdateMe(email: String, phone: String, postCode: String, name: String)
case CreateUser(email: String, password: String, phone: String, postCode: String, name: String)
case RegisterCard(stripeToken: String)
case BidderDetailsNotification(auctionID: String, identifier: String)
case LostPasswordNotification(email: String)
case FindExistingEmailRegistration(email: String)
}
extension ArtsyAPI : MoyaPath {
public var path: String {
switch self {
case .XApp:
return "/api/v1/xapp_token"
case .XAuth:
return "/oauth2/access_token"
case AuctionInfo(let id):
return "/api/v1/sale/\(id)"
case Auctions:
return "/api/v1/sales"
case AuctionListings(let id, _, _):
return "/api/v1/sale/\(id)/sale_artworks"
case AuctionInfoForArtwork(let auctionID, let artworkID):
return "/api/v1/sale/\(auctionID)/sale_artwork/\(artworkID)"
case SystemTime:
return "/api/v1/system/time"
case Ping:
return "/api/v1/system/ping"
case RegisterToBid:
return "/api/v1/bidder"
case MyCreditCards:
return "/api/v1/me/credit_cards"
case CreatePINForBidder(let bidderID):
return "/api/v1/bidder/\(bidderID)/pin"
case ActiveAuctions:
return "/api/v1/sales"
case Me:
return "/api/v1/me"
case UpdateMe:
return "/api/v1/me"
case CreateUser:
return "/api/v1/user"
case MyBiddersForAuction:
return "/api/v1/me/bidders"
case MyBidPositionsForAuctionArtwork:
return "/api/v1/me/bidder_positions"
case Artwork(let id):
return "/api/v1/artwork/\(id)"
case Artist(let id):
return "/api/v1/artist/\(id)"
case FindBidderRegistration:
return "/api/v1/bidder"
case PlaceABid:
return "/api/v1/me/bidder_position"
case RegisterCard:
return "/api/v1/me/credit_cards"
case TrustToken:
return "/api/v1/me/trust_token"
case BidderDetailsNotification:
return "/api/v1/bidder/bidding_details_notification"
case LostPasswordNotification:
return "/api/v1/users/send_reset_password_instructions"
case FindExistingEmailRegistration:
return "/api/v1/user"
}
}
}
extension ArtsyAPI : MoyaTarget {
public var base: String { return AppSetup.sharedState.useStaging ? "https://stagingapi.artsy.net" : "https://api.artsy.net" }
public var baseURL: NSURL { return NSURL(string: base)! }
public var parameters: [String: AnyObject] {
switch self {
case XAuth(let email, let password):
return [
"client_id": APIKeys.sharedKeys.key ?? "",
"client_secret": APIKeys.sharedKeys.secret ?? "",
"email": email,
"password": password,
"grant_type": "credentials"
]
case XApp:
return ["client_id": APIKeys.sharedKeys.key ?? "",
"client_secret": APIKeys.sharedKeys.secret ?? ""]
case Auctions:
return ["is_auction": "true"]
case RegisterToBid(let auctionID):
return ["sale_id": auctionID]
case MyBiddersForAuction(let auctionID):
return ["sale_id": auctionID]
case PlaceABid(let auctionID, let artworkID, let maxBidCents):
return [
"sale_id": auctionID,
"artwork_id": artworkID,
"max_bid_amount_cents": maxBidCents
]
case TrustToken(let number, let auctionID):
return ["number": number, "auction_pin": auctionID]
case CreateUser(let email, let password,let phone,let postCode, let name):
return [
"email": email, "password": password,
"phone": phone, "name": name,
"location": [ "postal_code": postCode ]
]
case UpdateMe(let email, let phone,let postCode, let name):
return [
"email": email, "phone": phone,
"name": name, "location": [ "postal_code": postCode ]
]
case RegisterCard(let token):
return ["provider": "stripe", "token": token]
case FindBidderRegistration(let auctionID, let phone):
return ["sale_id": auctionID, "number": phone]
case BidderDetailsNotification(let auctionID, let identifier):
return ["sale_id": auctionID, "identifier": identifier]
case LostPasswordNotification(let email):
return ["email": email]
case FindExistingEmailRegistration(let email):
return ["email": email]
case AuctionListings(_, let page, let pageSize):
return ["size": pageSize, "page": page]
case ActiveAuctions:
return ["is_auction": true, "live": true]
case MyBidPositionsForAuctionArtwork(let auctionID, let artworkID):
return ["sale_id": auctionID, "artwork_id": artworkID]
default:
return [:]
}
}
public var method: Moya.Method {
//TODO:
switch self {
case .LostPasswordNotification,
.CreateUser,
.PlaceABid,
.RegisterCard,
.RegisterToBid,
.CreatePINForBidder:
return .POST
case .FindExistingEmailRegistration:
return .HEAD
case .UpdateMe,
.BidderDetailsNotification:
return .PUT
default:
return .GET
}
}
public var sampleData: NSData {
switch self {
case XApp:
return stubbedResponse("XApp")
case XAuth:
return stubbedResponse("XAuth")
case TrustToken:
return stubbedResponse("XAuth")
case Auctions:
return stubbedResponse("Auctions")
case AuctionListings:
return stubbedResponse("AuctionListings")
case SystemTime:
return stubbedResponse("SystemTime")
case CreatePINForBidder:
return stubbedResponse("CreatePINForBidder")
case ActiveAuctions:
return stubbedResponse("ActiveAuctions")
case MyCreditCards:
return stubbedResponse("MyCreditCards")
case RegisterToBid:
return stubbedResponse("RegisterToBid")
case MyBiddersForAuction:
return stubbedResponse("MyBiddersForAuction")
case Me:
return stubbedResponse("Me")
case UpdateMe:
return stubbedResponse("Me")
case CreateUser:
return stubbedResponse("Me")
// This API returns a 302, so stubbed response isn't valid
case FindBidderRegistration:
return stubbedResponse("Me")
case PlaceABid:
return stubbedResponse("CreateABid")
case Artwork:
return stubbedResponse("Artwork")
case Artist:
return stubbedResponse("Artist")
case AuctionInfo:
return stubbedResponse("AuctionInfo")
case RegisterCard:
return stubbedResponse("RegisterCard")
case BidderDetailsNotification:
return stubbedResponse("RegisterToBid")
case LostPasswordNotification:
return stubbedResponse("ForgotPassword")
case FindExistingEmailRegistration:
return stubbedResponse("ForgotPassword")
case AuctionInfoForArtwork:
return stubbedResponse("AuctionInfoForArtwork")
case MyBidPositionsForAuctionArtwork:
return stubbedResponse("MyBidPositionsForAuctionArtwork")
case Ping:
return stubbedResponse("Ping")
}
}
}
// MARK: - Provider setup
public func endpointResolver () -> ((endpoint: Endpoint<ArtsyAPI>) -> (NSURLRequest)) {
return { (endpoint: Endpoint<ArtsyAPI>) -> (NSURLRequest) in
let request: NSMutableURLRequest = endpoint.urlRequest.mutableCopy() as! NSMutableURLRequest
request.HTTPShouldHandleCookies = false
return request
}
}
public class ArtsyProvider<T where T: MoyaTarget>: ReactiveMoyaProvider<T> {
public typealias OnlineSignalClosure = () -> RACSignal
// Closure that returns a signal which completes once the app is online.
public let onlineSignal: OnlineSignalClosure
public init(endpointsClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping(), endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEnpointResolution(), stubResponses: Bool = false, stubBehavior: MoyaStubbedBehavior = MoyaProvider.DefaultStubBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil, onlineSignal: OnlineSignalClosure = connectedToInternetSignal) {
self.onlineSignal = onlineSignal
super.init(endpointsClosure: endpointsClosure, endpointResolver: endpointResolver, stubResponses: stubResponses, networkActivityClosure: networkActivityClosure)
}
}
public struct Provider {
private static var endpointsClosure = { (target: ArtsyAPI) -> Endpoint<ArtsyAPI> in
var endpoint: Endpoint<ArtsyAPI> = Endpoint<ArtsyAPI>(URL: url(target), sampleResponse: .Success(200, {target.sampleData}), method: target.method, parameters: target.parameters)
// Sign all non-XApp token requests
switch target {
case .XApp:
return endpoint
case .XAuth:
return endpoint
default:
return endpoint.endpointByAddingHTTPHeaderFields(["X-Xapp-Token": XAppToken().token ?? ""])
}
}
public static func DefaultProvider() -> ArtsyProvider<ArtsyAPI> {
return ArtsyProvider(endpointsClosure: endpointsClosure, endpointResolver: endpointResolver(), stubResponses: APIKeys.sharedKeys.stubResponses)
}
public static func StubbingProvider() -> ArtsyProvider<ArtsyAPI> {
return ArtsyProvider(endpointsClosure: endpointsClosure, endpointResolver: endpointResolver(), stubResponses: true, onlineSignal: { RACSignal.empty() })
}
private struct SharedProvider {
static var instance = Provider.DefaultProvider()
}
public static var sharedProvider: ArtsyProvider<ArtsyAPI> {
get {
return SharedProvider.instance
}
set (newSharedProvider) {
SharedProvider.instance = newSharedProvider
}
}
}
// MARK: - Provider support
private func stubbedResponse(filename: String) -> NSData! {
@objc class TestClass { }
let bundle = NSBundle(forClass: TestClass.self)
let path = bundle.pathForResource(filename, ofType: "json")
return NSData(contentsOfFile: path!)
}
private extension String {
var URLEscapedString: String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())!
}
}
public func url(route: MoyaTarget) -> String {
return route.baseURL.URLByAppendingPathComponent(route.path).absoluteString!
}
| mit | 100d16a1a6395e5be7394649274b061b | 29.744361 | 403 | 0.623624 | 4.875596 | false | false | false | false |
hxx0215/VPNOn | VPNOn/AppDelegate.swift | 1 | 6325 | //
// AppDelegate.swift
// VPNOn
//
// Created by Lex Tang on 12/5/14.
// Copyright (c) 2014 LexTang.com. All rights reserved.
//
import UIKit
import CoreData
import VPNOnKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
splitViewController.delegate = self
splitViewController.preferredDisplayMode = .AllVisible
LTThemeManager.sharedManager.activateTheme()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
}
// MARK: - URL scheme
func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
var willConnect = false
var callback = ""
if let query = url.query {
let comps = query.componentsSeparatedByString("&")
if query == "connect" {
willConnect = true
} else if comps.count > 1 {
if comps[0] == "connect" {
willConnect = true
}
let callbackQuery = comps[1].componentsSeparatedByString("=")
if callbackQuery[0] == "callback" {
callback = callbackQuery[1]
}
}
}
if willConnect {
if let title = url.host {
let vpns = VPNDataManager.sharedManager.VPNHasTitle(title)
if vpns.count > 0 {
let vpn = vpns[0]
let passwordRef = VPNKeychainWrapper.passwordForVPNID(vpn.ID)
let secretRef = VPNKeychainWrapper.secretForVPNID(vpn.ID)
let certificate = VPNKeychainWrapper.certificateForVPNID(vpn.ID)
VPNDataManager.sharedManager.selectedVPNID = vpn.objectID
NSNotificationCenter.defaultCenter().postNotificationName("kLTSelectionDidChange", object: nil)
if vpn.ikev2 {
VPNManager.sharedManager.connectIKEv2(vpn.title, server: vpn.server, account: vpn.account, group: vpn.group, alwaysOn: vpn.alwaysOn, passwordRef: passwordRef, secretRef: secretRef, certificate: certificate)
} else {
VPNManager.sharedManager.connectIPSec(vpn.title, server: vpn.server, account: vpn.account, group: vpn.group, alwaysOn: vpn.alwaysOn, passwordRef: passwordRef, secretRef: secretRef, certificate: certificate)
}
if !callback.isEmpty {
if let url = NSURL(string: callback) {
UIApplication.sharedApplication().openURL(url)
}
}
}
}
} else {
if let host = url.host {
if let info = VPN.parseURL(url) {
let splitVC = window!.rootViewController as! UISplitViewController
let detailNC = splitVC.viewControllers.last! as! UINavigationController
detailNC.popToRootViewControllerAnimated(false)
let createVC = splitVC.storyboard!.instantiateViewControllerWithIdentifier(
NSStringFromClass(LTVPNConfigViewController)
) as! LTVPNConfigViewController
createVC.initializedVPNInfo = info
detailNC.pushViewController(createVC, animated: false)
}
}
}
return true
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
return false
}
}
| mit | df0239343e81275f12a9886b4e23a440 | 47.282443 | 285 | 0.633676 | 6.02381 | false | false | false | false |
Fluffcorn/ios-sticker-packs-app | MessagesExtension/WAStickers code files/Interoperability.swift | 1 | 2237 | //
// Copyright (c) WhatsApp Inc. and its affiliates.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
//
import UIKit
struct Interoperability {
private static let DefaultBundleIdentifier: String = "WA.WAStickersThirdParty"
private static let PasteboardExpirationSeconds: TimeInterval = 60
private static let PasteboardStickerPackDataType: String = "net.whatsapp.third-party.sticker-pack"
private static let WhatsAppURL: URL = URL(string: "whatsapp://stickerPack")!
static var iOSAppStoreLink: String?
static var AndroidStoreLink: String?
static func canSend() -> Bool {
return true
//return UIApplication.shared.canOpenURL(URL(string: "whatsapp://")!)
}
static func send(json: [String: Any]) -> (Bool, Data?) {
if Bundle.main.bundleIdentifier?.contains(DefaultBundleIdentifier) == true {
fatalError("Your bundle identifier must not include the default one.")
}
let pasteboard = UIPasteboard.general
var jsonWithAppStoreLink: [String: Any] = json
jsonWithAppStoreLink["ios_app_store_link"] = "http://itunes.apple.com/app/id1171532447"
jsonWithAppStoreLink["android_play_store_link"] = AndroidStoreLink
guard let dataToSend = try? JSONSerialization.data(withJSONObject: jsonWithAppStoreLink, options: []) else {
return (false, nil)
}
if #available(iOS 10.0, *) {
pasteboard.setItems([[PasteboardStickerPackDataType: dataToSend]], options: [UIPasteboard.OptionsKey.localOnly: true])
} else {
pasteboard.setData(dataToSend, forPasteboardType: PasteboardStickerPackDataType)
}
DispatchQueue.main.async {
if canSend() {
if #available(iOS 10.0, *) {
//UIApplication.sharedApplication.open(WhatsAppURL)
} else {
//UIApplication.shared.openURL(WhatsAppURL)
}
}
}
return (true, dataToSend)
}
static func copyImageToPasteboard(image: UIImage) {
UIPasteboard.general.image = image
}
}
| mit | add457012f5763a4b59a0f05f18de5c3 | 35.672131 | 130 | 0.654895 | 4.593429 | false | false | false | false |
lionchina/RxSwiftBook | RxGithubSignup/RxGithubSignup/SignupViewModel.swift | 1 | 2841 | //
// SignupViewModel.swift
// RxGithubSignup
//
// Created by MaxChen on 06/08/2017.
// Copyright © 2017 com.linglustudio. All rights reserved.
//
import RxCocoa
import RxSwift
class SignupViewModel {
let validatedUsername: Observable<ValidationResult>
let validatedPassword: Observable<ValidationResult>
let validatedPasswordRepeat: Observable<ValidationResult>
let signupEnabled: Observable<Bool>
let signedIn: Observable<Bool>
let signingIn: Observable<Bool>
init(input: (username: Observable<String>, password: Observable<String>, passwordRepeat: Observable<String>, loginTaps: Observable<Void>), dependency: (API: GitHubAPI, validationService: GitHubValidationService, wireframe: Wireframe)) {
let API = dependency.API
let validationService = dependency.validationService
let wireframe = dependency.wireframe
validatedUsername = input.username
.flatMapLatest { username in
return validationService.validateUsername(username).observeOn(MainScheduler.instance).catchErrorJustReturn(.failed(message: "Error contacting server"))
}.shareReplay(1)
validatedPassword = input.password
.map { password in
return validationService.validatePassword(password)
}.shareReplay(1)
validatedPasswordRepeat = Observable.combineLatest(input.password, input.passwordRepeat, resultSelector: validationService.validatePasswordRepeat).shareReplay(1)
let signingIn = ActivityIndicator()
self.signingIn = signingIn.asObservable()
let usernameAndPassword = Observable.combineLatest(input.username, input.password) { ($0, $1) }
signedIn = input.loginTaps.withLatestFrom(usernameAndPassword)
.flatMapLatest { (username, password) in
return API.signup(username, password: password)
.observeOn(MainScheduler.instance)
.catchErrorJustReturn(false)
.trackActivity(signingIn)
}
.flatMapLatest { loggedIn -> Observable<Bool> in
let message = loggedIn ? "Mock: Signed in to GitHub." : "Mock: Sign in to GitHub failed"
return wireframe.promptFor(message, cancelAction: "OK", actions: [])
.map { _ in
loggedIn
}
}.shareReplay(1)
signupEnabled = Observable.combineLatest(validatedUsername, validatedPassword, validatedPasswordRepeat, signingIn.asObservable()) { username, password, passwordRepeat, signingIn in
username.isValid && password.isValid && passwordRepeat.isValid && !signingIn
}.distinctUntilChanged()
.shareReplay(1)
}
}
| apache-2.0 | b6e712191d25895582937e3b3aa43b09 | 44.079365 | 240 | 0.65669 | 5.646123 | false | true | false | false |
wikimedia/wikipedia-ios | WMF Framework/RelatedSearchFetcher.swift | 1 | 2233 | import Foundation
@objc(WMFRelatedSearchFetcher)
final class RelatedSearchFetcher: Fetcher {
private struct RelatedPages: Decodable {
let pages: [ArticleSummary]?
}
@objc func fetchRelatedArticles(forArticleWithURL articleURL: URL?, completion: @escaping (Error?, [WMFInMemoryURLKey: ArticleSummary]?) -> Void) {
guard
let articleURL = articleURL,
let articleTitle = articleURL.percentEncodedPageTitleForPathComponents
else {
completion(Fetcher.invalidParametersError, nil)
return
}
let pathComponents = ["page", "related", articleTitle]
guard let taskURL = configuration.pageContentServiceAPIURLForURL(articleURL, appending: pathComponents) else {
completion(Fetcher.invalidParametersError, nil)
return
}
session.jsonDecodableTask(with: taskURL) { (relatedPages: RelatedPages?, response, error) in
if let error = error {
completion(error, nil)
return
}
guard let response = response as? HTTPURLResponse else {
completion(Fetcher.unexpectedResponseError, nil)
return
}
guard response.statusCode == 200 else {
let error = response.statusCode == 302 ? Fetcher.noNewDataError : Fetcher.unexpectedResponseError
completion(error, nil)
return
}
guard let summaries = relatedPages?.pages, summaries.count > 0 else {
completion(Fetcher.unexpectedResponseError, nil)
return
}
let summaryKeysWithValues: [(WMFInMemoryURLKey, ArticleSummary)] = summaries.compactMap { (summary) -> (WMFInMemoryURLKey, ArticleSummary)? in
summary.languageVariantCode = articleURL.wmf_languageVariantCode
guard let articleKey = summary.key else {
return nil
}
return (articleKey, summary)
}
completion(nil, Dictionary(uniqueKeysWithValues: summaryKeysWithValues))
}
}
}
| mit | 6b3dc9a95fa0a996704534d1a2ac6376 | 38.175439 | 154 | 0.592476 | 5.907407 | false | false | false | false |
MukeshKumarS/Swift | stdlib/public/core/Map.swift | 4 | 6666 | //===--- Map.swift - Lazily map over a SequenceType -----------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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
//
//===----------------------------------------------------------------------===//
/// The `GeneratorType` used by `MapSequence` and `MapCollection`.
/// Produces each element by passing the output of the `Base`
/// `GeneratorType` through a transform function returning `Element`.
public struct LazyMapGenerator<
Base : GeneratorType, Element
> : GeneratorType, SequenceType {
@available(*, unavailable, renamed="Element")
public typealias T = Element
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Requires: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`.
public mutating func next() -> Element? {
return _base.next().map(_transform)
}
public var base: Base { return _base }
internal var _base: Base
internal var _transform: (Base.Element)->Element
}
/// A `SequenceType` whose elements consist of those in a `Base`
/// `SequenceType` 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 struct LazyMapSequence<Base : SequenceType, Element>
: LazySequenceType {
public typealias Elements = LazyMapSequence
/// Return a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> LazyMapGenerator<Base.Generator, Element> {
return LazyMapGenerator(_base: _base.generate(), _transform: _transform)
}
/// Return a value less than or equal to the number of elements in
/// `self`, **nondestructively**.
///
/// - Complexity: O(N).
public func underestimateCount() -> Int {
return _base.underestimateCount()
}
/// Create an instance with elements `transform(x)` for each element
/// `x` of base.
public init(_ base: Base, transform: (Base.Generator.Element)->Element) {
self._base = base
self._transform = transform
}
public var _base: Base
internal var _transform: (Base.Generator.Element)->Element
@available(*, unavailable, renamed="Element")
public typealias T = Element
}
//===--- Collections ------------------------------------------------------===//
/// A `CollectionType` whose elements consist of those in a `Base`
/// `CollectionType` 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 struct LazyMapCollection<Base : CollectionType, Element>
: LazyCollectionType {
// FIXME: Should be inferrable.
public typealias Index = Base.Index
public var startIndex: Base.Index { return _base.startIndex }
public var endIndex: Base.Index { return _base.endIndex }
/// Access the element at `position`.
///
/// - Requires: `position` is a valid position in `self` and
/// `position != endIndex`.
public subscript(position: Base.Index) -> Element {
return _transform(_base[position])
}
/// Returns `true` iff `self` is empty.
public var isEmpty: Bool { return _base.isEmpty }
public var first: Element? { return _base.first.map(_transform) }
/// Returns a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> LazyMapGenerator<Base.Generator, Element> {
return LazyMapGenerator(_base: _base.generate(), _transform: _transform)
}
public func underestimateCount() -> Int {
return _base.underestimateCount()
}
/// Returns the number of elements.
///
/// - Complexity: O(1) if `Index` conforms to `RandomAccessIndexType`;
/// O(N) otherwise.
public var count: Base.Index.Distance {
return _base.count
}
/// Create an instance with elements `transform(x)` for each element
/// `x` of base.
public init(_ base: Base, transform: (Base.Generator.Element)->Element) {
self._base = base
self._transform = transform
}
public var _base: Base
var _transform: (Base.Generator.Element)->Element
@available(*, unavailable, renamed="Element")
public typealias T = Element
}
//===--- Support for s.lazy ----------------------------------------------===//
extension LazySequenceType {
/// Return 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.
@warn_unused_result
public func map<U>(
transform: (Elements.Generator.Element) -> U
) -> LazyMapSequence<Self.Elements, U> {
return LazyMapSequence(self.elements, transform: transform)
}
}
extension LazyCollectionType {
/// Return a `LazyMapCollection` over this `Collection`. The elements of
/// the result are computed lazily, each time they are read, by
/// calling `transform` function on a base element.
@warn_unused_result
public func map<U>(
transform: (Elements.Generator.Element) -> U
) -> LazyMapCollection<Self.Elements, U> {
return LazyMapCollection(self.elements, transform: transform)
}
}
/// Return an `Array` containing the results of mapping `transform`
/// over `source`.
@available(*, unavailable, message="call the 'map()' method on the sequence")
public func map<C : CollectionType, T>(
source: C, _ transform: (C.Generator.Element) -> T
) -> [T] {
fatalError("unavailable function can't be called")
}
/// Return an `Array` containing the results of mapping `transform`
/// over `source` and flattening the result.
@available(*, unavailable, message="call the 'flatMap()' method on the sequence")
public func flatMap<C : CollectionType, T>(
source: C, _ transform: (C.Generator.Element) -> [T]
) -> [T] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="LazyMapGenerator")
public struct MapSequenceGenerator<Base : GeneratorType, T> {}
@available(*, unavailable, renamed="LazyMapSequence")
public struct MapSequenceView<Base : SequenceType, T> {}
@available(*, unavailable, renamed="LazyMapCollection")
public struct MapCollectionView<Base : CollectionType, T> {}
// ${'Local Variables'}:
// eval: (read-only-mode 1)
// End:
| apache-2.0 | b3bb641f221eaa693e0457d3ef1404e3 | 33.53886 | 81 | 0.672667 | 4.275818 | false | false | false | false |
benlangmuir/swift | test/stdlib/TypeName.swift | 9 | 7215 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -O -module-name=main %s -o %t/O.out
// RUN: %target-codesign %t/O.out
// RUN: %target-run %t/O.out
// RUN: %target-build-swift -Onone -module-name=main %s -o %t/Onone.out
// RUN: %target-codesign %t/Onone.out
// RUN: %target-run %t/Onone.out
// REQUIRES: executable_test
// Freestanding/minimal runtime does not support printing type names at runtime.
// UNSUPPORTED: freestanding
import StdlibUnittest
let TypeNameTests = TestSuite("TypeName")
class C {}
struct S {}
enum E {}
protocol P {}
protocol P2 {}
protocol P3 {}
protocol AssociatedTypes {
associatedtype A
associatedtype B
associatedtype C
}
class Model : AssociatedTypes {
typealias A = C
typealias B = S
typealias C = E
}
struct Model2 : AssociatedTypes {
typealias A = C
typealias B = S
typealias C = E
}
class GC<T : AssociatedTypes> {}
struct GS<T : AssociatedTypes> {}
enum GE<T : AssociatedTypes> {}
class GC2<T : AssociatedTypes, U : AssociatedTypes> {}
TypeNameTests.test("Prints") {
expectEqual("Swift.Int", _typeName(Int.self))
expectEqual("main.C", _typeName(C.self))
expectEqual("main.S", _typeName(S.self))
expectEqual("main.E", _typeName(E.self))
expectEqual("main.GC<main.Model>",
_typeName(GC<Model>.self))
expectEqual("main.GS<main.Model>",
_typeName(GS<Model>.self))
expectEqual("main.GE<main.Model>",
_typeName(GE<Model>.self))
expectEqual("main.GC2<main.Model, main.Model2>",
_typeName(GC2<Model, Model2>.self))
expectEqual("main.P", _typeName(P.self))
typealias PP2 = P & P2
expectEqual("main.P & main.P2",
_typeName(PP2.self))
expectEqual("Any", _typeName(Any.self))
expectEqual("main.P & main.P2", _typeName((P & P2).self))
typealias F = () -> ()
typealias F2 = () -> () -> ()
typealias F3 = (() -> ()) -> ()
typealias F4 = (Int, Float) -> ()
typealias F5 = ((Int, Float)) -> ()
typealias F6 = (Int...) -> ()
expectEqual("() -> ()", _typeName(F.self))
expectEqual("() -> () -> ()", _typeName(F2.self))
expectEqual("(() -> ()) -> ()", _typeName(F3.self))
expectEqual("() -> ()", _typeName((() -> ()).self))
expectEqual("(Swift.Int, Swift.Float) -> ()", _typeName(F4.self))
expectEqual("((Swift.Int, Swift.Float)) -> ()", _typeName(F5.self))
expectEqual("(Swift.Int...) -> ()", _typeName(F6.self))
expectEqual("(main.P) -> main.P2 & main.P3",
_typeName(((P) -> P2 & P3).self))
expectEqual("() -> main.P & main.P2 & main.P3",
_typeName((() -> P & P2 & P3).self))
expectEqual("(main.P & main.P2) -> main.P & main.P3",
_typeName(((P & P2) -> P3 & P).self))
#if _runtime(_ObjC)
typealias B = @convention(block) () -> ()
typealias B2 = () -> @convention(block) () -> ()
typealias B3 = (@convention(block) () -> ()) -> ()
expectEqual("@convention(block) () -> ()", _typeName(B.self))
expectEqual("() -> @convention(block) () -> ()",
_typeName(B2.self))
expectEqual("(@convention(block) () -> ()) -> ()",
_typeName(B3.self))
#endif
expectEqual("(() -> ()).Type", _typeName(F.Type.self))
expectEqual("main.C.Type", _typeName(C.Type.self))
expectEqual("main.C.Type.Type", _typeName(C.Type.Type.self))
expectEqual("Any.Type", _typeName(Any.Type.self))
expectEqual("Any.Protocol", _typeName(Any.Protocol.self))
expectEqual("Swift.AnyObject", _typeName(AnyObject.self))
expectEqual("Swift.AnyObject.Type", _typeName(AnyClass.self))
expectEqual("Swift.Optional<Swift.AnyObject>",
_typeName((AnyObject?).self))
expectEqual("()", _typeName(Void.self))
typealias Tup = (Any, F, C)
expectEqual("(Any, () -> (), main.C)",
_typeName(Tup.self))
}
TypeNameTests.test("Inout") {
typealias IF = (inout Int) -> ()
typealias IF2 = (inout Int) -> (inout Int) -> ()
typealias IF3 = ((inout Int) -> ()) -> ()
typealias IF3a = (inout ((Int) -> ())) -> ()
typealias IF3b = (inout ((Int) -> ())) -> ()
typealias IF3c = ((inout Int) -> ()) -> ()
typealias IF4 = (inout (() -> ())) -> ()
typealias IF5 = (inout Int, Any) -> ()
expectEqual("(inout Swift.Int) -> ()", _typeName(IF.self))
expectEqual("(inout Swift.Int) -> (inout Swift.Int) -> ()",
_typeName(IF2.self))
expectEqual("((inout Swift.Int) -> ()) -> ()",
_typeName(IF3.self))
expectEqual("(inout (Swift.Int) -> ()) -> ()",
_typeName(IF3a.self))
expectEqual("(inout (Swift.Int) -> ()) -> ()",
_typeName(IF3b.self))
expectEqual("((inout Swift.Int) -> ()) -> ()",
_typeName(IF3c.self))
expectEqual("(inout () -> ()) -> ()",
_typeName(IF4.self))
expectEqual("(inout Swift.Int, Any) -> ()",
_typeName(IF5.self))
}
TypeNameTests.test("Functions") {
func curry1() {
}
func curry1Throws() throws {
}
func curry2() -> () -> () {
return curry1
}
func curry2Throws() throws -> () -> () {
return curry1
}
func curry3() -> () throws -> () {
return curry1Throws
}
func curry3Throws() throws -> () throws -> () {
return curry1Throws
}
expectEqual("() -> ()",
_typeName(type(of: curry1)))
expectEqual("() -> () -> ()",
_typeName(type(of: curry2)))
expectEqual("() throws -> () -> ()",
_typeName(type(of: curry2Throws)))
expectEqual("() -> () throws -> ()",
_typeName(type(of: curry3)))
expectEqual("() throws -> () throws -> ()",
_typeName(type(of: curry3Throws)))
}
class SomeOuterClass {
struct SomeInnerStruct {}
struct SomeInnerGenericStruct<T> {}
}
class SomeOuterGenericClass<T> {
struct SomeInnerStruct {}
struct SomeInnerGenericStruct<U> {}
}
TypeNameTests.test("Nested") {
expectEqual("main.SomeOuterClass.SomeInnerStruct",
_typeName(SomeOuterClass.SomeInnerStruct.self));
expectEqual("main.SomeOuterClass.SomeInnerGenericStruct<Swift.Int>",
_typeName(SomeOuterClass.SomeInnerGenericStruct<Int>.self));
expectEqual("main.SomeOuterGenericClass<Swift.Int>.SomeInnerStruct",
_typeName(SomeOuterGenericClass<Int>.SomeInnerStruct.self));
expectEqual("main.SomeOuterGenericClass<Swift.String>.SomeInnerGenericStruct<Swift.Int>",
_typeName(SomeOuterGenericClass<String>.SomeInnerGenericStruct<Int>.self));
}
extension SomeOuterGenericClass {
struct OtherInnerStruct {}
struct OtherInnerGenericStruct<U> {}
}
TypeNameTests.test("NestedInExtension") {
expectEqual("main.SomeOuterGenericClass<Swift.Int>.OtherInnerStruct",
_typeName(SomeOuterGenericClass<Int>.OtherInnerStruct.self));
expectEqual("main.SomeOuterGenericClass<Swift.Int>.OtherInnerGenericStruct<Swift.String>",
_typeName(SomeOuterGenericClass<Int>.OtherInnerGenericStruct<String>.self));
}
extension SomeOuterGenericClass where T == Int {
struct AnotherInnerStruct {}
struct AnotherInnerGenericStruct<U> {}
}
TypeNameTests.test("NestedInConstrainedExtension") {
expectEqual("(extension in main):main.SomeOuterGenericClass<Swift.Int>.AnotherInnerStruct",
_typeName(SomeOuterGenericClass<Int>.AnotherInnerStruct.self));
expectEqual("(extension in main):main.SomeOuterGenericClass<Swift.Int>.AnotherInnerGenericStruct<Swift.String>",
_typeName(SomeOuterGenericClass<Int>.AnotherInnerGenericStruct<String>.self));
}
runAllTests()
| apache-2.0 | 63083909e78b60e1161681f5984ef83e | 30.644737 | 114 | 0.637699 | 3.478785 | false | true | false | false |
SeraZheng/GitHouse.swift | GitHouse/IssueTableCell.swift | 1 | 2978 | //
// IssueTableCell.swift
// GitHouse
//
// Created by 郑少博 on 16/4/14.
// Copyright © 2016年 郑少博. All rights reserved.
//
import UIKit
import Octokit
public class IssueTableCell: UITableViewCell {
private var iconView: UIImageView?
private var titleLabel: UILabel?
private var descriptionLabel: UILabel?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
iconView = UIImageView(image: UIImage(named: "PlaceHolder"))
iconView!.contentMode = UIViewContentMode.ScaleToFill
contentView.addSubview(iconView!)
titleLabel = UILabel()
titleLabel!.numberOfLines = 1
titleLabel!.font = UIFont.boldSystemFontOfSize(20)
titleLabel!.textColor = UIColor.flatBlueColorDark()
titleLabel!.preferredMaxLayoutWidth = CGRectGetWidth(contentView.bounds) - 80
contentView.addSubview(titleLabel!)
descriptionLabel = UILabel()
descriptionLabel!.numberOfLines = 2
descriptionLabel!.font = UIFont.systemFontOfSize(14)
descriptionLabel!.textColor = UIColor.lightGrayColor()
descriptionLabel!.preferredMaxLayoutWidth = CGRectGetWidth(contentView.bounds) - 80
contentView.addSubview(descriptionLabel!)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func prepareForReuse() {
titleLabel?.text = ""
descriptionLabel?.text = ""
iconView?.image = UIImage(named: "PlaceHolder")
iconView?.af_cancelImageRequest()
super.prepareForReuse()
}
override public func updateConstraints() {
iconView!.snp_makeConstraints { (make) in
make.width.equalTo(60)
make.height.equalTo(60)
make.right.equalTo(-10)
make.top.equalTo(5)
}
titleLabel!.snp_makeConstraints { (make) in
make.left.equalTo(10)
make.top.equalTo(iconView!)
make.right.equalTo((iconView?.snp_left)!).offset(-10)
make.height.equalTo(20)
}
descriptionLabel!.snp_makeConstraints { (make) in
make.left.equalTo(titleLabel!)
make.right.equalTo(titleLabel!)
make.top.equalTo(titleLabel!.snp_bottom).offset(5)
make.bottom.equalTo(contentView.snp_bottom).offset(-5)
}
super.updateConstraints()
}
public func configCell(issue: Issue) -> Void {
iconView!.af_setImageWithURL(NSURL.init(string: (issue.user?.avatarURL)!)!)
titleLabel!.text = issue.title
if let description = issue.body {
descriptionLabel!.text = description
}
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
}
| mit | 4506974f12ccfcf57542cc61a533aa56 | 31.56044 | 91 | 0.625717 | 5.207381 | false | false | false | false |
wireapp/wire-ios | Wire-iOS Tests/DestructionCountdownViewTests.swift | 1 | 3141 | //
// Wire
// Copyright (C) 2016 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 XCTest
@testable import Wire
final class DestructionCountdownViewTests: ZMSnapshotTestCase {
var sut: DestructionCountdownView!
override func setUp() {
super.setUp()
}
override func tearDown() {
resetColorScheme()
sut = nil
super.tearDown()
}
func prepareSut(variant: ColorSchemeVariant = .light) {
ColorScheme.default.variant = variant
sut = DestructionCountdownView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
sut.backgroundColor = UIColor.from(scheme: .contentBackground)
}
func testThatItRendersCorrectlyInInitialState() {
prepareSut()
sut.setNeedsLayout()
sut.layoutIfNeeded()
verify(view: sut)
}
func testThatItRendersCorrectly_80_Percent_Progress() {
prepareSut()
sut.setProgress(0.8)
sut.setNeedsLayout()
sut.layoutIfNeeded()
verify(view: sut)
}
func testThatItRendersCorrectly_60_Percent_Progress() {
prepareSut()
sut.setProgress(0.6)
sut.setNeedsLayout()
sut.layoutIfNeeded()
verify(view: sut)
}
func testThatItRendersCorrectly_50_Percent_Progress() {
prepareSut()
sut.setProgress(0.5)
sut.setNeedsLayout()
sut.layoutIfNeeded()
verify(view: sut)
}
func testThatItRendersCorrectly_40_Percent_Progress() {
prepareSut()
sut.setProgress(0.4)
sut.setNeedsLayout()
sut.layoutIfNeeded()
verify(view: sut) }
func testThatItRendersCorrectly_20_Percent_Progress() {
prepareSut()
sut.setProgress(0.2)
sut.setNeedsLayout()
sut.layoutIfNeeded()
verify(view: sut)
}
func testThatItRendersCorrectly_0_Percent_Progress() {
prepareSut()
sut.setProgress(0)
sut.setNeedsLayout()
sut.layoutIfNeeded()
verify(view: sut)
}
func testThatItAnimatesProgress() {
prepareSut()
sut.startAnimating(duration: 5, currentProgress: 0.2)
XCTAssertTrue(sut.isAnimatingProgress)
sut.stopAnimating()
XCTAssertFalse(sut.isAnimatingProgress)
}
func testThatItRendersCorrectly_80_Percent_Progress_in_dark_theme() {
prepareSut(variant: .dark)
sut.setProgress(0.8)
sut.setNeedsLayout()
sut.layoutIfNeeded()
verify(view: sut)
}
}
| gpl-3.0 | dd96838b3665120962ee5b0eb38b4d30 | 24.958678 | 90 | 0.647564 | 4.532468 | false | true | false | false |
hassanabidpk/umapit_ios | uMAPit/controllers/ProfileViewController.swift | 1 | 9535 | //
// ProfileViewController.swift
// uMAPit
//
// Created by Hassan Abid on 12/02/2017.
// Copyright © 2017 uMAPit. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import RealmSwift
import Kingfisher
#if DEBUG
let BASE_USER_URL = "http://localhost:8000/rest-auth/user/"
let BASE_LOGOUT_URL = "http://localhost:8000/rest-auth/logout/"
#else
let BASE_USER_URL = "https://umapit.azurewebsites.net/rest-auth/user/"
let BASE_LOGOUT_URL = "https://umapit.azurewebsites.net/rest-auth/logout/"
#endif
class ProfileViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var userPlacesTableView: UITableView!
static let GRAVATAR_IMAGE_URL = "https://www.gravatar.com/avatar/"
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var name: UILabel!
var realm: Realm!
var placesResult: Results<Place>?
var notificationToken: NotificationToken?
override func viewDidLoad() {
super.viewDidLoad()
setUI()
realm = try! Realm()
// Set realm notification block
notificationToken = realm.addNotificationBlock { [unowned self] note, realm in
self.userPlacesTableView.reloadData()
}
self.getUserDetails()
}
override func viewWillAppear(_ animated: Bool) {
self.tabBarController?.tabBar.isHidden = false
}
// MARK - Helper methods
func setUI() {
self.navigationController?.navigationBar.barTintColor = UIColor.white
self.navigationController?.navigationBar.tintColor = Constants.tintColor
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: Constants.tintColor]
let logoutButton = UIBarButtonItem(title: "Log out", style: UIBarButtonItemStyle.plain, target: self, action: #selector(actionLogoutUser(_:)))
logoutButton.tintColor = UIColor.black
self.navigationItem.rightBarButtonItem = logoutButton
}
func getUserDetails() {
let userDefaults = UserDefaults.standard
let username = userDefaults.value(forKey: "username")
let predicate = NSPredicate(format: "username = %@", "\(username!)")
let results = try! Realm().objects(User.self).filter(predicate)
if(results.count > 0) {
let user = results[0]
self.setUserUI(first_name: user.first_name,
last_name: user.last_name,
email: user.email,
username: user.username)
} else {
let strToken = userDefaults.value(forKey: "userToken")
let authToken = "Token \(strToken!)"
let headers = [
"Authorization": authToken
]
Alamofire.request(BASE_USER_URL, parameters: nil, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in
debugPrint(response)
if let userDetails = response.result.value {
let json = JSON(userDetails)
if let first_name = json["first_name"].string,
let last_name = json["last_name"].string,
let username = json["username"].string,
let email = json["email"].string {
print("token: \(json) with firstName: \(first_name)")
let realm = try! Realm()
realm.beginWrite()
realm.create(User.self, value: ["first_name" : first_name,
"last_name" : last_name,
"email" : email,
"username" : username,
"pk" : json["pk"].intValue ])
try! realm.commitWrite()
self.setUserUI(first_name: first_name,
last_name: last_name,
email: email,
username: username)
} else {
print("login failed \(userDetails)")
}
}
}
}
}
func actionLogoutUser(_ sender:UIBarButtonItem) {
print("logout")
Alamofire.request(BASE_LOGOUT_URL).validate().responseJSON { response in
switch response.result {
case .success:
let userDefaults = UserDefaults.standard
userDefaults.removeObject(forKey: "userToken")
userDefaults.removeObject(forKey: "username")
userDefaults.synchronize()
self.deleteAllRealmDB()
let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LandingPageViewController") as! LandingPageViewController
let appDel:UIApplicationDelegate = UIApplication.shared.delegate!
appDel.window??.rootViewController = loginVC
print("Logout Successful")
case .failure(let error):
print(error)
}
}
self.dismiss(animated: true, completion: nil)
}
func deleteAllRealmDB() {
let realm = try! Realm()
try! realm.write {
realm.deleteAll()
print("deleted realm db because user has logout");
}
}
func setUserUI(first_name: String, last_name: String, email: String, username: String ) {
self.name.text = "\(first_name) \(last_name)"
let hash = email.md5
self.profileImage.kf.setImage(with: URL(string: "\(ProfileViewController.GRAVATAR_IMAGE_URL)\(hash)?s=150")!,
placeholder: nil,
options: [.transition(.fade(1))],
progressBlock: nil,
completionHandler: nil)
setUserPlaces(user_name: username)
}
func setUserPlaces(user_name: String) {
let predicate = NSPredicate(format: "username = %@", "\(user_name)")
let user = realm.objects(User.self).filter(predicate)
placesResult = realm.objects(Place.self).filter("user == %@", user[0])
self.userPlacesTableView.reloadData()
}
// MARK: - UITableView Delegate methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let result = placesResult {
return result.count
}
return 0
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "profilecell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ProfileTableViewCell
if let result = placesResult {
let object = result[indexPath.row]
cell.placeNameLabel?.text = object.name
let formatted_date = getFormattedDateForUI(object.created_at)
cell.createdAtLabel.text = "MAPPED \(formatted_date)"
cell.placeImage.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleBottomMargin, .flexibleRightMargin, .flexibleLeftMargin, .flexibleTopMargin]
cell.placeImage.contentMode = .scaleAspectFill
cell.placeImage.clipsToBounds = true
cell.placeImage.kf.setImage(with: URL(string: "\(IMAGE_BASE_URL)\(object.image_1)")!,
placeholder: nil,
options: [.transition(.fade(1))],
progressBlock: nil,
completionHandler: nil)
}
return cell
}
func getFormattedDateForUI(_ date: Date?) -> String {
if let release_date = date {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter.string(from: release_date)
}
return ""
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 5759d2443f57f7966d9414f1845007fd | 32.452632 | 166 | 0.517202 | 5.708982 | false | false | false | false |
yonaskolb/XcodeGen | Sources/ProjectSpec/BuildPhaseSpec.swift | 1 | 4540 | //
// File.swift
//
//
// Created by Yonas Kolb on 1/5/20.
//
import Foundation
import XcodeProj
import JSONUtilities
public enum BuildPhaseSpec: Equatable {
case sources
case headers
case resources
case copyFiles(CopyFilesSettings)
case none
// Not currently exposed as selectable options, but used internally
case frameworks
case runScript
case carbonResources
public struct CopyFilesSettings: Equatable, Hashable {
public static let xpcServices = CopyFilesSettings(
destination: .productsDirectory,
subpath: "$(CONTENTS_FOLDER_PATH)/XPCServices",
phaseOrder: .postCompile
)
public enum Destination: String {
case absolutePath
case productsDirectory
case wrapper
case executables
case resources
case javaResources
case frameworks
case sharedFrameworks
case sharedSupport
case plugins
public var destination: PBXCopyFilesBuildPhase.SubFolder? {
switch self {
case .absolutePath: return .absolutePath
case .productsDirectory: return .productsDirectory
case .wrapper: return .wrapper
case .executables: return .executables
case .resources: return .resources
case .javaResources: return .javaResources
case .frameworks: return .frameworks
case .sharedFrameworks: return .sharedFrameworks
case .sharedSupport: return .sharedSupport
case .plugins: return .plugins
}
}
}
public enum PhaseOrder: String {
/// Run before the Compile Sources phase
case preCompile
/// Run after the Compile Sources and post-compile Run Script phases
case postCompile
}
public var destination: Destination
public var subpath: String
public var phaseOrder: PhaseOrder
public init(
destination: Destination,
subpath: String,
phaseOrder: PhaseOrder
) {
self.destination = destination
self.subpath = subpath
self.phaseOrder = phaseOrder
}
}
public var buildPhase: BuildPhase? {
switch self {
case .sources: return .sources
case .headers: return .headers
case .resources: return .resources
case .copyFiles: return .copyFiles
case .frameworks: return .frameworks
case .runScript: return .runScript
case .carbonResources: return .carbonResources
case .none: return nil
}
}
}
extension BuildPhaseSpec {
public init(string: String) throws {
switch string {
case "sources": self = .sources
case "headers": self = .headers
case "resources": self = .resources
case "copyFiles":
throw SpecParsingError.invalidSourceBuildPhase("copyFiles must specify a \"destination\" and optional \"subpath\"")
case "none": self = .none
default:
throw SpecParsingError.invalidSourceBuildPhase(string.quoted)
}
}
}
extension BuildPhaseSpec: JSONObjectConvertible {
public init(jsonDictionary: JSONDictionary) throws {
self = .copyFiles(try jsonDictionary.json(atKeyPath: "copyFiles"))
}
}
extension BuildPhaseSpec: JSONEncodable {
public func toJSONValue() -> Any {
switch self {
case .sources: return "sources"
case .headers: return "headers"
case .resources: return "resources"
case .copyFiles(let files): return ["copyFiles": files.toJSONValue()]
case .none: return "none"
case .frameworks: fatalError("invalid build phase")
case .runScript: fatalError("invalid build phase")
case .carbonResources: fatalError("invalid build phase")
}
}
}
extension BuildPhaseSpec.CopyFilesSettings: JSONObjectConvertible {
public init(jsonDictionary: JSONDictionary) throws {
destination = try jsonDictionary.json(atKeyPath: "destination")
subpath = jsonDictionary.json(atKeyPath: "subpath") ?? ""
phaseOrder = .postCompile
}
}
extension BuildPhaseSpec.CopyFilesSettings: JSONEncodable {
public func toJSONValue() -> Any {
[
"destination": destination.rawValue,
"subpath": subpath,
]
}
}
| mit | 1aa382c6519bd2ec189343bba0f2d320 | 29.675676 | 127 | 0.614978 | 5.291375 | false | false | false | false |
devpunk/cartesian | cartesian/View/DrawProject/Menu/VDrawProjectMenuEditSpatial.swift | 1 | 3141 | import UIKit
class VDrawProjectMenuEditSpatial:UIView
{
weak var model:DNode?
private weak var controller:CDrawProject!
private let margin2:CGFloat
private let kBorderWidth:CGFloat = 1
private let kSelected:Bool = false
private let kMargin:CGFloat = 10
private let kZoom:CGFloat = 1
init(controller:CDrawProject)
{
margin2 = kMargin + kMargin
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let border:VBorder = VBorder(color:UIColor(white:0, alpha:0.1))
let button:UIButton = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = UIColor.clear
button.addTarget(
self,
action:#selector(actionButton(sender:)),
for:UIControlEvents.touchUpInside)
addSubview(border)
addSubview(button)
NSLayoutConstraint.equalsVertical(
view:border,
toView:self)
NSLayoutConstraint.rightToRight(
view:border,
toView:self)
NSLayoutConstraint.width(
view:border,
constant:kBorderWidth)
NSLayoutConstraint.equals(
view:button,
toView:self)
NotificationCenter.default.addObserver(
self,
selector:#selector(self.notifiedNodeDraw(sender:)),
name:Notification.nodeDraw,
object:nil)
}
required init?(coder:NSCoder)
{
return nil
}
deinit
{
NotificationCenter.default.removeObserver(self)
}
override func draw(_ rect:CGRect)
{
guard
let model:DNode = self.model,
let context:CGContext = UIGraphicsGetCurrentContext()
else
{
return
}
let newRect:CGRect = CGRect(
x:rect.origin.x + kMargin,
y:rect.origin.y + kMargin,
width:rect.size.width - margin2,
height:rect.size.height - margin2)
model.draw(
rect:newRect,
context:context,
zoom:kZoom,
selected:kSelected)
}
//MARK: notifications
func notifiedNodeDraw(sender notification:Notification)
{
guard
let nodeSender:DNode = notification.object as? DNode,
let currentNode:DNode = model
else
{
return
}
if currentNode === nodeSender
{
setNeedsDisplay()
}
}
//MARK: actions
func actionButton(sender button:UIButton)
{
guard
let point:CGPoint = controller.editingView?.center
else
{
return
}
controller.viewProject.viewScroll.centerOn(
point:point)
}
}
| mit | 349815ba75ffaaf8c0fec19d7549668d | 23.539063 | 71 | 0.543457 | 5.434256 | false | false | false | false |
IBM-Swift/BluePic | BluePic-iOS/BluePic/Models/BluemixConfiguration.swift | 1 | 3379 | /**
* Copyright IBM Corporation 2016, 2017
*
* 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
class BluemixConfiguration: NSObject {
//Plist Keys
fileprivate let kBluemixKeysPlistName = "cloud"
fileprivate let kIsLocalKey = "isLocal"
fileprivate let kAppRouteLocal = "appRouteLocal"
fileprivate let kAppRouteRemote = "appRouteRemote"
fileprivate let kBluemixAppRegionKey = "cloudAppRegion"
fileprivate let kBluemixPushAppGUIDKey = "pushAppGUID"
fileprivate let kBluemixPushAppClientSecret = "pushClientSecret"
fileprivate let kBluemixAppIdTenantIdKey = "appIdTenantId"
let localBaseRequestURL: String
let remoteBaseRequestURL: String
let appRegion: String
var pushAppGUID: String = ""
var pushClientSecret: String = ""
var appIdTenantId: String = ""
var isLocal: Bool = true
var isPushConfigured: Bool {
return pushAppGUID != "" && pushClientSecret != ""
}
override init() {
if var localBaseRequestURL = Utils.getStringValueWithKeyFromPlist(kBluemixKeysPlistName, key: kAppRouteLocal),
var remoteBaseRequestURL = Utils.getStringValueWithKeyFromPlist(kBluemixKeysPlistName, key: kAppRouteRemote),
let appRegion = Utils.getStringValueWithKeyFromPlist(kBluemixKeysPlistName, key: kBluemixAppRegionKey),
let isLocal = Utils.getBoolValueWithKeyFromPlist(kBluemixKeysPlistName, key: kIsLocalKey) {
self.appRegion = appRegion
self.isLocal = isLocal
if let lastChar = localBaseRequestURL.last, lastChar == "/" as Character {
localBaseRequestURL.remove(at: localBaseRequestURL.index(before: localBaseRequestURL.endIndex))
}
if let lastChar = remoteBaseRequestURL.last, lastChar == "/" as Character {
remoteBaseRequestURL.remove(at: remoteBaseRequestURL.index(before: remoteBaseRequestURL.endIndex))
}
self.localBaseRequestURL = localBaseRequestURL
self.remoteBaseRequestURL = remoteBaseRequestURL
// if present, add push app GUID and push client secret
if let pushAppGUID = Utils.getStringValueWithKeyFromPlist(kBluemixKeysPlistName, key: kBluemixPushAppGUIDKey) {
self.pushAppGUID = pushAppGUID
}
if let pushClientSecret = Utils.getStringValueWithKeyFromPlist(kBluemixKeysPlistName, key: kBluemixPushAppClientSecret) {
self.pushClientSecret = pushClientSecret
}
if let appIdTenantId = Utils.getStringValueWithKeyFromPlist(kBluemixKeysPlistName, key: kBluemixAppIdTenantIdKey) {
self.appIdTenantId = appIdTenantId
}
super.init()
} else {
fatalError("Could not load bluemix plist into object properties")
}
}
}
| apache-2.0 | 7387c9c3282e3a4f497d8c30a0ca8823 | 41.772152 | 133 | 0.699615 | 4.719274 | false | false | false | false |
BoxJeon/funjcam-ios | Platform/HTTPNetwork/Interface/HTTPNetwork.swift | 1 | 940 | import Foundation
public protocol HTTPNetwork {
func get(with params: HTTPGetParams) async throws -> HTTPNetworkResponse
}
public enum HTTPNetworkError: Error {
case malformedURL
case httpError(Int)
}
public struct HTTPGetParams {
public let url: URL?
public let headers: [String: String]?
public let queries: [String: Any]?
public init(url: URL?, headers: [String: String]?, queries :[String: Any?]?) {
self.url = url
self.headers = headers
self.queries = queries?.nilValueRemoved
}
}
public struct HTTPNetworkResponse {
public let body: Data
public init(body: Data) {
self.body = body
}
}
private extension Dictionary where Key == String, Value == Any? {
var nilValueRemoved: [String: Any] {
var newDictionary = [String: Any]()
self.forEach { key, value in
guard let value = value else { return }
newDictionary[key] = value
}
return newDictionary
}
}
| mit | 66d299a7f9e54ef2bc1f21dd800c2507 | 20.860465 | 80 | 0.676596 | 3.983051 | false | false | false | false |
AnRanScheme/magiGlobe | magi/magiGlobe/Pods/SQLite.swift/Sources/SQLite/Core/Statement.swift | 9 | 9652 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if SQLITE_SWIFT_STANDALONE
import sqlite3
#elseif SQLITE_SWIFT_SQLCIPHER
import SQLCipher
#elseif SWIFT_PACKAGE || COCOAPODS
import CSQLite
#endif
/// A single SQL statement.
public final class Statement {
fileprivate var handle: OpaquePointer? = nil
fileprivate let connection: Connection
init(_ connection: Connection, _ SQL: String) throws {
self.connection = connection
try connection.check(sqlite3_prepare_v2(connection.handle, SQL, -1, &handle, nil))
}
deinit {
sqlite3_finalize(handle)
}
public lazy var columnCount: Int = Int(sqlite3_column_count(self.handle))
public lazy var columnNames: [String] = (0..<Int32(self.columnCount)).map {
String(cString: sqlite3_column_name(self.handle, $0))
}
/// A cursor pointing to the current row.
public lazy var row: Cursor = Cursor(self)
/// Binds a list of parameters to a statement.
///
/// - Parameter values: A list of parameters to bind to the statement.
///
/// - Returns: The statement object (useful for chaining).
public func bind(_ values: Binding?...) -> Statement {
return bind(values)
}
/// Binds a list of parameters to a statement.
///
/// - Parameter values: A list of parameters to bind to the statement.
///
/// - Returns: The statement object (useful for chaining).
public func bind(_ values: [Binding?]) -> Statement {
if values.isEmpty { return self }
reset()
guard values.count == Int(sqlite3_bind_parameter_count(handle)) else {
fatalError("\(sqlite3_bind_parameter_count(handle)) values expected, \(values.count) passed")
}
for idx in 1...values.count { bind(values[idx - 1], atIndex: idx) }
return self
}
/// Binds a dictionary of named parameters to a statement.
///
/// - Parameter values: A dictionary of named parameters to bind to the
/// statement.
///
/// - Returns: The statement object (useful for chaining).
public func bind(_ values: [String: Binding?]) -> Statement {
reset()
for (name, value) in values {
let idx = sqlite3_bind_parameter_index(handle, name)
guard idx > 0 else {
fatalError("parameter not found: \(name)")
}
bind(value, atIndex: Int(idx))
}
return self
}
fileprivate func bind(_ value: Binding?, atIndex idx: Int) {
if value == nil {
sqlite3_bind_null(handle, Int32(idx))
} else if let value = value as? Blob {
sqlite3_bind_blob(handle, Int32(idx), value.bytes, Int32(value.bytes.count), SQLITE_TRANSIENT)
} else if let value = value as? Double {
sqlite3_bind_double(handle, Int32(idx), value)
} else if let value = value as? Int64 {
sqlite3_bind_int64(handle, Int32(idx), value)
} else if let value = value as? String {
sqlite3_bind_text(handle, Int32(idx), value, -1, SQLITE_TRANSIENT)
} else if let value = value as? Int {
self.bind(value.datatypeValue, atIndex: idx)
} else if let value = value as? Bool {
self.bind(value.datatypeValue, atIndex: idx)
} else if let value = value {
fatalError("tried to bind unexpected value \(value)")
}
}
/// - Parameter bindings: A list of parameters to bind to the statement.
///
/// - Throws: `Result.Error` if query execution fails.
///
/// - Returns: The statement object (useful for chaining).
@discardableResult public func run(_ bindings: Binding?...) throws -> Statement {
guard bindings.isEmpty else {
return try run(bindings)
}
reset(clearBindings: false)
repeat {} while try step()
return self
}
/// - Parameter bindings: A list of parameters to bind to the statement.
///
/// - Throws: `Result.Error` if query execution fails.
///
/// - Returns: The statement object (useful for chaining).
@discardableResult public func run(_ bindings: [Binding?]) throws -> Statement {
return try bind(bindings).run()
}
/// - Parameter bindings: A dictionary of named parameters to bind to the
/// statement.
///
/// - Throws: `Result.Error` if query execution fails.
///
/// - Returns: The statement object (useful for chaining).
@discardableResult public func run(_ bindings: [String: Binding?]) throws -> Statement {
return try bind(bindings).run()
}
/// - Parameter bindings: A list of parameters to bind to the statement.
///
/// - Returns: The first value of the first row returned.
public func scalar(_ bindings: Binding?...) throws -> Binding? {
guard bindings.isEmpty else {
return try scalar(bindings)
}
reset(clearBindings: false)
_ = try step()
return row[0]
}
/// - Parameter bindings: A list of parameters to bind to the statement.
///
/// - Returns: The first value of the first row returned.
public func scalar(_ bindings: [Binding?]) throws -> Binding? {
return try bind(bindings).scalar()
}
/// - Parameter bindings: A dictionary of named parameters to bind to the
/// statement.
///
/// - Returns: The first value of the first row returned.
public func scalar(_ bindings: [String: Binding?]) throws -> Binding? {
return try bind(bindings).scalar()
}
public func step() throws -> Bool {
return try connection.sync { try self.connection.check(sqlite3_step(self.handle)) == SQLITE_ROW }
}
fileprivate func reset(clearBindings shouldClear: Bool = true) {
sqlite3_reset(handle)
if (shouldClear) { sqlite3_clear_bindings(handle) }
}
}
extension Statement : Sequence {
public func makeIterator() -> Statement {
reset(clearBindings: false)
return self
}
}
extension Statement : IteratorProtocol {
public func next() -> [Binding?]? {
return try! step() ? Array(row) : nil
}
}
extension Statement : CustomStringConvertible {
public var description: String {
return String(cString: sqlite3_sql(handle))
}
}
public struct Cursor {
fileprivate let handle: OpaquePointer
fileprivate let columnCount: Int
fileprivate init(_ statement: Statement) {
handle = statement.handle!
columnCount = statement.columnCount
}
public subscript(idx: Int) -> Double {
return sqlite3_column_double(handle, Int32(idx))
}
public subscript(idx: Int) -> Int64 {
return sqlite3_column_int64(handle, Int32(idx))
}
public subscript(idx: Int) -> String {
return String(cString: UnsafePointer(sqlite3_column_text(handle, Int32(idx))))
}
public subscript(idx: Int) -> Blob {
if let pointer = sqlite3_column_blob(handle, Int32(idx)) {
let length = Int(sqlite3_column_bytes(handle, Int32(idx)))
return Blob(bytes: pointer, length: length)
} else {
// The return value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
// https://www.sqlite.org/c3ref/column_blob.html
return Blob(bytes: [])
}
}
// MARK: -
public subscript(idx: Int) -> Bool {
return Bool.fromDatatypeValue(self[idx])
}
public subscript(idx: Int) -> Int {
return Int.fromDatatypeValue(self[idx])
}
}
/// Cursors provide direct access to a statement’s current row.
extension Cursor : Sequence {
public subscript(idx: Int) -> Binding? {
switch sqlite3_column_type(handle, Int32(idx)) {
case SQLITE_BLOB:
return self[idx] as Blob
case SQLITE_FLOAT:
return self[idx] as Double
case SQLITE_INTEGER:
return self[idx] as Int64
case SQLITE_NULL:
return nil
case SQLITE_TEXT:
return self[idx] as String
case let type:
fatalError("unsupported column type: \(type)")
}
}
public func makeIterator() -> AnyIterator<Binding?> {
var idx = 0
return AnyIterator {
if idx >= self.columnCount {
return Optional<Binding?>.none
} else {
idx += 1
return self[idx - 1]
}
}
}
}
| mit | e973030d6e5cdfe317915f5ad20dcfeb | 31.488215 | 106 | 0.622344 | 4.344439 | false | false | false | false |
rudkx/swift | test/decl/protocol/protocol_with_superclass_where_clause.swift | 1 | 11536 | // RUN: %target-typecheck-verify-swift
// Protocols with superclass-constrained Self.
class Concrete {
typealias ConcreteAlias = String
func concreteMethod(_: ConcreteAlias) {}
}
class Generic<T> : Concrete { // expected-note 6 {{arguments to generic parameter 'T' ('Int' and 'String') are expected to be equal}}
typealias GenericAlias = (T, T)
func genericMethod(_: GenericAlias) {}
}
protocol BaseProto {}
protocol ProtoRefinesClass where Self : Generic<Int>, Self : BaseProto {
func requirementUsesClassTypes(_: ConcreteAlias, _: GenericAlias)
// expected-note@-1 {{protocol requires function 'requirementUsesClassTypes' with type '(Generic<Int>.ConcreteAlias, Generic<Int>.GenericAlias) -> ()' (aka '(String, (Int, Int)) -> ()'); do you want to add a stub?}}
}
func duplicateOverload<T : ProtoRefinesClass>(_: T) {}
// expected-note@-1 {{'duplicateOverload' previously declared here}}
func duplicateOverload<T : ProtoRefinesClass & Generic<Int>>(_: T) {}
// expected-error@-1 {{invalid redeclaration of 'duplicateOverload'}}
// expected-warning@-2 {{redundant superclass constraint 'T' : 'Generic<Int>'}}
// expected-note@-3 {{superclass constraint 'T' : 'Generic<Int>' implied here}}
extension ProtoRefinesClass {
func extensionMethodUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) {
_ = ConcreteAlias.self
_ = GenericAlias.self
concreteMethod(x)
genericMethod(y)
let _: Generic<Int> = self
let _: Concrete = self
let _: BaseProto = self
let _: BaseProto & Generic<Int> = self
let _: BaseProto & Concrete = self
let _: Generic<String> = self
// expected-error@-1 {{cannot assign value of type 'Generic<Int>' to type 'Generic<String>'}}
}
}
func usesProtoRefinesClass1(_ t: ProtoRefinesClass) {
let x: ProtoRefinesClass.ConcreteAlias = "hi"
_ = ProtoRefinesClass.ConcreteAlias.self
t.concreteMethod(x)
let y: ProtoRefinesClass.GenericAlias = (1, 2)
_ = ProtoRefinesClass.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot assign value of type 'Generic<Int>' to type 'Generic<String>'}}
}
func usesProtoRefinesClass2<T : ProtoRefinesClass>(_ t: T) {
let x: T.ConcreteAlias = "hi"
_ = T.ConcreteAlias.self
t.concreteMethod(x)
let y: T.GenericAlias = (1, 2)
_ = T.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot assign value of type 'Generic<Int>' to type 'Generic<String>'}}
}
class BadConformingClass1 : ProtoRefinesClass {
// expected-error@-1 {{type 'BadConformingClass1' does not conform to protocol 'ProtoRefinesClass'}}
// expected-error@-2 {{'ProtoRefinesClass' requires that 'BadConformingClass1' inherit from 'Generic<Int>'}}
// expected-note@-3 {{requirement specified as 'Self' : 'Generic<Int>' [with Self = BadConformingClass1]}}
func requirementUsesClassTypes(_: ConcreteAlias, _: GenericAlias) {
// expected-error@-1 {{cannot find type 'ConcreteAlias' in scope}}
// expected-error@-2 {{cannot find type 'GenericAlias' in scope}}
_ = ConcreteAlias.self
// expected-error@-1 {{cannot find 'ConcreteAlias' in scope}}
_ = GenericAlias.self
// expected-error@-1 {{cannot find 'GenericAlias' in scope}}
}
}
class BadConformingClass2 : Generic<String>, ProtoRefinesClass {
// expected-error@-1 {{'ProtoRefinesClass' requires that 'BadConformingClass2' inherit from 'Generic<Int>'}}
// expected-note@-2 {{requirement specified as 'Self' : 'Generic<Int>' [with Self = BadConformingClass2]}}
// expected-error@-3 {{type 'BadConformingClass2' does not conform to protocol 'ProtoRefinesClass'}}
// expected-note@+1 {{candidate has non-matching type '(BadConformingClass2.ConcreteAlias, BadConformingClass2.GenericAlias) -> ()' (aka '(String, (String, String)) -> ()')}}
func requirementUsesClassTypes(_: ConcreteAlias, _: GenericAlias) {
_ = ConcreteAlias.self
_ = GenericAlias.self
}
}
class GoodConformingClass : Generic<Int>, ProtoRefinesClass {
func requirementUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) {
_ = ConcreteAlias.self
_ = GenericAlias.self
concreteMethod(x)
genericMethod(y)
}
}
protocol ProtoRefinesProtoWithClass where Self : ProtoRefinesClass {}
extension ProtoRefinesProtoWithClass {
func anotherExtensionMethodUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) {
_ = ConcreteAlias.self
_ = GenericAlias.self
concreteMethod(x)
genericMethod(y)
let _: Generic<Int> = self
let _: Concrete = self
let _: BaseProto = self
let _: BaseProto & Generic<Int> = self
let _: BaseProto & Concrete = self
let _: Generic<String> = self
// expected-error@-1 {{cannot assign value of type 'Generic<Int>' to type 'Generic<String>'}}
}
}
func usesProtoRefinesProtoWithClass1(_ t: ProtoRefinesProtoWithClass) {
let x: ProtoRefinesProtoWithClass.ConcreteAlias = "hi"
_ = ProtoRefinesProtoWithClass.ConcreteAlias.self
t.concreteMethod(x)
let y: ProtoRefinesProtoWithClass.GenericAlias = (1, 2)
_ = ProtoRefinesProtoWithClass.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot assign value of type 'Generic<Int>' to type 'Generic<String>'}}
}
func usesProtoRefinesProtoWithClass2<T : ProtoRefinesProtoWithClass>(_ t: T) {
let x: T.ConcreteAlias = "hi"
_ = T.ConcreteAlias.self
t.concreteMethod(x)
let y: T.GenericAlias = (1, 2)
_ = T.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot assign value of type 'Generic<Int>' to type 'Generic<String>'}}
}
class ClassWithInits<T> {
init(notRequiredInit: ()) {}
// expected-note@-1 6{{selected non-required initializer 'init(notRequiredInit:)'}}
required init(requiredInit: ()) {}
}
protocol ProtocolWithClassInits where Self : ClassWithInits<Int> {}
func useProtocolWithClassInits1() {
_ = ProtocolWithClassInits(notRequiredInit: ())
// expected-error@-1 {{type 'any ProtocolWithClassInits' cannot be instantiated}}
_ = ProtocolWithClassInits(requiredInit: ())
// expected-error@-1 {{type 'any ProtocolWithClassInits' cannot be instantiated}}
}
func useProtocolWithClassInits2(_ t: ProtocolWithClassInits.Type) {
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'any ProtocolWithClassInits' with a metatype value must use a 'required' initializer}}
let _: ProtocolWithClassInits = t.init(requiredInit: ())
}
func useProtocolWithClassInits3<T : ProtocolWithClassInits>(_ t: T.Type) {
_ = T(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = T(requiredInit: ())
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = t.init(requiredInit: ())
}
protocol ProtocolRefinesClassInits : ProtocolWithClassInits {}
func useProtocolRefinesClassInits1() {
_ = ProtocolRefinesClassInits(notRequiredInit: ())
// expected-error@-1 {{type 'any ProtocolRefinesClassInits' cannot be instantiated}}
_ = ProtocolRefinesClassInits(requiredInit: ())
// expected-error@-1 {{type 'any ProtocolRefinesClassInits' cannot be instantiated}}
}
func useProtocolRefinesClassInits2(_ t: ProtocolRefinesClassInits.Type) {
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'any ProtocolRefinesClassInits' with a metatype value must use a 'required' initializer}}
let _: ProtocolRefinesClassInits = t.init(requiredInit: ())
}
func useProtocolRefinesClassInits3<T : ProtocolRefinesClassInits>(_ t: T.Type) {
_ = T(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = T(requiredInit: ())
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = t.init(requiredInit: ())
}
// Make sure that we don't require 'mutating' when the protocol has a superclass
// constraint.
protocol HasMutableProperty : Concrete {
var mutableThingy: Any? { get set }
}
extension HasMutableProperty {
func mutateThingy() {
mutableThingy = nil
}
}
// Some pathological examples -- just make sure they don't crash.
protocol RecursiveSelf where Self : Generic<Self> {}
// expected-error@-1 {{superclass constraint 'Self' : 'Generic<Self>' is recursive}}
protocol RecursiveAssociatedType where Self : Generic<Self.X> {
// expected-error@-1 {{superclass constraint 'Self' : 'Generic<Self.X>' is recursive}}
associatedtype X
}
protocol BaseProtocol {
typealias T = Int
}
class BaseClass : BaseProtocol {}
protocol RefinedProtocol where Self : BaseClass {
func takesT(_: T)
}
class RefinedClass : BaseClass, RefinedProtocol {
func takesT(_: T) {
_ = T.self
}
}
func takesBaseProtocol(_: BaseProtocol) {}
func passesRefinedProtocol(_ r: RefinedProtocol) {
takesBaseProtocol(r)
}
class LoopClass : LoopProto {}
protocol LoopProto where Self : LoopClass {}
class FirstClass {}
protocol FirstProtocol where Self : FirstClass {}
class SecondClass : FirstClass {}
protocol SecondProtocol where Self : SecondClass, Self : FirstProtocol {}
class FirstConformer : FirstClass, SecondProtocol {}
// expected-error@-1 {{type 'FirstConformer' does not conform to protocol 'SecondProtocol'}}
// expected-error@-2 {{'SecondProtocol' requires that 'FirstConformer' inherit from 'SecondClass'}}
// expected-note@-3 {{requirement specified as 'Self' : 'SecondClass' [with Self = FirstConformer]}}
class SecondConformer : SecondClass, SecondProtocol {}
// Duplicate superclass
// FIXME: Should be an error here too
protocol DuplicateSuper1 : Concrete where Self : Concrete {}
// expected-note@-1 {{superclass constraint 'Self' : 'Concrete' implied here}}
// expected-warning@-2 {{redundant superclass constraint 'Self' : 'Concrete'}}
protocol DuplicateSuper2 where Self : Concrete, Self : Concrete {}
// expected-note@-1 {{superclass constraint 'Self' : 'Concrete' implied here}}
// expected-warning@-2 {{redundant superclass constraint 'Self' : 'Concrete'}}
// Ambiguous name lookup situation
protocol Amb where Self : Concrete {}
// expected-note@-1 {{'Amb' previously declared here}}
// expected-note@-2 {{found this candidate}}
protocol Amb where Self : Concrete {}
// expected-error@-1 {{invalid redeclaration of 'Amb'}}
// expected-note@-2 {{found this candidate}}
extension Amb { // expected-error {{'Amb' is ambiguous for type lookup in this context}}
func extensionMethodUsesClassTypes() {
_ = ConcreteAlias.self
}
}
| apache-2.0 | 6c9a4d1729876ba7fc8fa3d186ae5495 | 32.149425 | 217 | 0.707871 | 3.865952 | false | false | false | false |
adolfrank/Swift_practise | 18-day/18-day/HomeViewController.swift | 1 | 3430 | //
// HomeViewController.swift
// 18-day
//
// Created by Hongbo Yu on 16/4/20.
// Copyright © 2016年 Frank. All rights reserved.
//
import UIKit
class HomeViewController: UITableViewController, MenuTransitionManagerDelegate {
let menuTransitionManager = MenuTransitionManager()
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
view.backgroundColor = UIColor(red:0.062, green:0.062, blue:0.07, alpha:1)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 5
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! HomeTableCell
if indexPath.row == 0 {
cell.bannerImageView.image = UIImage(named: "banner01")
cell.titleView.text = "Love mountain."
cell.authorView.text = "Allen Wang"
cell.avatarView.image = UIImage(named: "header01")
} else if indexPath.row == 1 {
cell.bannerImageView.image = UIImage(named: "banner02")
cell.titleView.text = "New graphic design - LIVE FREE"
cell.authorView.text = "Cole"
cell.avatarView.image = UIImage(named: "header02")
} else if indexPath.row == 2 {
cell.bannerImageView.image = UIImage(named: "banner03")
cell.titleView.text = "Summer sand"
cell.authorView.text = "Daniel Hooper"
cell.avatarView.image = UIImage(named: "header03")
} else if indexPath.row == 3{
cell.bannerImageView.image = UIImage(named: "banner04")
cell.titleView.text = "Seeking for signal"
cell.authorView.text = "Noby-Wan Kenobi"
cell.avatarView.image = UIImage(named: "header04")
} else {
cell.bannerImageView.image = UIImage(named: "banner05")
cell.titleView.text = "Seeking for signal"
cell.authorView.text = "Noby-Wan Kenobi"
cell.avatarView.image = UIImage(named: "header05")
}
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let menuTableViewController = segue.destinationViewController as! MenuViewController
// menuTableViewController.currentItem = self.title!
menuTableViewController.transitioningDelegate = menuTransitionManager
menuTransitionManager.delegate = self
}
func dismiss() {
dismissViewControllerAnimated(true, completion: nil)
}
func unwindToHome(segue: UIStoryboardSegue) {
let sourceController = segue.sourceViewController as! MenuViewController
self.title = sourceController.currentItem
}
}
| mit | 37955e55d8dc2b3495591e90941e0637 | 33.969388 | 118 | 0.642253 | 5.010234 | false | false | false | false |
megavolt605/CNLDataProvider | CNLDataProvider/CNLDataViewer+UICollectionView.swift | 1 | 9749 | //
// CNLDataViewer+UICollectionView.swift
// CNLDataProvider
//
// Created by Igor Smirnov on 23/12/2016.
// Copyright © 2016 Complex Numbers. All rights reserved.
//
import UIKit
extension UICollectionView: CNLDataViewer {
public var ownerViewController: UIViewController? {
return parentViewController
}
public subscript (indexPath: IndexPath) -> CNLDataViewerCell {
let identifier = cellType?(indexPath)?.cellIdentifier ?? "Cell"
return dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! CNLDataViewerCell // swiftlint:disable:this force_cast
}
public subscript (cellIdentifier: String?, indexPath: IndexPath) -> CNLDataViewerCell {
let identifier = cellIdentifier ?? cellType?(indexPath)?.cellIdentifier ?? "Cell"
return dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! CNLDataViewerCell // swiftlint:disable:this force_cast
}
public func loadMoreCell(_ indexPath: IndexPath) -> CNLDataViewerLoadMoreCell {
return dequeueReusableCell(withReuseIdentifier: "Load More Cell", for: indexPath) as! CNLDataViewerLoadMoreCell // swiftlint:disable:this force_cast
}
public func batchUpdates(_ updates: @escaping () -> Void) {
performBatchUpdates(updates, completion: nil)
}
public func batchUpdates(updates: @escaping () -> Void, completion: @escaping (_ isCompleted: Bool) -> Void) {
performBatchUpdates(updates, completion: completion)
}
public func initializeCells() {
if let loadMoreeCellDataSource = self as? CNLDataViewerLoadMore {
register(loadMoreeCellDataSource.loadMoreCellType, forCellWithReuseIdentifier: "Load More Cell")
}
//register(CNLCollectionViewLoadMoreCell.self, forCellWithReuseIdentifier: "Load More Cell")
}
public func selectItemAtIndexPath(_ indexPath: IndexPath, animated: Bool, scrollPosition position: CNLDataViewerScrollPosition) {
selectItem(at: indexPath, animated: animated, scrollPosition: position.collectionViewScrollPosition)
}
public func notifyDelegateDidSelectItemAtIndexPath(_ indexPath: IndexPath) {
delegate?.collectionView!(self, didSelectItemAt: indexPath)
}
public func selectedItemPaths() -> [IndexPath] {
return selectedItemPaths()
}
public func scrollToIndexPath(_ indexPath: IndexPath, atScrollPosition position: CNLDataViewerScrollPosition, animated: Bool) {
scrollToItem(at: indexPath, at: position.collectionViewScrollPosition, animated: animated)
}
func nonEmptySections() -> [Int] {
return (0..<numberOfSections).filter { return self.numberOfItems(inSection: $0) > 0 }
}
public func scrollToTop(_ animated: Bool = true) {
let sections = nonEmptySections()
if let section = sections.first {
scrollToItem(
at: IndexPath(item: 0, section: section),
at: UICollectionViewScrollPosition.top,
animated: animated
)
}
}
public func scrollToBottom(_ animated: Bool = true) {
let sections = nonEmptySections()
if let section = sections.last {
let rowCount = numberOfItems(inSection: section)
scrollToItem(
at: IndexPath(item: rowCount, section: section),
at: UICollectionViewScrollPosition.top,
animated: true
)
}
}
public func deselectAll(_ animated: Bool = true) {
let items = (0..<numberOfSections).flatMap { section in
return (0..<self.numberOfItems(inSection: section)).map {
return IndexPath(item: section, section: $0)
}
}
for item in items {
deselectItem(at: item, animated: animated)
}
}
public func reloadSections(_ sections: IndexSet, withRowAnimation animation: CNLDataViewerCellAnimation) {
reloadSections(sections)
}
public func reloadItemsAtIndexPaths(_ indexes: [IndexPath], withAnimation animation: CNLDataViewerCellAnimation) {
reloadItems(at: indexes)
}
public func createIndexPath(item: Int, section: Int) -> IndexPath {
return IndexPath(item: item, section: section)
}
// Cells
public func cellForItemAtIndexPath<T: CNLDataProvider>(
_ dataProvider: T,
cellIdentifier: String?,
indexPath: IndexPath,
context: CNLModelObject?
) -> AnyObject where T.ModelType.ArrayElement: CNLModelObject {
if dataProvider.dataProviderVariables.isLoadMoreIndexPath(indexPath) {
let cell = loadMoreCell(indexPath)
cell.setupCell(self, indexPath: indexPath)
let model = dataProvider.dataSource.model
if model.isPagingEnabled {
dataProvider.fetchNext(nil)
}
return cell as! UICollectionViewCell // swiftlint:disable:this force_cast
} else {
let cell = self[cellIdentifier, indexPath]
if let item = dataProvider.itemAtIndexPath(indexPath: indexPath) {
cell.setupCell(self, indexPath: indexPath, cellInfo: item, context: context)
}
return cell as! UICollectionViewCell // swiftlint:disable:this force_cast
}
}
public func cellSizeForItemAtIndexPath<T: CNLDataProvider>(_ dataProvider: T, indexPath: IndexPath, context: CNLModelObject?) -> CGSize? where T.ModelType.ArrayElement: CNLModelObject {
if dataProvider.dataProviderVariables.isLoadMoreIndexPath(indexPath) {
return CNLCollectionViewLoadMoreCell.cellSize(self, indexPath: indexPath)
} else {
if let item = dataProvider.itemAtIndexPath(indexPath: indexPath) {
return cellType?(indexPath)?.cellSize(self, indexPath: indexPath, cellInfo: item, context: context)
}
}
return CGSize.zero
}
// Headers
public func createHeader<T: CNLDataProvider>(_ dataProvider: T, section: Int) -> UIView? where T.ModelType: CNLModelArray, T.ModelType.ArrayElement: CNLModelObject {
let indexPath = createIndexPath(item: 0, section: section)
if let currentHeaderType = headerType?(section), let item = dataProvider.itemAtIndexPath(indexPath: indexPath) {
let height = currentHeaderType.headerHeight(self, section: section, cellInfo: item)
let view = UIView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: height))
let headerText = dataProvider.sectionTextForItem(item: item)
currentHeaderType.setupHeader(self, view: view, section: section, cellInfo: item, headerText: headerText)
return view
}
return nil
}
public func headerHeight<T: CNLDataProvider>(_ dataProvider: T, section: Int) -> CGFloat where T.ModelType: CNLModelArray, T.ModelType.ArrayElement: CNLModelObject {
let indexPath = createIndexPath(item: 0, section: section)
if let currentHeaderType = headerType?(section), let item = dataProvider.itemAtIndexPath(indexPath: indexPath) {
return currentHeaderType.headerHeight(self, section: section, cellInfo: item)
}
return 0
}
}
open class CNLCollectionViewLoadMoreCell: UICollectionViewCell, CNLDataViewerLoadMoreCell {
open var activity: CNLDataViewerActivity?
open var createActivity: () -> CNLDataViewerActivity? = { return nil }
open func setupCell<T: CNLDataViewer>(_ dataViewer: T, indexPath: IndexPath) where T: UIView {
contentView.backgroundColor = UIColor.clear
activity = createActivity()
if let activity = activity?.view {
contentView.addSubview(activity)
}
}
static open func cellSize<T: CNLDataViewer>(_ dataViewer: T, indexPath: IndexPath) -> CGSize where T: UIView {
return CGSize(width: dataViewer.frame.width, height: 40)
}
override open func layoutSubviews() {
super.layoutSubviews()
// sometimes layout is called BEFORE setupCell - workaround this bug
if activity != nil {
let minimalDimension = min(bounds.width, bounds.height)
activity!.frame.size = CGSize(width: minimalDimension, height: minimalDimension)
activity!.frame.origin = CGPoint(x: bounds.midX - minimalDimension / 2.0, y: 0)
if !activity!.isAnimating {
activity!.startAnimating()
}
}
}
}
/*
class CNLCollectionViewLoadMoreCell: UICollectionViewCell, CNLDataViewerLoadMoreCell {
var activity: NVActivityIndicatorView?
func setupCell<T : CNLDataViewer>(_ dataViewer: T, indexPath: IndexPath) where T : UIView {
activity = NVActivityIndicatorView(
frame: CGRect.zero,
type: NVActivityIndicatorType.randomType,
color: RPUIConfig.config.basicControls.animationColor,
padding: nil
)
contentView.addSubview(activity)
}
static func cellSize<T: CNLDataViewer>(_ dataViewer: T, indexPath: IndexPath) -> CGSize where T: UIView {
return CGSize(width: dataViewer.frame.width, height: 40)
}
override func layoutSubviews() {
super.layoutSubviews()
let minimalDimension = min(bounds.width, bounds.height)
activity.frame.size = CGSize(width: minimalDimension, height: minimalDimension)
activity.center = CGPoint(x: bounds.midX, y: minimalDimension / 2.0)
if !activity.isAnimating {
activity.startAnimating()
}
}
}
*/
| mit | f08ec6a60c37e4510395be37df77ddba | 40.65812 | 189 | 0.659828 | 5.11706 | false | false | false | false |
slabgorb/Tiler | Tiler/MapControlsView.swift | 1 | 2173 | //
// MapControlsView.swift
// Tiler
//
// Created by Keith Avery on 3/24/16.
// Copyright © 2016 Keith Avery. All rights reserved.
//
import UIKit
@IBDesignable class MapControlsView: UIView {
// MARK: Properties
@IBOutlet weak var textMapName: UITextField!
@IBOutlet weak var labelRow: UILabel!
@IBOutlet weak var labelColumn: UILabel!
@IBOutlet weak var stepperRow: UIStepper!
@IBOutlet weak var stepperColumn: UIStepper!
@IBOutlet weak var buttonMapName: UIButton!
@IBOutlet weak var buttonOK: UIButton!
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
// MARK: Actions
@IBAction func actionMapNameEditingDidEnd(sender: UITextField) {
textMapName.hidden = true
buttonMapName.hidden = false
}
@IBAction func actionOK(sender: UIButton) {
textMapName.endEditing(true)
}
@IBAction func actionMapNameChanged(sender: UITextField) {
//mapView.map.title = sender.text
buttonMapName.setTitle(sender.text, forState: .Normal)
}
@IBAction func stepperRowChange(sender: UIStepper) {
labelRow.text = String(Int(sender.value))
}
@IBAction func stepperColumnChange(sender: UIStepper) {
labelColumn.text = String(Int(sender.value))
}
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
setup()
}
func setup() {
self.stepperColumn.value = 1.0
self.stepperRow.value = 1.0
textMapName.hidden = true
}
// Our custom view from the XIB file
func xibSetup() {
var view: UIView!
view = UIView.loadFromNibNamed("MapControls", bundle: NSBundle(forClass: self.dynamicType))
view.frame = bounds
view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
addSubview(view)
}
}
| mit | 46901661048cecbb4574334540efaac7 | 26.15 | 101 | 0.654236 | 4.361446 | false | false | false | false |
terry408911/ReactiveCocoa | ReactiveCocoaTests/Swift/PropertySpec.swift | 1 | 10129 | //
// PropertySpec.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2015-01-23.
// Copyright (c) 2015 GitHub. All rights reserved.
//
import LlamaKit
import Nimble
import Quick
import ReactiveCocoa
private let initialPropertyValue = "InitialValue"
private let subsequentPropertyValue = "SubsequentValue"
class PropertySpec: QuickSpec {
override func spec() {
describe("ConstantProperty") {
it("should have the value given at initialization") {
let constantProperty = ConstantProperty(initialPropertyValue)
expect(constantProperty.value).to(equal(initialPropertyValue))
}
it("should yield a producer that sends the current value then completes") {
let constantProperty = ConstantProperty(initialPropertyValue)
var sentValue: String?
var signalCompleted = false
constantProperty.producer.start(next: { value in
sentValue = value
}, completed: {
signalCompleted = true
})
expect(sentValue).to(equal(initialPropertyValue))
expect(signalCompleted).to(beTruthy())
}
}
describe("MutableProperty") {
it("should have the value given at initialization") {
let mutableProperty = MutableProperty(initialPropertyValue)
expect(mutableProperty.value).to(equal(initialPropertyValue))
}
it("should yield a producer that sends the current value then all changes") {
let mutableProperty = MutableProperty(initialPropertyValue)
var sentValue: String?
mutableProperty.producer.start(next: { value in
sentValue = value
})
expect(sentValue).to(equal(initialPropertyValue))
mutableProperty.value = subsequentPropertyValue
expect(sentValue).to(equal(subsequentPropertyValue))
}
it("should complete its producer when deallocated") {
var mutableProperty: MutableProperty? = MutableProperty(initialPropertyValue)
var signalCompleted = false
mutableProperty?.producer.start(completed: {
signalCompleted = true
})
mutableProperty = nil
expect(signalCompleted).to(beTruthy())
}
}
describe("PropertyOf") {
it("should pass through behaviors of the input property") {
let constantProperty = ConstantProperty(initialPropertyValue)
let propertyOf = PropertyOf(constantProperty)
var sentValue: String?
var producerCompleted = false
propertyOf.producer.start(next: { value in
sentValue = value
}, completed: {
producerCompleted = true
})
expect(sentValue).to(equal(initialPropertyValue))
expect(producerCompleted).to(beTruthy())
}
}
describe("DynamicProperty") {
var object: ObservableObject!
var property: DynamicProperty!
let propertyValue: () -> Int? = {
if let value: AnyObject = property?.value {
return value as? Int
} else {
return nil
}
}
beforeEach {
object = ObservableObject()
expect(object.rac_value).to(equal(0))
property = DynamicProperty(object: object, keyPath: "rac_value")
}
afterEach {
object = nil
}
it("should read the underlying object") {
expect(propertyValue()).to(equal(0))
object.rac_value = 1
expect(propertyValue()).to(equal(1))
}
it("should write the underlying object") {
property.value = 1
expect(object.rac_value).to(equal(1))
expect(propertyValue()).to(equal(1))
}
it("should observe changes to the property and underlying object") {
var values: [Int] = []
property.producer.start(next: { value in
expect(value).notTo(beNil())
values.append((value as? Int) ?? -1)
})
expect(values).to(equal([ 0 ]))
property.value = 1
expect(values).to(equal([ 0, 1 ]))
object.rac_value = 2
expect(values).to(equal([ 0, 1, 2 ]))
}
it("should complete when the underlying object deallocates") {
var completed = false
property = {
// Use a closure so this object has a shorter lifetime.
let object = ObservableObject()
let property = DynamicProperty(object: object, keyPath: "rac_value")
property.producer.start(completed: {
completed = true
})
expect(completed).to(beFalsy())
expect(property.value).notTo(beNil())
return property
}()
expect(completed).toEventually(beTruthy())
expect(property.value).to(beNil())
}
it("should retain property while DynamicProperty's object is retained"){
weak var dynamicProperty: DynamicProperty? = property
property = nil
expect(dynamicProperty).toNot(beNil())
object = nil
expect(dynamicProperty).to(beNil())
}
}
describe("binding") {
describe("from a Signal") {
it("should update the property with values sent from the signal") {
let (signal, observer) = Signal<String, NoError>.pipe()
let mutableProperty = MutableProperty(initialPropertyValue)
mutableProperty <~ signal
// Verify that the binding hasn't changed the property value:
expect(mutableProperty.value).to(equal(initialPropertyValue))
sendNext(observer, subsequentPropertyValue)
expect(mutableProperty.value).to(equal(subsequentPropertyValue))
}
it("should tear down the binding when disposed") {
let (signal, observer) = Signal<String, NoError>.pipe()
let mutableProperty = MutableProperty(initialPropertyValue)
let bindingDisposable = mutableProperty <~ signal
bindingDisposable.dispose()
sendNext(observer, subsequentPropertyValue)
expect(mutableProperty.value).to(equal(initialPropertyValue))
}
it("should tear down the binding when bound signal is completed") {
let (signal, observer) = Signal<String, NoError>.pipe()
let mutableProperty = MutableProperty(initialPropertyValue)
let bindingDisposable = mutableProperty <~ signal
expect(bindingDisposable.disposed).to(beFalsy())
sendCompleted(observer)
expect(bindingDisposable.disposed).to(beTruthy())
}
it("should tear down the binding when the property deallocates") {
let (signal, observer) = Signal<String, NoError>.pipe()
var mutableProperty: MutableProperty<String>? = MutableProperty(initialPropertyValue)
let bindingDisposable = mutableProperty! <~ signal
mutableProperty = nil
expect(bindingDisposable.disposed).to(beTruthy())
}
}
describe("from a SignalProducer") {
it("should start a signal and update the property with its values") {
let signalValues = [initialPropertyValue, subsequentPropertyValue]
let signalProducer = SignalProducer<String, NoError>(values: signalValues)
let mutableProperty = MutableProperty(initialPropertyValue)
mutableProperty <~ signalProducer
expect(mutableProperty.value).to(equal(signalValues.last!))
}
it("should tear down the binding when disposed") {
let signalValues = [initialPropertyValue, subsequentPropertyValue]
let signalProducer = SignalProducer<String, NoError>(values: signalValues)
let mutableProperty = MutableProperty(initialPropertyValue)
let disposable = mutableProperty <~ signalProducer
disposable.dispose()
// TODO: Assert binding was teared-down?
}
it("should tear down the binding when bound signal is completed") {
let signalValues = [initialPropertyValue, subsequentPropertyValue]
let (signalProducer, observer) = SignalProducer<String, NoError>.buffer(1)
let mutableProperty = MutableProperty(initialPropertyValue)
let disposable = mutableProperty <~ signalProducer
expect(disposable.disposed).to(beFalsy())
sendCompleted(observer)
expect(disposable.disposed).to(beTruthy())
}
it("should tear down the binding when the property deallocates") {
let signalValues = [initialPropertyValue, subsequentPropertyValue]
let signalProducer = SignalProducer<String, NoError>(values: signalValues)
var mutableProperty: MutableProperty<String>? = MutableProperty(initialPropertyValue)
let disposable = mutableProperty! <~ signalProducer
mutableProperty = nil
expect(disposable.disposed).to(beTruthy())
}
}
describe("from another property") {
it("should take the source property's current value") {
let sourceProperty = ConstantProperty(initialPropertyValue)
let destinationProperty = MutableProperty("")
destinationProperty <~ sourceProperty.producer
expect(destinationProperty.value).to(equal(initialPropertyValue))
}
it("should update with changes to the source property's value") {
let sourceProperty = MutableProperty(initialPropertyValue)
let destinationProperty = MutableProperty("")
destinationProperty <~ sourceProperty.producer
destinationProperty.value = subsequentPropertyValue
expect(destinationProperty.value).to(equal(subsequentPropertyValue))
}
it("should tear down the binding when disposed") {
let sourceProperty = MutableProperty(initialPropertyValue)
let destinationProperty = MutableProperty("")
let bindingDisposable = destinationProperty <~ sourceProperty.producer
bindingDisposable.dispose()
sourceProperty.value = subsequentPropertyValue
expect(destinationProperty.value).to(equal(initialPropertyValue))
}
it("should tear down the binding when the source property deallocates") {
var sourceProperty: MutableProperty<String>? = MutableProperty(initialPropertyValue)
let destinationProperty = MutableProperty("")
let bindingDisposable = destinationProperty <~ sourceProperty!.producer
sourceProperty = nil
expect(bindingDisposable.disposed).to(beTruthy())
}
it("should tear down the binding when the destination property deallocates") {
let sourceProperty = MutableProperty(initialPropertyValue)
var destinationProperty: MutableProperty<String>? = MutableProperty("")
let bindingDisposable = destinationProperty! <~ sourceProperty.producer
destinationProperty = nil
expect(bindingDisposable.disposed).to(beTruthy())
}
}
}
}
}
private class ObservableObject: NSObject {
dynamic var rac_value: Int = 0
}
| mit | fb230eb2bb885fd46fd3a65bb95bcd03 | 28.106322 | 90 | 0.708461 | 4.434764 | false | false | false | false |
sunflash/SwiftHTTPClient | HTTPClient/Classes/HTTP/Client/HTTPClient.swift | 1 | 13155 | //
// Http.swift
// HTTPClient
//
// Created by Min Wu on 10/01/2017.
// Copyright © 2017 Min WU. All rights reserved.
//
import Foundation
import UIKit
/// Http client for network request
public class HTTPClient: Log {
//-----------------------------------------------------------------------------------------------------------------
// MARK: - Network property
private var urlSession = URLSession(configuration: .default)
/// Share instance of http client
public static let shared = HTTPClient()
/// Use session configuration to set global http header, cookies, access token for session
/// URLSessionConfiguration.HTTPAdditionalHeaders
public var configuration: URLSessionConfiguration = .default {
didSet {
self.urlSession.finishTasksAndInvalidate()
self.urlSession = URLSession(configuration: self.configuration)
}
}
/// Global retry parameter for all url session request, can be override local by each request
public var retry = 0
/// Global base url for all url session request, can be override local by each request
public var sessionBaseURL: URL? {
didSet {
ReachabilityDetection.shared.stopReachabilityMonitoring()
var reachabilityHosts = defaultReachabilityHosts
if let baseURLHost = sessionBaseURL?.absoluteString {
reachabilityHosts += [baseURLHost]
}
startReachabilityMonitoring(hosts: reachabilityHosts)
}
}
/// Response completion handles that would invoke each time an http response is recevied
public var responseCompletionHandlers: [String: (HTTPResponse) -> Void] = [String: (HTTPResponse)->Void]()
private let defaultReachabilityHosts = ["google.com", "apple.com"]
/// Initializes `self` with default configuration.
public init() {
startReachabilityMonitoring(hosts: defaultReachabilityHosts)
}
private func startReachabilityMonitoring(hosts: [String]) {
let status = ReachabilityDetection.shared.startReachabilityMonitoring(hosts: hosts)
log(.INFO, status.description)
}
//-----------------------------------------------------------------------------------------------------------------
// MARK: - Network request and response
private func gerneateURLRequest(url: URL, request: HTTPRequest) -> URLRequest {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = request.method.rawValue
if let contentType = request.contentType {
urlRequest.setValue(contentType.stringValue, forHTTPHeaderField: "Content-Type")
}
if let headers = request.headers {
headers.forEach {urlRequest.setValue($0.value, forHTTPHeaderField: $0.key)}
}
if let body = request.body {
urlRequest.httpBody = body
}
return urlRequest
}
private func validateResponse(request: HTTPRequest, response: URLResponse?) -> Bool {
guard let urlResponse = response as? HTTPURLResponse else {
return false
}
let isSucceedRequest = (200 ... 399 ~= urlResponse.statusCode)
var isValidContent = true
if let expectedResponseContentType = request.expectedResponseContentType {
let responseContentType = HTTPContentType(mimeType: urlResponse.mimeType)
isValidContent = (expectedResponseContentType == responseContentType)
}
let isValidResponse = (isSucceedRequest && isValidContent)
return isValidResponse
}
private func invalidRequestResponse(url: URL?) -> HTTPResponse {
let invalidURL = HTTPStatusCode.invalidUrl
let emptyHeaders = [String: String]()
return HTTPResponse(url: url, statusCode: invalidURL, headers: emptyHeaders)
}
private func noInternetResponse(url: URL) -> HTTPResponse {
let noInternet = HTTPStatusCode.noInternet
let emptyHeaders = [String: String]()
return HTTPResponse(url: url, statusCode: noInternet, headers: emptyHeaders)
}
private func unknownStatusResponse(url: URL, error: Error?) -> HTTPResponse {
let unknownStatus = HTTPStatusCode.unknownStatus
let emptyHeaders = [String: String]()
var unknownStatusResponse = HTTPResponse(url: url, statusCode: unknownStatus, headers: emptyHeaders)
unknownStatusResponse.error = error
return unknownStatusResponse
}
private func response(response: URLResponse, data: Data? = nil, error: Error? = nil) -> HTTPResponse {
let urlResponse = (response as? HTTPURLResponse) ?? HTTPURLResponse()
let statusCode = HTTPStatusCode(statusCode: urlResponse.statusCode)
let headers = lowerCaseHeaders(urlResponse.allHeaderFields as? [String: String])
var response = HTTPResponse(url: urlResponse.url, statusCode: statusCode, headers: headers)
response.contentType = HTTPContentType(mimeType: urlResponse.mimeType)
response.body = data
response.error = error
return response
}
private func lowerCaseHeaders(_ headers: [String: String]?) -> [String: String] {
var lowerCaseHeaders = [String: String]()
headers?.forEach {lowerCaseHeaders[$0.key.lowercased()] = $0.value}
return lowerCaseHeaders
}
//-----------------------------------------------------------------------------------------------------------------
// MARK: - Network request methods
/// Method for sending an HTTP POST/GET Request to the remote server
///
/// - Parameters:
/// - baseURL: Base url to send the request to, fallback to session global config "sessionBaseURL" if it's nil or unspecified.
/// - request: HTTPRequest object
/// - retry: Retry request if it's failded, fallback to session global config "retry" if it's nil or unspecified.
/// - success: On success this block will get called.
/// - error: On any error this block will get called, optional.
/// - Returns: RequestCancellationToken object for cancel request if necessary.
public func request(baseURL: URL? = nil,
request: HTTPRequest,
retry: Int? = nil,
success: @escaping (HTTPResponse) -> Void,
error: ((HTTPResponse) -> Void)? = nil) -> RequestCancellationToken {
var requestCancellationToken = RequestCancellationToken()
// If request base url is unspecified, fallback to session base url
var requestURL: URL? = baseURL ?? self.sessionBaseURL
// Path component should only appending once and not with retry
let shouldAppendingPathComponent = (request.retriesCount == 0)
if shouldAppendingPathComponent == true, request.path.isEmpty == false {
requestURL = URL(string: request.path, relativeTo: requestURL)
}
guard let url = requestURL?.absoluteURL, let validURL = URLComponents(url: url, resolvingAgainstBaseURL: true)?.url else {
error?(invalidRequestResponse(url: requestURL))
return requestCancellationToken
}
// use session global config self.retry if retry is nil or unspecified
let maxRetryCount = retry ?? self.retry
let urlRequest = self.gerneateURLRequest(url: validURL, request: request)
let reachability = ReachabilityDetection.shared
if reachability.monitoringHosts.isEmpty == false && reachability.isInternetAvailable == false {
error?(noInternetResponse(url: url))
return requestCancellationToken
}
let dataTask = self.urlSession.dataTask(with: urlRequest) { data, response, requestError in
let isValidResponse = self.validateResponse(request: request, response: response)
// retry -------------------------------------------
guard requestCancellationToken.isTaskCancelled == false else {return} // Stop retry, if task is cancel
if requestError != nil && requestError?._code == NSURLErrorTimedOut {
if request.retriesCount < maxRetryCount {
var newRequest = request
newRequest.retriesCount += 1
logAPI(.request, validURL, output: "Retry \(newRequest.retriesCount)")
requestCancellationToken = self.request(baseURL: url, request: newRequest, retry: maxRetryCount, success: success, error: error)
return
}
}
// error response ----------------------------------
guard requestCancellationToken.isTaskCancelled == false else {return} // Stop calling error handle, if task is cancel
if requestError != nil || response == nil || isValidResponse == false {
self.errorResponseHandler(url: url, response: response, data: data, requestError: requestError, error: error)
self.updateIndicatorDelayOnMainQueue()
return
}
// success response ----------------------------------
guard requestCancellationToken.isTaskCancelled == false else {return} // Stop calling success handle, if task is cancel
if let successResponse = response {
self.successResponseHandler(response: successResponse, data: data, success: success)
self.updateIndicatorDelayOnMainQueue()
}
}
dataTask.resume()
self.updateNetworkActivityIndicator()
requestCancellationToken.task = dataTask
return requestCancellationToken
}
/// Error response handler for request
///
/// - Parameters:
/// - url: url for request
/// - response: reponse return from the request, can be nil
/// - requestError: request error return from the request, can be nil
/// - error: error completion handler, can be nil if user only want completion for success only
private func errorResponseHandler(url: URL, response: URLResponse?, data: Data?, requestError: Error?, error: ((HTTPResponse) -> Void)?) {
guard let errorHandler = error else {return}
let errorCompletion: (HTTPResponse) -> Void = { errorResponse in
GCD.main.queue.async { [weak self] in
errorHandler(errorResponse)
self?.invokeResponseCompletionHandlers(errorResponse)
}
}
if let failedResponse = response { // Error with response
let failedResponse = self.response(response: failedResponse, data: data, error: requestError)
errorCompletion(failedResponse)
} else { // Error with no response
let unknownStatusResponse = self.unknownStatusResponse(url: url, error: requestError)
errorCompletion(unknownStatusResponse)
}
}
/// Success response handler for request
///
/// - Parameters:
/// - response: response for success request
/// - success: success completion handler
private func successResponseHandler(response: URLResponse, data: Data?, success: @escaping (HTTPResponse) -> Void) {
let successResponse = self.response(response: response, data: data)
GCD.main.queue.async { [weak self] in
success(successResponse)
self?.invokeResponseCompletionHandlers(successResponse)
}
}
/// Invoke each response completion handler, if there is any completion handler registed.
///
/// - Parameter response: `HTTPResponse`
private func invokeResponseCompletionHandlers(_ response: HTTPResponse) {
responseCompletionHandlers.forEach { _, completionHandler in
completionHandler(response)
}
}
/// Remove response completion handler with name
///
/// - Parameter name: name for response completion handler
public func removeResponseCompletionHandler(_ name: String) {
GCD.main.queue.async { [weak self] in
self?.responseCompletionHandlers.removeValue(forKey: name)
}
}
//-----------------------------------------------------------------------------------------------------------------
// MARK: - UI
private func updateIndicatorDelayOnMainQueue() {
// Update network activity indicator on main queue with a small delay
// aften request task is return, avoid false positiv with session outstanding task count.
GCD.main.after(delay: 0.1) { [weak self] in
self?.updateNetworkActivityIndicator()
}
}
private func updateNetworkActivityIndicator() {
// Note: useing "func getAllTasks(completionHandler: @escaping ([URLSessionTask]) -> Void)" for iOS 9
self.urlSession.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in
let outstandingTasksCount = [dataTasks.count, uploadTasks.count, downloadTasks.count].reduce(0, +)
GCD.main.queue.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = (outstandingTasksCount > 0)
}
}
}
}
| mit | 2cbefd66bb63021b70f249cc117b9247 | 40.626582 | 148 | 0.628934 | 5.487693 | false | false | false | false |
OSzhou/MyTestDemo | PerfectDemoProject(swift写服务端)/.build/checkouts/Perfect-HTTPServer.git--6671958091389663080/Tests/PerfectHTTPServerTests/PerfectHTTPServerTests.swift | 1 | 33630 | import XCTest
import PerfectLib
import PerfectNet
import PerfectThread
import PerfectHTTP
@testable import PerfectHTTPServer
func ShimHTTPRequest() -> HTTP11Request {
return HTTP11Request(connection: NetTCP())
}
class PerfectHTTPServerTests: XCTestCase {
override func setUp() {
super.setUp()
compatRoutes = nil
}
func testHPACKEncode() {
let encoder = HPACKEncoder()
let b = Bytes()
let headers = [
// (":method", "POST"),
// (":scheme", "https"),
// (":path", "/3/device/00fc13adff785122b4ad28809a3420982341241421348097878e577c991de8f0"),
// ("host", "api.development.push.apple.com"),
// ("apns-id", "eabeae54-14a8-11e5-b60b-1697f925ec7b"),
// ("apns-expiration", "0"),
// ("apns-priority", "10"),
// ("content-length", "33"),
("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4")]
do {
for (n, v) in headers {
try encoder.encodeHeader(out: b, name: UTF8Encoding.decode(string: n), value: UTF8Encoding.decode(string: v), sensitive: false)
}
class Listener: HeaderListener {
var headers = [(String, String)]()
func addHeader(name nam: [UInt8], value: [UInt8], sensitive: Bool) {
self.headers.append((UTF8Encoding.encode(bytes: nam), UTF8Encoding.encode(bytes: value)))
}
}
let decoder = HPACKDecoder()
let l = Listener()
try decoder.decode(input: b, headerListener: l)
XCTAssert(l.headers.count == headers.count)
for i in 0..<headers.count {
let h1 = headers[i]
let h2 = l.headers[i]
XCTAssertEqual(h1.0, h2.0)
XCTAssertEqual(h1.1, h2.1)
}
}
catch {
XCTAssert(false, "Exception \(error)")
}
}
func testWebConnectionHeadersWellFormed() {
let connection = ShimHTTPRequest()
let fullHeaders = "GET / HTTP/1.1\r\nX-Foo: bar\r\nX-Bar: \r\nContent-Type: application/x-www-form-urlencoded\r\n\r\n"
XCTAssert(false == connection.didReadSomeBytes(UTF8Encoding.decode(string: fullHeaders)) {
ok in
guard case .ok = ok else {
return XCTAssert(false, "\(ok)")
}
XCTAssertTrue(connection.header(.custom(name: "X-Foo")) == "bar", "\(connection.headers)")
XCTAssertTrue(connection.header(.custom(name: "X-Bar")) == "", "\(connection.headers)")
XCTAssertTrue(connection.contentType == "application/x-www-form-urlencoded", "\(connection.headers)")
})
}
func testWebConnectionHeadersLF() {
let connection = ShimHTTPRequest()
let fullHeaders = "GET / HTTP/1.1\nX-Foo: bar\nX-Bar: \nContent-Type: application/x-www-form-urlencoded\n\n"
XCTAssert(false == connection.didReadSomeBytes(UTF8Encoding.decode(string: fullHeaders)) {
ok in
guard case .ok = ok else {
return XCTAssert(false, "\(ok)")
}
XCTAssertTrue(connection.header(.custom(name: "x-foo")) == "bar", "\(connection.headers)")
XCTAssertTrue(connection.header(.custom(name: "x-bar")) == "", "\(connection.headers)")
XCTAssertTrue(connection.contentType == "application/x-www-form-urlencoded", "\(connection.headers)")
})
}
func testWebConnectionHeadersMalormed() {
let connection = ShimHTTPRequest()
let fullHeaders = "GET / HTTP/1.1\r\nX-Foo: bar\rX-Bar: \r\nContent-Type: application/x-www-form-urlencoded\r\n\r\n"
XCTAssert(false == connection.didReadSomeBytes(UTF8Encoding.decode(string: fullHeaders)) {
ok in
guard case .badRequest = ok else {
return XCTAssert(false, "\(ok)")
}
})
}
func testWebConnectionHeadersFolded() {
let connection = ShimHTTPRequest()
let fullHeaders = "GET / HTTP/1.1\r\nX-Foo: bar\r\n bar\r\nX-Bar: foo\r\n foo\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\n"
XCTAssert(false == connection.didReadSomeBytes(UTF8Encoding.decode(string: fullHeaders)) {
ok in
guard case .ok = ok else {
return XCTAssert(false, "\(ok)")
}
let wasFoldedValue = connection.header(.custom(name: "x-foo"))
XCTAssertTrue(wasFoldedValue == "bar bar", "\(connection.headers)")
XCTAssertTrue(connection.header(.custom(name: "x-bar")) == "foo foo", "\(connection.headers)")
XCTAssertTrue(connection.contentType == "application/x-www-form-urlencoded", "\(connection.headers)")
})
}
func testWebConnectionHeadersTooLarge() {
let connection = ShimHTTPRequest()
var fullHeaders = "GET / HTTP/1.1\r\nX-Foo:"
for _ in 0..<(1024*81) {
fullHeaders.append(" bar")
}
fullHeaders.append("\r\n\r\n")
XCTAssert(false == connection.didReadSomeBytes(UTF8Encoding.decode(string: fullHeaders)) {
ok in
guard case .requestEntityTooLarge = ok else {
return XCTAssert(false, "\(ok)")
}
XCTAssert(true)
})
}
func testWebRequestQueryParam() {
let req = ShimHTTPRequest()
req.queryString = "yabba=dabba&y=asd==&doo=fi+☃&fi=&fo=fum"
XCTAssert(req.param(name: "doo") == "fi ☃")
XCTAssert(req.param(name: "fi") == "")
XCTAssert(req.param(name: "y") == "asd==")
}
func testWebRequestPostParam() {
let req = ShimHTTPRequest()
req.postBodyBytes = Array("yabba=dabba&y=asd==&doo=fi+☃&fi=&fo=fum".utf8)
XCTAssert(req.param(name: "doo") == "fi ☃")
XCTAssert(req.param(name: "fi") == "")
XCTAssert(req.param(name: "y") == "asd==")
}
func testWebRequestCookie() {
let req = ShimHTTPRequest()
req.setHeader(.cookie, value: "yabba=dabba; doo=fi☃; fi=; fo=fum")
for cookie in req.cookies {
if cookie.0 == "doo" {
XCTAssert(cookie.1 == "fi☃")
}
if cookie.0 == "fi" {
XCTAssert(cookie.1 == "")
}
}
}
func testWebRequestPath1() {
let connection = ShimHTTPRequest()
let fullHeaders = "GET /pathA/pathB/path%20c HTTP/1.1\r\nX-Foo: bar\r\nX-Bar: \r\nContent-Type: application/x-www-form-urlencoded\r\n\r\n"
XCTAssert(false == connection.didReadSomeBytes(Array(fullHeaders.utf8)) {
ok in
guard case .ok = ok else {
return XCTAssert(false, "\(ok)")
}
XCTAssertEqual(connection.path, "/pathA/pathB/path%20c")
XCTAssertEqual(connection.pathComponents, ["/", "pathA", "pathB", "path c"])
})
}
func testWebRequestPath2() {
let connection = ShimHTTPRequest()
let fullHeaders = "GET /pathA/pathB//path%20c/?a=b&c=d%20e HTTP/1.1\r\nX-Foo: bar\r\nX-Bar: \r\nContent-Type: application/x-www-form-urlencoded\r\n\r\n"
XCTAssert(false == connection.didReadSomeBytes(Array(fullHeaders.utf8)) {
ok in
guard case .ok = ok else {
return XCTAssert(false, "\(ok)")
}
XCTAssertEqual(connection.path, "/pathA/pathB/path%20c/")
XCTAssertEqual(connection.pathComponents, ["/", "pathA", "pathB", "path c", "/"])
XCTAssert(connection.param(name: "a") == "b")
XCTAssert(connection.param(name: "c") == "d e")
})
}
func testWebRequestPath3() {
let connection = ShimHTTPRequest()
let path = "/pathA/pathB//path%20c/"
connection.path = path
XCTAssertEqual(connection.path, "/pathA/pathB/path%20c/")
XCTAssertEqual(connection.pathComponents, ["/", "pathA", "pathB", "path c", "/"])
}
func testWebRequestPath4() {
let connection = ShimHTTPRequest()
let fullHeaders = "GET /?a=b&c=d%20e HTTP/1.1\r\nX-Foo: bar\r\nX-Bar: \r\nContent-Type: application/x-www-form-urlencoded\r\n\r\n"
XCTAssert(false == connection.didReadSomeBytes(Array(fullHeaders.utf8)) {
ok in
guard case .ok = ok else {
return XCTAssert(false, "\(ok)")
}
XCTAssertEqual(connection.path, "/")
XCTAssertEqual(connection.pathComponents, ["/"])
XCTAssert(connection.param(name: "a") == "b")
XCTAssert(connection.param(name: "c") == "d e")
})
}
func testSimpleHandler() {
let port = 8282 as UInt16
let msg = "Hello, world!"
var routes = Routes()
routes.add(method: .get, uri: "/", handler: {
request, response in
response.addHeader(.contentType, value: "text/plain")
response.appendBody(string: msg)
response.completed()
}
)
let serverExpectation = self.expectation(description: "server")
let clientExpectation = self.expectation(description: "client")
let server = HTTPServer()
server.addRoutes(routes)
server.serverPort = port
func endClient() {
server.stop()
clientExpectation.fulfill()
}
Threading.dispatch {
do {
try server.start()
} catch PerfectError.networkError(let err, let msg) {
XCTAssert(false, "Network error thrown: \(err) \(msg)")
} catch {
XCTAssert(false, "Error thrown: \(error)")
}
serverExpectation.fulfill()
}
Threading.sleep(seconds: 1.0)
let clienttcp = NetTCP()
Threading.dispatch {
do {
try clienttcp.connect(address: "127.0.0.1", port: port, timeoutSeconds: 5.0) {
net in
guard let net = net else {
XCTAssert(false, "Could not connect to server")
return endClient()
}
let reqStr = "GET / HTTP/1.0\r\nHost: localhost:\(port)\r\nFrom: [email protected]\r\n\r\n"
net.write(string: reqStr) {
count in
guard count == reqStr.utf8.count else {
XCTAssert(false, "Could not write request \(count) != \(reqStr.utf8.count)")
return endClient()
}
Threading.sleep(seconds: 2.0)
net.readSomeBytes(count: 1024) {
bytes in
guard let bytes = bytes, bytes.count > 0 else {
XCTAssert(false, "Could not read bytes from server")
return endClient()
}
let str = UTF8Encoding.encode(bytes: bytes)
let splitted = str.characters.split(separator: "\r\n").map(String.init)
XCTAssertEqual(splitted.last, msg)
endClient()
}
}
}
} catch {
XCTAssert(false, "Error thrown: \(error)")
endClient()
}
}
self.waitForExpectations(timeout: 10000, handler: {
_ in
})
}
func testSimpleStreamingHandler() {
let port = 8282 as UInt16
var routes = Routes()
routes.add(method: .get, uri: "/", handler: {
request, response in
response.addHeader(.contentType, value: "text/plain")
response.isStreaming = true
response.appendBody(string: "A")
response.push {
ok in
XCTAssert(ok, "Failed in .push")
response.appendBody(string: "BC")
response.completed()
}
}
)
let serverExpectation = self.expectation(description: "server")
let clientExpectation = self.expectation(description: "client")
let server = HTTPServer()
server.serverPort = port
server.addRoutes(routes)
func endClient() {
server.stop()
clientExpectation.fulfill()
}
Threading.dispatch {
do {
try server.start()
} catch PerfectError.networkError(let err, let msg) {
XCTAssert(false, "Network error thrown: \(err) \(msg)")
} catch {
XCTAssert(false, "Error thrown: \(error)")
}
serverExpectation.fulfill()
}
Threading.sleep(seconds: 1.0)
let clientNet = NetTCP()
Threading.dispatch {
do {
try clientNet.connect(address: "127.0.0.1", port: port, timeoutSeconds: 5.0) {
net in
guard let net = net else {
XCTAssert(false, "Could not connect to server")
return endClient()
}
let reqStr = "GET / HTTP/1.0\r\nHost: localhost:\(port)\r\nFrom: [email protected]\r\n\r\n"
net.write(string: reqStr) {
count in
guard count == reqStr.utf8.count else {
XCTAssert(false, "Could not write request \(count) != \(reqStr.utf8.count)")
return endClient()
}
Threading.sleep(seconds: 2.0)
net.readSomeBytes(count: 2048) {
bytes in
guard let bytes = bytes, bytes.count > 0 else {
XCTAssert(false, "Could not read bytes from server")
return endClient()
}
let str = UTF8Encoding.encode(bytes: bytes)
let splitted = str.characters.split(separator: "\r\n", omittingEmptySubsequences: false).map(String.init)
let compare = ["HTTP/1.0 200 OK",
"Content-Type: text/plain",
"Transfer-Encoding: chunked",
"",
"1",
"A",
"2",
"BC",
"0",
"",
""]
XCTAssert(splitted.count == compare.count)
for (a, b) in zip(splitted, compare) {
XCTAssert(a == b, "\(splitted) != \(compare)")
}
endClient()
}
}
}
} catch {
XCTAssert(false, "Error thrown: \(error)")
endClient()
}
}
self.waitForExpectations(timeout: 10000, handler: {
_ in
})
}
func testSlowClient() {
let port = 8282 as UInt16
let msg = "Hello, world!"
var routes = Routes()
routes.add(method: .get, uri: "/", handler: {
request, response in
response.addHeader(.contentType, value: "text/plain")
response.appendBody(string: msg)
response.completed()
}
)
let serverExpectation = self.expectation(description: "server")
let clientExpectation = self.expectation(description: "client")
let server = HTTPServer()
server.serverPort = port
server.addRoutes(routes)
func endClient() {
server.stop()
clientExpectation.fulfill()
}
Threading.dispatch {
do {
try server.start()
} catch PerfectError.networkError(let err, let msg) {
XCTAssert(false, "Network error thrown: \(err) \(msg)")
} catch {
XCTAssert(false, "Error thrown: \(error)")
}
serverExpectation.fulfill()
}
Threading.sleep(seconds: 1.0)
let clientNet = NetTCP()
Threading.dispatch {
do {
try clientNet.connect(address: "127.0.0.1", port: port, timeoutSeconds: 5.0) {
net in
guard let net = net else {
XCTAssert(false, "Could not connect to server")
return endClient()
}
var reqIt = Array("GET / HTTP/1.0\r\nHost: localhost:\(port)\r\nFrom: [email protected]\r\n\r\n".utf8).makeIterator()
func pushChar() {
if let b = reqIt.next() {
let a = [b]
net.write(bytes: a) {
wrote in
guard 1 == wrote else {
XCTAssert(false, "Could not write request \(wrote) != \(1)")
return endClient()
}
Threading.sleep(seconds: 0.5)
Threading.dispatch {
pushChar()
}
}
} else {
Threading.sleep(seconds: 2.0)
net.readSomeBytes(count: 1024) {
bytes in
guard let bytes = bytes, bytes.count > 0 else {
XCTAssert(false, "Could not read bytes from server")
return endClient()
}
let str = UTF8Encoding.encode(bytes: bytes)
let splitted = str.characters.split(separator: "\r\n").map(String.init)
XCTAssert(splitted.last == msg)
endClient()
}
}
}
pushChar()
}
} catch {
XCTAssert(false, "Error thrown: \(error)")
endClient()
}
}
self.waitForExpectations(timeout: 20000, handler: {
_ in
})
}
static var oneSet = false, twoSet = false, threeSet = false
func testRequestFilters() {
let port = 8282 as UInt16
let msg = "Hello, world!"
PerfectHTTPServerTests.oneSet = false
PerfectHTTPServerTests.twoSet = false
PerfectHTTPServerTests.threeSet = false
struct Filter1: HTTPRequestFilter {
func filter(request: HTTPRequest, response: HTTPResponse, callback: (HTTPRequestFilterResult) -> ()) {
PerfectHTTPServerTests.oneSet = true
callback(.continue(request, response))
}
}
struct Filter2: HTTPRequestFilter {
func filter(request: HTTPRequest, response: HTTPResponse, callback: (HTTPRequestFilterResult) -> ()) {
XCTAssert(PerfectHTTPServerTests.oneSet)
XCTAssert(!PerfectHTTPServerTests.twoSet && !PerfectHTTPServerTests.threeSet)
PerfectHTTPServerTests.twoSet = true
callback(.execute(request, response))
}
}
struct Filter3: HTTPRequestFilter {
func filter(request: HTTPRequest, response: HTTPResponse, callback: (HTTPRequestFilterResult) -> ()) {
XCTAssert(false, "This filter should be skipped")
callback(.continue(request, response))
}
}
struct Filter4: HTTPRequestFilter {
func filter(request: HTTPRequest, response: HTTPResponse, callback: (HTTPRequestFilterResult) -> ()) {
XCTAssert(PerfectHTTPServerTests.oneSet && PerfectHTTPServerTests.twoSet)
XCTAssert(!PerfectHTTPServerTests.threeSet)
PerfectHTTPServerTests.threeSet = true
callback(.halt(request, response))
}
}
let requestFilters: [(HTTPRequestFilter, HTTPFilterPriority)] = [(Filter1(), HTTPFilterPriority.high), (Filter2(), HTTPFilterPriority.medium), (Filter3(), HTTPFilterPriority.medium), (Filter4(), HTTPFilterPriority.low)]
var routes = Routes()
routes.add(method: .get, uri: "/", handler: {
request, response in
XCTAssert(false, "This handler should not execute")
response.addHeader(.contentType, value: "text/plain")
response.appendBody(string: msg)
response.completed()
}
)
let serverExpectation = self.expectation(description: "server")
let clientExpectation = self.expectation(description: "client")
let server = HTTPServer()
server.setRequestFilters(requestFilters)
server.serverPort = port
server.addRoutes(routes)
func endClient() {
server.stop()
clientExpectation.fulfill()
}
Threading.dispatch {
do {
try server.start()
} catch PerfectError.networkError(let err, let msg) {
XCTAssert(false, "Network error thrown: \(err) \(msg)")
} catch {
XCTAssert(false, "Error thrown: \(error)")
}
serverExpectation.fulfill()
}
Threading.sleep(seconds: 1.0)
let clientNet = NetTCP()
Threading.dispatch {
do {
try clientNet.connect(address: "127.0.0.1", port: port, timeoutSeconds: 5.0) {
net in
guard let net = net else {
XCTAssert(false, "Could not connect to server")
return endClient()
}
let reqStr = "GET / HTTP/1.0\r\nHost: localhost:\(port)\r\nFrom: [email protected]\r\n\r\n"
net.write(string: reqStr) {
count in
guard count == reqStr.utf8.count else {
XCTAssert(false, "Could not write request \(count) != \(reqStr.utf8.count)")
return endClient()
}
Threading.sleep(seconds: 3.0)
net.readSomeBytes(count: 1024) {
bytes in
guard let bytes = bytes, bytes.count > 0 else {
XCTAssert(false, "Could not read bytes from server")
return endClient()
}
endClient()
}
}
}
} catch {
XCTAssert(false, "Error thrown: \(error)")
endClient()
}
}
self.waitForExpectations(timeout: 10000, handler: {
_ in
XCTAssert(PerfectHTTPServerTests.oneSet && PerfectHTTPServerTests.twoSet && PerfectHTTPServerTests.threeSet)
})
}
func testResponseFilters() {
let port = 8282 as UInt16
struct Filter1: HTTPResponseFilter {
func filterHeaders(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
response.setHeader(.custom(name: "X-Custom"), value: "Value")
callback(.continue)
}
func filterBody(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
callback(.continue)
}
}
struct Filter2: HTTPResponseFilter {
func filterHeaders(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
callback(.continue)
}
func filterBody(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
var b = response.bodyBytes
b = b.map { $0 == 65 ? 97 : $0 }
response.bodyBytes = b
callback(.continue)
}
}
struct Filter3: HTTPResponseFilter {
func filterHeaders(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
callback(.continue)
}
func filterBody(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
var b = response.bodyBytes
b = b.map { $0 == 66 ? 98 : $0 }
response.bodyBytes = b
callback(.done)
}
}
struct Filter4: HTTPResponseFilter {
func filterHeaders(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
callback(.continue)
}
func filterBody(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
XCTAssert(false, "This should not execute")
callback(.done)
}
}
let responseFilters: [(HTTPResponseFilter, HTTPFilterPriority)] = [
(Filter1(), HTTPFilterPriority.high),
(Filter2(), HTTPFilterPriority.medium),
(Filter3(), HTTPFilterPriority.low),
(Filter4(), HTTPFilterPriority.low)
]
var routes = Routes()
routes.add(method: .get, uri: "/", handler: {
request, response in
response.addHeader(.contentType, value: "text/plain")
response.appendBody(string: "ABZABZ")
response.completed()
}
)
let serverExpectation = self.expectation(description: "server")
let clientExpectation = self.expectation(description: "client")
let server = HTTPServer()
server.setResponseFilters(responseFilters)
server.serverPort = port
server.addRoutes(routes)
func endClient() {
server.stop()
clientExpectation.fulfill()
}
Threading.dispatch {
do {
try server.start()
} catch PerfectError.networkError(let err, let msg) {
XCTAssert(false, "Network error thrown: \(err) \(msg)")
} catch {
XCTAssert(false, "Error thrown: \(error)")
}
serverExpectation.fulfill()
}
Threading.sleep(seconds: 1.0)
let clientNet = NetTCP()
Threading.dispatch {
do {
try clientNet.connect(address: "127.0.0.1", port: port, timeoutSeconds: 5.0) {
net in
guard let net = net else {
XCTAssert(false, "Could not connect to server")
return endClient()
}
let reqStr = "GET / HTTP/1.0\r\nHost: localhost:\(port)\r\nFrom: [email protected]\r\n\r\n"
net.write(string: reqStr) {
count in
guard count == reqStr.utf8.count else {
XCTAssert(false, "Could not write request \(count) != \(reqStr.utf8.count)")
return endClient()
}
Threading.sleep(seconds: 3.0)
net.readSomeBytes(count: 2048) {
bytes in
guard let bytes = bytes, bytes.count > 0 else {
XCTAssert(false, "Could not read bytes from server")
return endClient()
}
let str = UTF8Encoding.encode(bytes: bytes)
let splitted = str.characters.split(separator: "\r\n", omittingEmptySubsequences: false).map(String.init)
let compare = ["HTTP/1.0 200 OK",
"Content-Type: text/plain",
"Content-Length: 6",
"X-Custom: Value",
"",
"abZabZ"]
XCTAssert(splitted.count == compare.count)
for (a, b) in zip(splitted, compare) {
XCTAssert(a == b, "\(splitted) != \(compare)")
}
endClient()
}
}
}
} catch {
XCTAssert(false, "Error thrown: \(error)")
endClient()
}
}
self.waitForExpectations(timeout: 10000, handler: {
_ in
})
}
func testStreamingResponseFilters() {
let port = 8282 as UInt16
struct Filter1: HTTPResponseFilter {
func filterHeaders(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
response.setHeader(.custom(name: "X-Custom"), value: "Value")
callback(.continue)
}
func filterBody(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
callback(.continue)
}
}
struct Filter2: HTTPResponseFilter {
func filterHeaders(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
callback(.continue)
}
func filterBody(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
var b = response.bodyBytes
b = b.map { $0 == 65 ? 97 : $0 }
response.bodyBytes = b
callback(.continue)
}
}
struct Filter3: HTTPResponseFilter {
func filterHeaders(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
callback(.continue)
}
func filterBody(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
var b = response.bodyBytes
b = b.map { $0 == 66 ? 98 : $0 }
response.bodyBytes = b
callback(.done)
}
}
struct Filter4: HTTPResponseFilter {
func filterHeaders(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
callback(.continue)
}
func filterBody(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
XCTAssert(false, "This should not execute")
callback(.done)
}
}
let responseFilters: [(HTTPResponseFilter, HTTPFilterPriority)] = [
(Filter1(), HTTPFilterPriority.high),
(Filter2(), HTTPFilterPriority.medium),
(Filter3(), HTTPFilterPriority.low),
(Filter4(), HTTPFilterPriority.low)
]
var routes = Routes()
routes.add(method: .get, uri: "/", handler: {
request, response in
response.addHeader(.contentType, value: "text/plain")
response.isStreaming = true
response.appendBody(string: "ABZ")
response.push {
_ in
response.appendBody(string: "ABZ")
response.completed()
}
}
)
let serverExpectation = self.expectation(description: "server")
let clientExpectation = self.expectation(description: "client")
let server = HTTPServer()
server.setResponseFilters(responseFilters)
server.serverPort = port
server.addRoutes(routes)
func endClient() {
server.stop()
clientExpectation.fulfill()
}
Threading.dispatch {
do {
try server.start()
} catch PerfectError.networkError(let err, let msg) {
XCTAssert(false, "Network error thrown: \(err) \(msg)")
} catch {
XCTAssert(false, "Error thrown: \(error)")
}
serverExpectation.fulfill()
}
Threading.sleep(seconds: 1.0)
let clientNet = NetTCP()
Threading.dispatch {
do {
try clientNet.connect(address: "127.0.0.1", port: port, timeoutSeconds: 5.0) {
net in
guard let net = net else {
XCTAssert(false, "Could not connect to server")
return endClient()
}
let reqStr = "GET / HTTP/1.0\r\nHost: localhost:\(port)\r\nFrom: [email protected]\r\n\r\n"
net.write(string: reqStr) {
count in
guard count == reqStr.utf8.count else {
XCTAssert(false, "Could not write request \(count) != \(reqStr.utf8.count)")
return endClient()
}
Threading.sleep(seconds: 3.0)
net.readSomeBytes(count: 2048) {
bytes in
guard let bytes = bytes, bytes.count > 0 else {
XCTAssert(false, "Could not read bytes from server")
return endClient()
}
let str = UTF8Encoding.encode(bytes: bytes)
let splitted = str.characters.split(separator: "\r\n", omittingEmptySubsequences: false).map(String.init)
let compare = ["HTTP/1.0 200 OK",
"Content-Type: text/plain",
"Transfer-Encoding: chunked",
"X-Custom: Value",
"",
"3",
"abZ",
"3",
"abZ",
"0",
"",
""]
XCTAssert(splitted.count == compare.count)
for (a, b) in zip(splitted, compare) {
XCTAssert(a == b, "\(splitted) != \(compare)")
}
endClient()
}
}
}
} catch {
XCTAssert(false, "Error thrown: \(error)")
endClient()
}
}
self.waitForExpectations(timeout: 10000, handler: {
_ in
})
}
func testServerConf1() {
let port = 8282
func handler(data: [String:Any]) throws -> RequestHandler {
return handler2
}
func handler2(request: HTTPRequest, response: HTTPResponse) {
// Respond with a simple message.
response.setHeader(.contentType, value: "text/html")
response.appendBody(string: "<html><title>Hello, world!</title><body>Hello, world!</body></html>")
// Ensure that response.completed() is called when your processing is done.
response.completed()
}
let confData = [
"servers": [
[
"name":"localhost",
"address":"0.0.0.0",
"port":port,
"routes":[
["method":"get", "uri":"/test.html", "handler":handler],
["method":"get", "uri":"/test.png", "handler":handler2]
],
"filters":[
[
"type":"response",
"priority":"high",
"name":PerfectHTTPServer.HTTPFilter.contentCompression,
]
]
]
]
]
let configs: [HTTPServer.LaunchContext]
do {
configs = try HTTPServer.launch(wait: false, configurationData: confData)
} catch {
return XCTAssert(false, "Error: \(error)")
}
let clientExpectation = self.expectation(description: "client")
Threading.sleep(seconds: 1.0)
do {
let client = NetTCP()
try client.connect(address: "127.0.0.1", port: UInt16(port), timeoutSeconds: 5.0) {
net in
guard let net = net else {
XCTAssert(false, "Could not connect to server")
return clientExpectation.fulfill()
}
let reqStr = "GET /test.html HTTP/1.1\r\nHost: localhost:\(port)\r\nAccept-Encoding: gzip, deflate\r\n\r\n"
net.write(string: reqStr) {
count in
guard count == reqStr.utf8.count else {
XCTAssert(false, "Could not write request \(count) != \(reqStr.utf8.count) \(String(validatingUTF8: strerror(errno)) ?? "no error msg")")
return clientExpectation.fulfill()
}
Threading.sleep(seconds: 2.0)
net.readSomeBytes(count: 1024) {
bytes in
guard let bytes = bytes, bytes.count > 0 else {
XCTAssert(false, "Could not read bytes from server")
return clientExpectation.fulfill()
}
// let str = UTF8Encoding.encode(bytes: bytes)
// let splitted = str.characters.split(separator: "\r\n").map(String.init)
// XCTAssert(splitted.last == msg)
clientExpectation.fulfill()
}
}
}
} catch {
XCTAssert(false, "Error thrown: \(error)")
clientExpectation.fulfill()
}
waitForExpectations(timeout: 10000) {
_ in
configs.forEach { _ = try? $0.terminate().wait() }
}
}
func testRoutingTrailingSlash() {
let port = 8282 as UInt16
var routes = Routes()
let badHandler = {
(_:HTTPRequest, resp:HTTPResponse) in
resp.completed(status: .internalServerError)
}
let goodHandler = {
(_:HTTPRequest, resp:HTTPResponse) in
resp.completed(status: .notFound)
}
routes.add(method: .get, uri: "/", handler: { _, _ in })
routes.add(method: .get, uri: "/test/", handler: goodHandler)
routes.add(method: .get, uri: "/**", handler: badHandler)
let serverExpectation = self.expectation(description: "server")
let clientExpectation = self.expectation(description: "client")
let server = HTTPServer()
server.serverPort = port
server.addRoutes(routes)
func endClient() {
server.stop()
clientExpectation.fulfill()
}
Threading.dispatch {
do {
try server.start()
} catch PerfectError.networkError(let err, let msg) {
XCTAssert(false, "Network error thrown: \(err) \(msg)")
} catch {
XCTAssert(false, "Error thrown: \(error)")
}
serverExpectation.fulfill()
}
Threading.sleep(seconds: 1.0)
let clientNet = NetTCP()
Threading.dispatch {
do {
try clientNet.connect(address: "127.0.0.1", port: port, timeoutSeconds: 5.0) {
net in
guard let net = net else {
XCTAssert(false, "Could not connect to server")
return endClient()
}
let reqStr = "GET /test/ HTTP/1.0\r\nHost: localhost:\(port)\r\nFrom: [email protected]\r\n\r\n"
net.write(string: reqStr) {
count in
guard count == reqStr.utf8.count else {
XCTAssert(false, "Could not write request \(count) != \(reqStr.utf8.count)")
return endClient()
}
Threading.sleep(seconds: 2.0)
net.readSomeBytes(count: 1024) {
bytes in
guard let bytes = bytes, bytes.count > 0 else {
XCTAssert(false, "Could not read bytes from server")
return endClient()
}
let str = UTF8Encoding.encode(bytes: bytes)
let splitted = str.characters.split(separator: "\r\n", omittingEmptySubsequences: false).map(String.init)
let compare = "HTTP/1.0 404 Not Found"
XCTAssert(splitted.first == compare)
endClient()
}
}
}
} catch {
XCTAssert(false, "Error thrown: \(error)")
endClient()
}
}
self.waitForExpectations(timeout: 10000, handler: {
_ in
})
}
static var allTests : [(String, (PerfectHTTPServerTests) -> () throws -> Void)] {
return [
("testHPACKEncode", testHPACKEncode),
("testWebConnectionHeadersWellFormed", testWebConnectionHeadersWellFormed),
("testWebConnectionHeadersLF", testWebConnectionHeadersLF),
("testWebConnectionHeadersMalormed", testWebConnectionHeadersMalormed),
("testWebConnectionHeadersFolded", testWebConnectionHeadersFolded),
("testWebConnectionHeadersTooLarge", testWebConnectionHeadersTooLarge),
("testWebRequestQueryParam", testWebRequestQueryParam),
("testWebRequestPostParam", testWebRequestPostParam),
("testWebRequestCookie", testWebRequestCookie),
("testWebRequestPath1", testWebRequestPath1),
("testWebRequestPath2", testWebRequestPath2),
("testWebRequestPath3", testWebRequestPath3),
("testWebRequestPath4", testWebRequestPath4),
("testSimpleHandler", testSimpleHandler),
("testSimpleStreamingHandler", testSimpleStreamingHandler),
("testSlowClient", testSlowClient),
("testRequestFilters", testRequestFilters),
("testResponseFilters", testResponseFilters),
("testStreamingResponseFilters", testStreamingResponseFilters),
("testServerConf1", testServerConf1),
("testRoutingTrailingSlash", testRoutingTrailingSlash)
]
}
}
| apache-2.0 | 16d8cbcc7b8f8f68061755d7cd2f3f14 | 29.150673 | 221 | 0.632578 | 3.415769 | false | true | false | false |
enbaya/WebyclipSDK | WebyclipSDK/Classes/WebyclipSession.swift | 1 | 7856 | import Foundation
import Alamofire
import CryptoSwift
import SwiftyJSON
/**
A session is user's interaction with the Webyclip videos
*/
open class WebyclipSession {
//MARK: - Private
fileprivate var sslEndpoint: String
private func getDataFromCDN(id: String,
completion: @escaping ([WebyclipMedia]) -> Void,
error: @escaping (_ error: NSError?) -> Void) {
var webyclipMedia = [WebyclipMedia]()
let md5 = id.md5().md5()
let url = "https://\(self.sslEndpoint)/group/\(md5).json"
Alamofire.request(url).responseString { response in
guard response.result.isSuccess else {
print("Error while fetching context: \(response.result.error)")
error(nil)
return
}
guard response.response?.statusCode != 404 else {
print("Object not found on CDN")
error(nil)
return
}
guard let value = response.result.value, value.range(of: "webyclipMediaForContext") != nil else {
print("Malformed data received from CDN")
error(nil)
return
}
let jsonString = value.substring(with: Range<String.Index>(uncheckedBounds: (lower: value.index(value.startIndex, offsetBy: 24) , upper: value.index(value.endIndex, offsetBy: -1))))
if let dataFromString = jsonString.data(using: String.Encoding.utf8, allowLossyConversion: false) {
var cdnIsValid = false
let json = JSON(data: dataFromString)
if (json["cdn_update_time"].exists()) {
let cdnUpdateTime = Date(timeIntervalSince1970: json["cdn_update_time"].doubleValue / 1000)
let now = Date()
if (WebyclipUtils.getDaysBetweenDates(startDate: now, endDate: cdnUpdateTime) <= 3) {
cdnIsValid = true;
}
}
if (cdnIsValid) {
for item in json["contexts"][0]["medias"].arrayValue {
let mediaItem = WebyclipMedia(media: item)
webyclipMedia.append(mediaItem)
}
}
else {
error(nil)
return
}
}
else {
error(nil)
return
}
completion(webyclipMedia)
}
}
private func getDataFromServer(id: String,
config: WebyclipContextConfig,
completion: @escaping ([WebyclipMedia]) -> Void,
error: @escaping (_ error: NSError?) -> Void) {
var webyclipMedia = [WebyclipMedia]()
let md5 = id.md5().md5()
let url = "https://app.webyclip.com/api.php?action=get_media_for_context_group"
let params: Parameters = [
"site_id": self.siteId,
"contexts": [
[
"site_id": self.siteId,
"type": config.type,
"context_id": config.id,
"tags": config.tags
]
],
"group_id": md5
]
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default).responseString { response in
guard response.result.isSuccess else {
print("Error while fetching context: \(response.result.error)")
error(nil)
return
}
guard let value = response.result.value else {
print("Malformed data received from server")
error(nil)
return
}
if let dataFromString = value.data(using: String.Encoding.utf8, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
for item in json["contexts"][0]["medias"].arrayValue {
let mediaItem = WebyclipMedia(media: item)
webyclipMedia.append(mediaItem)
}
}
completion(webyclipMedia)
}
}
//MARK: - Public
open var siteId: String
public init(siteId: String) {
let components = siteId.components(separatedBy: ":")
self.siteId = components[0]
self.sslEndpoint = components[1]
}
/**
Create a context object to represent the content on the view you like to get matching videos for
- parameter config: Context configuration `WebyclipContextConfig`
- parameter success: Callback that is called in case of a success with the newly created `WebyclipContext`
- parameter error: Callback that is called in case of error
*/
open func createContext(_ config: WebyclipContextConfig, success: @escaping (_ context: WebyclipContext) -> Void, error: @escaping (_ error: NSError?) -> Void) {
self.getDataFromCDN(id: config.id,
completion: { medias in
success(WebyclipContext(items: medias))
},
error: {_ in
self.getDataFromServer(id: config.id,
config: config,
completion: { medias in
success(WebyclipContext(items: medias))
},
error: error)
})
}
/**
Create a carousel component with a thumbnail for each media.
- parameter context: Bind this carousel to a context. When the context loads, the context medias will be set to the carousel.
- parameter carouselConfig: Carousel configuration `WebyclipCarouselConfig`
- parameter player: Player object `WebyclipPlayerController`
- returns `WebyclipCarouselController`
*/
open func createCarousel(_ context: WebyclipContext, player: WebyclipPlayerController, carouselConfig: WebyclipCarouselConfig, isCompact: Bool = false) -> WebyclipCarouselController {
return WebyclipCarouselController(session: self, context: context, player: player, config: carouselConfig, isCompact: isCompact)
}
/**
Create a player component that plays media from the defined list.
- parameter config: Player configuration `WebyclipPlayerConfig`
- parameter context: Bind this player to a context. When the context loads, the context medias will be set to the player.
- returns `WebyclipPlayerController`
*/
open func createPlayer(_ config: WebyclipPlayerConfig, context: WebyclipContext) -> WebyclipPlayerController {
return WebyclipPlayerController(session: self, context: context)
}
/**
Report a CFA event
- parameter context: The context this CFA is associated with
- parameter action: The action name
*/
open func reportCFA(_ context: WebyclipContext, action: String) {
// Currently NOT implemented
}
/**
Report purchase
- parameter context: The context this purchase is associated with
*/
open func reportCFA(_ context: WebyclipContext) {
// Currently NOT implemented
}
}
| mit | 85494b8541d29e0b654c8ecf4e03d6cd | 38.676768 | 193 | 0.524058 | 5.240827 | false | true | false | false |
avito-tech/Paparazzo | Paparazzo/Core/VIPER/NewCamera/View/SelectedPhotosBarView.swift | 1 | 7878 | import ImageSource
import UIKit
final class SelectedPhotosBarView: UIView {
let lastPhotoThumbnailView = UIImageView()
private let penultimatePhotoThumbnailView = UIImageView()
let label = UILabel()
private let button = ButtonWithActivity(activityStyle: .white)
private let placeholderLabel = UILabel()
private let lastPhotoThumbnailSize = CGSize(width: 48, height: 36)
private let penultimatePhotoThumbnailSize = CGSize(width: 43, height: 32)
var onButtonTap: (() -> ())?
var onLastPhotoThumbnailTap: (() -> ())?
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
layer.cornerRadius = 10
placeholderLabel.numberOfLines = 2
placeholderLabel.textColor = UIColor(red: 0.646, green: 0.646, blue: 0.646, alpha: 1)
lastPhotoThumbnailView.contentMode = .scaleAspectFill
lastPhotoThumbnailView.clipsToBounds = true
lastPhotoThumbnailView.layer.cornerRadius = 5
lastPhotoThumbnailView.accessibilityIdentifier = "lastPhotoThumbnailView"
penultimatePhotoThumbnailView.contentMode = .scaleAspectFill
penultimatePhotoThumbnailView.clipsToBounds = true
penultimatePhotoThumbnailView.alpha = 0.26
penultimatePhotoThumbnailView.layer.cornerRadius = 5
penultimatePhotoThumbnailView.accessibilityIdentifier = "penultimatePhotoThumbnailView"
button.accessibilityIdentifier = AccessibilityId.doneButton.rawValue
button.titleEdgeInsets = UIEdgeInsets(top: 10, left: 24, bottom: 11, right: 24)
button.layer.backgroundColor = UIColor(red: 0, green: 0.67, blue: 1, alpha: 1).cgColor
button.layer.cornerRadius = 6
button.addTarget(self, action: #selector(handleButtonTap), for: .touchUpInside)
lastPhotoThumbnailView.isUserInteractionEnabled = true
lastPhotoThumbnailView.addGestureRecognizer(
UITapGestureRecognizer(target: self, action: #selector(handleLastPhotoThumbnailTap))
)
addSubview(penultimatePhotoThumbnailView)
addSubview(lastPhotoThumbnailView)
addSubview(label)
addSubview(placeholderLabel)
addSubview(button)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - SelectedPhotosBarView
func setLastImage(_ imageSource: ImageSource?, resultHandler: ((ImageRequestResult<UIImage>) -> ())? = nil) {
lastPhotoThumbnailView.setImage(
fromSource: imageSource,
size: lastPhotoThumbnailSize,
resultHandler: resultHandler
)
}
func setPenultimateImage(_ imageSource: ImageSource?, resultHandler: ((ImageRequestResult<UIImage>) -> ())? = nil) {
penultimatePhotoThumbnailView.setImage(
fromSource: imageSource,
size: penultimatePhotoThumbnailSize,
resultHandler: resultHandler
)
}
func setTheme(_ theme: NewCameraUITheme) {
backgroundColor = theme.newCameraSelectedPhotosBarBackgroundColor
label.textColor = theme.newCameraPhotosCountColor
label.font = theme.newCameraPhotosCountFont
placeholderLabel.font = theme.newCameraPhotosCountPlaceholderFont
placeholderLabel.textColor = theme.newCameraPhotosCountPlaceholderColor
button.titleLabel?.font = theme.newCameraDoneButtonFont
button.setTitleColor(theme.newCameraSelectedPhotosBarButtonTitleColorNormal, for: .normal)
button.backgroundColor = theme.newCameraSelectedPhotosBarButtonBackgroundColor
}
func setDoneButtonTitle(_ title: String) {
button.setTitle(title, for: .normal)
setNeedsLayout()
}
func setPlaceholderText(_ text: String) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineHeightMultiple = 1.07
placeholderLabel.attributedText = NSMutableAttributedString(
string: text,
attributes: [.paragraphStyle: paragraphStyle]
)
setNeedsLayout()
}
func setPlaceholderHidden(_ isHidden: Bool) {
placeholderLabel.isHidden = isHidden
label.isHidden = !isHidden
lastPhotoThumbnailView.isHidden = !isHidden
penultimatePhotoThumbnailView.isHidden = !isHidden
}
func setHidden(_ isHidden: Bool, animated: Bool) {
guard self.isHidden != isHidden else { return }
if animated && isHidden {
transform = .identity
UIView.animate(
withDuration: 0.15,
animations: {
self.alpha = 0
self.transform = CGAffineTransform(translationX: 0, y: 5)
},
completion: { _ in
self.isHidden = true
self.transform = .identity
}
)
} else if animated && !isHidden {
self.isHidden = false
alpha = 0
transform = CGAffineTransform(translationX: 0, y: 5)
UIView.animate(
withDuration: 0.15,
animations: {
self.alpha = 1
self.transform = .identity
}
)
} else {
self.isHidden = isHidden
}
}
func setContinueButtonStyle(_ style: MediaPickerContinueButtonStyle) {
guard button.style != style else { return }
UIView.animate(
withDuration: 0.3,
animations: {
self.button.style = style
self.layOutButton()
}
)
}
// MARK: - UIView
override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: size.width, height: 72)
}
override func layoutSubviews() {
super.layoutSubviews()
lastPhotoThumbnailView.layout(
left: bounds.left + 15,
top: bounds.top + 18,
width: lastPhotoThumbnailSize.width,
height: lastPhotoThumbnailSize.height
)
penultimatePhotoThumbnailView.layout(
left: bounds.left + 19,
top: lastPhotoThumbnailView.top + 9,
width: penultimatePhotoThumbnailSize.width,
height: penultimatePhotoThumbnailSize.height
)
layOutButton()
let placeholderInsets = UIEdgeInsets(top: 0, left: 19, bottom: 0, right: 7)
let placeholderSize = placeholderLabel.sizeForWidth(button.left - bounds.left - placeholderInsets.width)
placeholderLabel.frame = CGRect(
x: bounds.left + placeholderInsets.left,
y: floor(bounds.top + (bounds.height - placeholderSize.height) / 2),
width: placeholderSize.width,
height: placeholderSize.height
)
label.layout(
left: lastPhotoThumbnailView.right + 8,
right: button.left - 16,
top: bounds.top,
bottom: bounds.bottom
)
}
// MARK: - Private - Layout
private func layOutButton() {
let buttonSize = button.sizeThatFits()
button.frame = CGRect(
x: bounds.right - 16 - buttonSize.width,
y: floor(bounds.centerY - buttonSize.height / 2),
width: buttonSize.width,
height: buttonSize.height
)
}
// MARK: - Private - Event handlers
@objc private func handleButtonTap() {
onButtonTap?()
}
@objc private func handleLastPhotoThumbnailTap() {
onLastPhotoThumbnailTap?()
}
}
| mit | 02002e8edbde5534c4d4161972a210d8 | 34.169643 | 120 | 0.609673 | 5.30148 | false | false | false | false |
oursky/Redux | Example/Redux/TodoListAction.swift | 1 | 2225 | //
// TodoListAction.swift
// SwiftRedux
//
// Created by Steven Chan on 31/12/15.
// Copyright (c) 2016 Oursky Limited. All rights reserved.
//
import Redux
let kTodoListUserDefaultsKey = "SwiftRedux.example.TodoList"
public enum TodoListAction: ReduxActionType {
case load
case loadSuccess(list: [TodoListItem])
case loadFail
case add(token: String, content: String)
case addSuccess(token: String, createdAt: NSDate)
case addFail(token: String)
}
public struct TodoListActionCreators {
static func load(
_ dispatch: @escaping DispatchFunction,
userDefaults: UserDefaults
) {
dispatch(
ReduxAction(payload: TodoListAction.load)
)
let list = userDefaults
.array(forKey: kTodoListUserDefaultsKey) ?? [Any]()
let itemList = list.map {
(item: Any) in
TodoListItem(dict: (item as! [String: AnyObject]))
}
// need some time to load
delay(1.0) {
dispatch(
ReduxAction(
payload: TodoListAction.loadSuccess(list: itemList)
)
)
}
}
static func add(
_ content: String,
dispatch: DispatchFunction,
userDefaults: UserDefaults
) {
let token = NSUUID().uuidString
dispatch(
ReduxAction(
payload: TodoListAction.add(token: token, content: content)
)
)
let createdAt = NSDate()
let newItem = TodoListItem(content: content, createdAt: createdAt)
var list = userDefaults
.array(forKey: kTodoListUserDefaultsKey) ?? [AnyObject]()
list.append(newItem.toDict())
userDefaults.set(list, forKey: kTodoListUserDefaultsKey)
userDefaults.synchronize()
dispatch(
ReduxAction(
payload: TodoListAction.addSuccess(
token: token,
createdAt: createdAt
)
)
)
}
}
// delay helper
func delay(_ delay: Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
closure()
}
}
| mit | dc123fc77ddb150255794196fe75824f | 22.670213 | 75 | 0.571685 | 4.723992 | false | false | false | false |
geeven/EveryWeekSwiftDemo | Demo1/Demo1/ViewController.swift | 1 | 1879 | //
// ViewController.swift
// Demo1
//
// Created by Geeven on 16/3/3.
// Copyright © 2016年 Geeven. All rights reserved.
//
import UIKit
import SnapKit
class ViewController: UIViewController {
//MARK: - 属性
@IBOutlet weak var containerView: UIView!
//MARK: - 生命周期方法
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
//添加手势
let gesture = UIPanGestureRecognizer(target: self, action:"panGesture:")
view.addGestureRecognizer(gesture)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - 私有函数
@objc private func panGesture(gesture:UIPanGestureRecognizer) {
let location = gesture.locationInView(self.containerView)
containerView.transform = CGAffineTransformTranslate(containerView.transform, location.x, 0)
gesture.setTranslation(CGPointZero, inView: containerView)
}
//MARK: - 私有函数
private lazy var titleLabel:UILabel = {
let label = UILabel()
label.font = UIFont.systemFontOfSize(20)
label.text = "利用storyBoard实现\n最简单的抽屉效果"
label.textColor = UIColor.redColor()
label.backgroundColor = UIColor.yellowColor()
label.numberOfLines = 0
label.textAlignment = .Center
label.sizeToFit()
return label
}()
}
extension ViewController {
private func setupUI() {
view.backgroundColor = UIColor.whiteColor()
view.insertSubview(titleLabel, atIndex: 0)
titleLabel.snp_makeConstraints { (make) -> Void in
make.center.equalTo(view)
}
}
}
| mit | 822c969a677711964e857ec0708cb9df | 21.65 | 100 | 0.584989 | 5.191977 | false | false | false | false |
tensorflow/swift-models | TrainingLoop/TrainingLoop.swift | 1 | 13734 | // Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// 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 ModelSupport
import TensorFlow
// Workaround https://bugs.swift.org/browse/TF-1122 that prevents us from registering a
// loss function inside our TrainingLoop struct
public final class LossFunctionWrapper<Output: Differentiable, Target> {
public typealias F = @differentiable(Output, @noDerivative Target) -> Tensor<Float>
public var f: F
init(_ f: @escaping F) { self.f = f }
}
/// Types whose elements represent a training loop.
///
/// - Note: This protocol is mainly there to give us an easy type for a generic `TrainingLoop`
/// and unless you need to rewrite your own training loop entirely, you should use `TrainingLoop`.
public protocol TrainingLoopProtocol {
// Associatedtypes
/// The type of the sequence of epochs for the training data.
associatedtype Training
where
Training: Sequence, Training.Element: Collection,
Training.Element.Element == LabeledData<Opt.Model.Input, Target>
/// The type of the collection of batches for the validation data.
associatedtype Validation
where
Validation: Collection,
Validation.Element == LabeledData<Opt.Model.Input, Target>
/// The type of the target of our model.
associatedtype Target
/// The type of the optimizer used.
associatedtype Opt: Optimizer where Opt.Model: Module
// Typealiases
/// The type of the model.
typealias Model = Opt.Model
/// The type of the input of the model.
typealias Input = Opt.Model.Input
/// The type of the output of the model.
typealias Output = Opt.Model.Output
/// The type of a batch.
typealias Batch = LabeledData<Input, Target>
// In a wrapper for now because of TF-1122.
/// The type of the loss function.
typealias LossFunction = LossFunctionWrapper<Output, Target>
// Data
/// The training epochs.
var training: Training { get }
/// The validation batches.
var validation: Validation { get }
// Optimizer and loss function
/// The optimizer.
var optimizer: Opt { get set }
/// The loss function.
var lossFunction: LossFunction { get set }
/// The metrics on which training is measured.
var metrics: [TrainingMetrics] { get set }
// Callbacks
/// The callbacks used to customize the training loop.
var callbacks: [TrainingLoopCallback<Self>] { get set }
// Temporary data
// MARK: - Step-level data
/// The last input fed to the model.
var lastStepInput: Input? { get set }
/// The last target.
var lastStepTarget: Target? { get set }
/// The last predictions of the model.
var lastStepOutput: Output? { get set }
/// The last gradients computed.
var lastStepGradient: Model.TangentVector? { get set }
/// The last loss.
var lastStepLoss: Tensor<Float>? { get set }
/// The number of batches in the current collection of batches.
var batchCount: Int? { get set }
/// The index of the current batch.
var batchIndex: Int? { get set }
// MARK: - Epoch-level data
/// The number of epochs we are currently fitting for.
var epochCount: Int? { get set }
/// The index of the current epoch.
var epochIndex: Int? { get set }
// MARK: - Others
/// The log for last statistics
var lastStatsLog: [(name: String, value: Float)]? { get set }
}
/// The events that occur during a call to `fit` in the `TrainingLoop`
///
/// - Note: The method is called `fit` and not `train` because it trains the model and validates it.
/// Each epoch is composed of a *training* phase and a *validation* phase.
public enum TrainingLoopEvent {
/// The start of a fit.
case fitStart
/// The end of a fit.
case fitEnd
/// The start of one epoch (training + validation).
case epochStart
/// The start of one epoch (training + validation).
case epochEnd
/// The start of a training phase.
case trainingStart
/// The end of a training phase.
case trainingEnd
/// The start of a validation phase.
case validationStart
/// The end of a validation phase.
case validationEnd
/// The start of a training or inference step on a batch.
case batchStart
/// The end of a training or inference step on a batch.
case batchEnd
/// At the start of the optimizer update, just after the differentiable step.
case updateStart
/// Just after the model prediction at inference, before computing the loss.
case inferencePredictionEnd
}
/// Callbacks that can inject custom behavior in a training loop.
public typealias TrainingLoopCallback<L: TrainingLoopProtocol> = (
_ loop: inout L, _ event: TrainingLoopEvent
) throws -> Void
/// A generic training loop.
///
/// - Parameter `Training`: the type of the sequence of epochs for training data.
/// - Parameter `Validation`: the type of the collection of batches for validation.
/// - Parameter `Target`: the type of the target.
/// - Parameter `Opt`: the type of the optimizer used.
public struct TrainingLoop<
Training: Sequence, Validation: Collection, Target, Opt: Optimizer
>: TrainingLoopProtocol
where
Training.Element: Collection, Training.Element.Element == LabeledData<Opt.Model.Input, Target>,
Validation.Element == LabeledData<Opt.Model.Input, Target>, Opt.Model: Module
{
// Typealiases
/// The type of the model.
public typealias Model = Opt.Model
/// The type of the input of the model.
public typealias Input = Opt.Model.Input
/// The type of the output of the model.
public typealias Output = Opt.Model.Output
/// The type of a batch.
public typealias Batch = LabeledData<Input, Target>
// In a wrapper for now because of TF-1122.
/// The type of the loss function.
public typealias LossFunction = LossFunctionWrapper<Output, Target>
// Data
/// The training epochs.
public let training: Training
/// The validation batches.
public let validation: Validation
// Optimizer and loss function
/// The optimizer.
public var optimizer: Opt
/// The loss function
public var lossFunction: LossFunction
/// The metrics
public var metrics: [TrainingMetrics]
/// Callbacks
/// The callbacks used to customize the training loop.
public var callbacks: [TrainingLoopCallback<Self>]
// MARK: - Default callback objects
/// The callback that records the training statistics.
public var statisticsRecorder: StatisticsRecorder? = nil
/// The callback that prints the training progress.
public var progressPrinter: ProgressPrinter? = nil
/// Temporary data
// MARK: - Step-level data
/// The last input fed to the model.
public var lastStepInput: Input? = nil
/// The last target.
public var lastStepTarget: Target? = nil
/// The last predictions of the model.
public var lastStepOutput: Output? = nil
/// The last gradients computed.
public var lastStepGradient: Model.TangentVector? = nil
/// The last loss.
public var lastStepLoss: Tensor<Float>? = nil
/// The number of batches in the current collection of batches.
public var batchCount: Int? = nil
/// The index of the current batch.
public var batchIndex: Int? = nil
// MARK: - Epoch-level data
/// The number of epochs we are currently fitting for.
public var epochCount: Int? = nil
/// The index of the current epoch.
public var epochIndex: Int? = nil
// MARK: - Others
/// The log for last statistics
public var lastStatsLog: [(name: String, value: Float)]? = nil
/// Creates an instance from `training` and `validation` data, a `model`, an `optimizer` and a
/// `lossFunction`.
///
/// Parameter callbacks: Callbacks that the `TrainingLoop` will use in every call to fit.
public init(
training: Training, validation: Validation, optimizer: Opt,
lossFunction: @escaping LossFunction.F,
metrics: [TrainingMetrics] = [],
callbacks: [TrainingLoopCallback<Self>] = [],
includeDefaultCallbacks: Bool = true
) {
self.training = training
self.validation = validation
self.optimizer = optimizer
self.lossFunction = LossFunction(lossFunction)
self.metrics = metrics
if includeDefaultCallbacks {
let statisticsRecorder = StatisticsRecorder(metrics: [.loss] + metrics)
let progressPrinter = ProgressPrinter()
self.statisticsRecorder = statisticsRecorder
self.progressPrinter = progressPrinter
self.callbacks = [
statisticsRecorder.record,
progressPrinter.printProgress,
] + callbacks
} else {
self.callbacks = callbacks
}
}
}
extension TrainingLoop {
/// The default differentiable step.
public mutating func differentiableStep(model: Model) throws {
guard let data = lastStepInput else { return }
guard let target = lastStepTarget else { return }
(lastStepLoss, lastStepGradient) = valueWithGradient(at: model) {
(model: Model) -> Tensor<Float> in
let predictions = model(data)
lastStepOutput = predictions
return lossFunction.f(predictions, target)
}
}
/// The step used for inference.
public mutating func inferenceStep(model: Model) throws {
guard let data = lastStepInput else { return }
lastStepOutput = model(data)
guard let target = lastStepTarget else { return }
try handleEvent(.inferencePredictionEnd)
lastStepLoss = lossFunction.f(lastStepOutput!, target)
}
/// The step used for training.
public mutating func trainingStep(
model: inout Model, differentiableStep: (Model, inout Self) throws -> Void
) throws {
try differentiableStep(model, &self)
try handleEvent(.updateStart)
optimizer.update(&model, along: lastStepGradient!)
}
}
/// Control flow of the training loop.
///
/// - Note: Each of the "end" event is called after its corresponding "cancel" action for cleanup.
public enum TrainingLoopAction: Error {
/// Abort actions in the current training/inference step and goes to the next batch.
case cancelBatch
/// Abort actions in the current training phase and goes to the validation phase.
case cancelTraining
/// Abort actions in the current validation phase and goes to the next epoch.
case cancelValidation
/// Abort actions in the current epoch and goes to the next epoch.
case cancelEpoch
/// Abort actions in the current fit and ends fitting.
case cancelFit
}
extension TrainingLoop {
/// Call `event` on all callbacks.
mutating private func handleEvent(_ event: TrainingLoopEvent) throws {
for callback in callbacks {
try callback(&self, event)
}
}
}
extension TrainingLoop {
/// Performs `step` on each of `batches`.
mutating private func multipleSteps<Batches: Collection>(
on batches: Batches, step: (inout Self) throws -> Void
) throws where Batches.Element == Batch {
batchCount = batches.count
for (i, batch) in batches.enumerated() {
batchIndex = i
(lastStepInput, lastStepTarget) = (batch.data, batch.label)
do {
try handleEvent(.batchStart)
try step(&self)
} catch TrainingLoopAction.cancelBatch {}
try handleEvent(.batchEnd)
LazyTensorBarrier()
}
}
}
extension TrainingLoop {
/// Fit the model for `epochs` using `callbacks` to customize the default training loop.
///
/// - Parameters:
/// - inferenceStep: The step used during the validation phase of each epoch. The default value
/// uses the `inferenceStep` method of `TrainingLoop`.
/// - trainingStep: The step used during the training phase of each epoch. The default value
/// uses the `trainingStep` method of `TrainingLoop`.
public mutating func fit(
_ model: inout Model, epochs: Int, callbacks: [TrainingLoopCallback<Self>] = [],
on device: Device = Device.default,
differentiableStep: (Model, inout Self) throws -> Void = {
try $1.differentiableStep(model: $0)
}
) throws {
let callbacksCount = self.callbacks.count
self.callbacks += callbacks
defer { self.callbacks = Array(self.callbacks.prefix(callbacksCount)) }
epochCount = epochs
model.move(to: device)
optimizer = Opt(copying: optimizer, to: device)
do {
try handleEvent(.fitStart)
LazyTensorBarrier()
for (i, batches) in training.prefix(epochs).enumerated() {
epochIndex = i
do {
try handleEvent(.epochStart)
// Training phase
do {
Context.local.learningPhase = .training
try handleEvent(.trainingStart)
try multipleSteps(
on: batches,
step: {
try $0.trainingStep(model: &model, differentiableStep: differentiableStep)
})
} catch TrainingLoopAction.cancelTraining {}
try handleEvent(.trainingEnd)
// Validation phase
do {
Context.local.learningPhase = .inference
try handleEvent(.validationStart)
try multipleSteps(on: validation, step: { try $0.inferenceStep(model: model) })
} catch TrainingLoopAction.cancelValidation {}
try handleEvent(.validationEnd)
} catch TrainingLoopAction.cancelEpoch {}
try handleEvent(.epochEnd)
}
} catch TrainingLoopAction.cancelFit {}
try handleEvent(.fitEnd)
}
}
| apache-2.0 | 63917e52c26059c68add1ba888228027 | 30.072398 | 100 | 0.693243 | 4.336596 | false | false | false | false |
khizkhiz/swift | test/IDE/complete_pattern.swift | 8 | 6303 |
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_IS_1 > %t.types.txt
// RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.types.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_IS_2 > %t.types.txt
// RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.types.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_IS_3 > %t.types.txt
// RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.types.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_IS_GENERIC_1 > %t.types.txt
// RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.types.txt
// RUN: FileCheck %s -check-prefix=PATTERN_IS_GENERIC_1 < %t.types.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PATTERN_IS_GENERIC_2 > %t.types.txt
// RUN: FileCheck %s -check-prefix=GLOBAL_NEGATIVE < %t.types.txt
// RUN: FileCheck %s -check-prefix=PATTERN_IS_GENERIC_2 < %t.types.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AFTER_PATTERN_IS | FileCheck %s -check-prefix=AFTER_PATTERN_IS
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MULTI_PATTERN_1 | FileCheck %s -check-prefix=MULTI_PATTERN_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MULTI_PATTERN_2 | FileCheck %s -check-prefix=MULTI_PATTERN_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MULTI_PATTERN_3 | FileCheck %s -check-prefix=MULTI_PATTERN_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MULTI_PATTERN_4 | FileCheck %s -check-prefix=MULTI_PATTERN_4
//===--- Helper types that are used in this test
struct FooStruct {
}
var fooObject : FooStruct
func fooFunc() -> FooStruct {
return fooObject
}
enum FooEnum {
}
class FooClass {
}
protocol FooProtocol {
var fooInstanceVar : Int
typealias FooTypeAlias1
func fooInstanceFunc0() -> Double
func fooInstanceFunc1(a: Int) -> Double
subscript(i: Int) -> Double
}
protocol BarProtocol {
var barInstanceVar : Int
typealias BarTypeAlias1
func barInstanceFunc0() -> Double
func barInstanceFunc1(a: Int) -> Double
}
typealias FooTypealias = Int
// GLOBAL_NEGATIVE-NOT: fooObject
// GLOBAL_NEGATIVE-NOT: fooFunc
//===---
//===--- Test that we don't try to suggest anything where pattern-atom is expected.
//===---
var #^PATTERN_ATOM_1^#
var (#^PATTERN_ATOM_2^#
var (a, #^PATTERN_ATOM_3^#
var (a #^PATTERN_ATOM_4^#
var ((#^PATTERN_ATOM_5^#
var ((a, b), #^PATTERN_ATOM_6^#
//===---
//===--- Test that we complete the type in 'is' pattern.
//===---
func patternIs1(x: FooClass) {
switch x {
case is #^PATTERN_IS_1^#
}
}
func patternIs2() {
switch unknown_var {
case is #^PATTERN_IS_2^#
}
}
func patternIs3() {
switch {
case is #^PATTERN_IS_3^#
}
}
//===--- Test that we include types from generic parameter lists.
func patternIsGeneric1<
GenericFoo : FooProtocol,
GenericBar : protocol<FooProtocol, BarProtocol>,
GenericBaz>(x: FooClass) {
switch x {
case is #^PATTERN_IS_GENERIC_1^#
}
}
// PATTERN_IS_GENERIC_1: Begin completions
// Generic parameters of the function.
// PATTERN_IS_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}}
// PATTERN_IS_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: GenericBar[#GenericBar#]{{; name=.+$}}
// PATTERN_IS_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: GenericBaz[#GenericBaz#]{{; name=.+$}}
// PATTERN_IS_GENERIC_1: End completions
struct PatternIsGeneric2<
StructGenericFoo : FooProtocol,
StructGenericBar : protocol<FooProtocol, BarProtocol>,
StructGenericBaz> {
func patternIsGeneric2<
GenericFoo : FooProtocol,
GenericBar : protocol<FooProtocol, BarProtocol>,
GenericBaz>(x: FooClass) {
switch x {
case is #^PATTERN_IS_GENERIC_2^#
}
}
}
// PATTERN_IS_GENERIC_2: Begin completions
// Generic parameters of the struct.
// PATTERN_IS_GENERIC_2-DAG: Decl[GenericTypeParam]/CurrNominal: StructGenericFoo[#StructGenericFoo#]{{; name=.+$}}
// PATTERN_IS_GENERIC_2-DAG: Decl[GenericTypeParam]/CurrNominal: StructGenericBar[#StructGenericBar#]{{; name=.+$}}
// PATTERN_IS_GENERIC_2-DAG: Decl[GenericTypeParam]/CurrNominal: StructGenericBaz[#StructGenericBaz#]{{; name=.+$}}
// Generic parameters of the function.
// PATTERN_IS_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}}
// PATTERN_IS_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: GenericBar[#GenericBar#]{{; name=.+$}}
// PATTERN_IS_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: GenericBaz[#GenericBaz#]{{; name=.+$}}
// PATTERN_IS_GENERIC_2: End completions
// rdar://21174713
// AFTER_PATTERN_IS: Begin completions
func test<T>(x: T) {
switch T.self {
case is Int.Type:
#^AFTER_PATTERN_IS^#
}
}
func test_multiple_patterns1(x: Int) {
switch (x, x) {
case (0, let a), #^MULTI_PATTERN_1^#
}
}
// MULTI_PATTERN_1: Begin completions
// MULTI_PATTERN_1-NOT: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// MULTI_PATTERN_1-DAG: Decl[LocalVar]/Local: x[#Int#]{{; name=.+$}}
// MULTI_PATTERN_1: End completions
func test_multiple_patterns2(x: Int) {
switch (x, x) {
case (0, let a), (let a, 0):
#^MULTI_PATTERN_2^#
}
}
// MULTI_PATTERN_2: Begin completions
// MULTI_PATTERN_2-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// MULTI_PATTERN_2-DAG: Decl[LocalVar]/Local: x[#Int#]{{; name=.+$}}
// MULTI_PATTERN_2: End completions
func test_multiple_patterns3(x: Int) {
switch (x, x) {
case (0, let a), (let b, 0):
#^MULTI_PATTERN_3^#
}
}
// MULTI_PATTERN_3: Begin completions
// MULTI_PATTERN_3-DAG: Decl[LocalVar]/Local: x[#Int#]{{; name=.+$}}
// MULTI_PATTERN_3: End completions
func test_multiple_patterns4(x: Int) {
switch (x, x) {
case (0, let a) where #^MULTI_PATTERN_4^#
}
}
// MULTI_PATTERN_4: Begin completions
// MULTI_PATTERN_4-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// MULTI_PATTERN_4-DAG: Decl[LocalVar]/Local: x[#Int#]{{; name=.+$}}
// MULTI_PATTERN_4: End completions
| apache-2.0 | 3ac1b2006717de92cb0a09df30a258a8 | 30.994924 | 153 | 0.683484 | 3.372392 | false | true | false | false |
tkremenek/swift | test/Generics/unify_concrete_types_1.swift | 1 | 1084 | // RUN: %target-typecheck-verify-swift -requirement-machine=verify -debug-requirement-machine 2>&1 | %FileCheck %s
struct Foo<A, B> {}
protocol P1 {
associatedtype X where X == Foo<Y1, Z1>
associatedtype Y1
associatedtype Z1
}
protocol P2 {
associatedtype X where X == Foo<Y2, Z2>
associatedtype Y2
associatedtype Z2
}
struct MergeTest<G : P1 & P2> {
func foo1(x: G.Y1) -> G.Y2 { return x }
func foo2(x: G.Z1) -> G.Z2 { return x }
}
// CHECK-LABEL: Adding generic signature <τ_0_0 where τ_0_0 : P1, τ_0_0 : P2> {
// CHECK-LABEL: Rewrite system: {
// CHECK: - τ_0_0.[P2:Y2] => τ_0_0.[P1:Y1]
// CHECK: - τ_0_0.[P2:Z2] => τ_0_0.[P1:Z1]
// CHECK: }
// CHECK-LABEL: Equivalence class map: {
// CHECK: [P1:X] => { concrete_type: [concrete: Foo<τ_0_0, τ_0_1> with <[P1:Y1], [P1:Z1]>] }
// CHECK: [P2:X] => { concrete_type: [concrete: Foo<τ_0_0, τ_0_1> with <[P2:Y2], [P2:Z2]>] }
// CHECK: τ_0_0 => { conforms_to: [P1 P2] }
// CHECK: τ_0_0.[P1&P2:X] => { concrete_type: [concrete: Foo<τ_0_0, τ_0_1> with <τ_0_0.[P2:Y2], τ_0_0.[P2:Z2]>] }
// CHECK: }
| apache-2.0 | c42fbb6d2816837a3bf57de8a213a40e | 32.34375 | 114 | 0.593252 | 2.222917 | false | false | false | false |
programersun/HiChongSwift | HiChongSwift/SquareDetailMiddleCell.swift | 1 | 1509 | //
// SquareDetailMiddleCell.swift
// HiChongSwift
//
// Created by eagle on 14/12/12.
// Copyright (c) 2014年 Duostec. All rights reserved.
//
import UIKit
class SquareDetailMiddleCell: UITableViewCell {
@IBOutlet weak private var icyMakeImageView: UIImageView!
@IBOutlet weak var icyLabel: UILabel!
enum SquareDetailMiddleCellType: Int {
case Location = 0
case Phone
case Comment
}
var cellType: SquareDetailMiddleCellType?{
didSet{
if let unwrapped = cellType {
switch unwrapped {
case .Location:
self.icyMakeImageView.image = UIImage(named: "sqDetailGeoMark")
case .Phone:
self.icyMakeImageView.image = UIImage(named: "sqDetailPhone")
case .Comment:
self.icyMakeImageView.image = UIImage(named: "sqDetailComment")
}
}
}
}
class func identifier() -> String {
return "SquareDetailMiddleCellIdentifier"
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.icyLabel.textColor = UIColor.LCYThemeDarkText()
self.cellType = SquareDetailMiddleCellType.Location
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| apache-2.0 | 6ad953135605002665c5119cfb0e0676 | 26.4 | 83 | 0.595886 | 4.845659 | false | false | false | false |
devpunk/velvet_room | Source/Model/Vita/MVitaLinkStorageIdentifier.swift | 1 | 1917 | import Foundation
extension MVitaLink
{
private static let kPredicate:String = "identifier == \"%@\""
private class func factoryPredicate(
identifier:String) -> NSPredicate
{
let predicateString:String = String(
format:MVitaLink.kPredicate,
identifier)
let predicate:NSPredicate = NSPredicate(
format:predicateString)
return predicate
}
private class func createIdentifier(
identifier:String,
database:Database,
completion:@escaping((DVitaIdentifier) -> ()))
{
database.create
{ (item:DVitaIdentifier) in
item.config(identifier:identifier)
identifierCreated(
identifier:item,
database:database,
completion:completion)
}
}
private class func identifierCreated(
identifier:DVitaIdentifier,
database:Database,
completion:@escaping((DVitaIdentifier) -> ()))
{
database.save
{
completion(identifier)
}
}
//MARK: internal
class func factoryIdentifier(
identifier:String,
database:Database,
completion:@escaping((DVitaIdentifier) -> ()))
{
let predicate:NSPredicate = factoryPredicate(
identifier:identifier)
database.fetch(predicate:predicate)
{ (items:[DVitaIdentifier]) in
guard
let first:DVitaIdentifier = items.first
else
{
createIdentifier(
identifier:identifier,
database:database,
completion:completion)
return
}
completion(first)
}
}
}
| mit | df4992287da0f2a24b27f02be2b28421 | 23.896104 | 65 | 0.515389 | 6.009404 | false | false | false | false |
wendyabrantes/WAInvisionProjectSpaceExample | WAInvisionProjectSpace/InvisionProjectSpaceTransition.swift | 1 | 8142 | //
// InvisionProjectSpaceTransition.swift
// WAInvisionProjectSpaceExample
//
// Created by Wendy Abrantes on 23/02/2017.
// Copyright © 2017 Wendy Abrantes. All rights reserved.
//
import UIKit
class InvisionProjectSpaceTransition: NSObject, UIViewControllerAnimatedTransitioning {
private var isDismissed = false
init(isDismissed: Bool) {
self.isDismissed = isDismissed
super.init()
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.4
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if(isDismissed){
dimissController(transitionContext: transitionContext)
} else {
presentController(transitionContext: transitionContext)
}
}
func copyVisibleCells(visibleCells: [UICollectionViewCell], currentSelected: InvisionProjectSpaceViewCell?) -> (cells:[InvisionProjectSpaceViewCell], selectedCell: InvisionProjectSpaceViewCell?) {
var cells = [InvisionProjectSpaceViewCell]()
var selectedCell: InvisionProjectSpaceViewCell?
guard let visibleCells = visibleCells as? [InvisionProjectSpaceViewCell] else { return (cells, selectedCell) }
for cell in visibleCells {
let copyCell = cell.copy() as! InvisionProjectSpaceViewCell
cells.append(copyCell)
if cell == currentSelected {
selectedCell = copyCell
}
}
return (cells, selectedCell)
}
func presentController(transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: .from) as? InvisionProjectSpaceCollectionViewController else { return }
guard let toVC = transitionContext.viewController(forKey: .to) else { return }
let duration = transitionDuration(using: transitionContext)
let containerView = transitionContext.containerView
containerView.backgroundColor = UIColor.white
let finalFrame = transitionContext.finalFrame(for: toVC)
toVC.view.frame = finalFrame
//1. clone visible cells and get a reference to the selected cell
let copyCells = copyVisibleCells(visibleCells: fromVC.collectionView!.visibleCells, currentSelected: fromVC.selectedCell)
for cell in copyCells.cells {
if let globalFrame = fromVC.collectionView?.convert(cell.frame, to: nil) {
cell.frame = globalFrame
}
//2. add the cell to the temporary container view
containerView.addSubview(cell)
}
var selectedOriginalFrame: CGRect = .zero
if let selectedCell = copyCells.selectedCell {
selectedOriginalFrame = selectedCell.frame
}
//3. hide the current collection view
fromVC.view.isHidden = true
UIViewPropertyAnimator.runningPropertyAnimator(withDuration: duration,
delay: 0.0,
options: [.curveEaseOut, .layoutSubviews],
animations: {
//4. set the template to be fullscreen and animate the frame
if let selectedCell = copyCells.selectedCell {
selectedCell.isFullScreen = true
selectedCell.frame = finalFrame
}
//5. We slide all other cells off the screen
for cell in copyCells.cells {
if cell != copyCells.selectedCell {
var translateX: CGFloat = 0
if cell.frame.minX < selectedOriginalFrame.minX {
translateX = -(cell.frame.maxX + 20)
} else {
translateX = finalFrame.width - (cell.frame.minX - 20)
}
cell.transform = CGAffineTransform(translationX: translateX, y: 0)
}
}
}) { (position) in
for cell in copyCells.cells {
cell.removeFromSuperview()
}
fromVC.view.isHidden = false
containerView.addSubview(toVC.view)
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
func dimissController(transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: .from) else { return }
guard let toVC = transitionContext.viewController(forKey: .to) as? InvisionProjectSpaceCollectionViewController else { return }
let duration = transitionDuration(using: transitionContext)
let containerView = transitionContext.containerView
let finalFrame = transitionContext.finalFrame(for: toVC)
toVC.view.frame = finalFrame
let copyCells = copyVisibleCells(visibleCells: toVC.collectionView!.visibleCells, currentSelected: toVC.selectedCell)
var selectedOriginalFrame: CGRect = .zero
if let selectedCell = copyCells.selectedCell {
selectedOriginalFrame = toVC.collectionView?.convert(selectedCell.frame, to: nil) ?? .zero
//1. we set the current selected cell to full screen template
selectedCell.isFullScreen = true
selectedCell.frame = fromVC.view.frame
}
for cell in copyCells.cells {
//2. all other cell need to be slide of the screen
if cell != copyCells.selectedCell {
if let globalFrame = toVC.collectionView?.convert(cell.frame, to: nil) {
cell.frame = globalFrame
}
var translateX: CGFloat = 0
if cell.frame.minX < selectedOriginalFrame.minX {
translateX = -(cell.frame.maxX + 20)
} else {
translateX = finalFrame.width - (cell.frame.minX - 20)
}
cell.transform = CGAffineTransform(translationX: translateX, y: 0)
}
containerView.addSubview(cell)
}
fromVC.view.removeFromSuperview()
toVC.view.isHidden = true
//3. layout the selected cell for Full screen state
copyCells.selectedCell?.layoutSubviews()
UIViewPropertyAnimator.runningPropertyAnimator(withDuration: duration,
delay: 0.0,
options: [.curveEaseOut, .layoutSubviews],
animations: {
//3. set the card view template and animate the frame
if let selectedCell = copyCells.selectedCell {
selectedCell.isFullScreen = false
selectedCell.frame = selectedOriginalFrame
}
for cell in copyCells.cells {
if cell != copyCells.selectedCell {
cell.transform = CGAffineTransform(translationX: 0, y: 0)
}
}
}) { (position) in
for cell in copyCells.cells {
cell.removeFromSuperview()
}
toVC.view.isHidden = false
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
| mit | 5db126440ee21e7982cc72e4f16453c1 | 43.977901 | 198 | 0.553495 | 6.305964 | false | false | false | false |
Fiser12/LaTuerka-tvOS | LaTuerka/Crawler.swift | 1 | 6573 | //
// Crawler.swift
// LaTuerka
//
// Created by Fiser on 10/2/16.
/*
This file is part of Foobar.
Foobar 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.
Foobar 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import UIKit
import CoreData
class Crawler: Observable{
static let sharedInstance = Crawler()
var observable:[Observer] = []
var programas:[Programa] = [
Programa(Imagen: UIImage(named: "videoblogMonedero")!, URL: "http://especiales.publico.es/publico-tv/la-tuerka/videoblog-de-monedero", Titulo: "VIDEOBLOG DE MONEDERO"),
Programa(Imagen: UIImage(named: "elTornillo")!, URL: "http://especiales.publico.es/publico-tv/la-tuerka/el-tornillo", Titulo: "EL TORNILLO"),
Programa(Imagen: UIImage(named: "laKlau")!, URL: "http://especiales.publico.es/publico-tv/la-tuerka/la-klau", Titulo: "LA KLAU"),
Programa(Imagen: UIImage(named: "laTuerkaNews")!, URL: "http://especiales.publico.es/publico-tv/la-tuerka/tuerka-news", Titulo: "LA TUERKA NEWS"),
Programa(Imagen: UIImage(named: "enClaveTuerka")!, URL: "http://especiales.publico.es/publico-tv/la-tuerka/en-clave-tuerka", Titulo: "EN CLAVE TUERKA"),
Programa(Imagen: UIImage(named: "otraVueltaDeTuerka")!, URL: "http://especiales.publico.es/publico-tv/la-tuerka/otra-vuelta-de-tuerka", Titulo: "OTRA VUELTA DE TUERKA")]
var comprobarProgramas:[String] = []
fileprivate init(){
for programa in programas
{
DispatchQueue.global().async(execute: {
self.descargarProgramasBucle(Programa: programa, URL: programa.url)
DispatchQueue.main.async(execute: {
if let elemento:Observer = self.observable.filter({$0.observerID() == programa.titulo}).first{
elemento.invocar()
}
});
});
}
}
func comprobar(_ id:String)
{
if !comprobarProgramas.contains(id)
{
comprobarProgramas.append(id)
if comprobarProgramas.count == 6{
if let elemento:Observer = self.observable.filter({$0.observerID() == "Central"}).first{
DispatchQueue.main.async(execute: {
elemento.invocar()
});
}
}
}
}
func addObserver(_ observer:Observer)
{
observable.append(observer)
}
func descargarProgramasBucle(Programa programa: Programa, URL urlActual: String)
{
if(urlActual != "#"){
descargarRecursivamente(URL: urlActual, Programa: programa)
if let urlNS:URL = URL(string: urlActual){
if let data:Data = try? Data(contentsOf: urlNS){
let doc = TFHpple(htmlData: data)
if let elements = doc?.search(withXPathQuery: "//div[@class='navegation bottom']//ul//li[@class='next']//a") as? [TFHppleElement] {
descargarProgramasBucle(Programa: programa, URL: elements.first!.object(forKey: "href"))
}
}
}
}
}
fileprivate func descargarRecursivamente(URL urlActual:String, Programa programa:Programa)
{
if let urlNS:URL = URL(string: urlActual)
{
if let data:Data = try? Data(contentsOf: urlNS)
{
let doc = TFHpple(htmlData: data)
if let elements = doc?.search(withXPathQuery: "//div[@class='list']/div[not(@class='robapaginas')]") as? [TFHppleElement] {
for element in elements {
let urlTag:TFHppleElement! = (element.search(withXPathQuery: "//a") as? [TFHppleElement])?.first
var url:String = "http://especiales.publico.es"+(urlTag?.object(forKey: "href"))!
url = obtenerURLVideo(URL: url)
let titulo:String! = ((element.search(withXPathQuery: "//h4//a") as? [TFHppleElement])?.first)?.text()
let imageURL:String! = (urlTag?.search(withXPathQuery: "//img") as? [TFHppleElement])?.first?.object(forKey: "src")
if url != ""{
let episodio:Episodio = Episodio(URL: url, Imagen: imageURL, Titulo: titulo)
programa.episodios.append(episodio)
comprobar(programa.titulo)
}
}
}
}
}
}
func obtenerURLVideo(URL urlActual: String) -> String
{
let urlFinal:String = "";
guard let myURL = URL(string: urlActual) else {
print("Error: \(urlActual) doesn't seem to be a valid URL")
return ""
}
do {
let regex:String = "\\{\"file\":\"(.*)\",\"label\":"
let testStr = try String(contentsOf: myURL, encoding: .ascii)
let nsRegularExpression = try! NSRegularExpression(pattern: regex, options: [])
let matches = nsRegularExpression.matches(in: testStr, options: [], range: NSRange(location: 0, length: testStr.characters.count))
if matches.isEmpty{
return "";
}
for index in 1..<matches[0].numberOfRanges {
return ((testStr as NSString).substring(with: matches[0].range(at: index)))
}
} catch let error {
print("Error: \(error)")
}
return urlFinal
}
}
extension String {
var length: Int {
return self.characters.count
}
func getURLs() -> [URL] {
let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let links = detector?.matches(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSMakeRange(0, length)).map {$0 }
return links!.filter { link in
return link.url != nil
}.map { link -> URL in
return link.url!
}
}
}
| gpl-3.0 | 087b5de1eda1bfe45d1d110ad2ef84b3 | 42.243421 | 177 | 0.580557 | 3.954874 | false | false | false | false |
JakubMazur/FMBMParallaxView | FMBMParallaxView/AppDelegate.swift | 1 | 7071 | //
// AppDelegate.swift
// FMBMParallaxView
//
// Created by Kuba Mazur on 05.07.2014.
// Copyright (c) 2014 Kettu Jakub Mazur. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
func saveContext () {
var error: NSError? = nil
let managedObjectContext = self.managedObjectContext
if managedObjectContext != nil {
if managedObjectContext.hasChanges && !managedObjectContext.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
// #pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
var managedObjectContext: NSManagedObjectContext {
if !_managedObjectContext {
let coordinator = self.persistentStoreCoordinator
if coordinator != nil {
_managedObjectContext = NSManagedObjectContext()
_managedObjectContext!.persistentStoreCoordinator = coordinator
}
}
return _managedObjectContext!
}
var _managedObjectContext: NSManagedObjectContext? = nil
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
var managedObjectModel: NSManagedObjectModel {
if !_managedObjectModel {
let modelURL = NSBundle.mainBundle().URLForResource("FMBMParallaxView", withExtension: "momd")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
}
return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
var persistentStoreCoordinator: NSPersistentStoreCoordinator {
if !_persistentStoreCoordinator {
let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("FMBMParallaxView.sqlite")
var error: NSError? = nil
_persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
NSFileManager.defaultManager().removeItemAtURL(storeURL, error: nil)
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true}
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
return _persistentStoreCoordinator!
}
var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil
// #pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
var applicationDocumentsDirectory: NSURL {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.endIndex-1] as NSURL
}
}
| mit | cde7eb522248c2829635459b7a4e01c8 | 51.377778 | 285 | 0.702447 | 6.122078 | false | false | false | false |
rdlester/simply-giphy | SimplyGiphy/models/GiphyModel.swift | 1 | 6049 | // Model objects corresponding to types from the Giphy API:
// https://developers.giphy.com/docs/#schema-definitions
//
// JSON parsing implemented with Gloss.
import Gloss
// A Giphy User.
struct User: Decodable {
let avatarURL: URL?
let bannerURL: URL?
let profileURL: URL?
let username: String?
let displayName: String?
let twitter: String?
init?(json: JSON) {
avatarURL = "avatar_url" <~~ json
bannerURL = "banner_url" <~~ json
profileURL = "profile_url" <~~ json
username = "username" <~~ json
displayName = "display_name" <~~ json
twitter = "twitter" <~~ json
}
}
// An individual Gif Image.
// Not all items are available for all formats - reference the API docs to determine which are available.
struct ImageFormat: Decodable {
let url: URL?
let width: Int?
let height: Int?
let size: Int?
let frames: Int?
let mp4: URL?
let mp4Size: Int?
let webp: URL?
let webpSize: Int?
init?(json: JSON) {
url = "url" <~~ json
width = jsonStringToInt(key: "width", json: json)
height = jsonStringToInt(key: "height", json: json)
size = jsonStringToInt(key: "size", json: json)
frames = jsonStringToInt(key: "frames", json: json)
mp4 = "mp4" <~~ json
mp4Size = jsonStringToInt(key: "mp4_size", json: json)
webp = "webp" <~~ json
webpSize = jsonStringToInt(key: "webp_size", json: json)
}
}
// Convert a JSON String value to a Swift Int.
private func jsonStringToInt(key: String, json: JSON) -> Int? {
let stringVal: String? = key <~~ json
return stringVal.flatMap { Int($0) }
}
// An array of images in various formats.
struct Images: Decodable {
let fixedHeight: ImageFormat?
let fixedHeightStill: ImageFormat?
let fixedHeightDownsampled: ImageFormat?
let fixedWidth: ImageFormat?
let fixedWidthStill: ImageFormat?
let fixedWidthDownsampled: ImageFormat?
let fixedHeightSmall: ImageFormat?
let fixedHeightSmallStill: ImageFormat?
let fixedWidthSmall: ImageFormat?
let fixedWidthSmallStill: ImageFormat?
let downsized: ImageFormat?
let downsizedStill: ImageFormat?
let downsizedLarge: ImageFormat?
let downsizedMedium: ImageFormat?
let downsizedSmall: ImageFormat?
let original: ImageFormat?
let originalStill: ImageFormat?
let looping: ImageFormat?
let preview: ImageFormat?
let previewGif: ImageFormat?
init?(json: JSON) {
fixedHeight = "fixed_height" <~~ json
fixedHeightStill = "fixed_height_still" <~~ json
fixedHeightDownsampled = "fixed_height_downsampled" <~~ json
fixedWidth = "fixed_width" <~~ json
fixedWidthStill = "fixed_width_still" <~~ json
fixedWidthDownsampled = "fixed_width_downsampled" <~~ json
fixedHeightSmall = "fixed_height_small" <~~ json
fixedHeightSmallStill = "fixed_height_small_still" <~~ json
fixedWidthSmall = "fixed_width_small" <~~ json
fixedWidthSmallStill = "fixed_width_small_still" <~~ json
downsized = "downsized" <~~ json
downsizedStill = "downsized_still" <~~ json
downsizedLarge = "downsized_large" <~~ json
downsizedMedium = "downsized_medium" <~~ json
downsizedSmall = "downsized_small" <~~ json
original = "original" <~~ json
originalStill = "original_still" <~~ json
looping = "looping" <~~ json
preview = "preview" <~~ json
previewGif = "preview_gif" <~~ json
}
}
// Metadata representing the request.
struct Meta: Decodable {
let msg: String?
let status: Int?
let responseId: String?
init?(json: JSON) {
msg = "msg" <~~ json
status = "status" <~~ json
responseId = "response_id" <~~ json
}
}
// Paging information for the associated request.
struct Pagination: Decodable {
let offset: Int?
let totalCount: Int?
let count: Int?
init?(json: JSON) {
offset = "offset" <~~ json
totalCount = "total_count" <~~ json
count = "count" <~~ json
}
}
// An individual Gif.
struct Gif: Decodable {
let type: String?
let id: String? // swiftlint:disable:this identifier_name
let slug: String?
let url: URL?
let bitlyURL: URL?
let embedURL: URL?
let source: URL?
let rating: String?
let tags: [String]?
let featuredTags: [String]?
let user: User?
let sourceTld: String?
let sourcePostURL: URL?
let updateDatetime: Date?
let createDatetime: Date?
let importDatetime: Date?
let trendingDatetime: Date?
let images: Images?
init?(json: JSON) {
type = "type" <~~ json
id = "id" <~~ json
slug = "slug" <~~ json
url = "url" <~~ json
bitlyURL = "bitly_url" <~~ json
embedURL = "embed_url" <~~ json
source = "source" <~~ json
rating = "rating" <~~ json
tags = "tags" <~~ json
featuredTags = "featured_tags" <~~ json
user = "user" <~~ json
sourceTld = "source_tld" <~~ json
sourcePostURL = "source_post_url" <~~ json
let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd HH:mm:ss")
updateDatetime = Decoder.decode(dateForKey: "update_datetime", dateFormatter: dateFormatter)(json)
createDatetime = Decoder.decode(dateForKey: "create_datetime", dateFormatter: dateFormatter)(json)
importDatetime = Decoder.decode(dateForKey: "import_datetime", dateFormatter: dateFormatter)(json)
trendingDatetime = Decoder.decode(dateForKey: "trending_datetime", dateFormatter: dateFormatter)(json)
images = "images" <~~ json
}
}
// The Search API response.
struct SearchResponse: Decodable {
let data: [Gif]?
let pagination: Pagination?
let meta: Meta?
init?(json: JSON) {
data = "data" <~~ json
pagination = "pagination" <~~ json
meta = "meta" <~~ json
}
}
| apache-2.0 | 02876d59d5135267f4971c89a8b39255 | 30.020513 | 110 | 0.626054 | 4.084402 | false | false | false | false |
apple/swift-nio | Sources/NIOCore/EventLoopFuture+WithEventLoop.swift | 1 | 13472 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension EventLoopFuture {
#if swift(>=5.6)
/// When the current `EventLoopFuture<Value>` is fulfilled, run the provided callback,
/// which will provide a new `EventLoopFuture` alongside the `EventLoop` associated with this future.
///
/// This allows you to dynamically dispatch new asynchronous tasks as phases in a
/// longer series of processing steps. Note that you can use the results of the
/// current `EventLoopFuture<Value>` when determining how to dispatch the next operation.
///
/// This works well when you have APIs that already know how to return `EventLoopFuture`s.
/// You can do something with the result of one and just return the next future:
///
/// ```
/// let d1 = networkRequest(args).future()
/// let d2 = d1.flatMapWithEventLoop { t, eventLoop -> EventLoopFuture<NewValue> in
/// eventLoop.makeSucceededFuture(t + 1)
/// }
/// d2.whenSuccess { u in
/// NSLog("Result of second request: \(u)")
/// }
/// ```
///
/// Note: In a sense, the `EventLoopFuture<NewValue>` is returned before it's created.
///
/// - parameters:
/// - callback: Function that will receive the value of this `EventLoopFuture` and return
/// a new `EventLoopFuture`.
/// - returns: A future that will receive the eventual value.
@inlinable
@preconcurrency
public func flatMapWithEventLoop<NewValue>(_ callback: @escaping @Sendable (Value, EventLoop) -> EventLoopFuture<NewValue>) -> EventLoopFuture<NewValue> {
self._flatMapWithEventLoop(callback)
}
@usableFromInline typealias FlatMapWithEventLoopCallback<NewValue> = @Sendable (Value, EventLoop) -> EventLoopFuture<NewValue>
#else
/// When the current `EventLoopFuture<Value>` is fulfilled, run the provided callback,
/// which will provide a new `EventLoopFuture` alongside the `EventLoop` associated with this future.
///
/// This allows you to dynamically dispatch new asynchronous tasks as phases in a
/// longer series of processing steps. Note that you can use the results of the
/// current `EventLoopFuture<Value>` when determining how to dispatch the next operation.
///
/// This works well when you have APIs that already know how to return `EventLoopFuture`s.
/// You can do something with the result of one and just return the next future:
///
/// ```
/// let d1 = networkRequest(args).future()
/// let d2 = d1.flatMapWithEventLoop { t, eventLoop -> EventLoopFuture<NewValue> in
/// eventLoop.makeSucceededFuture(t + 1)
/// }
/// d2.whenSuccess { u in
/// NSLog("Result of second request: \(u)")
/// }
/// ```
///
/// Note: In a sense, the `EventLoopFuture<NewValue>` is returned before it's created.
///
/// - parameters:
/// - callback: Function that will receive the value of this `EventLoopFuture` and return
/// a new `EventLoopFuture`.
/// - returns: A future that will receive the eventual value.
@inlinable
public func flatMapWithEventLoop<NewValue>(_ callback: @escaping (Value, EventLoop) -> EventLoopFuture<NewValue>) -> EventLoopFuture<NewValue> {
self._flatMapWithEventLoop(callback)
}
@usableFromInline typealias FlatMapWithEventLoopCallback<NewValue> = (Value, EventLoop) -> EventLoopFuture<NewValue>
#endif
@inlinable
func _flatMapWithEventLoop<NewValue>(_ callback: @escaping FlatMapWithEventLoopCallback<NewValue>) -> EventLoopFuture<NewValue> {
let next = EventLoopPromise<NewValue>.makeUnleakablePromise(eventLoop: self.eventLoop)
self._whenComplete { [eventLoop = self.eventLoop] in
switch self._value! {
case .success(let t):
let futureU = callback(t, eventLoop)
if futureU.eventLoop.inEventLoop {
return futureU._addCallback {
next._setValue(value: futureU._value!)
}
} else {
futureU.cascade(to: next)
return CallbackList()
}
case .failure(let error):
return next._setValue(value: .failure(error))
}
}
return next.futureResult
}
#if swift(>=5.6)
/// When the current `EventLoopFuture<Value>` is in an error state, run the provided callback, which
/// may recover from the error by returning an `EventLoopFuture<NewValue>`. The callback is intended to potentially
/// recover from the error by returning a new `EventLoopFuture` that will eventually contain the recovered
/// result.
///
/// If the callback cannot recover it should return a failed `EventLoopFuture`.
///
/// - parameters:
/// - callback: Function that will receive the error value of this `EventLoopFuture` and return
/// a new value lifted into a new `EventLoopFuture`.
/// - returns: A future that will receive the recovered value.
@inlinable
@preconcurrency
public func flatMapErrorWithEventLoop(_ callback: @escaping @Sendable (Error, EventLoop) -> EventLoopFuture<Value>) -> EventLoopFuture<Value> {
self._flatMapErrorWithEventLoop(callback)
}
@usableFromInline typealias FlatMapWithErrorWithEventLoopCallback = @Sendable (Error, EventLoop) -> EventLoopFuture<Value>
#else
/// When the current `EventLoopFuture<Value>` is in an error state, run the provided callback, which
/// may recover from the error by returning an `EventLoopFuture<NewValue>`. The callback is intended to potentially
/// recover from the error by returning a new `EventLoopFuture` that will eventually contain the recovered
/// result.
///
/// If the callback cannot recover it should return a failed `EventLoopFuture`.
///
/// - parameters:
/// - callback: Function that will receive the error value of this `EventLoopFuture` and return
/// a new value lifted into a new `EventLoopFuture`.
/// - returns: A future that will receive the recovered value.
@inlinable
public func flatMapErrorWithEventLoop(_ callback: @escaping (Error, EventLoop) -> EventLoopFuture<Value>) -> EventLoopFuture<Value> {
self._flatMapErrorWithEventLoop(callback)
}
@usableFromInline typealias FlatMapWithErrorWithEventLoopCallback = (Error, EventLoop) -> EventLoopFuture<Value>
#endif
@inlinable
func _flatMapErrorWithEventLoop(_ callback: @escaping FlatMapWithErrorWithEventLoopCallback) -> EventLoopFuture<Value> {
let next = EventLoopPromise<Value>.makeUnleakablePromise(eventLoop: self.eventLoop)
self._whenComplete { [eventLoop = self.eventLoop] in
switch self._value! {
case .success(let t):
return next._setValue(value: .success(t))
case .failure(let e):
let t = callback(e, eventLoop)
if t.eventLoop.inEventLoop {
return t._addCallback {
next._setValue(value: t._value!)
}
} else {
t.cascade(to: next)
return CallbackList()
}
}
}
return next.futureResult
}
#if swift(>=5.6)
/// Returns a new `EventLoopFuture` that fires only when this `EventLoopFuture` and
/// all the provided `futures` complete. It then provides the result of folding the value of this
/// `EventLoopFuture` with the values of all the provided `futures`.
///
/// This function is suited when you have APIs that already know how to return `EventLoopFuture`s.
///
/// The returned `EventLoopFuture` will fail as soon as the a failure is encountered in any of the
/// `futures` (or in this one). However, the failure will not occur until all preceding
/// `EventLoopFutures` have completed. At the point the failure is encountered, all subsequent
/// `EventLoopFuture` objects will no longer be waited for. This function therefore fails fast: once
/// a failure is encountered, it will immediately fail the overall EventLoopFuture.
///
/// - parameters:
/// - futures: An array of `EventLoopFuture<NewValue>` to wait for.
/// - with: A function that will be used to fold the values of two `EventLoopFuture`s and return a new value wrapped in an `EventLoopFuture`.
/// - returns: A new `EventLoopFuture` with the folded value whose callbacks run on `self.eventLoop`.
@inlinable
@preconcurrency
public func foldWithEventLoop<OtherValue>(
_ futures: [EventLoopFuture<OtherValue>],
with combiningFunction: @escaping @Sendable (Value, OtherValue, EventLoop) -> EventLoopFuture<Value>
) -> EventLoopFuture<Value> {
func fold0(eventLoop: EventLoop) -> EventLoopFuture<Value> {
let body = futures.reduce(self) { (f1: EventLoopFuture<Value>, f2: EventLoopFuture<OtherValue>) -> EventLoopFuture<Value> in
let newFuture = f1.and(f2).flatMap { (args: (Value, OtherValue)) -> EventLoopFuture<Value> in
let (f1Value, f2Value) = args
self.eventLoop.assertInEventLoop()
return combiningFunction(f1Value, f2Value, eventLoop)
}
assert(newFuture.eventLoop === self.eventLoop)
return newFuture
}
return body
}
if self.eventLoop.inEventLoop {
return fold0(eventLoop: self.eventLoop)
} else {
let promise = self.eventLoop.makePromise(of: Value.self)
self.eventLoop.execute { [eventLoop = self.eventLoop] in
fold0(eventLoop: eventLoop).cascade(to: promise)
}
return promise.futureResult
}
}
@usableFromInline typealias FoldWithEventLoop<OtherValue> = @Sendable (Value, OtherValue, EventLoop) -> EventLoopFuture<Value>
#else
/// Returns a new `EventLoopFuture` that fires only when this `EventLoopFuture` and
/// all the provided `futures` complete. It then provides the result of folding the value of this
/// `EventLoopFuture` with the values of all the provided `futures`.
///
/// This function is suited when you have APIs that already know how to return `EventLoopFuture`s.
///
/// The returned `EventLoopFuture` will fail as soon as the a failure is encountered in any of the
/// `futures` (or in this one). However, the failure will not occur until all preceding
/// `EventLoopFutures` have completed. At the point the failure is encountered, all subsequent
/// `EventLoopFuture` objects will no longer be waited for. This function therefore fails fast: once
/// a failure is encountered, it will immediately fail the overall EventLoopFuture.
///
/// - parameters:
/// - futures: An array of `EventLoopFuture<NewValue>` to wait for.
/// - with: A function that will be used to fold the values of two `EventLoopFuture`s and return a new value wrapped in an `EventLoopFuture`.
/// - returns: A new `EventLoopFuture` with the folded value whose callbacks run on `self.eventLoop`.
@inlinable
public func foldWithEventLoop<OtherValue>(
_ futures: [EventLoopFuture<OtherValue>],
with combiningFunction: @escaping (Value, OtherValue, EventLoop) -> EventLoopFuture<Value>
) -> EventLoopFuture<Value> {
self._foldWithEventLoop(futures, with: combiningFunction)
}
@usableFromInline typealias FoldWithEventLoop<OtherValue> = (Value, OtherValue, EventLoop) -> EventLoopFuture<Value>
#endif
@inlinable
func _foldWithEventLoop<OtherValue>(
_ futures: [EventLoopFuture<OtherValue>],
with combiningFunction: @escaping FoldWithEventLoop<OtherValue>
) -> EventLoopFuture<Value> {
func fold0(eventLoop: EventLoop) -> EventLoopFuture<Value> {
let body = futures.reduce(self) { (f1: EventLoopFuture<Value>, f2: EventLoopFuture<OtherValue>) -> EventLoopFuture<Value> in
let newFuture = f1.and(f2).flatMap { (args: (Value, OtherValue)) -> EventLoopFuture<Value> in
let (f1Value, f2Value) = args
self.eventLoop.assertInEventLoop()
return combiningFunction(f1Value, f2Value, eventLoop)
}
assert(newFuture.eventLoop === self.eventLoop)
return newFuture
}
return body
}
if self.eventLoop.inEventLoop {
return fold0(eventLoop: self.eventLoop)
} else {
let promise = self.eventLoop.makePromise(of: Value.self)
self.eventLoop.execute { [eventLoop = self.eventLoop] in
fold0(eventLoop: eventLoop).cascade(to: promise)
}
return promise.futureResult
}
}
}
| apache-2.0 | 4879b72c33f4d6bfdca7f696ef87f810 | 49.646617 | 158 | 0.642444 | 4.886471 | false | false | false | false |
magnatronus/ti-swift-watch-test | extensions/watchapp/watchapp WatchKit Extension/RepliesInterfaceController.swift | 1 | 1607 | //
// RepliesInterfaceController.swift
// watchapp
//
// Created by Stephen Rogers on 11/03/2016.
//
import WatchKit
import Foundation
import WatchConnectivity
class RepliesInterfaceController: WKInterfaceController {
@IBOutlet var repliesTable: WKInterfaceTable!
var selectedIndex = 0
var replyArray: [String]?
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// check if we have a valid replyModel and populate table
if let replyModel = context as? [String] {
NSLog("Model count: \(replyModel.count)")
replyArray = replyModel
repliesTable.setNumberOfRows(replyModel.count, withRowType: "replyRow")
// create rows
for index in 0..<repliesTable.numberOfRows {
if let controller = repliesTable.rowControllerAtIndex(index) as? ReplyRowController {
controller.reply = replyModel[index] as String
}
}
}
}
// when reply selected sent to phone and close controller
override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) {
// get selected reply
let reply = replyArray![rowIndex]
selectedIndex = rowIndex
// now send it back to the phone
NSLog("Selected reply was \(reply)")
_ = WCSession.defaultSession().transferUserInfo(["reply": reply])
// close controller
dismissController()
}
}
| apache-2.0 | f78123692a4a6399366b08a9e612ccce | 27.696429 | 101 | 0.604231 | 5.465986 | false | false | false | false |
AlexeyDemedetskiy/BillScaner | BillScaner/sources/BillPresenter.swift | 1 | 1002 | //
// BillPresenter.swift
// BillScaner
//
// Created by Alexey Demedetskii on 5/25/17.
// Copyright © 2017 Alexey Demedeckiy. All rights reserved.
//
import Foundation
let moneyFormatter: NumberFormatter = {
var formatter = NumberFormatter()
formatter.numberStyle = .currency
return formatter
}()
func localizedFormatter(sum: Float) -> String {
guard let result = moneyFormatter.string(from: sum as NSNumber) else {
fatalError("Cannot format sum: \(sum)")
}
return result
}
extension BillViewController.ViewModel {
init(bill: Bill, formatter: (Float) -> String = localizedFormatter) {
var total: Float = 0.0
var items: [Item] = bill.items.map { item in
let sum: Float = item.cost * .init(item.count)
total += sum
return Item(title: item.title, sum: formatter(sum))
}
items.append(Item(title: "Total", sum: formatter(total)))
self.items = items
}
}
| mit | 533ad836bd02e9cb8c13b1b45b691a79 | 24.666667 | 74 | 0.621379 | 3.972222 | false | false | false | false |
LiuChang712/SwiftHelper | SwiftHelper/Foundation/Array+SH.swift | 1 | 2852 | //
// Array+Extension.swift
// SwiftHelper
//
// Created by 刘畅 on 16/6/30.
// Copyright © 2016年 LiuChang. All rights reserved.
//
import UIKit
public extension Array {
/// return safe element
subscript (safe index: Int) -> Element? {
return (0..<count).contains(index) ? self[index] : nil
}
/// multiple index
/// eg: let array = [23,23,4,5,67,7] print(array[3,2,1])
subscript(i1: Int, i2: Int, rest: Int...) -> [Element] {
get {
var result: [Element] = [self[i1], self[i2]]
for index in rest {
result.append(self[index])
}
return result
}
set (values) {
for (index, value) in zip([i1, i2] + rest, values) {
self[index] = value
}
}
}
func union(_ values: [Element]...) -> Array {
var result = self
for array in values {
for value in array {
result.append(value)
}
}
return result
}
func random() -> Element? {
guard count > 0 else { return nil }
let index = Int(arc4random_uniform(UInt32(count)))
return self[index]
}
func forEachEnumerated(_ body: @escaping (_ index: Int, _ value: Element) -> Void) {
enumerated().forEach(body)
}
func jsonString() -> String? {
return JSONSerialization.jsonString(from: self)
}
static func json(from jsonString: String) -> Array? {
guard let data = JSONSerialization.jsonObject(from: jsonString) as? Array else { return nil }
return data
}
}
public extension Array where Element: Equatable {
func indexes(of value: Element) -> [Int] {
return enumerated().compactMap { ($0.element == value) ? $0.offset : nil }
}
mutating func remove(value: Element) {
self = filter { $0 != value }
}
mutating func remove(first value: Element) {
guard let index = firstIndex(of: value) else { return }
remove(at: index)
}
mutating func remove(last value: Element) {
guard let index = lastIndex(of: value) else { return }
remove(at: index)
}
}
public extension Array where Element: Hashable {
mutating func remove(objects: [Element]) {
let elementsSet = Set(objects)
self = filter { !elementsSet.contains($0) }
}
mutating func unique() {
self = reduce(into: []) {
if !$0.contains($1) {
$0.append($1)
}
}
}
}
public extension Array where Element: NSObject {
func clone() -> Array {
var objects = Array<Element>()
for element in self {
objects.append(element.copy() as! Element)
}
return objects
}
}
| mit | e019e82cb26f37c45f6473e8772c4440 | 24.630631 | 101 | 0.534622 | 4.0701 | false | false | false | false |
Intercambio/CloudUI | CloudUI/CloudUI/AccountListModule.swift | 1 | 1216 | //
// AccountListModule.swift
// CloudUI
//
// Created by Tobias Kraentzer on 23.01.17.
// Copyright © 2017 Tobias Kräntzer. All rights reserved.
//
import UIKit
import CloudService
public protocol AccountListRouter: class {
func present(_ resource: Resource) -> Void
func presentNewAccount() -> Void
func presentSettings(for account: Account) -> Void
}
public class AccountListModule: UserInterfaceModule {
public weak var router: AccountListRouter?
public let interactor: AccountListInteractor
public init(interactor: AccountListInteractor) {
self.interactor = interactor
}
public func makeViewController() -> UIViewController {
let presenter = AccountListPresenter(interactor: interactor)
presenter.router = router
let viewControler = AccountListViewController(presenter: presenter)
return viewControler
}
}
extension Notification.Name {
public static let AccountListInteractorDidChange = Notification.Name(rawValue: "AccountListInteractorDidChange")
}
public protocol AccountListInteractor: class {
func allAccounts() throws -> [Account]
func resource(with resourceID: ResourceID) throws -> Resource?
}
| gpl-3.0 | eb6e9fd09964d7f0094a29c2636b5432 | 28.609756 | 116 | 0.733937 | 4.760784 | false | false | false | false |
Koolistov/Convenience | Convenience/Logging.swift | 1 | 517 | //
// Logging.swift
// Convenience
//
// Created by Johan Kool on 2/12/14.
// Copyright (c) 2014 Koolistov Pte. Ltd. All rights reserved.
//
import Foundation
/**
Log debug info
Set OTHER_SWIFT_FLAGS = -DDEBUG in your Xcode project target.
*/
public func debugLog(body: Any! = nil, filename: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__) {
#if DEBUG
NSLog("\(NSURL(fileURLWithPath: filename).lastPathComponent):\(line) \(functionName) \(body)")
#endif
}
| mit | 00faf8902d32a593cd33e587e75faae8 | 24.85 | 128 | 0.647969 | 3.640845 | false | false | false | false |
roecrew/AudioKit | AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Oscillator Synth.xcplaygroundpage/Contents.swift | 2 | 1926 | //: ## Oscillator Synth
//:
import XCPlayground
import AudioKit
//: Choose the waveform shape here
let waveform = AKTable(.Sawtooth) // .Triangle, etc.
var oscillator = AKOscillator(waveform: waveform)
var currentMIDINote = 0
var currentAmplitude = 0.1
var currentRampTime = 0.0
AudioKit.output = oscillator
AudioKit.start()
let playgroundWidth = 500
class PlaygroundView: AKPlaygroundView, AKKeyboardDelegate {
override func setup() {
addTitle("Oscillator Synth")
addSubview(AKPropertySlider(
property: "Amplitude",
format: "%0.3f",
value: oscillator.amplitude,
color: AKColor.purpleColor()
) { amplitude in
currentAmplitude = amplitude
})
addSubview(AKPropertySlider(
property: "Ramp Time",
format: "%0.3f s",
value: oscillator.rampTime, maximum: 1,
color: AKColor.orangeColor()
) { time in
currentRampTime = time
})
let keyboard = AKKeyboardView(width: playgroundWidth - 60,
height: 100, firstOctave: 3, octaveCount: 3)
keyboard.delegate = self
addSubview(keyboard)
}
func noteOn(note: MIDINoteNumber) {
currentMIDINote = note
// start from the correct note if amplitude is zero
if oscillator.amplitude == 0 {
oscillator.rampTime = 0
}
oscillator.frequency = note.midiNoteToFrequency()
// Still use rampTime for volume
oscillator.rampTime = currentRampTime
oscillator.amplitude = currentAmplitude
oscillator.play()
}
func noteOff(note: MIDINoteNumber) {
if currentMIDINote == note {
oscillator.amplitude = 0
}
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
| mit | 4c4d3e7876a3f083272ed253897e724c | 25.75 | 76 | 0.621495 | 5.028721 | false | false | false | false |
onekiloparsec/SwiftVOTable | SwiftVOTable/VOTableUtils.swift | 1 | 2243 | //
// VOTableUtils.swift
// SwiftVOTable
//
// Created by Cédric Foellmi on 08/06/15.
// Copyright (c) 2015 onekiloparsec. All rights reserved.
//
import Foundation
extension NSObject {
// Borrowed from https://www.weheartswift.com/swift-objc-magic/
func propertyNamesOfClass(cls: AnyClass) -> [String] {
var names: [String] = []
var count: UInt32 = 0
// Uses the Objc Runtime to get the property list
var properties = class_copyPropertyList(cls, &count)
for var i = 0; i < Int(count); ++i {
let property: objc_property_t = properties[i]
let name: String = NSString(CString: property_getName(property), encoding: NSUTF8StringEncoding) as! String
names.append(name)
}
free(properties)
return names
}
}
extension VOTableElement {
func propertyNames() -> [String] {
var names: [String] = []
names += self.propertyNamesOfClass(self.dynamicType)
if !self.isMemberOfClass(VOTableElement) {
names += self.propertyNamesOfClass(self.superclass!)
}
return names
}
func filteredPropertyNames() -> [String] {
var names = self.propertyNames()
return names.filter({ $0 != "content" && $0 != "parentElement" })
}
func hasProperty(name: String) -> Bool! {
return Set(self.propertyNames()).contains(name)
}
func isPropertyAnArray(name: String) -> Bool! {
return self.valueForKey(name) as AnyObject! is Array<AnyObject>
}
}
extension String {
var length: Int {
return Int(count(self))
}
func plural() -> String {
let index: String.Index = advance(self.startIndex, self.length-1)
if self.length == 0 || self.substringFromIndex(index) == "s" {
return self;
}
return self + "s"
}
}
// See http://www.juliusparishy.com/articles/2014/12/14/adopting-map-reduce-in-swift
func join<T : Equatable>(objs: [T], separator: String) -> String {
return objs.reduce("") {
sum, obj in
let maybeSeparator = (obj == objs.last) ? "" : separator
return "\(sum)\(obj)\(maybeSeparator)"
}
}
| mit | 9f6c8a606265df110cc18a189a7352c8 | 27.025 | 119 | 0.592328 | 3.892361 | false | false | false | false |
devyu/Stroe | JYStore/DetailViewController.swift | 1 | 945 | //
// DetailViewController.swift
// JYStore
//
// Created by mac on 12/7/15.
// Copyright © 2015 JY. All rights reserved.
//
import Cocoa
class DetailViewController: NSViewController {
@IBOutlet weak var productImageView: NSImageView!
@IBOutlet weak var titleLabel: NSTextField!
@IBOutlet weak var descriptionLabel: NSTextField!
@IBOutlet weak var audienceLabel: NSTextField!
var selectedProduct: Product? {
didSet {
updateUI()
}
}
override func viewWillAppear() {
updateUI()
}
private func updateUI() {
if viewLoaded {
if let product = selectedProduct {
productImageView.image = product.image
titleLabel.stringValue = product.title
descriptionLabel.stringValue = product.descriptionText
audienceLabel.stringValue = product.audience
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
}
| mit | b930f82eb9f981b197fb2f07634b0d0b | 20.454545 | 62 | 0.670551 | 4.696517 | false | false | false | false |
DuckDeck/GrandMenu | Sources/GrandMenu.swift | 1 | 16162 | //
// GrandMenu.swift
// GrandMenuDemo
//
// Created by Tyrant on 1/15/16.
// Copyright © 2016 Qfq. All rights reserved.
//
import UIKit
open class GrandMenu: UIView,GraneMenuItemDelegate {
open var arrItemsTitle:[String]?{
didSet{
setupItems()
}
}
open var sliderBarLeftRightOffset = 15{
didSet{
setupItems()
}
}
open var itemLeftRightOffset:Float = 10{
didSet{
setupItems()
}
}
open var sliderBarHeight = 2
open var sliderColor = UIColor.red{
didSet{
vSlider?.backgroundColor = sliderColor
}
}
var allItemWidth:Float = 0
open var averageManu:Bool = true //当Menu过多时,设置无效
open var defaultSelectedIndex:Int = 0{
didSet{
if defaultSelectedIndex < arrItemsTitle!.count{
setupItems()
}
}
}
open var itemColor:UIColor = UIColor.black{
didSet{
if let items = arrItems{
for item in items{
item.color = itemColor
}
}
}
}
open var itemSeletedColor:UIColor = UIColor.red{
didSet{
if let items = arrItems{
for item in items{
item.selectedColor = itemSeletedColor
}
}
}
}
open var itemFont:Float?{
didSet{
if itemFont == nil{
return
}
if let items = arrItems{
for item in items{
item.Font = UIFont.systemFont(ofSize: CGFloat(itemFont!))
}
}
}
}
open var itemUIFont:UIFont?{
didSet{
if itemUIFont == nil{
return
}
if let items = arrItems{
for item in items{
item.Font = itemUIFont!
}
}
}
}
open var itemSelectedFont:Float?{
didSet{
if itemSelectedFont == nil{
return
}
if let items = arrItems{
for item in items{
item.selectedFont = UIFont.systemFont(ofSize: CGFloat(itemSelectedFont!))
}
}
}
}
open var itemSelectedUIFont:UIFont?{
didSet{
if itemSelectedUIFont == nil{
return
}
if let items = arrItems{
for item in items{
item.selectedFont = itemSelectedUIFont!
}
}
}
}
open var selectMenu:((_ item:GrandMenuItem, _ index:Int)->())?
fileprivate var selectedItemIndex:Int = 0
fileprivate var scrollView:UIScrollView?
fileprivate var arrItems:[GrandMenuItem]?
fileprivate var vSlider:UIView?
fileprivate var vBottomLine:UIView?
fileprivate var selectedItem:GrandMenuItem?{
willSet{
selectedItem?.selected = false //这个警告可以无视
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
fileprivate override init(frame: CGRect) {
super.init(frame: frame)
arrItems = [GrandMenuItem]()
scrollView = UIScrollView(frame: bounds)
scrollView!.backgroundColor = UIColor.clear
scrollView!.showsHorizontalScrollIndicator = false
scrollView!.showsVerticalScrollIndicator = false
scrollView!.bounces = false
addSubview(scrollView!)
vSlider = UIView()
vSlider?.backgroundColor = sliderColor
scrollView!.addSubview(vSlider!)
}
public convenience init(frame: CGRect,titles:[String]){
self.init(frame:frame)
if let window = UIApplication.shared.keyWindow
{
if var viewController = window.rootViewController{
while viewController.presentedViewController != nil{
viewController = viewController.presentedViewController!
}
while viewController.isKind(of: UINavigationController.self) && (viewController as! UINavigationController).topViewController != nil{
viewController = (viewController as! UINavigationController).topViewController!
}
viewController.automaticallyAdjustsScrollViewInsets = false
}
}
arrItemsTitle = titles
setupItems()
}
open func addBottomLine(_ bgColor:UIColor,size:CGSize){
vBottomLine = UIView(frame: CGRect(x: (frame.size.width - size.width) / 2, y: frame.size.height, width: size.width, height: size.height))
vBottomLine?.backgroundColor = bgColor
addSubview(vBottomLine!)
frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: vBottomLine!.frame.maxY)
}
func setupItems(){
weak var weakSelf = self
for view in scrollView!.subviews{
if view is GrandMenuItem{
view.removeFromSuperview()
}
}
arrItems?.removeAll(keepingCapacity: true)
var x:Float = 0
var maxItemWidth:Float = 0.0
allItemWidth = 0
for title in arrItemsTitle! {
let item = GrandMenuItem()
item.selectedColor = itemSeletedColor
item.color = itemColor
if let f = itemFont{
item.Font = UIFont.systemFont(ofSize: CGFloat(f))
}
if let f = itemUIFont{
item.Font = f
}
if let sf = itemSelectedFont{
item.selectedFont = UIFont.systemFont(ofSize: CGFloat(sf))
}
if let sf = itemSelectedUIFont{
item.selectedFont = sf
}
item.delegate = weakSelf
var itemWidth = GrandMenuItem.getTitleWidth(title, fontSize: Float(item.Font.pointSize), leftrightOffset: itemLeftRightOffset)
if itemWidth > maxItemWidth{
maxItemWidth = itemWidth
}
if averageManu{
if maxItemWidth * Float(arrItemsTitle!.count) > Float(frame.size.width){
itemWidth = maxItemWidth
}
else{
itemWidth = Float(frame.size.width / CGFloat(arrItemsTitle!.count))
}
}
allItemWidth = allItemWidth + itemWidth
item.frame = CGRect(x: CGFloat(x), y: CGFloat(0), width: CGFloat(itemWidth), height: scrollView!.frame.height)
item.title = title
arrItems!.append(item)
scrollView?.addSubview(item)
x = Float(item.frame.maxX)
}
scrollView?.contentSize = CGSize(width: CGFloat(x), height: scrollView!.frame.height)
let defaultItem = arrItems![defaultSelectedIndex]
selectedItemIndex = defaultSelectedIndex
defaultItem.selected = true
selectedItem = defaultItem
vSlider?.frame = CGRect(x: defaultItem.frame.origin.x + CGFloat(sliderBarLeftRightOffset), y: frame.size.height - CGFloat(sliderBarHeight), width: defaultItem.frame.size.width - CGFloat(sliderBarLeftRightOffset * 2), height: CGFloat(sliderBarHeight))
}
func scrollToVisibleItem(_ item:GrandMenuItem){
weak var weakSelf = self
let selectedItemIndex = arrItems!.find({(s:GrandMenuItem) ->Bool in return s.title! == weakSelf?.selectedItem!.title!}).1
let visibleItemIndex = arrItems!.find({(s:GrandMenuItem) ->Bool in return s.title! == item.title!}).1
if selectedItemIndex == visibleItemIndex{
return
}
var offset = scrollView!.contentOffset
if item.frame.midX > offset.x && item.frame.maxX < (offset.x + scrollView!.frame.width){
return
}
if selectedItemIndex < visibleItemIndex{
if selectedItem!.frame.maxX < offset.x{
offset.x = item.frame.minX
}
else{
offset.x = item.frame.maxX - scrollView!.frame.width
}
}
else{
if selectedItem!.frame.minX > offset.x + scrollView!.frame.width{
offset.x = item.frame.maxX - scrollView!.frame.width
}
else{
offset.x = item.frame.minX
}
}
scrollView?.contentOffset = offset
}
func addAnimationWithSelectedItem(_ item:GrandMenuItem,withAnimation:Bool = true)
{
// let dx = item.frame.midX - selectedItem!.frame.midX
let dx = item.frame.midX - vSlider!.frame.size.width / 2
// let positionAnimation = CABasicAnimation()
// positionAnimation.keyPath = "position.x"
// positionAnimation.fromValue = vSlider?.layer.position.x
// positionAnimation.toValue = vSlider!.layer.position.x + dx
// let boundsAnimation = CABasicAnimation()
// boundsAnimation.keyPath = "bounds.size.width"
// boundsAnimation.fromValue = CGRectGetWidth(vSlider!.layer.bounds)
// boundsAnimation.toValue = CGRectGetWidth(item.frame)
//这个是不必要的动画
// let animationGroup = CAAnimationGroup()
// animationGroup.animations = [positionAnimation]
// animationGroup.duration = 0.2
// vSlider?.layer.addAnimation(animationGroup, forKey: "basic")
//
// vSlider?.layer.position = CGPoint(x: vSlider!.layer.position.x + dx, y: vSlider!.layer.position.y)
// var rect = vSlider!.layer.bounds
// rect.size.width = CGRectGetWidth(item.frame) - CGFloat(sliderBarLeftRightOffset * 2)
// vSlider?.layer.bounds = rect
//这个动画有个小Bug,目前不知道怎么修正,它会先把滑块移动到目的地再消失,再执行动画,所以只好用下面的方法了,这种情况有30%的可能性发生
//不用这种动画试试
if withAnimation{
weak var weakSelf = self
UIView.animate(withDuration: 0.2, animations: { () -> Void in
weakSelf?.vSlider?.frame = CGRect(x: dx, y:weakSelf!.vSlider!.frame.origin.y, width: weakSelf!.vSlider!.frame.size.width, height: weakSelf!.vSlider!.frame.size.height)
})
}
else{
vSlider?.frame = CGRect(x: dx, y: vSlider!.frame.origin.y, width: vSlider!.frame.size.width, height: vSlider!.frame.size.height)
}
}
open func adjustScrollOffset(){
let x = selectedItem!.frame.origin.x
let right = x + selectedItem!.frame.size.width
if right <= 0.5 * scrollView!.frame.width {
scrollView?.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
}
else if right > scrollView!.contentSize.width - 0.5 * scrollView!.frame.width{
if CGFloat(allItemWidth) < scrollView!.frame.width{
return
}
scrollView?.setContentOffset(CGPoint(x: scrollView!.contentSize.width - scrollView!.frame.width, y: 0), animated: true)
}
else{
let of = x - 0.5 * scrollView!.frame.width + selectedItem!.frame.size.width * 0.5
if of > 0{
scrollView?.setContentOffset(CGPoint(x: of, y: 0), animated: true)
}
}
}
func GraneMenuItemSelected(_ item: GrandMenuItem) {
if item == selectedItem!{
addAnimationWithSelectedItem(item)
return
}
addAnimationWithSelectedItem(item)
selectedItem = item
//调整到合适的位置
adjustScrollOffset()
if let call = selectMenu{
let item = arrItems!.find({(s:GrandMenuItem) ->Bool in return s.selected == item.selected })
call(item.0!, item.1)
}
}
open func selectSlideBarItemAtIndex(_ index:Int,withAnimation:Bool = true){
let item = arrItems![index]
if item == selectedItem!{
addAnimationWithSelectedItem(item)
return
}
item.selected = true
scrollToVisibleItem(item)
addAnimationWithSelectedItem(item, withAnimation: withAnimation)
selectedItem = item
//it will check
if let call = selectMenu{
let item = arrItems!.find({(s:GrandMenuItem) ->Bool in return s.selected == item.selected })
call(item.0!, item.1)
}
}
open func setSlidertBar(x:Float) {
if x < 0{
// if vSlider!.frame.origin.x + vSlider!.frame.size.width < self.frame.size.width{
vSlider!.frame = CGRect(x: vSlider!.frame.origin.x - CGFloat(x), y: vSlider!.frame.origin.y, width: vSlider!.frame.size.width, height: vSlider!.frame.size.height)
// }
}
else{
// if vSlider!.frame.origin.x > 0{
vSlider!.frame = CGRect(x: vSlider!.frame.origin.x - CGFloat(x), y: vSlider!.frame.origin.y, width: vSlider!.frame.size.width, height: vSlider!.frame.size.height)
// }
}
}
open func adjustSlider() {
let center = vSlider!.frame.origin.x + vSlider!.frame.size.width / 2
if center < -10 {
selectSlideBarItemAtIndex(arrItems!.count - 1, withAnimation: false)
return
}
if center > arrItems!.last!.frame.origin.x + arrItems!.last!.frame.size.width + 10{
selectSlideBarItemAtIndex(0,withAnimation: false)
return
}
var index = 0
for i in 0..<arrItems!.count {
if center > arrItems![i].frame.origin.x && center <= arrItems![i].frame.origin.x + arrItems![i].frame.size.width{
index = i
break
}
}
selectSlideBarItemAtIndex(index)
}
}
extension Array{
func find(_ method:(Element)->Bool)->(Element?,Int){
var index = 0
for item in self{
if method(item){
return (item,index)
}
index += 1
}
return (nil,-1)
}
mutating func remove(_ method:(Element)->Bool)->(Element?,Bool){
let result = find(method)
if result.1 >= 0{
return (self.remove(at: result.1),true)
}
return (nil,false)
}
func compareFirstObject(_ arrTarget:Array, method:(Element,Element)->Bool)->Bool{
if count == 0 || arrTarget.count == 0
{
return false
}
let firstItem = first!
let targetFirstItem = arrTarget.first!
if method(firstItem,targetFirstItem)
{
return true
}
return false
}
func compareLastObject(_ arrTarget:Array, method:(Element,Element)->Bool)->Bool{
if count == 0 || arrTarget.count == 0
{
return false
}
let firstItem = last!
let targetFirstItem = arrTarget.last!
if method(firstItem,targetFirstItem)
{
return true
}
return false
}
mutating func exchangeObjectAdIndex(_ IndexA:Int,atIndexB:Int)
{
if IndexA >= count || IndexA < 0{
return
}
if atIndexB >= count || atIndexB < 0{
return
}
let objA = self[IndexA]
let objB = self[atIndexB]
replaceObject(objA, atIndex: atIndexB)
replaceObject(objB, atIndex: IndexA)
}
mutating func replaceObject(_ obj:Element,atIndex:Int){
if atIndex >= count || atIndex < 0{
return
}
self.remove(at: atIndex)
insert(obj, at: atIndex)
}
mutating func merge(_ newArray:Array){
for obj in newArray
{
append(obj)
}
}
}
| mit | 93794cb572ac1d3194fccbcc4fe85ae2 | 33.329032 | 258 | 0.550273 | 4.632327 | false | false | false | false |
spark/photon-tinker-ios | Photon-Tinker/DeviceInspectorEventsViewController.swift | 1 | 9631 | //
// DeviceInspectorEventsViewController.swift
// Particle
//
// Copyright (c) 2019 Particle. All rights reserved.
//
class DeviceInspectorEventsViewController: DeviceInspectorChildViewController, SearchBarViewDelegate, UITableViewDelegate, UITableViewDataSource, DeviceEventTableViewCellDelegate {
@IBOutlet weak var searchBar: SearchBarView!
@IBOutlet weak var clearEventsButton: UIButton!
@IBOutlet weak var playPauseButton: UIButton!
@IBOutlet var noEventsView: UIView!
var events: [ParticleEvent] = []
var filteredEvents: [ParticleEvent] = []
var filterText: String = ""
var subscribeId: Any?
var paused: Bool = false
var filtering: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
UIBarButtonItem.appearance(whenContainedInInstancesOf:[UISearchBar.self]).tintColor = ParticleStyle.ButtonColor
self.clearEventsButton.tintColor = ParticleStyle.ButtonColor
self.playPauseButton.tintColor = ParticleStyle.ButtonColor
self.noEventsView.removeFromSuperview()
addRefreshControl()
setupSearch()
}
override func viewWillAppear(_ animated: Bool) {
subscribeToDeviceEvents()
}
override func viewWillDisappear(_ animated: Bool) {
unsubscribeFromDeviceEvents()
}
private func setupSearch() {
searchBar.inputText.placeholder = TinkerStrings.Events.SearchPlaceholder
searchBar.delegate = self
}
//MARK: Search bar delegate
func searchBarTextDidChange(searchBar: SearchBarView, text: String?) {
if let text = text, text.count > 0 {
self.filtering = true
self.filterText = text
self.filterEvents()
SEGAnalytics.shared().track("DeviceInspector_EventFilterTyping")
} else {
self.filtering = false
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
func searchBarDidBeginEditing(searchBar: SearchBarView) {
}
func searchBarDidEndEditing(searchBar: SearchBarView) {
}
override func update() {
super.update()
self.tableView.reloadData()
self.tableView.isUserInteractionEnabled = true
self.refreshControl.endRefreshing()
self.evalNoEventsViewVisibility()
}
func subscribeToDeviceEvents() {
self.subscribeId = ParticleCloud.sharedInstance().subscribeToDeviceEvents(withPrefix: nil, deviceID: self.device.id, handler: {[weak self] (event:ParticleEvent?, error:Error?) in
if let _ = error {
print ("could not subscribe to events to show in events inspector...")
} else {
DispatchQueue.main.async(execute: {
if let self = self {
if let e = event {
// insert new event to datasource
self.events.insert(e, at: 0)
if self.filtering {
self.filterEvents()
self.tableView.reloadData()
} else {
if !self.view.isHidden {
self.tableView.beginUpdates()
self.tableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .top)
self.tableView.endUpdates()
} else {
self.tableView.reloadData()
}
}
self.evalNoEventsViewVisibility()
}
}
})
}
})
}
func unsubscribeFromDeviceEvents() {
if let sid = self.subscribeId {
ParticleCloud.sharedInstance().unsubscribeFromEvent(withID: sid)
}
}
override func showTutorial() {
if ParticleUtils.shouldDisplayTutorialForViewController(self) {
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
//3
var tutorial3 = YCTutorialBox(headline: TinkerStrings.Events.Tutorial.Tutorial3.Title, withHelpText: TinkerStrings.Events.Tutorial.Tutorial3.Message)
//2
var tutorial2 = YCTutorialBox(headline: TinkerStrings.Events.Tutorial.Tutorial2.Title, withHelpText: TinkerStrings.Events.Tutorial.Tutorial2.Message) {
tutorial3?.showAndFocus(self.searchBar.superview)
}
// 1
var tutorial = YCTutorialBox(headline: TinkerStrings.Events.Tutorial.Tutorial1.Title, withHelpText: TinkerStrings.Events.Tutorial.Tutorial1.Message) {
tutorial2?.showAndFocus(self.searchBar)
}
tutorial?.showAndFocus(self.view)
ParticleUtils.setTutorialWasDisplayedForViewController(self)
}
}
}
func filterEvents() {
if self.filtering {
self.filteredEvents = self.events.filter({$0.event.lowercased().contains(self.filterText) || $0.data!.lowercased().contains(self.filterText)}) // filter for both name and data
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if filtering {
return self.filteredEvents.count
} else {
return self.events.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: DeviceEventTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "eventCell") as! DeviceEventTableViewCell
if filtering {
cell.setup(self.filteredEvents[(indexPath as NSIndexPath).row])
} else {
cell.setup(self.events[(indexPath as NSIndexPath).row])
}
cell.delegate = self
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 105.0
}
@IBAction func playPauseButtonTapped(_ sender: AnyObject) {
if paused {
paused = false
SEGAnalytics.shared().track("DeviceInspector_EventStreamPlay")
playPauseButton.setImage(UIImage(named: "IconPause"), for: .normal)
subscribeToDeviceEvents()
} else {
paused = true
SEGAnalytics.shared().track("DeviceInspector_EventStreamPause")
playPauseButton.setImage(UIImage(named: "IconPlay"), for: .normal)
unsubscribeFromDeviceEvents()
}
}
@IBAction func clearButtonTapped(_ sender: AnyObject) {
let alert = UIAlertController(title: TinkerStrings.Events.Prompt.ClearAllEvents.Title, message: TinkerStrings.Events.Prompt.ClearAllEvents.Message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: TinkerStrings.Action.Yes, style: .default) { [weak self] action in
if let self = self {
self.events = []
self.filteredEvents = []
self.tableView.reloadData()
self.evalNoEventsViewVisibility()
}
SEGAnalytics.shared().track("DeviceInspector_EventsCleared")
})
alert.addAction(UIAlertAction(title: TinkerStrings.Action.No, style: .cancel) { action in
})
self.present(alert, animated: true)
}
func evalNoEventsViewVisibility() {
self.tableView.tableHeaderView = nil
self.noEventsView.removeFromSuperview()
self.tableView.tableHeaderView = (self.events.count > 0) ? nil : self.noEventsView
self.adjustTableViewHeaderViewConstraints()
}
func tappedOnCopyButton(_ sender: DeviceEventTableViewCell, event: ParticleEvent) {
UIPasteboard.general.string = event.description
RMessage.showNotification(withTitle: TinkerStrings.Events.Prompt.EventCopied.Title, subtitle: TinkerStrings.Events.Prompt.EventCopied.Message, type: .success, customTypeName: nil, callback: nil)
SEGAnalytics.shared().track("DeviceInspector_EventCopied")
}
func tappedOnPayloadButton(_ sender: DeviceEventTableViewCell, event: ParticleEvent) {
let alert = UIAlertController(title: event.event, message: "\(event.data ?? "")\r\n\r\n\(event.time.eventTimeFormattedString())", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: TinkerStrings.Action.CopyDataToClipboard, style: .default) { [weak self] action in
UIPasteboard.general.string = event.data ?? ""
RMessage.showNotification(withTitle: TinkerStrings.Events.Prompt.DataCopied.Title, subtitle: TinkerStrings.Events.Prompt.DataCopied.Message, type: .success, customTypeName: nil, callback: nil)
SEGAnalytics.shared().track("DeviceInspector_EventDataCopied")
})
alert.addAction(UIAlertAction(title: TinkerStrings.Action.CopyEventToClipboard, style: .default) { [weak self] action in
UIPasteboard.general.string = event.description
RMessage.showNotification(withTitle: TinkerStrings.Events.Prompt.EventCopied.Title, subtitle: TinkerStrings.Events.Prompt.EventCopied.Message, type: .success, customTypeName: nil, callback: nil)
SEGAnalytics.shared().track("DeviceInspector_EventPayloadCopied")
})
alert.addAction(UIAlertAction(title: TinkerStrings.Action.Close, style: .cancel) { action in
})
self.present(alert, animated: true)
}
}
| apache-2.0 | b7f88af3e3c2065f16e184d34ea49c27 | 37.524 | 206 | 0.627557 | 5.177957 | false | false | false | false |
jekahy/Adoreavatars | Adoravatars/AvatarsVM.swift | 1 | 1295 | //
// AvatarsVM.swift
// Adoravatars
//
// Created by Eugene on 25.06.17.
// Copyright © 2017 Eugene. All rights reserved.
//
import RxSwift
import RxCocoa
protocol AvatarsVMType {
var avatars:Driver<[Avatar]> {get}
var title:Driver<String>{get}
var api:APIDownloadable{get}
var service:AvatarsGettable{get}
var downloadsVM:DownloadsVMType{get}
func avatarVM(for avatar:Avatar)->AvatarVM
}
class AvatarsVM:AvatarsVMType {
let avatars:Driver<[Avatar]>
let title: Driver<String>
let api:APIDownloadable
let service:AvatarsGettable
let downloadsVM: DownloadsVMType
init(service:AvatarsGettable = AvatarService(), api:APIDownloadable = APIService(baseURL: APIBaseURLs.avatar)){
avatars = service.getAvatars().asDriver(onErrorJustReturn:[])
title = Observable.just("Adoreavatars").asDriver(onErrorJustReturn: "")
downloadsVM = DownloadsVM(api: api)
self.api = api
self.service = service
}
func avatarVM(for avatar:Avatar)->AvatarVM
{
return AvatarVM(avatar, service: service, api: api)
}
}
extension AvatarsVM:Equatable{
static func ==(lhs: AvatarsVM, rhs: AvatarsVM) -> Bool
{
return lhs.api === rhs.api
}
}
| mit | 4808f894c79e7cf4183d2f59eaee959d | 22.527273 | 115 | 0.658423 | 3.909366 | false | false | false | false |
coach-plus/ios | Pods/RxSwift/RxSwift/Rx.swift | 6 | 6252 | //
// Rx.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if TRACE_RESOURCES
private let resourceCount = AtomicInt(0)
/// Resource utilization information
public struct Resources {
/// Counts internal Rx resource allocations (Observables, Observers, Disposables, etc.). This provides a simple way to detect leaks during development.
public static var total: Int32 {
return load(resourceCount)
}
/// Increments `Resources.total` resource count.
///
/// - returns: New resource count
public static func incrementTotal() -> Int32 {
return increment(resourceCount)
}
/// Decrements `Resources.total` resource count
///
/// - returns: New resource count
public static func decrementTotal() -> Int32 {
return decrement(resourceCount)
}
}
#endif
/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass.
func rxAbstractMethod(file: StaticString = #file, line: UInt = #line) -> Swift.Never {
rxFatalError("Abstract method", file: file, line: line)
}
func rxFatalError(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> Swift.Never {
fatalError(lastMessage(), file: file, line: line)
}
func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) {
#if DEBUG
fatalError(lastMessage(), file: file, line: line)
#else
print("\(file):\(line): \(lastMessage())")
#endif
}
func incrementChecked(_ i: inout Int) throws -> Int {
if i == Int.max {
throw RxError.overflow
}
defer { i += 1 }
return i
}
func decrementChecked(_ i: inout Int) throws -> Int {
if i == Int.min {
throw RxError.overflow
}
defer { i -= 1 }
return i
}
#if DEBUG
import class Foundation.Thread
final class SynchronizationTracker {
private let _lock = RecursiveLock()
public enum SynchronizationErrorMessages: String {
case variable = "Two different threads are trying to assign the same `Variable.value` unsynchronized.\n This is undefined behavior because the end result (variable value) is nondeterministic and depends on the \n operating system thread scheduler. This will cause random behavior of your program.\n"
case `default` = "Two different unsynchronized threads are trying to send some event simultaneously.\n This is undefined behavior because the ordering of the effects caused by these events is nondeterministic and depends on the \n operating system thread scheduler. This will result in a random behavior of your program.\n"
}
private var _threads = [UnsafeMutableRawPointer: Int]()
private func synchronizationError(_ message: String) {
#if FATAL_SYNCHRONIZATION
rxFatalError(message)
#else
print(message)
#endif
}
func register(synchronizationErrorMessage: SynchronizationErrorMessages) {
self._lock.lock(); defer { self._lock.unlock() }
let pointer = Unmanaged.passUnretained(Thread.current).toOpaque()
let count = (self._threads[pointer] ?? 0) + 1
if count > 1 {
self.synchronizationError(
"⚠️ Reentrancy anomaly was detected.\n" +
" > Debugging: To debug this issue you can set a breakpoint in \(#file):\(#line) and observe the call stack.\n" +
" > Problem: This behavior is breaking the observable sequence grammar. `next (error | completed)?`\n" +
" This behavior breaks the grammar because there is overlapping between sequence events.\n" +
" Observable sequence is trying to send an event before sending of previous event has finished.\n" +
" > Interpretation: This could mean that there is some kind of unexpected cyclic dependency in your code,\n" +
" or that the system is not behaving in the expected way.\n" +
" > Remedy: If this is the expected behavior this message can be suppressed by adding `.observeOn(MainScheduler.asyncInstance)`\n" +
" or by enqueuing sequence events in some other way.\n"
)
}
self._threads[pointer] = count
if self._threads.count > 1 {
self.synchronizationError(
"⚠️ Synchronization anomaly was detected.\n" +
" > Debugging: To debug this issue you can set a breakpoint in \(#file):\(#line) and observe the call stack.\n" +
" > Problem: This behavior is breaking the observable sequence grammar. `next (error | completed)?`\n" +
" This behavior breaks the grammar because there is overlapping between sequence events.\n" +
" Observable sequence is trying to send an event before sending of previous event has finished.\n" +
" > Interpretation: " + synchronizationErrorMessage.rawValue +
" > Remedy: If this is the expected behavior this message can be suppressed by adding `.observeOn(MainScheduler.asyncInstance)`\n" +
" or by synchronizing sequence events in some other way.\n"
)
}
}
func unregister() {
self._lock.lock(); defer { self._lock.unlock() }
let pointer = Unmanaged.passUnretained(Thread.current).toOpaque()
self._threads[pointer] = (self._threads[pointer] ?? 1) - 1
if self._threads[pointer] == 0 {
self._threads[pointer] = nil
}
}
}
#endif
/// RxSwift global hooks
public enum Hooks {
// Should capture call stack
public static var recordCallStackOnError: Bool = false
}
| mit | 427ed01631017c6953c7beab8ecf3adf | 43.276596 | 341 | 0.61637 | 4.86215 | false | false | false | false |
coach-plus/ios | Pods/RxSwift/RxSwift/Observables/RetryWhen.swift | 6 | 8079 | //
// RetryWhen.swift
// RxSwift
//
// Created by Junior B. on 06/10/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
public func retryWhen<TriggerObservable: ObservableType, Error: Swift.Error>(_ notificationHandler: @escaping (Observable<Error>) -> TriggerObservable)
-> Observable<Element> {
return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler)
}
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
public func retryWhen<TriggerObservable: ObservableType>(_ notificationHandler: @escaping (Observable<Swift.Error>) -> TriggerObservable)
-> Observable<Element> {
return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler)
}
}
final private class RetryTriggerSink<Sequence: Swift.Sequence, Observer: ObserverType, TriggerObservable: ObservableType, Error>
: ObserverType where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element {
typealias Element = TriggerObservable.Element
typealias Parent = RetryWhenSequenceSinkIter<Sequence, Observer, TriggerObservable, Error>
private let _parent: Parent
init(parent: Parent) {
self._parent = parent
}
func on(_ event: Event<Element>) {
switch event {
case .next:
self._parent._parent._lastError = nil
self._parent._parent.schedule(.moveNext)
case .error(let e):
self._parent._parent.forwardOn(.error(e))
self._parent._parent.dispose()
case .completed:
self._parent._parent.forwardOn(.completed)
self._parent._parent.dispose()
}
}
}
final private class RetryWhenSequenceSinkIter<Sequence: Swift.Sequence, Observer: ObserverType, TriggerObservable: ObservableType, Error>
: ObserverType
, Disposable where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element {
typealias Element = Observer.Element
typealias Parent = RetryWhenSequenceSink<Sequence, Observer, TriggerObservable, Error>
fileprivate let _parent: Parent
private let _errorHandlerSubscription = SingleAssignmentDisposable()
private let _subscription: Disposable
init(parent: Parent, subscription: Disposable) {
self._parent = parent
self._subscription = subscription
}
func on(_ event: Event<Element>) {
switch event {
case .next:
self._parent.forwardOn(event)
case .error(let error):
self._parent._lastError = error
if let failedWith = error as? Error {
// dispose current subscription
self._subscription.dispose()
let errorHandlerSubscription = self._parent._notifier.subscribe(RetryTriggerSink(parent: self))
self._errorHandlerSubscription.setDisposable(errorHandlerSubscription)
self._parent._errorSubject.on(.next(failedWith))
}
else {
self._parent.forwardOn(.error(error))
self._parent.dispose()
}
case .completed:
self._parent.forwardOn(event)
self._parent.dispose()
}
}
final func dispose() {
self._subscription.dispose()
self._errorHandlerSubscription.dispose()
}
}
final private class RetryWhenSequenceSink<Sequence: Swift.Sequence, Observer: ObserverType, TriggerObservable: ObservableType, Error>
: TailRecursiveSink<Sequence, Observer> where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element {
typealias Element = Observer.Element
typealias Parent = RetryWhenSequence<Sequence, TriggerObservable, Error>
let _lock = RecursiveLock()
private let _parent: Parent
fileprivate var _lastError: Swift.Error?
fileprivate let _errorSubject = PublishSubject<Error>()
private let _handler: Observable<TriggerObservable.Element>
fileprivate let _notifier = PublishSubject<TriggerObservable.Element>()
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self._parent = parent
self._handler = parent._notificationHandler(self._errorSubject).asObservable()
super.init(observer: observer, cancel: cancel)
}
override func done() {
if let lastError = self._lastError {
self.forwardOn(.error(lastError))
self._lastError = nil
}
else {
self.forwardOn(.completed)
}
self.dispose()
}
override func extract(_ observable: Observable<Element>) -> SequenceGenerator? {
// It is important to always return `nil` here because there are sideffects in the `run` method
// that are dependant on particular `retryWhen` operator so single operator stack can't be reused in this
// case.
return nil
}
override func subscribeToNext(_ source: Observable<Element>) -> Disposable {
let subscription = SingleAssignmentDisposable()
let iter = RetryWhenSequenceSinkIter(parent: self, subscription: subscription)
subscription.setDisposable(source.subscribe(iter))
return iter
}
override func run(_ sources: SequenceGenerator) -> Disposable {
let triggerSubscription = self._handler.subscribe(self._notifier.asObserver())
let superSubscription = super.run(sources)
return Disposables.create(superSubscription, triggerSubscription)
}
}
final private class RetryWhenSequence<Sequence: Swift.Sequence, TriggerObservable: ObservableType, Error>: Producer<Sequence.Element.Element> where Sequence.Element: ObservableType {
typealias Element = Sequence.Element.Element
private let _sources: Sequence
fileprivate let _notificationHandler: (Observable<Error>) -> TriggerObservable
init(sources: Sequence, notificationHandler: @escaping (Observable<Error>) -> TriggerObservable) {
self._sources = sources
self._notificationHandler = notificationHandler
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = RetryWhenSequenceSink<Sequence, Observer, TriggerObservable, Error>(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run((self._sources.makeIterator(), nil))
return (sink: sink, subscription: subscription)
}
}
| mit | a5ee614966d89ee2687e9ea94b4e6625 | 43.384615 | 254 | 0.699678 | 5.174888 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothGATT/GATTObjectSize.swift | 1 | 2056 | //
// GATTObjectSize.swift
// Bluetooth
//
// Created by Carlos Duclos on 7/11/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/**
Object Size
- SeeAlso: [Object Size](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.object_size.xml)
*/
@frozen
public struct GATTObjectSize: GATTCharacteristic, Equatable {
internal static let length = MemoryLayout<UInt32>.size * 2
public static var uuid: BluetoothUUID { return .objectSize }
public var currentSize: Size
public var allocatedSize: Size
public init(currentSize: Size, allocatedSize: Size) {
self.currentSize = currentSize
self.allocatedSize = allocatedSize
}
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
let currentSize = Size(rawValue: UInt32(littleEndian: UInt32(bytes: (data[0], data[1], data[2], data[3]))))
let allocatedSize = Size(rawValue: UInt32(littleEndian: UInt32(bytes: (data[4], data[5], data[6], data[7]))))
self.init(currentSize: currentSize, allocatedSize: allocatedSize)
}
public var data: Data {
let currentSizeBytes = currentSize.rawValue.littleEndian.bytes
let allocatedSizeBytes = allocatedSize.rawValue.littleEndian.bytes
return Data([currentSizeBytes.0,
currentSizeBytes.1,
currentSizeBytes.2,
currentSizeBytes.3,
allocatedSizeBytes.0,
allocatedSizeBytes.1,
allocatedSizeBytes.2,
allocatedSizeBytes.3
])
}
}
extension GATTObjectSize {
public struct Size: RawRepresentable, Equatable, Hashable {
public var rawValue: UInt32
public init(rawValue: UInt32) {
self.rawValue = rawValue
}
}
}
| mit | 8048694c1f7497be18cc1812156856be | 27.150685 | 141 | 0.599027 | 4.681093 | false | false | false | false |
nodekit-io/nodekit-windows | src/nodekit/NKElectro/common/NKEMenu/NKEMenu-ios.swift | 1 | 2271 | /*
* nodekit.io
*
* Copyright (c) 2016 OffGrid Networks. All Rights Reserved.
* Portions Copyright (c) 2013 GitHub, Inc. under MIT License
*
* 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 UIKit
// NKElectro MENU Placeholder code only: on roadmap but lower priority as not supported on mobile
extension NKE_Menu: NKScriptExport {
static func attachTo(context: NKScriptContext) {
let principal = NKE_Menu()
context.NKloadPlugin(principal, namespace: "io.nodekit.electro._menu", options: [String:AnyObject]())
}
func rewriteGeneratedStub(stub: String, forKey: String) -> String {
switch (forKey) {
case ".global":
let url = NSBundle(forClass: NKE_Menu.self).pathForResource("menu", ofType: "js", inDirectory: "lib-electro")
let appjs = try? NSString(contentsOfFile: url!, encoding: NSUTF8StringEncoding) as String
let url2 = NSBundle(forClass: NKE_Menu.self).pathForResource("menu-item", ofType: "js", inDirectory: "lib-electro")
let appjs2 = try? NSString(contentsOfFile: url2!, encoding: NSUTF8StringEncoding) as String
return "function loadplugin1(){\n" + appjs! + "\n}\n" + "\n" + "function loadplugin2(){\n" + appjs2! + "\n}\n" + stub + "\n" + "loadplugin1(); loadplugin2();" + "\n"
default:
return stub
}
}
}
class NKE_Menu: NSObject, NKEMenuProtocol {
func setApplicationMenu(menu: [String: AnyObject]) -> Void { NKE_Menu.NotImplemented(); }
func sendActionToFirstResponder(action: String) -> Void { NKE_Menu.NotImplemented(); } //OS X
private static func NotImplemented(functionName: String = __FUNCTION__) -> Void {
log("!menu.\(functionName) is not implemented")
}
}
| apache-2.0 | ae1f1128facd6e3689405a2e7775b09e | 39.553571 | 177 | 0.683399 | 3.991213 | false | false | false | false |
Killectro/RxGrailed | RxGrailed/RxGrailedTests/ViewModels/ListingViewModelSpec.swift | 1 | 1803 | //
// ListingViewModelSpec.swift
// RxGrailed
//
// Created by DJ Mitchell on 2/28/17.
// Copyright © 2017 Killectro. All rights reserved.
//
import Foundation
import Quick
import Nimble
import Mapper
import RxSwift
import RxCocoa
@testable
import RxGrailed
class ListingviewModelSpec: QuickSpec {
override func spec() {
var subject: ListingViewModel!
let json = testListingJSON() as NSDictionary
let listing = try! Listing(map: Mapper(JSON: json))
var disposeBag: DisposeBag!
beforeEach {
subject = ListingViewModel(listing: listing)
disposeBag = DisposeBag()
}
it("has an image") {
waitUntil(timeout: 10.0) { done in
subject
.image
.drive(onNext: { image in
expect(image).toNot(beNil())
done()
})
.disposed(by: disposeBag)
}
}
it("correctly formats price") {
// Assume USD
expect(subject.price) == "$300"
}
it("correctly formats designer") {
expect(subject.designer) == "SUPREME"
}
it("correctly formats title") {
expect(subject.title) == "Supreme Brick"
}
it("correctly formats description") {
expect(subject.description) == "Literally just a brick"
}
it("correctly formats size") {
expect(subject.size) == "ONE SIZE"
}
it("correctly formats title and size") {
expect(subject.titleAndSize) == "Supreme Brick size ONE SIZE"
}
it("correctly formats seller name") {
expect(subject.sellerName) == "NOT_YMBAPE"
}
}
}
| mit | 55139cb6dcf6c44018adb407aa8cac77 | 24.380282 | 73 | 0.536071 | 4.620513 | false | false | false | false |
sdhjl2000/swiftdialog | Pods/OAuthSwift/OAuthSwift/OAuth2Swift.swift | 7 | 5978 | //
// OAuth2Swift.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/22/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
public class OAuth2Swift: NSObject {
public var client: OAuthSwiftClient
public var authorize_url_handler: OAuthSwiftURLHandlerType = OAuthSwiftOpenURLExternally.sharedInstance
var consumer_key: String
var consumer_secret: String
var authorize_url: String
var access_token_url: String?
var response_type: String
var observer: AnyObject?
public convenience init(consumerKey: String, consumerSecret: String, authorizeUrl: String, accessTokenUrl: String, responseType: String){
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, responseType: responseType)
self.access_token_url = accessTokenUrl
}
public init(consumerKey: String, consumerSecret: String, authorizeUrl: String, responseType: String){
self.consumer_key = consumerKey
self.consumer_secret = consumerSecret
self.authorize_url = authorizeUrl
self.response_type = responseType
self.client = OAuthSwiftClient(consumerKey: consumerKey, consumerSecret: consumerSecret)
}
struct CallbackNotification {
static let notificationName = "OAuthSwiftCallbackNotificationName"
static let optionsURLKey = "OAuthSwiftCallbackNotificationOptionsURLKey"
}
struct OAuthSwiftError {
static let domain = "OAuthSwiftErrorDomain"
static let appOnlyAuthenticationErrorCode = 1
}
public typealias TokenSuccessHandler = (credential: OAuthSwiftCredential, response: NSURLResponse?, parameters: NSDictionary) -> Void
public typealias FailureHandler = (error: NSError) -> Void
public func authorizeWithCallbackURL(callbackURL: NSURL, scope: String, state: String, params: Dictionary<String, String> = Dictionary<String, String>(), success: TokenSuccessHandler, failure: ((error: NSError) -> Void)) {
self.observer = NSNotificationCenter.defaultCenter().addObserverForName(CallbackNotification.notificationName, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock:{
notification in
NSNotificationCenter.defaultCenter().removeObserver(self.observer!)
let url = notification.userInfo![CallbackNotification.optionsURLKey] as! NSURL
var responseParameters: Dictionary<String, String> = Dictionary()
if let query = url.query {
responseParameters = query.parametersFromQueryString()
}
if ((url.fragment) != nil && url.fragment!.isEmpty == false) {
responseParameters = url.fragment!.parametersFromQueryString()
}
if let accessToken = responseParameters["access_token"] {
self.client.credential.oauth_token = accessToken
success(credential: self.client.credential, response: nil, parameters: responseParameters)
}
if let code = responseParameters["code"] {
self.postOAuthAccessTokenWithRequestTokenByCode(code.stringByRemovingPercentEncoding!,
callbackURL:callbackURL,
success: { credential, response, responseParameters in
success(credential: credential, response: response, parameters: responseParameters)
}, failure: failure)
}
})
//let authorizeURL = NSURL(string: )
var urlString = String()
urlString += self.authorize_url
urlString += (self.authorize_url.has("?") ? "&" : "?") + "client_id=\(self.consumer_key)"
urlString += "&redirect_uri=\(callbackURL.absoluteString!)"
urlString += "&response_type=\(self.response_type)"
if (scope != "") {
urlString += "&scope=\(scope)"
}
if (state != "") {
urlString += "&state=\(state)"
}
for param in params {
urlString += "&\(param.0)=\(param.1)"
}
if let queryURL = NSURL(string: urlString) {
self.authorize_url_handler.handle(queryURL)
}
}
func postOAuthAccessTokenWithRequestTokenByCode(code: String, callbackURL: NSURL, success: TokenSuccessHandler, failure: FailureHandler?) {
var parameters = Dictionary<String, AnyObject>()
parameters["client_id"] = self.consumer_key
parameters["client_secret"] = self.consumer_secret
parameters["code"] = code
parameters["grant_type"] = "authorization_code"
parameters["redirect_uri"] = callbackURL.absoluteString!
self.client.post(self.access_token_url!, parameters: parameters, success: {
data, response in
var responseJSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)
let responseParameters: NSDictionary
if responseJSON != nil {
responseParameters = responseJSON as! NSDictionary
} else {
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as String!
responseParameters = responseString.parametersFromQueryString()
}
let accessToken = responseParameters["access_token"] as! String
self.client.credential.oauth_token = accessToken
self.client.credential.oauth2 = true
success(credential: self.client.credential, response: response, parameters: responseParameters)
}, failure: failure)
}
public class func handleOpenURL(url: NSURL) {
let notification = NSNotification(name: CallbackNotification.notificationName, object: nil,
userInfo: [CallbackNotification.optionsURLKey: url])
NSNotificationCenter.defaultCenter().postNotification(notification)
}
}
| apache-2.0 | 88ed28e0e09bb814593d30447c1bcb75 | 44.287879 | 226 | 0.661425 | 5.48944 | false | false | false | false |
aranasaurus/GalaxyKit | swift/src/Sector.swift | 2 | 1030 | import GameplayKit
public class Sector {
public let x: UInt
public let y: UInt
public let stars: [Star]
public init(_ x: UInt, _ y: UInt, numStars: UInt, sectorSize: Int) {
self.x = x
self.y = y
let coordSource = GKMersenneTwisterRandomSource(seed: UInt64((x << 16) + y))
let starSource = GKMersenneTwisterRandomSource(seed: UInt64((y << 16) + x))
// Advance the sources by a few... just for fun.
coordSource.nextInt()
coordSource.nextInt()
coordSource.nextInt()
starSource.nextInt()
starSource.nextInt()
starSource.nextInt()
var stars = [Star]()
for _ in 0..<numStars {
stars.append(Star(randomSource: starSource, coordinate: Coordinate(randomSource: coordSource, sectorSize: sectorSize)))
}
self.stars = stars
}
}
extension Sector: CustomDebugStringConvertible {
public var debugDescription: String { return "[\(x), \(y)]: \(stars)" }
}
| mit | fcaea53fa80c4f8ded31875ea86f6bef | 29.294118 | 131 | 0.597087 | 4.039216 | false | false | false | false |
acsanchezcu/LabelTranslator | LabelTranslator/LabelTranslator/APIs/VisionAPI.swift | 1 | 5972 | //
// VisionAPI.swift
// LabelTranslator
//
// Created by Sanchez Custodio, Abel (Cognizant) on 8/14/17.
// Copyright © 2017 Sanchez Custodio, Abel. All rights reserved.
//
import Vision
import UIKit
class VisionAPI
{
// MARK: - Singleton
static let shared = VisionAPI()
// MARK: - Public Methods
func highlight(imageView: UIImageView, completionHandler: @escaping ([UIImage]) -> Void) {
highlight(view: imageView, pixelBuffer: nil, completionHandler: completionHandler)
}
func highlight(pixelBuffer: CVPixelBuffer, view: UIView) {
highlight(view: view, pixelBuffer: pixelBuffer, completionHandler: nil)
}
// MARK: - Private Methods
private func highlight(view: UIView, pixelBuffer: CVPixelBuffer?, completionHandler: (([UIImage]) -> Void)?) {
var imageRequestHandler: VNImageRequestHandler?
if let imageView = view as? UIImageView,
let cgImage = imageView.image?.cgImage {
imageRequestHandler = VNImageRequestHandler(cgImage: cgImage, options: [:])
} else if let pixelBuffer = pixelBuffer {
imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: 6, options: [:])
}
guard let handler = imageRequestHandler else {
if let completionHandler = completionHandler {
completionHandler([])
}
return
}
let request = VNDetectTextRectanglesRequest { [weak self] (request, error) in
if error != nil {
if let completionHandler = completionHandler {
completionHandler([])
}
return
}
self?.detectTextHandler(request: request, view: view, completionHandler: completionHandler)
}
request.reportCharacterBoxes = true
do {
try handler.perform([request])
} catch {
print(error)
}
}
private func highlightWords(box: VNTextObservation, view: UIView) {
guard let boxes = box.characterBoxes else { return }
let outline = CALayer()
guard let frame = getFramesForWord(boxes: boxes, view: view) else { return }
outline.frame = frame
outline.borderWidth = 2.0
outline.borderColor = UIColor.red.cgColor
view.layer.addSublayer(outline)
}
private func getFramesForWord(boxes: [VNRectangleObservation], view: UIView) -> CGRect? {
var maxX: CGFloat = 9999.0
var minX: CGFloat = 0.0
var maxY: CGFloat = 9999.0
var minY: CGFloat = 0.0
for char in boxes {
if char.bottomLeft.x < maxX {
maxX = char.bottomLeft.x
}
if char.bottomRight.x > minX {
minX = char.bottomRight.x
}
if char.bottomRight.y < maxY {
maxY = char.bottomRight.y
}
if char.topRight.y > minY {
minY = char.topRight.y
}
}
var width: CGFloat = 0.0
var height: CGFloat = 0.0
if let imageView = view as? UIImageView,
let image = imageView.image {
width = image.size.width
height = image.size.height
} else {
width = view.frame.size.width
height = view.frame.size.height
}
let xCord = maxX * width
let yCord = (1 - minY) * height
let widthWord = (minX - maxX) * width
let heightWord = (minY - maxY) * height
return CGRect(x: xCord, y: yCord, width: widthWord, height: heightWord)
}
private func detectTextHandler(request: VNRequest, view: UIView, completionHandler: (([UIImage]) -> Void)?) {
DispatchQueue.main.async {
if let imageView = view as? UIImageView {
imageView.layer.sublayers?.removeAll()
} else {
view.layer.sublayers?.removeSubrange(1...)
}
}
guard let observations = request.results,
observations.count > 0 else {
if let completionHandler = completionHandler {
completionHandler([])
}
return
}
let result = observations.map({$0 as? VNTextObservation})
DispatchQueue.main.async() {
for region in result {
guard let region = region else {
continue
}
self.highlightWords(box: region, view: view)
}
if let completionHandler = completionHandler {
self.getWordImages(view: view, result: result, completionHandler: completionHandler)
}
}
}
private func getWordImages(view: UIView, result: [VNTextObservation?], completionHandler: @escaping ([UIImage]) -> Void) {
var images: [UIImage] = []
guard let imageView = view as? UIImageView,
let image = imageView.image else {
completionHandler(images)
return
}
for box in result {
guard let box = box else {
continue
}
guard let boxes = box.characterBoxes else { break }
guard let cgImage = image.cgImage,
let frame = getFramesForWord(boxes: boxes, view: view),
let imageRef = cgImage.cropping(to: frame) else { break }
let imageCropped = UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation)
images.append(imageCropped)
}
completionHandler(images)
}
}
| mit | 24fd952a2996d848ecebbe12aecc4df1 | 31.628415 | 126 | 0.540111 | 5.233129 | false | false | false | false |
pi3r0/PHExpendableCells | PHExpendableCells/PHExpendableCells/PHECellTestV.swift | 1 | 1910 | //
// PHECellTestV.swift
// ExpandableCells
//
// Created by Pierre Houguet on 02/03/2016.
// Copyright © 2016 Pierre Houguet. All rights reserved.
//
import UIKit
class PHECellTestV: UIView {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
var _anImageV : UIImageView!;
var _aLabel : UILabel!;
var _height : CGFloat = 0;
init(frame: CGRect, andHeight height : CGFloat ) {
_height = height;
let originY = (frame.height - _height)/2;
_anImageV = UIImageView(frame: CGRect(x: 0.0, y: originY, width: frame.height, height: _height));
_anImageV.contentMode = .ScaleAspectFill;
_aLabel = UILabel(frame: CGRect(x: 0, y: (frame.height - 20)/2, width: frame.width, height: 20));
_aLabel.textAlignment = .Center;
super.init(frame: frame);
addSubview(_anImageV);
addSubview(_aLabel);
clipsToBounds = true;
autoresizesSubviews = true;
}
override func layoutSubviews() {
super.layoutSubviews();
let originY = (frame.height - (_height))/2;
_anImageV.frame = CGRect(x: 0.0, y: originY, width: frame.width, height: _height);
_aLabel.frame = CGRect(x: 0, y: (frame.height - 20)/2, width: frame.width, height: 20);
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setImageIndex(index : NSInteger) {
let imageIndex : NSInteger = index%8;
_anImageV.image = UIImage(named: String(imageIndex));
_aLabel.text = "Cell at index \(index)";
}
}
| mit | 8040d9518177849e21f989c752d62e43 | 25.150685 | 105 | 0.572027 | 4.070362 | false | false | false | false |
SteveBarnegren/TweenKit | TweenKit/TweenKit/RunBlockAction.swift | 1 | 1085 | //
// RunBlockAction.swift
// TweenKit
//
// Created by Steve Barnegren on 19/03/2017.
// Copyright © 2017 Steve Barnegren. All rights reserved.
//
import Foundation
/** Runs a block. Can be used to add callbacks in sequences */
public class RunBlockAction: TriggerAction {
// MARK: - Public
public var onBecomeActive: () -> () = {}
public var onBecomeInactive: () -> () = {}
/**
Create with a callback closure
- Parameter handler: The closure to call
*/
public init(handler: @escaping () -> ()) {
self.handler = handler
}
// MARK: - Private
let handler: () -> ()
public let duration = 0.0
public var reverse: Bool = false
public func trigger() {
handler()
}
public func willBecomeActive() {
onBecomeActive()
}
public func didBecomeInactive() {
onBecomeInactive()
}
public func willBegin() {
}
public func didFinish() {
}
public func update(t: CFTimeInterval) {
// Do nothing
}
}
| mit | 43c02e909cc8797444a32767e3d6accb | 19.074074 | 62 | 0.563653 | 4.42449 | false | false | false | false |
mlatham/AFToolkit | Sources/AFToolkit/Sqlite/Sqlite+TypeDefs.swift | 1 | 1031 | import Foundation
open class Sqlite {
public typealias ErrorPointer = AutoreleasingUnsafeMutablePointer<NSError?>
public typealias ReplaceStatement = OpaquePointer
public typealias CursorStatement = OpaquePointer
public typealias Statement = OpaquePointer
public typealias Database = OpaquePointer
public typealias QueryClosure = (Database?, inout Error?) -> Any?
public typealias QueryCompletion = (Any?, Error?) -> Void
public typealias CountCompletion = (Int32, Error?) -> Void
public typealias StatementClosure = (Database?, inout Error?) throws -> Void
public typealias StatementCompletion = (Error?) -> Void
public enum TypeAffinity: String {
case text = "TEXT"
case numeric = "NUMERIC"
case integer = "INTEGER"
case real = "REAL"
case blob = "BLOB"
}
public enum Keyword: String {
case primaryKey = "PRIMARY KEY"
case autoincrement = "AUTOINCREMEMT"
case notNull = "NOT NULL"
case collateNoCase = "COLLATE NOCASE"
case defaultFalse = "DEFAULT 0"
case defaultTrue = "DEFAULT 1"
}
}
| mit | 47ae2a3bb02bb16ebb16bf4019a48e76 | 30.242424 | 77 | 0.742968 | 4.075099 | false | false | false | false |
sarah-j-smith/Quest | Common/Renderer.swift | 1 | 6963 | //
// Renderer.swift
// SwiftQuest
//
// Created by Sarah Smith on 23/12/2014.
// Copyright (c) 2014 Sarah Smith. All rights reserved.
//
import Foundation
class Renderer
{
var templates = [ String : GRMustacheTemplate ]()
let htmlPage : GRMustacheTemplate
private var _pageTitle : String?
private var _bodyTextParagraphs : [ String ]?
private var _buttonAssembly : [ LinkDescription ]?
private var _codaParagrahps : [ String ]?
private var _javascriptEntries : [ String ]?
private var _popoverFields : [ String : String ]?
init() {
let bundle = NSBundle(forClass: Renderer.self)
let path = bundle.pathForResource("templates/template", ofType: "html")!
var err : NSError?
htmlPage = GRMustacheTemplate(fromContentsOfFile: path, error: &err)
}
// MARK: HTML generation
/** Return a string of HTML for the renderers current state as set up by earlier calls to setTitle and other page-model accessors. Will reset the page-model to empty. */
func html() -> String
{
var templateFields = [ "header" : "Untitled", "content" : "Nothing special." ]
if let title = _pageTitle
{
templateFields["header"] = title
_pageTitle = nil
}
if let bodyText = _bodyTextParagraphs
{
templateFields["content"] = htmlParagraphs(bodyText)
_bodyTextParagraphs = nil
}
if let buttons = _buttonAssembly
{
let buttonLinks = buttons.map { lnk in self.createLinkButton(lnk) }
let btns = "".join(buttonLinks)
templateFields["buttons"] = btns
_buttonAssembly = nil
}
if let popover = _popoverFields
{
let popoverHTML = render(templateName: "popover", withObject: popover)
addCodaParagraph(popoverHTML)
addJavascript("$('#myModal').modal('show');")
_popoverFields = nil
}
if let coda = _codaParagrahps
{
templateFields["coda"] = htmlParagraphs(coda)
_codaParagrahps = nil
}
if let javascriptTexts = _javascriptEntries
{
templateFields["javascriptText"] = "\n".join(javascriptTexts)
}
var errorReport : NSError?
let result = htmlPage.renderObject(templateFields, error: &errorReport)
if let err = errorReport
{
NSLog("%@", templateFields)
NSLog("Rendering failed: \(err.localizedDescription)")
return "<html><body><h1>Error</h1><p>\(err.localizedDescription)</p></body></html>"
}
return result
}
func htmlParagraphs( list: [String]? ) -> String?
{
if let listStrings = list
{
if listStrings.count == 0
{
return nil
}
else if listStrings.count == 1
{
return "<p>\(listStrings[0])</p>"
}
else
{
return "<p>" + join("</p><p>", listStrings) + "</p>"
}
}
return nil
}
// MARK: Page model accessors
func setPageTitle(pageTitle: String)
{
_pageTitle = pageTitle
}
func addBodyParagraphs(paragraphs: [ String ])
{
if _bodyTextParagraphs == nil
{
_bodyTextParagraphs = paragraphs
}
else
{
_bodyTextParagraphs!.extend(paragraphs)
}
}
func addButtonLinks(linkArray: [ LinkDescription ])
{
if _buttonAssembly == nil
{
_buttonAssembly = linkArray
}
else
{
_buttonAssembly!.extend(linkArray)
}
}
func addCodaParagraph(coda: String)
{
if _codaParagrahps == nil
{
_codaParagrahps = [ coda ]
}
else
{
_codaParagrahps!.append(coda)
}
}
/** Sets up a snippet of javascript to be inserted in the page. It is placed at the end of the page, after jQuery is loaded. */
func addJavascript(javascript: String)
{
if _javascriptEntries == nil
{
_javascriptEntries = [ javascript ]
}
else
{
_javascriptEntries!.append(javascript)
}
}
func setPopover(bodyText text: String, titleText title: String, buttonLabel: String = "OK" )
{
_popoverFields = [ "popoverTitle" : title, "popoverBody" : text, "buttonLabel" : buttonLabel ]
}
// MARK: Low-level template renderers
func render( #templateName : String, withObject: AnyObject ) -> String
{
var template : GRMustacheTemplate!
if let templateActual = templates[ templateName ]
{
template = templateActual
}
else
{
let bundle = NSBundle(forClass: Renderer.self)
let path = bundle.pathForResource("templates/\(templateName)", ofType: "html")!
var err : NSError?
if let templateLoad = GRMustacheTemplate(fromContentsOfFile: path, error: &err)
{
template = templateLoad
templates.updateValue(templateLoad, forKey: templateName)
}
else
{
NSLog("Could not load template %@", path)
if let errActual = err
{
NSLog(" %@", errActual.localizedDescription)
}
}
}
if let result = template.renderObject(withObject, error: nil)
{
return result
}
return ""
}
func createImageThumbnail( link: String ) -> String
{
return render(templateName: "imageElement", withObject: link)
}
func createLinkButton( link: LinkDescription ) -> String
{
return render(templateName: "linkButton", withObject: link)
}
func createNavButton( link: LinkDescription ) -> String
{
return render(templateName: "navButton", withObject: link)
}
func urlCleanName( name: String ) -> String
{
if name == "" { return "" }
let badChars = NSRegularExpression(pattern: "[^\\p{L} #-]+", options: nil, error: nil)!
let allName = NSRange(location: 0, length: countElements(name))
var result = badChars.stringByReplacingMatchesInString(name, options: nil, range: allName, withTemplate: "")
if result == "" { return "" }
let allName2 = NSRange(location: 0, length: countElements(result))
let spaces = NSRegularExpression(pattern: "\\s+", options: nil, error: nil)!
result = spaces.stringByReplacingMatchesInString(result, options: nil, range: allName2, withTemplate: "-")
result = result.lowercaseString
return result
}
} | mit | b8d854ef21a08b9ba874f148f471e115 | 29.41048 | 174 | 0.552635 | 4.70473 | false | false | false | false |
stephentyrone/swift | test/Constraints/members.swift | 3 | 18906 | // RUN: %target-typecheck-verify-swift -swift-version 5
////
// Members of structs
////
struct X {
func f0(_ i: Int) -> X { }
func f1(_ i: Int) { }
mutating func f1(_ f: Float) { }
func f2<T>(_ x: T) -> T { }
}
struct Y<T> {
func f0(_: T) -> T {}
func f1<U>(_ x: U, y: T) -> (T, U) {}
}
var i : Int
var x : X
var yf : Y<Float>
func g0(_: (inout X) -> (Float) -> ()) {}
_ = x.f0(i)
x.f0(i).f1(i)
g0(X.f1) // expected-error{{partial application of 'mutating' method}}
_ = x.f0(x.f2(1))
_ = x.f0(1).f2(i)
_ = yf.f0(1)
_ = yf.f1(i, y: 1)
// Members referenced from inside the struct
struct Z {
var i : Int
func getI() -> Int { return i }
mutating func incI() {}
func curried(_ x: Int) -> (Int) -> Int { return { y in x + y } }
subscript (k : Int) -> Int {
get {
return i + k
}
mutating
set {
i -= k
}
}
}
struct GZ<T> {
var i : T
func getI() -> T { return i }
func f1<U>(_ a: T, b: U) -> (T, U) {
return (a, b)
}
func f2() {
var f : Float
var t = f1(i, b: f)
f = t.1
var zi = Z.i; // expected-error{{instance member 'i' cannot be used on type 'Z'}}
var zj = Z.asdfasdf // expected-error {{type 'Z' has no member 'asdfasdf'}}
}
}
var z = Z(i: 0)
var getI = z.getI
var incI = z.incI // expected-error{{partial application of 'mutating'}}
var zi = z.getI()
var zcurried1 = z.curried
var zcurried2 = z.curried(0)
var zcurriedFull = z.curried(0)(1)
////
// Members of modules
////
// Module
Swift.print(3, terminator: "")
////
// Unqualified references
////
////
// Members of literals
////
// FIXME: Crappy diagnostic
"foo".lower() // expected-error{{value of type 'String' has no member 'lower'}}
var tmp = "foo".debugDescription
////
// Members of enums
////
enum W {
case Omega
func foo(_ x: Int) {}
func curried(_ x: Int) -> (Int) -> () {}
}
var w = W.Omega
var foo = w.foo
var fooFull : () = w.foo(0)
var wcurried1 = w.curried
var wcurried2 = w.curried(0)
var wcurriedFull : () = w.curried(0)(1)
// Member of enum type
func enumMetatypeMember(_ opt: Int?) {
opt.none // expected-error{{enum case 'none' cannot be used as an instance member}}
}
////
// Nested types
////
// Reference a Type member. <rdar://problem/15034920>
class G<T> {
class In {
class func foo() {}
}
}
func goo() {
G<Int>.In.foo()
}
////
// Misc ambiguities
////
// <rdar://problem/15537772>
struct DefaultArgs {
static func f(_ a: Int = 0) -> DefaultArgs {
return DefaultArgs()
}
init() {
self = .f()
}
}
class InstanceOrClassMethod {
func method() -> Bool { return true }
class func method(_ other: InstanceOrClassMethod) -> Bool { return false }
}
func testPreferClassMethodToCurriedInstanceMethod(_ obj: InstanceOrClassMethod) {
let result = InstanceOrClassMethod.method(obj)
let _: Bool = result // no-warning
let _: () -> Bool = InstanceOrClassMethod.method(obj)
}
protocol Numeric {
static func +(x: Self, y: Self) -> Self
}
func acceptBinaryFunc<T>(_ x: T, _ fn: (T, T) -> T) { }
func testNumeric<T : Numeric>(_ x: T) {
acceptBinaryFunc(x, +)
}
/* FIXME: We can't check this directly, but it can happen with
multiple modules.
class PropertyOrMethod {
func member() -> Int { return 0 }
let member = false
class func methodOnClass(_ obj: PropertyOrMethod) -> Int { return 0 }
let methodOnClass = false
}
func testPreferPropertyToMethod(_ obj: PropertyOrMethod) {
let result = obj.member
let resultChecked: Bool = result
let called = obj.member()
let calledChecked: Int = called
let curried = obj.member as () -> Int
let methodOnClass = PropertyOrMethod.methodOnClass
let methodOnClassChecked: (PropertyOrMethod) -> Int = methodOnClass
}
*/
struct Foo { var foo: Int }
protocol ExtendedWithMutatingMethods { }
extension ExtendedWithMutatingMethods {
mutating func mutatingMethod() {}
var mutableProperty: Foo {
get { }
set { }
}
var nonmutatingProperty: Foo {
get { }
nonmutating set { }
}
var mutatingGetProperty: Foo {
mutating get { }
set { }
}
}
class ClassExtendedWithMutatingMethods: ExtendedWithMutatingMethods {}
class SubclassExtendedWithMutatingMethods: ClassExtendedWithMutatingMethods {}
func testClassExtendedWithMutatingMethods(_ c: ClassExtendedWithMutatingMethods, // expected-note* {{}}
sub: SubclassExtendedWithMutatingMethods) { // expected-note* {{}}
c.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'c' is a 'let' constant}}
c.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
c.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
c.nonmutatingProperty = Foo(foo: 0)
c.nonmutatingProperty.foo = 0
c.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
c.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = c.mutableProperty
_ = c.mutableProperty.foo
_ = c.nonmutatingProperty
_ = c.nonmutatingProperty.foo
// FIXME: diagnostic nondeterministically says "member" or "getter"
_ = c.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = c.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
sub.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'sub' is a 'let' constant}}
sub.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
sub.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
sub.nonmutatingProperty = Foo(foo: 0)
sub.nonmutatingProperty.foo = 0
sub.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
sub.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = sub.mutableProperty
_ = sub.mutableProperty.foo
_ = sub.nonmutatingProperty
_ = sub.nonmutatingProperty.foo
_ = sub.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = sub.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
var mutableC = c
mutableC.mutatingMethod()
mutableC.mutableProperty = Foo(foo: 0)
mutableC.mutableProperty.foo = 0
mutableC.nonmutatingProperty = Foo(foo: 0)
mutableC.nonmutatingProperty.foo = 0
mutableC.mutatingGetProperty = Foo(foo: 0)
mutableC.mutatingGetProperty.foo = 0
_ = mutableC.mutableProperty
_ = mutableC.mutableProperty.foo
_ = mutableC.nonmutatingProperty
_ = mutableC.nonmutatingProperty.foo
_ = mutableC.mutatingGetProperty
_ = mutableC.mutatingGetProperty.foo
var mutableSub = sub
mutableSub.mutatingMethod()
mutableSub.mutableProperty = Foo(foo: 0)
mutableSub.mutableProperty.foo = 0
mutableSub.nonmutatingProperty = Foo(foo: 0)
mutableSub.nonmutatingProperty.foo = 0
_ = mutableSub.mutableProperty
_ = mutableSub.mutableProperty.foo
_ = mutableSub.nonmutatingProperty
_ = mutableSub.nonmutatingProperty.foo
_ = mutableSub.mutatingGetProperty
_ = mutableSub.mutatingGetProperty.foo
}
// <rdar://problem/18879585> QoI: error message for attempted access to instance properties in static methods are bad.
enum LedModules: Int {
case WS2811_1x_5V
}
extension LedModules {
static var watts: Double {
return [0.30][self.rawValue] // expected-error {{instance member 'rawValue' cannot be used on type 'LedModules'}}
}
}
// <rdar://problem/15117741> QoI: calling a static function on an instance produces a non-helpful diagnostic
class r15117741S {
static func g() {}
}
func test15117741(_ s: r15117741S) {
s.g() // expected-error {{static member 'g' cannot be used on instance of type 'r15117741S'}}
}
// <rdar://problem/22491394> References to unavailable decls sometimes diagnosed as ambiguous
struct UnavailMember {
@available(*, unavailable)
static var XYZ : UnavailMember { get {} } // expected-note {{'XYZ' has been explicitly marked unavailable here}}
}
let _ : [UnavailMember] = [.XYZ] // expected-error {{'XYZ' is unavailable}}
let _ : [UnavailMember] = [.ABC] // expected-error {{type 'UnavailMember' has no member 'ABC'}}
// <rdar://problem/22490787> QoI: Poor error message iterating over property with non-sequence type that defines an Iterator type alias
struct S22490787 {
typealias Iterator = AnyIterator<Int>
}
func f22490787() {
var path: S22490787 = S22490787()
for p in path { // expected-error {{for-in loop requires 'S22490787' to conform to 'Sequence'}}
}
}
// <rdar://problem/23942743> [QoI] Bad diagnostic when errors inside enum constructor
enum r23942743 {
case Tomato(cloud: String)
}
let _ = .Tomato(cloud: .none) // expected-error {{reference to member 'Tomato' cannot be resolved without a contextual type}}
// expected-error@-1 {{cannot infer contextual base in reference to member 'none'}}
// SR-650: REGRESSION: Assertion failed: (baseTy && "Couldn't find appropriate context"), function getMemberSubstitutions
enum SomeErrorType {
case StandaloneError
case UnderlyingError(String)
static func someErrorFromString(_ str: String) -> SomeErrorType? {
if str == "standalone" { return .StandaloneError }
if str == "underlying" { return .UnderlyingError } // expected-error {{member 'UnderlyingError' expects argument of type 'String'}}
return nil
}
}
// SR-2193: QoI: better diagnostic when a decl exists, but is not a type
enum SR_2193_Error: Error {
case Boom
}
do {
throw SR_2193_Error.Boom
} catch let e as SR_2193_Error.Boom { // expected-error {{enum case 'Boom' is not a member type of 'SR_2193_Error'}}
}
// rdar://problem/25341015
extension Sequence {
func r25341015_1() -> Int {
return max(1, 2) // expected-error {{use of 'max' refers to instance method rather than global function 'max' in module 'Swift'}} expected-note {{use 'Swift.' to reference the global function in module 'Swift'}}
}
}
class C_25341015 {
static func baz(_ x: Int, _ y: Int) {}
func baz() {}
func qux() {
baz(1, 2) // expected-error {{static member 'baz' cannot be used on instance of type 'C_25341015'}} {{5-5=C_25341015.}}
}
}
struct S_25341015 {
static func foo(_ x: Int, y: Int) {}
func foo(z: Int) {}
func bar() {
foo(1, y: 2) // expected-error {{static member 'foo' cannot be used on instance of type 'S_25341015'}} {{5-5=S_25341015.}}
}
}
func r25341015() {
func baz(_ x: Int, _ y: Int) {}
class Bar {
func baz() {}
func qux() {
baz(1, 2) // expected-error {{use of 'baz' refers to instance method rather than local function 'baz'}}
}
}
}
func r25341015_local(x: Int, y: Int) {}
func r25341015_inner() {
func r25341015_local() {}
r25341015_local(x: 1, y: 2) // expected-error {{argument passed to call that takes no arguments}}
}
// rdar://problem/32854314 - Emit shadowing diagnostics even if argument types do not much completely
func foo_32854314() -> Double {
return 42
}
func bar_32854314() -> Int {
return 0
}
extension Array where Element == Int {
func foo() {
let _ = min(foo_32854314(), bar_32854314()) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}}
// expected-error@-1 {{use of 'min' refers to instance method rather than global function 'min' in module 'Swift'}}
}
func foo(_ x: Int, _ y: Double) {
let _ = min(x, y) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}}
// expected-error@-1 {{use of 'min' refers to instance method rather than global function 'min' in module 'Swift'}}
}
func bar() {
let _ = min(1.0, 2) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}}
// expected-error@-1 {{use of 'min' refers to instance method rather than global function 'min' in module 'Swift'}}
}
}
// Crash in diagnoseImplicitSelfErrors()
struct Aardvark {
var snout: Int
mutating func burrow() {
dig(&snout, .y) // expected-error {{type 'Int' has no member 'y'}}
}
func dig(_: inout Int, _: Int) {}
}
func rdar33914444() {
struct A {
enum R<E: Error> {
case e(E) // expected-note {{'e' declared here}}
}
struct S {
enum E: Error {
case e1
}
let e: R<E>
}
}
_ = A.S(e: .e1)
// expected-error@-1 {{type 'A.R<A.S.E>' has no member 'e1'; did you mean 'e'?}}
}
// SR-5324: Better diagnostic when instance member of outer type is referenced from nested type
struct Outer {
var outer: Int
struct Inner {
var inner: Int
func sum() -> Int {
return inner + outer
// expected-error@-1 {{instance member 'outer' of type 'Outer' cannot be used on instance of nested type 'Outer.Inner'}}
}
}
}
// rdar://problem/39514009 - don't crash when trying to diagnose members with special names
print("hello")[0] // expected-error {{value of type '()' has no subscripts}}
func rdar40537782() {
class A {}
class B : A {
override init() {}
func foo() -> A { return A() }
}
struct S<T> {
init(_ a: T...) {}
}
func bar<T>(_ t: T) {
_ = S(B(), .foo(), A()) // expected-error {{type 'A' has no member 'foo'}}
}
}
func rdar36989788() {
struct A<T> {
func foo() -> A<T> {
return self
}
}
func bar<T>(_ x: A<T>) -> (A<T>, A<T>) {
return (x.foo(), x.undefined()) // expected-error {{value of type 'A<T>' has no member 'undefined'}}
}
}
func rdar46211109() {
struct MyIntSequenceStruct: Sequence {
struct Iterator: IteratorProtocol {
var current = 0
mutating func next() -> Int? {
return current + 1
}
}
func makeIterator() -> Iterator {
return Iterator()
}
}
func foo<E, S: Sequence>(_ type: E.Type) -> S? where S.Element == E {
return nil
}
let _: MyIntSequenceStruct? = foo(Int.Self)
// expected-error@-1 {{type 'Int' has no member 'Self'}}
}
class A {}
enum B {
static func foo() {
bar(A()) // expected-error {{instance member 'bar' cannot be used on type 'B'}}
}
func bar(_: A) {}
}
class C {
static func foo() {
bar(0) // expected-error {{instance member 'bar' cannot be used on type 'C'}}
}
func bar(_: Int) {}
}
class D {
static func foo() {}
func bar() {
foo() // expected-error {{static member 'foo' cannot be used on instance of type 'D'}}
}
}
func rdar_48114578() {
struct S<T> {
var value: T
static func valueOf<T>(_ v: T) -> S<T> {
return S<T>(value: v)
}
}
typealias A = (a: [String]?, b: Int)
func foo(_ a: [String], _ b: Int) -> S<A> {
let v = (a, b)
return .valueOf(v)
}
func bar(_ a: [String], _ b: Int) -> S<A> {
return .valueOf((a, b)) // Ok
}
}
struct S_Min {
var xmin: Int = 42
}
func xmin(_: Int, _: Float) -> Int { return 0 }
func xmin(_: Float, _: Int) -> Int { return 0 }
extension S_Min : CustomStringConvertible {
public var description: String {
return "\(xmin)" // Ok
}
}
// rdar://problem/50679161
func rdar50679161() {
struct Point {}
struct S {
var w, h: Point
}
struct Q {
init(a: Int, b: Int) {}
init(a: Point, b: Point) {}
}
func foo() {
_ = { () -> Void in
var foo = S
// expected-error@-1 {{expected member name or constructor call after type name}}
// expected-note@-2 {{add arguments after the type to construct a value of the type}}
// expected-note@-3 {{use '.self' to reference the type object}}
if let v = Int?(1) {
var _ = Q(
a: v + foo.w,
// expected-error@-1 {{instance member 'w' cannot be used on type 'S'}}
// expected-error@-2 {{cannot convert value of type 'Point' to expected argument type 'Int'}}
b: v + foo.h
// expected-error@-1 {{instance member 'h' cannot be used on type 'S'}}
// expected-error@-2 {{cannot convert value of type 'Point' to expected argument type 'Int'}}
)
}
}
}
}
func rdar_50467583_and_50909555() {
if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) {
// rdar://problem/50467583
let _: Set = [Int][] // expected-error {{no 'subscript' candidates produce the expected contextual result type 'Set'}}
// expected-error@-1 {{no exact matches in call to subscript}}
// expected-note@-2 {{found candidate with type '(Int) -> Int'}}
// expected-note@-3 {{found candidate with type '(Range<Int>) -> ArraySlice<Int>'}}
// expected-note@-4 {{found candidate with type '((UnboundedRange_) -> ()) -> ArraySlice<Int>'}}
// expected-note@-5 {{found candidate with type '(RangeSet<Array<Int>.Index>) -> DiscontiguousSlice<[Int]>' (aka '(RangeSet<Int>) -> DiscontiguousSlice<Array<Int>>')}}
// expected-note@-6 {{found candidate with type '(Range<Array<Int>.Index>) -> Slice<[Int]>' (aka '(Range<Int>) -> Slice<Array<Int>>')}}
}
// rdar://problem/50909555
struct S {
static subscript(x: Int, y: Int) -> Int { // expected-note {{'subscript(_:_:)' declared here}}
return 1
}
}
func test(_ s: S) {
s[1] // expected-error {{static member 'subscript' cannot be used on instance of type 'S'}} {{5-6=S}}
// expected-error@-1 {{missing argument for parameter #2 in call}} {{8-8=, <#Int#>}}
}
}
// SR-9396 (rdar://problem/46427500) - Nonsensical error message related to constrained extensions
struct SR_9396<A, B> {}
extension SR_9396 where A == Bool { // expected-note {{where 'A' = 'Int'}}
func foo() {}
}
func test_sr_9396(_ s: SR_9396<Int, Double>) {
s.foo() // expected-error {{referencing instance method 'foo()' on 'SR_9396' requires the types 'Int' and 'Bool' be equivalent}}
}
// rdar://problem/34770265 - Better diagnostic needed for constrained extension method call
extension Dictionary where Key == String { // expected-note {{where 'Key' = 'Int'}}
func rdar_34770265_key() {}
}
extension Dictionary where Value == String { // expected-note {{where 'Value' = 'Int'}}
func rdar_34770265_val() {}
}
func test_34770265(_ dict: [Int: Int]) {
dict.rdar_34770265_key()
// expected-error@-1 {{referencing instance method 'rdar_34770265_key()' on 'Dictionary' requires the types 'Int' and 'String' be equivalent}}
dict.rdar_34770265_val()
// expected-error@-1 {{referencing instance method 'rdar_34770265_val()' on 'Dictionary' requires the types 'Int' and 'String' be equivalent}}
}
// SR-12672
_ = [.e] // expected-error {{reference to member 'e' cannot be resolved without a contextual type}}
let _ : [Any] = [.e] // expected-error {{type 'Any' has no member 'e'}}
_ = [1 :.e] // expected-error {{reference to member 'e' cannot be resolved without a contextual type}}
_ = [.e: 1] // expected-error {{reference to member 'e' cannot be resolved without a contextual type}}
let _ : [Int: Any] = [1 : .e] // expected-error {{type 'Any' has no member 'e'}}
let _ : (Int, Any) = (1, .e) // expected-error {{type 'Any' has no member 'e'}}
_ = (1, .e) // expected-error {{cannot infer contextual base in reference to member 'e'}}
| apache-2.0 | a1aae505abd59620d90d8c0d2673de88 | 26.967456 | 215 | 0.640167 | 3.524609 | false | false | false | false |
hooman/swift | test/AutoDiff/validation-test/differentiable_property.swift | 1 | 4285 | // RUN: %target-run-simple-swift(-Xfrontend -requirement-machine=off)
// REQUIRES: executable_test
// An end-to-end test that we can differentiate property accesses, with custom
// VJPs for the properties specified in various ways.
import StdlibUnittest
import DifferentiationUnittest
var E2EDifferentiablePropertyTests = TestSuite("E2EDifferentiableProperty")
struct TangentSpace : AdditiveArithmetic {
let x, y: Tracked<Float>
}
extension TangentSpace : Differentiable {
typealias TangentVector = TangentSpace
}
struct Space {
/// `x` is a computed property with a custom vjp.
var x: Tracked<Float> {
@differentiable(reverse)
get { storedX }
set { storedX = newValue }
}
@derivative(of: x)
func vjpX() -> (value: Tracked<Float>, pullback: (Tracked<Float>) -> TangentSpace) {
return (x, { v in TangentSpace(x: v, y: 0) } )
}
private var storedX: Tracked<Float>
@differentiable(reverse)
var y: Tracked<Float>
init(x: Tracked<Float>, y: Tracked<Float>) {
self.storedX = x
self.y = y
}
}
extension Space : Differentiable {
typealias TangentVector = TangentSpace
mutating func move(by offset: TangentSpace) {
x.move(by: offset.x)
y.move(by: offset.y)
}
}
E2EDifferentiablePropertyTests.testWithLeakChecking("computed property") {
let actualGrad = gradient(at: Space(x: 0, y: 0)) { (point: Space) -> Tracked<Float> in
return 2 * point.x
}
let expectedGrad = TangentSpace(x: 2, y: 0)
expectEqual(expectedGrad, actualGrad)
}
E2EDifferentiablePropertyTests.testWithLeakChecking("stored property") {
let actualGrad = gradient(at: Space(x: 0, y: 0)) { (point: Space) -> Tracked<Float> in
return 3 * point.y
}
let expectedGrad = TangentSpace(x: 0, y: 3)
expectEqual(expectedGrad, actualGrad)
}
struct GenericMemberWrapper<T : Differentiable> : Differentiable {
// Stored property.
@differentiable(reverse)
var x: T
func vjpX() -> (T, (T.TangentVector) -> GenericMemberWrapper.TangentVector) {
return (x, { TangentVector(x: $0) })
}
}
E2EDifferentiablePropertyTests.testWithLeakChecking("generic stored property") {
let actualGrad = gradient(at: GenericMemberWrapper<Tracked<Float>>(x: 1)) { point in
return 2 * point.x
}
let expectedGrad = GenericMemberWrapper<Tracked<Float>>.TangentVector(x: 2)
expectEqual(expectedGrad, actualGrad)
}
struct ProductSpaceSelfTangent : AdditiveArithmetic {
let x, y: Tracked<Float>
}
extension ProductSpaceSelfTangent : Differentiable {
typealias TangentVector = ProductSpaceSelfTangent
}
E2EDifferentiablePropertyTests.testWithLeakChecking("fieldwise product space, self tangent") {
let actualGrad = gradient(at: ProductSpaceSelfTangent(x: 0, y: 0)) { (point: ProductSpaceSelfTangent) -> Tracked<Float> in
return 5 * point.y
}
let expectedGrad = ProductSpaceSelfTangent(x: 0, y: 5)
expectEqual(expectedGrad, actualGrad)
}
struct ProductSpaceOtherTangentTangentSpace : AdditiveArithmetic {
let x, y: Tracked<Float>
}
extension ProductSpaceOtherTangentTangentSpace : Differentiable {
typealias TangentVector = ProductSpaceOtherTangentTangentSpace
}
struct ProductSpaceOtherTangent {
var x, y: Tracked<Float>
}
extension ProductSpaceOtherTangent : Differentiable {
typealias TangentVector = ProductSpaceOtherTangentTangentSpace
mutating func move(by offset: ProductSpaceOtherTangentTangentSpace) {
x.move(by: offset.x)
y.move(by: offset.y)
}
}
E2EDifferentiablePropertyTests.testWithLeakChecking("fieldwise product space, other tangent") {
let actualGrad = gradient(
at: ProductSpaceOtherTangent(x: 0, y: 0)
) { (point: ProductSpaceOtherTangent) -> Tracked<Float> in
return 7 * point.y
}
let expectedGrad = ProductSpaceOtherTangentTangentSpace(x: 0, y: 7)
expectEqual(expectedGrad, actualGrad)
}
E2EDifferentiablePropertyTests.testWithLeakChecking("computed property") {
struct TF_544 : Differentiable {
var value: Tracked<Float>
@differentiable(reverse)
var computed: Tracked<Float> {
get { value }
set { value = newValue }
}
}
let actualGrad = gradient(at: TF_544(value: 2.4)) { x in
return x.computed * x.computed
}
let expectedGrad = TF_544.TangentVector(value: 4.8)
expectEqual(expectedGrad, actualGrad)
}
runAllTests()
| apache-2.0 | e308109b03e9a2c4d2ad8dd79866d60c | 27.952703 | 124 | 0.730222 | 3.684437 | false | true | false | false |
hooman/swift | stdlib/private/OSLog/OSLogPrivacy.swift | 14 | 6442 | //===----------------- OSLogPrivacy.swift ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This file defines the APIs for specifying privacy in the log messages and also
// the logic for encoding them in the byte buffer passed to the libtrace library.
/// Privacy options for specifying privacy level of the interpolated expressions
/// in the string interpolations passed to the log APIs.
@frozen
public struct OSLogPrivacy {
@usableFromInline
internal enum PrivacyOption {
case `private`
case `public`
case auto
}
public enum Mask {
/// Applies a salted hashing transformation to an interpolated value to redact it in the logs.
///
/// Its purpose is to permit the correlation of identical values across multiple log lines
/// without revealing the value itself.
case hash
case none
}
@usableFromInline
internal var privacy: PrivacyOption
@usableFromInline
internal var mask: Mask
@_transparent
@usableFromInline
internal init(privacy: PrivacyOption, mask: Mask) {
self.privacy = privacy
self.mask = mask
}
/// Sets the privacy level of an interpolated value to public.
///
/// When the privacy level is public, the value will be displayed
/// normally without any redaction in the logs.
@_semantics("constant_evaluable")
@_optimize(none)
@inlinable
public static var `public`: OSLogPrivacy {
OSLogPrivacy(privacy: .public, mask: .none)
}
/// Sets the privacy level of an interpolated value to private.
///
/// When the privacy level is private, the value will be redacted in the logs,
/// subject to the privacy configuration of the logging system.
@_semantics("constant_evaluable")
@_optimize(none)
@inlinable
public static var `private`: OSLogPrivacy {
OSLogPrivacy(privacy: .private, mask: .none)
}
/// Sets the privacy level of an interpolated value to private and
/// applies a `mask` to the interpolated value to redacted it.
///
/// When the privacy level is private, the value will be redacted in the logs,
/// subject to the privacy configuration of the logging system.
///
/// If the value need not be redacted in the logs, its full value is captured as normal.
/// Otherwise (i.e. if the value would be redacted) the `mask` is applied to
/// the argument value and the result of the transformation is recorded instead.
///
/// - Parameters:
/// - mask: Mask to use with the privacy option.
@_semantics("constant_evaluable")
@_optimize(none)
@inlinable
public static func `private`(mask: Mask) -> OSLogPrivacy {
OSLogPrivacy(privacy: .private, mask: mask)
}
/// Auto-infers a privacy level for an interpolated value.
///
/// The system will automatically decide whether the value should
/// be captured fully in the logs or should be redacted.
@_semantics("constant_evaluable")
@_optimize(none)
@inlinable
public static var auto: OSLogPrivacy {
OSLogPrivacy(privacy: .auto, mask: .none)
}
/// Auto-infers a privacy level for an interpolated value and applies a `mask`
/// to the interpolated value to redacted it when necessary.
///
/// The system will automatically decide whether the value should
/// be captured fully in the logs or should be redacted.
/// If the value need not be redacted in the logs, its full value is captured as normal.
/// Otherwise (i.e. if the value would be redacted) the `mask` is applied to
/// the argument value and the result of the transformation is recorded instead.
///
/// - Parameters:
/// - mask: Mask to use with the privacy option.
@_semantics("constant_evaluable")
@_optimize(none)
@inlinable
public static func auto(mask: Mask) -> OSLogPrivacy {
OSLogPrivacy(privacy: .auto, mask: mask)
}
/// Return an argument flag for the privacy option., as defined by the
/// os_log ABI, which occupies four least significant bits of the first byte of the
/// argument header. The first two bits are used to indicate privacy and
/// the other two are reserved.
@inlinable
@_semantics("constant_evaluable")
@_optimize(none)
internal var argumentFlag: UInt8 {
switch privacy {
case .private:
return 0x1
case .public:
return 0x2
default:
return 0
}
}
@inlinable
@_semantics("constant_evaluable")
@_optimize(none)
internal var isAtleastPrivate: Bool {
switch privacy {
case .public:
return false
case .auto:
return false
default:
return true
}
}
@inlinable
@_semantics("constant_evaluable")
@_optimize(none)
internal var needsPrivacySpecifier: Bool {
if case .hash = mask {
return true
}
switch privacy {
case .auto:
return false
default:
return true
}
}
@inlinable
@_transparent
internal var hasMask: Bool {
if case .hash = mask {
return true
}
return false
}
/// A 64-bit value obtained by interpreting the mask name as a little-endian unsigned
/// integer.
@inlinable
@_transparent
internal var maskValue: UInt64 {
// Return the value of
// 'h' | 'a' << 8 | 's' << 16 | 'h' << 24 which equals
// 104 | (97 << 8) | (115 << 16) | (104 << 24)
1752392040
}
/// Return an os log format specifier for this `privacy` level. The
/// format specifier goes within curly braces e.g. %{private} in the format
/// string passed to the os log ABI.
@inlinable
@_semantics("constant_evaluable")
@_optimize(none)
internal var privacySpecifier: String? {
let hasMask = self.hasMask
var isAuto = false
if case .auto = privacy {
isAuto = true
}
if isAuto, !hasMask {
return nil
}
var specifier: String
switch privacy {
case .public:
specifier = "public"
case .private:
specifier = "private"
default:
specifier = ""
}
if hasMask {
if !isAuto {
specifier += ","
}
specifier += "mask.hash"
}
return specifier
}
}
| apache-2.0 | ec9f6403fdcb9a17e07a2c0c4064bf45 | 28.281818 | 98 | 0.65756 | 4.32059 | false | false | false | false |
firebase/firebase-ios-sdk | FirebaseInAppMessaging/Tests/Integration/DefaultUITestApp/FiamDisplaySwiftExample/ModalMessageViewController.swift | 2 | 8533 | /*
* Copyright 2018 Google
*
* 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
class ModalMessageViewController: CommonMessageTestVC {
func testModalMessage(titleText: String,
bodyText: String?,
textColor: UIColor,
backgroundColor: UIColor,
imageData: InAppMessagingImageData?,
actionButton: InAppMessagingActionButton?,
actionURL: URL?) -> InAppMessagingModalDisplay {
return InAppMessagingModalDisplay(
campaignName: "campaignName",
titleText: titleText,
bodyText: bodyText,
textColor: textColor,
backgroundColor: backgroundColor,
imageData: imageData,
actionButton: actionButton,
actionURL: actionURL,
appData: nil
)
}
let displayImpl = InAppMessagingDefaultDisplayImpl()
@IBOutlet var verifyLabel: UILabel!
override func messageClicked(_ inAppMessage: InAppMessagingDisplayMessage,
with action: InAppMessagingAction) {
super.messageClicked(inAppMessage, with: action)
verifyLabel.text = "message clicked!"
}
override func messageDismissed(_ inAppMessage: InAppMessagingDisplayMessage,
dismissType: FIRInAppMessagingDismissType) {
super.messageDismissed(inAppMessage, dismissType: dismissType)
verifyLabel.text = "message dismissed!"
}
@IBAction func showRegular(_ sender: Any) {
verifyLabel.text = "Verification Label"
let imageRawData = produceImageOfSize(size: CGSize(width: 200, height: 200))
let fiamImageData = InAppMessagingImageData(imageURL: "url not important",
imageData: imageRawData!)
let modalMessage = testModalMessage(
titleText: normalMessageTitle,
bodyText: normalMessageBody,
textColor: UIColor.black,
backgroundColor: UIColor.blue,
imageData: fiamImageData,
actionButton: defaultActionButton,
actionURL: URL(string: "http://firebase.com")
)
displayImpl.displayMessage(modalMessage, displayDelegate: self)
}
@IBAction func showWithoutImage(_ sender: Any) {
verifyLabel.text = "Verification Label"
let modalMessage = testModalMessage(
titleText: normalMessageTitle,
bodyText: normalMessageBody,
textColor: UIColor.black,
backgroundColor: UIColor.blue,
imageData: nil,
actionButton: defaultActionButton,
actionURL: URL(string: "http://firebase.com")
)
displayImpl.displayMessage(modalMessage, displayDelegate: self)
}
@IBAction func showWithoutButton(_ sender: Any) {
verifyLabel.text = "Verification Label"
let imageRawData = produceImageOfSize(size: CGSize(width: 200, height: 200))
let fiamImageData = InAppMessagingImageData(imageURL: "url not important",
imageData: imageRawData!)
let modalMessage = testModalMessage(
titleText: normalMessageTitle,
bodyText: normalMessageBody,
textColor: UIColor.black,
backgroundColor: UIColor.blue,
imageData: fiamImageData,
actionButton: nil,
actionURL: nil
)
displayImpl.displayMessage(modalMessage, displayDelegate: self)
}
@IBAction func showWithoutImageAndButton(_ sender: Any) {
verifyLabel.text = "Verification Label"
let modalMessage = testModalMessage(
titleText: normalMessageTitle,
bodyText: normalMessageBody,
textColor: UIColor.black,
backgroundColor: UIColor.blue,
imageData: nil,
actionButton: nil,
actionURL: nil
)
displayImpl.displayMessage(modalMessage, displayDelegate: self)
}
@IBAction func showWithLargeBody(_ sender: Any) {
verifyLabel.text = "Verification Label"
let modalMessage = testModalMessage(
titleText: normalMessageTitle,
bodyText: longBodyText,
textColor: UIColor.black,
backgroundColor: UIColor.blue,
imageData: nil,
actionButton: defaultActionButton,
actionURL: URL(string: "http://firebase.com")
)
displayImpl.displayMessage(modalMessage, displayDelegate: self)
}
@IBAction func showWithLargeTitleAndBody(_ sender: Any) {
verifyLabel.text = "Verification Label"
let imageRawData = produceImageOfSize(size: CGSize(width: 200, height: 200))
let fiamImageData = InAppMessagingImageData(imageURL: "url not important",
imageData: imageRawData!)
let modalMessage = testModalMessage(
titleText: longTitleText,
bodyText: longBodyText,
textColor: UIColor.black,
backgroundColor: UIColor.blue,
imageData: fiamImageData,
actionButton: defaultActionButton,
actionURL: URL(string: "http://firebase.com")
)
displayImpl.displayMessage(modalMessage, displayDelegate: self)
}
@IBAction func showWithLargeTitle(_ sender: Any) {
verifyLabel.text = "Verification Label"
let modalMessage = testModalMessage(
titleText: longBodyText,
bodyText: normalMessageBody,
textColor: UIColor.black,
backgroundColor: UIColor.blue,
imageData: nil,
actionButton: defaultActionButton,
actionURL: URL(string: "http://firebase.com")
)
displayImpl.displayMessage(modalMessage, displayDelegate: self)
}
@IBAction func showWithLargeTitleAndBodyWithoutImage(_ sender: Any) {
verifyLabel.text = "Verification Label"
let modalMessage = testModalMessage(
titleText: longTitleText,
bodyText: longBodyText,
textColor: UIColor.black,
backgroundColor: UIColor.blue,
imageData: nil,
actionButton: defaultActionButton,
actionURL: URL(string: "http://firebase.com")
)
displayImpl.displayMessage(modalMessage, displayDelegate: self)
}
@IBAction func showWithLargeTitleWithoutBodyWithoutImageWithoutButton(_ sender: Any) {
verifyLabel.text = "Verification Label"
let modalMessage = testModalMessage(
titleText: longBodyText,
bodyText: "",
textColor: UIColor.black,
backgroundColor: UIColor.blue,
imageData: nil,
actionButton: nil,
actionURL: nil
)
displayImpl.displayMessage(modalMessage, displayDelegate: self)
}
@IBAction func showWithWideImage(_ sender: Any) {
verifyLabel.text = "Verification Label"
let imageRawData = produceImageOfSize(size: CGSize(width: 600, height: 200))
let fiamImageData = InAppMessagingImageData(imageURL: "url not important",
imageData: imageRawData!)
let modalMessage = testModalMessage(
titleText: normalMessageTitle,
bodyText: normalMessageBody,
textColor: UIColor.black,
backgroundColor: UIColor.blue,
imageData: fiamImageData,
actionButton: defaultActionButton,
actionURL: URL(string: "http://firebase.com")
)
displayImpl.displayMessage(modalMessage, displayDelegate: self)
}
@IBAction func showWithThinImage(_ sender: Any) {
verifyLabel.text = "Verification Label"
let imageRawData = produceImageOfSize(size: CGSize(width: 200, height: 600))
let fiamImageData = InAppMessagingImageData(imageURL: "url not important",
imageData: imageRawData!)
let modalMessage = testModalMessage(
titleText: normalMessageTitle,
bodyText: normalMessageBody,
textColor: UIColor.black,
backgroundColor: UIColor.blue,
imageData: fiamImageData,
actionButton: defaultActionButton,
actionURL: URL(string: "http://firebase.com")
)
displayImpl.displayMessage(modalMessage, displayDelegate: self)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 05b85c382536d2550e5d1796a0e93f1b | 32.996016 | 88 | 0.683464 | 4.799213 | false | true | false | false |
apple/swift-lldb | packages/Python/lldbsuite/test/lang/swift/po/val_types/main.swift | 1 | 1778 | // main.swift
//
// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
struct DefaultMirror {
var a = 12
var b = 24
}
struct CustomMirror : CustomReflectable {
var a = 12
var b = 24
public var customMirror: Mirror {
get { return Mirror(self, children: ["c" : a + b]) }
}
}
struct CustomSummary : CustomStringConvertible, CustomDebugStringConvertible {
var a = 12
var b = 24
var description: String { return "CustomStringConvertible" }
var debugDescription: String { return "CustomDebugStringConvertible" }
}
func main() {
var dm = DefaultMirror()
var cm = CustomMirror()
var cs = CustomSummary()
var patatino = "foo"
print("yay I am done!") //% self.expect("po dm", substrs=['a', 'b', '12', '24'])
//% self.expect("po cm", substrs=['c', '36'])
//% self.expect("po cm", substrs=['12', '24'], matching=False)
//% self.expect("po cs", substrs=['CustomDebugStringConvertible'])
//% self.expect("po cs", substrs=['CustomStringConvertible'], matching=False)
//% self.expect("po cs", substrs=['a', '12', 'b', '24'])
//% self.expect("script lldb.frame.FindVariable('cs').GetObjectDescription()", substrs=['a', '12', 'b', '24'])
//% self.expect("po (12,24,36,48)", substrs=['12', '24', '36', '48'])
//% self.expect("po [dm as Any,cm as Any,48 as Any]", substrs=['12', '24', '36', '48'])
//% self.expect("po patatino", substrs=['foo'])
}
main()
| apache-2.0 | 4bf39345c817f2e1505df7bde47339b6 | 33.862745 | 112 | 0.619235 | 3.766949 | false | false | false | false |
delannoyk/SoundcloudSDK | sources/SoundcloudSDK/soundcloud/Soundcloud.swift | 1 | 2899 | //
// Soundcloud.swift
// Soundcloud
//
// Created by Benjamin Chrobot on 11/9/16.
// Copyright (c) 2015 Kevin Delannoy. All rights reserved.
//
import Foundation
// MARK: Properties
/// Your Soundcloud app client identifier
public var clientIdentifier: String? {
get {
return SoundcloudClient.clientIdentifier
}
set(newClientIdentifier) {
SoundcloudClient.clientIdentifier = newClientIdentifier
}
}
/// Your Soundcloud app client secret
public var clientSecret: String? {
get {
return SoundcloudClient.clientSecret
}
set(newClientSecret) {
SoundcloudClient.clientSecret = newClientSecret
}
}
/// Your Soundcloud redirect URI
public var redirectURI: String? {
get {
return SoundcloudClient.redirectURI
}
set(newRedirectURI) {
SoundcloudClient.redirectURI = newRedirectURI
}
}
/**
Convience method to set Soundcloud app credentials
- parameter clientIdentifier: Your Soundcloud app client identifier
- parameter clientSecret: Your Soundcloud app client secret
- parameter redirectURI: Your Soundcloud redirect URI
*/
public func configure(clientIdentifier: String?, clientSecret: String?, redirectURI: String?) {
SoundcloudClient.clientIdentifier = clientIdentifier
SoundcloudClient.clientSecret = clientSecret
SoundcloudClient.redirectURI = redirectURI
}
// MARK: Session Management
#if os(iOS) || os(OSX)
/**
Logs a user in. This method will present an UIViewController over `displayViewController`
that will load a web view so that user is available to log in
- parameter displayViewController: An UIViewController that is in the view hierarchy
- parameter completion: The closure that will be called when the user is logged in or upon error
*/
public func login(in displayViewController: ViewController, completion: @escaping (SimpleAPIResponse<Session>) -> Void) {
SoundcloudClient.login(in: displayViewController, completion: completion)
}
/// The session property is only set when a user has logged in.
public var session: Session? {
return SoundcloudClient.session
}
/**
Logs out the current user. This is a straight-forward call.
*/
public func destroySession() {
SoundcloudClient.destroySession()
}
#endif
// MARK: Resolve
/// A resolve response can either be a/some User(s) or a/some Track(s) or a Playlist.
public typealias ResolveResponse = (users: [User]?, tracks: [Track]?, playlist: Playlist?)
/**
Resolve allows you to lookup and access API resources when you only know the SoundCloud.com URL.
- parameter URI: The URI to lookup
- parameter completion: The closure that will be called when the result is ready or upon error
*/
public func resolve(URI: String, completion: @escaping (SimpleAPIResponse<ResolveResponse>) -> Void) {
SoundcloudClient.resolve(URI: URI, completion: completion)
}
| mit | a6a4b38cab25d95ec8dad50cae879954 | 28.581633 | 121 | 0.733356 | 4.405775 | false | false | false | false |
Ethenyl/JAMFKit | JamfKit/Sources/Session/Requests/SessionManagerRequests.swift | 1 | 6195 | //
// Copyright © 2017-present JamfKit. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
enum HttpHeader: String {
case accept = "Accept"
case authorization = "Authorization"
case contentType = "Content-Type"
}
enum HeaderContentType: String {
case json = "application/json"
}
extension SessionManager {
// MARK: - Functions
/// Returns a Base64 encoded username & password pair to be used for Basic HTTP authentication
static func computeAuthorizationHeader(from username: String, password: String) -> String {
guard
!username.isEmpty,
!password.isEmpty,
let authorizationData = "\(username):\(password)".data(using: String.Encoding.utf8)
else {
return ""
}
return "Basic \(authorizationData.base64EncodedString())"
}
/// Returns an authentified URLRequst matching the supplied configuration
func authentifiedRequest(for url: URL, authorizationHeader: String, method: HttpMethod) -> URLRequest {
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
request.setValue(authorizationHeader, forHTTPHeaderField: HttpHeader.authorization.rawValue)
return request
}
func baseRequest(endpoint: String, key: String, value: String, method: HttpMethod) -> URLRequest? {
guard let url = host?.appendingPathComponent("\(endpoint)/\(key.asCleanedKey())/\(value)") else {
return nil
}
return authentifiedRequest(for: url, authorizationHeader: authorizationHeader, method: method)
}
}
// MARK: - Create
extension SessionManager {
/// Returns a `CREATE` URLRequest for the supplied URL
func createRequest(for object: Endpoint & Requestable, key: String, value: String) -> URLRequest? {
guard
var request = baseRequest(endpoint: object.endpoint, key: key, value: value, method: .post),
let data = try? JSONSerialization.data(withJSONObject: object.toJSON(), options: .prettyPrinted) else {
return nil
}
request.setValue(HeaderContentType.json.rawValue, forHTTPHeaderField: HttpHeader.contentType.rawValue)
request.httpBody = data
return request
}
}
// MARK: - Read
extension SessionManager {
/// Returns a `READ` URLRequest for the supplied JSS endpoint
func readAllRequest(for endpoint: String) -> URLRequest? {
guard let url = host?.appendingPathComponent("\(endpoint)") else {
return nil
}
var request = authentifiedRequest(for: url, authorizationHeader: authorizationHeader, method: HttpMethod.get)
request.setValue(HeaderContentType.json.rawValue, forHTTPHeaderField: HttpHeader.accept.rawValue)
return request
}
/// Returns a `READ` URLRequest for the supplied endpoint type & identifier
func readRequest(for endpoint: Endpoint.Type, key: String, value: String) -> URLRequest? {
guard var request = baseRequest(endpoint: endpoint.Endpoint, key: key, value: value, method: .get) else {
return nil
}
request.setValue(HeaderContentType.json.rawValue, forHTTPHeaderField: HttpHeader.accept.rawValue)
return request
}
/// Returns a `READ` URLRequest for the supplied JSS object
func readRequest(for object: Endpoint) -> URLRequest? {
guard let url = host?.appendingPathComponent("\(object.endpoint)") else {
return nil
}
var request = authentifiedRequest(for: url, authorizationHeader: authorizationHeader, method: HttpMethod.get)
request.setValue(HeaderContentType.json.rawValue, forHTTPHeaderField: HttpHeader.accept.rawValue)
return request
}
/// Returns a `READ` URLRequest for the supplied JSS object
func readRequest(for object: Endpoint, key: String, value: String) -> URLRequest? {
guard var request = baseRequest(endpoint: object.endpoint, key: key, value: value, method: .get) else {
return nil
}
request.setValue(HeaderContentType.json.rawValue, forHTTPHeaderField: HttpHeader.accept.rawValue)
return request
}
}
// MARK: - Update
extension SessionManager {
/// Returns an `UPDATE` URLRequest for the supplied JSS object
func updateRequest(for object: Endpoint & Requestable) -> URLRequest? {
guard
let url = host?.appendingPathComponent("\(object.endpoint)"),
let data = try? JSONSerialization.data(withJSONObject: object.toJSON(), options: .prettyPrinted) else {
return nil
}
var request = authentifiedRequest(for: url, authorizationHeader: authorizationHeader, method: HttpMethod.put)
request.setValue(HeaderContentType.json.rawValue, forHTTPHeaderField: HttpHeader.contentType.rawValue)
request.httpBody = data
return request
}
/// Returns an `UPDATE` URLRequest for the supplied JSS object
func updateRequest(for object: Endpoint & Requestable, key: String, value: String) -> URLRequest? {
guard
var request = self.baseRequest(endpoint: object.endpoint, key: key, value: value, method: .put),
let data = try? JSONSerialization.data(withJSONObject: object.toJSON(), options: .prettyPrinted) else {
return nil
}
request.setValue(HeaderContentType.json.rawValue, forHTTPHeaderField: HttpHeader.contentType.rawValue)
request.httpBody = data
return request
}
}
// MARK: - Delete
extension SessionManager {
/// Returns a `DELETE` URLRequest for the supplied endpoint type & identifier
func deleteRequest(for endpoint: Endpoint.Type, key: String, value: String) -> URLRequest? {
return baseRequest(endpoint: endpoint.Endpoint, key: key, value: value, method: .delete)
}
/// Returns a `DELETE` URLRequest for the supplied URL
func deleteRequest(for object: Endpoint, key: String, value: String) -> URLRequest? {
return baseRequest(endpoint: object.endpoint, key: key, value: value, method: .delete)
}
}
| mit | 1851554c50cf17f643da24634243aef8 | 35.869048 | 117 | 0.67856 | 4.850431 | false | false | false | false |
MvanDiemen/olery-mariokart | Olery Kart/PlayerOverViewController.swift | 1 | 1629 | import Foundation
import UIKit
import CoreData
class PlayerOverViewController:UIViewController {
@IBOutlet var name:UILabel?
@IBOutlet var games:UILabel?
@IBOutlet var score:UILabel?
@IBOutlet var maxScore:UILabel?
@IBOutlet var mkei:UILabel?
@IBOutlet var first:UILabel?
@IBOutlet var second:UILabel?
@IBOutlet var third:UILabel?
@IBOutlet var fourth:UILabel?
var mGames:Int = 0
var mMaxScore:Int = 0
var mScore:Int = 0
var mName:String = ""
var mFirst:Int = 0
var mSecond:Int = 0
var mThird:Int = 0
var mFourth:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
self.modalPresentationStyle = .CurrentContext
self.modalPresentationStyle = .FormSheet
name?.text = mName
games?.text = "\(mGames)"
maxScore?.text = "\(mMaxScore)"
score?.text = "\(mScore)"
var index = Float(mScore) / Float(mMaxScore)
var percentage = Int(round(index * 100))
mkei?.text = "\(percentage)"
first?.text = "\(mFirst)"
second?.text = "\(mSecond)"
third?.text = "\(mThird)"
fourth?.text = "\(mFourth)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setNumbers(newGames:Int, newMaxScore:Int, newScore:Int, newName:String) {
mGames = newGames
mMaxScore = newMaxScore
mScore = newScore
mName = newName
}
func setPlaces(newFirst:Int, newSecond:Int, newThird:Int, newFourth:Int) {
mFirst = newFirst
mSecond = newSecond
mThird = newThird
mFourth = newFourth
}
} | mit | 859ca9ab986934e7cd3850566ffd5345 | 24.873016 | 80 | 0.658072 | 3.727689 | false | false | false | false |
bannzai/ResourceKit | Sources/ResourceKitCore/Storyboard/ViewController/ViewControllerOutput.swift | 1 | 10053 | //
// ViewControllerOutput.swift
// ResourceKit
//
// Created by Yudai.Hirose on 2017/09/23.
// Copyright © 2017年 kingkong999yhirose. All rights reserved.
//
import Foundation
public protocol ViewControllerOutput: Output {
}
public struct ViewControllerOutputImpl: ViewControllerOutput {
let name: String
let storyboardInfos: [ViewControllerInfoOfStoryboard]
let hasSuperClass: Bool
let superClassStoryboardInfos: [ViewControllerInfoOfStoryboard]
let config: Config
public fileprivate(set) var declaration: String = ""
var seguesForGenerateStruct: [String] {
return storyboardInfos.flatMap { $0.segues }
}
init(
name: String,
storyboardInfos: [ViewControllerInfoOfStoryboard],
hasSuperClass: Bool,
superClassStoryboardInfos: [ViewControllerInfoOfStoryboard],
config: Config
) {
self.name = name
self.storyboardInfos = storyboardInfos
self.hasSuperClass = hasSuperClass
self.superClassStoryboardInfos = superClassStoryboardInfos
self.config = config
self.declaration = generateDeclarationIfStoryboardInfoExists()
}
}
// MARK: - Private
fileprivate extension ViewControllerOutputImpl {
func generateDeclarationIfStoryboardInfoExists() -> String {
if storyboardInfos.isEmpty {
return ""
}
return generateDeclaration()
}
func generateDeclaration() -> String {
let begin = "extension \(name) {" + Const.newLine
let viewControllerAndPerformSegueFunctions = storyboardInfos
.flatMap {
let viewControllerFunctions = generateForInsitantiateViewController(from: $0)
let performSeguesFunctions = generateForPerformSegue(from: $0)
if viewControllerFunctions.isEmpty {
return performSeguesFunctions.appendNewLineIfNotEmpty()
}
if performSeguesFunctions.isEmpty {
return viewControllerFunctions.appendNewLineIfNotEmpty()
}
return viewControllerFunctions.appendNewLineIfNotEmpty().appendNewLineIfNotEmpty()
+ performSeguesFunctions.appendNewLineIfNotEmpty().appendNewLineIfNotEmpty()
}
.joined()
let segueStruct = generateForSegueStruct()
let body = viewControllerAndPerformSegueFunctions + segueStruct.appendNewLineIfNotEmpty()
let end = "}" + Const.newLine
return [begin, body, end].joined().appendNewLineIfNotEmpty()
}
func generateForSegueStruct() -> String {
if !config.segue.standard {
return ""
}
if seguesForGenerateStruct.isEmpty {
return ""
}
let begin = "\(Const.tab1)public struct Segue {"
let body: String = seguesForGenerateStruct
.flatMap {
"\(Const.tab2)public static let \($0.lowerFirst): String = \"\($0)\""
}
.joined(separator: Const.newLine)
let end = "\(Const.tab1)}"
return [begin, body, end].joined(separator: Const.newLine)
}
func generateForInsitantiateViewController(from storyboard: ViewControllerInfoOfStoryboard) -> String {
if !config.viewController.instantiateStoryboardAny {
return ""
}
return storyboard.isInitial ? fromStoryboardForInitial(from: storyboard) : fromStoryboard(from: storyboard)
}
func generateForPerformSegue(from storyboard: ViewControllerInfoOfStoryboard) -> String {
if !config.needGenerateSegue {
return ""
}
return generatePerformSegues(from: storyboard)
}
func generatePerformSegues(from storyboard: ViewControllerInfoOfStoryboard) -> String {
if !config.needGenerateSegue {
return ""
}
if storyboard.segues.isEmpty {
return ""
}
if seguesForGenerateStruct.isEmpty {
return ""
}
return seguesForGenerateStruct
.flatMap {
generatePerformSegue(from: storyboard, and: $0)
}
.joined(separator: Const.newLine)
}
func generatePerformSegue(from storyboard: ViewControllerInfoOfStoryboard, and segueIdentifier: String) -> String {
let overrideOrNil = makeOverrideIfNeededForPerformSegue(from: storyboard)
let overrideOrObjC = overrideOrNil == nil ? "@objc " : overrideOrNil! + " "
let head = "\(Const.tab1)\(overrideOrObjC)"
if config.segue.addition {
return [
"\(head)open func performSegue\(segueIdentifier)(closure: ((UIStoryboardSegue) -> Void)? = nil) {",
"\(Const.tab2)performSegue(\"\(segueIdentifier)\", closure: closure)",
"\(Const.tab1)}",
]
.joined(separator: Const.newLine)
}
return [
"\(head)open func performSegue\(segueIdentifier)(sender: AnyObject? = nil) {",
"\(Const.tab2)performSegue(withIdentifier: \"\(segueIdentifier)\", sender: sender)",
"\(Const.tab1)}",
]
.joined(separator: Const.newLine)
}
func fromStoryboard(from storyboard: ViewControllerInfoOfStoryboard) -> String {
if storyboard.storyboardIdentifier.isEmpty {
return ""
}
let overrideOrNil = makeOverrideIfNeededForFromStoryboardFunction(from: storyboard)
let overrideOrObjC = overrideOrNil == nil ? "@objc " : overrideOrNil! + " "
let head = "\(Const.tab1)\(overrideOrObjC)open class func "
if storyboardInfos.filter({ $0.storyboardName == storyboard.storyboardName }).count > 1 {
return [
head + "instanceFrom\(storyboard.storyboardName + storyboard.storyboardIdentifier)() -> \(name) {",
"\(Const.tab2)let storyboard = UIStoryboard(name: \"\(storyboard.storyboardName)\", bundle: nil) ",
"\(Const.tab2)let viewController = storyboard.instantiateViewController(withIdentifier: \"\(storyboard.storyboardIdentifier)\") as! \(name)",
"\(Const.tab2)return viewController",
"\(Const.tab1)}"
]
.joined(separator: Const.newLine)
}
return [
head + "instanceFrom\(storyboard.storyboardName)() -> \(name) {",
"\(Const.tab2)let storyboard = UIStoryboard(name: \"\(storyboard.storyboardName)\", bundle: nil) ",
"\(Const.tab2)let viewController = storyboard.instantiateViewController(withIdentifier: \"\(storyboard.storyboardIdentifier)\") as! \(name)",
"\(Const.tab2)return viewController",
"\(Const.tab1)}",
]
.joined(separator: Const.newLine)
}
func fromStoryboardForInitial(from storyboard: ViewControllerInfoOfStoryboard) -> String {
let overrideOrNil = makeOverrideIfNeededForFromStoryboardFunction(from: storyboard)
let overrideOrObjC = overrideOrNil == nil ? "@objc " : overrideOrNil! + " "
let head = "\(Const.tab1)\(overrideOrObjC)open class func "
if storyboardInfos.filter ({ $0.isInitial }).count > 1 {
return [
head + "initialFrom\(storyboard.storyboardName)() -> \(name) {",
"\(Const.tab2)let storyboard = UIStoryboard(name: \"\(storyboard.storyboardName)\", bundle: nil) ",
"\(Const.tab2)let viewController = storyboard.instantiateInitialViewController() as! \(name)",
"\(Const.tab2)return viewController",
"\(Const.tab1)}"
]
.joined(separator: Const.newLine)
}
return [
head + "initialViewController() -> \(name) {",
"\(Const.tab2)let storyboard = UIStoryboard(name: \"\(storyboard.storyboardName)\", bundle: nil) ",
"\(Const.tab2)let viewController = storyboard.instantiateInitialViewController() as! \(name)",
"\(Const.tab2)return viewController",
"\(Const.tab1)}"
]
.joined(separator: Const.newLine)
}
func needOverrideForStoryboard(_ storyboard: ViewControllerInfoOfStoryboard) -> Bool {
if !hasSuperClass {
return false
}
// For initialViewController()
let hasInitialOfSuperClass = superClassStoryboardInfos.filter({ $0.isInitial }).count > 0
let needOverrideForInitial = hasInitialOfSuperClass && storyboard.isInitial
if needOverrideForInitial {
return true
}
if storyboard.storyboardIdentifier.isEmpty {
return false
}
// For not initialViewController()
let storyboardsForIsNotInitial = superClassStoryboardInfos.filter({ !$0.isInitial })
return storyboardsForIsNotInitial.filter({ $0.storyboardName == storyboard.storyboardName }).count > 1
}
func needOverrideForSegue(_ storyboard: ViewControllerInfoOfStoryboard) -> Bool {
if !hasSuperClass {
return false
}
let superClassSegues = superClassStoryboardInfos.flatMap { $0.segues }
let segues = storyboardInfos.flatMap { $0.segues }
return superClassSegues.contains { superClassSegue in
segues.contains { segue in
segue == superClassSegue
}
}
}
func makeOverrideIfNeededForFromStoryboardFunction(from storyboard: ViewControllerInfoOfStoryboard) -> String? {
return needOverrideForStoryboard(storyboard) ? "override" : nil
}
func makeOverrideIfNeededForPerformSegue(from storyboard: ViewControllerInfoOfStoryboard) -> String? {
return needOverrideForSegue(storyboard) ? "override" : nil
}
}
| mit | 36bf86d32497e47c9eca92b0cb2aa63a | 38.72332 | 157 | 0.610547 | 5.245303 | false | false | false | false |
huangboju/Moots | Examples/Lumia/Lumia/Component/Transitions/PhotoTransitioning/AssetTransitionDriver.swift | 1 | 16104 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The AssetTransitionDriver class manages the transition from start to finish. This object will live the lifetime of the transition, and
is resposible for driving the interactivity and animation. It utilizes UIViewPropertyAnimator to smoothly interact and interrupt the
transition.
*/
import UIKit
class AssetTransitionDriver: NSObject {
var transitionAnimator: UIViewPropertyAnimator!
var isInteractive: Bool { return transitionContext.isInteractive }
let transitionContext: UIViewControllerContextTransitioning
private let operation: UINavigationController.Operation
private let panGestureRecognizer: UIPanGestureRecognizer
private var itemFrameAnimator: UIViewPropertyAnimator?
private var items: Array<AssetTransitionItem> = []
private var interactiveItem: AssetTransitionItem?
// MARK: Initialization
init(operation: UINavigationController.Operation, context: UIViewControllerContextTransitioning, panGestureRecognizer panGesture: UIPanGestureRecognizer) {
self.transitionContext = context
self.operation = operation
self.panGestureRecognizer = panGesture
super.init()
// Setup the transition "chrome"
let fromViewController = context.viewController(forKey: .from)!
let toViewController = context.viewController(forKey: .to)!
let fromAssetTransitioning = (fromViewController as! AssetTransitioning)
let toAssetTransitioning = (toViewController as! AssetTransitioning)
let fromView = fromViewController.view!
let toView = toViewController.view!
let containerView = context.containerView
// Add ourselves as a target of the pan gesture
self.panGestureRecognizer.addTarget(self, action: #selector(updateInteraction))
// Ensure the toView has the correct size and position
toView.frame = context.finalFrame(for: toViewController)
// Create a visual effect view and animate the effect in the transition animator
let effect: UIVisualEffect? = (operation == .pop) ? UIBlurEffect(style: .extraLight) : nil
let targetEffect: UIVisualEffect? = (operation == .pop) ? nil : UIBlurEffect(style: .light)
let visualEffectView = UIVisualEffectView(effect: effect)
visualEffectView.frame = containerView.bounds
visualEffectView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
containerView.addSubview(visualEffectView)
// Insert the toViewController's view into the transition container view
let topView: UIView
var topViewTargetAlpha: CGFloat = 0.0
if operation == .push {
topView = toView
topViewTargetAlpha = 1.0
toView.alpha = 0.0
containerView.addSubview(toView)
} else {
topView = fromView
topViewTargetAlpha = 0.0
containerView.insertSubview(toView, at: 0)
}
// Initiate the handshake between view controller, per the AssetTransitioning Protocol
self.items = fromAssetTransitioning.itemsForTransition(context: context).filter({ (item) -> Bool in
guard let targetFrame = toAssetTransitioning.targetFrame(transitionItem: item), !targetFrame.isEmpty && !targetFrame.isNull && !targetFrame.isInfinite else {
return false
}
item.targetFrame = containerView.convert(targetFrame, from: toView)
item.imageView = {
let imageView = UIImageView(frame: containerView.convert(item.initialFrame, from: nil))
imageView.clipsToBounds = true
imageView.contentMode = .scaleAspectFill
imageView.isUserInteractionEnabled = true
imageView.image = item.image
let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(press(_ :)))
longPressGestureRecognizer.minimumPressDuration = 0.0
imageView.addGestureRecognizer(longPressGestureRecognizer)
containerView.addSubview(imageView)
return imageView
}()
return true
})
// Inform the view controller's the transition is about to start
fromAssetTransitioning.willTransition(fromController: fromViewController, toController: toViewController, items: items)
toAssetTransitioning.willTransition(fromController: fromViewController, toController: toViewController, items: items)
// Add animations and completion to the transition animator
self.setupTransitionAnimator({
topView.alpha = topViewTargetAlpha
visualEffectView.effect = targetEffect
}, transitionCompletion: { [unowned self] (position) in
// Finish the protocol handshake
fromAssetTransitioning.didTransition(fromController: fromViewController, toController: toViewController, items: self.items)
toAssetTransitioning.didTransition(fromController: fromViewController, toController: toViewController, items: self.items)
// Remove all transition views
for item in self.items {
item.imageView?.removeFromSuperview()
}
visualEffectView.removeFromSuperview()
})
if context.isInteractive {
// If the transition is initially interactive, ensure we know what item is being manipulated
self.updateInteractiveItemFor(panGestureRecognizer.location(in: containerView))
} else {
// Begin the animation phase immediately if the transition is not initially interactive
animate(.end)
}
}
// MARK: Private Helpers
private func updateInteractiveItemFor(_ locationInContainer: CGPoint) {
func itemAtPoint(point: CGPoint) -> AssetTransitionItem? {
if let view = transitionContext.containerView.hitTest(point, with: nil) {
for item in self.items {
if item.imageView == view {
return item
}
}
}
return nil
}
if let item = itemAtPoint(point: locationInContainer), let itemCenter = item.imageView?.center {
item.touchOffset = (locationInContainer - itemCenter).vector
interactiveItem = item
}
}
private func convert(_ velocity: CGPoint, for item: AssetTransitionItem?) -> CGVector {
guard let currentFrame = item?.imageView?.frame, let targetFrame = item?.targetFrame else {
return CGVector.zero
}
let dx = abs(targetFrame.midX - currentFrame.midX)
let dy = abs(targetFrame.midY - currentFrame.midY)
guard dx > 0.0 && dy > 0.0 else {
return CGVector.zero
}
let range = CGFloat(35.0)
let clippedVx = clip(-range, range, velocity.x / dx)
let clippedVy = clip(-range, range, velocity.y / dy)
return CGVector(dx: clippedVx, dy: clippedVy)
}
private func timingCurveVelocity() -> CGVector {
// Convert the gesture recognizer's velocity into the initial velocity for the animation curve
let gestureVelocity = panGestureRecognizer.velocity(in: transitionContext.containerView)
return convert(gestureVelocity, for: interactiveItem)
}
private func completionPosition() -> UIViewAnimatingPosition {
let completionThreshold: CGFloat = 0.33
let flickMagnitude: CGFloat = 1200 //pts/sec
let velocity = panGestureRecognizer.velocity(in: transitionContext.containerView).vector
let isFlick = (velocity.magnitude > flickMagnitude)
let isFlickDown = isFlick && (velocity.dy > 0.0)
let isFlickUp = isFlick && (velocity.dy < 0.0)
if (operation == .push && isFlickUp) || (operation == .pop && isFlickDown) {
return .end
} else if (operation == .push && isFlickDown) || (operation == .pop && isFlickUp) {
return .start
} else if transitionAnimator.fractionComplete > completionThreshold {
return .end
} else {
return .start
}
}
private func updateItemsForInteractive(translation: CGPoint) {
let progressStep = progressStepFor(translation: translation)
for item in items {
let initialSize = item.initialFrame.size
if let imageView = item.imageView, let finalSize = item.targetFrame?.size {
let currentSize = imageView.frame.size
let itemPercentComplete = clip(-0.05, 1.05, (currentSize.width - initialSize.width) / (finalSize.width - initialSize.width) + progressStep)
let itemWidth = lerp(initialSize.width, finalSize.width, itemPercentComplete)
let itemHeight = lerp(initialSize.height, finalSize.height, itemPercentComplete)
let scaleTransform = CGAffineTransform(scaleX: (itemWidth / currentSize.width), y: (itemHeight / currentSize.height))
let scaledOffset = item.touchOffset.apply(transform: scaleTransform)
imageView.center = (imageView.center + (translation.add(rhs: item.touchOffset.subtract(rhs: scaledOffset)))).point
imageView.bounds = CGRect(origin: .zero, size: CGSize(width: itemWidth, height: itemHeight))
item.touchOffset = scaledOffset
}
}
}
private func progressStepFor(translation: CGPoint) -> CGFloat {
return (operation == .push ? -1.0 : 1.0) * translation.y / transitionContext.containerView.bounds.midY
}
// MARK: Gesture Callbacks
@objc func press(_ longPressGesture: UILongPressGestureRecognizer) {
switch longPressGesture.state {
case .began:
pauseAnimation()
updateInteractiveItemFor(longPressGesture.location(in: transitionContext.containerView))
case .ended, .cancelled:
endInteraction()
default: break
}
}
// MARK: Interesting UIViewPropertyAnimator Setup
/// UIKit calls startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning)
/// on our interaction controller (AssetTransitionController). The AssetTransitionDriver (self) is
/// then created with the transitionContext to manage the transition. It calls this func from Init().
func setupTransitionAnimator(_ transitionAnimations: @escaping ()->(), transitionCompletion: @escaping (UIViewAnimatingPosition)->()) {
// The duration of the transition, if uninterrupted
let transitionDuration = AssetTransitionDriver.animationDuration()
// Create a UIViewPropertyAnimator that lives the lifetime of the transition
transitionAnimator = UIViewPropertyAnimator(duration: transitionDuration, curve: .easeOut, animations: transitionAnimations)
transitionAnimator.addCompletion { [unowned self] (position) in
// Call the supplied completion
transitionCompletion(position)
// Inform the transition context that the transition has completed
let completed = (position == .end)
self.transitionContext.completeTransition(completed)
}
}
// MARK: Interesting Interruptible Transitioning Stuff
@objc func updateInteraction(_ fromGesture: UIPanGestureRecognizer) {
switch fromGesture.state {
case .began, .changed:
// Ask the gesture recognizer for it's translation
let translation = fromGesture.translation(in: transitionContext.containerView)
// Calculate the percent complete
let percentComplete = transitionAnimator.fractionComplete + progressStepFor(translation: translation)
// Update the transition animator's fractionCompete to scrub it's animations
transitionAnimator.fractionComplete = percentComplete
// Inform the transition context of the updated percent complete
transitionContext.updateInteractiveTransition(percentComplete)
// Update each transition item for the
updateItemsForInteractive(translation: translation)
// Reset the gestures translation
fromGesture.setTranslation(CGPoint.zero, in: transitionContext.containerView)
case .ended, .cancelled:
// End the interactive phase of the transition
endInteraction()
default: break
}
}
func endInteraction() {
// Ensure the context is currently interactive
guard transitionContext.isInteractive else { return }
// Inform the transition context of whether we are finishing or cancelling the transition
let completionPosition = self.completionPosition()
if completionPosition == .end {
transitionContext.finishInteractiveTransition()
} else {
transitionContext.cancelInteractiveTransition()
}
// Begin the animation phase of the transition to either the start or finsh position
animate(completionPosition)
}
func animate(_ toPosition: UIViewAnimatingPosition) {
// Create a property animator to animate each image's frame change
let itemFrameAnimator = AssetTransitionDriver.propertyAnimator(initialVelocity: timingCurveVelocity())
itemFrameAnimator.addAnimations {
for item in self.items {
item.imageView?.frame = (toPosition == .end ? item.targetFrame : item.initialFrame)!
}
}
// Start the property animator and keep track of it
itemFrameAnimator.startAnimation()
self.itemFrameAnimator = itemFrameAnimator
// Reverse the transition animator if we are returning to the start position
transitionAnimator.isReversed = (toPosition == .start)
// Start or continue the transition animator (if it was previously paused)
if transitionAnimator.state == .inactive {
transitionAnimator.startAnimation()
} else {
// Calculate the duration factor for which to continue the animation.
// This has been chosen to match the duration of the property animator created above
let durationFactor = CGFloat(itemFrameAnimator.duration / transitionAnimator.duration)
transitionAnimator.continueAnimation(withTimingParameters: nil, durationFactor: durationFactor)
}
}
func pauseAnimation() {
// Stop (without finishing) the property animator used for transition item frame changes
itemFrameAnimator?.stopAnimation(true)
// Pause the transition animator
transitionAnimator.pauseAnimation()
// Inform the transition context that we have paused
transitionContext.pauseInteractiveTransition()
}
// MARK: Interesting Property Animator Stuff
class func animationDuration() -> TimeInterval {
return AssetTransitionDriver.propertyAnimator().duration
}
class func propertyAnimator(initialVelocity: CGVector = .zero) -> UIViewPropertyAnimator {
let timingParameters = UISpringTimingParameters(mass: 4.5, stiffness: 1300, damping: 95, initialVelocity: initialVelocity)
return UIViewPropertyAnimator(duration: assetTransitionDuration, timingParameters:timingParameters)
}
}
| mit | e7997f9ba164e9a00d90d6ddea8b00dc | 45.944606 | 169 | 0.653708 | 5.891694 | false | false | false | false |
STShenZhaoliang/iOS-GuidesAndSampleCode | 精通Swift设计模式/Chapter 17/SportsStore/SportsStore/ProductDataStore.swift | 3 | 3863 | import Foundation
final class ProductDataStore {
var callback:((Product) -> Void)?;
private var networkQ:dispatch_queue_t
private var uiQ:dispatch_queue_t;
lazy var products:[Product] = self.loadData();
init() {
networkQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
uiQ = dispatch_get_main_queue();
}
private func loadData() -> [Product] {
var products = [Product]();
for product in productData {
var p:Product = LowStockIncreaseDecorator(product: product);
if (p.category == "Soccer") {
p = SoccerDecreaseDecorator(product: p);
}
dispatch_async(self.networkQ, {() in
let stockConn = NetworkPool.getConnection();
let level = stockConn.getStockLevel(p.name);
if (level != nil) {
p.stockLevel = level!;
dispatch_async(self.uiQ, {() in
if (self.callback != nil) {
self.callback!(p);
}
})
}
NetworkPool.returnConnecton(stockConn);
});
products.append(p);
}
return products;
}
private var productData:[Product] = [
ProductComposite(name: "Running Pack",
description: "Complete Running Outfit", category: "Running",
stockLevel: 10, products:
Product.createProduct("Shirt", description: "Running Shirt",
category: "Running", price: 42, stockLevel: 10),
Product.createProduct("Shorts", description: "Running Shorts",
category: "Running", price: 30, stockLevel: 10),
Product.createProduct("Shoes", description: "Running Shoes",
category: "Running", price: 120, stockLevel: 10),
ProductComposite(name: "Headgear", description: "Hat, etc",
category: "Running", stockLevel: 10, products:
Product.createProduct("Hat", description: "Running Hat",
category: "Running", price: 10, stockLevel: 10),
Product.createProduct("Sunglasses", description: "Glasses",
category: "Running", price: 10, stockLevel: 10))
),
Product.createProduct("Kayak", description:"A boat for one person",
category:"Watersports", price:275.0, stockLevel:0),
Product.createProduct("Lifejacket",
description:"Protective and fashionable",
category:"Watersports", price:48.95, stockLevel:0),
Product.createProduct("Soccer Ball",
description:"FIFA-approved size and weight",
category:"Soccer", price:19.5, stockLevel:0),
Product.createProduct("Corner Flags",
description:"Give your playing field a professional touch",
category:"Soccer", price:34.95, stockLevel:0),
Product.createProduct("Stadium",
description:"Flat-packed 35,000-seat stadium",
category:"Soccer", price:79500.0, stockLevel:0),
Product.createProduct("Thinking Cap",
description:"Improve your brain efficiency",
category:"Chess", price:16.0, stockLevel:0),
Product.createProduct("Unsteady Chair",
description:"Secretly give your opponent a disadvantage",
category: "Chess", price: 29.95, stockLevel:0),
Product.createProduct("Human Chess Board",
description:"A fun game for the family",
category:"Chess", price:75.0, stockLevel:0),
Product.createProduct("Bling-Bling King",
description:"Gold-plated, diamond-studded King",
category:"Chess", price:1200.0, stockLevel:0)];
}
| mit | cad6ae6dd7098c96fba568e4712e4dd8 | 43.402299 | 84 | 0.568211 | 4.798758 | false | false | false | false |
debugsquad/nubecero | nubecero/Model/HomeUpload/MHomeUploadItemStatusUploaded.swift | 1 | 1922 | import UIKit
class MHomeUploadItemStatusUploaded:MHomeUploadItemStatus
{
private let kAssetSync:String = "assetHomeSyncUploading"
private let kFinished:Bool = false
private let kSelectable:Bool = true
init(item:MHomeUploadItem?)
{
let reusableIdentifier:String = VHomeUploadCellActive.reusableIdentifier
let color:UIColor = UIColor.black
super.init(
reusableIdentifier:reusableIdentifier,
item:item,
assetSync:kAssetSync,
finished:kFinished,
selectable:kSelectable,
color:color)
}
override init(
reusableIdentifier:String,
item:MHomeUploadItem?,
assetSync:String,
finished:Bool,
selectable:Bool,
color:UIColor)
{
fatalError()
}
override func process(controller:CHomeUploadSync)
{
super.process(controller:controller)
guard
let userId:MSession.UserId = MSession.sharedInstance.user.userId,
let photoId:String = item?.photoId
else
{
let errorName:String = NSLocalizedString("MHomeUploadItemStatusLoaded_errorUser", comment:"")
controller.errorSyncing(error:errorName)
return
}
let parentUser:String = FDatabase.Parent.user.rawValue
let propertyPhotos:String = FDatabaseModelUser.Property.photos.rawValue
let propertyStatus:String = FDatabaseModelPhoto.Property.status.rawValue
let pathStatus:String = "\(parentUser)/\(userId)/\(propertyPhotos)/\(photoId)/\(propertyStatus)"
let status:Int = MPhotos.Status.synced.rawValue
FMain.sharedInstance.database.updateChild(
path:pathStatus,
json:status)
item?.statusSynced()
controller.keepSyncing()
}
}
| mit | bbf19f07d456a520ebf63f65b35aa463 | 29.507937 | 105 | 0.620708 | 5.180593 | false | false | false | false |
GiorgioNatili/CryptoMessages | CryptoMessages/messages/services/LocalMessagesService.swift | 1 | 3180 | //
// LocalMessagesService.swift
// CryptoMessages
//
// Created by Giorgio Natili on 5/8/17.
// Copyright © 2017 Giorgio Natili. All rights reserved.
//
import Foundation
import RxSwift
class LocalMessageService: MessagesService {
let gateway: LocalStorageGateway
init(localStorageGateway: LocalStorageGateway) {
self.gateway = localStorageGateway
}
// MARK: - MessagesService implementation
func allMessages() -> Observable<[EncryptedMessage]> {
return Observable.create { observer in
do {
let messages = try self.gateway.manageAccessToContext(handler: self.gateway.fetchMessagesOnLocalStorage())
observer.onNext(messages)
observer.onCompleted()
} catch let fetchError as FetchError {
observer.onError(fetchError)
} catch let error as NSError {
let fetchError = FetchError(details: error.userInfo.description, errorCode: error.code)
observer.onError(fetchError)
}
return Disposables.create()
}
}
func saveMessage(content: String, password: String) -> Observable<EncryptedMessage> {
return Observable.create { observer in
do {
let newMessage = try self.gateway.manageAccessToContext(handler: self.gateway.saveMessageOnLocalStorage(content: content, password: password))
observer.onNext(newMessage)
observer.onCompleted()
} catch let fetchError as FetchError {
observer.onError(fetchError)
} catch let error as NSError {
let fetchError = FetchError(details: error.userInfo.description, errorCode: error.code)
observer.onError(fetchError)
}
return Disposables.create()
}
}
func updateMessage(message: EncryptedMessage) -> Observable<EncryptedMessage> {
return Observable.create { observer in
do {
let newMessage = try self.gateway.manageAccessToContext(handler: self.gateway.updateMessageOnLocalStorage(message: message))
observer.onNext(newMessage)
observer.onCompleted()
} catch let fetchError as FetchError {
observer.onError(fetchError)
} catch let error as NSError {
let fetchError = FetchError(details: error.userInfo.description, errorCode: error.code)
observer.onError(fetchError)
}
return Disposables.create()
}
}
func getMessage(id: Int) -> Observable<EncryptedMessage> {
// TODO read the local data and return the object
return Observable.from(optional: EncryptedMessage())
}
}
| unlicense | 19d76eb8196c52de6422adaaf98761be | 31.111111 | 158 | 0.551431 | 6.009452 | false | false | false | false |
atrick/swift | stdlib/public/Concurrency/AsyncStream.swift | 1 | 16989 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
/// An asynchronous sequence generated from a closure that calls a continuation
/// to produce new elements.
///
/// `AsyncStream` conforms to `AsyncSequence`, providing a convenient way to
/// create an asynchronous sequence without manually implementing an
/// asynchronous iterator. In particular, an asynchronous stream is well-suited
/// to adapt callback- or delegation-based APIs to participate with
/// `async`-`await`.
///
/// You initialize an `AsyncStream` with a closure that receives an
/// `AsyncStream.Continuation`. Produce elements in this closure, then provide
/// them to the stream by calling the continuation's `yield(_:)` method. When
/// there are no further elements to produce, call the continuation's
/// `finish()` method. This causes the sequence iterator to produce a `nil`,
/// which terminates the sequence. The continuation conforms to `Sendable`, which permits
/// calling it from concurrent contexts external to the iteration of the
/// `AsyncStream`.
///
/// An arbitrary source of elements can produce elements faster than they are
/// consumed by a caller iterating over them. Because of this, `AsyncStream`
/// defines a buffering behavior, allowing the stream to buffer a specific
/// number of oldest or newest elements. By default, the buffer limit is
/// `Int.max`, which means the value is unbounded.
///
/// ### Adapting Existing Code to Use Streams
///
/// To adapt existing callback code to use `async`-`await`, use the callbacks
/// to provide values to the stream, by using the continuation's `yield(_:)`
/// method.
///
/// Consider a hypothetical `QuakeMonitor` type that provides callers with
/// `Quake` instances every time it detects an earthquake. To receive callbacks,
/// callers set a custom closure as the value of the monitor's
/// `quakeHandler` property, which the monitor calls back as necessary.
///
/// class QuakeMonitor {
/// var quakeHandler: ((Quake) -> Void)?
///
/// func startMonitoring() {…}
/// func stopMonitoring() {…}
/// }
///
/// To adapt this to use `async`-`await`, extend the `QuakeMonitor` to add a
/// `quakes` property, of type `AsyncStream<Quake>`. In the getter for this
/// property, return an `AsyncStream`, whose `build` closure -- called at
/// runtime to create the stream -- uses the continuation to perform the
/// following steps:
///
/// 1. Creates a `QuakeMonitor` instance.
/// 2. Sets the monitor's `quakeHandler` property to a closure that receives
/// each `Quake` instance and forwards it to the stream by calling the
/// continuation's `yield(_:)` method.
/// 3. Sets the continuation's `onTermination` property to a closure that
/// calls `stopMonitoring()` on the monitor.
/// 4. Calls `startMonitoring` on the `QuakeMonitor`.
///
/// ```
/// extension QuakeMonitor {
///
/// static var quakes: AsyncStream<Quake> {
/// AsyncStream { continuation in
/// let monitor = QuakeMonitor()
/// monitor.quakeHandler = { quake in
/// continuation.yield(quake)
/// }
/// continuation.onTermination = { @Sendable _ in
/// monitor.stopMonitoring()
/// }
/// monitor.startMonitoring()
/// }
/// }
/// }
/// ```
///
/// Because the stream is an `AsyncSequence`, the call point can use the
/// `for`-`await`-`in` syntax to process each `Quake` instance as the stream
/// produces it:
///
/// for await quake in QuakeMonitor.quakes {
/// print ("Quake: \(quake.date)")
/// }
/// print ("Stream finished.")
///
@available(SwiftStdlib 5.1, *)
public struct AsyncStream<Element> {
/// A mechanism to interface between synchronous code and an asynchronous
/// stream.
///
/// The closure you provide to the `AsyncStream` in
/// `init(_:bufferingPolicy:_:)` receives an instance of this type when
/// invoked. Use this continuation to provide elements to the stream by
/// calling one of the `yield` methods, then terminate the stream normally by
/// calling the `finish()` method.
///
/// - Note: Unlike other continuations in Swift, `AsyncStream.Continuation`
/// supports escaping.
public struct Continuation: Sendable {
/// A type that indicates how the stream terminated.
///
/// The `onTermination` closure receives an instance of this type.
public enum Termination {
/// The stream finished as a result of calling the continuation's
/// `finish` method.
case finished
/// The stream finished as a result of cancellation.
case cancelled
}
/// A type that indicates the result of yielding a value to a client, by
/// way of the continuation.
///
/// The various `yield` methods of `AsyncStream.Continuation` return this
/// type to indicate the success or failure of yielding an element to the
/// continuation.
public enum YieldResult {
/// The stream successfully enqueued the element.
///
/// This value represents the successful enqueueing of an element, whether
/// the stream buffers the element or delivers it immediately to a pending
/// call to `next()`. The associated value `remaining` is a hint that
/// indicates the number of remaining slots in the buffer at the time of
/// the `yield` call.
///
/// - Note: From a thread safety point of view, `remaining` is a lower bound
/// on the number of remaining slots. This is because a subsequent call
/// that uses the `remaining` value could race on the consumption of
/// values from the stream.
case enqueued(remaining: Int)
/// The stream didn't enqueue the element because the buffer was full.
///
/// The associated element for this case is the element dropped by the stream.
case dropped(Element)
/// The stream didn't enqueue the element because the stream was in a
/// terminal state.
///
/// This indicates the stream terminated prior to calling `yield`, either
/// because the stream finished normally or through cancellation.
case terminated
}
/// A strategy that handles exhaustion of a buffer’s capacity.
public enum BufferingPolicy {
/// Continue to add to the buffer, without imposing a limit on the number
/// of buffered elements.
case unbounded
/// When the buffer is full, discard the newly received element.
///
/// This strategy enforces keeping at most the specified number of oldest
/// values.
case bufferingOldest(Int)
/// When the buffer is full, discard the oldest element in the buffer.
///
/// This strategy enforces keeping at most the specified number of newest
/// values.
case bufferingNewest(Int)
}
let storage: _Storage
/// Resume the task awaiting the next iteration point by having it return
/// normally from its suspension point with a given element.
///
/// - Parameter value: The value to yield from the continuation.
/// - Returns: A `YieldResult` that indicates the success or failure of the
/// yield operation.
///
/// If nothing is awaiting the next value, this method attempts to buffer the
/// result's element.
///
/// This can be called more than once and returns to the caller immediately
/// without blocking for any awaiting consumption from the iteration.
@discardableResult
public func yield(_ value: __owned Element) -> YieldResult {
storage.yield(value)
}
/// Resume the task awaiting the next iteration point by having it return
/// nil, which signifies the end of the iteration.
///
/// Calling this function more than once has no effect. After calling
/// finish, the stream enters a terminal state and doesn't produces any additional
/// elements.
public func finish() {
storage.finish()
}
/// A callback to invoke when canceling iteration of an asynchronous
/// stream.
///
/// If an `onTermination` callback is set, using task cancellation to
/// terminate iteration of an `AsyncStream` results in a call to this
/// callback.
///
/// Canceling an active iteration invokes the `onTermination` callback
/// first, then resumes by yielding `nil`. This means that you can perform
/// needed cleanup in the cancellation handler. After reaching a terminal
/// state as a result of cancellation, the `AsyncStream` sets the callback
/// to `nil`.
public var onTermination: (@Sendable (Termination) -> Void)? {
get {
return storage.getOnTermination()
}
nonmutating set {
storage.setOnTermination(newValue)
}
}
}
final class _Context {
let storage: _Storage?
let produce: () async -> Element?
init(storage: _Storage? = nil, produce: @escaping () async -> Element?) {
self.storage = storage
self.produce = produce
}
deinit {
storage?.cancel()
}
}
let context: _Context
/// Constructs an asynchronous stream for an element type, using the
/// specified buffering policy and element-producing closure.
///
/// - Parameters:
/// - elementType: The type of element the `AsyncStream` produces.
/// - bufferingPolicy: A `Continuation.BufferingPolicy` value to
/// set the stream's buffering behavior. By default, the stream buffers an
/// unlimited number of elements. You can also set the policy to buffer a
/// specified number of oldest or newest elements.
/// - build: A custom closure that yields values to the
/// `AsyncStream`. This closure receives an `AsyncStream.Continuation`
/// instance that it uses to provide elements to the stream and terminate the
/// stream when finished.
///
/// The `AsyncStream.Continuation` received by the `build` closure is
/// appropriate for use in concurrent contexts. It is thread safe to send and
/// finish; all calls to the continuation are serialized. However, calling
/// this from multiple concurrent contexts could result in out-of-order
/// delivery.
///
/// The following example shows an `AsyncStream` created with this
/// initializer that produces 100 random numbers on a one-second interval,
/// calling `yield(_:)` to deliver each element to the awaiting call point.
/// When the `for` loop exits, the stream finishes by calling the
/// continuation's `finish()` method.
///
/// let stream = AsyncStream<Int>(Int.self,
/// bufferingPolicy: .bufferingNewest(5)) { continuation in
/// Task.detached {
/// for _ in 0..<100 {
/// await Task.sleep(1 * 1_000_000_000)
/// continuation.yield(Int.random(in: 1...10))
/// }
/// continuation.finish()
/// }
/// }
///
/// // Call point:
/// for await random in stream {
/// print ("\(random)")
/// }
///
public init(
_ elementType: Element.Type = Element.self,
bufferingPolicy limit: Continuation.BufferingPolicy = .unbounded,
_ build: (Continuation) -> Void
) {
let storage: _Storage = .create(limit: limit)
context = _Context(storage: storage, produce: storage.next)
build(Continuation(storage: storage))
}
/// Constructs an asynchronous stream from a given element-producing
/// closure, with an optional closure to handle cancellation.
///
/// - Parameters:
/// - produce: A closure that asynchronously produces elements for the
/// stream.
/// - onCancel: A closure to execute when canceling the stream's task.
///
/// Use this convenience initializer when you have an asynchronous function
/// that can produce elements for the stream, and don't want to invoke
/// a continuation manually. This initializer "unfolds" your closure into
/// an asynchronous stream. The created stream handles conformance
/// to the `AsyncSequence` protocol automatically, including termination
/// (either by cancellation or by returning `nil` from the closure to finish
/// iteration).
///
/// The following example shows an `AsyncStream` created with this
/// initializer that produces random numbers on a one-second interval. This
/// example uses the Swift multiple trailing closure syntax, which omits
/// the `unfolding` parameter label.
///
/// let stream = AsyncStream<Int> {
/// await Task.sleep(1 * 1_000_000_000)
/// return Int.random(in: 1...10)
/// }
/// onCancel: { @Sendable () in print ("Canceled.") }
/// )
///
/// // Call point:
/// for await random in stream {
/// print ("\(random)")
/// }
///
///
public init(
unfolding produce: @escaping () async -> Element?,
onCancel: (@Sendable () -> Void)? = nil
) {
let storage: _AsyncStreamCriticalStorage<Optional<() async -> Element?>>
= .create(produce)
context = _Context {
return await withTaskCancellationHandler {
guard let result = await storage.value?() else {
storage.value = nil
return nil
}
return result
} onCancel: {
storage.value = nil
onCancel?()
}
}
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncStream: AsyncSequence {
/// The asynchronous iterator for iterating an asynchronous stream.
///
/// This type doesn't conform to `Sendable`. Don't use it from multiple
/// concurrent contexts. It is a programmer error to invoke `next()` from a
/// concurrent context that contends with another such call, which
/// results in a call to `fatalError()`.
public struct Iterator: AsyncIteratorProtocol {
let context: _Context
/// The next value from the asynchronous stream.
///
/// When `next()` returns `nil`, this signifies the end of the
/// `AsyncStream`.
///
/// It is a programmer error to invoke `next()` from a
/// concurrent context that contends with another such call, which
/// results in a call to `fatalError()`.
///
/// If you cancel the task this iterator is running in while `next()` is
/// awaiting a value, the `AsyncStream` terminates. In this case, `next()`
/// might return `nil` immediately, or return `nil` on subsequent calls.
public mutating func next() async -> Element? {
await context.produce()
}
}
/// Creates the asynchronous iterator that produces elements of this
/// asynchronous sequence.
public func makeAsyncIterator() -> Iterator {
return Iterator(context: context)
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncStream.Continuation {
/// Resume the task awaiting the next iteration point by having it return
/// normally from its suspension point with a given result's success value.
///
/// - Parameter result: A result to yield from the continuation.
/// - Returns: A `YieldResult` that indicates the success or failure of the
/// yield operation.
///
/// If nothing is awaiting the next value, the method attempts to buffer the
/// result's element.
///
/// If you call this method repeatedly, each call returns immediately, without
/// blocking for any awaiting consumption from the iteration.
@discardableResult
public func yield(
with result: Result<Element, Never>
) -> YieldResult {
switch result {
case .success(let val):
return storage.yield(val)
}
}
/// Resume the task awaiting the next iteration point by having it return
/// normally from its suspension point.
///
/// - Returns: A `YieldResult` that indicates the success or failure of the
/// yield operation.
///
/// Use this method with `AsyncStream` instances whose `Element` type is
/// `Void`. In this case, the `yield()` call unblocks the awaiting
/// iteration; there is no value to return.
///
/// If you call this method repeatedly, each call returns immediately, without
/// blocking for any awaiting consumption from the iteration.
@discardableResult
public func yield() -> YieldResult where Element == Void {
return storage.yield(())
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncStream: @unchecked Sendable where Element: Sendable { }
| apache-2.0 | 9027eedfd14e00688bea302bd7084887 | 38.221709 | 95 | 0.64806 | 4.735917 | false | false | false | false |
qq456cvb/DeepLearningKitForiOS | iOSDeepLearningKitApp/iOSDeepLearningKitApp/iOSDeepLearningKitApp/ViewController.swift | 1 | 11777 | //
// ViewController.swift
// iOSDeepLearningKitApp
//
// Created by Amund Tveit on 13/02/16.
// Copyright © 2016 DeepLearningKit. All rights reserved.
//
import UIKit
import CoreGraphics
import AVFoundation
public class AtomicBoolean {
private var val: UInt8 = 0
public init(initialValue: Bool) {
self.val = (initialValue == false ? 0 : 1)
}
public func getAndSet(value: Bool) -> Bool {
if value {
return OSAtomicTestAndSet(7, &val)
} else {
return OSAtomicTestAndClear(7, &val)
}
}
public func get() -> Bool {
return val != 0
}
}
class ViewController: UIViewController, UIImagePickerControllerDelegate,
UINavigationControllerDelegate, AVCaptureVideoDataOutputSampleBufferDelegate {
@IBOutlet weak var chooseBtn: UIButton!
@IBOutlet weak var imageView: UIImageView!
var deepNetwork: DeepNetwork!
let imagePicker = UIImagePickerController()
let path = Bundle.main.path(forResource: "yolo_tiny", ofType: "bson")!
let imageShape:[Float] = [1.0, 3.0, 448.0, 448.0]
let cameraSession = AVCaptureSession()
let caching_mode = false
var loaded = false
var frame_done = AtomicBoolean.init(initialValue: true)
@IBAction func start(_ sender: Any) {
cameraSession.sessionPreset = AVCaptureSessionPresetMedium
let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) as AVCaptureDevice
do {
let deviceInput = try AVCaptureDeviceInput(device: captureDevice)
cameraSession.beginConfiguration() // 1
if (cameraSession.canAddInput(deviceInput) == true) {
cameraSession.addInput(deviceInput)
}
let dataOutput = AVCaptureVideoDataOutput() // 2
dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString) : NSNumber(value: kCVPixelFormatType_32BGRA as UInt32)] // 3
dataOutput.alwaysDiscardsLateVideoFrames = true // 4
if (cameraSession.canAddOutput(dataOutput) == true) {
cameraSession.addOutput(dataOutput)
}
cameraSession.commitConfiguration() //5
let queue = DispatchQueue(label: "video") // 6
dataOutput.setSampleBufferDelegate(self, queue: queue) // 7
cameraSession.startRunning()
}
catch let error as NSError {
NSLog("\(error), \(error.localizedDescription)")
}
}
func imageFromSampleBuffer(sampleBuffer : CMSampleBuffer) -> UIImage
{
// Get a CMSampleBuffer's Core Video image buffer for the media data
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
// Lock the base address of the pixel buffer
CVPixelBufferLockBaseAddress(imageBuffer!, CVPixelBufferLockFlags.readOnly);
// Get the number of bytes per row for the pixel buffer
let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer!);
// Get the number of bytes per row for the pixel buffer
let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer!);
// Get the pixel buffer width and height
let width = CVPixelBufferGetWidth(imageBuffer!);
let height = CVPixelBufferGetHeight(imageBuffer!);
// Create a device-dependent RGB color space
let colorSpace = CGColorSpaceCreateDeviceRGB();
// Create a bitmap graphics context with the sample buffer data
var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Little.rawValue
bitmapInfo |= CGImageAlphaInfo.premultipliedFirst.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
//let bitmapInfo: UInt32 = CGBitmapInfo.alphaInfoMask.rawValue
let context = CGContext.init(data: baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo)
// Create a Quartz image from the pixel data in the bitmap graphics context
let quartzImage = context?.makeImage();
// Unlock the pixel buffer
CVPixelBufferUnlockBaseAddress(imageBuffer!, CVPixelBufferLockFlags.readOnly);
// Create an image object from the Quartz image
let image = UIImage.init(cgImage: quartzImage!, scale: 1.0, orientation: .down);
return (image);
}
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
if frame_done.get() {
_ = self.frame_done.getAndSet(value: false)
let captured = self.imageFromSampleBuffer(sampleBuffer: sampleBuffer)
DispatchQueue.global().async {
let resized = self.resizeImage(image: captured, newWidth: CGFloat(self.imageShape[3]), newHeight: CGFloat(self.imageShape[2]))
let (r, g, b, _) = imageToMatrix(resized)
var image = b + g + r
for (i, _) in image.enumerated() {
image[i] /= 255
}
self.deepNetwork.loadDeepNetworkFromBSON(self.path, inputImage: image, inputShape: self.imageShape, caching_mode:self.caching_mode)
// 1. classify image (of cat)
self.deepNetwork.yoloDetect(captured, imageView: self.imageView)
_ = self.frame_done.getAndSet(value: true)
}
}
}
func resizeImage(image: UIImage, newWidth: CGFloat, newHeight: CGFloat) -> UIImage {
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
@IBAction func imageChoosen(_ sender: Any) {
imagePicker.allowsEditing = false
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print(info.debugDescription)
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
// imageView.contentMode = .scaleAspectFit
imageView.image = pickedImage
}
// DispatchQueue.global().async {
// let resized = self.resizeImage(image: self.imageView.image!, newWidth: CGFloat(self.imageShape[3]), newHeight: CGFloat(self.imageShape[2]))
//
// // print(resized.size.width)
//
// let (r, g, b, _) = imageToMatrix(resized)
// var image = b + g + r
// for (i, _) in image.enumerated() {
// image[i] /= 255
// }
// self.deepNetwork.loadDeepNetworkFromBSON(self.path, inputImage: image, inputShape: self.imageShape, caching_mode:self.caching_mode)
//
// // 1. classify image (of cat)
// self.deepNetwork.yoloDetect(image, imageView: self.imageView)
// }
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
imagePicker.delegate = self
imageView.image = #imageLiteral(resourceName: "lena")
deepNetwork = DeepNetwork()
}
override func viewDidAppear(_ animated: Bool) {
// conv1.json contains a cifar 10 image of a cat
// let conv1Layer = deepNetwork.loadJSONFile("conv1")!
// let image: [Float] = conv1Layer["input"] as! [Float]
//
// _ = UIImage(named: "lena")
// //shows a tiny (32x32) CIFAR 10 image on screen
// showCIFARImage(image)
// var randomimage = createFloatNumbersArray(image.count)
// for i in 0..<randomimage.count {
// randomimage[i] = Float(arc4random_uniform(1000))
// }
// **********************comment out below to debug at launch time ******************//
// let imageCount = Int(imageShape.reduce(1, *))
//
// let resizeLena = resizeImage(image: #imageLiteral(resourceName: "lena"), newWidth: 448.0, newHeight: 448.0)
// let (r, g, b, _) = imageToMatrix(resizeLena)
// var image = b + g + r
// for (i, _) in image.enumerated() {
// image[i] /= 255
// }
// print(image.max()!)
//
// var randomimage = createFloatNumbersArray(imageCount)
// for i in 0..<randomimage.count {
// randomimage[i] = Float(1.0)
// }
//
// // 0. load network in network model
// deepNetwork.loadDeepNetworkFromBSON(path, inputImage: image, inputShape: imageShape, caching_mode:caching_mode)
//
// // 1. classify image (of cat)
// deepNetwork.yoloDetect(image, imageView: imageView)
// deepNetwork.loadDeepNetworkFromBSON(path, inputImage: randomimage, inputShape: imageShape, caching_mode:caching_mode)
// deepNetwork.classify(randomimage)
// **********************comment out above to debug at launch time ******************//
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//***********************************************************************************
func showCIFARImage(_ cifarImageData:[Float]) {
var cifarImageData = cifarImageData
let size = CGSize(width: 32, height: 32)
let rect = CGRect(origin: CGPoint(x: 0,y: 0), size: size)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
UIColor.white.setFill() // or custom color
UIRectFill(rect)
var image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// CIFAR 10 images are 32x32 in 3 channels - RGB
// it is stored as 3 sequences of 32x32 = 1024 numbers in cifarImageData, i.e.
// red: numbers from position 0 to 1024 (not inclusive)
// green: numbers from position 1024 to 2048 (not inclusive)
// blue: numbers from position 2048 to 3072 (not inclusive)
for i in 0..<32 {
for j in 0..<32 {
let r = UInt8(cifarImageData[i*32 + j])
let g = UInt8(cifarImageData[32*32 + i*32 + j])
let b = UInt8(cifarImageData[2*32*32 + i*32 + j])
// used to set pixels - RGBA into an UIImage
// for more info about RGBA check out https://en.wikipedia.org/wiki/RGBA_color_space
image = image?.setPixelColorAtPoint(CGPoint(x: j,y: i), color: UIImage.RawColorType(r,g,b,255))!
// used to read pixels - RGBA from an UIImage
_ = image?.getPixelColorAtLocation(CGPoint(x:i, y:j))
}
}
print(image?.size ?? CGSize(width: 0, height: 0))
// Displaying original image.
let originalImageView:UIImageView = UIImageView(frame: CGRect(x: 20, y: 20, width: image!.size.width, height: image!.size.height))
originalImageView.image = image
self.view.addSubview(originalImageView)
}
}
| apache-2.0 | d23c9236242595bfd977d6311a8eb217 | 40.174825 | 175 | 0.597826 | 4.818331 | false | false | false | false |
jtaxen/FindShelter | FindShelter/Model/SpatialServiceExtension.swift | 1 | 5454 | //
// SpatialServiceExtension.swift
// FindShelter
//
// Created by ÅF Jacob Taxén on 2017-05-23.
// Copyright © 2017 Jacob Taxén. All rights reserved.
//
import Foundation
import CoreLocation
extension SpatialService {
func convertUTMToLatLon(north y: Double, east X: Double) -> CLLocationCoordinate2D {
let x = (X - falseEasting)/k0
let phi1 = footpointLatitude(y)
let t = tan(phi1)
let eta2 = ( a - b ) * ( a + b ) / ( b * b ) * ( 1 + cos(2 * phi1) ) / 2
let gamma = t * ( 1 + eta2 )
let nu = a / sqrt( 1 - e2 * ( 1 - cos(2 * phi1) ) / 2 )
let beta = x / nu
let beta2 = beta**2
let P = -gamma / 2
let Q = (gamma/24) * ( (5 + 3 * (t**2) ) + ( eta2 - 4 * (eta2**2) ) - 9 * (t**2) * eta2 )
let r1 = ( 61 + 90 * (t**2) + 45 * (t**4) )
let r2 = ( 46 * eta2 - 3 * (eta2**2) + 100 * (eta2**3) + 88 * (eta2**4) )
let r3 = ( 252 * (t**2) * eta2 + 66 * (t**2) * (eta2**2) - 84 * (t**2) * (eta2**3) + 192 * (t**2) * (eta2**4) )
let r4 = ( 90 * (t**4) * (eta2*2) - 225 * (t**4) * (eta2**2) )
let R = ( -gamma/720 ) * ( r1 + r2 - r3 - r4 )
let S = ( gamma / 40320 ) * (1385 + 3633 * (t**2) + 4095 * (t**4) + 1575 * (t**6) )
let T = ( -1/6 ) * ( 1 + 2 * (t**2) + eta2 )
let u1 = ( 5 + 28 * (t**2) + 24 * (t**4) )
let u2 = ( 6 * eta2 - 3 * (eta2**2) - 4 * (eta2**3) )
let u3 = ( 8 * (t**2) * eta2 + 4 * (t**2) * (eta2**2) + 24 * (t**2) * (eta2**3) )
let U = ( 1/120 ) * ( u1 + u2 + u3 )
let V = ( -1/5040 ) * ( 61 + (t**2) * ( 662 + (t**2) * ( 1320 + 720 * (t**2) ) ) )
let phi = phi1 + beta2 * ( P + beta2 * ( Q + beta2 * ( R + S * beta2 ) ) )
let deltaLambda = ( beta/cos(phi1) ) * ( 1 + beta2 * ( T + beta2 * ( U + beta2 * V ) ) )
let lambda = longitudeFromDeltaLambda(deltaLambda, X)
return CLLocationCoordinate2D(latitude: degree(phi), longitude: degree(lambda))
}
func convertLatLonToUTM(point: CLLocationCoordinate2D) -> (Double, Double) {
let phi = radian(point.latitude)
let lambda = radian(point.longitude)
let nu = a / sqrt( 1 - e2 * ( 1 - cos(2 * phi) ) / 2 )
let t = tan(phi)
let s = sin(phi)
let c = cos(phi)
let eta2 = (a**2) * ( 1 + cos(2*phi) ) * e2 / ( 2 * (b**2) )
let A = nu * c
let B = ( nu/6 ) * (c**3) * ( 1 - (t**2) + eta2)
let c1 = ( 5 - 18 * (t**2) + (t**4) )
let c2 = ( 14 * eta2 + 13 * (eta2**2) + 4 * (eta2**3) )
let c3 = ( 58 * (t**2) * eta2 + 64 * (t**2) * (eta2**2) + 24 * (t**2) * (eta2**3) )
let C = ( nu/120 ) * (c**5) * ( c1 + c2 - c3 )
let D = ( nu/5040 ) * (c**7) * ( 61 - 479 * (t**2) + 179 * (t**4) - (t**6) )
let F = ( nu/2 ) * s * c
let G = ( nu/24 ) * s * (c**3) * ( ( 5 - (t**2) ) + ( 9 * eta2 + 4 * (eta2**2) ) )
let h1 = ( 61 - 58 * (t**2) + (t**4) )
let h2 = ( 270 * eta2 + 445 * (eta2**2) + 324 * (eta2**3) + 88 * (eta2**4) )
let h3 = ( 330 * (t**2) * (eta2) + 680 * (t**2) * (eta2**2) + 600 * (t**2) * (eta2**3) + 192 * (t**2) * (eta2**4) )
let H = ( nu/720 ) * s * (c**5) * ( h1 + h2 - h3 )
let I = ( nu/40320 ) * s * (c**7) * ( 1385 - 3111 * (t**2) + 543 * (t**4) - (t**6) )
let deltaLambda = deltaLambdaFromLongitude(lambda, radian(Double(midmeridian)))
let M = meridionalArc(phi)
let X = A * (deltaLambda) + B * (deltaLambda**3) + C * (deltaLambda)**5 + D * (deltaLambda**7)
let Y = M + F * (deltaLambda**2) + G * (deltaLambda**4) + H * (deltaLambda**6) + I * (deltaLambda**8)
let E = eastUTM(fromTM : X, lambda, radian(midmeridian))
let N = Y * k0
return (N,E)
}
}
// MARK: - Helper functions
internal extension SpatialService {
func meridionalArc(_ phi: Double) -> Double {
let A = a * ( 1 + n * ( -1 + (n**2) * ( 5 * ( 1 - n) / 4 + (n**2) * ( 81 * ( 1 - n ) / 64 ))))
let B = ( 3 * n * a / 2 ) * ( 1 + n * ( -1 + n * ( 7/8 + n * -7/8 + 55 * n / 64 )))
let C = (15 * (n**2) * a / 16) * ( 1 + n * ( -1 + n * ( 3/4 - 3 * n / 4)))
let D = (35 * (n**3) * a / 48 ) * ( 1 + n * ( -1 + 11 * n / 16))
let E = (315 * (n**4) * a / 512) * (1 - n)
return (A * phi - B * sin(2*phi) + C * sin(4*phi) - D * sin(6*phi) + E * sin(8*phi))
}
func footpointLatitude(_ y: Double, accuracy: Double = 1e-8) -> Double {
let c = b / ( a * a * A0 )
var phi = c * y
var M = meridionalArc(phi) * k0
while abs( M - y ) > accuracy {
phi += c * ( y - M )
M = meridionalArc(phi) * k0
}
return phi
}
func longitudeFromDeltaLambda(_ deltaLambda: Double, _ x: Double) -> Double {
if x < 500000 {
return radian(midmeridian) - abs(deltaLambda)
} else {
return radian(midmeridian) + abs(deltaLambda)
}
}
func deltaLambdaFromLongitude( _ longitude: Double,_ midmeridian: Double) -> Double {
if longitude < midmeridian {
return longitude - midmeridian
} else {
return midmeridian - longitude
}
}
func eastUTM(fromTM x: Double, _ longitude: Double, _ midmeridian: Double) -> Double {
if longitude > midmeridian {
return falseEasting + abs( k0 * x )
} else {
return falseEasting - abs( k0 * x )
}
}
}
| mit | 3104f39e371bde2f38f1d763dd7bf19e | 35.824324 | 126 | 0.446422 | 2.448338 | false | false | false | false |
zisko/swift | test/SILOptimizer/outliner.swift | 1 | 8970 | // RUN: %target-swift-frontend -Osize -import-objc-header %S/Inputs/Outliner.h %s -emit-sil | %FileCheck %s
// RUN: %target-swift-frontend -Osize -g -import-objc-header %S/Inputs/Outliner.h %s -emit-sil | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
public class MyGizmo {
private var gizmo : Gizmo
private var optionalGizmo : Gizmo?
init() {
gizmo = Gizmo()
}
// CHECK-LABEL: sil @$S8outliner7MyGizmoC11usePropertyyyF
// CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC14stringPropertySSSgvgToTeab_
// CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@in_guaranteed Gizmo) -> @owned Optional<String>
// CHECK-NOT: return
// CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@in_guaranteed Gizmo) -> @owned Optional<String>
// CHECK: return
public func useProperty() {
print(gizmo.stringProperty)
print(optionalGizmo!.stringProperty)
}
}
// CHECK-LABEL: sil @$S8outliner13testOutliningyyF
// CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC14stringPropertySSSgvgToTepb_
// CHECK: apply [[FUN]](%{{.*}}) : $@convention(thin) (Gizmo) -> @owned Optional<String>
// CHECK: apply [[FUN]](%{{.*}}) : $@convention(thin) (Gizmo) -> @owned Optional<String>
// CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC14stringPropertySSSgvsToTembnn_
// CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Gizmo) -> ()
// CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Gizmo) -> ()
// CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC12modifyString_10withNumber0D6FoobarSSSgAF_SiypSgtFToTembnnnb_
// CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String>
// CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String>
// CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC11doSomethingyypSgSaySSGSgFToTembnn_
// CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject>
// CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject>
// CHECK: return
public func testOutlining() {
let gizmo = Gizmo()
let foobar = Gizmo()
print(gizmo.stringProperty)
print(gizmo.stringProperty)
gizmo.stringProperty = "foobar"
gizmo.stringProperty = "foobar2"
gizmo.modifyString("hello", withNumber:1, withFoobar: foobar)
gizmo.modifyString("hello", withNumber:1, withFoobar: foobar)
let arr = [ "foo", "bar"]
gizmo.doSomething(arr)
gizmo.doSomething(arr)
}
// CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC14stringPropertySSSgvgToTeab_ : $@convention(thin) (@in_guaranteed Gizmo) -> @owned Optional<String>
// CHECK: bb0(%0 : $*Gizmo):
// CHECK: %1 = load %0 : $*Gizmo
// CHECK: %2 = objc_method %1 : $Gizmo, #Gizmo.stringProperty!getter.1.foreign : (Gizmo) -> () -> String?
// CHECK: %3 = apply %2(%1) : $@convention(objc_method) (Gizmo) -> @autoreleased Optional<NSString>
// CHECK: switch_enum %3 : $Optional<NSString>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2
// CHECK: bb1(%5 : $NSString):
// CHECK: %6 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
// CHECK: %7 = metatype $@thin String.Type
// CHECK: %8 = apply %6(%3, %7) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
// CHECK: %9 = enum $Optional<String>, #Optional.some!enumelt.1, %8 : $String
// CHECK: br bb3(%9 : $Optional<String>)
// CHECK: bb2:
// CHECK: %11 = enum $Optional<String>, #Optional.none!enumelt
// CHECK: br bb3(%11 : $Optional<String>)
// CHECK: bb3(%13 : $Optional<String>):
// CHECK: return %13 : $Optional<String>
// CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC14stringPropertySSSgvgToTepb_ : $@convention(thin) (Gizmo) -> @owned Optional<String>
// CHECK: bb0(%0 : $Gizmo):
// CHECK: %1 = objc_method %0 : $Gizmo, #Gizmo.stringProperty!getter.1.foreign : (Gizmo) -> () -> String?
// CHECK: %2 = apply %1(%0) : $@convention(objc_method) (Gizmo) -> @autoreleased Optional<NSString>
// CHECK: switch_enum %2 : $Optional<NSString>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2
// CHECK:bb1(%4 : $NSString):
// CHECK: %5 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
// CHECK: %6 = metatype $@thin String.Type
// CHECK: %7 = apply %5(%2, %6) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
// CHECK: %8 = enum $Optional<String>, #Optional.some!enumelt.1, %7 : $String
// CHECK: br bb3(%8 : $Optional<String>)
// CHECK:bb2:
// CHECK: %10 = enum $Optional<String>, #Optional.none!enumelt
// CHECK: br bb3(%10 : $Optional<String>)
// CHECK:bb3(%12 : $Optional<String>):
// CHECK: return %12 : $Optional<String>
// CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC14stringPropertySSSgvsToTembnn_ : $@convention(thin) (@owned String, Gizmo) -> () {
// CHECK: bb0(%0 : $String, %1 : $Gizmo):
// CHECK: %2 = objc_method %1 : $Gizmo, #Gizmo.stringProperty!setter.1.foreign : (Gizmo) -> (String?) -> ()
// CHECK: %3 = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK: %4 = apply %3(%0) : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK: release_value %0 : $String
// CHECK: %6 = enum $Optional<NSString>, #Optional.some!enumelt.1, %4 : $NSString
// CHECK: %7 = apply %2(%6, %1) : $@convention(objc_method) (Optional<NSString>, Gizmo) -> ()
// CHECK: strong_release %4 : $NSString
// CHECK: return %7 : $()
// CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC12modifyString_10withNumber0D6FoobarSSSgAF_SiypSgtFToTembnnnb_ : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String> {
// CHECK: bb0(%0 : $String, %1 : $Int, %2 : $Optional<AnyObject>, %3 : $Gizmo):
// CHECK: %4 = objc_method %3 : $Gizmo, #Gizmo.modifyString!1.foreign : (Gizmo) -> (String?, Int, Any?) -> String?
// CHECK: %5 = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK: %6 = apply %5(%0) : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK: release_value %0 : $String
// CHECK: %8 = enum $Optional<NSString>, #Optional.some!enumelt.1, %6 : $NSString
// CHECK: %9 = apply %4(%8, %1, %2, %3) : $@convention(objc_method) (Optional<NSString>, Int, Optional<AnyObject>, Gizmo) -> @autoreleased Optional<NSString>
// CHECK: strong_release %6 : $NSString
// CHECK: switch_enum %9 : $Optional<NSString>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1
//
// CHECK: bb1:
// CHECK: %12 = enum $Optional<String>, #Optional.none!enumelt
// CHECK: br bb3(%12 : $Optional<String>)
//
// CHECK: bb2(%14 : $NSString):
// CHECK: %15 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
// CHECK: %16 = metatype $@thin String.Type
// CHECK: %17 = apply %15(%9, %16) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String
// CHECK: %18 = enum $Optional<String>, #Optional.some!enumelt.1, %17 : $String
// CHECK: br bb3(%18 : $Optional<String>)
//
// CHECK: bb3(%20 : $Optional<String>):
// CHECK: return %20 : $Optional<String>
// CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC11doSomethingyypSgSaySSGSgFToTembnn_ : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject> {
// CHECK: bb0(%0 : $Array<String>, %1 : $Gizmo):
// CHECK: %2 = objc_method %1 : $Gizmo, #Gizmo.doSomething!1.foreign : (Gizmo) -> ([String]?) -> Any?
// CHECK: %3 = function_ref @$SSa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF : $@convention(method) <{{.*}}> (@guaranteed Array<{{.*}}>) -> @owned NSArray
// CHECK: %4 = apply %3<String>(%0) : $@convention(method) <{{.*}}> (@guaranteed Array<{{.*}}>) -> @owned NSArray
// CHECK: release_value %0 : $Array<String>
// CHECK: %6 = enum $Optional<NSArray>, #Optional.some!enumelt.1, %4 : $NSArray
// CHECK: %7 = apply %2(%6, %1) : $@convention(objc_method) (Optional<NSArray>, Gizmo) -> @autoreleased Optional<AnyObject>
// CHECK: strong_release %4 : $NSArray
// CHECK: return %7 : $Optional<AnyObject>
public func dontCrash<T: Proto>(x : Gizmo2<T>) {
let s = x.doSomething()
print(s)
}
public func dontCrash2(_ c: SomeGenericClass) -> Bool {
guard let str = c.version else {
return false
}
guard let str2 = c.doSomething() else {
return false
}
let arr = [ "foo", "bar"]
c.doSomething2(arr)
return true
}
| apache-2.0 | b0416e7f2815356a80a306f29f325d16 | 56.5 | 211 | 0.661315 | 3.263005 | false | false | false | false |
googlemaps/last-mile-fleet-solution-samples | ios_driverapp_samples/LMFSDriverSampleApp/ListTab/Details/TaskDetailsPage.swift | 1 | 2015 | /*
* Copyright 2022 Google LLC. All rights reserved.
*
* 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 GoogleMaps
import SwiftUI
/// This view defines the page we push to when the user taps on the arrow button
/// for a task in the stop list.
struct TaskDetailsPage: View {
@ObservedObject var task: ModelData.Task
@State var selectedMarker: GMSMarker?
@State var markers: [GMSMarker]
@State private var zoom: Float = 15
var body: some View {
VStack {
MapViewControllerBridge(
markers: $markers,
selectedMarker: $selectedMarker,
zoom: $zoom
)
.frame(height: 250)
HStack {
Spacer(minLength: 60)
TaskDetails(task: task)
}
Spacer()
}
.navigationTitle(task.taskInfo.plannedWaypoint.description)
.navigationBarTitleDisplayMode(.inline)
}
init(task: ModelData.Task, stop: ModelData.Stop) {
// Ensure Google Maps SDK is initialized.
let _ = LMFSDriverSampleApp.googleMapsInited
self.task = task
self.markers = [
CustomMarker.makeMarker(task: task, showLabel: false),
CustomMarker.makeMarker(stop: stop, showLabel: false),
]
self.selectedMarker = nil
}
}
struct TaskDetailsPage_Previews: PreviewProvider {
static var previews: some View {
let _ = LMFSDriverSampleApp.googleMapsInited
let modelData = ModelData(filename: "test_manifest")
let stop = modelData.stops[0]
TaskDetailsPage(task: modelData.tasks(stop: stop)[0], stop: stop)
}
}
| apache-2.0 | 737b8739652786cef818935d0116b9d4 | 29.530303 | 91 | 0.699752 | 4.146091 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/TableViewDataSources/AvatarDetailViewDataSource.swift | 1 | 8945 | //
// AvatarDetailViewDataSource.swift
// Habitica
//
// Created by Phillip Thelen on 20.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
class AvatarDetailViewDataSource: BaseReactiveCollectionViewDataSource<CustomizationProtocol> {
private let customizationRepository = CustomizationRepository()
private let userRepository = UserRepository()
var customizationGroup: String?
var customizationType: String
var purchaseSet: ((CustomizationSetProtocol) -> Void)?
private var ownedCustomizations: [OwnedCustomizationProtocol] = []
private var customizationSets: [String: CustomizationSetProtocol] = [:]
private var equippedKey: String?
private var preferences: PreferencesProtocol?
init(type: String, group: String?) {
self.customizationType = type
self.customizationGroup = group
super.init()
disposable.add(customizationRepository.getCustomizations(type: customizationType, group: customizationGroup)
.combineLatest(with: customizationRepository.getOwnedCustomizations(type: customizationType, group: customizationGroup))
.on(value: {[weak self](customizations, ownedCustomizations) in
self?.ownedCustomizations = ownedCustomizations.value
self?.configureSections(customizations.value)
}).start())
disposable.add(userRepository.getUser().on(value: {[weak self]user in
self?.preferences = user.preferences
self?.updateEquippedKey(user: user)
self?.collectionView?.reloadData()
}).start())
}
func updateEquippedKey(user: UserProtocol) {
switch customizationType {
case "shirt":
equippedKey = user.preferences?.shirt
case "skin":
equippedKey = user.preferences?.skin
case "chair":
equippedKey = user.preferences?.chair
case "hair":
switch customizationGroup {
case "bangs":
equippedKey = String(user.preferences?.hair?.bangs ?? 0)
case "base":
equippedKey = String(user.preferences?.hair?.base ?? 0)
case "mustache":
equippedKey = String(user.preferences?.hair?.mustache ?? 0)
case "beard":
equippedKey = String(user.preferences?.hair?.beard ?? 0)
case "color":
equippedKey = String(user.preferences?.hair?.color ?? "")
case "flower":
equippedKey = String(user.preferences?.hair?.flower ?? 0)
default:
return
}
default:
return
}
}
func owns(customization: CustomizationProtocol) -> Bool {
return ownedCustomizations.contains(where: { (ownedCustomization) -> Bool in
return ownedCustomization.key == customization.key
})
}
private func configureSections(_ customizations: [CustomizationProtocol]) {
customizationSets.removeAll()
sections.removeAll()
sections.append(ItemSection<CustomizationProtocol>())
for customization in customizations {
if customization.price > 0 && !customization.isPurchasable {
if !owns(customization: customization) {
continue
}
}
if let set = customization.set {
if let index = sections.firstIndex(where: { (section) -> Bool in
return section.key == set.key
}) {
sections[index].items.append(customization)
} else {
customizationSets[set.key ?? ""] = set
sections.append(ItemSection<CustomizationProtocol>(key: set.key, title: set.text))
sections.last?.items.append(customization)
}
} else {
sections[0].items.append(customization)
}
}
if customizationType == "background" {
sections = sections.filter({ section -> Bool in
return section.items.isEmpty == false
}).sorted { (firstSection, secondSection) -> Bool in
if firstSection.key?.contains("incentive") == true || firstSection.key?.contains("timeTravel") == true {
return true
} else if secondSection.key?.contains("incentive") == true || secondSection.key?.contains("timeTravel") == true {
return false
}
if let firstKey = firstSection.key?.replacingOccurrences(of: "backgrounds", with: ""), let secondKey = secondSection.key?.replacingOccurrences(of: "backgrounds", with: "") {
let firstIndex = firstKey.index(firstKey.startIndex, offsetBy: 2)
let firstMonth = Int(firstKey[..<firstIndex]) ?? 0
let firstYear = Int(firstKey[firstIndex...]) ?? 0
let secondIndex = secondKey.index(secondKey.startIndex, offsetBy: 2)
let secondMonth = Int(secondKey[..<secondIndex]) ?? 0
let secondYear = Int(secondKey[secondIndex...]) ?? 0
if firstYear == secondYear {
return firstMonth >= secondMonth
} else {
return firstYear >= secondYear
}
}
return firstSection.key ?? "" < secondSection.key ?? ""
}
}
self.collectionView?.reloadData()
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
if let customization = item(at: indexPath), let customizationCell = cell as? CustomizationDetailCell {
customizationCell.configure(customization: customization, preferences: preferences)
customizationCell.isCustomizationSelected = customization.key == equippedKey
customizationCell.currencyView.isHidden = customization.isPurchasable == false || owns(customization: customization)
if customization.set?.key?.contains("incentive") == true {
customizationCell.imageView.alpha = owns(customization: customization) ? 1.0 : 0.3
} else {
customizationCell.imageView.alpha = 1.0
}
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if let customization = item(at: indexPath) {
if customization.isPurchasable == true && !owns(customization: customization) {
if customization.type == "background" {
return CGSize(width: 106, height: 138)
} else {
return CGSize(width: 80, height: 108)
}
} else {
if customization.type == "background" {
return CGSize(width: 106, height: 106)
} else {
return CGSize(width: 80, height: 108)
}
}
}
return CGSize.zero
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let view = super.collectionView(collectionView, viewForSupplementaryElementOfKind: kind, at: indexPath)
let section = sections[indexPath.section]
if let headerView = view as? CustomizationHeaderView {
if let set = customizationSets[section.key ?? ""] {
headerView.configure(customizationSet: set, isBackground: customizationType == "background")
if set.setItems?.contains(where: { (customization) -> Bool in
return !self.owns(customization: customization)
}) == true && set.setPrice != 0 && set.key?.contains("timeTravel") != true && set.key?.contains("incentive") != true {
headerView.purchaseButton.isHidden = false
} else {
headerView.purchaseButton.isHidden = true
}
headerView.purchaseButtonTapped = {
if let action = self.purchaseSet {
action(set)
}
}
} else {
headerView.purchaseButton.isHidden = true
}
}
return view
}
}
| gpl-3.0 | f9dfb4e6059f6f31a4c561fb4feafe79 | 42.629268 | 189 | 0.575022 | 5.493857 | false | false | false | false |
radioboo/ListKitDemo | ListKitDemo/Stubs/SampleData.swift | 1 | 2763 | //
// SampleData.swift
// ListKitDemo
//
// Created by 酒井篤 on 2016/12/10.
// Copyright © 2016年 Atsushi Sakai. All rights reserved.
//
import UIKit
class SampleData {
class func createInitialDataSet() -> [Any] {
return [
RecommendFeed(),
UserHistory(users: allUsers()),
Feed(id: UUID().uuidString, user: allUsers()[0], comment: "はい…", image: UIImage(named: "IMG_005.jpg")!),
Feed(id: UUID().uuidString, user: allUsers()[4], comment: "おっさんそば食えや", image: UIImage(named: "IMG_005.jpg")!),
Feed(id: UUID().uuidString, user: allUsers()[3], comment: "またうどんか…", image: UIImage(named: "IMG_004.jpg")!),
Feed(id: UUID().uuidString, user: allUsers()[2], comment: "うどんたべすぎると糖尿病になるぞ!!!!!", image: UIImage(named: "IMG_003.jpg")!),
Feed(id: UUID().uuidString, user: allUsers()[1], comment: "昨日うどんたべた。今日もだべたい。", image: UIImage(named: "IMG_002.jpg")!),
Feed(id: UUID().uuidString, user: allUsers()[0], comment: "あったかいうどんたべたいなぁ", image: UIImage(named: "IMG_001.jpg")!),
] as [Any]
}
class func createRandomFeed() -> Feed {
return Feed(id: UUID().uuidString, user: randomUser(), comment: randomComment(), image: randomImage()!)
}
class func allUsers() -> [User] {
let radioboo = User(id: 1, nickname: "radioboo")
let ainame = User(id: 2, nickname: "ainame")
let punchdrunker = User(id: 3, nickname: "punchdrunker")
let sarukun = User(id: 4, nickname: "sarukun")
let sobataro = User(id: 5, nickname: "sobataro")
return [radioboo, ainame, punchdrunker, sarukun, sobataro]
}
class func randomUser() -> User {
let index = Int((arc4random_uniform(UInt32(allUsers().count))))
return allUsers()[index]
}
class func randomImage() -> UIImage? {
let images = [
UIImage(named: "IMG_001.jpg"),
UIImage(named: "IMG_002.jpg"),
UIImage(named: "IMG_003.jpg"),
UIImage(named: "IMG_004.jpg"),
UIImage(named: "IMG_005.jpg"),
]
let index = Int((arc4random_uniform(UInt32(images.count))))
return images[index]
}
class func randomComment() -> String {
let strings = [
"ズルズルっ!!!!!",
"そばうまい…!!!",
"小諸そばは梅干しが食えるので良い",
"しぶそばは新そば使ってるらしいぞ!?!?",
]
let index = Int((arc4random_uniform(UInt32(strings.count))))
return strings[index]
}
}
| mit | 6fdf364464e652e1ebee41b79a6503fc | 36.294118 | 134 | 0.566246 | 3.280724 | false | false | false | false |
NordicSemiconductor/IOS-nRF-Toolbox | nRF Toolbox/Profiles/Glucose/Cell/BGMTableViewCell.swift | 1 | 2792 | /*
* Copyright (c) 2020, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
class BGMTableViewCell: UITableViewCell {
@IBOutlet var dateLabel: UILabel!
@IBOutlet var placeLabel: UILabel!
@IBOutlet var valueLabel: UILabel!
@IBOutlet var unitLabel: UILabel!
func update(with reading: GlucoseReading) {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
dateLabel.text = dateFormatter.string(from: reading.timestamp as Date)
if reading.glucoseConcentrationTypeAndLocationPresent {
placeLabel.text = "\(reading.type!)"
switch reading.unit! {
case .mol_L:
valueLabel.text = String(format: "%.1f", reading.glucoseConcentration! * 1000) // mol/l -> mmol/l conversion
unitLabel.text = "mmol/l"
break
case .kg_L:
valueLabel.text = String(format: "%0f", reading.glucoseConcentration! * 100000) // kg/l -> mg/dl conversion
unitLabel.text = "mg/dl"
break
}
} else {
valueLabel.text = "-"
placeLabel.text = "Unavailable"
unitLabel.text = ""
}
}
}
| bsd-3-clause | c20f40f65db62ffdf88b46939c785cdc | 39.463768 | 126 | 0.686963 | 4.724196 | false | false | false | false |
smoope/swift-client-conversation | Framework/Source/ConversationView.swift | 1 | 7258 | //
// Copyright 2017 smoope GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
internal enum ConversationViewElementKind: String {
case headLoading = "head-loading"
case headText = "head-text"
case avatar = "avatar"
case detail = "detail"
case unknown = "unknown"
init(_ rawValue: RawValue) {
let value = ConversationViewElementKind(rawValue: rawValue)
self = value ?? .unknown
}
}
extension ConversationViewElementKind: ExpressibleByStringLiteral {
init(stringLiteral value: String) {
self.init(value)
}
init(unicodeScalarLiteral value: String) {
self.init(value)
}
init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
}
public class ConversationView: UICollectionView {
public dynamic var nativeBackgroundColor: UIColor? {
didSet {
nativeTextColor = nativeBackgroundColor?.legibleTextColor ?? .darkText
}
}
public dynamic var foreignBackgroundColor: UIColor? {
didSet {
foreignTextColor = foreignBackgroundColor?.legibleTextColor ?? .darkText
}
}
public dynamic var actionColor: UIColor? {
didSet {
tintColor = actionColor
actionTextColor = actionColor?.legibleTextColor ?? .white
}
}
public dynamic var isCalendarEventDetectorDisabled: Bool = false
internal var nativeTextColor: UIColor = .darkText
internal var foreignTextColor: UIColor = .darkText
internal var actionTextColor: UIColor = .white
internal var messageBackgroundImage: UIImage? = UIImage(named: "filled-background-16", in: Bundle(for: ConversationView.self), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate)
internal var messageBackgroundInset: UIEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
internal var isLoadingNew: Bool = false
internal var triggeredLoadNewCount: Int = 0
internal var isLoadingMore: Bool = false
internal var wasLoadingMore: Bool = false
// MARK: ui variables
internal var canLoadMore: Bool = true {
didSet {
guard canLoadMore != oldValue else { return }
collectionViewLayout.invalidateLayout()
}
}
internal var wasErrorOnLoadMore: Bool = false {
didSet {
guard wasErrorOnLoadMore != oldValue else { return }
collectionViewLayout.invalidateLayout()
}
}
internal var dataDetectorTypes: UIDataDetectorTypes = [.address, .calendarEvent, .link, .phoneNumber]
// MARK: -
internal override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
internal func commonInit() {
nativeBackgroundColor = ConversationView.appearance().nativeBackgroundColor
?? UIColor(colorLiteralRed: 0, green: 150/255, blue: 136/255, alpha: 1)
foreignBackgroundColor = ConversationView.appearance().foreignBackgroundColor
?? UIColor(white: 0.86, alpha: 1)
actionColor = ConversationView.appearance().actionColor
?? actionColor
?? tintColor
isCalendarEventDetectorDisabled = ConversationView.appearance().isCalendarEventDetectorDisabled
registerCellTypes()
reassingDataDetectorTypes()
}
internal func registerCellTypes() {
register(TextCell.self, forCellWithReuseIdentifier: "text")
register(PreviewCell.self, forCellWithReuseIdentifier: "preview")
register(FileCell.self, forCellWithReuseIdentifier: "file")
register(SingleChoiceCell.self, forCellWithReuseIdentifier: "smoope.choice.single")
register(URLButtonsCell.self, forCellWithReuseIdentifier: "smoope.url.buttons")
register(TextSupplementaryView.self,
forSupplementaryViewOfKind: ConversationViewElementKind.headText.rawValue,
withReuseIdentifier: ConversationViewElementKind.headText.rawValue)
register(LoadingSupplementaryView.self,
forSupplementaryViewOfKind: ConversationViewElementKind.headLoading.rawValue,
withReuseIdentifier: ConversationViewElementKind.headLoading.rawValue)
register(RoundAvatarSupplementaryView.self,
forSupplementaryViewOfKind: ConversationViewElementKind.avatar.rawValue,
withReuseIdentifier: ConversationViewElementKind.avatar.rawValue)
register(_MsgAuthorTimeSupplementaryView.self,
forSupplementaryViewOfKind: ConversationViewElementKind.detail.rawValue,
withReuseIdentifier: ConversationViewElementKind.detail.rawValue)
}
internal func reassingDataDetectorTypes() {
var types: UIDataDetectorTypes = [.address, .calendarEvent, .link, .phoneNumber]
isCalendarEventDetectorDisabled ? types.subtract(.calendarEvent) : types.formUnion(.calendarEvent)
dataDetectorTypes = types
}
internal func reloadDataWithoutMoving() {
reloadData()
layoutIfNeeded()
contentOffset = collectionViewLayout.targetContentOffset(forProposedContentOffset: contentOffset)
}
internal func scrollTo(indexPath: IndexPath, animated: Bool) {
guard let frame = layoutAttributesForSupplementaryElement(ofKind: "detail", at: indexPath)?.frame else { return }
scrollRectToVisible(frame, animated: animated)
}
internal func updateDetailLabels(_ indexPaths: [IndexPath]) {
for indexPath in indexPaths {
if let sup = supplementaryView(forElementKind: ConversationViewElementKind.detail.rawValue, at: indexPath) {
delegate?.collectionView?(self,
willDisplaySupplementaryView: sup,
forElementKind: ConversationViewElementKind.detail.rawValue,
at: indexPath)
}
}
}
}
internal protocol ConversationTrait {
var nativeBackgroundColor: UIColor? { get }
var foreignBackgroundColor: UIColor? { get }
var nativeTextColor: UIColor { get }
var foreignTextColor: UIColor { get }
var actionColor: UIColor? { get }
}
extension ConversationView: ConversationTrait { }
| apache-2.0 | e5750f47bba7e6d73a22abb77a12b260 | 34.404878 | 187 | 0.662166 | 5.600309 | false | false | false | false |
kaojohnny/CoreStore | Sources/Transactions/AsynchronousDataTransaction.swift | 1 | 9882 | //
// AsynchronousDataTransaction.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
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - AsynchronousDataTransaction
/**
The `AsynchronousDataTransaction` provides an interface for `NSManagedObject` creates, updates, and deletes. A transaction object should typically be only used from within a transaction block initiated from `DataStack.beginAsynchronous(_:)`, or from `CoreStore.beginAsynchronous(_:)`.
*/
public final class AsynchronousDataTransaction: BaseDataTransaction {
/**
Saves the transaction changes. This method should not be used after the `commit()` method was already called once.
- parameter completion: the block executed after the save completes. Success or failure is reported by the `SaveResult` argument of the block.
*/
public func commit(completion: (result: SaveResult) -> Void = { _ in }) {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to commit a \(cs_typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to commit a \(cs_typeName(self)) more than once."
)
self.isCommitted = true
let group = GCDGroup()
group.enter()
self.context.saveAsynchronouslyWithCompletion { (result) -> Void in
self.result = result
completion(result: result)
group.leave()
}
group.wait()
}
/**
Begins a child transaction synchronously where NSManagedObject creates, updates, and deletes can be made. This method should not be used after the `commit()` method was already called once.
- parameter closure: the block where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent `NSManagedObjectContext`.
- returns: a `SaveResult` value indicating success or failure, or `nil` if the transaction was not comitted synchronously
*/
public func beginSynchronous(closure: (transaction: SynchronousDataTransaction) -> Void) -> SaveResult? {
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to begin a child transaction from a \(cs_typeName(self)) outside its designated queue."
)
CoreStore.assert(
!self.isCommitted,
"Attempted to begin a child transaction from an already committed \(cs_typeName(self))."
)
return SynchronousDataTransaction(
mainContext: self.context,
queue: self.childTransactionQueue,
closure: closure).performAndWait()
}
// MARK: BaseDataTransaction
/**
Creates a new `NSManagedObject` with the specified entity type.
- parameter into: the `Into` clause indicating the destination `NSManagedObject` entity type and the destination configuration
- returns: a new `NSManagedObject` instance of the specified entity type.
*/
public override func create<T: NSManagedObject>(into: Into<T>) -> T {
CoreStore.assert(
!self.isCommitted,
"Attempted to create an entity of type \(cs_typeName(T)) from an already committed \(cs_typeName(self))."
)
return super.create(into)
}
/**
Returns an editable proxy of a specified `NSManagedObject`. This method should not be used after the `commit()` method was already called once.
- parameter object: the `NSManagedObject` type to be edited
- returns: an editable proxy for the specified `NSManagedObject`.
*/
@warn_unused_result
public override func edit<T: NSManagedObject>(object: T?) -> T? {
CoreStore.assert(
!self.isCommitted,
"Attempted to update an entity of type \(cs_typeName(object)) from an already committed \(cs_typeName(self))."
)
return super.edit(object)
}
/**
Returns an editable proxy of the object with the specified `NSManagedObjectID`. This method should not be used after the `commit()` method was already called once.
- parameter into: an `Into` clause specifying the entity type
- parameter objectID: the `NSManagedObjectID` for the object to be edited
- returns: an editable proxy for the specified `NSManagedObject`.
*/
@warn_unused_result
public override func edit<T: NSManagedObject>(into: Into<T>, _ objectID: NSManagedObjectID) -> T? {
CoreStore.assert(
!self.isCommitted,
"Attempted to update an entity of type \(cs_typeName(T)) from an already committed \(cs_typeName(self))."
)
return super.edit(into, objectID)
}
/**
Deletes a specified `NSManagedObject`. This method should not be used after the `commit()` method was already called once.
- parameter object: the `NSManagedObject` type to be deleted
*/
public override func delete(object: NSManagedObject?) {
CoreStore.assert(
!self.isCommitted,
"Attempted to delete an entity of type \(cs_typeName(object)) from an already committed \(cs_typeName(self))."
)
super.delete(object)
}
/**
Deletes the specified `NSManagedObject`s.
- parameter object1: the `NSManagedObject` type to be deleted
- parameter object2: another `NSManagedObject` type to be deleted
- parameter objects: other `NSManagedObject`s type to be deleted
*/
public override func delete(object1: NSManagedObject?, _ object2: NSManagedObject?, _ objects: NSManagedObject?...) {
CoreStore.assert(
!self.isCommitted,
"Attempted to delete an entities from an already committed \(cs_typeName(self))."
)
super.delete(([object1, object2] + objects).flatMap { $0 })
}
/**
Deletes the specified `NSManagedObject`s.
- parameter objects: the `NSManagedObject`s type to be deleted
*/
public override func delete<S: SequenceType where S.Generator.Element: NSManagedObject>(objects: S) {
CoreStore.assert(
!self.isCommitted,
"Attempted to delete an entities from an already committed \(cs_typeName(self))."
)
super.delete(objects)
}
// MARK: Internal
internal init(mainContext: NSManagedObjectContext, queue: GCDQueue, closure: (transaction: AsynchronousDataTransaction) -> Void) {
self.closure = closure
super.init(mainContext: mainContext, queue: queue, supportsUndo: false, bypassesQueueing: false)
}
internal func perform() {
self.transactionQueue.async {
self.closure(transaction: self)
if !self.isCommitted && self.hasChanges {
CoreStore.log(
.Warning,
message: "The closure for the \(cs_typeName(self)) completed without being committed. All changes made within the transaction were discarded."
)
}
}
}
internal func performAndWait() -> SaveResult? {
self.transactionQueue.sync {
self.closure(transaction: self)
if !self.isCommitted && self.hasChanges {
CoreStore.log(
.Warning,
message: "The closure for the \(cs_typeName(self)) completed without being committed. All changes made within the transaction were discarded."
)
}
}
return self.result
}
// MARK: Private
private let closure: (transaction: AsynchronousDataTransaction) -> Void
// MARK: Deprecated
@available(*, deprecated=1.3.4, obsoleted=2.0.0, message="Resetting the context is inherently unsafe. This method will be removed in the near future. Use `beginUnsafe()` to create transactions with `undo` support.")
public func rollback() {
CoreStore.assert(
!self.isCommitted,
"Attempted to rollback an already committed \(cs_typeName(self))."
)
CoreStore.assert(
self.transactionQueue.isCurrentExecutionContext(),
"Attempted to rollback a \(cs_typeName(self)) outside its designated queue."
)
self.context.reset()
}
}
| mit | d0a7dffb9fc767339f8c133ee9831b3a | 37.597656 | 285 | 0.638397 | 5.146354 | false | false | false | false |
AndrewBennet/readinglist | ReadingList/ViewControllers/Settings/About.swift | 1 | 7158 | import SwiftUI
import UIKit
import WhatsNewKit
import SafariServices
import MessageUI
struct About: View {
let changeListProvider = ChangeListProvider()
@State var isShowingMailAlert = false
@State var isShowingMailView = false
@State var isShowingFaq = false
@EnvironmentObject var hostingSplitView: HostingSettingsSplitView
var body: some View {
SwiftUI.List {
Section(header: AboutHeader(), footer: AboutFooter()) {
IconCell("Website",
imageName: "house.fill",
backgroundColor: .blue,
withChevron: true
).presentingSafari(URL(string: "https://readinglist.app")!)
IconCell("Share",
imageName: "paperplane.fill",
backgroundColor: .orange
).modal(ActivityView(activityItems: [URL(string: "https://\(Settings.appStoreAddress)")!], applicationActivities: nil, excludedActivityTypes: nil))
IconCell("Twitter",
image: TwitterIcon(),
withChevron: true
).presentingSafari(URL(string: "https://twitter.com/ReadingListApp")!)
IconCell("Email Developer",
imageName: "envelope.fill",
backgroundColor: .paleEmailBlue
).onTapGesture {
if #available(iOS 14.0, *) {
isShowingMailAlert = true
} else {
// Action sheet anchors are messed up on iOS 13;
// go straight to the Email view, skipping the sheet
isShowingMailView = true
}
}.actionSheet(isPresented: $isShowingMailAlert) {
mailAlert
}.sheet(isPresented: $isShowingMailView) {
mailView
}
IconCell("Attributions",
imageName: "heart.fill",
backgroundColor: .green
// Re-provide the environment object, otherwise we seem to get trouble
// when the containing hosting VC gets removed from the window
).navigating(to: Attributions().environmentObject(hostingSplitView))
IconCell("Privacy Policy",
imageName: "lock.fill",
backgroundColor: Color(.darkGray)
).navigating(to: PrivacyPolicy().environmentObject(hostingSplitView))
if changeListProvider.thisVersionChangeList() != nil {
IconCell("Recent Changes",
imageName: "wrench.fill",
backgroundColor: .blue,
withChevron: true
).modal(ChangeListWrapper())
}
}
}
.possiblyInsetGroupedListStyle(inset: hostingSplitView.isSplit)
.navigationBarTitle("About")
}
var mailAlert: ActionSheet {
let emailButton: ActionSheet.Button
if MFMailComposeViewController.canSendMail() {
emailButton = .default(Text("Email"), action: {
isShowingMailView = true
})
} else {
emailButton = .default(Text("Copy Email Address"), action: {
UIPasteboard.general.string = "[email protected]"
})
}
return ActionSheet(
title: Text(""),
message: Text("""
Hi there!
To suggest features or report bugs, please email me. I try my best to \
reply to every email I receive, but this app is a one-person project, so \
please be patient if it takes a little time for my reply!
If you do have a specific question, I would suggest first looking on the FAQ \
in case your answer is there.
"""),
buttons: [
emailButton,
.default(Text("Open FAQ"), action: {
isShowingFaq = true
}),
.cancel(Text("Dismiss"), action: {})
]
)
}
var mailView: MailView {
MailView(
isShowing: $isShowingMailView,
receipients: [
"Reading List Developer <\(Settings.feedbackEmailAddress)>"
],
messageBody: """
Your Message Here:
Extra Info:
App Version: \(BuildInfo.thisBuild.fullDescription)
iOS Version: \(UIDevice.current.systemVersion)
Device: \(UIDevice.current.modelName)
""",
subject: "Reading List Feedback"
)
}
}
struct AboutHeader: View {
var innerBody: some View {
(Text("Reading List ").bold() +
Text("""
is developed by single developer – me, Andrew 👋 I hope you are enjoying using the app 😊
If you value the app, please consider leaving a review, tweeting about it, sharing, or leaving a tip.
Happy Reading! 📚
"""
)).font(.subheadline)
.foregroundColor(Color(.label))
.padding(.bottom, 20)
.padding(.top, 10)
}
var body: some View {
if #available(iOS 14.0, *) {
innerBody
.textCase(nil)
.padding(.horizontal, 12)
} else {
innerBody
}
}
}
struct AboutFooter: View {
static let numberFormatter: NumberFormatter = {
var formatter = NumberFormatter()
formatter.usesGroupingSeparator = false
return formatter
}()
var buildNumber = numberFormatter.string(from: BuildInfo.thisBuild.buildNumber as NSNumber) ?? "0"
var body: some View {
VStack(alignment: .center, spacing: 4) {
Text("v\(BuildInfo.thisBuild.version.description) (\(buildNumber))")
Text("© Andrew Bennet 2021")
}
.frame(maxWidth: .infinity, alignment: .center)
.font(.caption)
.foregroundColor(Color(.label))
.padding(.top, 10)
}
}
extension Color {
static let twitterBlue = Color(
.sRGB,
red: 76 / 255,
green: 160 / 255,
blue: 235 / 255,
opacity: 1
)
static let paleEmailBlue = Color(
.sRGB,
red: 94 / 255,
green: 191 / 255,
blue: 244 / 255,
opacity: 1
)
}
fileprivate extension Image {
func iconTemplate() -> some View {
self.resizable()
.renderingMode(.template)
.foregroundColor(.white)
}
}
struct TwitterIcon: View {
var body: some View {
SettingsIcon(color: .twitterBlue) {
Image("twitter")
.iconTemplate()
.frame(width: 18, height: 18, alignment: .center)
}
}
}
struct About_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
About().environmentObject(HostingSettingsSplitView())
}
}
}
| gpl-3.0 | a53400dcd859da5003b41ed78d349d12 | 31.481818 | 163 | 0.528408 | 5.227505 | false | false | false | false |
7factory/mia-HeliumKit | Pods/MIAHydrogenKit/HydrogenKit/URLRequestBuilder.swift | 2 | 2806 | import Foundation
// TODO: This class should not be exposed publicly.
public class URLRequestBuilder {
public init() { }
func createURLRequestFromResource<A>(baseURL: NSURL, resource: Resource<A>, modifyRequest: (NSMutableURLRequest -> Void)?) -> NSURLRequest? {
let urlComponents = NSURLComponents(URL: baseURL, resolvingAgainstBaseURL: true)
if let urlComponents = urlComponents {
applyPathReplacements(urlComponents, resource: resource)
addParameters(urlComponents, resource: resource)
let urlRequest = NSMutableURLRequest(URL: urlComponents.URL!)
if let headers = resource.headers {
for header in headers {
urlRequest.setValue(header.0, forHTTPHeaderField: header.1)
}
}
urlRequest.HTTPMethod = resource.method.requestMethod()
if let body = resource.method.requestBody() {
urlRequest.HTTPBody = body
}
if let modifyRequest = modifyRequest {
modifyRequest(urlRequest)
}
// should the
return urlRequest.copy() as? NSURLRequest
}
return nil
}
private func applyPathReplacements<A>(urlComponents: NSURLComponents, resource: Resource<A>) {
var resourcePath = resource.path
if let path = resourcePath {
if !path.hasPrefix("/") {
resourcePath = "/\(path)"
}
} else {
resourcePath = ""
}
if let pathReplacements = resource.pathReplacements {
for replacement in pathReplacements {
if let range = resourcePath!.rangeOfString(replacement.0, options: NSStringCompareOptions.CaseInsensitiveSearch) {
resourcePath!.replaceRange(range, with: replacement.1)
}
}
}
urlComponents.path = resourcePath
}
private func addParameters<A>(urlComponents: NSURLComponents, resource: Resource<A>) {
if let parameters = resource.parameters {
let sortedParameters = parameters.sort { $0.0 < $1.0 }
var query = ""
for index in 0..<sortedParameters.count {
let parameter = sortedParameters[index]
query += "\(parameter.0)=\(parameter.1)"
if index < parameters.count - 1 {
query += "&"
}
}
urlComponents.query = query
}
}
}
| mit | 807b06c2ba10d7284d6b38a838fe4c34 | 31.627907 | 145 | 0.519957 | 6.249443 | false | false | false | false |
Igor-Palaguta/YoutubeEngine | Source/YoutubeEngine/Data/SearchItem.swift | 1 | 2241 | import Foundation
public enum SearchItem: Equatable {
case channel(Channel)
case video(Video)
case playlist(Playlist)
public var video: Video? {
if case .video(let video) = self {
return video
}
return nil
}
public var channel: Channel? {
if case .channel(let channel) = self {
return channel
}
return nil
}
public var playlist: Playlist? {
if case .playlist(let playlist) = self {
return playlist
}
return nil
}
}
extension SearchItem: Decodable {
private enum CodingKeys: String, CodingKey {
case id
case snippet
}
private enum IDCodingKeys: String, CodingKey {
case kind
case channelID = "channelId"
case videoID = "videoId"
case playlistID = "playlistId"
}
private enum Kind: String, Decodable {
case channel = "youtube#channel"
case video = "youtube#video"
case playlist = "youtube#playlist"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let idContainer = try container.nestedContainer(keyedBy: IDCodingKeys.self, forKey: .id)
let kind = try idContainer.decode(Kind.self, forKey: .kind)
switch kind {
case .channel:
let id = try idContainer.decode(String.self, forKey: .channelID)
let snippet = try container.decodeIfPresent(ChannelSnippet.self, forKey: .snippet)
let channel = Channel(id: id, snippet: snippet)
self = .channel(channel)
case .video:
let id = try idContainer.decode(String.self, forKey: .videoID)
let snippet = try container.decodeIfPresent(VideoSnippet.self, forKey: .snippet)
let video = Video(id: id, snippet: snippet)
self = .video(video)
case .playlist:
let id = try idContainer.decode(String.self, forKey: .playlistID)
let snippet = try container.decodeIfPresent(PlaylistSnippet.self, forKey: .snippet)
let playlist = Playlist(id: id, snippet: snippet)
self = .playlist(playlist)
}
}
}
| mit | 4ad60b9c8d7865a32aa29be18e43f87b | 30.56338 | 96 | 0.604195 | 4.509054 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Tree/543_Diameter of Binary Tree.swift | 1 | 1832 | // 543_Diameter of Binary Tree
// https://leetcode.com/problems/diameter-of-binary-tree/
//
// Created by Honghao Zhang on 9/21/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
//
//Example:
//Given a binary tree
//
// 1
// / \
// 2 3
// / \
// 4 5
//Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
//
//Note: The length of path between two nodes is represented by the number of edges between them.
//
// 计算一个tree的周长,就是这个tree中最长的路径
import Foundation
class Num543 {
// Compute the max depth of left and right, the diameter is the left max + right max
// Then check the max among root, left and right
func diameterOfBinaryTree(_ root: TreeNode?) -> Int {
// diameter of root is left depth + 1 + right depth + 1
if root == nil {
return 0
}
let leftMaxDepth: Int
if let left = root!.left {
leftMaxDepth = maxDepth(left) + 1
}
else {
leftMaxDepth = 0
}
let rightMaxDepth: Int
if let right = root!.right {
rightMaxDepth = maxDepth(right) + 1
}
else {
rightMaxDepth = 0
}
let d = leftMaxDepth + rightMaxDepth
let dLeft = diameterOfBinaryTree(root!.left)
let dRight = diameterOfBinaryTree(root!.right)
return max(d, dLeft, dRight)
}
private func maxDepth(_ root: TreeNode?) -> Int {
if root == nil {
return 0
}
if root!.left == nil, root!.right == nil {
return 0
}
return max(maxDepth(root!.left), maxDepth(root!.right)) + 1
}
}
| mit | e6eff1833ae551f099c825e552732cf8 | 25.791045 | 228 | 0.622841 | 3.626263 | false | false | false | false |
Legoless/Analytical | Analytical/Classes/Provider/GoogleProvider.swift | 1 | 6521 | //
// GoogleProvider.swift
// Analytical
//
// Created by Dal Rupnik on 18/07/16.
// Copyright © 2016 Unified Sense. All rights reserved.
//
import Analytical
import Foundation
//
// Google has been deprecated and is incompatible with Firebase Analytics in the same project.
// This file is kept here for legacy purposes.
//
public class GoogleProvider : BaseProvider<GAITracker>, AnalyticalProvider {
public static let TrackingId = "TrackingId"
private var gai : GAI!
private var trackingId : String?
public var uncaughtExceptions : Bool = false {
didSet {
gai.trackUncaughtExceptions = uncaughtExceptions
}
}
public init(trackingId: String? = nil) {
self.trackingId = trackingId
super.init()
}
//
// MARK: Analytical
//
public func setup(with properties: Properties?) {
gai = GAI.sharedInstance()
gai.trackUncaughtExceptions = false
//gai.logger.logLevel = GAILogLevel.Verbose
if let trackingId = properties?[GoogleProvider.TrackingId] as? String {
self.trackingId = trackingId
}
if let trackingId = trackingId {
instance = gai.tracker(withTrackingId: trackingId)
}
else {
var configureError:NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
assert(configureError == nil, "Error configuring Google services: \(configureError?.localizedDescription ?? "")")
instance = gai.defaultTracker
}
}
public func flush() {
gai.dispatch()
}
public func reset() {
//
// Google has no user variable reset mechanism, as there is no retrieval mechanism.
//
// TODO: Should this be implemented on the provider side, just for the sake of completion?
//
}
public override func event(name: EventName, properties: Properties? = nil) {
//
// Google Analytics works with Category, Action, Label and Value,
// where both Category and Action are required.
//
let properties = prepareProperties(properties: mergeGlobal(properties: properties, overwrite: true))
instance.send(GAIDictionaryBuilder.createEvent(withCategory: properties["category"] as? String, action: name, label: properties["label"] as? String, value: properties["value"] as? NSNumber).parsed)
}
public func screen(name: EventName, properties: Properties? = nil) {
//
// Send screen as an event in addition
//
event(name: name, properties: properties)
instance.set(kGAIScreenName, value: name)
instance.send(GAIDictionaryBuilder.createScreenView().build() as [NSObject : AnyObject])
}
public override func finish(name: EventName, properties: Properties? = nil) {
guard let startDate = events[name] else {
return
}
event(name: name, properties: properties)
let properties = prepareProperties(properties: mergeGlobal(properties: properties, overwrite: true))
let interval = NSNumber(value: NSDate().timeIntervalSince(startDate))
instance.send(GAIDictionaryBuilder.createTiming(withCategory: properties["category"] as? String, interval: interval, name: name, label: properties["label"] as? String).parsed)
}
public func identify(userId: String, properties: Properties? = nil) {
instance.set(kGAIUserId, value: userId)
if let properties = properties {
set(properties: properties)
}
}
public func alias(userId: String, forId: String) {
//
// No alias power for Google Analytics
//
identify(userId: forId)
}
public func set(properties: Properties) {
let properties = prepareProperties(properties: properties)
for (property, value) in properties {
guard let value = value as? String else {
continue
}
instance.set(property, value: value)
}
}
public func increment(property: String, by number: NSDecimalNumber) {
//
// No increment for Google Analytics
//
}
public override func purchase(amount: NSDecimalNumber, properties: Properties? = nil) {
let properties = prepareProperties(properties: mergeGlobal(properties: properties, overwrite: true))
let transactionId = properties[Property.Purchase.transactionId.rawValue] as? String
let affilation = properties[Property.Purchase.affiliation.rawValue] as? String
let tax = properties[Property.Purchase.tax.rawValue] as? NSNumber
let shipping = properties[Property.Purchase.shipping.rawValue] as? NSNumber
let currency = properties[Property.Purchase.currency.rawValue] as? String
let transaction = GAIDictionaryBuilder.createTransaction(withId: transactionId, affiliation: affilation, revenue: amount, tax: tax, shipping: shipping, currencyCode: currency)!
let item = properties[Property.Purchase.item.rawValue] as? String
let category = properties[Property.category.rawValue] as? String
let sku = properties[Property.Purchase.sku.rawValue] as? String
let quantity = properties[Property.Purchase.quantity.rawValue] as? NSNumber
let itemTransaction = GAIDictionaryBuilder.createItem(withTransactionId: transactionId, name: item, sku: sku, category: category, price: amount, quantity: quantity, currencyCode: currency)!
instance.send(transaction.parsed)
instance.send(itemTransaction.parsed)
}
//
// MARK: Private Methods
//
private func prepareProperties(properties: Properties?) -> Properties {
var currentProperties : Properties! = properties
if currentProperties == nil {
currentProperties = [:]
}
if currentProperties["category"] == nil {
currentProperties["category"] = "default"
}
return currentProperties
}
}
//
// MARK: Extensions for helper methods
//
extension GAIDictionaryBuilder {
var parsed : [NSObject : AnyObject] {
return self.build() as [NSObject : AnyObject]
}
}
| mit | 5446e3aa53f8fe800bf00f87d334567f | 33.315789 | 205 | 0.628834 | 5.105717 | false | false | false | false |
kstaring/swift | test/IRGen/sil_generic_witness_methods.swift | 4 | 4468 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
// FIXME: These should be SIL tests, but we can't parse generic types in SIL
// yet.
protocol P {
func concrete_method()
static func concrete_static_method()
func generic_method<Z>(_ x: Z)
}
struct S {}
// CHECK-LABEL: define hidden void @_TF27sil_generic_witness_methods12call_methods{{.*}}(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U, i8** %T.P)
func call_methods<T: P, U>(_ x: T, y: S, z: U) {
// CHECK: [[STATIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 1
// CHECK: [[STATIC_METHOD_PTR:%.*]] = load i8*, i8** [[STATIC_METHOD_ADDR]], align 8
// CHECK: [[STATIC_METHOD:%.*]] = bitcast i8* [[STATIC_METHOD_PTR]] to void (%swift.type*, %swift.type*, i8**)*
// CHECK: call void [[STATIC_METHOD]](%swift.type* %T, %swift.type* %T, i8** %T.P)
T.concrete_static_method()
// CHECK: [[CONCRETE_METHOD_PTR:%.*]] = load i8*, i8** %T.P, align 8
// CHECK: [[CONCRETE_METHOD:%.*]] = bitcast i8* [[CONCRETE_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, i8**)*
// CHECK: call void [[CONCRETE_METHOD]](%swift.opaque* noalias nocapture {{%.*}}, %swift.type* %T, i8** %T.P)
x.concrete_method()
// CHECK: [[GENERIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 2
// CHECK: [[GENERIC_METHOD_PTR:%.*]] = load i8*, i8** [[GENERIC_METHOD_ADDR]], align 8
// CHECK: [[GENERIC_METHOD:%.*]] = bitcast i8* [[GENERIC_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)*
// CHECK: call void [[GENERIC_METHOD]](%swift.opaque* noalias nocapture {{.*}}, %swift.type* {{.*}} @_TMfV27sil_generic_witness_methods1S, {{.*}} %swift.opaque* {{.*}}, %swift.type* %T, i8** %T.P)
x.generic_method(y)
// CHECK: [[GENERIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 2
// CHECK: [[GENERIC_METHOD_PTR:%.*]] = load i8*, i8** [[GENERIC_METHOD_ADDR]], align 8
// CHECK: [[GENERIC_METHOD:%.*]] = bitcast i8* [[GENERIC_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)*
// CHECK: call void [[GENERIC_METHOD]](%swift.opaque* noalias nocapture {{.*}}, %swift.type* %U, %swift.opaque* {{.*}}, %swift.type* %T, i8** %T.P)
x.generic_method(z)
}
// CHECK-LABEL: define hidden void @_TF27sil_generic_witness_methods24call_existential_methods{{.*}}(%P27sil_generic_witness_methods1P_* noalias nocapture dereferenceable({{.*}}))
func call_existential_methods(_ x: P, y: S) {
// CHECK: [[METADATA_ADDR:%.*]] = getelementptr inbounds %P27sil_generic_witness_methods1P_, %P27sil_generic_witness_methods1P_* [[X:%0]], i32 0, i32 1
// CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]], align 8
// CHECK: [[WTABLE_ADDR:%.*]] = getelementptr inbounds %P27sil_generic_witness_methods1P_, %P27sil_generic_witness_methods1P_* [[X]], i32 0, i32 2
// CHECK: [[WTABLE:%.*]] = load i8**, i8*** [[WTABLE_ADDR]], align 8
// CHECK: [[CONCRETE_METHOD_PTR:%.*]] = load i8*, i8** [[WTABLE]], align 8
// CHECK: [[CONCRETE_METHOD:%.*]] = bitcast i8* [[CONCRETE_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, i8**)*
// CHECK: call void [[CONCRETE_METHOD]](%swift.opaque* noalias nocapture {{%.*}}, %swift.type* [[METADATA]], i8** [[WTABLE]])
x.concrete_method()
// CHECK: [[METADATA_ADDR:%.*]] = getelementptr inbounds %P27sil_generic_witness_methods1P_, %P27sil_generic_witness_methods1P_* [[X]], i32 0, i32 1
// CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]], align 8
// CHECK: [[WTABLE_ADDR:%.*]] = getelementptr inbounds %P27sil_generic_witness_methods1P_, %P27sil_generic_witness_methods1P_* [[X:%.*]], i32 0, i32 2
// CHECK: [[WTABLE:%.*]] = load i8**, i8*** [[WTABLE_ADDR]], align 8
// CHECK: [[GENERIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[WTABLE]], i32 2
// CHECK: [[GENERIC_METHOD_PTR:%.*]] = load i8*, i8** [[GENERIC_METHOD_ADDR]], align 8
// CHECK: [[GENERIC_METHOD:%.*]] = bitcast i8* [[GENERIC_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)*
// CHECK: call void [[GENERIC_METHOD]](%swift.opaque* noalias nocapture {{.*}}, %swift.type* {{.*}} @_TMfV27sil_generic_witness_methods1S, {{.*}} %swift.opaque* noalias nocapture {{%.*}}, %swift.type* [[METADATA]], i8** [[WTABLE]])
x.generic_method(y)
}
| apache-2.0 | 1bfad60663f47d26d1a01fa97eec10f0 | 73.466667 | 233 | 0.628469 | 3.216703 | false | false | false | false |
applivery/applivery-ios-sdk | AppliveryBehaviorTests/Mocks/FeedbackViewMock.swift | 1 | 1859 | //
// FeedbackViewMock.swift
// AppliverySDK
//
// Created by Alejandro Jiménez on 21/4/16.
// Copyright © 2016 Applivery S.L. All rights reserved.
//
import Foundation
import UIKit
@testable import Applivery
class FeedbackViewMock: FeedbackView {
// INPUTS
var fakeMessage: String?
var fakeEditedScreenshot: UIImage?
// OUTPUTS
var spyShowScreenshot: (called: Bool, image: UIImage?) = (false, nil)
var spyRestoreScreenshot: (called: Bool, image: UIImage?) = (false, nil)
var spyShowFeedbackFormulary: (called: Bool, preview: UIImage?) = (false, nil)
var spyShowScreenshotPreviewCalled = false
var spyHideScreenshotPreviewCalled = false
var spyNeedMessageCalled = false
var spyShowLoadingCalled = false
var spyStopLoadingCalled = false
var spyShowMessage: (called: Bool, message: String?) = (false, nil)
var spyDismissCalled = false
// MARK: - Methods
func showScreenshot(_ screenshot: UIImage?) {
self.spyShowScreenshot = (true, screenshot)
}
func restoreSceenshot(_ screenshot: UIImage) {
self.spyRestoreScreenshot = (true, screenshot)
}
func showFeedbackFormulary(with preview: UIImage) {
self.spyShowFeedbackFormulary = (true, preview)
}
func showScreenshotPreview() {
self.spyShowScreenshotPreviewCalled = true
}
func hideScreenshotPreview() {
self.spyHideScreenshotPreviewCalled = true
}
func textMessage() -> String? {
return self.fakeMessage
}
func needMessage() {
self.spyNeedMessageCalled = true
}
func showMessage(_ message: String) {
self.spyShowMessage = (true, message)
}
func showLoading() {
self.spyShowLoadingCalled = true
}
func stopLoading() {
self.spyStopLoadingCalled = true
}
func editedScreenshot() -> UIImage? {
return self.fakeEditedScreenshot
}
func dismiss(animated flag: Bool, completion: (() -> Void)?) {
self.spyDismissCalled = true
}
}
| mit | 79e4b15def8ac732c480055e09761f06 | 21.373494 | 79 | 0.732364 | 3.432532 | false | false | false | false |
russbishop/swift | test/Reflection/Inputs/ObjectiveCTypes.swift | 1 | 657 | import Foundation
import CoreGraphics
public class OC : NSObject {
public let nsObject: NSObject = NSObject()
public let nsString: NSString = ""
public let cfString: CFString = ""
public let aBlock: @convention(block) () -> () = {}
public let ocnss: GenericOC<NSString> = GenericOC()
public let occfs: GenericOC<CFString> = GenericOC()
}
public class GenericOC<T> : NSObject {
}
public class HasObjCClasses {
let url = NSURL()
let integer = NSInteger()
let rect = CGRect(x: 0, y: 1, width: 2, height: 3)
}
@objc public protocol OP {}
public func closureHasObjCClasses(b: Bundle, c: NSCoding) -> () -> () {
return { _ = b; _ = c }
}
| apache-2.0 | 6e1fb69615205c30c0bde6e2c628fed9 | 24.269231 | 71 | 0.665145 | 3.513369 | false | false | false | false |
leejayID/Linkage-Swift | Linkage/TableView/RightTableViewCell.swift | 1 | 1873 | //
// RightTableViewCell.swift
// Linkage
//
// Created by LeeJay on 2017/3/3.
// Copyright © 2017年 LeeJay. All rights reserved.
//
import UIKit
class RightTableViewCell: UITableViewCell {
private lazy var nameLabel = UILabel()
private lazy var imageV = UIImageView()
private lazy var priceLabel = UILabel()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configureUI()
}
func setDatas(_ model : FoodModel) {
guard
let minPrice = model.minPrice,
let picture = model.picture,
let name = model.name else { return }
priceLabel.text = "¥\(minPrice)"
nameLabel.text = name
guard let url = URL.init(string: picture) else { return }
imageV.kf.setImage(with: url)
}
func configureUI() {
imageV.frame = CGRect(x: 15, y: 15, width: 50, height: 50)
contentView.addSubview(imageV)
nameLabel.frame = CGRect(x: 80, y: 10, width: 200, height: 30)
nameLabel.font = UIFont.systemFont(ofSize: 14)
contentView.addSubview(nameLabel)
priceLabel.frame = CGRect(x: 80, y: 45, width: 200, height: 30)
priceLabel.font = UIFont.systemFont(ofSize: 14)
priceLabel.textColor = UIColor.red
contentView.addSubview(priceLabel)
}
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
}
}
| apache-2.0 | 15e4d5769de59db2be7efcb437968e41 | 27.30303 | 74 | 0.609208 | 4.512077 | false | false | false | false |