repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ben-ng/swift | test/Interpreter/protocol_extensions.swift | 10 | 4915 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
// Extend a protocol with a property.
extension Sequence {
final var myCount: Int {
var result = 0
for _ in self {
result += 1
}
return result
}
}
// CHECK: 4
print(["a", "b", "c", "d"].myCount)
// Extend a protocol with a function.
extension Collection {
final var myIndices: Range<Index> {
return startIndex..<endIndex
}
func clone() -> Self {
return self
}
}
// CHECK: 4
print(["a", "b", "c", "d"].clone().myCount)
extension Sequence {
final public func myEnumerated() -> EnumeratedSequence<Self> {
return self.enumerated()
}
}
// CHECK: (0, a)
// CHECK-NEXT: (1, b)
// CHECK-NEXT: (2, c)
for (index, element) in ["a", "b", "c"].myEnumerated() {
print("(\(index), \(element))")
}
extension Sequence {
final public func myReduce<T>(
_ initial: T, combine: (T, Self.Iterator.Element) -> T
) -> T {
var result = initial
for value in self {
result = combine(result, value)
}
return result
}
}
// CHECK: 15
print([1, 2, 3, 4, 5].myReduce(0, combine: +))
extension Sequence {
final public func myZip<S : Sequence>(_ s: S) -> Zip2Sequence<Self, S> {
return Zip2Sequence(_sequence1: self, _sequence2: s)
}
}
// CHECK: (1, a)
// CHECK-NEXT: (2, b)
// CHECK-NEXT: (3, c)
for (a, b) in [1, 2, 3].myZip(["a", "b", "c"]) {
print("(\(a), \(b))")
}
// Mutating algorithms.
extension MutableCollection
where Self: RandomAccessCollection, Self.Iterator.Element : Comparable {
public final mutating func myPartition() -> Index {
let first = self.first
return self.partition(by: { $0 >= first! })
}
}
extension RangeReplaceableCollection {
public final func myJoin<S : Sequence where S.Iterator.Element == Self>(
_ elements: S
) -> Self {
var result = Self()
var iter = elements.makeIterator()
if let first = iter.next() {
result.append(contentsOf: first)
while let next = iter.next() {
result.append(contentsOf: self)
result.append(contentsOf: next)
}
}
return result
}
}
// CHECK: a,b,c
print(
String(
",".characters.myJoin(["a".characters, "b".characters, "c".characters])
)
)
// Constrained extensions for specific types.
extension Collection where Self.Iterator.Element == String {
final var myCommaSeparatedList: String {
if startIndex == endIndex { return "" }
var result = ""
var first = true
for x in self {
if first { first = false }
else { result += ", " }
result += x
}
return result
}
}
// CHECK: x, y, z
print(["x", "y", "z"].myCommaSeparatedList)
// CHECK: {{[tuv], [tuv], [tuv]}}
print((["t", "u", "v"] as Set).myCommaSeparatedList)
// Existentials
protocol ExistP1 {
func existP1()
}
extension ExistP1 {
final func runExistP1() {
print("runExistP1")
self.existP1()
}
}
struct ExistP1_Struct : ExistP1 {
func existP1() {
print(" - ExistP1_Struct")
}
}
class ExistP1_Class : ExistP1 {
func existP1() {
print(" - ExistP1_Class")
}
}
// CHECK: runExistP1
// CHECK-NEXT: - ExistP1_Struct
var existP1: ExistP1 = ExistP1_Struct()
existP1.runExistP1()
// CHECK: runExistP1
// CHECK-NEXT: - ExistP1_Class
existP1 = ExistP1_Class()
existP1.runExistP1()
protocol P {
mutating func setValue(_ b: Bool)
func getValue() -> Bool
}
extension P {
final var extValue: Bool {
get { return getValue() }
set(newValue) { setValue(newValue) }
}
}
extension Bool : P {
mutating func setValue(_ b: Bool) { self = b }
func getValue() -> Bool { return self }
}
class C : P {
var theValue: Bool = false
func setValue(_ b: Bool) { theValue = b }
func getValue() -> Bool { return theValue }
}
func toggle(_ value: inout Bool) {
value = !value
}
var p: P = true
// CHECK: Bool
print("Bool")
// CHECK: true
p.extValue = true
print(p.extValue)
// CHECK: false
p.extValue = false
print(p.extValue)
// CHECK: true
toggle(&p.extValue)
print(p.extValue)
// CHECK: C
print("C")
p = C()
// CHECK: true
p.extValue = true
print(p.extValue)
// CHECK: false
p.extValue = false
print(p.extValue)
// CHECK: true
toggle(&p.extValue)
print(p.extValue)
// Logical lvalues of existential type.
struct HasP {
var _p: P
var p: P {
get { return _p }
set { _p = newValue }
}
}
var hasP = HasP(_p: false)
// CHECK: true
hasP.p.extValue = true
print(hasP.p.extValue)
// CHECK: false
toggle(&hasP.p.extValue)
print(hasP.p.extValue)
// rdar://problem/20739719
class Super: Init {
required init(x: Int) { print("\(x) \(type(of: self))") }
}
class Sub: Super {}
protocol Init { init(x: Int) }
extension Init { init() { self.init(x: 17) } }
// CHECK: 17 Super
_ = Super()
// CHECK: 17 Sub
_ = Sub()
// CHECK: 17 Super
var sup: Super.Type = Super.self
_ = sup.init()
// CHECK: 17 Sub
sup = Sub.self
_ = sup.init()
// CHECK: DONE
print("DONE")
| apache-2.0 | c949482fe020b4109ddfaffa0bc356b6 | 17.40824 | 75 | 0.615056 | 3.047117 | false | false | false | false |
rakaramos/networklayer | NetworkLayer/Request/BaseRequest.swift | 1 | 3231 | import Foundation
public class BaseRequest: NSOperation {
var theURL = NSURL()
var bandwidth: Double {
return benchmark.bandwidth(incomingData)
}
private let incomingData = NSMutableData()
private var sessionTask: NSURLSessionTask?
private var benchmark: Benchmark = Benchmark()
private var localURLSession: NSURLSession {
return NSURLSession(configuration: localConfig, delegate: self, delegateQueue: nil)
}
private var localConfig: NSURLSessionConfiguration {
return NSURLSessionConfiguration.defaultSessionConfiguration()
}
var average: Double {
get {
return benchmark.average
}
}
var innerFinished: Bool = false {
didSet {
if(innerFinished) {
benchmark.stop()
}
}
}
override public var finished: Bool {
get {
return innerFinished
}
//Note that I am triggering a KVO notification on isFinished as opposed to finished which is what the property name is. This seems to be a Swift-ism as the NSOperation get accessor is called isFinished instead of getFinished and I suspect that is part of why I need to tickle the accessor name instead of the property name.
set (newValue) {
willChangeValueForKey("isFinished")
innerFinished = newValue
didChangeValueForKey("isFinished")
}
}
convenience public init(URL: NSURL) {
self.init()
self.theURL = URL
}
override public func start() {
print("Start fetching \(theURL)")
if cancelled {
finished = true
return
}
let request = NSMutableURLRequest(URL: theURL)
sessionTask = localURLSession.dataTaskWithRequest(request)
sessionTask?.resume()
}
func finish() {
finished = true
sessionTask?.cancel()
}
}
extension BaseRequest: NSURLSessionDelegate {
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
print("Start downloading \(theURL) \(queuePriority.rawValue)")
benchmark.start()
if cancelled {
finish()
return
}
//Check the response code and react appropriately
completionHandler(.Allow)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if cancelled {
finish()
return
}
incomingData.appendData(data)
benchmark.tick(incomingData, feshData: data)
}
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
defer {
finished = true
}
if cancelled {
sessionTask?.cancel()
return
}
if NSThread.isMainThread() { print("Main Thread!") }
if error != nil {
print("Failed to receive response: \(error)")
return
}
//processData()
}
} | mit | 450ecfa81e2875b0ea2de3eb3b4b0f51 | 29.205607 | 331 | 0.607861 | 5.668421 | false | true | false | false |
SuPair/VPNOn | VPNOnKit/VPNManager.swift | 1 | 7157 | //
// VPNManager.swift
// VPNOn
//
// Created by Lex Tang on 12/5/14.
// Copyright (c) 2014 LexTang.com. All rights reserved.
//
import Foundation
import NetworkExtension
import CoreData
let kAppGroupIdentifier = "group.VPNOn"
final public class VPNManager
{
lazy var manager: NEVPNManager = {
return NEVPNManager.sharedManager()
}()
lazy var defaults: NSUserDefaults = {
return NSUserDefaults(suiteName: kAppGroupIdentifier)!
}()
public lazy var wormhole: Wormhole = {
return Wormhole(appGroupIdentifier: kAppGroupIdentifier, messageDirectoryName: "Wormhole")
}()
public var status: NEVPNStatus {
get {
return manager.connection.status
}
}
private let kVPNOnDisplayFlags = "displayFlags"
public var displayFlags: Bool {
get {
if let value = defaults.objectForKey(kVPNOnDisplayFlags) as! Int? {
return Bool(value)
}
return true
}
set {
defaults.setObject(Int(newValue), forKey: kVPNOnDisplayFlags)
defaults.synchronize()
}
}
public class var sharedManager : VPNManager
{
struct Static
{
static let sharedInstance : VPNManager = {
let instance = VPNManager()
instance.manager.loadFromPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
if let err = error {
debugPrint("Failed to load preferences: \(err.localizedDescription)")
}
}
instance.manager.localizedDescription = "VPN On"
instance.manager.enabled = true
return instance
}()
}
return Static.sharedInstance
}
public func connectIPSec(title: String, server: String, account: String?, group: String?, alwaysOn: Bool = true, passwordRef: NSData?, secretRef: NSData?, certificate: NSData?) {
let p = NEVPNProtocolIPSec()
p.authenticationMethod = NEVPNIKEAuthenticationMethod.None
p.useExtendedAuthentication = true
p.serverAddress = server
p.disconnectOnSleep = !alwaysOn
manager.localizedDescription = "VPN On - \(title)"
if let grp = group {
p.localIdentifier = grp
} else {
p.localIdentifier = "VPN"
}
if let username = account {
p.username = username
}
if let password = passwordRef {
p.passwordReference = password
}
if let secret = secretRef {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.SharedSecret
p.sharedSecretReference = secret
}
if let certficiateData = certificate {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.Certificate
p.identityData = certficiateData
}
manager.enabled = true
manager.`protocol` = p
configOnDemand()
#if (arch(i386) || arch(x86_64)) && os(iOS) // #if TARGET_IPHONE_SIMULATOR for Swift
print("I'm afraid you can not connect VPN in simulators.")
#else
manager.saveToPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
if let err = error {
debugPrintln("Failed to save profile: \(err.localizedDescription)")
} else {
var connectError : NSError?
self.manager.connection.startVPNTunnelAndReturnError(&connectError)
if let connectErr = connectError {
debugPrintln("Failed to start tunnel: \(connectErr.localizedDescription)")
}
}
}
#endif
}
public func connectIKEv2(title: String, server: String, account: String?, group: String?, alwaysOn: Bool = true, passwordRef: NSData?, secretRef: NSData?, certificate: NSData?) {
let p = NEVPNProtocolIKEv2()
p.authenticationMethod = NEVPNIKEAuthenticationMethod.None
p.useExtendedAuthentication = true
p.serverAddress = server
p.remoteIdentifier = server
p.disconnectOnSleep = !alwaysOn
p.deadPeerDetectionRate = NEVPNIKEv2DeadPeerDetectionRate.Medium
// TODO: Add an option into config page
manager.localizedDescription = "VPN On - \(title)"
if let grp = group {
p.localIdentifier = grp
} else {
p.localIdentifier = "VPN"
}
if let username = account {
p.username = username
}
if let password = passwordRef {
p.passwordReference = password
}
if let secret = secretRef {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.SharedSecret
p.sharedSecretReference = secret
}
if let certficiateData = certificate {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.Certificate
p.serverCertificateCommonName = server
p.serverCertificateIssuerCommonName = server
p.identityData = certficiateData
}
manager.enabled = true
manager.`protocol` = p
configOnDemand()
manager.saveToPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
if let err = error {
debugPrint("Failed to save profile: \(err.localizedDescription)")
} else {
var connectError : NSError?
do {
try self.manager.connection.startVPNTunnelAndReturnError()
} catch var error as NSError {
connectError = error
if let connectErr = connectError {
debugPrint("Failed to start IKEv2 tunnel: \(connectErr.localizedDescription)")
}
} catch {
fatalError()
}
}
}
}
public func configOnDemand() {
if onDemandDomainsArray.count > 0 && onDemand {
let connectionRule = NEEvaluateConnectionRule(
matchDomains: onDemandDomainsArray,
andAction: NEEvaluateConnectionRuleAction.ConnectIfNeeded
)
let ruleEvaluateConnection = NEOnDemandRuleEvaluateConnection()
ruleEvaluateConnection.connectionRules = [connectionRule]
manager.onDemandRules = [ruleEvaluateConnection]
manager.onDemandEnabled = true
} else {
manager.onDemandRules = [AnyObject]()
manager.onDemandEnabled = false
}
}
public func disconnect() {
manager.connection.stopVPNTunnel()
}
public func removeProfile() {
manager.removeFromPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
}
}
}
| mit | 54562db4e4237b5e0dcaf1c67d611ed8 | 31.384615 | 182 | 0.567137 | 5.591406 | false | false | false | false |
masters3d/xswift | exercises/hamming/Tests/HammingTests/HammingTests.swift | 3 | 2157 | import XCTest
@testable import Hamming
class HammingTests: XCTestCase {
func testNoDifferenceBetweenEmptyStrands() {
let result = Hamming.compute("", against: "")!
let expected = 0
XCTAssertEqual(expected, result)
}
func testNoDifferenceBetweenIdenticalStrands() {
let result = Hamming.compute("GGACTGA", against:"GGACTGA")!
let expected = 0
XCTAssertEqual(expected, result)
}
func testCompleteHammingDistanceInSmallStrand() {
let result = Hamming.compute("ACT", against: "GGA")!
let expected = 3
XCTAssertEqual(expected, result)
}
func testSmallHammingDistanceInMiddleSomewhere() {
let result = Hamming.compute("GGACG", against:"GGTCG")!
let expected = 1
XCTAssertEqual(expected, result)
}
func testLargerDistance() {
let result = Hamming.compute("ACCAGGG", against:"ACTATGG")!
let expected = 2
XCTAssertEqual(expected, result)
}
func testReturnsNilWhenOtherStrandLonger() {
let result = Hamming.compute("AAACTAGGGG", against:"AGGCTAGCGGTAGGAC")
XCTAssertNil(result, "Different length strands return nil")
}
func testReturnsNilWhenOriginalStrandLonger() {
let result = Hamming.compute("GACTACGGACAGGGTAGGGAAT", against:"GACATCGCACACC")
XCTAssertNil(result, "Different length strands return nil")
}
static var allTests: [(String, (HammingTests) -> () throws -> Void)] {
return [
("testNoDifferenceBetweenEmptyStrands", testNoDifferenceBetweenEmptyStrands),
("testNoDifferenceBetweenIdenticalStrands", testNoDifferenceBetweenIdenticalStrands),
("testCompleteHammingDistanceInSmallStrand", testCompleteHammingDistanceInSmallStrand),
("testSmallHammingDistanceInMiddleSomewhere", testSmallHammingDistanceInMiddleSomewhere),
("testLargerDistance", testLargerDistance),
("testReturnsNilWhenOtherStrandLonger", testReturnsNilWhenOtherStrandLonger),
("testReturnsNilWhenOriginalStrandLonger", testReturnsNilWhenOriginalStrandLonger),
]
}
}
| mit | b1255b05b87e2851bb2bc1aa65a04732 | 37.517857 | 101 | 0.690774 | 4.503132 | false | true | false | false |
auth0/Lock.swift | Lock/DatabasePresenter.swift | 1 | 16523 | // DatabasePresenter.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import SafariServices
class DatabasePresenter: Presentable, Loggable {
let database: DatabaseConnection
let options: Options
let style: Style
var authenticator: DatabaseAuthenticatable
var creator: DatabaseUserCreator
var navigator: Navigable
var messagePresenter: MessagePresenter? {
didSet {
self.authPresenter?.messagePresenter = self.messagePresenter
}
}
var authPresenter: AuthPresenter?
var enterpriseInteractor: EnterpriseDomainInteractor?
var initialEmail: String? { return self.authenticator.validEmail ? self.authenticator.email : nil }
var initialUsername: String? { return self.authenticator.validUsername ? self.authenticator.username : nil }
weak var databaseView: DatabaseOnlyView?
var currentScreen: DatabaseScreen?
convenience init(interactor: DatabaseInteractor, connection: DatabaseConnection, navigator: Navigable, options: Options, style: Style) {
self.init(authenticator: interactor, creator: interactor, connection: connection, navigator: navigator, options: options, style: style)
}
init(authenticator: DatabaseAuthenticatable, creator: DatabaseUserCreator, connection: DatabaseConnection, navigator: Navigable, options: Options, style: Style) {
self.authenticator = authenticator
self.creator = creator
self.database = connection
self.navigator = navigator
self.options = options
self.style = style
}
var view: View {
let initialScreen = self.options.initialScreen
let allow = self.options.allow
let database = DatabaseOnlyView(allowedModes: allow)
database.navigator = self.navigator
database.switcher?.onSelectionChange = { [unowned self, weak database] switcher in
let selected = switcher.selected
guard let view = database else { return }
self.logger.debug("selected \(selected)")
self.navigator.resetScroll(false)
switch selected {
case .signup:
self.showSignup(inView: view, username: self.initialUsername, email: self.initialEmail)
case .login:
self.showLogin(inView: view, identifier: self.authenticator.identifier)
}
}
if allow.contains(.Login) && initialScreen == .login {
database.switcher?.selected = .login
showLogin(inView: database, identifier: authenticator.identifier)
} else if allow.contains(.Signup) && (initialScreen == .signup || !allow.contains(.Login)) {
database.switcher?.selected = .signup
showSignup(inView: database, username: initialUsername, email: initialEmail)
}
self.databaseView = database
return database
}
private func showLogin(inView view: DatabaseView, identifier: String?) {
self.messagePresenter?.hideCurrent()
let authCollectionView = self.authPresenter?.newViewToEmbed(withInsets: UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20), isLogin: true)
let style = self.database.requiresUsername ? self.options.usernameStyle : [.Email]
view.showLogin(withIdentifierStyle: style, identifier: identifier, authCollectionView: authCollectionView, showPassword: self.options.allowShowPassword)
self.currentScreen = .login
let form = view.form
form?.onValueChange = self.handleInput
form?.onSubmit = { [weak form] input in
form?.onValueChange(input)
guard let attribute = self.getUserAttribute(from: input.type) else { return false }
do {
try self.authenticator.update(attribute, value: input.text)
return true
} catch {
return false
}
}
let action = { [weak form] (button: PrimaryButton) in
guard let isValid = form?.shouldSubmit(), isValid else { return }
self.messagePresenter?.hideCurrent()
self.logger.info("Perform login for email: \(self.authenticator.email.verbatim())")
button.inProgress = true
let errorHandler: (LocalizableError?) -> Void = { error in
Queue.main.async {
button.inProgress = false
guard let error = error else {
self.logger.debug("Logged in!")
let message = "You have logged in successfully.".i18n(key: "com.auth0.lock.database.login.success.message", comment: "User logged in")
if !self.options.autoClose {
self.messagePresenter?.showSuccess(message)
}
return
}
if case CredentialAuthError.multifactorRequired = error {
self.navigator.navigate(.multifactor)
return
} else if case CredentialAuthError.multifactorTokenRequired(let token) = error {
self.navigator.navigate(.multifactorWithToken(token))
return
} else {
form?.needsToUpdateState()
self.messagePresenter?.showError(error)
self.logger.error("Failed with error \(error)")
}
}
}
if let connection = self.enterpriseInteractor?.connection, let domain = self.enterpriseInteractor?.domain {
if self.options.enterpriseConnectionUsingActiveAuth.contains(connection.name) {
self.navigator.navigate(.enterpriseActiveAuth(connection: connection, domain: domain))
} else {
self.enterpriseInteractor?.login(errorHandler)
}
} else {
self.authenticator.login(errorHandler)
}
}
let primaryButton = view.primaryButton
view.form?.onReturn = { [weak primaryButton] field in
guard let button = primaryButton, field.returnKey == .done else { return } // FIXME: Log warn
action(button)
}
view.primaryButton?.onPress = action
view.secondaryButton?.title = "Don’t remember your password?".i18n(key: "com.auth0.lock.database.button.forgot_password", comment: "Forgot password")
view.secondaryButton?.color = .clear
view.secondaryButton?.onPress = { _ in
self.navigator.navigate(.forgotPassword)
}
}
private func showSignup(inView view: DatabaseView, username: String?, email: String?) {
self.messagePresenter?.hideCurrent()
let authCollectionView = self.authPresenter?.newViewToEmbed(withInsets: UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20), isLogin: false)
let interactor = self.authenticator as? DatabaseInteractor
let passwordPolicyValidator = interactor?.passwordValidator as? PasswordPolicyValidator
self.currentScreen = .signup
interactor?.user.reset()
view.showSignUp(withUsername: self.database.requiresUsername, username: username, email: email, authCollectionView: authCollectionView, additionalFields: self.options.customSignupFields, passwordPolicyValidator: passwordPolicyValidator, showPassword: self.options.allowShowPassword, showTerms: options.showTerms || options.mustAcceptTerms)
view.allFields?.filter { $0.text != nil && !$0.text!.isEmpty }.forEach(self.handleInput)
let form = view.form
view.form?.onValueChange = self.handleInput
form?.onSubmit = { [weak form] input in
form?.onValueChange(input)
guard let attribute = self.getUserAttribute(from: input.type) else { return false }
do {
try self.authenticator.update(attribute, value: input.text)
return true
} catch {
return false
}
}
let action = { [weak form, weak view] (button: PrimaryButton) in
guard let isValid = form?.shouldSubmit(), isValid else { return }
self.messagePresenter?.hideCurrent()
self.logger.info("Perform sign up for email \(self.creator.email.verbatim())")
view?.allFields?.forEach { self.handleInput($0) }
let interactor = self.creator
button.inProgress = true
interactor.create { createError, loginError in
Queue.main.async {
button.inProgress = false
guard createError != nil || loginError != nil else {
if !self.options.loginAfterSignup {
let message = "Thanks for signing up.".i18n(key: "com.auth0.lock.database.signup.success.message", comment: "User signed up")
if let databaseView = self.databaseView, self.options.allow.contains(.Login) {
self.databaseView?.switcher?.selected = .login
self.showLogin(inView: databaseView, identifier: self.creator.identifier)
}
if self.options.allow.contains(.Login) || !self.options.autoClose {
self.messagePresenter?.showSuccess(message)
}
}
return
}
if let error = loginError, case .multifactorRequired = error {
self.navigator.navigate(.multifactor)
return
} else if let error = loginError, case .multifactorTokenRequired(let token) = error {
self.navigator.navigate(.multifactorWithToken(token))
return
}
let error: LocalizableError = createError ?? loginError!
form?.needsToUpdateState()
self.messagePresenter?.showError(error)
self.logger.error("Failed with error \(error)")
}
}
}
let checkTermsAndSignup = { [weak view] (button: PrimaryButton) in
if self.options.mustAcceptTerms {
let validForm = view?.allFields?
.filter { !$0.state.isValid }
.isEmpty ?? false
if validForm { self.showTermsPrompt(atButton: button) { _ in action(button) } }
} else {
action(button)
}
}
view.form?.onReturn = { [weak view] field in
guard let button = view?.primaryButton, field.returnKey == .done else { return } // FIXME: Log warn
checkTermsAndSignup(button)
}
view.primaryButton?.onPress = checkTermsAndSignup
view.secondaryButton?.title = "By signing up, you agree to our terms of\n service and privacy policy".i18n(key: "com.auth0.lock.database.button.tos", comment: "tos & privacy")
view.secondaryButton?.color = self.style.termsButtonColor
view.secondaryButton?.titleColor = self.style.termsButtonTitleColor
view.secondaryButton?.onPress = { button in
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alert.popoverPresentationController?.sourceView = button
alert.popoverPresentationController?.sourceRect = button.bounds
let cancel = UIAlertAction(title: "Cancel".i18n(key: "com.auth0.lock.database.tos.sheet.cancel", comment: "Cancel"), style: .cancel, handler: nil)
let tos = UIAlertAction(title: "Terms of Service".i18n(key: "com.auth0.lock.database.tos.sheet.title", comment: "ToS"), style: .default, handler: safariBuilder(forURL: self.options.termsOfServiceURL as URL, navigator: self.navigator))
let privacy = UIAlertAction(title: "Privacy Policy".i18n(key: "com.auth0.lock.database.tos.sheet.privacy", comment: "Privacy"), style: .default, handler: safariBuilder(forURL: self.options.privacyPolicyURL as URL, navigator: self.navigator))
[cancel, tos, privacy].forEach { alert.addAction($0) }
self.navigator.present(alert)
}
}
private func handleInput(_ input: InputField) {
self.messagePresenter?.hideCurrent()
self.logger.verbose("new value: \(input.text.verbatim()) for type: \(input.type)")
guard let attribute = getUserAttribute(from: input.type) else { return }
var updateHRD: Bool = false
switch attribute {
case .email: updateHRD = true
case .emailOrUsername: updateHRD = true
default: break
}
do {
try self.authenticator.update(attribute, value: input.text)
input.showValid()
if self.currentScreen == .login && updateHRD {
try? self.enterpriseInteractor?.updateEmail(input.text)
if let connection = self.enterpriseInteractor?.connection {
self.logger.verbose("Enterprise connection detected: \(connection)")
if self.databaseView?.ssoBar == nil { self.databaseView?.presentEnterprise() }
} else {
self.databaseView?.removeEnterprise()
}
}
} catch let error as InputValidationError {
input.showError(error.localizedMessage(withConnection: self.database))
} catch {
input.showError()
}
}
private func getUserAttribute(from inputType: InputField.InputType) -> UserAttribute? {
switch inputType {
case .email: return .email
case .emailOrUsername: return .emailOrUsername
case .password: return .password(enforcePolicy: self.currentScreen == .signup)
case .username: return .username
case .custom(let name, _, _, let storage, _, _, _, _, _, _, _):
return .custom(name: name, storage: storage)
default: return nil
}
}
func showTermsPrompt(atButton button: PrimaryButton, successHandler: @escaping (PrimaryButton) -> Void) {
let terms = "Terms & Policy".i18n(key: "com.auth0.lock.database.button.tos.title", comment: "tos title")
let alert = UIAlertController(title: terms, message: "By signing up, you agree to our terms of\n service and privacy policy".i18n(key: "com.auth0.lock.database.button.tos", comment: "tos & privacy"), preferredStyle: .alert)
alert.popoverPresentationController?.sourceView = button
alert.popoverPresentationController?.sourceRect = button.bounds
let cancelAction = UIAlertAction(title: "Cancel".i18n(key: "com.auth0.lock.database.tos.sheet.cancel", comment: "Cancel"), style: .cancel, handler: nil)
let okAction = UIAlertAction(title: "Accept".i18n(key: "com.auth0.lock.database.tos.sheet.accept", comment: "Accept"), style: .default) { _ in
successHandler(button)
}
[cancelAction, okAction].forEach { alert.addAction($0) }
self.navigator.present(alert)
}
}
private func safariBuilder(forURL url: URL, navigator: Navigable) -> (UIAlertAction) -> Void {
return { _ in
let safari = SFSafariViewController(url: url)
navigator.present(safari)
}
}
| mit | ff2af954f8ff4f105cc160f753cc6883 | 48.612613 | 347 | 0.624962 | 4.883535 | false | false | false | false |
sgtsquiggs/WordSearch | WordSearch/Puzzle.swift | 1 | 2892 | //
// Puzzle.swift
// WordSearch
//
// Created by Matthew Crenshaw on 11/7/15.
// Copyright © 2015 Matthew Crenshaw. All rights reserved.
//
import Foundation
/// ASSUMPTION: `character_grid` will always be a square 2d array
struct Puzzle {
let sourceLanguage: String
let targetLanguage: String
let word: String
let characterGrid: [[String]]
let wordLocations: [WordLocation]
let rows: Int
let columns: Int
/// Decodes `Puzzle` from json.
static func decodeJson(json: AnyObject) -> Puzzle? {
guard let dict = json as? [String:AnyObject] else {
assertionFailure("json is not a dictionary")
return nil
}
guard let sourceLanguage_field: AnyObject = dict["source_language"] else {
assertionFailure("field 'source_language' is mising")
return nil
}
guard let sourceLanguage: String = String.decodeJson(sourceLanguage_field) else {
assertionFailure("field 'source_language' is not a String")
return nil
}
guard let targetLanguage_field: AnyObject = dict["target_language"] else {
assertionFailure("field 'target_language' is mising")
return nil
}
guard let targetLanguage: String = String.decodeJson(targetLanguage_field) else {
assertionFailure("field 'target_language' is not a String")
return nil
}
guard let word_field: AnyObject = dict["word"] else {
assertionFailure("field 'word_field' is mising")
return nil
}
guard let word: String = String.decodeJson(word_field) else {
assertionFailure("field 'word_field' is not a String")
return nil
}
guard let characterGrid_field: AnyObject = dict["character_grid"] else {
assertionFailure("field 'character_grid' is missing")
return nil
}
guard let characterGrid: [[String]] = Array.decodeJson({ Array.decodeJson({ String.decodeJson($0) }, $0) }, characterGrid_field) else {
assertionFailure("field 'character_grid' is not a [[String]]")
return nil
}
guard let wordLocations_field: AnyObject = dict["word_locations"] else {
assertionFailure("field 'word_locations' is missing")
return nil
}
guard let wordLocations: [WordLocation] = WordLocation.decodeJson(wordLocations_field) else {
assertionFailure("field word_locations is not word locations")
return nil
}
let rows = characterGrid.count
let columns = characterGrid.first!.count
return Puzzle(sourceLanguage: sourceLanguage, targetLanguage: targetLanguage, word: word, characterGrid: characterGrid, wordLocations: wordLocations, rows: rows, columns: columns)
}
}
| mit | bfce205131f5510fef423a40e5baa6e9 | 35.594937 | 187 | 0.626427 | 4.670436 | false | false | false | false |
LamGiauKhongKhoTeam/LGKK | ModulesTests/CryptoSwiftTests/PBKDF.swift | 1 | 4251 | //
// PBKDF.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 04/04/16.
// Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
//
import XCTest
@testable import CryptoSwift
class PBKDF: XCTestCase {
func testPBKDF1() {
let password: Array<UInt8> = [0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64]
let salt: Array<UInt8> = [0x78, 0x57, 0x8E, 0x5A, 0x5D, 0x63, 0xCB, 0x06]
let value = try! PKCS5.PBKDF1(password: password, salt: salt, iterations: 1000, keyLength: 16).calculate()
XCTAssertEqual(value.toHexString(), "dc19847e05c64d2faf10ebfb4a3d2a20")
}
func testPBKDF2() {
// P = "password", S = "salt", c = 1, dkLen = 20
XCTAssertEqual([0x0c, 0x60, 0xc8, 0x0f, 0x96, 0x1f, 0x0e, 0x71, 0xf3, 0xa9, 0xb5, 0x24, 0xaf, 0x60, 0x12, 0x06, 0x2f, 0xe0, 0x37, 0xa6],
try PKCS5.PBKDF2(password: [0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64], salt: [0x73, 0x61, 0x6C, 0x74], iterations: 1, keyLength: 20, variant: .sha1).calculate())
// P = "password", S = "salt", c = 2, dkLen = 20
XCTAssertEqual([0xea, 0x6c, 0x01, 0x4d, 0xc7, 0x2d, 0x6f, 0x8c, 0xcd, 0x1e, 0xd9, 0x2a, 0xce, 0x1d, 0x41, 0xf0, 0xd8, 0xde, 0x89, 0x57],
try PKCS5.PBKDF2(password: [0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64], salt: [0x73, 0x61, 0x6C, 0x74], iterations: 2, keyLength: 20, variant: .sha1).calculate())
// P = "password", S = "salt", c = 4096, dkLen = 20
XCTAssertEqual([0x4b, 0x00, 0x79, 0x01, 0xb7, 0x65, 0x48, 0x9a, 0xbe, 0xad, 0x49, 0xd9, 0x26, 0xf7, 0x21, 0xd0, 0x65, 0xa4, 0x29, 0xc1],
try PKCS5.PBKDF2(password: [0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64], salt: [0x73, 0x61, 0x6C, 0x74], iterations: 4096, keyLength: 20, variant: .sha1).calculate())
// P = "password", S = "salt", c = 16777216, dkLen = 20
// Commented because it takes a lot of time with Debug build to finish.
// XCTAssertEqual([0xee, 0xfe, 0x3d, 0x61, 0xcd, 0x4d, 0xa4, 0xe4, 0xe9, 0x94, 0x5b, 0x3d, 0x6b, 0xa2, 0x15, 0x8c, 0x26, 0x34, 0xe9, 0x84],
// try PKCS5.PBKDF2(password: [0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64], salt: [0x73, 0x61, 0x6C, 0x74], iterations: 16777216, keyLength: 20, variant: .sha1).calculate())
// P = "passwordPASSWORDpassword", S = "saltSALTsaltSALTsaltSALTsaltSALTsalt", c = 4096, dkLen = 25
XCTAssertEqual([0x3d, 0x2e, 0xec, 0x4f, 0xe4, 0x1c, 0x84, 0x9b, 0x80, 0xc8, 0xd8, 0x36, 0x62, 0xc0, 0xe4, 0x4a, 0x8b, 0x29, 0x1a, 0x96, 0x4c, 0xf2, 0xf0, 0x70, 0x38],
try PKCS5.PBKDF2(password: [0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64, 0x50, 0x41, 0x53, 0x53, 0x57, 0x4F, 0x52, 0x44, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64], salt: [0x73, 0x61, 0x6C, 0x74, 0x53, 0x41, 0x4C, 0x54, 0x73, 0x61, 0x6C, 0x74, 0x53, 0x41, 0x4C, 0x54, 0x73, 0x61, 0x6C, 0x74, 0x53, 0x41, 0x4C, 0x54, 0x73, 0x61, 0x6C, 0x74, 0x53, 0x41, 0x4C, 0x54, 0x73, 0x61, 0x6C, 0x74], iterations: 4096, keyLength: 25, variant: .sha1).calculate())
// P = "pass\0word", S = "sa\0lt", c = 4096, dkLen = 16
XCTAssertEqual([0x56, 0xfa, 0x6a, 0xa7, 0x55, 0x48, 0x09, 0x9d, 0xcc, 0x37, 0xd7, 0xf0, 0x34, 0x25, 0xe0, 0xc3],
try PKCS5.PBKDF2(password: [0x70, 0x61, 0x73, 0x73, 0x00, 0x77, 0x6F, 0x72, 0x64], salt: [0x73, 0x61, 0x00, 0x6C, 0x74], iterations: 4096, keyLength: 16, variant: .sha1).calculate())
}
func testPBKDF2Length() {
let password: Array<UInt8> = Array("s33krit".utf8)
let salt: Array<UInt8> = Array("nacl".utf8)
let value = try! PKCS5.PBKDF2(password: password, salt: salt, iterations: 2, keyLength: 8, variant: .sha1).calculate()
XCTAssert(value.toHexString() == "a53cf3df485e5cd9", "PBKDF2 fail")
}
func testPerformance() {
let password: Array<UInt8> = Array("s33krit".utf8)
let salt: Array<UInt8> = Array("nacl".utf8)
measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true, for: { () -> Void in
let _ = try! PKCS5.PBKDF2(password: password, salt: salt, iterations: 65536, keyLength: 32, variant: .sha1).calculate()
})
}
}
| mit | 098bfdce37813ad5c391d2a5dbdaa4df | 67.548387 | 481 | 0.625176 | 2.335165 | false | true | false | false |
carlospaelinck/pokebattle | PokéBattle/PokémonInstance.swift | 1 | 4574 | //
// PokémonInstance.swift
// PokéBattle
//
// Created by Carlos Paelinck on 4/11/16.
// Copyright © 2016 Carlos Paelinck. All rights reserved.
//
import Foundation
class PokémonInstance: NSObject, NSCoding {
var basePokémon: Pokémon
var level: Int
var nature: Nature
var IVs: Stats
var EVs: Stats
var attacks: [Attack]
init(basePokémon: Pokémon, level: Int, nature: Nature, IVs: Stats, EVs: Stats, attacks: [Attack]) {
self.basePokémon = basePokémon
self.level = level
self.nature = nature
self.IVs = IVs
self.EVs = EVs
self.attacks = attacks
}
required init?(coder aDecoder: NSCoder) {
basePokémon = aDecoder.decodeObjectForKey("basePokémon") as! Pokémon
level = aDecoder.decodeObjectForKey("level") as! Int
IVs = aDecoder.decodeObjectForKey("IVs") as! Stats
EVs = aDecoder.decodeObjectForKey("EVs") as! Stats
attacks = aDecoder.decodeObjectForKey("attacks") as! [Attack]
let natureValue = aDecoder.decodeObjectForKey("nature") as! Int
nature = Nature(rawValue: natureValue)!
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(basePokémon, forKey: "basePokémon")
aCoder.encodeObject(level, forKey: "level")
aCoder.encodeObject(IVs, forKey: "IVs")
aCoder.encodeObject(EVs, forKey: "EVs")
aCoder.encodeObject(attacks, forKey: "attacks")
aCoder.encodeObject(nature.rawValue, forKey: "nature")
}
var hitPoints: Double {
let base = 2 * Double(basePokémon.stats.hitPoints) + Double(IVs.hitPoints) + floor(Double(EVs.hitPoints) / 4.0)
return floor((floor(base * Double(level)) / 100) + Double(level) + 10.0)
}
var attack: Double {
let natureMultiplier: Double
switch nature {
case .Adamant, .Brave, .Lonely, .Naughty:
natureMultiplier = 1.1
case .Bold, .Modest, .Calm, .Timid:
natureMultiplier = 0.9
default: natureMultiplier = 1
}
let base = 2 * Double(basePokémon.stats.attack) + Double(IVs.attack) + floor(Double(EVs.attack) / 4.0)
return floor((floor((base * Double(level)) / 100) + 5.0) * natureMultiplier)
}
var defense: Double {
let natureMultiplier: Double
switch nature {
case .Bold, .Relaxed, .Impish, .Lax:
natureMultiplier = 1.1
case .Lonely, .Hasty, .Mild, .Gentle:
natureMultiplier = 0.9
default: natureMultiplier = 1
}
let base = 2 * Double(basePokémon.stats.defense) + Double(IVs.defense) + floor(Double(EVs.defense) / 4.0)
return floor((floor((base * Double(level)) / 100) + 5.0) * natureMultiplier)
}
var specialAttack: Double {
let natureMultiplier: Double
switch nature {
case .Modest, .Mild, .Quiet, .Rash:
natureMultiplier = 1.1
case .Adamant, .Jolly, .Impish, .Careful:
natureMultiplier = 0.9
default: natureMultiplier = 1
}
let base = 2 * Double(basePokémon.stats.specialAttack) + Double(IVs.specialAttack) + floor(Double(EVs.specialAttack) / 4.0)
return floor((floor((base * Double(level)) / 100) + 5.0) * natureMultiplier)
}
var specialDefense: Double {
let natureMultiplier: Double
switch nature {
case .Calm, .Careful, .Sassy, .Gentle:
natureMultiplier = 1.1
case .Naughty, .Naive, .Rash, .Lax:
natureMultiplier = 0.9
default: natureMultiplier = 1
}
let base = 2 * Double(basePokémon.stats.specialDefense) + Double(IVs.specialDefense) + floor(Double(EVs.specialDefense) / 4.0)
return floor((floor((base * Double(level)) / 100) + 5.0) * natureMultiplier)
}
var speed: Double {
let natureMultiplier: Double
switch nature {
case .Timid, .Jolly, .Hasty, .Naive:
natureMultiplier = 1.1
case .Quiet, .Sassy, .Brave, .Relaxed:
natureMultiplier = 0.9
default: natureMultiplier = 1
}
let base = 2 * Double(basePokémon.stats.speed) + Double(IVs.speed) + floor(Double(EVs.speed) / 4.0)
return floor((floor((base * Double(level)) / 100) + 5.0) * natureMultiplier)
}
override var description: String {
return "\(basePokémon.name) @ Lv.\(level)\n---\nHP: \(hitPoints)\nAtk: \(attack)\nDef: \(defense)\nSpAtk: \(specialAttack)\nSpDef: \(specialDefense)\nSpd: \(speed)"
}
} | mit | d39e4bb37645583b32807517a1d7b68c | 31.06338 | 172 | 0.61094 | 3.612698 | false | false | false | false |
AlvinL33/TownHunt | TownHunt-1.9/TownHunt/PinPackMapViewController.swift | 1 | 2300 | //
// PinPackMapViewController.swift
// TownHunt
//
// Created by Alvin Lee on 07/04/2017.
// Copyright © 2017 LeeTech. All rights reserved.
//
import MapKit
import CoreData
import Foundation
class PinPackMapViewController: UIViewController {
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.
}
// Returns an array of Pin Location objects
func getListOfPinLocations(packData: [String: Any]) -> [PinLocation] {
let packDetailPinList = packData["Pins"] as! [[String:String]]
var gamePins: [PinLocation] = []
if packDetailPinList.isEmpty {
print(packDetailPinList)
print("No Pins in pack")
} else{
print("There are pins in the loaded pack")
for pin in packDetailPinList{
let pinToAdd = PinLocation(title: pin["Title"]!, hint: pin["Hint"]!, codeword: pin["Codeword"]!, coordinate: CLLocationCoordinate2D(latitude: Double(pin["CoordLatitude"]!)!, longitude: Double(pin["CoordLongitude"]!)!), pointVal: Int(pin["PointValue"]!)!)
gamePins.append(pinToAdd)
}
}
return gamePins
}
// Returns all of the pack data loaded from local storage
func loadPackFromFile(filename: String, userPackDictName: String, selectedPackKey: String, userID: String) -> [String : AnyObject]{
var packData: [String : AnyObject] = [:]
let defaults = UserDefaults.standard
let localStorageHandler = LocalStorageHandler(fileName: filename, subDirectory: "User-\(userID)-Packs", directory: .documentDirectory)
let retrievedJSON = localStorageHandler.retrieveJSONData()
packData = retrievedJSON as! [String : AnyObject]
return packData
}
func displayAlertMessage(alertTitle: String, alertMessage: String){
let alertCon = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
alertCon.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alertCon, animated: true, completion: nil)
}
}
| apache-2.0 | 96b4902c37e2093bed33dd2cafb92876 | 39.333333 | 270 | 0.664637 | 4.635081 | false | false | false | false |
arnaudbenard/npm-stats | Pods/Charts/Charts/Classes/Data/CandleChartDataSet.swift | 19 | 3016 | //
// CandleChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class CandleChartDataSet: BarLineScatterCandleChartDataSet
{
/// the width of the candle-shadow-line in pixels.
/// :default: 3.0
public var shadowWidth = CGFloat(1.5)
/// the space between the candle entries
/// :default: 0.1 (10%)
private var _bodySpace = CGFloat(0.1)
/// the color of the shadow line
public var shadowColor: UIColor?
/// use candle color for the shadow
public var shadowColorSameAsCandle = false
/// color for open <= close
public var decreasingColor: UIColor?
/// color for open > close
public var increasingColor: UIColor?
/// Are decreasing values drawn as filled?
public var decreasingFilled = false
/// Are increasing values drawn as filled?
public var increasingFilled = true
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label)
}
internal override func calcMinMax(#start: Int, end: Int)
{
if (yVals.count == 0)
{
return
}
var entries = yVals as! [CandleChartDataEntry]
var endValue : Int
if end == 0
{
endValue = entries.count - 1
}
else
{
endValue = end
}
_lastStart = start
_lastEnd = end
_yMin = entries[start].low
_yMax = entries[start].high
for (var i = start + 1; i <= endValue; i++)
{
var e = entries[i]
if (e.low < _yMin)
{
_yMin = e.low
}
if (e.high > _yMax)
{
_yMax = e.high
}
}
}
/// the space that is left out on the left and right side of each candle,
/// :default: 0.1 (10%), max 0.45, min 0.0
public var bodySpace: CGFloat
{
set
{
_bodySpace = newValue
if (_bodySpace < 0.0)
{
_bodySpace = 0.0
}
if (_bodySpace > 0.45)
{
_bodySpace = 0.45
}
}
get
{
return _bodySpace
}
}
/// Is the shadow color same as the candle color?
public var isShadowColorSameAsCandle: Bool { return shadowColorSameAsCandle }
/// Are increasing values drawn as filled?
public var isIncreasingFilled: Bool { return increasingFilled; }
/// Are decreasing values drawn as filled?
public var isDecreasingFilled: Bool { return decreasingFilled; }
} | mit | 79264ca7f656781f4fae0fd836418d33 | 23.330645 | 81 | 0.532162 | 4.625767 | false | false | false | false |
planvine/Line-Up-iOS-SDK | Pod/Classes/Line-Up_ExtCoreData.swift | 1 | 13005 | /**
* Copyright (c) 2016 Line-Up
*
* 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
extension LineUp {
//MARK: - CoreData methods
/**
* Get the event (PVEvent) with id: 'id' from CoreData.
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getEventFromCoreData(id: NSNumber) -> PVEvent? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVEvent, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"eventID = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVEvent)!
}
} catch { return nil }
return nil
}
class func getVenueFromCoreData(id: NSNumber) -> PVVenue? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVVenue, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"venueID = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVVenue)!
}
} catch { return nil }
return nil
}
/**
* Get the performance (PVPerformance) with id: 'id' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
public class func getPerformanceFromCoreData(id: NSNumber) -> PVPerformance? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVPerformance, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"performanceID = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVPerformance)!
}
} catch { return nil }
return nil
}
/**
* It returns true if the performance with id: 'id' has tickets, false otherwise
*/
class func performanceHasTickets(id: NSNumber) -> Bool {
var perf : PVPerformance? = getPerformanceFromCoreData(id)
if perf == nil {
perf = getPerformance(id)
}
if perf != nil && perf!.hasTickets == true {
return true
}
return false
}
/**
* Get the user (PVUser) with accessToken: 'userToken' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
public class func getUserWithTokenFromCoreData(userToken: String) -> PVUser? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVUser, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"accessToken = %@",userToken)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVUser)!
}
} catch { return nil }
return nil
}
/**
* Get the ticket (PVTicket) with id: 'id' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
public class func getTicketFromCoreData(id: NSNumber) -> PVTicket? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVTicket, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"id = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVTicket)!
}
} catch { return nil }
return nil
}
/**
* Get the receipts (array of PVReceipt) for the usen with token: 'userToken' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getTicketsReceiptsFromCoreData(userToken: String) -> [PVReceipt]? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVReceipt, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"user.accessToken = %@",userToken)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
guard objects.count > 0 else {
return nil
}
return objects as? Array<PVReceipt>
} catch {
return nil
}
}
/**
* Get the receipt (PVReceipt) with id: 'id' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getReceiptFromCoreData(id: NSNumber) -> PVReceipt? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVReceipt, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"id = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
guard objects.count > 0 else {
return nil
}
return (objects.lastObject as? PVReceipt)
} catch {
return nil
}
}
/**
* Get list of tickets (array of PVTicket) available for the performance with id: 'performanceId' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getTicketsFromCoreDataOfPerformance(performanceId: NSNumber) -> [PVTicket] {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVPerformance, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"performanceID = %@",performanceId)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 && (objects.lastObject as! PVPerformance).tickets != nil && (objects.lastObject as! PVPerformance).tickets!.allObjects.count > 0{
return (objects.lastObject as? PVPerformance)!.tickets!.allObjects as! Array<PVTicket>
}
} catch { return Array() }
return Array()
}
/**
* Get list of credit cards (array of PVCard for the user with Line-Up token: 'userToken' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getCardsFromCoreData(userToken: String) -> (NSFetchRequest, [PVCard]?) {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)!
let sortDescriptor1 = NSSortDescriptor(key: "selectedCard", ascending: false)
let sortDescriptor2 = NSSortDescriptor(key: "brand", ascending: false)
let sortDescriptor3 = NSSortDescriptor(key: "expYear", ascending: false)
let sortDescriptor4 = NSSortDescriptor(key: "expMonth", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor1,sortDescriptor2,sortDescriptor3,sortDescriptor4]
fetchRequest.predicate = NSPredicate(format: "user.accessToken = %@",userToken)
do {
return (fetchRequest,try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) as? Array<PVCard>)
} catch {
return (fetchRequest,nil)
}
}
/**
* Get list of credit cards (array of PVCard for the user with Line-Up token: 'userToken' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getCardFromCoreData(id: String) -> PVCard? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"id = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVCard)!
}
} catch { return nil }
return nil
}
/**
* Delete all the credit cards from CoreData except the cards in 'listOfCards'
*/
public class func deleteCardsFromCoreDataExcept(listOfCards: Array<PVCard>, userToken: String) {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)!
let sortDescriptor1 = NSSortDescriptor(key: "selectedCard", ascending: false)
let sortDescriptor2 = NSSortDescriptor(key: "brand", ascending: false)
let sortDescriptor3 = NSSortDescriptor(key: "expYear", ascending: false)
let sortDescriptor4 = NSSortDescriptor(key: "expMonth", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor1,sortDescriptor2,sortDescriptor3,sortDescriptor4]
var listOfIds: Array<String> = Array()
for card in listOfCards {
if card.id != nil {
listOfIds.append(card.id!)
}
}
fetchRequest.predicate = NSPredicate(format: "user.accessToken = %@ && NOT id IN %@",userToken, listOfIds)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
for managedObject in objects {
PVCoreData.managedObjectContext.deleteObject(managedObject as! NSManagedObject)
}
try PVCoreData.managedObjectContext.save()
} catch { }
}
/**
* Set the card (PVCard) as selected card (default one) on the device (CoreData)
*/
public class func setSelectedCard(card: PVCard) {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)!
do {
let objects : Array<PVCard> = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) as! Array<PVCard>
for obj in objects {
if obj.id != card.id {
obj.selectedCard = false
} else {
obj.selectedCard = true
}
}
try PVCoreData.managedObjectContext.save()
} catch { }
}
}
| mit | 36cf39ac119b6c4f5806f267e145bace | 46.637363 | 162 | 0.665283 | 5.11002 | false | false | false | false |
IDLabs-Gate/enVision | enVision/kNN.swift | 2 | 2285 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 ID Labs L.L.C.
//
// 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 KNN {
private let kNN = tfkNN()
private var loaded = false
func load(){
kNN.loadModel("kNN.pb")
loaded = true
}
func run(x: [Double], samples: [[Double]], classes: [Int]) -> (Int, Double){
guard classes.count>0 && samples.count==classes.count else { return (-1,0) }
if !loaded { load() }
//choosing k = n^(1/2), but not more than the min count/2 of samples in a class
let minCount = Set(classes).map { c in classes.filter { $0==c }.count }.min{ a,b in a<b }!
var k = Int(sqrt(Double(samples.count)))
if k>minCount/2 { k = minCount/2 }
if k<1 { k = 1 }
print ("K", k)
let c = kNN.classify(x, samples: samples, classes: classes, k: Int32(k))
guard let pred = c?.first?.key as? Int else { return (-1,0) }
guard let dist = c?.first?.value as? Double else { return (-1,0) }
return (pred,dist)
}
func clean(){
kNN.clean()
loaded = false;
}
}
| mit | 11e1f81ce4813fe9d1d986676eb3e06b | 35.854839 | 98 | 0.623195 | 3.912671 | false | false | false | false |
lcddhr/DouyuTV | DouyuTV/Vender/DDKit/UIimage/UIImage+Asset.swift | 2 | 1055 | //
// UIImage+Asset.swift
// DouyuTV
//
// Created by lovelydd on 16/1/14.
// Copyright © 2016年 xiaomutou. All rights reserved.
//
import Foundation
import UIKit
extension UIImage {
enum Asset : String {
case Btn_search = "btn_search"
case Btn_search_clicked = "btn_search_clicked"
case Image_scan = "Image_scan"
case Image_scan_click = "Image_scan_click"
case Logo = "logo"
case S_logo = "s_logo"
case Btn_column_normal = "btn_column_normal"
case Btn_column_selected = "btn_column_selected"
case Btn_home_normal = "btn_home_normal"
case Btn_home_selected = "btn_home_selected"
case Btn_live_normal = "btn_live_normal"
case Btn_live_selected = "btn_live_selected"
case Btn_user_normal = "btn_user_normal"
case Btn_user_selected = "btn_user_selected"
var image: UIImage {
return UIImage(asset: self)
}
}
convenience init!(asset: Asset) {
self.init(named: asset.rawValue)
}
} | mit | 17073d3f99bcd7292d0f3ac7678ab6e2 | 28.25 | 56 | 0.604563 | 3.530201 | false | false | false | false |
iqingchen/DouYuZhiBo | DY/DY/Classes/Home/Controller/GameViewController.swift | 1 | 4771 | //
// GameViewController.swift
// DY
//
// Created by zhang on 16/12/6.
// Copyright © 2016年 zhang. All rights reserved.
//
import UIKit
//MARK: - 定义常量
private let kEdgeMargin : CGFloat = 10
private let kItemW : CGFloat = (kScreenW - 2 * kEdgeMargin) / 3
private let kItemH : CGFloat = kItemW * 6 / 5
private let kHeaderViewH : CGFloat = 50
private let kGameViewH : CGFloat = 90
private let kGameCellID : String = "kGameCellID"
private let kReusableViewHeadID : String = "kReusableViewHeadID"
class GameViewController: BaseViewController {
//MARK: - 懒加载
fileprivate lazy var gameViewModel : GameViewModel = GameViewModel()
fileprivate lazy var commonHeaderView : CollectionHeaderView = {
let header = CollectionHeaderView.collectionHeaderView()
header.frame = CGRect(x: 0, y: -(kHeaderViewH + kGameViewH), width: kScreenW, height: kHeaderViewH)
header.titleLabel.text = "常见"
header.iconImageView.image = UIImage(named: "Img_orange")
header.moreBtn.isHidden = true
return header
}()
fileprivate lazy var recommendGameView : RecommendGameView = {
let gameView = RecommendGameView.createRecommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kItemH)
layout.sectionInset = UIEdgeInsetsMake(0, kEdgeMargin, 0, kEdgeMargin)
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.white
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kReusableViewHeadID)
return collectionView
}()
//MARK: - 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
//设置ui
setupUI()
//网络请求
requestData()
}
}
//MARK: - 设置UI
extension GameViewController {
override func setupUI() {
contentView = collectionView
//添加collectionView
view.addSubview(collectionView)
//添加常见header
collectionView.addSubview(commonHeaderView)
//添加常见游戏View
collectionView.addSubview(recommendGameView)
collectionView.contentInset = UIEdgeInsetsMake(kHeaderViewH + kGameViewH, 0, 0, 0)
super.setupUI()
}
}
//MARK: - 网络请求
extension GameViewController {
fileprivate func requestData() {
gameViewModel.loadAllGanmesData {
//1.刷新表格
self.collectionView.reloadData()
//2.讲数据传给recommendGameView
self.recommendGameView.baseGameModel = Array(self.gameViewModel.games[0..<10])
//数据请求完成
self.loadDataFinished()
}
}
}
//MARK: - 实现collectionView的数据源方法
extension GameViewController : UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gameViewModel.games.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell
cell.baseGame = gameViewModel.games[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kReusableViewHeadID, for: indexPath) as! CollectionHeaderView
let group = AnchorGroup()
group.tag_name = "全部"
group.icon_name = "Img_orange"
header.group = group
header.moreBtn.isHidden = true
return header
}
}
| mit | 7ae1606747d042ec912edcad0ebb5fc7 | 37.666667 | 192 | 0.69181 | 5.32721 | false | false | false | false |
khizkhiz/swift | test/SILOptimizer/definite_init_failable_initializers_diagnostics.swift | 2 | 2561 | // RUN: %target-swift-frontend -emit-sil -disable-objc-attr-requires-foundation-module -verify %s
// High-level tests that DI rejects certain invalid idioms for early
// return from initializers.
// <rdar://problem/19267795> failable initializers that call noreturn function produces bogus diagnostics
class FailableInitThatFailsReallyHard {
init?() { // no diagnostics generated.
fatalError("bad")
}
}
class BaseClass {}
final class DerivedClass : BaseClass {
init(x : ()) {
fatalError("bad") // no diagnostics.
}
}
func something(x: Int) {}
func something(x: inout Int) {}
func something(x: AnyObject) {}
func something(x: Any.Type) {}
// <rdar://problem/22946400> DI needs to diagnose self usages in error block
//
// FIXME: crappy QoI
class ErrantBaseClass {
init() throws {}
}
class ErrantClass : ErrantBaseClass {
let x: Int
var y: Int
override init() throws {
x = 10
y = 10
try super.init()
}
init(invalidEscapeDesignated: ()) {
x = 10
y = 10
do {
try super.init()
} catch {}
} // expected-error {{'self' used inside 'catch' block reachable from super.init call}}
convenience init(invalidEscapeConvenience: ()) {
do {
try self.init()
} catch {}
} // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
init(noEscapeDesignated: ()) throws {
x = 10
y = 10
do {
try super.init()
} catch let e {
throw e // ok
}
}
convenience init(noEscapeConvenience: ()) throws {
do {
try self.init()
} catch let e {
throw e // ok
}
}
convenience init(invalidAccess: ()) throws {
do {
try self.init()
} catch let e {
something(x) // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
something(self.x) // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
something(y) // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
something(self.y) // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
something(&y) // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
something(&self.y) // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
something(self) // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
// FIXME: not diagnosed
something(self.dynamicType)
throw e
}
}
}
| apache-2.0 | d0b22b42f3e326165207a92ff19b2d7a | 24.868687 | 109 | 0.643108 | 3.83958 | false | false | false | false |
khizkhiz/swift | test/ClangModules/objc_init.swift | 2 | 4584 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil -I %S/Inputs/custom-modules %s -verify
// REQUIRES: objc_interop
// REQUIRES: OS=macosx
// FIXME: <rdar://problem/19452886> test/ClangModules/objc_init.swift should not require REQUIRES: OS=macosx
import AppKit
import objc_ext
import TestProtocols
import ObjCParseExtras
// rdar://problem/18500201
extension NSSet {
convenience init<T>(array: Array<T>) {
self.init()
}
}
// Subclassing and designated initializers
func testNSInterestingDesignated() {
NSInterestingDesignated() // expected-warning{{unused}}
NSInterestingDesignated(string:"hello") // expected-warning{{unused}}
NSInterestingDesignatedSub() // expected-warning{{unused}}
NSInterestingDesignatedSub(string:"hello") // expected-warning{{unused}}
}
extension URLDocument {
convenience init(string: String) {
self.init(url: string)
}
}
class MyDocument1 : URLDocument {
override init() {
super.init()
}
}
func createMyDocument1() {
var md = MyDocument1()
md = MyDocument1(url: "http://llvm.org")
// Inherited convenience init.
md = MyDocument1(string: "http://llvm.org")
_ = md
}
class MyDocument2 : URLDocument {
init(url: String) {
super.init(url: url) // expected-error{{must call a designated initializer of the superclass 'URLDocument'}}
}
}
class MyDocument3 : NSAwesomeDocument {
override init() {
super.init()
}
}
func createMyDocument3(url: NSURL) {
var md = MyDocument3()
md = try! MyDocument3(contentsOf: url, ofType:"")
_ = md
}
class MyInterestingDesignated : NSInterestingDesignatedSub {
override init(string str: String) {
super.init(string: str)
}
init(int i: Int) {
super.init() // expected-error{{must call a designated initializer of the superclass 'NSInterestingDesignatedSub'}}
}
}
func createMyInterestingDesignated() {
_ = MyInterestingDesignated(url: "http://llvm.org")
}
func testNoReturn(a : NSAwesomeDocument) -> Int {
a.noReturnMethod(42)
return 17 // TODO: In principle, we should produce an unreachable code diagnostic here.
}
// Initializer inheritance from protocol-specified initializers.
class MyViewController : NSViewController {
}
class MyView : NSView {
override init() { super.init() }
} // expected-error{{'required' initializer 'init(coder:)' must be provided by subclass of 'NSView'}}
class MyMenu : NSMenu {
override init(title: String) { super.init(title: title) }
} // expected-error{{'required' initializer 'init(coder:)' must be provided by subclass of 'NSMenu'}}
class MyTableViewController : NSTableViewController {
}
class MyOtherTableViewController : NSTableViewController {
override init(int i: Int) {
super.init(int: i)
}
} // expected-error{{'required' initializer 'init(coder:)' must be provided by subclass of 'NSTableViewController'}}
class MyThirdTableViewController : NSTableViewController {
override init(int i: Int) {
super.init(int: i)
}
required init(coder: NSCoder) {
super.init(coder: coder)!
}
}
func checkInitWithCoder(coder: NSCoder) {
NSViewController(coder: coder) // expected-warning{{unused}}
NSTableViewController(coder: coder) // expected-warning{{unused}}
MyViewController(coder: coder) // expected-warning{{unused}}
MyTableViewController(coder: coder) // expected-warning{{unused}}
MyOtherTableViewController(coder: coder) // expected-error{{incorrect argument label in call (have 'coder:', expected 'int:')}}
MyThirdTableViewController(coder: coder) // expected-warning{{unused}}
}
// <rdar://problem/16838409>
class MyDictionary1 : NSDictionary {}
func getMyDictionary1() {
_ = MyDictionary1()
}
// <rdar://problem/16838515>
class MyDictionary2 : NSDictionary {
override init() {
super.init()
}
}
class MyString : NSString {
override init() { super.init() }
} // expected-error{{'required' initializer 'init(coder:)' must be provided by subclass of 'NSString'}}
// <rdar://problem/17281900>
class View: NSView {
override func addSubview(aView: NSView) {
_ = MyViewController.init()
}
}
// rdar://problem/19726164
class NonNullDefaultInitSubSub : NonNullDefaultInitSub {
func foo() {
_ = NonNullDefaultInitSubSub() as NonNullDefaultInitSubSub?
}
}
class DesignatedInitSub : DesignatedInitBase {
var foo: Int?
override init(int: Int) {}
}
class DesignedInitSubSub : DesignatedInitSub {
init(double: Double) { super.init(int: 0) } // okay
init(string: String) { super.init() } // expected-error {{must call a designated initializer of the superclass 'DesignatedInitSub'}}
}
| apache-2.0 | 10a076ea591c51d0c9a356051cb0b8a5 | 26.614458 | 134 | 0.71575 | 3.766639 | false | false | false | false |
amolloy/LinkAgainstTheWorld | Frameworks/TileMap/TileMap/Layer.swift | 2 | 2344 | //
// Layer.swift
// TileMap
//
// Created by Andrew Molloy on 8/9/15.
// Copyright © 2015 Andrew Molloy. All rights reserved.
//
import Foundation
protocol Tileable
{
}
class Layer : Loadable
{
var chunkType : ChunkType?
let tiles : [[Tileable]]
required init?(inputStream: NSInputStream, dataLength: Int, tileMap: TileMap, chunkType: ChunkType)
{
guard let mapHeader = tileMap.mapHeader,
let blockData = tileMap.blockData,
let animationData = tileMap.animationData else
{
tiles = [[Tileable]]()
return nil
}
let swapBytes = mapHeader.swapBytes
var tileRows = [[Tileable]]()
if mapHeader.mapType == .FMP05
{
for _ in 0..<mapHeader.mapSize.height
{
var tileColumns = [Tileable]()
for _ in 0..<mapHeader.mapSize.width
{
guard let tile = inputStream.readInt16(swapBytes) else
{
tiles = [[Tileable]]()
return nil
}
if tile >= 0
{
let theIndex = Int(tile) / mapHeader.blockStructureSize
tileColumns.append(blockData.blockStructures[theIndex])
}
else
{
let divisor : Int
if .FMP05 == mapHeader.mapType
{
divisor = 16
}
else
{
divisor = 1
}
let theIndex = Int(-tile) / divisor - 1
tileColumns.append(animationData.animationStructures[theIndex])
}
}
tileRows.append(tileColumns)
}
}
else if mapHeader.mapType == .FMP10
{
// TODO
assert(false, "FMP 1.0 Maps not yet implemented")
}
else if mapHeader.mapType == .FMP10RLE
{
// TODO
assert(false, "FMP 1.0RLE Maps not yet implemented")
}
else
{
// TODO Throw too new (shouldn't even get here in that case)
tiles = [[Tileable]]()
return nil
}
tiles = tileRows
tileMap.addLayer(self, index: chunkType.layer())
}
static func registerWithTileMap(tileMap: TileMap)
{
tileMap.registerLoadable(self, chunkType: ChunkType.BODY)
tileMap.registerLoadable(self, chunkType: ChunkType.LYR1)
tileMap.registerLoadable(self, chunkType: ChunkType.LYR2)
tileMap.registerLoadable(self, chunkType: ChunkType.LYR3)
tileMap.registerLoadable(self, chunkType: ChunkType.LYR4)
tileMap.registerLoadable(self, chunkType: ChunkType.LYR5)
tileMap.registerLoadable(self, chunkType: ChunkType.LYR6)
tileMap.registerLoadable(self, chunkType: ChunkType.LYR7)
}
}
| mit | 184570b0afd5db77bf2ebfdb0c5ff656 | 21.970588 | 100 | 0.66624 | 3.249653 | false | false | false | false |
aliceatlas/hexagen | Hexagen/Swift/Task/GeneratorTask.swift | 1 | 1197 | /*****\\\\
/ \\\\ Swift/Task/GeneratorTask.swift
/ /\ /\ \\\\ (part of Hexagen)
\ \_X_/ ////
\ //// Copyright © 2015 Alice Atlas (see LICENSE.md)
\*****////
public final class AsyncGen<OutType, ReturnType>: Async<ReturnType> {
private let feed: Feed<OutType>
public init(queue: dispatch_queue_t = mainQueue, body: (OutType -> Void) -> ReturnType) {
var post: (OutType -> Void)!
var end: (Void -> Void)!
feed = Feed<OutType> { (_post, _end) in
post = _post
end = _end
}
super.init(queue: queue, start: false, body: {
let ret = body(post!)
end()
return ret
})
}
}
extension AsyncGen: SequenceType {
public func generate() -> Subscription<OutType> {
let gen = feed.generate()
if !started {
start()
}
return gen
}
public func map<T>(fn: OutType -> T) -> LazySequence<MapSequenceView<AsyncGen, T>> {
return lazy(self).map(fn)
}
public func filter(fn: OutType -> Bool) -> LazySequence<FilterSequenceView<AsyncGen>> {
return lazy(self).filter(fn)
}
}
| mit | 9dbfb14876211c724778602adb61d96d | 26.813953 | 93 | 0.521739 | 3.725857 | false | false | false | false |
manGoweb/S3 | Sources/S3Kit/URLBuilder/S3URLBuilder.swift | 1 | 1772 | import Foundation
import S3Signer
/// URL builder
public final class S3URLBuilder: URLBuilder {
/// Default bucket
let defaultBucket: String
/// S3 Configuration
let config: S3Signer.Config
/// Initializer
public init(defaultBucket: String, config: S3Signer.Config) {
self.defaultBucket = defaultBucket
self.config = config
}
/// Plain Base URL with no bucket specified
/// *Format: https://s3.eu-west-2.amazonaws.com/
public func plain(region: Region? = nil) throws -> URL {
let urlString = (region ?? config.region).hostUrlString()
guard let url = URL(string: urlString) else {
throw S3.Error.invalidUrl
}
return url
}
/// Base URL for S3 region
/// *Format: https://bucket.s3.eu-west-2.amazonaws.com/path_or_parameter*
public func url(region: Region? = nil, bucket: String? = nil, path: String? = nil) throws -> URL {
let urlString = (region ?? config.region).hostUrlString(bucket: (bucket ?? defaultBucket))
guard let url = URL(string: urlString) else {
throw S3.Error.invalidUrl
}
return url
}
/// Base URL for a file in a bucket
/// * Format: https://s3.eu-west-2.amazonaws.com/bucket/file.txt
/// * We can't have a bucket in the host or DELETE will attempt to delete the bucket, not file!
public func url(file: LocationConvertible) throws -> URL {
let urlString = (file.region ?? config.region).hostUrlString()
guard let url = URL(string: urlString)?.appendingPathComponent(file.bucket ?? defaultBucket).appendingPathComponent(file.path) else {
throw S3.Error.invalidUrl
}
return url
}
}
| mit | 38b3692554280010cb6e7d6fc55ddcac | 33.745098 | 141 | 0.623589 | 4.169412 | false | true | false | false |
johndpope/Cerberus | Cerberus/Classes/TimelineCollectionViewController.swift | 1 | 5379 | import UIKit
import Timepiece
class TimelineCollectionViewController: UICollectionViewController {
var timeArray = [String]()
private var timer: NSTimer?
private let timerTickIntervalSec = 60.0
override func viewDidLoad() {
super.viewDidLoad()
generateTimeLabels()
collectionView?.showsVerticalScrollIndicator = false
let nib = UINib(nibName: XibNames.TimeCollectionViewCell.rawValue, bundle: nil)
self.collectionView?.registerNib(nib, forCellWithReuseIdentifier: CollectionViewCellreuseIdentifier.TimeCell.rawValue)
self.timer = NSTimer.scheduledTimerWithTimeInterval(timerTickIntervalSec, target: self, selector: "onTimerTick:", userInfo: nil, repeats: true)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "didUpdateTimelineNotification:",
name: NotifictionNames.TimelineCollectionViewControllerDidUpdateTimelineNotification.rawValue,
object: nil
)
}
deinit {
self.timer?.invalidate()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
private func generateTimeLabels() {
let now = NSDate()
var date = now.beginningOfDay
while date < now.endOfDay {
var nextDate = date + 30.minutes
timeArray.append(date.stringFromFormat("HH:mm"))
if date < now && now < nextDate {
// timeArray.append(now.stringFromFormat("HH:mm")) // TODO
}
date = nextDate
}
timeArray.append("24:00")
}
func didUpdateTimelineNotification(notification: NSNotification) {
scrollToCurrentTime()
}
override func viewDidAppear(animated: Bool) {
scrollToCurrentTime()
}
// MARK: UICollectionViewDataSource
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return timeArray.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let reuseIdentifier = CollectionViewCellreuseIdentifier.TimeCell.rawValue
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! TimeCollectionViewCell
cell.timeLabel.text = timeArray[indexPath.row]
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let timelineCollectionViewFlowLayout = collectionViewLayout as! TimelineCollectionViewFlowLayout
return timelineCollectionViewFlowLayout.sizeForTimeline()
}
// MARK: UIScrollViewDelegate
override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
scrollToCenteredCell()
}
override func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
scrollToCenteredCell()
}
}
// MARK: Private
private func scrollToCenteredCell() {
let point = CGPointMake(collectionView!.center.x, collectionView!.center.y + collectionView!.contentOffset.y)
if let centeredIndexPath = collectionView?.indexPathForItemAtPoint(point) {
collectionView?.scrollToItemAtIndexPath(centeredIndexPath, atScrollPosition: .CenteredVertically, animated: true)
}
}
private func scrollToCurrentTime() {
let date = NSDate()
let newIndex = NSIndexPath(forItem: (date.hour * 60 + date.minute) / 30, inSection: 0)
self.collectionView?.scrollToItemAtIndexPath(newIndex, atScrollPosition: UICollectionViewScrollPosition.CenteredVertically, animated: true)
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
let (visibles, nearestCenter) = getVisibleCellsAndNearestCenterCell()
let timelineCollectionViewFlowLayout = self.collectionViewLayout as! TimelineCollectionViewFlowLayout
for cellInfo in visibles {
let cell = cellInfo.cell as! TimeCollectionViewCell
cell.hidden = false
let time = self.timeArray[cellInfo.row]
var dy: CGFloat = 0.0
var height: CGFloat = timelineCollectionViewFlowLayout.sizeForTimeline().height
var alpha: CGFloat = 0.0
if cell == nearestCenter.cell {
height += TimelineHeight
alpha = 1.0
cell.makeLabelBold()
} else {
dy = (cellInfo.row < nearestCenter.row ? -1 : +1) * TimelineHeight / 2
alpha = 0.5
cell.makeLabelNormal()
}
UIView.animateWithDuration(0.6,
delay: 0.0,
usingSpringWithDamping: 0.5,
initialSpringVelocity: 0.0,
options: .CurveEaseInOut,
animations: { () -> Void in
cell.bounds.size.height = height
cell.transform = CGAffineTransformMakeTranslation(0, dy)
cell.alpha = alpha
},
completion: nil
)
}
}
// MARK: timer
func onTimerTick(timer: NSTimer) {
scrollToCurrentTime()
}
}
| mit | 116e700ef9be581ab31c33b64c8d70d1 | 33.703226 | 169 | 0.659602 | 5.734542 | false | false | false | false |
AnirudhDas/AniruddhaDas.github.io | GuessImageGame/GuessImageGame/Configurations/Constants.swift | 1 | 764 | import Foundation
import UIKit
//MARK:- Storyboard
public let CollectionViewCellIdentifier = "ImageCell"
//MARK:- Other Configurable Parameters
public let MAX_NUMBER_OF_IMAGES = 9
public let STARTING_TIME: TimeInterval = 15
public let GUESS_WHERE_THIS_PHTO_WAS = "Guess where this photo was"
public let PLAY_AGAIN = "Play Again"
public let NAVIGATION_BAR_TITLE = "Guess the Image"
public let SPINNER_TITLE = "Please wait..."
public let ALERT_TITLE = "Congrats!"
public let ALERT_MESSAGE = "Your guess is correct."
public let ALERT_BUTTON_TITLE = "OK"
//MARK:- Images
public let PLACEHOLDER = #imageLiteral(resourceName: "placeholder")
public let FLIPPED = #imageLiteral(resourceName: "flipped")
public let BACKGROUND = #imageLiteral(resourceName: "background")
| apache-2.0 | 76664e7f1e57d353ae133a41c21b22a4 | 35.380952 | 67 | 0.769634 | 3.839196 | false | false | false | false |
netprotections/atonecon-ios | AtoneCon/Sources/NetworkReachabilityManager.swift | 1 | 7949 | #if !os(watchOS)
import Foundation
import SystemConfiguration
/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and
/// WiFi network interfaces.
///
/// Reachability can be used to determine background information about why a network operation failed, or to retry
/// network requests when a connection is established. It should not be used to prevent a user from initiating a network
/// request, as it's possible that an initial request may be required to establish reachability.
internal class NetworkReachabilityManager {
/// Defines the various states of network reachability.
///
/// - unknown: It is unknown whether the network is reachable.
/// - notReachable: The network is not reachable.
/// - reachable: The network is reachable.
internal enum NetworkReachabilityStatus {
case unknown
case notReachable
case reachable(ConnectionType)
}
/// Defines the various connection types detected by reachability flags.
///
/// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi.
/// - wwan: The connection type is a WWAN connection.
internal enum ConnectionType {
case ethernetOrWiFi
case wwan
}
/// A closure executed when the network reachability status changes. The closure takes a single argument: the
/// network reachability status.
internal typealias Listener = (NetworkReachabilityStatus) -> Void
// MARK: - Properties
/// Whether the network is currently reachable.
internal var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
/// Whether the network is currently reachable over the WWAN interface.
internal var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) }
/// Whether the network is currently reachable over Ethernet or WiFi interface.
internal var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) }
/// The current network reachability status.
internal var networkReachabilityStatus: NetworkReachabilityStatus {
guard let flags = self.flags else { return .unknown }
return networkReachabilityStatusForFlags(flags)
}
/// The dispatch queue to execute the `listener` closure on.
internal var listenerQueue: DispatchQueue = DispatchQueue.main
/// A closure executed when the network reachability status changes.
internal var listener: Listener?
private var flags: SCNetworkReachabilityFlags? {
var flags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(reachability, &flags) {
return flags
}
return nil
}
private let reachability: SCNetworkReachability
private var previousFlags: SCNetworkReachabilityFlags
// MARK: - Initialization
/// Creates a `NetworkReachabilityManager` instance with the specified host.
///
/// - parameter host: The host used to evaluate network reachability.
///
/// - returns: The new `NetworkReachabilityManager` instance.
internal convenience init?(host: String) {
guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
self.init(reachability: reachability)
}
/// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0.
///
/// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
/// status of the device, both IPv4 and IPv6.
///
/// - returns: The new `NetworkReachabilityManager` instance.
internal convenience init?() {
var address = sockaddr_in()
address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
address.sin_family = sa_family_t(AF_INET)
guard let reachability = withUnsafePointer(to: &address, { pointer in
return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size) {
return SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else { return nil }
self.init(reachability: reachability)
}
private init(reachability: SCNetworkReachability) {
self.reachability = reachability
self.previousFlags = SCNetworkReachabilityFlags()
}
deinit {
stopListening()
}
// MARK: - Listening
/// Starts listening for changes in network reachability status.
///
/// - returns: `true` if listening was started successfully, `false` otherwise.
@discardableResult
internal func startListening() -> Bool {
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = Unmanaged.passUnretained(self).toOpaque()
let callbackEnabled = SCNetworkReachabilitySetCallback(
reachability, { (_, flags, info) in
if let info = info {
let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(info).takeUnretainedValue()
reachability.notifyListener(flags)
}
},
&context
)
let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
listenerQueue.async {
self.previousFlags = SCNetworkReachabilityFlags()
self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
}
return callbackEnabled && queueEnabled
}
/// Stops listening for changes in network reachability status.
internal func stopListening() {
SCNetworkReachabilitySetCallback(reachability, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachability, nil)
}
// MARK: - Internal - Listener Notification
internal func notifyListener(_ flags: SCNetworkReachabilityFlags) {
guard previousFlags != flags else { return }
previousFlags = flags
listener?(networkReachabilityStatusForFlags(flags))
}
// MARK: - Internal - Network Reachability Status
internal func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
guard isNetworkReachable(with: flags) else { return .notReachable }
var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi)
#if os(iOS)
if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) }
#endif
return networkStatus
}
internal func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool {
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic)
let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired)
return isReachable && ( !needsConnection || canConnectWithoutUserInteraction)
}
}
// MARK: -
extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
/// Returns whether the two network reachability status values are equal.
///
/// - parameter lhs: The left-hand side value to compare.
/// - parameter rhs: The right-hand side value to compare.
///
/// - returns: `true` if the two values are equal, `false` otherwise.
internal func == (lhs: NetworkReachabilityManager.NetworkReachabilityStatus, rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
-> Bool {
switch (lhs, rhs) {
case (.unknown, .unknown):
return true
case (.notReachable, .notReachable):
return true
case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)):
return lhsConnectionType == rhsConnectionType
default:
return false
}
}
#endif
| mit | acbd72702303e9511dff1ea96db6fa83 | 37.400966 | 135 | 0.69883 | 5.649609 | false | false | false | false |
googlemaps/maps-sdk-for-ios-samples | GooglePlaces-Swift/GooglePlacesSwiftDemos/Swift/SampleListViewController.swift | 1 | 3819 | // Copyright 2020 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 GooglePlaces
import UIKit
/// The class which displays the list of demos.
class SampleListViewController: UITableViewController {
static let sampleCellIdentifier = "sampleCellIdentifier"
let sampleSections = Samples.allSamples()
let configuration: AutocompleteConfiguration = {
let fields: [GMSPlaceField] = [
.name, .placeID, .plusCode, .coordinate, .openingHours, .phoneNumber, .formattedAddress,
.rating, .userRatingsTotal, .priceLevel, .types, .website, .viewport, .addressComponents,
.photos, .utcOffsetMinutes, .businessStatus, .iconImageURL, .iconBackgroundColor,
]
return AutocompleteConfiguration(
autocompleteFilter: GMSAutocompleteFilter(),
placeFields: GMSPlaceField(rawValue: fields.reduce(0) { $0 | $1.rawValue }))
}()
private lazy var editButton: UIBarButtonItem = {
UIBarButtonItem(
title: "Edit", style: .plain, target: self, action: #selector(showConfiguration))
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(
UITableViewCell.self, forCellReuseIdentifier: SampleListViewController.sampleCellIdentifier)
tableView.dataSource = self
tableView.delegate = self
navigationItem.rightBarButtonItem = editButton
}
func sample(at indexPath: IndexPath) -> Sample? {
guard indexPath.section >= 0 && indexPath.section < sampleSections.count else { return nil }
let section = sampleSections[indexPath.section]
guard indexPath.row >= 0 && indexPath.row < section.samples.count else { return nil }
return section.samples[indexPath.row]
}
@objc private func showConfiguration(_sender: UIButton) {
navigationController?.present(
ConfigurationViewController(configuration: configuration), animated: true)
}
// MARK: - Override UITableView
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard section <= sampleSections.count else {
return 0
}
return sampleSections[section].samples.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
-> UITableViewCell
{
let cell = tableView.dequeueReusableCell(
withIdentifier: SampleListViewController.sampleCellIdentifier, for: indexPath)
if let sample = sample(at: indexPath) {
cell.textLabel?.text = sample.title
}
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sampleSections.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
guard section <= sampleSections.count else {
return nil
}
return sampleSections[section].name
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let sample = sample(at: indexPath) {
let viewController = sample.viewControllerClass.init()
if let controller = viewController as? AutocompleteBaseViewController {
controller.autocompleteConfiguration = configuration
}
navigationController?.pushViewController(viewController, animated: true)
}
}
}
| apache-2.0 | 814d3843d287307565bf8ca92899ed56 | 35.721154 | 100 | 0.731867 | 4.852605 | false | true | false | false |
bannzai/ResourceKit | Sources/ResourceKitCore/Parser/XibParser.swift | 1 | 2407 | //
// XibParser.swift
// ResourceKit
//
// Created by kingkong999yhirose on 2016/05/03.
// Copyright © 2016年 kingkong999yhirose. All rights reserved.
//
import Foundation
public protocol XibParser: Parsable {
}
public class XibPerserImpl: NSObject, XibParser {
let url: URL
let resource: AppendableForXibs
fileprivate var name: String = ""
// should parse for root view
// ResourceKit not support second xib view
fileprivate var isOnce: Bool = false
fileprivate let ignoreCase = [
"UIResponder"
]
public init(url: URL, writeResource resource: AppendableForXibs) throws {
self.url = url
self.resource = resource
super.init()
}
public func parse() throws {
guard url.pathExtension == "xib" else {
throw ResourceKitErrorType.spcifiedPathError(path: url.absoluteString, errorInfo: ResourceKitErrorType.createErrorInfo())
}
name = url.deletingPathExtension().lastPathComponent
// Don't create ipad resources
if name.contains("~") {
return
}
guard let parser = XMLParser(contentsOf: url) else {
throw ResourceKitErrorType.spcifiedPathError(path: url.absoluteString, errorInfo: ResourceKitErrorType.createErrorInfo())
}
parser.delegate = self
parser.parse()
}
public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
generateXibs(attributeDict, elementName: elementName)
}
fileprivate func generateXibs(_ attributes: [String: String], elementName: String) {
if isOnce {
return
}
guard let className = attributes["customClass"] else {
return
}
if ignoreCase.contains(className) {
return
}
let hasFilesOwner = attributes.flatMap ({ $1 }).contains("IBFilesOwner")
if hasFilesOwner {
return
}
isOnce = true
resource
.appendXib(
Xib(
nibName: name,
className: className,
isFilesOwner: hasFilesOwner
)
)
}
}
| mit | 5ba092e1e39638fb25d747f7b11a1bb0 | 26.632184 | 186 | 0.585691 | 5.039832 | false | false | false | false |
admkopec/BetaOS | Kernel/Modules/ACPI/AML/Method.swift | 1 | 3381 | //
// Method.swift
// Kernel
//
// Created by Adam Kopeć on 1/26/18.
// Copyright © 2018 Adam Kopeć. All rights reserved.
//
// ACPI Method Invocation
extension ACPI {
struct AMLExecutionContext {
let scope: AMLNameString
let args: AMLTermArgList
let globalObjects: ACPI.GlobalObjects
var endOfMethod = false
private var _returnValue: AMLTermArg? = nil
var returnValue: AMLTermArg? {
mutating get {
let ret = _returnValue
_returnValue = nil
return ret
}
set {
_returnValue = newValue
}
}
var localObjects: [AMLTermArg?] = Array(repeatElement(nil, count: 8))
init(scope: AMLNameString, args: AMLTermArgList, globalObjects: ACPI.GlobalObjects) {
self.scope = scope
self.args = args
self.globalObjects = globalObjects
}
func withNewScope(_ newScope: AMLNameString) -> AMLExecutionContext {
return AMLExecutionContext(scope: newScope, args: [], globalObjects: globalObjects)
}
mutating func execute(termList: AMLTermList) throws {
for termObj in termList {
if let op = termObj as? AMLType2Opcode {
// FIXME, should something be done with the result or maybe it should
// only be returned in the context
_ = try op.execute(context: &self)
} else if let op = termObj as? AMLType1Opcode {
try op.execute(context: &self)
} else if let op = termObj as? AMLNamedObj {
try op.createNamedObject(context: &self)
} else if let op = termObj as? AMLNameSpaceModifierObj {
try op.execute(context: &self)
} else {
fatalError("Unknown op: \(type(of: termObj))")
}
if endOfMethod {
return
}
}
}
}
func invokeMethod(name: String, _ args: Any...) throws -> AMLTermArg? {
var methodArgs: AMLTermArgList = []
for arg in args {
if let arg = arg as? String {
methodArgs.append(AMLString(arg))
} else if let arg = arg as? AMLInteger {
methodArgs.append(AMLIntegerData(AMLInteger(arg)))
} else {
throw AMLError.invalidData(reason: "Bad data: \(arg)")
}
}
guard let mi = /*try*/ AMLMethodInvocation(method: AMLNameString(name), args: methodArgs) else { return nil }
var context = AMLExecutionContext(scope: mi.method, args: [], globalObjects: globalObjects)
return try mi.execute(context: &context)
}
static func _OSI_Method(_ args: AMLTermArgList) throws -> AMLTermArg {
guard args.count == 1 else {
throw AMLError.invalidData(reason: "_OSI: Should only be 1 arg")
}
guard let arg = args[0] as? AMLString else {
throw AMLError.invalidData(reason: "_OSI: is not a string")
}
if arg.value == "Darwin" {
return AMLIntegerData(0xffffffff)
} else {
return AMLIntegerData(0)
}
}
}
| apache-2.0 | 32c763410c8096750e31b4d9d01322d6 | 34.557895 | 117 | 0.535228 | 4.791489 | false | false | false | false |
CPRTeam/CCIP-iOS | Pods/FSPagerView/Sources/FSPageViewTransformer.swift | 1 | 11428 | //
// FSPagerViewTransformer.swift
// FSPagerView
//
// Created by Wenchao Ding on 05/01/2017.
// Copyright © 2017 Wenchao Ding. All rights reserved.
//
import UIKit
@objc
public enum FSPagerViewTransformerType: Int {
case crossFading
case zoomOut
case depth
case overlap
case linear
case coverFlow
case ferrisWheel
case invertedFerrisWheel
case cubic
}
open class FSPagerViewTransformer: NSObject {
open internal(set) weak var pagerView: FSPagerView?
open internal(set) var type: FSPagerViewTransformerType
open var minimumScale: CGFloat = 0.65
open var minimumAlpha: CGFloat = 0.6
@objc
public init(type: FSPagerViewTransformerType) {
self.type = type
switch type {
case .zoomOut:
self.minimumScale = 0.85
case .depth:
self.minimumScale = 0.5
default:
break
}
}
// Apply transform to attributes - zIndex: Int, frame: CGRect, alpha: CGFloat, transform: CGAffineTransform or transform3D: CATransform3D.
open func applyTransform(to attributes: FSPagerViewLayoutAttributes) {
guard let pagerView = self.pagerView else {
return
}
let position = attributes.position
let scrollDirection = pagerView.scrollDirection
let itemSpacing = (scrollDirection == .horizontal ? attributes.bounds.width : attributes.bounds.height) + self.proposedInteritemSpacing()
switch self.type {
case .crossFading:
var zIndex = 0
var alpha: CGFloat = 0
var transform = CGAffineTransform.identity
switch scrollDirection {
case .horizontal:
transform.tx = -itemSpacing * position
case .vertical:
transform.ty = -itemSpacing * position
}
if (abs(position) < 1) { // [-1,1]
// Use the default slide transition when moving to the left page
alpha = 1 - abs(position)
zIndex = 1
} else { // (1,+Infinity]
// This page is way off-screen to the right.
alpha = 0
zIndex = Int.min
}
attributes.alpha = alpha
attributes.transform = transform
attributes.zIndex = zIndex
case .zoomOut:
var alpha: CGFloat = 0
var transform = CGAffineTransform.identity
switch position {
case -CGFloat.greatestFiniteMagnitude ..< -1 : // [-Infinity,-1)
// This page is way off-screen to the left.
alpha = 0
case -1 ... 1 : // [-1,1]
// Modify the default slide transition to shrink the page as well
let scaleFactor = max(self.minimumScale, 1 - abs(position))
transform.a = scaleFactor
transform.d = scaleFactor
switch scrollDirection {
case .horizontal:
let vertMargin = attributes.bounds.height * (1 - scaleFactor) / 2;
let horzMargin = itemSpacing * (1 - scaleFactor) / 2;
transform.tx = position < 0 ? (horzMargin - vertMargin*2) : (-horzMargin + vertMargin*2)
case .vertical:
let horzMargin = attributes.bounds.width * (1 - scaleFactor) / 2;
let vertMargin = itemSpacing * (1 - scaleFactor) / 2;
transform.ty = position < 0 ? (vertMargin - horzMargin*2) : (-vertMargin + horzMargin*2)
}
// Fade the page relative to its size.
alpha = self.minimumAlpha + (scaleFactor-self.minimumScale)/(1-self.minimumScale)*(1-self.minimumAlpha)
case 1 ... CGFloat.greatestFiniteMagnitude : // (1,+Infinity]
// This page is way off-screen to the right.
alpha = 0
default:
break
}
attributes.alpha = alpha
attributes.transform = transform
case .depth:
var transform = CGAffineTransform.identity
var zIndex = 0
var alpha: CGFloat = 0.0
switch position {
case -CGFloat.greatestFiniteMagnitude ..< -1: // [-Infinity,-1)
// This page is way off-screen to the left.
alpha = 0
zIndex = 0
case -1 ... 0: // [-1,0]
// Use the default slide transition when moving to the left page
alpha = 1
transform.tx = 0
transform.a = 1
transform.d = 1
zIndex = 1
case 0 ..< 1: // (0,1)
// Fade the page out.
alpha = CGFloat(1.0) - position
// Counteract the default slide transition
switch scrollDirection {
case .horizontal:
transform.tx = itemSpacing * -position
case .vertical:
transform.ty = itemSpacing * -position
}
// Scale the page down (between minimumScale and 1)
let scaleFactor = self.minimumScale
+ (1.0 - self.minimumScale) * (1.0 - abs(position));
transform.a = scaleFactor
transform.d = scaleFactor
zIndex = 0
case 1 ... CGFloat.greatestFiniteMagnitude: // [1,+Infinity)
// This page is way off-screen to the right.
alpha = 0
zIndex = 0
default:
break
}
attributes.alpha = alpha
attributes.transform = transform
attributes.zIndex = zIndex
case .overlap,.linear:
guard scrollDirection == .horizontal else {
// This type doesn't support vertical mode
return
}
let scale = max(1 - (1-self.minimumScale) * abs(position), self.minimumScale)
let transform = CGAffineTransform(scaleX: scale, y: scale)
attributes.transform = transform
let alpha = (self.minimumAlpha + (1-abs(position))*(1-self.minimumAlpha))
attributes.alpha = alpha
let zIndex = (1-abs(position)) * 10
attributes.zIndex = Int(zIndex)
case .coverFlow:
guard scrollDirection == .horizontal else {
// This type doesn't support vertical mode
return
}
let position = min(max(-position,-1) ,1)
let rotation = sin(position*(.pi)*0.5)*(.pi)*0.25*1.5
let translationZ = -itemSpacing * 0.5 * abs(position)
var transform3D = CATransform3DIdentity
transform3D.m34 = -0.002
transform3D = CATransform3DRotate(transform3D, rotation, 0, 1, 0)
transform3D = CATransform3DTranslate(transform3D, 0, 0, translationZ)
attributes.zIndex = 100 - Int(abs(position))
attributes.transform3D = transform3D
case .ferrisWheel, .invertedFerrisWheel:
guard scrollDirection == .horizontal else {
// This type doesn't support vertical mode
return
}
// http://ronnqvi.st/translate-rotate-translate/
var zIndex = 0
var transform = CGAffineTransform.identity
switch position {
case -5 ... 5:
let itemSpacing = attributes.bounds.width+self.proposedInteritemSpacing()
let count: CGFloat = 14
let circle: CGFloat = .pi * 2.0
let radius = itemSpacing * count / circle
let ty = radius * (self.type == .ferrisWheel ? 1 : -1)
let theta = circle / count
let rotation = position * theta * (self.type == .ferrisWheel ? 1 : -1)
transform = transform.translatedBy(x: -position*itemSpacing, y: ty)
transform = transform.rotated(by: rotation)
transform = transform.translatedBy(x: 0, y: -ty)
zIndex = Int((4.0-abs(position)*10))
default:
break
}
attributes.alpha = abs(position) < 0.5 ? 1 : self.minimumAlpha
attributes.transform = transform
attributes.zIndex = zIndex
case .cubic:
switch position {
case -CGFloat.greatestFiniteMagnitude ... -1:
attributes.alpha = 0
case -1 ..< 1:
attributes.alpha = 1
attributes.zIndex = Int((1-position) * CGFloat(10))
let direction: CGFloat = position < 0 ? 1 : -1
let theta = position * .pi * 0.5 * (scrollDirection == .horizontal ? 1 : -1)
let radius = scrollDirection == .horizontal ? attributes.bounds.width : attributes.bounds.height
var transform3D = CATransform3DIdentity
transform3D.m34 = -0.002
switch scrollDirection {
case .horizontal:
// ForwardX -> RotateY -> BackwardX
attributes.center.x += direction*radius*0.5 // ForwardX
transform3D = CATransform3DRotate(transform3D, theta, 0, 1, 0) // RotateY
transform3D = CATransform3DTranslate(transform3D,-direction*radius*0.5, 0, 0) // BackwardX
case .vertical:
// ForwardY -> RotateX -> BackwardY
attributes.center.y += direction*radius*0.5 // ForwardY
transform3D = CATransform3DRotate(transform3D, theta, 1, 0, 0) // RotateX
transform3D = CATransform3DTranslate(transform3D,0, -direction*radius*0.5, 0) // BackwardY
}
attributes.transform3D = transform3D
case 1 ... CGFloat.greatestFiniteMagnitude:
attributes.alpha = 0
default:
attributes.alpha = 0
attributes.zIndex = 0
}
}
}
// An interitem spacing proposed by transformer class. This will override the default interitemSpacing provided by the pager view.
open func proposedInteritemSpacing() -> CGFloat {
guard let pagerView = self.pagerView else {
return 0
}
let scrollDirection = pagerView.scrollDirection
switch self.type {
case .overlap:
guard scrollDirection == .horizontal else {
return 0
}
return pagerView.itemSize.width * -self.minimumScale * 0.6
case .linear:
guard scrollDirection == .horizontal else {
return 0
}
return pagerView.itemSize.width * -self.minimumScale * 0.2
case .coverFlow:
guard scrollDirection == .horizontal else {
return 0
}
return -pagerView.itemSize.width * sin(.pi*0.25*0.25*3.0)
case .ferrisWheel,.invertedFerrisWheel:
guard scrollDirection == .horizontal else {
return 0
}
return -pagerView.itemSize.width * 0.15
case .cubic:
return 0
default:
break
}
return pagerView.interitemSpacing
}
}
| gpl-3.0 | 2dcd1b25f293f7c64808c0f8aa3d4dea | 40.857143 | 145 | 0.537586 | 5.067406 | false | false | false | false |
k-o-d-e-n/CGLayout | Sources/Classes/container.cglayout.swift | 1 | 4212 | //
// LayoutElementsContainer.swift
// CGLayout
//
// Created by Denis Koryttsev on 01/10/2017.
//
//
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#elseif os(Linux)
import Foundation
#endif
protocol EnterPoint {
associatedtype Container
var child: LayoutElement { get }
func add(to container: Container)
}
protocol ContainerManagement {
associatedtype Child
associatedtype Container
func add(_ child: Child, to container: Container)
}
struct Enter<Container>: EnterPoint {
let base: _AnyEnterPoint<Container>
var child: LayoutElement { return base.child }
init<Point: EnterPoint>(_ base: Point) where Point.Container == Container {
self.base = _Enter(base)
}
init<Management: ContainerManagement>(_ element: Management.Child, managedBy management: Management) where Management.Child: LayoutElement, Management.Container == Container {
self.base = _Enter(Enter.Any.init(element: element, management: management))
}
func add(to container: Container) {
base.add(to: container)
}
private struct `Any`<Management: ContainerManagement>: EnterPoint where Management.Child: LayoutElement, Management.Container == Container {
let element: Management.Child
let management: Management
var child: LayoutElement { element }
func add(to container: Container) {
management.add(element, to: container)
}
}
}
class _AnyEnterPoint<Container>: EnterPoint {
var child: LayoutElement { fatalError("Unimplemented") }
func add(to container: Container) {
fatalError("Unimplemented")
}
}
final class _Enter<Base: EnterPoint>: _AnyEnterPoint<Base.Container> {
private let base: Base
override var child: LayoutElement { base.child }
init(_ base: Base) {
self.base = base
}
override func add(to container: Base.Container) {
base.add(to: container)
}
}
/// The container does not know which child is being added,
/// but the child knows exactly where it is being added
protocol ChildrenProtocol {
associatedtype Child
func add(_ child: Child)
//func remove(_ child: Child)
}
#if os(iOS)
extension UIView {
struct SublayerManagement<Container: UIView>: ContainerManagement {
func add(_ child: CALayer, to container: Container) {
container.layer.addSublayer(child)
}
}
}
extension CALayer {
struct Layers: ChildrenProtocol {
let layer: CALayer
func add(_ child: CALayer) {
layer.addSublayer(layer)
}
}
}
public extension UIView {
var sublayers: Layers { return Layers(base: CALayer.Layers(layer: layer)) }
struct Layers: ChildrenProtocol {
let base: CALayer.Layers
func add(_ child: CALayer) {
base.add(child)
}
}
var layoutGuides: LayoutGuides { return LayoutGuides(view: self) }
struct LayoutGuides: ChildrenProtocol {
let view: UIView
func add(_ child: LayoutGuide<UIView>) {
child.add(to: view)
}
}
}
public extension StackLayoutGuide where Parent: UIView {
var views: Views { return Views(stackLayoutGuide: self) }
struct Views: ChildrenProtocol {
let stackLayoutGuide: StackLayoutGuide<Parent>
func add(_ child: UIView) {
stackLayoutGuide.ownerElement?.addSubview(child)
stackLayoutGuide.items.append(.uiView(child))
}
}
var layers: Layers { return Layers(stackLayoutGuide: self) }
struct Layers: ChildrenProtocol {
let stackLayoutGuide: StackLayoutGuide<Parent>
func add(_ child: CALayer) {
stackLayoutGuide.ownerElement?.layer.addSublayer(child)
stackLayoutGuide.items.append(.caLayer(child))
}
}
var layoutGuides: LayoutGuides { return LayoutGuides(stackLayoutGuide: self) }
struct LayoutGuides: ChildrenProtocol {
let stackLayoutGuide: StackLayoutGuide<Parent>
func add(_ child: LayoutGuide<UIView>) {
stackLayoutGuide.ownerElement?.add(layoutGuide: child)
stackLayoutGuide.items.append(.layoutGuide(child))
}
}
}
#endif
| mit | 335f7a3edf7ca546740b41700dbc221c | 27.653061 | 179 | 0.664767 | 4.3875 | false | false | false | false |
123kyky/SteamReader | SteamReader/SteamReader/View/NewsItemView.swift | 1 | 1201 | //
// NewsItemView.swift
// SteamReader
//
// Created by Kyle Roberts on 4/29/16.
// Copyright © 2016 Kyle Roberts. All rights reserved.
//
import UIKit
class NewsItemView: UIView, UIWebViewDelegate {
@IBOutlet var view: UIView!
@IBOutlet weak var webView: UIWebView!
var newsItem: NewsItem! {
didSet {
if newsItem.contents != nil {
let html = "<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"news.css\"></head>" + "<body>\(newsItem.contents!)</body></html>"
webView.loadHTMLString(html, baseURL: NSBundle.mainBundle().bundleURL)
}
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NSBundle.mainBundle().loadNibNamed("NewsItemView", owner: self, options: nil)
addSubview(view)
view.snp_makeConstraints { (make) in
make.edges.equalTo(self)
}
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
// TODO: Handle news navigation (back button)
return navigationType == .Other
}
}
| mit | d4f44522c89c41e001afa3add4e8a1ac | 29.769231 | 155 | 0.615833 | 4.528302 | false | false | false | false |
Snowy1803/BreakBaloon-mobile | BreakBaloon/RandGame/RandGameBonusLevel.swift | 1 | 1344 | //
// RandGameBonusLevel.swift
// BreakBaloon
//
// Created by Emil on 02/08/2016.
// Copyright © 2016 Snowy_1803. All rights reserved.
//
import Foundation
import SpriteKit
class RandGameBonusLevel: RandGameLevel {
let modifier: Double
init(_ index: Int, modifier: Double) {
self.modifier = modifier
super.init(index)
}
override func start(_ view: SKView, transition: SKTransition = SKTransition.flipVertical(withDuration: 1)) {
gamescene = RandGameScene(view: view, level: self)
view.presentScene(gamescene!, transition: transition)
gamescene!.addChild(RandGameBonusLevelInfoNode(level: self, scene: gamescene!))
}
override func end(_ missing: Int) {
guard !status.finished else {
super.end(missing)
return
}
let xp = Double(max(0, numberOfBaloons - missing)) * modifier
gamescene!.gvc.addXP(xp)
let stars = missing == 0 ? 3 : missing <= maxMissingBaloonToWin / 2 ? 2 : 1
status = RandGameLevelStatus.getFinished(stars: stars)
unlockNextLevel()
gamescene?.addChild(RandGameLevelEndNode(level: self, scene: gamescene!, stars: stars, xpBonus: Int(xp)))
}
override func createNode() -> RandGameLevelNode {
RandGameBonusLevelNode(level: self)
}
}
| mit | 3d3c105b9af9f38caac1d5f69191217e | 30.97619 | 113 | 0.647803 | 3.997024 | false | false | false | false |
merlos/iOS-Open-GPX-Tracker | OpenGpxTracker/DistanceLabel.swift | 1 | 1329 | //
// DistanceLabel.swift
// OpenGpxTracker
//
// Created by merlos on 01/10/15.
//
import Foundation
import UIKit
import MapKit
///
/// A label to display distances.
///
/// The text is displated in meters if is less than 1km (for instance "980m") and in
/// km with two decimals if it is larger than 1km (for instance "1.20km").
///
/// If `useImperial` is true, it displays the distance always in miles ("0.23mi").
///
/// To update the text displayed set the `distance` property.
///
open class DistanceLabel: UILabel {
/// Internal variable that keeps the actual distance
private var _distance = 0.0
///Internal variable to keep the use of imperial units
private var _useImperial = false
/// Use imperial units (miles)? False by default.
/// If true, displays meters and kilometers
open var useImperial: Bool {
get {
return _useImperial
}
set {
_useImperial = newValue
distance = _distance //updates text displayed to reflect the new units
}
}
/// Distance in meters
open var distance: CLLocationDistance {
get {
return _distance
}
set {
_distance = newValue
text = newValue.toDistance(useImperial: _useImperial)
}
}
}
| gpl-3.0 | 7747c0477449c3f8e2270b4139e16283 | 24.557692 | 84 | 0.610986 | 4.314935 | false | false | false | false |
davidtps/douyuDemo | douyuDemo/douyuDemo/Classes/Home/Controller/HomeViewController.swift | 1 | 4464 | //
// HomeViewController.swift
// douyuDemo
//
// Created by 田鹏升 on 2017/8/31.
// Copyright © 2017年 田鹏升. All rights reserved.
//
import UIKit
private let mTitleViewH:CGFloat = 40
class HomeViewController: UIViewController {
// MARK:- 懒加载 titleView contentView
fileprivate lazy var pageTitleView:PageTitleView = {[weak self] in //避免循环引用问题
let titleFrame = CGRect(x: 0, y: mStatusBarH+mNavigationBarH, width: mScreenW, height: mTitleViewH)
let titles = ["推荐","游戏","娱乐","趣玩"]
let titleview = PageTitleView(frame: titleFrame, titles: titles)
titleview.delegate = self
return titleview
}()
fileprivate lazy var pageContentView:PageContentView = {[unowned self] in
let contentViewH = mScreenH - (mStatusBarH+mNavigationBarH+mTitleViewH+mTabBarH)
let contentFrame = CGRect(x: 0, y: mStatusBarH+mNavigationBarH+mTitleViewH, width: mScreenW, height: contentViewH)
var childVcs:[UIViewController] = [UIViewController]()
childVcs.append(RecommendViewController())
for _ in 0..<3{
let vc = UIViewController()
vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255)))
childVcs.append(vc)
}
let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentVc: self)
contentView.delegate = self
return contentView
}()
override func viewDidLoad() {
super.viewDidLoad()
initUI()
}
}
// MARK:- 实现pageTitleVeiw 的代理协议,通知pageContentView 做出切换
extension HomeViewController:PageTitleViewDelegate{
func pageTitleViewClick(selectedIndex index: Int) {
pageContentView.setSelectedPage(index: index)
}
}
// MARK:- 实现pageContentView 的代理协议
extension HomeViewController :PageContentViewDelegate{
func pageScrollEvent(pageContentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTitleView.setTitleViewChange(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
extension HomeViewController{
fileprivate func initUI(){
//scrollview 不需要内边距
automaticallyAdjustsScrollViewInsets = false
// MARK:- 初始化导航栏UI
navigationInit();
// MARK:- 添加pageTitle
view.addSubview(pageTitleView)
// MARK:- 添加contentView
view.addSubview(pageContentView)
}
func navigationInit() {
// 左侧,设置logo
// let logo = UIButton();
// logo.setImage(UIImage(named:"logo"), for: UIControlState.normal)
// logo.sizeToFit()
navigationItem.leftBarButtonItem = UIBarButtonItem(normal: "logo")
//设置右侧 item
let size = CGSize(width:40,height:40);
// let hisBtn = UIButton();
//
// hisBtn.setImage(UIImage(named:"image_my_history"), for: UIControlState.normal)
// hisBtn.setImage(UIImage(named:"Image_my_history_click"), for: UIControlState.highlighted)
// hisBtn.frame = CGRect(origin: CGPoint.zero, size: size)
//
// let scanBtn = UIButton();
// scanBtn.setImage(UIImage(named:"Image_scan"), for: UIControlState.normal)
// scanBtn.setImage(UIImage(named:"Image_scan_click"), for: UIControlState.highlighted)
// scanBtn.frame = CGRect(origin: CGPoint.zero, size: size)
//
//
// let searchBtn = UIButton();
// searchBtn.setImage(UIImage(named:"btn_search"), for: UIControlState.normal)
// searchBtn.setImage(UIImage(named:"btn_search_clicked"), for: UIControlState.highlighted)
// searchBtn.frame = CGRect(origin: CGPoint.zero, size: size)
let history = UIBarButtonItem(normal:"image_my_history",highlight:"Image_my_history_click",size:size)
let scan = UIBarButtonItem(normal:"Image_scan",highlight:"Image_scan_click",size:size)
let search = UIBarButtonItem(normal:"btn_search",highlight:"btn_search_clicked",size:size)
navigationItem.rightBarButtonItems = [history,scan,search]
}
}
| apache-2.0 | e84ccffc25768f1d4ea1293c1e07dbf6 | 38.990741 | 156 | 0.639037 | 4.599574 | false | false | false | false |
kokoroe/kokoroe-sdk-ios | KokoroeSDK/Network/Authentication/KKRAuthenticationRequest.swift | 1 | 3773 | //
// KKRAuthenticationRequest.swift
// KokoroeSDK
//
// Created by Guillaume Mirambeau on 27/04/2016.
// Copyright © 2016 I know u will. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireObjectMapper
import ObjectMapper
enum KKRAuthenticationConstant {
case Unknown, Password, Facebook
func value() -> String {
switch self {
case .Unknown:
return "unknown"
case .Password:
return "password"
case .Facebook:
return "facebook"
}
}
}
enum KKRAuthenticationType {
case None, Email, Facebook
};
class KKRAuthenticationRequestObject: KKRMasterRequestObject {
var email: String? {
didSet {
if let unwrapEmail = email {
self.container["username"] = unwrapEmail
} else {
self.container.removeValueForKey("username")
}
}
}
var password: String? {
didSet {
if let unwrapPassword = password {
self.container["password"] = unwrapPassword
} else {
self.container.removeValueForKey("password")
}
}
}
var token: String? {
didSet {
if let unwrapToken = token {
self.container["token"] = unwrapToken
} else {
self.container.removeValueForKey("token")
}
}
}
private var _grantType: String?
//var connectionType:KKRConnectionType = .None
//private var _authenticationType: KKRAuthenticationType = .None
var authenticationType: KKRAuthenticationType = .None {
didSet {
//_authenticationType = newValue
switch authenticationType {
case .Email:
_grantType = KKRAuthenticationConstant.Password.value()
self.container["grant_type"] = _grantType
case .Facebook:
_grantType = KKRAuthenticationConstant.Facebook.value()
self.container["grant_type"] = _grantType
default:
_grantType = KKRAuthenticationConstant.Unknown.value()
self.container.removeValueForKey("grant_type")
}
}
}
}
let KKRConnectionPathPattern = "/oauth/token"
class KKRAuthenticationRequest: NSObject {
func authentication(authenticationObject: KKRAuthenticationRequestObject, completion: (result: KKRAuthenticationResponseObject?, error: NSError?) -> Void) {
KKRMasterRequest.sharedInstance.request(.POST, KKRConnectionPathPattern, bodyParameters: authenticationObject.container)
.validate()
.responseObject { (response: Response<KKRAuthenticationResponseObject, NSError>) in
switch response.result {
case .Success:
if let authenticationResponseObject = response.result.value {
completion(result: authenticationResponseObject, error: nil)
} else {
completion(result: nil, error: nil)
}
case .Failure(let error):
completion(result: nil, error: error)
}
}
}
func logout() {
KKRMasterRequest.sharedInstance.accessToken = nil
}
}
class KKRAuthenticationResponseObject: Mappable {
var accessToken: String?
var tokenType: String?
var expiresIn: Int?
required init?(_ map: Map){
}
func mapping(map: Map) {
self.accessToken <- map["access_token"]
self.tokenType <- map["token_type"]
self.expiresIn <- map["expires_in"]
}
} | mit | b5ff266626a43897c947784ec127efcd | 29.184 | 160 | 0.572641 | 5.049531 | false | false | false | false |
WangWenzhuang/ZKProgressHUD | ZKProgressHUD/ZKProgressView.swift | 1 | 1972 | //
// ZKProgressView.swift
// ZKProgressHUD
//
// Created by 王文壮 on 2017/3/15.
// Copyright © 2017年 WangWenzhuang. All rights reserved.
//
import UIKit
/// 进度
class ZKProgressView: UIView {
var progressColor: UIColor?
var progressFont: UIFont?
private var _progress: Double = 0
private var textLabel: UILabel!
var progress: Double {
get {
return _progress
}
set {
self._progress = newValue
self.setNeedsDisplay()
self.setNeedsLayout()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.textLabel = UILabel()
self.addSubview(self.textLabel)
self.textLabel.textAlignment = .center
self.textLabel.font = self.progressFont ?? Config.font
self.textLabel.textColor = self.progressColor ?? Config.foregroundColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.textLabel.text = "\(Int(self.progress * 100))%"
self.textLabel.sizeToFit()
self.textLabel.frame.origin = CGPoint(x: (self.width - self.textLabel.width) / 2, y: (self.height - self.textLabel.height) / 2)
}
override func draw(_ rect: CGRect) {
if let ctx = UIGraphicsGetCurrentContext() {
let arcCenter = CGPoint(x: self.width / 2, y: self.width / 2)
let radius = arcCenter.x - 2
let startAngle = -(Double.pi / 2)
let endAngle = startAngle + Double.pi * 2 * self.progress
let path = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: true)
ctx.setLineWidth(4)
self.progressColor?.setStroke()
ctx.addPath(path.cgPath)
ctx.strokePath()
}
}
}
| mit | 9aadbcfe3b3baa89647b242ee935c0b8 | 31.65 | 152 | 0.605411 | 4.372768 | false | false | false | false |
robin/YLUtils | MyPlayground.playground/Sources/PlaygroundUtils.swift | 1 | 632 | import Foundation
import UIKit
public func viewWithLayer(layer: CALayer, size: CGSize = CGSize(width: 300, height: 300)) -> UIView {
let view = UIView(frame: CGRect(origin: .zero, size: size))
layer.bounds = view.bounds
layer.position = view.center
view.layer.addSublayer(layer)
return view
}
public func viewWithPath(path: UIBezierPath, size: CGSize = CGSize(width: 300, height: 300)) -> UIView {
let layer = CAShapeLayer()
layer.strokeColor = UIColor.whiteColor().CGColor
layer.path = path.CGPath
layer.fillColor = UIColor.darkGrayColor().CGColor
return viewWithLayer(layer, size: size)
} | mit | 4ae288ff53ddf96ea5e6ebf3316986d7 | 34.166667 | 104 | 0.713608 | 4.025478 | false | false | false | false |
mattrubin/SwiftGit2 | SwiftGit2/Errors.swift | 1 | 1808 | import Foundation
import libgit2
public let libGit2ErrorDomain = "org.libgit2.libgit2"
internal extension NSError {
/// Returns an NSError with an error domain and message for libgit2 errors.
///
/// :param: errorCode An error code returned by a libgit2 function.
/// :param: libGit2PointOfFailure The name of the libgit2 function that produced the
/// error code.
/// :returns: An NSError with a libgit2 error domain, code, and message.
convenience init(gitError errorCode: Int32, pointOfFailure: String? = nil) {
let code = Int(errorCode)
var userInfo: [String: String] = [:]
if let message = errorMessage(errorCode) {
userInfo[NSLocalizedDescriptionKey] = message
} else {
userInfo[NSLocalizedDescriptionKey] = "Unknown libgit2 error."
}
if let pointOfFailure = pointOfFailure {
userInfo[NSLocalizedFailureReasonErrorKey] = "\(pointOfFailure) failed."
}
self.init(domain: libGit2ErrorDomain, code: code, userInfo: userInfo)
}
}
/// Returns the libgit2 error message for the given error code.
///
/// The error message represents the last error message generated by
/// libgit2 in the current thread.
///
/// :param: errorCode An error code returned by a libgit2 function.
/// :returns: If the error message exists either in libgit2's thread-specific registry,
/// or errno has been set by the system, this function returns the
/// corresponding string representation of that error. Otherwise, it returns
/// nil.
private func errorMessage(_ errorCode: Int32) -> String? {
let last = giterr_last()
if let lastErrorPointer = last {
return String(validatingUTF8: lastErrorPointer.pointee.message)
} else if UInt32(errorCode) == GITERR_OS.rawValue {
return String(validatingUTF8: strerror(errno))
} else {
return nil
}
}
| mit | 9496c8690a3c6ba6cbd40d7cf0d6e999 | 35.16 | 87 | 0.724558 | 3.938998 | false | false | false | false |
sacrelee/iOSDev | Notes/Swift/Coding.playground/Pages/Classes and Structures.xcplaygroundpage/Contents.swift | 1 | 3098 | /// 类和结构体
// swift中类和结构体的关系更加密切,以下主要通过实例而不是对象来说明
/* 类与结构体的相同点:
*定义属性用于存储值
*定义方法用于提供功能
*定义附属脚本用于访问值
*定义构造器用于生成初始化值
*通过扩展以增加默认实现的功能
*实现协议以提供某种标准功能”
类另外拥有以下附加功能:
*继承允许一个类继承另一个类的特征
*类型转换允许在运行时检查和解释一个类实例的类型
*解构器允许一个类实例释放任何其所被分配的资源
*用计数允许对一个类的多次引用
命名
为类和结构体使用首字母大写的驼峰命名方式,变量或者方法使用首字母小写的驼峰
*/
/// 定义
class SomeClass{} // 类
struct SomeSturct{} // 结构体
struct Resolution{ // 结构体:像素,拥有宽和高
var width = 0
var height = 0
}
class VideoPlayer{ // VideoMode类,拥有各种变量以及方法
var resolution = Resolution()
var isFullScreen = false
var name:String?
func play(){print("playing")}
func pause(){print("pause")}
func stop(){print("stop")}
}
// 创建实例
var reso = Resolution()
let vp = VideoPlayer()
// 访问属性或者方法均通过点语法
reso.width = 1280
reso.height = 720
let width = reso.width
vp.name = "Inception"
let isFull = vp.isFullScreen
vp.pause() // 调用pause方法
// 结构体构造器,
let vga = Resolution(width: 1920, height: 1080)
/// 结构体和枚举是值类型
var fourK = vga
fourK.width = 3840
fourK.height = 2160
// 只是值拷贝,改变fourK并不改变vga中的属性
print("FourK:\(fourK.width)x\(fourK.height); HD:\(vga.width)x\(vga.height)");
// 枚举也是如此,仅仅是值拷贝,
enum Companys{
case Apple, Google, Amazon, IBM
}
let aCo = Companys.Apple
var bCo = aCo
bCo = .IBM
print("A:\(aCo), B:\(bCo)")
/// 类是引用类型
let aVideoPlayer = vp
aVideoPlayer.name = "insteller"
// 改变aVideoPlayer中属性的同时改变了vp中的属性,类是引用类型
// vp和aVideoPlayer均为常量类型,改变其中属性并不改变常量值
print("aVideoPlayer:\(aVideoPlayer.name),vp:\(vp.name)")
/// 恒等运算符
// 使用"==="表示等价于,"!=="表示不等价于。用于判断是否是引用了的实例
if aVideoPlayer === vp
{
print("They are equal!")
}
// == 表示值相等 != 表示值不相等
/// 类和结构体之间的选择
/*
结构体的主要目的是用来封装少量相关简单数据值。
有理由预计一个结构体实例在赋值或传递时,封装的数据将会被拷贝而不是被引用。
任何在结构体中储存的值类型属性,也将会被拷贝,而不是被引用。
结构体不需要去继承另一个已存在类型的属性或者行为。”
*/
/// 字符串,数组,字典的赋值和复制行为
// swift中这三者均以结构体形式实现,因此均为值拷贝
// Objective C中这三者均以类形式实现,因此均为传递引用
| apache-2.0 | ae5aa82d35831910840624354ce44867 | 16.752381 | 77 | 0.697425 | 2.33584 | false | false | false | false |
ps2/rileylink_ios | OmniKitUI/ViewModels/PairPodViewModel.swift | 1 | 7722 | //
// PairPodViewModel.swift
// OmniKit
//
// Created by Pete Schwamb on 3/2/20.
// Copyright © 2021 LoopKit Authors. All rights reserved.
//
import SwiftUI
import LoopKit
import LoopKitUI
import OmniKit
class PairPodViewModel: ObservableObject, Identifiable {
enum NavBarButtonAction {
case cancel
case discard
var text: String {
switch self {
case .cancel:
return LocalizedString("Cancel", comment: "Pairing interface navigation bar button text for cancel action")
case .discard:
return LocalizedString("Discard Pod", comment: "Pairing interface navigation bar button text for discard pod action")
}
}
func color(using guidanceColors: GuidanceColors) -> Color? {
switch self {
case .discard:
return guidanceColors.critical
case .cancel:
return nil
}
}
}
enum PairPodViewModelState {
case ready
case pairing
case priming(finishTime: CFTimeInterval)
case error(OmnipodPairingError)
case finished
var instructionsDisabled: Bool {
switch self {
case .ready:
return false
case .error(let error):
return !error.recoverable
default:
return true
}
}
var actionButtonAccessibilityLabel: String {
switch self {
case .ready:
return LocalizedString("Pair pod.", comment: "Pairing action button accessibility label while ready to pair")
case .pairing:
return LocalizedString("Pairing.", comment: "Pairing action button accessibility label while pairing")
case .priming:
return LocalizedString("Priming. Please wait.", comment: "Pairing action button accessibility label while priming")
case .error(let error):
return String(format: "%@ %@", error.errorDescription ?? "", error.recoverySuggestion ?? "")
case .finished:
return LocalizedString("Pod paired successfully. Continue.", comment: "Pairing action button accessibility label when pairing succeeded")
}
}
var nextActionButtonDescription: String {
switch self {
case .ready:
return LocalizedString("Pair Pod", comment: "Pod pairing action button text while ready to pair")
case .error:
return LocalizedString("Retry", comment: "Pod pairing action button text while showing error")
case .pairing:
return LocalizedString("Pairing...", comment: "Pod pairing action button text while pairing")
case .priming:
return LocalizedString("Priming...", comment: "Pod pairing action button text while priming")
case .finished:
return LocalizedString("Continue", comment: "Pod pairing action button text when paired")
}
}
var navBarButtonAction: NavBarButtonAction {
// switch self {
// case .error(_, let podCommState):
// if podCommState == .activating {
// return .discard
// }
// default:
// break
// }
return .cancel
}
var navBarVisible: Bool {
if case .error(let error) = self {
return error.recoverable
}
return true
}
var showProgressDetail: Bool {
switch self {
case .ready:
return false
default:
return true
}
}
var progressState: ProgressIndicatorState {
switch self {
case .ready, .error:
return .hidden
case .pairing:
return .indeterminantProgress
case .priming(let finishTime):
return .timedProgress(finishTime: finishTime)
case .finished:
return .completed
}
}
var isProcessing: Bool {
switch self {
case .pairing, .priming:
return true
default:
return false
}
}
var isFinished: Bool {
if case .finished = self {
return true
}
return false
}
}
var error: OmnipodPairingError? {
if case .error(let error) = state {
return error
}
return nil
}
@Published var state: PairPodViewModelState = .ready
var podIsActivated: Bool {
return false // podPairer.podCommState != .noPod
}
var backButtonHidden: Bool {
if case .pairing = state {
return true
}
if podIsActivated {
return true
}
return false
}
var didFinish: (() -> Void)?
var didRequestDeactivation: (() -> Void)?
var didCancelSetup: (() -> Void)?
var podPairer: PodPairer
init(podPairer: PodPairer) {
self.podPairer = podPairer
}
private func pair() {
state = .pairing
podPairer.pair { (status) in
DispatchQueue.main.async {
switch status {
case .failure(let error):
let pairingError = OmnipodPairingError.pumpManagerError(error)
self.state = .error(pairingError)
case .success(let duration):
if duration > 0 {
self.state = .priming(finishTime: CACurrentMediaTime() + duration)
DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
self.state = .finished
}
} else {
self.state = .finished
}
}
}
}
}
public func continueButtonTapped() {
switch state {
case .error(let error):
if !error.recoverable {
self.didRequestDeactivation?()
} else {
// Retry
pair()
}
case .finished:
didFinish?()
default:
pair()
}
}
}
// Pairing recovery suggestions
enum OmnipodPairingError : LocalizedError {
case pumpManagerError(PumpManagerError)
var recoverySuggestion: String? {
switch self {
case .pumpManagerError(let error):
return error.recoverySuggestion
}
}
var errorDescription: String? {
switch self {
case .pumpManagerError(let error):
return error.errorDescription
}
}
var recoverable: Bool {
// switch self {
// case .pumpManagerError(let error):
// TODO: check which errors are recoverable
return true
// }
}
}
public protocol PodPairer {
func pair(completion: @escaping (PumpManagerResult<TimeInterval>) -> Void)
func discardPod(completion: @escaping (Bool) -> ())
}
extension OmnipodPumpManager: PodPairer {
public func discardPod(completion: @escaping (Bool) -> ()) {
}
public func pair(completion: @escaping (PumpManagerResult<TimeInterval>) -> Void) {
pairAndPrime(completion: completion)
}
}
| mit | 65049f947cff31925115c1ea99bbb92f | 28.582375 | 153 | 0.520528 | 5.507133 | false | false | false | false |
AgaKhanFoundation/WCF-iOS | Pods/Nimble/Sources/Nimble/Utils/Await.swift | 2 | 13535 | #if !os(WASI)
import CoreFoundation
import Dispatch
import Foundation
private let timeoutLeeway = DispatchTimeInterval.milliseconds(1)
private let pollLeeway = DispatchTimeInterval.milliseconds(1)
/// Stores debugging information about callers
internal struct WaitingInfo: CustomStringConvertible {
let name: String
let file: FileString
let lineNumber: UInt
var description: String {
return "\(name) at \(file):\(lineNumber)"
}
}
internal protocol WaitLock {
func acquireWaitingLock(_ fnName: String, file: FileString, line: UInt)
func releaseWaitingLock()
func isWaitingLocked() -> Bool
}
internal class AssertionWaitLock: WaitLock {
private var currentWaiter: WaitingInfo?
init() { }
func acquireWaitingLock(_ fnName: String, file: FileString, line: UInt) {
let info = WaitingInfo(name: fnName, file: file, lineNumber: line)
let isMainThread = Thread.isMainThread
nimblePrecondition(
isMainThread,
"InvalidNimbleAPIUsage",
"\(fnName) can only run on the main thread."
)
nimblePrecondition(
currentWaiter == nil,
"InvalidNimbleAPIUsage",
"""
Nested async expectations are not allowed to avoid creating flaky tests.
The call to
\t\(info)
triggered this exception because
\t\(currentWaiter!)
is currently managing the main run loop.
"""
)
currentWaiter = info
}
func isWaitingLocked() -> Bool {
return currentWaiter != nil
}
func releaseWaitingLock() {
currentWaiter = nil
}
}
internal enum AwaitResult<T> {
/// Incomplete indicates None (aka - this value hasn't been fulfilled yet)
case incomplete
/// TimedOut indicates the result reached its defined timeout limit before returning
case timedOut
/// BlockedRunLoop indicates the main runloop is too busy processing other blocks to trigger
/// the timeout code.
///
/// This may also mean the async code waiting upon may have never actually ran within the
/// required time because other timers & sources are running on the main run loop.
case blockedRunLoop
/// The async block successfully executed and returned a given result
case completed(T)
/// When a Swift Error is thrown
case errorThrown(Error)
/// When an Objective-C Exception is raised
case raisedException(NSException)
func isIncomplete() -> Bool {
switch self {
case .incomplete: return true
default: return false
}
}
func isCompleted() -> Bool {
switch self {
case .completed: return true
default: return false
}
}
}
/// Holds the resulting value from an asynchronous expectation.
/// This class is thread-safe at receiving an "response" to this promise.
internal final class AwaitPromise<T> {
private(set) internal var asyncResult: AwaitResult<T> = .incomplete
private var signal: DispatchSemaphore
init() {
signal = DispatchSemaphore(value: 1)
}
deinit {
signal.signal()
}
/// Resolves the promise with the given result if it has not been resolved. Repeated calls to
/// this method will resolve in a no-op.
///
/// @returns a Bool that indicates if the async result was accepted or rejected because another
/// value was received first.
func resolveResult(_ result: AwaitResult<T>) -> Bool {
if signal.wait(timeout: .now()) == .success {
self.asyncResult = result
return true
} else {
return false
}
}
}
internal struct AwaitTrigger {
let timeoutSource: DispatchSourceTimer
let actionSource: DispatchSourceTimer?
let start: () throws -> Void
}
/// Factory for building fully configured AwaitPromises and waiting for their results.
///
/// This factory stores all the state for an async expectation so that Await doesn't
/// doesn't have to manage it.
internal class AwaitPromiseBuilder<T> {
let awaiter: Awaiter
let waitLock: WaitLock
let trigger: AwaitTrigger
let promise: AwaitPromise<T>
internal init(
awaiter: Awaiter,
waitLock: WaitLock,
promise: AwaitPromise<T>,
trigger: AwaitTrigger) {
self.awaiter = awaiter
self.waitLock = waitLock
self.promise = promise
self.trigger = trigger
}
func timeout(_ timeoutInterval: DispatchTimeInterval, forcefullyAbortTimeout: DispatchTimeInterval) -> Self {
// = Discussion =
//
// There's a lot of technical decisions here that is useful to elaborate on. This is
// definitely more lower-level than the previous NSRunLoop based implementation.
//
//
// Why Dispatch Source?
//
//
// We're using a dispatch source to have better control of the run loop behavior.
// A timer source gives us deferred-timing control without having to rely as much on
// a run loop's traditional dispatching machinery (eg - NSTimers, DefaultRunLoopMode, etc.)
// which is ripe for getting corrupted by application code.
//
// And unlike dispatch_async(), we can control how likely our code gets prioritized to
// executed (see leeway parameter) + DISPATCH_TIMER_STRICT.
//
// This timer is assumed to run on the HIGH priority queue to ensure it maintains the
// highest priority over normal application / test code when possible.
//
//
// Run Loop Management
//
// In order to properly interrupt the waiting behavior performed by this factory class,
// this timer stops the main run loop to tell the waiter code that the result should be
// checked.
//
// In addition, stopping the run loop is used to halt code executed on the main run loop.
trigger.timeoutSource.schedule(
deadline: DispatchTime.now() + timeoutInterval,
repeating: .never,
leeway: timeoutLeeway
)
trigger.timeoutSource.setEventHandler {
guard self.promise.asyncResult.isIncomplete() else { return }
let timedOutSem = DispatchSemaphore(value: 0)
let semTimedOutOrBlocked = DispatchSemaphore(value: 0)
semTimedOutOrBlocked.signal()
let runLoop = CFRunLoopGetMain()
#if canImport(Darwin)
let runLoopMode = CFRunLoopMode.defaultMode.rawValue
#else
let runLoopMode = kCFRunLoopDefaultMode
#endif
CFRunLoopPerformBlock(runLoop, runLoopMode) {
if semTimedOutOrBlocked.wait(timeout: .now()) == .success {
timedOutSem.signal()
semTimedOutOrBlocked.signal()
if self.promise.resolveResult(.timedOut) {
CFRunLoopStop(CFRunLoopGetMain())
}
}
}
// potentially interrupt blocking code on run loop to let timeout code run
CFRunLoopStop(runLoop)
let now = DispatchTime.now() + forcefullyAbortTimeout
let didNotTimeOut = timedOutSem.wait(timeout: now) != .success
let timeoutWasNotTriggered = semTimedOutOrBlocked.wait(timeout: .now()) == .success
if didNotTimeOut && timeoutWasNotTriggered {
if self.promise.resolveResult(.blockedRunLoop) {
CFRunLoopStop(CFRunLoopGetMain())
}
}
}
return self
}
/// Blocks for an asynchronous result.
///
/// @discussion
/// This function must be executed on the main thread and cannot be nested. This is because
/// this function (and it's related methods) coordinate through the main run loop. Tampering
/// with the run loop can cause undesirable behavior.
///
/// This method will return an AwaitResult in the following cases:
///
/// - The main run loop is blocked by other operations and the async expectation cannot be
/// be stopped.
/// - The async expectation timed out
/// - The async expectation succeeded
/// - The async expectation raised an unexpected exception (objc)
/// - The async expectation raised an unexpected error (swift)
///
/// The returned AwaitResult will NEVER be .incomplete.
func wait(_ fnName: String = #function, file: FileString = #file, line: UInt = #line) -> AwaitResult<T> {
waitLock.acquireWaitingLock(
fnName,
file: file,
line: line)
let capture = NMBExceptionCapture(handler: ({ exception in
_ = self.promise.resolveResult(.raisedException(exception))
}), finally: ({
self.waitLock.releaseWaitingLock()
}))
capture.tryBlock {
do {
try self.trigger.start()
} catch let error {
_ = self.promise.resolveResult(.errorThrown(error))
}
self.trigger.timeoutSource.resume()
while self.promise.asyncResult.isIncomplete() {
// Stopping the run loop does not work unless we run only 1 mode
_ = RunLoop.current.run(mode: .default, before: .distantFuture)
}
self.trigger.timeoutSource.cancel()
if let asyncSource = self.trigger.actionSource {
asyncSource.cancel()
}
}
return promise.asyncResult
}
}
internal class Awaiter {
let waitLock: WaitLock
let timeoutQueue: DispatchQueue
let asyncQueue: DispatchQueue
internal init(
waitLock: WaitLock,
asyncQueue: DispatchQueue,
timeoutQueue: DispatchQueue) {
self.waitLock = waitLock
self.asyncQueue = asyncQueue
self.timeoutQueue = timeoutQueue
}
private func createTimerSource(_ queue: DispatchQueue) -> DispatchSourceTimer {
return DispatchSource.makeTimerSource(flags: .strict, queue: queue)
}
func performBlock<T>(
file: FileString,
line: UInt,
_ closure: @escaping (@escaping (T) -> Void) throws -> Void
) -> AwaitPromiseBuilder<T> {
let promise = AwaitPromise<T>()
let timeoutSource = createTimerSource(timeoutQueue)
var completionCount = 0
let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: nil) {
try closure { result in
completionCount += 1
if completionCount < 2 {
func completeBlock() {
if promise.resolveResult(.completed(result)) {
CFRunLoopStop(CFRunLoopGetMain())
}
}
if Thread.isMainThread {
completeBlock()
} else {
DispatchQueue.main.async { completeBlock() }
}
} else {
fail("waitUntil(..) expects its completion closure to be only called once",
file: file, line: line)
}
}
}
return AwaitPromiseBuilder(
awaiter: self,
waitLock: waitLock,
promise: promise,
trigger: trigger)
}
func poll<T>(_ pollInterval: DispatchTimeInterval, closure: @escaping () throws -> T?) -> AwaitPromiseBuilder<T> {
let promise = AwaitPromise<T>()
let timeoutSource = createTimerSource(timeoutQueue)
let asyncSource = createTimerSource(asyncQueue)
let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: asyncSource) {
let interval = pollInterval
asyncSource.schedule(deadline: .now(), repeating: interval, leeway: pollLeeway)
asyncSource.setEventHandler {
do {
if let result = try closure() {
if promise.resolveResult(.completed(result)) {
CFRunLoopStop(CFRunLoopGetCurrent())
}
}
} catch let error {
if promise.resolveResult(.errorThrown(error)) {
CFRunLoopStop(CFRunLoopGetCurrent())
}
}
}
asyncSource.resume()
}
return AwaitPromiseBuilder(
awaiter: self,
waitLock: waitLock,
promise: promise,
trigger: trigger)
}
}
internal func pollBlock(
pollInterval: DispatchTimeInterval,
timeoutInterval: DispatchTimeInterval,
file: FileString,
line: UInt,
fnName: String = #function,
expression: @escaping () throws -> Bool) -> AwaitResult<Bool> {
let awaiter = NimbleEnvironment.activeInstance.awaiter
let result = awaiter.poll(pollInterval) { () throws -> Bool? in
if try expression() {
return true
}
return nil
}.timeout(timeoutInterval, forcefullyAbortTimeout: timeoutInterval.divided).wait(fnName, file: file, line: line)
return result
}
#endif // #if !os(WASI)
| bsd-3-clause | 2d0adefd0ba365ea89f0b0a7e9c3de11 | 35.093333 | 120 | 0.595936 | 5.177888 | false | false | false | false |
jackcook/interface | Interface/AppDelegate.swift | 1 | 1840 | //
// AppDelegate.swift
// Interface
//
// Created by Jack Cook on 4/2/16.
// Copyright © 2016 Jack Cook. All rights reserved.
//
import UIKit
var language: String? {
get {
return NSUserDefaults.standardUserDefaults().stringForKey("InterfaceLanguage")
}
set(newValue) {
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "InterfaceLanguage")
}
}
var lang: String {
get {
return language!.componentsSeparatedByString("-")[0]
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if language != nil {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let avc = storyboard.instantiateViewControllerWithIdentifier("ArticlesViewController") as! ArticlesViewController
let navController = UINavigationController()
window?.rootViewController = navController
navController.pushViewController(avc, animated: false)
}
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
guard let host = url.host else {
return true
}
switch host {
case "auth":
if let component = url.pathComponents?[1] {
switch component {
case "quizlet":
Quizlet.sharedInstance.handleAuthorizationResponse(url)
default:
break
}
}
default:
break
}
return true
}
}
| mit | ab935f165f72ba326303ac5877b4f4d2 | 26.447761 | 129 | 0.595432 | 5.641104 | false | false | false | false |
playbasis/native-sdk-ios | PlaybasisSDK/Classes/PBModel/PBLeaderBoard.swift | 1 | 1816 | //
// PBLeaderBoard.swift
// Playbook
//
// Created by Nuttapol Thitaweera on 6/24/2559 BE.
// Copyright © 2559 smartsoftasia. All rights reserved.
//
import UIKit
import ObjectMapper
public class PBLeaderBoard: PBModel {
public var dateCompleted:NSDate?
public var dateJoined:NSDate?
public var status:String! = ""
public var current:Int! = 0
public var goal:Int! = 0
public var player:PBPlayerBasic?
public var rank:Int! = 0
override public func mapping(map: Map) {
super.mapping(map)
self.dateCompleted <- (map["date_completed"],ISO8601DateTransform())
self.dateJoined <- (map["date_join"], ISO8601DateTransform())
self.status <- map["status"]
self.current <- map["current"]
self.goal <- map["goal"]
self.player <- map["player"]
self.rank <- map["rank"]
}
public override init() {
super.init()
}
required public init?(_ map: Map) {
super.init(map)
}
init(apiResponse:PBApiResponse) {
super.init()
Mapper<PBLeaderBoard>().map(apiResponse.parsedJson!["player_data"], toObject: self)
}
class func pbLeaderBoardDataFromApiResponse(apiResponse:PBApiResponse) -> (leaderBoardList:[PBLeaderBoard], playerData:PBLeaderBoard?) {
var pbLeaderBoardList:[PBLeaderBoard] = []
pbLeaderBoardList = Mapper<PBLeaderBoard>().mapArray(apiResponse.parsedJson!["result"])!
if let playerDataJson = apiResponse.parsedJson!["player_data"], let playerData:PBLeaderBoard = Mapper<PBLeaderBoard>().map(playerDataJson) {
return (leaderBoardList:pbLeaderBoardList, playerData:playerData)
}
else {
return (leaderBoardList:pbLeaderBoardList, playerData:nil)
}
}
}
| mit | bc2ada3599b97fcf6316430511e99d5e | 30.293103 | 148 | 0.642424 | 4.033333 | false | false | false | false |
arietis/codility-swift | 10.3.swift | 1 | 770 | public func solution(inout A : [Int]) -> Int {
// write your code in Swift 2.2
let n = A.count
if n < 3 {
return 0
}
var peaks: [Int] = []
for i in 1..<n - 1 {
if A[i - 1] < A[i] && A[i] > A[i + 1] {
peaks.append(i)
}
}
for var i = n; i > 0; i -= 1 {
if n % i != 0 {
continue
}
let blockSize = n / i
var currentBlock = 0
for j in peaks {
if j / blockSize > currentBlock {
break
}
if j / blockSize == currentBlock {
currentBlock += 1
}
}
if currentBlock == i {
return i
}
}
return 0
}
| mit | 3cd4150fd48d94bc6fd4062509852159 | 17.333333 | 47 | 0.361039 | 3.969072 | false | false | false | false |
benlangmuir/swift | test/Serialization/Recovery/implementation-only-missing.swift | 11 | 3973 | // Recover from missing types hidden behind an importation-only when indexing
// a system module.
// rdar://problem/52837313
// RUN: %empty-directory(%t)
//// Build the private module, the public module and the client app normally.
//// Force the public module to be system with an underlying Clang module.
// RUN: %target-swift-frontend -emit-module -DPRIVATE_LIB %s -module-name private_lib -emit-module-path %t/private_lib.swiftmodule
// RUN: %target-swift-frontend -emit-module -DPUBLIC_LIB %s -module-name public_lib -emit-module-path %t/public_lib.swiftmodule -I %t -I %S/Inputs/implementation-only-missing -import-underlying-module
//// The client app should build OK without the private module. Removing the
//// private module is superfluous but makes sure that it's not somehow loaded.
// RUN: rm %t/private_lib.swiftmodule
// RUN: %target-swift-frontend -typecheck -DCLIENT_APP %s -I %t -index-system-modules -index-store-path %t
// RUN: %target-swift-frontend -typecheck -DCLIENT_APP %s -I %t -D FAIL_TYPECHECK -verify
// RUN: %target-swift-frontend -emit-sil -DCLIENT_APP %s -I %t -module-name client
//// Printing the public module should not crash when checking for overrides of
//// methods from the private module.
// RUN: %target-swift-ide-test -print-module -module-to-print=public_lib -source-filename=x -skip-overrides -I %t
#if PRIVATE_LIB
@propertyWrapper
public struct IoiPropertyWrapper<V> {
var content: V
public init(_ v: V) {
content = v
}
public var wrappedValue: V {
return content
}
}
public struct HiddenGenStruct<A: HiddenProtocol> {
public init() {}
}
public protocol HiddenProtocol {
associatedtype Value
}
public protocol HiddenProtocol2 {}
public protocol HiddenProtocolWithOverride {
func hiddenOverride()
}
public class HiddenClass {}
#elseif PUBLIC_LIB
@_implementationOnly import private_lib
struct LibProtocolConstraint { }
protocol LibProtocolTABound { }
struct LibProtocolTA: LibProtocolTABound { }
protocol LibProtocol {
associatedtype TA: LibProtocolTABound = LibProtocolTA
func hiddenRequirement<A>(
param: HiddenGenStruct<A>
) where A.Value == LibProtocolConstraint
}
extension LibProtocol where TA == LibProtocolTA {
func hiddenRequirement<A>(
param: HiddenGenStruct<A>
) where A.Value == LibProtocolConstraint { }
}
public struct PublicStruct: LibProtocol {
typealias TA = LibProtocolTA
public init() { }
public var nonWrappedVar: String = "some text"
}
struct StructWithOverride: HiddenProtocolWithOverride {
func hiddenOverride() {}
}
internal protocol RefinesHiddenProtocol: HiddenProtocol {
}
public struct PublicStructConformsToHiddenProtocol: RefinesHiddenProtocol {
public typealias Value = Int
public init() { }
}
public class SomeClass {
func funcUsingIoiType(_ a: HiddenClass) {}
}
// Check that we recover from a reference to an implementation-only
// imported type in a protocol composition. rdar://78631465
protocol CompositionMemberInheriting : HiddenProtocol2 {}
protocol CompositionMemberSimple {}
protocol InheritingFromComposition : CompositionMemberInheriting & CompositionMemberSimple {}
struct StructInheritingFromComposition : CompositionMemberInheriting & CompositionMemberSimple {}
class ClassInheritingFromComposition : CompositionMemberInheriting & CompositionMemberSimple {}
protocol InheritingFromCompositionDirect : CompositionMemberSimple & HiddenProtocol2 {}
#elseif CLIENT_APP
import public_lib
var s = PublicStruct()
print(s.nonWrappedVar)
var p = PublicStructConformsToHiddenProtocol()
print(p)
#if FAIL_TYPECHECK
// Access to a missing member on an AnyObject triggers a typo correction
// that looks at *all* class members. rdar://79427805
class ClassUnrelatedToSomeClass {}
var something = ClassUnrelatedToSomeClass() as AnyObject
something.triggerTypoCorrection = 123 // expected-error {{value of type 'AnyObject' has no member 'triggerTypoCorrection'}}
#endif
#endif
| apache-2.0 | f4aa6c324be3bf8c7f9bc52581ff397e | 29.561538 | 200 | 0.762648 | 3.996982 | false | false | false | false |
CoderLiLe/Swift | 类/main.swift | 1 | 1493 | //
// main.swift
// 类
//
// Created by LiLe on 15/4/4.
// Copyright (c) 2015年 LiLe. All rights reserved.
//
import Foundation
/*
对于OC和Swift的初始化,苹果官方给了一些很合理的解释,请点开这里:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html
*/
/*
定义Swift初始化方法,必须遵循三条规则:
1.指定构造器必须调用它直接父类的指定构造器方法
2.便利构造器必须调用同一类中定义的其他初始化方法
3.便利构造器在最后必须调用一个指定构造器。
*/
/*
类的基本定义
Swift中的结构体和类非常相似, 但是又有不同之处
类是具有相同属性和方法的抽象
格式:
class 类名称 {
类的属性和方法
}
*/
class Rect {
var width:Double = 0.0
var height:Double = 0.0
func show() -> Void{
print("width = \(width) height = \(height)")
}
}
// 类没有逐一构造器
//var r1 = Rect(width: 10.0, height: 10.0)
var r1 = Rect()
r1.show()
var r2 = r1
r2.show()
// 类是引用类型, 结构体之间的赋值其实是将r2指向了r1的存储控件, 所以他们是两个只想同一块存储空间, 修改其中一个会影响到另外一个
r1.width = 99
r1.show()
r2.show()
/*
恒等运算符, 用于判断是否是同一个实例, 也就是是否指向同一块存储空间
=== !==
*/
var r3 = Rect()
if r1 === r3
{
print("指向同一块存储空间")
}
| mit | ab0a5533ca589d9d47d209d346067868 | 15.789474 | 154 | 0.677116 | 2.28401 | false | false | false | false |
Dimillian/HackerSwifter | Hacker Swifter/Hacker Swifter/Extensions/HTMLString.swift | 1 | 2629 | //
// HTMLString.swift
// HackerSwifter
//
// Created by Thomas Ricouard on 18/07/14.
// Copyright (c) 2014 Thomas Ricouard. All rights reserved.
//
import Foundation
extension String {
static func stringByRemovingHTMLEntities(string: String) -> String {
var result = string
result = result.stringByReplacingOccurrencesOfString("<p>", withString: "\n\n", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("</p>", withString: "", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("<i>", withString: "", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("</i>", withString: "", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("&", withString: "&", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString(">", withString: ">", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("'", withString: "'", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("/", withString: "/", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString(""", withString: "\"", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("<", withString: "<", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("<", withString: "<", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString(">", withString: ">", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("&", withString: "&", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("<pre><code>", withString: "", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("</code></pre>", withString: "", options: .CaseInsensitiveSearch, range: nil)
let regex = try? NSRegularExpression(pattern: "<a[^>]+href=\"(.*?)\"[^>]*>.*?</a>",
options: NSRegularExpressionOptions.CaseInsensitive)
result = regex!.stringByReplacingMatchesInString(result, options: [], range: NSMakeRange(0, result.utf16.count), withTemplate: "$1")
return result
}
} | mit | 8965b3795c70e8afcc6be60ed2f5ada7 | 70.081081 | 140 | 0.709015 | 5.51153 | false | false | false | false |
mtransitapps/mtransit-for-ios | MonTransit/Source/SQL/SQLHelper/BusDataProviderHelper.swift | 1 | 3137 | //
// BusDataProviderHelper.swift
// SidebarMenu
//
// Created by Thibault on 15-12-17.
// Copyright © 2015 Thibault. All rights reserved.
//
import UIKit
import SQLite
class BusDataProviderHelper {
private let routes = Table("route")
private let id = Expression<Int>("_id")
private let shortname = Expression<String>("short_name")
private let longName = Expression<String>("long_name")
private let color = Expression<String>("color")
private var busList = [BusObject]()
init()
{
}
func createRoutes(iAgency:Agency, iSqlCOnnection:Connection) -> Bool
{
do {
let wStopRawType = iAgency.getMainFilePath()
let wFileText = iAgency.getZipData().getDataFileFromZip(iAgency.mGtfsRoute, iDocumentName: wStopRawType)
if wFileText != ""
{
let wStops = wFileText.stringByReplacingOccurrencesOfString("'", withString: "").componentsSeparatedByString("\n")
let docsTrans = try! iSqlCOnnection.prepare("INSERT INTO ROUTE (_id, short_name, long_name, color) VALUES (?,?,?,?)")
try iSqlCOnnection.transaction(.Deferred) { () -> Void in
for wStop in wStops
{
let wStopFormated = wStop.componentsSeparatedByString(",")
if wStopFormated.count == 4{
try docsTrans.run(Int(wStopFormated[0])!, wStopFormated[1], wStopFormated[2], wStopFormated[3])
}
}
}
}
return true
}
catch {
print("insertion failed: \(error)")
return false
}
}
func retrieveRouteName(iId:Int)
{
let wRoutes = try! SQLProvider.sqlProvider.mainDatabase(iId).prepare(routes)
for route in wRoutes
{
busList.append(BusObject(iBusId: route[id], iBusName: route[longName],iBusNumber: route[shortname],iBusColor: route[color]))
}
}
func retrieveRouteById(iRouteId:Int, iId:Int) -> BusObject
{
let wRoute = try! SQLProvider.sqlProvider.mainDatabase(iId).prepare(routes.filter(id == iRouteId))
for route in wRoute
{
return BusObject(iBusId: route[id], iBusName: route[longName],iBusNumber: route[shortname],iBusColor: route[color])
}
return BusObject()
}
func retrieveLongName(index:Int) -> (wlongName: String, wshortName: String, iColor: String)
{
return (busList[index].getBusName(), busList[index].getBusNumber(), busList[index].getBusColor())
}
func retrieveBusAtIndex(iBusId:Int) -> BusObject
{
return busList[iBusId]
}
func retrieveBus(iBusId:Int) -> BusObject!
{
for wBus in busList
{
if wBus.getBusId() == iBusId{
return wBus
}
}
return nil
}
func totalRoutes() -> Int
{
return busList.count
}
}
| apache-2.0 | 8c1b9e54f72abaa8672265b7161998ca | 29.745098 | 136 | 0.560587 | 4.26087 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/GroupDetails/GroupParticipantsDetail/GroupParticipantsDetailViewModel.swift | 1 | 4222 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireDataModel
fileprivate extension String {
var isValidQuery: Bool {
return !isEmpty && self != "@"
}
}
typealias GroupParticipantsDetailConversation = GroupDetailsConversationType & StableRandomParticipantsProvider
final class GroupParticipantsDetailViewModel: NSObject, SearchHeaderViewControllerDelegate, ZMConversationObserver {
private var internalParticipants: [UserType]
private var filterQuery: String?
let selectedParticipants: [UserType]
let conversation: GroupParticipantsDetailConversation
var participantsDidChange: (() -> Void)?
fileprivate var token: NSObjectProtocol?
var indexPathOfFirstSelectedParticipant: IndexPath? {
guard let user = selectedParticipants.first as? ZMUser else { return nil }
guard let row = (internalParticipants.firstIndex {
($0 as? ZMUser)?.remoteIdentifier == user.remoteIdentifier
}) else { return nil }
let section = user.isGroupAdmin(in: conversation) ? 0 : 1
return IndexPath(row: row, section: section)
}
var participants = [UserType]() {
didSet {
computeParticipantGroups()
participantsDidChange?()
}
}
var admins = [UserType]()
var members = [UserType]()
init(selectedParticipants: [UserType],
conversation: GroupParticipantsDetailConversation) {
internalParticipants = conversation.sortedOtherParticipants
self.conversation = conversation
self.selectedParticipants = selectedParticipants.sorted { $0.name < $1.name }
super.init()
if let conversation = conversation as? ZMConversation {
token = ConversationChangeInfo.add(observer: self, for: conversation)
}
computeVisibleParticipants()
}
private func computeVisibleParticipants() {
guard let query = filterQuery,
query.isValidQuery else {
return participants = internalParticipants
}
participants = (internalParticipants as NSArray).filtered(using: filterPredicate(for: query)) as! [UserType]
}
private func computeParticipantGroups() {
admins = participants.filter({$0.isGroupAdmin(in: conversation)})
members = participants.filter({!$0.isGroupAdmin(in: conversation)})
}
private func filterPredicate(for query: String) -> NSPredicate {
let trimmedQuery = query.trim()
var predicates = [
NSPredicate(format: "name contains[cd] %@", trimmedQuery),
NSPredicate(format: "handle contains[cd] %@", trimmedQuery)
]
if query.hasPrefix("@") {
predicates.append(.init(format: "handle contains[cd] %@", String(trimmedQuery.dropFirst())))
}
return NSCompoundPredicate(orPredicateWithSubpredicates: predicates)
}
func conversationDidChange(_ changeInfo: ConversationChangeInfo) {
guard changeInfo.participantsChanged else { return }
internalParticipants = conversation.sortedOtherParticipants
computeVisibleParticipants()
}
// MARK: - SearchHeaderViewControllerDelegate
func searchHeaderViewController(
_ searchHeaderViewController: SearchHeaderViewController,
updatedSearchQuery query: String
) {
filterQuery = query
computeVisibleParticipants()
}
func searchHeaderViewControllerDidConfirmAction(_ searchHeaderViewController: SearchHeaderViewController) {
// no-op
}
}
| gpl-3.0 | 64f9c2c912097330436fb9817a0ea155 | 33.892562 | 116 | 0.693036 | 5.251244 | false | false | false | false |
JackieQu/QP_DouYu | QP_DouYu/QP_DouYu/Classes/Home/View/AmuseMenuViewCell.swift | 1 | 1581 | //
// AmuseMenuViewCell.swift
// QP_DouYu
//
// Created by JackieQu on 2017/3/8.
// Copyright © 2017年 JackieQu. All rights reserved.
//
import UIKit
private let kGameCellID = "kGameCellID"
class AmuseMenuViewCell: UICollectionViewCell {
var groups : [AnchorGroup]? {
didSet {
collectionView.reloadData()
}
}
@IBOutlet weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
collectionView.register(UINib(nibName: "CollectionViewGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let itemW = collectionView.bounds.width / 4
let itemH = collectionView.bounds.height / 2
layout.itemSize = CGSize(width: itemW, height: itemH)
}
}
extension AmuseMenuViewCell : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return groups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionViewGameCell
cell.clipsToBounds = true
cell.baseGame = groups![indexPath.item]
return cell
}
}
| mit | 3a9ecbd8733819e0288c719ac0a2ac4c | 27.690909 | 130 | 0.673004 | 5.441379 | false | false | false | false |
Nekitosss/tableAnimator | Sources/TableAnimator/TableAnimationApplier.swift | 1 | 21209 | //
// TableAnimationApplier.swift
// NPTableAnimator
//
// Created by Nikita Patskov on 14.11.17.
//
import UIKit
#if os(iOS)
private var tableAssociatedObjectHandle: UInt8 = 0
private var collectionAssociatedObjectHandle: UInt8 = 0
private let monitor = NSObject()
#if swift(>=4.2)
public typealias UITableViewRowAnimation = UITableView.RowAnimation
#endif
/// TableView rows animation style set.
public struct UITableViewRowAnimationSet {
let insert: UITableViewRowAnimation
let delete: UITableViewRowAnimation
let reload: UITableViewRowAnimation
public init(insert: UITableViewRowAnimation, delete: UITableViewRowAnimation, reload: UITableViewRowAnimation) {
self.insert = insert
self.delete = delete
self.reload = reload
}
}
extension UITableView: EmptyCheckableSequence {
var isEmpty: Bool {
let block: () -> Bool = {
let numberOfSections = (self.dataSource?.numberOfSections?(in: self)) ?? 0
let rowsCount: Int = (0 ..< numberOfSections)
.reduce(0) { $0 + (self.dataSource?.tableView(self, numberOfRowsInSection: $1) ?? 0) }
return rowsCount == 0
}
if Thread.isMainThread {
return block()
} else {
return DispatchQueue.main.sync(execute: block)
}
}
/// Use this for applying changes for UITableView.
///
/// - Parameters:
/// - owner: Apply moves to Operation queue, so you need to pass owner for capturing.
/// - newList: New list that should be presented in collection view.
/// - getCurrentListBlock: Block for getting current screen list. Called from main thread.
/// - animator: Instance of TableAnimator for calculating changes.
/// - animated: If you dont want to animate changes, just pass *false*, otherwise, pass *true*.
/// - options: Additional options for animations applying.
/// - from: Initial list, which we got from *getCurrentListBlock()*.
/// - to: New list to set, which you pass in *newList*.
/// - setNewListBlock: Block for changing current screen list to passed *newList*. Called from main thread.
/// - rowAnimations: Specific UITableViewRowAnimations that will be passed in all animation type during applying.
/// - completion: Block for capturing animation completion. Called from main thread.
/// - error: Block for capturing error during changes calculation. When we got error in changes, we call *setNewListBlock* and *tableView.reloadData()*, then error block called
/// - tableError: TableAnimatorError
public func apply<T, O: AnyObject>(owner: O, newList: [T], animator: TableAnimator<T>, animated: Bool, options: ApplyAnimationOptions = [], getCurrentListBlock: @escaping (_ owner: O) -> [T], setNewListBlock: @escaping ((owner: O, newList: [T])) -> Void, rowAnimations: UITableViewRowAnimationSet, completion: (() -> Void)?, error: ((_ tableError: Error) -> Void)?) {
if options.contains(.cancelPreviousAddedOperations) {
self.getApplyQueue().cancelAllOperations()
}
if options.contains(.withoutActuallyRefreshTable) {
self.getApplyQueue().addOperation {
DispatchQueue.main.sync { [weak owner] in
guard let strongO = owner else { return }
setNewListBlock((strongO, newList))
}
}
return
} else if !animated || (self.isEmpty && options.contains(.withoutAnimationForEmptyTable)) {
self.getApplyQueue().addOperation {
DispatchQueue.main.sync { [weak owner, weak self] in
guard let strongO = owner, let strong = self else { return }
setNewListBlock((strongO, newList))
strong.reloadData()
completion?()
}
}
return
}
let setAnimationsClosure: (UITableView, TableAnimations) -> Void = { table, animations in
let animations = table.applyOptions(options: options, to: animations)
table.insertSections(animations.sections.toInsert, with: rowAnimations.insert)
table.deleteSections(animations.sections.toDelete, with: rowAnimations.delete)
table.reloadSections(animations.sections.toUpdate, with: rowAnimations.reload)
for (from, to) in animations.sections.toMove {
table.moveSection(from, toSection: to)
}
table.insertRows(at: animations.cells.toInsert, with: rowAnimations.insert)
table.deleteRows(at: animations.cells.toDelete, with: rowAnimations.delete)
table.reloadRows(at: animations.cells.toUpdate, with: rowAnimations.reload)
for (from, to) in animations.cells.toMove {
table.moveRow(at: from, to: to)
}
}
let safeApplyClosure: (O, DispatchSemaphore, TableAnimations) -> Void = { [weak self] anOwner, semaphore, animations in
guard let strong = self, strong.dataSource != nil else {
return
}
if #available(iOS 11, *) {
strong.performBatchUpdates({
setNewListBlock((anOwner, newList))
setAnimationsClosure(strong, animations)
}, completion: { _ in
if animations.cells.toDeferredUpdate.isEmpty {
completion?()
}
semaphore.signal()
})
} else {
strong.beginUpdates()
setNewListBlock((anOwner, newList))
setAnimationsClosure(strong, animations)
strong.endUpdates()
if animations.cells.toDeferredUpdate.isEmpty {
completion?()
}
semaphore.signal()
}
}
let safeDeferredApplyClosure: (O, DispatchSemaphore, [IndexPath]) -> Void = { [weak self] _, semaphore, toDeferredUpdate in
guard let strong = self, strong.dataSource != nil else {
return
}
let toDeferredUpdate = strong.applyOptions(options: options, toDeferredUpdatePaths: toDeferredUpdate)
if #available(iOS 11, *) {
strong.performBatchUpdates({
strong.reloadRows(at: toDeferredUpdate, with: rowAnimations.reload)
}, completion: { _ in
completion?()
semaphore.signal()
})
} else {
strong.beginUpdates()
strong.reloadRows(at: toDeferredUpdate, with: rowAnimations.reload)
strong.endUpdates()
completion?()
semaphore.signal()
}
}
let onAnimationsError: (O, Error) -> Void = { [weak self] owner, anError in
setNewListBlock((owner, newList))
self?.reloadData()
error?(anError)
}
safeApplier.apply(owner: owner,
newList: newList,
options: options,
animator: animator,
getCurrentListBlock: getCurrentListBlock,
mainPerform: safeApplyClosure,
deferredPerform: safeDeferredApplyClosure,
onAnimationsError: onAnimationsError)
}
/// Use this for applying changes for UITableView.
///
/// - Parameters:
/// - owner: Apply moves to Operation queue, so you need to pass owner for capturing.
/// - newList: New list that should be presented in collection view.
/// - getCurrentListBlock: Block for getting current screen list. Called from main thread.
/// - animator: Instance of TableAnimator for calculating changes.
/// - animated: If you dont want to animate changes, just pass *false*, otherwise, pass *true*.
/// - options: Additional options for animations applying.
/// - from: Initial list, which we got from *getCurrentListBlock()*.
/// - to: New list to set, which you pass in *newList*.
/// - setNewListBlock: Block for changing current screen list to passed *newList*. Called from main thread.
/// - rowAnimation: UITableViewRowAnimation that will be passed in all animation type during applying.
/// - completion: Block for capturing animation completion. Called from main thread.
/// - error: Block for capturing error during changes calculation. When we got error in changes, we call *setNewListBlock* and *tableView.reloadData()*, then error block called
/// - tableError: TableAnimatorError
public func apply<T, O: AnyObject>(owner: O, newList: [T], animator: TableAnimator<T>, animated: Bool, options: ApplyAnimationOptions = [], getCurrentListBlock: @escaping (_ owner: O) -> [T], setNewListBlock: @escaping ((owner: O, newList: [T])) -> Void, rowAnimation: UITableViewRowAnimation, completion: (() -> Void)? = nil, error: ((_ tableError: Error) -> Void)? = nil) {
let animationSet = UITableViewRowAnimationSet(insert: rowAnimation, delete: rowAnimation, reload: rowAnimation)
self.apply(owner: owner, newList: newList, animator: animator, animated: animated, options: options, getCurrentListBlock: getCurrentListBlock, setNewListBlock: setNewListBlock, rowAnimations: animationSet, completion: completion, error: error)
}
/// Use this function when you need synchronize something with serialized animation queue.
///
/// - Returns: Queue that used for animations synchronizing.
public func getApplyQueue() -> OperationQueue {
return safeApplier.applyQueue
}
/// User this when you want to provide your own operation queue for animations serializing.
/// - Note: You **had to** use serialized queue!
///
/// - Parameter operationQueue: Operation queue that will be used for animatino synchronizing.
/// - Returns: *true* if queue was successfully set, *false* if table already have queue for animations.
public func provideApplyQueue(_ operationQueue: OperationQueue) -> Bool {
objc_sync_enter(monitor)
defer { objc_sync_exit(monitor) }
if (objc_getAssociatedObject(self, &tableAssociatedObjectHandle) as? SafeApplier) != nil {
return false
} else {
let applier = SafeApplier(associatedTable: self, operationQueue: operationQueue)
objc_setAssociatedObject(self, &tableAssociatedObjectHandle, applier, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return true
}
}
private var safeApplier: SafeApplier {
get {
objc_sync_enter(monitor)
defer { objc_sync_exit(monitor) }
if let applier = objc_getAssociatedObject(self, &tableAssociatedObjectHandle) as? SafeApplier {
return applier
} else {
let applier = SafeApplier(associatedTable: self)
objc_setAssociatedObject(self, &tableAssociatedObjectHandle, applier, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return applier
}
}
set {
objc_sync_enter(monitor)
defer { objc_sync_exit(monitor) }
objc_setAssociatedObject(self, &tableAssociatedObjectHandle, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
private func applyOptions(options: ApplyAnimationOptions, to animations: (cells: CellsAnimations, sections: SectionsAnimations)) -> (cells: CellsAnimations, sections: SectionsAnimations) {
var animations = animations
if let visibleRows = self.indexPathsForVisibleRows,
let firstResponderIndex = visibleRows.first(where: { self.cellForRow(at: $0)?.isActuallyResponder == true }) {
if options.contains(.excludeFirstResponderCellFromReload) {
animations.cells.toUpdate = animations.cells.toUpdate.filter({ $0 != firstResponderIndex })
}
if options.contains(.excludeFirstResponderSectionFromReload) {
animations.sections.toUpdate.remove(firstResponderIndex.section)
}
}
return animations
}
private func applyOptions(options: ApplyAnimationOptions, toDeferredUpdatePaths: [IndexPath]) -> [IndexPath] {
if let visibleRows = self.indexPathsForVisibleRows,
let firstResponderIndex = visibleRows.first(where: { self.cellForRow(at: $0)?.isActuallyResponder == true }),
options.contains(.excludeFirstResponderCellFromReload) {
return toDeferredUpdatePaths.filter({ $0 != firstResponderIndex })
}
return toDeferredUpdatePaths
}
}
extension UIKit.UICollectionView: EmptyCheckableSequence {
var isEmpty: Bool {
let block: () -> Bool = {
let numberOfSections = (self.dataSource?.numberOfSections?(in: self)) ?? 0
let rowsCount = (0 ..< numberOfSections)
.reduce(0) { $0 + (self.dataSource?.collectionView(self, numberOfItemsInSection: $1) ?? 0) }
return rowsCount == 0
}
if Thread.isMainThread {
return block()
} else {
return DispatchQueue.main.sync(execute: block)
}
}
var safeApplier: SafeApplier {
get {
objc_sync_enter(monitor)
defer { objc_sync_exit(monitor) }
if let applier = objc_getAssociatedObject(self, &collectionAssociatedObjectHandle) as? SafeApplier {
return applier
} else {
let applier = SafeApplier(associatedTable: self)
objc_setAssociatedObject(self, &collectionAssociatedObjectHandle, applier, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return applier
}
}
set {
objc_sync_enter(monitor)
defer { objc_sync_exit(monitor) }
objc_setAssociatedObject(self, &collectionAssociatedObjectHandle, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func applyOptions(options: ApplyAnimationOptions, to animations: (cells: CellsAnimations, sections: SectionsAnimations)) -> (cells: CellsAnimations, sections: SectionsAnimations) {
var animations = animations
if let firstResponderIndex = indexPathsForVisibleItems.first(where: { self.cellForItem(at: $0)?.isActuallyResponder == true }) {
if options.contains(.excludeFirstResponderCellFromReload) {
animations.cells.toUpdate = animations.cells.toUpdate.filter({ $0 != firstResponderIndex })
}
if options.contains(.excludeFirstResponderSectionFromReload) {
animations.sections.toUpdate.remove(firstResponderIndex.section)
}
}
return animations
}
func applyOptions(options: ApplyAnimationOptions, toDeferredUpdatePaths: [IndexPath]) -> [IndexPath] {
if let firstResponderIndex = indexPathsForVisibleItems.first(where: { self.cellForItem(at: $0)?.isActuallyResponder == true }),
options.contains(.excludeFirstResponderCellFromReload) {
return toDeferredUpdatePaths.filter({ $0 != firstResponderIndex })
}
return toDeferredUpdatePaths
}
/// Use this for applying changes for UICollectionView.
///
/// - Parameters:
/// - owner: Apply moves to Operation queue, so you need to pass owner for capturing.
/// - newList: New list that should be presented in collection view.
/// - getCurrentListBlock: Block for getting current screen list. Called from main thread.
/// - animator: Instance of TableAnimator for calculating changes.
/// - animated: If you dont want to animate changes, just pass *false*, otherwise, pass *true*.
/// - options: Additional options for animations applying.
/// - from: Initial list, which we got from *getCurrentListBlock()*.
/// - to: New list to set, which you pass in *newList*.
/// - setNewListBlock: Block for changing current screen list to passed *newList*. Called from main thread.
/// - completion: Block for capturing animation completion. Called from main thread.
/// - error: Block for capturing error during changes calculation. When we got error in changes, we call *setNewListBlock* and *collectionView.reloadData()*, then error block called
/// - tableError: TableAnimatorError
public func apply<T, O: AnyObject>(owner: O, newList: [T], animator: TableAnimator<T>, animated: Bool, options: ApplyAnimationOptions = [], getCurrentListBlock: @escaping (_ owner: O) -> [T], setNewListBlock: @escaping ((owner: O, newList: [T])) -> Void, completion: (() -> Void)? = nil, error: ((_ tableError: Error) -> Void)? = nil) {
if options.contains(.cancelPreviousAddedOperations) {
self.getApplyQueue().cancelAllOperations()
}
if options.contains(.withoutActuallyRefreshTable) {
self.getApplyQueue().addOperation {
DispatchQueue.main.sync { [weak owner] in
guard let strongO = owner else { return }
setNewListBlock((strongO, newList))
}
}
return
} else if !animated || (self.isEmpty && options.contains(.withoutAnimationForEmptyTable)) {
self.getApplyQueue().addOperation {
DispatchQueue.main.sync { [weak owner, weak self] in
guard let strongO = owner, let strong = self else { return }
setNewListBlock((strongO, newList))
strong.reloadData()
completion?()
}
}
return
}
let safeApplyClosure: (O, DispatchSemaphore, TableAnimations) -> Void = { [weak self] anOwner, semaphore, animations in
guard let strong = self, strong.dataSource != nil else {
return
}
let animations = strong.applyOptions(options: options, to: animations)
strong.performBatchUpdates({
setNewListBlock((anOwner, newList))
strong.insertSections(animations.sections.toInsert)
strong.deleteSections(animations.sections.toDelete)
strong.reloadSections(animations.sections.toUpdate)
for (from, to) in animations.sections.toMove {
strong.moveSection(from, toSection: to)
}
strong.insertItems(at: animations.cells.toInsert)
strong.deleteItems(at: animations.cells.toDelete)
strong.reloadItems(at: animations.cells.toUpdate)
for (from, to) in animations.cells.toMove {
strong.moveItem(at: from, to: to)
}
}, completion: { _ in
if animations.cells.toDeferredUpdate.isEmpty {
completion?()
}
semaphore.signal()
})
}
let safeDeferredApplyClosure: (O, DispatchSemaphore, [IndexPath]) -> Void = { [weak self] _, semaphore, toDeferredUpdate in
guard let strong = self, strong.dataSource != nil else {
return
}
let toDeferredUpdate = strong.applyOptions(options: options, toDeferredUpdatePaths: toDeferredUpdate)
strong.performBatchUpdates({
strong.reloadItems(at: toDeferredUpdate)
}, completion: { _ in
completion?()
semaphore.signal()
})
}
let onAnimationsError: (O, Error) -> Void = { [weak self] anOwner, anError in
setNewListBlock((anOwner, newList))
self?.reloadData()
if let strong = self, strong.dataSource == nil {
return
}
error?(anError)
}
safeApplier.apply(owner: owner,
newList: newList,
options: options,
animator: animator,
getCurrentListBlock: getCurrentListBlock,
mainPerform: safeApplyClosure,
deferredPerform: safeDeferredApplyClosure,
onAnimationsError: onAnimationsError)
}
/// Use this when you need synchronize something with serialized animation queue.
///
/// - Returns: Queue that used for animations synchronizing.
public func getApplyQueue() -> OperationQueue {
return safeApplier.applyQueue
}
/// User this when you want to provide your own operation queue for animations serializing.
/// - Note: You **had to** use serialized queue!
///
/// - Parameter operationQueue: Operation queue that will be used for animatino synchronizing.
/// - Returns: *true* if queue was successfully set, *false* if table already have queue for animations.
public func provideApplyQueue(_ operationQueue: OperationQueue) -> Bool {
objc_sync_enter(monitor)
defer { objc_sync_exit(monitor) }
if (objc_getAssociatedObject(self, &tableAssociatedObjectHandle) as? SafeApplier) != nil {
return false
} else {
let applier = SafeApplier(associatedTable: self, operationQueue: operationQueue)
objc_setAssociatedObject(self, &tableAssociatedObjectHandle, applier, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return true
}
}
}
#endif
| mit | 0569d5d5923644ab593dd515183c0740 | 40.504892 | 377 | 0.630817 | 4.648039 | false | false | false | false |
JoshuaRystedt/CalculateEaster | CalculateEasterDate.swift | 1 | 797 | //
// CalculateEasterDate.swift
// Church Cal
//
// Created by Joshua Rystedt on 11/10/15
//
import Foundation
func calculateEasterDateFor(desiredYear: Int) -> NSDate {
// Calculate the date for Easter in any given year
let a = desiredYear % 19
let b = desiredYear / 100
let c = desiredYear % 100
let d = (19 * a + b - b / 4 - ((b - (b + 8) / 25 + 1) / 3) + 15) % 30
let e = (32 + 2 * (b % 4) + 2 * (c / 4) - d - (c % 4)) % 7
let f = d + e - 7 * ((a + 11 * d + 22 * e) / 451) + 114
let month = f / 31
let day = f % 31 + 1
// Create NSDate for Easter
customDateComponents.month = month
customDateComponents.day = day
customDateComponents.year = desiredYear
return calendar.dateFromComponents(customDateComponents)!
}
| gpl-3.0 | 526015b0b7338b03178a5f7028db599c | 26.482759 | 73 | 0.57591 | 3.266393 | false | false | false | false |
AndreMuis/Algorithms | BuildOrder.playground/Contents.swift | 1 | 2535 | //
// Determine the build order for a list of projects with dependencies
//
enum State
{
case NotBuilt
case Visiting
case Built
}
class Project
{
let name : String
var state : State
var dependencies : [Project]
init(name: String)
{
self.name = name
self.state = State.NotBuilt
self.dependencies = [Project]()
}
}
func orderProjects(projects : [Project]) -> [Project]
{
var orderedProjects : [Project] = [Project]()
for project in projects
{
if project.state != State.Built
{
if depthFirstSearch(rootProject: project, orderedProjects: &orderedProjects) == false
{
orderedProjects.removeAll()
break
}
}
}
return orderedProjects
}
func depthFirstSearch(rootProject rootProject : Project, inout orderedProjects : [Project]) -> Bool
{
if (rootProject.state == State.Visiting)
{
return false
}
if rootProject.state == State.NotBuilt
{
rootProject.state = State.Visiting
for project in rootProject.dependencies
{
if depthFirstSearch(rootProject: project, orderedProjects: &orderedProjects) == false
{
return false
}
}
rootProject.state = State.Built
orderedProjects.append(rootProject)
}
return true
}
//
// B - C - D H
// | | | |
// A E - F - G I
//
var projects : [Project] = [Project]()
var aProject = Project(name: "A")
projects.append(aProject)
var bProject = Project(name: "B")
projects.append(bProject)
var cProject = Project(name: "C")
projects.append(cProject)
var dProject = Project(name: "D")
projects.append(dProject)
var eProject = Project(name: "E")
projects.append(eProject)
var fProject = Project(name: "F")
projects.append(fProject)
var gProject = Project(name: "G")
projects.append(gProject)
var hProject = Project(name: "H")
projects.append(hProject)
var iProject = Project(name: "I")
projects.append(iProject)
bProject.dependencies = [aProject]
cProject.dependencies = [bProject, dProject, eProject]
dProject.dependencies = [fProject]
eProject.dependencies = [fProject]
fProject.dependencies = [gProject]
hProject.dependencies = [iProject]
var orderedProjects : [Project] = orderProjects(projects)
for project in orderedProjects
{
print(project.name)
}
gProject.dependencies = [cProject]
orderProjects(projects)
| mit | beb6966b277c0e510d86200c8b448ffa | 17.23741 | 99 | 0.628402 | 3.806306 | false | false | false | false |
johnno1962c/swift-corelibs-foundation | Foundation/NSString.swift | 1 | 66102 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
public typealias unichar = UInt16
extension unichar : ExpressibleByUnicodeScalarLiteral {
public typealias UnicodeScalarLiteralType = UnicodeScalar
public init(unicodeScalarLiteral scalar: UnicodeScalar) {
self.init(scalar.value)
}
}
#if os(OSX) || os(iOS)
internal let kCFStringEncodingMacRoman = CFStringBuiltInEncodings.macRoman.rawValue
internal let kCFStringEncodingWindowsLatin1 = CFStringBuiltInEncodings.windowsLatin1.rawValue
internal let kCFStringEncodingISOLatin1 = CFStringBuiltInEncodings.isoLatin1.rawValue
internal let kCFStringEncodingNextStepLatin = CFStringBuiltInEncodings.nextStepLatin.rawValue
internal let kCFStringEncodingASCII = CFStringBuiltInEncodings.ASCII.rawValue
internal let kCFStringEncodingUnicode = CFStringBuiltInEncodings.unicode.rawValue
internal let kCFStringEncodingUTF8 = CFStringBuiltInEncodings.UTF8.rawValue
internal let kCFStringEncodingNonLossyASCII = CFStringBuiltInEncodings.nonLossyASCII.rawValue
internal let kCFStringEncodingUTF16 = CFStringBuiltInEncodings.UTF16.rawValue
internal let kCFStringEncodingUTF16BE = CFStringBuiltInEncodings.UTF16BE.rawValue
internal let kCFStringEncodingUTF16LE = CFStringBuiltInEncodings.UTF16LE.rawValue
internal let kCFStringEncodingUTF32 = CFStringBuiltInEncodings.UTF32.rawValue
internal let kCFStringEncodingUTF32BE = CFStringBuiltInEncodings.UTF32BE.rawValue
internal let kCFStringEncodingUTF32LE = CFStringBuiltInEncodings.UTF32LE.rawValue
internal let kCFStringGraphemeCluster = CFStringCharacterClusterType.graphemeCluster
internal let kCFStringComposedCharacterCluster = CFStringCharacterClusterType.composedCharacterCluster
internal let kCFStringCursorMovementCluster = CFStringCharacterClusterType.cursorMovementCluster
internal let kCFStringBackwardDeletionCluster = CFStringCharacterClusterType.backwardDeletionCluster
internal let kCFStringNormalizationFormD = CFStringNormalizationForm.D
internal let kCFStringNormalizationFormKD = CFStringNormalizationForm.KD
internal let kCFStringNormalizationFormC = CFStringNormalizationForm.C
internal let kCFStringNormalizationFormKC = CFStringNormalizationForm.KC
#endif
extension NSString {
public struct EncodingConversionOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let allowLossy = EncodingConversionOptions(rawValue: 1)
public static let externalRepresentation = EncodingConversionOptions(rawValue: 2)
internal static let failOnPartialEncodingConversion = EncodingConversionOptions(rawValue: 1 << 20)
}
public struct EnumerationOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let byLines = EnumerationOptions(rawValue: 0)
public static let byParagraphs = EnumerationOptions(rawValue: 1)
public static let byComposedCharacterSequences = EnumerationOptions(rawValue: 2)
public static let byWords = EnumerationOptions(rawValue: 3)
public static let bySentences = EnumerationOptions(rawValue: 4)
public static let reverse = EnumerationOptions(rawValue: 1 << 8)
public static let substringNotRequired = EnumerationOptions(rawValue: 1 << 9)
public static let localized = EnumerationOptions(rawValue: 1 << 10)
internal static let forceFullTokens = EnumerationOptions(rawValue: 1 << 20)
}
}
extension NSString {
public struct CompareOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let caseInsensitive = CompareOptions(rawValue: 1)
public static let literal = CompareOptions(rawValue: 2)
public static let backwards = CompareOptions(rawValue: 4)
public static let anchored = CompareOptions(rawValue: 8)
public static let numeric = CompareOptions(rawValue: 64)
public static let diacriticInsensitive = CompareOptions(rawValue: 128)
public static let widthInsensitive = CompareOptions(rawValue: 256)
public static let forcedOrdering = CompareOptions(rawValue: 512)
public static let regularExpression = CompareOptions(rawValue: 1024)
internal func _cfValue(_ fixLiteral: Bool = false) -> CFStringCompareFlags {
#if os(OSX) || os(iOS)
return contains(.literal) || !fixLiteral ? CFStringCompareFlags(rawValue: rawValue) : CFStringCompareFlags(rawValue: rawValue).union(.compareNonliteral)
#else
return contains(.literal) || !fixLiteral ? CFStringCompareFlags(rawValue) : CFStringCompareFlags(rawValue) | UInt(kCFCompareNonliteral)
#endif
}
}
}
internal func _createRegexForPattern(_ pattern: String, _ options: NSRegularExpression.Options) -> NSRegularExpression? {
struct local {
static let __NSRegularExpressionCache: NSCache<NSString, NSRegularExpression> = {
let cache = NSCache<NSString, NSRegularExpression>()
cache.name = "NSRegularExpressionCache"
cache.countLimit = 10
return cache
}()
}
let key = "\(options):\(pattern)"
if let regex = local.__NSRegularExpressionCache.object(forKey: key._nsObject) {
return regex
}
do {
let regex = try NSRegularExpression(pattern: pattern, options: options)
local.__NSRegularExpressionCache.setObject(regex, forKey: key._nsObject)
return regex
} catch {
}
return nil
}
internal func _bytesInEncoding(_ str: NSString, _ encoding: String.Encoding, _ fatalOnError: Bool, _ externalRep: Bool, _ lossy: Bool) -> UnsafePointer<Int8>? {
let theRange = NSMakeRange(0, str.length)
var cLength = 0
var used = 0
var options: NSString.EncodingConversionOptions = []
if externalRep {
options.formUnion(.externalRepresentation)
}
if lossy {
options.formUnion(.allowLossy)
}
if !str.getBytes(nil, maxLength: Int.max - 1, usedLength: &cLength, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) {
if fatalOnError {
fatalError("Conversion on encoding failed")
}
return nil
}
let buffer = malloc(cLength + 1)!.bindMemory(to: Int8.self, capacity: cLength + 1)
if !str.getBytes(buffer, maxLength: cLength, usedLength: &used, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) {
fatalError("Internal inconsistency; previously claimed getBytes returned success but failed with similar invocation")
}
buffer.advanced(by: cLength).initialize(to: 0)
return UnsafePointer(buffer) // leaked and should be autoreleased via a NSData backing but we cannot here
}
internal func isALineSeparatorTypeCharacter(_ ch: unichar) -> Bool {
if ch > 0x0d && ch < 0x0085 { /* Quick test to cover most chars */
return false
}
return ch == 0x0a || ch == 0x0d || ch == 0x0085 || ch == 0x2028 || ch == 0x2029
}
internal func isAParagraphSeparatorTypeCharacter(_ ch: unichar) -> Bool {
if ch > 0x0d && ch < 0x2029 { /* Quick test to cover most chars */
return false
}
return ch == 0x0a || ch == 0x0d || ch == 0x2029
}
open class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding {
private let _cfinfo = _CFInfo(typeID: CFStringGetTypeID())
internal var _storage: String
open var length: Int {
guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else {
NSRequiresConcreteImplementation()
}
return _storage.utf16.count
}
open func character(at index: Int) -> unichar {
guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else {
NSRequiresConcreteImplementation()
}
let start = _storage.utf16.startIndex
return _storage.utf16[start.advanced(by: index)]
}
public override convenience init() {
let characters = Array<unichar>(repeating: 0, count: 1)
self.init(characters: characters, length: 0)
}
internal init(_ string: String) {
_storage = string
}
public convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.string") {
let str = aDecoder._decodePropertyListForKey("NS.string") as! String
self.init(string: str)
} else {
let decodedData : Data? = aDecoder.withDecodedUnsafeBufferPointer(forKey: "NS.bytes") {
guard let buffer = $0 else { return nil }
return Data(buffer: buffer)
}
guard let data = decodedData else { return nil }
self.init(data: data, encoding: String.Encoding.utf8.rawValue)
}
}
public required convenience init(string aString: String) {
self.init(aString)
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSString.self || type(of: self) === NSMutableString.self {
if let contents = _fastContents {
return NSMutableString(characters: contents, length: length)
}
}
let characters = UnsafeMutablePointer<unichar>.allocate(capacity: length)
getCharacters(characters, range: NSMakeRange(0, length))
let result = NSMutableString(characters: characters, length: length)
characters.deinitialize()
characters.deallocate(capacity: length)
return result
}
public static var supportsSecureCoding: Bool {
return true
}
open func encode(with aCoder: NSCoder) {
if let aKeyedCoder = aCoder as? NSKeyedArchiver {
aKeyedCoder._encodePropertyList(self, forKey: "NS.string")
} else {
aCoder.encode(self)
}
}
public init(characters: UnsafePointer<unichar>, length: Int) {
_storage = String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length))
}
public required convenience init(unicodeScalarLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required convenience init(extendedGraphemeClusterLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required init(stringLiteral value: StaticString) {
_storage = String(describing: value)
}
public convenience init?(cString nullTerminatedCString: UnsafePointer<Int8>, encoding: UInt) {
self.init(string: CFStringCreateWithCString(kCFAllocatorSystemDefault, nullTerminatedCString, CFStringConvertNSStringEncodingToEncoding(encoding))._swiftObject)
}
internal func _fastCStringContents(_ nullTerminated: Bool) -> UnsafePointer<Int8>? {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
if _storage._core.isASCII {
return unsafeBitCast(_storage._core.startASCII, to: UnsafePointer<Int8>.self)
}
}
return nil
}
internal var _fastContents: UnsafePointer<UniChar>? {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
if !_storage._core.isASCII {
return UnsafePointer<UniChar>(_storage._core.startUTF16)
}
}
return nil
}
internal var _encodingCantBeStoredInEightBitCFString: Bool {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return !_storage._core.isASCII
}
return false
}
override open var _cfTypeID: CFTypeID {
return CFStringGetTypeID()
}
open override func isEqual(_ object: Any?) -> Bool {
guard let string = (object as? NSString)?._swiftObject else { return false }
return self.isEqual(to: string)
}
open override var description: String {
return _swiftObject
}
open override var hash: Int {
return Int(bitPattern:CFStringHashNSString(self._cfObject))
}
}
extension NSString {
public func getCharacters(_ buffer: UnsafeMutablePointer<unichar>, range: NSRange) {
for idx in 0..<range.length {
buffer[idx] = character(at: idx + range.location)
}
}
public func substring(from: Int) -> String {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return String(_storage.utf16.suffix(from: _storage.utf16.startIndex.advanced(by: from)))!
} else {
return substring(with: NSMakeRange(from, length - from))
}
}
public func substring(to: Int) -> String {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return String(_storage.utf16.prefix(upTo: _storage.utf16.startIndex
.advanced(by: to)))!
} else {
return substring(with: NSMakeRange(0, to))
}
}
public func substring(with range: NSRange) -> String {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
let start = _storage.utf16.startIndex
let min = start.advanced(by: range.location)
let max = start.advanced(by: range.location + range.length)
return String(decoding: _storage.utf16[min..<max], as: UTF16.self)
} else {
let buff = UnsafeMutablePointer<unichar>.allocate(capacity: range.length)
getCharacters(buff, range: range)
let result = String(describing: buff)
buff.deinitialize()
buff.deallocate(capacity: range.length)
return result
}
}
public func compare(_ string: String) -> ComparisonResult {
return compare(string, options: [], range: NSMakeRange(0, length))
}
public func compare(_ string: String, options mask: CompareOptions) -> ComparisonResult {
return compare(string, options: mask, range: NSMakeRange(0, length))
}
public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange) -> ComparisonResult {
return compare(string, options: mask, range: compareRange, locale: nil)
}
public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange, locale: Any?) -> ComparisonResult {
var res: CFComparisonResult
if let loc = locale {
res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), (loc as! NSLocale)._cfObject)
} else {
res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), nil)
}
return ComparisonResult._fromCF(res)
}
public func caseInsensitiveCompare(_ string: String) -> ComparisonResult {
return compare(string, options: .caseInsensitive, range: NSMakeRange(0, length))
}
public func localizedCompare(_ string: String) -> ComparisonResult {
return compare(string, options: [], range: NSMakeRange(0, length), locale: Locale.current._bridgeToObjectiveC())
}
public func localizedCaseInsensitiveCompare(_ string: String) -> ComparisonResult {
return compare(string, options: .caseInsensitive, range: NSMakeRange(0, length), locale: Locale.current._bridgeToObjectiveC())
}
public func localizedStandardCompare(_ string: String) -> ComparisonResult {
return compare(string, options: [.caseInsensitive, .numeric, .widthInsensitive, .forcedOrdering], range: NSMakeRange(0, length), locale: Locale.current._bridgeToObjectiveC())
}
public func isEqual(to aString: String) -> Bool {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return _storage == aString
} else {
return length == aString.length && compare(aString, options: .literal, range: NSMakeRange(0, length)) == .orderedSame
}
}
public func hasPrefix(_ str: String) -> Bool {
return range(of: str, options: .anchored, range: NSMakeRange(0, length)).location != NSNotFound
}
public func hasSuffix(_ str: String) -> Bool {
return range(of: str, options: [.anchored, .backwards], range: NSMakeRange(0, length)).location != NSNotFound
}
public func commonPrefix(with str: String, options mask: CompareOptions = []) -> String {
var currentSubstring: CFMutableString?
let isLiteral = mask.contains(.literal)
var lastMatch = NSRange()
let selfLen = length
let otherLen = str.length
var low = 0
var high = selfLen
var probe = (low + high) / 2
if (probe > otherLen) {
probe = otherLen // A little heuristic to avoid some extra work
}
if selfLen == 0 || otherLen == 0 {
return ""
}
var numCharsBuffered = 0
var arrayBuffer = [unichar](repeating: 0, count: 100)
let other = str._nsObject
return arrayBuffer.withUnsafeMutablePointerOrAllocation(selfLen, fastpath: UnsafeMutablePointer<unichar>(mutating: _fastContents)) { (selfChars: UnsafeMutablePointer<unichar>) -> String in
// Now do the binary search. Note that the probe value determines the length of the substring to check.
while true {
let range = NSMakeRange(0, isLiteral ? probe + 1 : NSMaxRange(rangeOfComposedCharacterSequence(at: probe))) // Extend the end of the composed char sequence
if range.length > numCharsBuffered { // Buffer more characters if needed
getCharacters(selfChars, range: NSMakeRange(numCharsBuffered, range.length - numCharsBuffered))
numCharsBuffered = range.length
}
if currentSubstring == nil {
currentSubstring = CFStringCreateMutableWithExternalCharactersNoCopy(kCFAllocatorSystemDefault, selfChars, range.length, range.length, kCFAllocatorNull)
} else {
CFStringSetExternalCharactersNoCopy(currentSubstring, selfChars, range.length, range.length)
}
if other.range(of: currentSubstring!._swiftObject, options: mask.union(.anchored), range: NSMakeRange(0, otherLen)).length != 0 { // Match
lastMatch = range
low = probe + 1
} else {
high = probe
}
if low >= high {
break
}
probe = (low + high) / 2
}
return lastMatch.length != 0 ? substring(with: lastMatch) : ""
}
}
public func contains(_ str: String) -> Bool {
return range(of: str, options: [], range: NSMakeRange(0, length), locale: nil).location != NSNotFound
}
public func localizedCaseInsensitiveContains(_ str: String) -> Bool {
return range(of: str, options: .caseInsensitive, range: NSMakeRange(0, length), locale: Locale.current).location != NSNotFound
}
public func localizedStandardContains(_ str: String) -> Bool {
return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSMakeRange(0, length), locale: Locale.current).location != NSNotFound
}
public func localizedStandardRange(of str: String) -> NSRange {
return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSMakeRange(0, length), locale: Locale.current)
}
public func range(of searchString: String) -> NSRange {
return range(of: searchString, options: [], range: NSMakeRange(0, length), locale: nil)
}
public func range(of searchString: String, options mask: CompareOptions = []) -> NSRange {
return range(of: searchString, options: mask, range: NSMakeRange(0, length), locale: nil)
}
public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange {
return range(of: searchString, options: mask, range: searchRange, locale: nil)
}
internal func _rangeOfRegularExpressionPattern(regex pattern: String, options mask: CompareOptions, range searchRange: NSRange, locale: Locale?) -> NSRange {
var matchedRange = NSMakeRange(NSNotFound, 0)
let regexOptions: NSRegularExpression.Options = mask.contains(.caseInsensitive) ? .caseInsensitive : []
let matchingOptions: NSRegularExpression.MatchingOptions = mask.contains(.anchored) ? .anchored : []
if let regex = _createRegexForPattern(pattern, regexOptions) {
matchedRange = regex.rangeOfFirstMatch(in: _swiftObject, options: matchingOptions, range: searchRange)
}
return matchedRange
}
public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange, locale: Locale?) -> NSRange {
let findStrLen = searchString.length
let len = length
precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)")
if mask.contains(.regularExpression) {
return _rangeOfRegularExpressionPattern(regex: searchString, options: mask, range:searchRange, locale: locale)
}
if searchRange.length == 0 || findStrLen == 0 { // ??? This last item can't be here for correct Unicode compares
return NSMakeRange(NSNotFound, 0)
}
var result = CFRange()
let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in
if let loc = locale {
return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), loc._cfObject, rangep)
} else {
return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), nil, rangep)
}
}
if res {
return NSMakeRange(result.location, result.length)
} else {
return NSMakeRange(NSNotFound, 0)
}
}
public func rangeOfCharacter(from searchSet: CharacterSet) -> NSRange {
return rangeOfCharacter(from: searchSet, options: [], range: NSMakeRange(0, length))
}
public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = []) -> NSRange {
return rangeOfCharacter(from: searchSet, options: mask, range: NSMakeRange(0, length))
}
public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange {
let len = length
precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)")
var result = CFRange()
let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in
return CFStringFindCharacterFromSet(_cfObject, searchSet._cfObject, CFRange(searchRange), mask._cfValue(), rangep)
}
if res {
return NSMakeRange(result.location, result.length)
} else {
return NSMakeRange(NSNotFound, 0)
}
}
public func rangeOfComposedCharacterSequence(at index: Int) -> NSRange {
let range = CFStringGetRangeOfCharacterClusterAtIndex(_cfObject, index, kCFStringComposedCharacterCluster)
return NSMakeRange(range.location, range.length)
}
public func rangeOfComposedCharacterSequences(for range: NSRange) -> NSRange {
let length = self.length
var start: Int
var end: Int
if range.location == length {
start = length
} else {
start = rangeOfComposedCharacterSequence(at: range.location).location
}
var endOfRange = NSMaxRange(range)
if endOfRange == length {
end = length
} else {
if range.length > 0 {
endOfRange = endOfRange - 1 // We want 0-length range to be treated same as 1-length range.
}
end = NSMaxRange(rangeOfComposedCharacterSequence(at: endOfRange))
}
return NSMakeRange(start, end - start)
}
public func appending(_ aString: String) -> String {
return _swiftObject + aString
}
public var doubleValue: Double {
var start: Int = 0
var result = 0.0
let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Double) -> Void in
result = value
}
return result
}
public var floatValue: Float {
var start: Int = 0
var result: Float = 0.0
let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Float) -> Void in
result = value
}
return result
}
public var intValue: Int32 {
return Scanner(string: _swiftObject).scanInt32() ?? 0
}
public var integerValue: Int {
let scanner = Scanner(string: _swiftObject)
var value: Int = 0
let _ = scanner.scanInt(&value)
return value
}
public var longLongValue: Int64 {
return Scanner(string: _swiftObject).scanInt64() ?? 0
}
public var boolValue: Bool {
let scanner = Scanner(string: _swiftObject)
// skip initial whitespace if present
let _ = scanner.scanCharactersFromSet(.whitespaces)
// scan a single optional '+' or '-' character, followed by zeroes
if scanner.scanString("+") == nil {
let _ = scanner.scanString("-")
}
// scan any following zeroes
let _ = scanner.scanCharactersFromSet(CharacterSet(charactersIn: "0"))
return scanner.scanCharactersFromSet(CharacterSet(charactersIn: "tTyY123456789")) != nil
}
public var uppercased: String {
return uppercased(with: nil)
}
public var lowercased: String {
return lowercased(with: nil)
}
public var capitalized: String {
return capitalized(with: nil)
}
public var localizedUppercase: String {
return uppercased(with: Locale.current)
}
public var localizedLowercase: String {
return lowercased(with: Locale.current)
}
public var localizedCapitalized: String {
return capitalized(with: Locale.current)
}
public func uppercased(with locale: Locale?) -> String {
let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)!
CFStringUppercase(mutableCopy, locale?._cfObject ?? nil)
return mutableCopy._swiftObject
}
public func lowercased(with locale: Locale?) -> String {
let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)!
CFStringLowercase(mutableCopy, locale?._cfObject ?? nil)
return mutableCopy._swiftObject
}
public func capitalized(with locale: Locale?) -> String {
let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)!
CFStringCapitalize(mutableCopy, locale?._cfObject ?? nil)
return mutableCopy._swiftObject
}
internal func _getBlockStart(_ startPtr: UnsafeMutablePointer<Int>?, end endPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, forRange range: NSRange, stopAtLineSeparators line: Bool) {
let len = length
var ch: unichar
precondition(range.length <= len && range.location < len - range.length, "Range {\(range.location), \(range.length)} is out of bounds of length \(len)")
if range.location == 0 && range.length == len && contentsEndPtr == nil { // This occurs often
startPtr?.pointee = 0
endPtr?.pointee = range.length
return
}
/* Find the starting point first */
if startPtr != nil {
var start: Int = 0
if range.location == 0 {
start = 0
} else {
var buf = _NSStringBuffer(string: self, start: range.location, end: len)
/* Take care of the special case where start happens to fall right between \r and \n */
ch = buf.currentCharacter
buf.rewind()
if ch == 0x0a && buf.currentCharacter == 0x0d {
buf.rewind()
}
while true {
if line ? isALineSeparatorTypeCharacter(buf.currentCharacter) : isAParagraphSeparatorTypeCharacter(buf.currentCharacter) {
start = buf.location + 1
break
} else if buf.location <= 0 {
start = 0
break
} else {
buf.rewind()
}
}
startPtr!.pointee = start
}
}
if (endPtr != nil || contentsEndPtr != nil) {
var endOfContents = 1
var lineSeparatorLength = 1
var buf = _NSStringBuffer(string: self, start: NSMaxRange(range) - (range.length > 0 ? 1 : 0), end: len)
/* First look at the last char in the range (if the range is zero length, the char after the range) to see if we're already on or within a end of line sequence... */
ch = buf.currentCharacter
if ch == 0x0a {
endOfContents = buf.location
buf.rewind()
if buf.currentCharacter == 0x0d {
lineSeparatorLength = 2
endOfContents -= 1
}
} else {
while true {
if line ? isALineSeparatorTypeCharacter(ch) : isAParagraphSeparatorTypeCharacter(ch) {
endOfContents = buf.location /* This is actually end of contentsRange */
buf.advance() /* OK for this to go past the end */
if ch == 0x0d && buf.currentCharacter == 0x0a {
lineSeparatorLength = 2
}
break
} else if buf.location == len {
endOfContents = len
lineSeparatorLength = 0
break
} else {
buf.advance()
ch = buf.currentCharacter
}
}
}
contentsEndPtr?.pointee = endOfContents
endPtr?.pointee = endOfContents + lineSeparatorLength
}
}
public func getLineStart(_ startPtr: UnsafeMutablePointer<Int>?, end lineEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) {
_getBlockStart(startPtr, end: lineEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: true)
}
public func lineRange(for range: NSRange) -> NSRange {
var start = 0
var lineEnd = 0
getLineStart(&start, end: &lineEnd, contentsEnd: nil, for: range)
return NSMakeRange(start, lineEnd - start)
}
public func getParagraphStart(_ startPtr: UnsafeMutablePointer<Int>?, end parEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) {
_getBlockStart(startPtr, end: parEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: false)
}
public func paragraphRange(for range: NSRange) -> NSRange {
var start = 0
var parEnd = 0
getParagraphStart(&start, end: &parEnd, contentsEnd: nil, for: range)
return NSMakeRange(start, parEnd - start)
}
public func enumerateSubstrings(in range: NSRange, options opts: EnumerationOptions = [], using block: (String?, NSRange, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
NSUnimplemented()
}
public func enumerateLines(_ block: (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
enumerateSubstrings(in: NSMakeRange(0, length), options:.byLines) { substr, substrRange, enclosingRange, stop in
block(substr!, stop)
}
}
public var utf8String: UnsafePointer<Int8>? {
return _bytesInEncoding(self, String.Encoding.utf8, false, false, false)
}
public var fastestEncoding: UInt {
return String.Encoding.unicode.rawValue
}
public var smallestEncoding: UInt {
if canBeConverted(to: String.Encoding.ascii.rawValue) {
return String.Encoding.ascii.rawValue
}
return String.Encoding.unicode.rawValue
}
public func data(using encoding: UInt, allowLossyConversion lossy: Bool = false) -> Data? {
let len = length
var reqSize = 0
let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding)
if !CFStringIsEncodingAvailable(cfStringEncoding) {
return nil
}
let convertedLen = __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, nil, 0, &reqSize)
if convertedLen != len {
return nil // Not able to do it all...
}
if 0 < reqSize {
var data = Data(count: reqSize)
data.count = data.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Int in
if __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, UnsafeMutablePointer<UInt8>(mutableBytes), reqSize, &reqSize) == convertedLen {
return reqSize
} else {
fatalError("didn't convert all characters")
}
}
return data
}
return Data()
}
public func data(using encoding: UInt) -> Data? {
return data(using: encoding, allowLossyConversion: false)
}
public func canBeConverted(to encoding: UInt) -> Bool {
if encoding == String.Encoding.unicode.rawValue || encoding == String.Encoding.nonLossyASCII.rawValue || encoding == String.Encoding.utf8.rawValue {
return true
}
return __CFStringEncodeByteStream(_cfObject, 0, length, false, CFStringConvertNSStringEncodingToEncoding(encoding), 0, nil, 0, nil) == length
}
public func cString(using encoding: UInt) -> UnsafePointer<Int8>? {
return _bytesInEncoding(self, String.Encoding(rawValue: encoding), false, false, false)
}
public func getCString(_ buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferCount: Int, encoding: UInt) -> Bool {
var used = 0
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
if _storage._core.isASCII {
used = min(self.length, maxBufferCount - 1)
_storage._core.startASCII.withMemoryRebound(to: Int8.self,
capacity: used) {
buffer.moveAssign(from: $0, count: used)
}
buffer.advanced(by: used).initialize(to: 0)
return true
}
}
if getBytes(UnsafeMutableRawPointer(buffer), maxLength: maxBufferCount, usedLength: &used, encoding: encoding, options: [], range: NSMakeRange(0, self.length), remaining: nil) {
buffer.advanced(by: used).initialize(to: 0)
return true
}
return false
}
public func getBytes(_ buffer: UnsafeMutableRawPointer?, maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>?, encoding: UInt, options: EncodingConversionOptions = [], range: NSRange, remaining leftover: NSRangePointer?) -> Bool {
var totalBytesWritten = 0
var numCharsProcessed = 0
let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding)
var result = true
if length > 0 {
if CFStringIsEncodingAvailable(cfStringEncoding) {
let lossyOk = options.contains(.allowLossy)
let externalRep = options.contains(.externalRepresentation)
let failOnPartial = options.contains(.failOnPartialEncodingConversion)
let bytePtr = buffer?.bindMemory(to: UInt8.self, capacity: maxBufferCount)
numCharsProcessed = __CFStringEncodeByteStream(_cfObject, range.location, range.length, externalRep, cfStringEncoding, lossyOk ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, bytePtr, bytePtr != nil ? maxBufferCount : 0, &totalBytesWritten)
if (failOnPartial && numCharsProcessed < range.length) || numCharsProcessed == 0 {
result = false
}
} else {
result = false /* ??? Need other encodings */
}
}
usedBufferCount?.pointee = totalBytesWritten
leftover?.pointee = NSMakeRange(range.location + numCharsProcessed, range.length - numCharsProcessed)
return result
}
public func maximumLengthOfBytes(using enc: UInt) -> Int {
let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc)
let result = CFStringGetMaximumSizeForEncoding(length, cfEnc)
return result == kCFNotFound ? 0 : result
}
public func lengthOfBytes(using enc: UInt) -> Int {
let len = length
var numBytes: CFIndex = 0
let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc)
let convertedLen = __CFStringEncodeByteStream(_cfObject, 0, len, false, cfEnc, 0, nil, 0, &numBytes)
return convertedLen != len ? 0 : numBytes
}
open class var availableStringEncodings: UnsafePointer<UInt> {
struct once {
static let encodings: UnsafePointer<UInt> = {
let cfEncodings = CFStringGetListOfAvailableEncodings()!
var idx = 0
var numEncodings = 0
while cfEncodings.advanced(by: idx).pointee != kCFStringEncodingInvalidId {
idx += 1
numEncodings += 1
}
let theEncodingList = UnsafeMutablePointer<String.Encoding.RawValue>.allocate(capacity: numEncodings + 1)
theEncodingList.advanced(by: numEncodings).pointee = 0 // Terminator
numEncodings -= 1
while numEncodings >= 0 {
theEncodingList.advanced(by: numEncodings).pointee = CFStringConvertEncodingToNSStringEncoding(cfEncodings.advanced(by: numEncodings).pointee)
numEncodings -= 1
}
return UnsafePointer<UInt>(theEncodingList)
}()
}
return once.encodings
}
open class func localizedName(of encoding: UInt) -> String {
if let theString = CFStringGetNameOfEncoding(CFStringConvertNSStringEncodingToEncoding(encoding)) {
// TODO: read the localized version from the Foundation "bundle"
return theString._swiftObject
}
return ""
}
open class var defaultCStringEncoding: UInt {
return CFStringConvertEncodingToNSStringEncoding(CFStringGetSystemEncoding())
}
open var decomposedStringWithCanonicalMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormD)
return string._swiftObject
}
open var precomposedStringWithCanonicalMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormC)
return string._swiftObject
}
open var decomposedStringWithCompatibilityMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormKD)
return string._swiftObject
}
open var precomposedStringWithCompatibilityMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormKC)
return string._swiftObject
}
open func components(separatedBy separator: String) -> [String] {
let len = length
var lrange = range(of: separator, options: [], range: NSMakeRange(0, len))
if lrange.length == 0 {
return [_swiftObject]
} else {
var array = [String]()
var srange = NSMakeRange(0, len)
while true {
let trange = NSMakeRange(srange.location, lrange.location - srange.location)
array.append(substring(with: trange))
srange.location = lrange.location + lrange.length
srange.length = len - srange.location
lrange = range(of: separator, options: [], range: srange)
if lrange.length == 0 {
break
}
}
array.append(substring(with: srange))
return array
}
}
open func components(separatedBy separator: CharacterSet) -> [String] {
let len = length
var range = rangeOfCharacter(from: separator, options: [], range: NSMakeRange(0, len))
if range.length == 0 {
return [_swiftObject]
} else {
var array = [String]()
var srange = NSMakeRange(0, len)
while true {
let trange = NSMakeRange(srange.location, range.location - srange.location)
array.append(substring(with: trange))
srange.location = range.location + range.length
srange.length = len - srange.location
range = rangeOfCharacter(from: separator, options: [], range: srange)
if range.length == 0 {
break
}
}
array.append(substring(with: srange))
return array
}
}
open func trimmingCharacters(in set: CharacterSet) -> String {
let len = length
var buf = _NSStringBuffer(string: self, start: 0, end: len)
while !buf.isAtEnd,
let character = UnicodeScalar(buf.currentCharacter),
set.contains(character) {
buf.advance()
}
let startOfNonTrimmedRange = buf.location // This points at the first char not in the set
if startOfNonTrimmedRange == len { // Note that this also covers the len == 0 case, which is important to do here before the len-1 in the next line.
return ""
} else if startOfNonTrimmedRange < len - 1 {
buf.location = len - 1
while let character = UnicodeScalar(buf.currentCharacter),
set.contains(character),
buf.location >= startOfNonTrimmedRange {
buf.rewind()
}
let endOfNonTrimmedRange = buf.location
return substring(with: NSMakeRange(startOfNonTrimmedRange, endOfNonTrimmedRange + 1 - startOfNonTrimmedRange))
} else {
return substring(with: NSMakeRange(startOfNonTrimmedRange, 1))
}
}
open func padding(toLength newLength: Int, withPad padString: String, startingAt padIndex: Int) -> String {
let len = length
if newLength <= len { // The simple cases (truncation)
return newLength == len ? _swiftObject : substring(with: NSMakeRange(0, newLength))
}
let padLen = padString.length
if padLen < 1 {
fatalError("empty pad string")
}
if padIndex >= padLen {
fatalError("out of range padIndex")
}
let mStr = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, _cfObject)!
CFStringPad(mStr, padString._cfObject, newLength, padIndex)
return mStr._swiftObject
}
open func folding(options: CompareOptions = [], locale: Locale?) -> String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringFold(string, options._cfValue(), locale?._cfObject)
return string._swiftObject
}
internal func _stringByReplacingOccurrencesOfRegularExpressionPattern(_ pattern: String, withTemplate replacement: String, options: CompareOptions, range: NSRange) -> String {
let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : []
let matchingOptions: NSRegularExpression.MatchingOptions = options.contains(.anchored) ? .anchored : []
if let regex = _createRegexForPattern(pattern, regexOptions) {
return regex.stringByReplacingMatches(in: _swiftObject, options: matchingOptions, range: range, withTemplate: replacement)
}
return ""
}
open func replacingOccurrences(of target: String, with replacement: String, options: CompareOptions = [], range searchRange: NSRange) -> String {
if options.contains(.regularExpression) {
return _stringByReplacingOccurrencesOfRegularExpressionPattern(target, withTemplate: replacement, options: options, range: searchRange)
}
let str = mutableCopy(with: nil) as! NSMutableString
if str.replaceOccurrences(of: target, with: replacement, options: options, range: searchRange) == 0 {
return _swiftObject
} else {
return str._swiftObject
}
}
open func replacingOccurrences(of target: String, with replacement: String) -> String {
return replacingOccurrences(of: target, with: replacement, options: [], range: NSMakeRange(0, length))
}
open func replacingCharacters(in range: NSRange, with replacement: String) -> String {
let str = mutableCopy(with: nil) as! NSMutableString
str.replaceCharacters(in: range, with: replacement)
return str._swiftObject
}
open func applyingTransform(_ transform: String, reverse: Bool) -> String? {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, _cfObject)
if (CFStringTransform(string, nil, transform._cfObject, reverse)) {
return string._swiftObject
} else {
return nil
}
}
internal func _getExternalRepresentation(_ data: inout Data, _ dest: URL, _ enc: UInt) throws {
let length = self.length
var numBytes = 0
let theRange = NSMakeRange(0, length)
if !getBytes(nil, maxLength: Int.max - 1, usedLength: &numBytes, encoding: enc, options: [], range: theRange, remaining: nil) {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteInapplicableStringEncoding.rawValue, userInfo: [
NSURLErrorKey: dest,
])
}
var mData = Data(count: numBytes)
// The getBytes:... call should hopefully not fail, given it succeeded above, but check anyway (mutable string changing behind our back?)
var used = 0
// This binds mData memory to UInt8 because Data.withUnsafeMutableBytes does not handle raw pointers.
try mData.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Void in
if !getBytes(mutableBytes, maxLength: numBytes, usedLength: &used, encoding: enc, options: [], range: theRange, remaining: nil) {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnknown.rawValue, userInfo: [
NSURLErrorKey: dest,
])
}
}
data = mData
}
internal func _writeTo(_ url: URL, _ useAuxiliaryFile: Bool, _ enc: UInt) throws {
var data = Data()
try _getExternalRepresentation(&data, url, enc)
try data.write(to: url, options: useAuxiliaryFile ? .atomic : [])
}
open func write(to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws {
try _writeTo(url, useAuxiliaryFile, enc)
}
open func write(toFile path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws {
try _writeTo(URL(fileURLWithPath: path), useAuxiliaryFile, enc)
}
public convenience init(charactersNoCopy characters: UnsafeMutablePointer<unichar>, length: Int, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ {
// ignore the no-copy-ness
self.init(characters: characters, length: length)
if freeBuffer { // cant take a hint here...
free(UnsafeMutableRawPointer(characters))
}
}
public convenience init?(utf8String nullTerminatedCString: UnsafePointer<Int8>) {
let count = Int(strlen(nullTerminatedCString))
if let str = nullTerminatedCString.withMemoryRebound(to: UInt8.self, capacity: count, {
let buffer = UnsafeBufferPointer<UInt8>(start: $0, count: count)
return String._fromCodeUnitSequence(UTF8.self, input: buffer)
}) as String?
{
self.init(str)
} else {
return nil
}
}
public convenience init(format: String, arguments argList: CVaListPointer) {
let str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, argList)!
self.init(str._swiftObject)
}
public convenience init(format: String, locale: AnyObject?, arguments argList: CVaListPointer) {
let str: CFString
if let loc = locale {
if type(of: loc) === NSLocale.self || type(of: loc) === NSDictionary.self {
str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, unsafeBitCast(loc, to: CFDictionary.self), format._cfObject, argList)
} else {
fatalError("locale parameter must be a NSLocale or a NSDictionary")
}
} else {
str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, argList)
}
self.init(str._swiftObject)
}
public convenience init(format: NSString, _ args: CVarArg...) {
let str = withVaList(args) { (vaPtr) -> CFString! in
CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, vaPtr)
}!
self.init(str._swiftObject)
}
public convenience init?(data: Data, encoding: UInt) {
if data.isEmpty {
self.init("")
} else {
guard let cf = data.withUnsafeBytes({ (bytes: UnsafePointer<UInt8>) -> CFString? in
return CFStringCreateWithBytes(kCFAllocatorDefault, bytes, data.count, CFStringConvertNSStringEncodingToEncoding(encoding), true)
}) else { return nil }
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
return nil
}
}
}
public convenience init?(bytes: UnsafeRawPointer, length len: Int, encoding: UInt) {
let bytePtr = bytes.bindMemory(to: UInt8.self, capacity: len)
guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, len, CFStringConvertNSStringEncodingToEncoding(encoding), true) else {
return nil
}
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
return nil
}
}
public convenience init?(bytesNoCopy bytes: UnsafeMutableRawPointer, length len: Int, encoding: UInt, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ {
// just copy for now since the internal storage will be a copy anyhow
self.init(bytes: bytes, length: len, encoding: encoding)
if freeBuffer { // dont take the hint
free(bytes)
}
}
public convenience init(contentsOf url: URL, encoding enc: UInt) throws {
let readResult = try NSData(contentsOf: url, options: [])
let bytePtr = readResult.bytes.bindMemory(to: UInt8.self, capacity: readResult.length)
guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, readResult.length, CFStringConvertNSStringEncodingToEncoding(enc), true) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [
"NSDebugDescription" : "Unable to create a string using the specified encoding."
])
}
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [
"NSDebugDescription" : "Unable to bridge CFString to String."
])
}
}
public convenience init(contentsOfFile path: String, encoding enc: UInt) throws {
try self.init(contentsOf: URL(fileURLWithPath: path), encoding: enc)
}
public convenience init(contentsOf url: URL, usedEncoding enc: UnsafeMutablePointer<UInt>?) throws {
let readResult = try NSData(contentsOf: url, options:[])
let encoding: UInt
let offset: Int
let bytePtr = readResult.bytes.bindMemory(to: UInt8.self, capacity:readResult.length)
if readResult.length >= 4 && bytePtr[0] == 0xFF && bytePtr[1] == 0xFE && bytePtr[2] == 0x00 && bytePtr[3] == 0x00 {
encoding = String.Encoding.utf32LittleEndian.rawValue
offset = 4
}
else if readResult.length >= 2 && bytePtr[0] == 0xFE && bytePtr[1] == 0xFF {
encoding = String.Encoding.utf16BigEndian.rawValue
offset = 2
}
else if readResult.length >= 2 && bytePtr[0] == 0xFF && bytePtr[1] == 0xFE {
encoding = String.Encoding.utf16LittleEndian.rawValue
offset = 2
}
else if readResult.length >= 4 && bytePtr[0] == 0x00 && bytePtr[1] == 0x00 && bytePtr[2] == 0xFE && bytePtr[3] == 0xFF {
encoding = String.Encoding.utf32BigEndian.rawValue
offset = 4
}
else {
//Need to work on more conditions. This should be the default
encoding = String.Encoding.utf8.rawValue
offset = 0
}
enc?.pointee = encoding
// Since the encoding being passed includes the byte order the BOM wont be checked or skipped, so pass offset to
// manually skip the BOM header.
guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr + offset, readResult.length - offset,
CFStringConvertNSStringEncodingToEncoding(encoding), true) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [
"NSDebugDescription" : "Unable to create a string using the specified encoding."
])
}
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [
"NSDebugDescription" : "Unable to bridge CFString to String."
])
}
}
public convenience init(contentsOfFile path: String, usedEncoding enc: UnsafeMutablePointer<UInt>?) throws {
try self.init(contentsOf: URL(fileURLWithPath: path), usedEncoding: enc)
}
}
extension NSString : ExpressibleByStringLiteral { }
open class NSMutableString : NSString {
open func replaceCharacters(in range: NSRange, with aString: String) {
guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else {
NSRequiresConcreteImplementation()
}
let start = _storage.utf16.startIndex
let min = _storage.utf16.index(start, offsetBy: range.location).samePosition(in: _storage)!
let max = _storage.utf16.index(start, offsetBy: range.location + range.length).samePosition(in: _storage)!
_storage.replaceSubrange(min..<max, with: aString)
}
public required override init(characters: UnsafePointer<unichar>, length: Int) {
super.init(characters: characters, length: length)
}
public required init(capacity: Int) {
super.init(characters: [], length: 0)
}
public convenience required init?(coder aDecoder: NSCoder) {
guard let str = NSString(coder: aDecoder) else {
return nil
}
self.init(string: String._unconditionallyBridgeFromObjectiveC(str))
}
public required convenience init(unicodeScalarLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required convenience init(extendedGraphemeClusterLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required init(stringLiteral value: StaticString) {
if value.hasPointerRepresentation {
super.init(String._fromWellFormedCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: value.utf8Start, count: Int(value.utf8CodeUnitCount))))
} else {
var uintValue = value.unicodeScalar.value
super.init(String._fromWellFormedCodeUnitSequence(UTF32.self, input: UnsafeBufferPointer(start: &uintValue, count: 1)))
}
}
public required init(string aString: String) {
super.init(aString)
}
internal func appendCharacters(_ characters: UnsafePointer<unichar>, length: Int) {
if type(of: self) == NSMutableString.self {
_storage.append(String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length)))
} else {
replaceCharacters(in: NSMakeRange(self.length, 0), with: String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length)))
}
}
internal func _cfAppendCString(_ characters: UnsafePointer<Int8>, length: Int) {
if type(of: self) == NSMutableString.self {
_storage.append(String(cString: characters))
}
}
}
extension NSMutableString {
public func insert(_ aString: String, at loc: Int) {
replaceCharacters(in: NSMakeRange(loc, 0), with: aString)
}
public func deleteCharacters(in range: NSRange) {
replaceCharacters(in: range, with: "")
}
public func append(_ aString: String) {
replaceCharacters(in: NSMakeRange(length, 0), with: aString)
}
public func setString(_ aString: String) {
replaceCharacters(in: NSMakeRange(0, length), with: aString)
}
internal func _replaceOccurrencesOfRegularExpressionPattern(_ pattern: String, withTemplate replacement: String, options: CompareOptions, range searchRange: NSRange) -> Int {
let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : []
let matchingOptions: NSRegularExpression.MatchingOptions = options.contains(.anchored) ? .anchored : []
if let regex = _createRegexForPattern(pattern, regexOptions) {
return regex.replaceMatches(in: self, options: matchingOptions, range: searchRange, withTemplate: replacement)
}
return 0
}
public func replaceOccurrences(of target: String, with replacement: String, options: CompareOptions = [], range searchRange: NSRange) -> Int {
let backwards = options.contains(.backwards)
let len = length
precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Search range is out of bounds")
if options.contains(.regularExpression) {
return _replaceOccurrencesOfRegularExpressionPattern(target, withTemplate:replacement, options:options, range: searchRange)
}
if let findResults = CFStringCreateArrayWithFindResults(kCFAllocatorSystemDefault, _cfObject, target._cfObject, CFRange(searchRange), options._cfValue(true)) {
let numOccurrences = CFArrayGetCount(findResults)
for cnt in 0..<numOccurrences {
let rangePtr = CFArrayGetValueAtIndex(findResults, backwards ? cnt : numOccurrences - cnt - 1)
replaceCharacters(in: NSRange(rangePtr!.load(as: CFRange.self)), with: replacement)
}
return numOccurrences
} else {
return 0
}
}
public func applyTransform(_ transform: String, reverse: Bool, range: NSRange, updatedRange resultingRange: NSRangePointer?) -> Bool {
var cfRange = CFRangeMake(range.location, range.length)
return withUnsafeMutablePointer(to: &cfRange) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in
if CFStringTransform(_cfMutableObject, rangep, transform._cfObject, reverse) {
resultingRange?.pointee.location = rangep.pointee.location
resultingRange?.pointee.length = rangep.pointee.length
return true
}
return false
}
}
}
extension String {
// this is only valid for the usage for CF since it expects the length to be in unicode characters instead of grapheme clusters "✌🏾".utf16.count = 3 and CFStringGetLength(CFSTR("✌🏾")) = 3 not 1 as it would be represented with grapheme clusters
internal var length: Int {
return utf16.count
}
}
extension NSString : _CFBridgeable, _SwiftBridgeable {
typealias SwiftType = String
internal var _cfObject: CFString { return unsafeBitCast(self, to: CFString.self) }
internal var _swiftObject: String { return String._unconditionallyBridgeFromObjectiveC(self) }
}
extension NSMutableString {
internal var _cfMutableObject: CFMutableString { return unsafeBitCast(self, to: CFMutableString.self) }
}
extension CFString : _NSBridgeable, _SwiftBridgeable {
typealias NSType = NSString
typealias SwiftType = String
internal var _nsObject: NSType { return unsafeBitCast(self, to: NSString.self) }
internal var _swiftObject: String { return _nsObject._swiftObject }
}
extension String : _NSBridgeable, _CFBridgeable {
typealias NSType = NSString
typealias CFType = CFString
internal var _nsObject: NSType { return _bridgeToObjectiveC() }
internal var _cfObject: CFType { return _nsObject._cfObject }
}
#if !(os(OSX) || os(iOS))
extension String {
public func hasPrefix(_ prefix: String) -> Bool {
if prefix.isEmpty {
return true
}
let cfstring = self._cfObject
let range = CFRangeMake(0, CFStringGetLength(cfstring))
let opts = CFStringCompareFlags(
kCFCompareAnchored | kCFCompareNonliteral)
return CFStringFindWithOptions(cfstring, prefix._cfObject,
range, opts, nil)
}
public func hasSuffix(_ suffix: String) -> Bool {
if suffix.isEmpty {
return true
}
let cfstring = self._cfObject
let range = CFRangeMake(0, CFStringGetLength(cfstring))
let opts = CFStringCompareFlags(
kCFCompareAnchored | kCFCompareBackwards | kCFCompareNonliteral)
return CFStringFindWithOptions(cfstring, suffix._cfObject,
range, opts, nil)
}
}
#endif
extension NSString : _StructTypeBridgeable {
public typealias _StructType = String
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
| apache-2.0 | eb911ebeaf9daf71647d7f929588a2aa | 43.12016 | 274 | 0.637415 | 5.159407 | false | false | false | false |
tedvb/Cubic | Cubic/Drawing.swift | 1 | 5126 | //
// Drawing.swift
// Cubic
//
// Created by Ted von Bevern on 5/27/15.
// Copyright (c) 2015 Ted von Bevern. All rights reserved.
//
import Foundation
import SceneKit
func drawLUT(lut: LUT, numInterpPoints: Int) -> [SCNNode] {
var lutNodes = [SCNNode]()
for i in 0...numInterpPoints {
var lutNode = SCNNode()
for point in lut.points {
var sphereGeometry = SCNSphere(radius: 0.01)
var red: CGFloat
var green: CGFloat
var blue: CGFloat
//interpolate r, g, b values for each point based on i / numInterpPoints
red = CGFloat((point.red - point.originRed) * Double(i) / Double(numInterpPoints) + point.originRed)
green = CGFloat((point.green - point.originGreen) * Double(i) / Double(numInterpPoints) + point.originGreen)
blue = CGFloat((point.blue - point.originBlue) * Double(i) / Double(numInterpPoints) + point.originBlue)
sphereGeometry.firstMaterial!.diffuse.contents = NSColor(red: red, green: green, blue: blue, alpha: 1.0)
sphereGeometry.segmentCount = 5
var sphereNode = SCNNode(geometry: sphereGeometry)
sphereNode.position = SCNVector3Make(red, green, blue)
lutNode.addChildNode(sphereNode)
}
lutNodes.append(lutNode)
}
return lutNodes
}
func drawFrame() -> SCNNode {
var frameNode = SCNNode()
var edgeNodes = [SCNNode]()
for var i = 0; i < 9; i++ {
var geo = SCNCylinder(radius: 0.001, height: 1.0)
geo.firstMaterial!.diffuse.contents = NSColor.whiteColor()
edgeNodes.append(SCNNode(geometry: geo))
edgeNodes[i].pivot = SCNMatrix4MakeTranslation(CGFloat(0), CGFloat(-0.5), CGFloat(0))
}
edgeNodes[0].rotation = SCNVector4Make(CGFloat(0), CGFloat(0), CGFloat(1.0), CGFloat(-M_PI_2))
edgeNodes[0].position = SCNVector3Make(CGFloat(0), CGFloat(1.0), CGFloat(0))
edgeNodes[1].position = SCNVector3Make(CGFloat(1.0), CGFloat(0), CGFloat(0))
edgeNodes[2].rotation = SCNVector4Make(CGFloat(1.0), CGFloat(0), CGFloat(0), CGFloat(M_PI_2))
edgeNodes[2].position = SCNVector3Make(CGFloat(1.0), CGFloat(0), CGFloat(0))
edgeNodes[3].rotation = SCNVector4Make(CGFloat(1.0), CGFloat(0), CGFloat(0), CGFloat(M_PI_2))
edgeNodes[3].position = SCNVector3Make(CGFloat(0), CGFloat(1.0), CGFloat(0))
edgeNodes[4].rotation = SCNVector4Make(CGFloat(1.0), CGFloat(0), CGFloat(0), CGFloat(M_PI_2))
edgeNodes[4].position = SCNVector3Make(CGFloat(1.0), CGFloat(1.0), CGFloat(0))
edgeNodes[5].position = SCNVector3Make(CGFloat(0), CGFloat(0), CGFloat(1.0))
edgeNodes[6].rotation = SCNVector4Make(CGFloat(0), CGFloat(0), CGFloat(1.0), CGFloat(-M_PI_2))
edgeNodes[6].position = SCNVector3Make(CGFloat(0), CGFloat(1.0), CGFloat(1.0))
edgeNodes[7].position = SCNVector3Make(CGFloat(1.0), CGFloat(0), CGFloat(1.0))
edgeNodes[8].rotation = SCNVector4Make(CGFloat(0), CGFloat(0), CGFloat(1.0), CGFloat(-M_PI_2))
edgeNodes[8].position = SCNVector3Make(CGFloat(0), CGFloat(0), CGFloat(1.0))
for node in edgeNodes {
frameNode.addChildNode(node)
}
return frameNode
}
func drawAxes() -> SCNNode {
var axisNode = SCNNode()
let rCylinder = SCNCylinder(radius: 0.001, height: 1.0)
let gCylinder = SCNCylinder(radius: 0.001, height: 1.0)
let bCylinder = SCNCylinder(radius: 0.001, height: 1.0)
rCylinder.firstMaterial!.diffuse.contents = NSColor.redColor()
gCylinder.firstMaterial!.diffuse.contents = NSColor.greenColor()
bCylinder.firstMaterial!.diffuse.contents = NSColor.blueColor()
var rAxisNode = SCNNode(geometry: rCylinder)
var gAxisNode = SCNNode(geometry: gCylinder)
var bAxisNode = SCNNode(geometry: bCylinder)
rAxisNode.pivot = SCNMatrix4MakeTranslation(CGFloat(0), CGFloat(0.5), CGFloat(0.0))
gAxisNode.pivot = SCNMatrix4MakeTranslation(CGFloat(0), CGFloat(-0.5), CGFloat(0.0))
bAxisNode.pivot = SCNMatrix4MakeTranslation(CGFloat(0), CGFloat(-0.5), CGFloat(0.0))
rAxisNode.rotation = SCNVector4Make(CGFloat(0.0), CGFloat(0.0), CGFloat(1.0), CGFloat(M_PI_2))
gAxisNode.rotation = SCNVector4Make(CGFloat(0.0), CGFloat(1.0), CGFloat(0.0), CGFloat(M_PI_2))
bAxisNode.rotation = SCNVector4Make(CGFloat(1.0), CGFloat(0.0), CGFloat(0.0), CGFloat(M_PI_2))
axisNode.addChildNode(rAxisNode)
axisNode.addChildNode(gAxisNode)
axisNode.addChildNode(bAxisNode)
return axisNode
}
func drawDiagonal() -> SCNNode {
let diagCylinder = SCNCylinder(radius: 0.001, height: sqrt(3))
diagCylinder.firstMaterial!.diffuse.contents = NSColor.whiteColor()
var diagNode = SCNNode(geometry: diagCylinder)
diagNode.pivot = SCNMatrix4MakeTranslation(CGFloat(0.0), CGFloat(-sqrt(3)/2.0), CGFloat(0.0))
diagNode.rotation = SCNVector4Make(CGFloat(1.0), CGFloat(0.0), CGFloat(-1.0), CGFloat(0.95531))
return diagNode
}
| mit | 397cbd8490c6a0b4967232906af18979 | 37.833333 | 120 | 0.65158 | 3.572125 | false | false | false | false |
lanjing99/iOSByTutorials | iOS 8 by tutorials/Chapter 15 - Beginning CloudKit/BabiFud-Final/BabiFud/DetailViewController.swift | 1 | 11705 | /*
* Copyright (c) 2014 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import UIWidgets
import CloudKit
class DetailViewController: UITableViewController, UISplitViewControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var masterPopoverController: UIPopoverController? = nil
@IBOutlet var coverView: UIImageView!
@IBOutlet var titleLabel: UILabel!
@IBOutlet var starRating: StarRatingControl!
@IBOutlet var kidsMenuButton: CheckedButton!
@IBOutlet var healthyChoiceButton: CheckedButton!
@IBOutlet var womensRoomButton: UIButton!
@IBOutlet var mensRoomButton: UIButton!
@IBOutlet var boosterButton: UIButton!
@IBOutlet var highchairButton: UIButton!
@IBOutlet var addPhotoButton: UIButton!
@IBOutlet var photoScrollView: UIScrollView!
@IBOutlet var noteTextView: UITextView!
var detailItem: Establishment! {
didSet {
if self.masterPopoverController != nil {
self.masterPopoverController!.dismissPopoverAnimated(true)
}
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail: Establishment = self.detailItem {
title = detail.name
detail.loadCoverPhoto() { image in
dispatch_async(dispatch_get_main_queue()) {
self.coverView.image = image
}
}
titleLabel.text = detail.name
starRating.maxRating = 5
starRating.enabled = false
Model.sharedInstance().userInfo.loggedInToICloud() {
accountStatus, error in
let enabled = accountStatus == .Available || accountStatus == .CouldNotDetermine
self.starRating.enabled = enabled
self.healthyChoiceButton.enabled = enabled
self.kidsMenuButton.enabled = enabled
self.mensRoomButton.enabled = enabled
self.womensRoomButton.enabled = enabled
self.boosterButton.enabled = enabled
self.highchairButton.enabled = enabled
self.addPhotoButton.enabled = enabled
}
self.kidsMenuButton.checked = detailItem.kidsMenu
self.healthyChoiceButton.checked = detailItem.healthyChoice
self.womensRoomButton.selected = (detailItem.changingTable() & ChangingTableLocation.Womens).boolValue
self.mensRoomButton.selected = (detailItem.changingTable() & ChangingTableLocation.Mens).boolValue
self.highchairButton.selected = (detailItem.seatingType() & SeatingType.HighChair).boolValue
self.boosterButton.selected = (detailItem.seatingType() & SeatingType.Booster).boolValue
detail.fetchRating() { rating, isUser in
dispatch_async(dispatch_get_main_queue()) {
self.starRating.maxRating = 5
self.starRating.rating = Float(rating)
self.starRating.setNeedsDisplay()
self.starRating.emptyColor = isUser ? UIColor.yellowColor() : UIColor.whiteColor()
self.starRating.solidColor = isUser ? UIColor.yellowColor() : UIColor.whiteColor()
}
}
detail.fetchPhotos() { assets in
if assets != nil {
var x = 10
for record in assets {
if let asset = record.objectForKey("Photo") as? CKAsset {
let image: UIImage? = UIImage(contentsOfFile: asset.fileURL.path!)
if image != nil {
let imView = UIImageView(image: image)
imView.frame = CGRect(x: x, y: 0, width: 60, height: 60)
imView.clipsToBounds = true
imView.layer.cornerRadius = 8
x += 70
imView.layer.borderWidth = 0.0
//if the user has discovered the photo poster, color the photo with a green border
if let photoUserRef = record.objectForKey("User") as? CKReference {
let photoUserId = photoUserRef.recordID
let contactList = Model.sharedInstance().userInfo.contacts
let contacts = contactList.filter {$0.userRecordID == photoUserId}
if contacts.count > 0 {
imView.layer.borderWidth = 1.0
imView.layer.borderColor = UIColor.greenColor().CGColor
}
}
dispatch_async(dispatch_get_main_queue()) {
self.photoScrollView.addSubview(imView)
}
}
}
}
}
}
detail.fetchNote() { note in
println("note \(note)")
if let noteText = note {
dispatch_async(dispatch_get_main_queue()) {
self.noteTextView.text = noteText
}
}
}
}
}
func saveRating(rating: NSNumber) {
// 1
let ratingRecord = CKRecord(recordType: "Rating")
// 2
ratingRecord.setObject(rating, forKey: "Rating")
// 3
let ref = CKReference(record: self.detailItem.record,
action: .DeleteSelf)
// 4
ratingRecord.setObject(ref, forKey: "Establishment")
// 5
Model.sharedInstance().userInfo.userID() {
userID, error in
if let userRecord = userID {
//6
let userRef = CKReference(recordID: userRecord,
action: .None)
ratingRecord.setObject(userRef, forKey: "User")
// 7
self.detailItem.database.saveRecord(ratingRecord) {
record, error in
if error != nil {
println("error saving rating: (\rating)")
} else {
dispatch_async(dispatch_get_main_queue()) {
self.starRating.emptyColor = UIColor.yellowColor()
self.starRating.solidColor = UIColor.yellowColor()
self.starRating.setNeedsDisplay()
}
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
coverView.clipsToBounds = true
coverView.layer.cornerRadius = 10.0
starRating.editingChangedBlock = { rating in
self.saveRating(rating)
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
configureView()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "EditNote" {
let noteController = segue.destinationViewController as NotesViewController
noteController.establishment = self.detailItem
}
}
// #pragma mark - Split view
func splitViewController(splitController: UISplitViewController, willHideViewController viewController: UIViewController, withBarButtonItem barButtonItem: UIBarButtonItem, forPopoverController popoverController: UIPopoverController) {
barButtonItem.title = NSLocalizedString("Places", comment: "Places")
self.navigationItem.setLeftBarButtonItem(barButtonItem, animated: true)
self.masterPopoverController = popoverController
}
func splitViewController(splitController: UISplitViewController, willShowViewController viewController: UIViewController, invalidatingBarButtonItem barButtonItem: UIBarButtonItem) {
// Called when the view is shown again in the split view, invalidating the button and popover controller.
self.navigationItem.setLeftBarButtonItem(nil, animated: true)
self.masterPopoverController = nil
}
func splitViewController(splitController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
// #pragma mark - Image Picking
@IBAction func addPhoto(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .SavedPhotosAlbum
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]!) {
dismissViewControllerAnimated(true, completion: nil)
if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
self.addPhotoToEstablishment(selectedImage)
}
}
}
func generateFileURL() -> NSURL {
let fileManager = NSFileManager.defaultManager()
let fileArray: NSArray = fileManager.URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)
let fileURL = fileArray.lastObject?.URLByAppendingPathComponent(NSUUID().UUIDString).URLByAppendingPathExtension("jpg")
if let filePath = fileArray.lastObject?.path {
if !fileManager.fileExistsAtPath(filePath!) {
fileManager.createDirectoryAtPath(filePath!, withIntermediateDirectories: true, attributes: nil, error: nil)
}
}
return fileURL!
}
func addNewPhotoToScrollView(photo:UIImage) {
let newImView = UIImageView(image: photo)
let offset = self.detailItem.assetCount * 70 + 10
var frame: CGRect = CGRect(x: offset, y: 0, width: 60, height: 60)
newImView.frame = frame
newImView.clipsToBounds = true
newImView.layer.cornerRadius = 8
dispatch_async(dispatch_get_main_queue()) {
self.photoScrollView.addSubview(newImView)
self.photoScrollView.contentSize = CGSize(width: CGRectGetMaxX(frame), height: CGRectGetHeight(frame));
}
}
func addPhotoToEstablishment(photo: UIImage) {
//1
let fileURL = generateFileURL()
let data = UIImageJPEGRepresentation(photo, 0.9)
var error : NSError?
let wrote = data.writeToURL(fileURL, options: .AtomicWrite, error: &error)
if (error != nil) {
UIAlertView(title: "Error Saving Photo",
message: error?.localizedDescription, delegate: nil,
cancelButtonTitle: "OK").show()
return
}
// 2
let asset = CKAsset(fileURL: fileURL)
// 3
let ref = CKReference(record: self.detailItem.record,
action: .DeleteSelf)
// 4
Model.sharedInstance().userInfo.userID() {
userID, error in
if let userRecordID = userID {
let userRef = CKReference(recordID: userRecordID, action: .None)
// 5
let record = CKRecord(recordType: "EstablishmentPhoto")
record.setObject(asset, forKey: "Photo")
// 6
record.setObject(ref, forKey: "Establishment")
record.setObject(userRef, forKey: "User")
// 7
self.detailItem.database.saveRecord(record) {record, error in
if error == nil {
// 8
self.addNewPhotoToScrollView(photo)
}
NSFileManager.defaultManager().removeItemAtURL(fileURL, error: nil)
}
}
}
}
}
| mit | 99b7d9df8e52bc5590771cfdcb69ae1e | 37.127036 | 236 | 0.682187 | 4.84278 | false | false | false | false |
zsheikh-systango/WordPower | Skeleton/Pods/NotificationBannerSwift/NotificationBanner/Classes/NotificationBannerQueue.swift | 2 | 3296 | /*
The MIT License (MIT)
Copyright (c) 2017 Dalton Hinterscher
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
public enum QueuePosition {
case back
case front
}
public class NotificationBannerQueue: NSObject {
/// The default instance of the NotificationBannerQueue
public static let `default` = NotificationBannerQueue()
/// The notification banners currently placed on the queue
private(set) var banners: [BaseNotificationBanner] = []
/// The current number of notification banners on the queue
public var numberOfBanners: Int {
return banners.count
}
/**
Adds a banner to the queue
-parameter banner: The notification banner to add to the queue
-parameter queuePosition: The position to show the notification banner. If the position is .front, the
banner will be displayed immediately
*/
func addBanner(_ banner: BaseNotificationBanner, queuePosition: QueuePosition) {
if queuePosition == .back {
banners.append(banner)
if banners.index(of: banner) == 0 {
banner.show(placeOnQueue: false, bannerPosition: banner.bannerPosition)
}
} else {
banner.show(placeOnQueue: false, bannerPosition: banner.bannerPosition)
if let firstBanner = banners.first {
firstBanner.suspend()
}
banners.insert(banner, at: 0)
}
}
/**
Shows the next notificaiton banner on the queue if one exists
-parameter callback: The closure to execute after a banner is shown or when the queue is empty
*/
func showNext(callback: ((_ isEmpty: Bool) -> Void)) {
if !banners.isEmpty {
banners.removeFirst()
}
guard let banner = banners.first else {
callback(true)
return
}
if banner.isSuspended {
banner.resume()
} else {
banner.show(placeOnQueue: false)
}
callback(false)
}
/**
Removes all notification banners from the queue
*/
public func removeAll() {
banners.removeAll()
}
}
| mit | 258d52306086791686778d1c50f29563 | 33.694737 | 147 | 0.649879 | 5.166144 | false | false | false | false |
pengleelove/Reflect | Reflect/Reflect/Reflect/Reflect+Property.swift | 4 | 1022 | //
// Reflect+Property.swift
// Reflect
//
// Created by 冯成林 on 15/8/19.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import Foundation
extension Reflect{
/** 获取类名 */
var classNameString: String {return "\(self.dynamicType)"}
/** 遍历成员属性:对象调用 */
func properties(property: (name: String, type: ReflectType, value: Any) -> Void){
for (var i=0; i<mirror.count; i++){
if mirror[i].0 == "super" {continue}
let propertyNameString = mirror[i].0
let propertyValueInstaceMirrorType = mirror[i].1
property(name:propertyNameString , type: ReflectType(propertyMirrorType: propertyValueInstaceMirrorType), value: propertyValueInstaceMirrorType.value)
}
}
/** 静态方法调用 */
class func properties(property: (name: String, type: ReflectType, value: Any) -> Void){self().properties(property)}
}
| mit | 4b74655575062b3e01ff41932129b891 | 23.769231 | 162 | 0.590062 | 4.181818 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/API/HTTP/HTTPMethod.swift | 1 | 417 | //
// HTTPMethod.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 12/12/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
enum HTTPMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case head = "HEAD"
case delete = "DELETE"
case patch = "PATCH"
case trace = "TRACE"
case options = "OPTIONS"
case connect = "CONNECT"
}
| mit | cf8addd018270457749097105aef75e5 | 18.809524 | 54 | 0.615385 | 3.409836 | false | false | false | false |
marko628/Playground | Answers.playgroundbook/Contents/Sources/PlaygroundInternal/DateInputCell.swift | 1 | 1118 | // DateInputCell.swift
import UIKit
class DateInputCell : PopoverInputCell {
private var dateFormatter = DateFormatter()
private let datePicker = UIDatePicker()
class override var reuseIdentifier: String {
return "DateInputCell"
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
valueType = .date
dateFormatter.dateStyle = .long
datePicker.datePickerMode = .date
datePicker.addTarget(self, action: #selector(DateInputCell.valueDidChange), for: .valueChanged)
datePicker.autoresizingMask = [.flexibleWidth, .flexibleHeight]
datePicker.frame = popoverViewController.view.bounds
popoverViewController.view.addSubview(datePicker)
popoverContentSize = datePicker.intrinsicContentSize
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func valueDidChange() {
messageText = dateFormatter.string(from: datePicker.date)
}
}
| mit | fe23f437c63ac6494589bd0e48820145 | 33.9375 | 103 | 0.698569 | 5.453659 | false | false | false | false |
taketo1024/SwiftyAlgebra | Sources/SwmCore/Util/Format.swift | 1 | 6979 | //
// Letters.swift
// SwiftyMath
//
// Created by Taketo Sano on 2018/03/10.
// Copyright © 2018年 Taketo Sano. All rights reserved.
//
// see: https://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts
public struct Format {
public static func sup(_ i: Int) -> String {
sup(String(i))
}
public static func sup(_ s: String) -> String {
String( s.map { c in
switch c {
case "0": return "⁰"
case "1": return "¹"
case "2": return "²"
case "3": return "³"
case "4": return "⁴"
case "5": return "⁵"
case "6": return "⁶"
case "7": return "⁷"
case "8": return "⁸"
case "9": return "⁹"
case "+": return "⁺"
case "-": return "⁻"
case "(": return "⁽"
case ")": return "⁾"
case ",": return " ̓"
default: return c
}
} )
}
public static func sub(_ i: Int) -> String {
sub(String(i))
}
public static func sub(_ s: String) -> String {
String( s.map { c in
switch c {
case "0": return "₀"
case "1": return "₁"
case "2": return "₂"
case "3": return "₃"
case "4": return "₄"
case "5": return "₅"
case "6": return "₆"
case "7": return "₇"
case "8": return "₈"
case "9": return "₉"
case "+": return "₊"
case "-": return "₋"
case "(": return "₍"
case ")": return "₎"
case ",": return " ̦"
case "*": return " ͙"
default: return c
}
} )
}
public static func symbol(_ x: String, _ i: Int) -> String {
"\(x)\(sub(i))"
}
public static func power<X: CustomStringConvertible>(_ x: X, _ n: Int) -> String {
let xStr = x.description
return n == 0 ? "1" : n == 1 ? xStr : "\(xStr)\(sup(n))"
}
public static func term<R: Ring, X: CustomStringConvertible>(_ r: R = .identity, _ x: X, _ n: Int = 0) -> String {
let p = power(x, n)
switch (r, p) {
case (.zero, _):
return "0"
case (_, "1"):
return "\(r)"
case (.identity, _):
return p
case (-.identity, _):
return "-\(p)"
default:
return "\(r)\(p)"
}
}
public static func linearCombination<S: Sequence, X: CustomStringConvertible, R: Ring>(_ terms: S) -> String where S.Element == (X, R) {
func parenthesize(_ x: String) -> Bool {
x.contains(" ")
}
let termsStr = terms.compactMap{ (x, a) -> String? in
let aStr = a.description
let xStr = x.description
switch (aStr, parenthesize(aStr), xStr, parenthesize(xStr)) {
case ("0", _, _, _):
return nil
case (_, _, "1", _):
return aStr
case ("1", _, _, _):
return xStr
case ("-1", _, _, false):
return "-\(xStr)"
case ("-1", _, _, true):
return "-(\(xStr))"
case (_, false, _, false):
return "\(aStr)\(xStr)"
case (_, true, _, false):
return "(\(aStr))\(xStr)"
default:
return "(\(aStr))(\(xStr))"
}
}
return termsStr.isEmpty
? "0"
: termsStr.reduce(into: "") { (str, next) in
if str.isEmpty {
str += next
} else if next.hasPrefix("-") {
str += " - \(next[1...])"
} else {
str += " + \(next)"
}
}
}
public static func table<S1, S2, T>(rows: S1, cols: S2, symbol: String = "", separator s: String = "\t", printHeaders: Bool = true, op: (S1.Element, S2.Element) -> T) -> String
where S1: Sequence, S2: Sequence {
let head = printHeaders ? [[symbol] + cols.map{ y in "\(y)" }] : []
let body = rows.enumerated().map { (i, x) -> [String] in
let head = printHeaders ? ["\(x)"] : []
let line = cols.enumerated().map { (j, y) in
"\(op(x, y))"
}
return head + line
}
return (head + body).map{ $0.joined(separator: s) }.joined(separator: "\n")
}
public static func table<S, T>(elements: S, default d: String = "", symbol: String = "j\\i", separator s: String = "\t", printHeaders: Bool = true) -> String
where S: Sequence, S.Element == (Int, Int, T) {
let dict = Dictionary(elements.map{ (i, j, t) in ([i, j], t) } )
if dict.isEmpty {
return "empty"
}
let I = dict.keys.map{ $0[0] }.uniqued().sorted()
let J = dict.keys.map{ $0[1] }.uniqued().sorted()
return Format.table(rows: J.reversed(),
cols: I,
symbol: symbol,
separator: s,
printHeaders: printHeaders)
{ (j, i) -> String in
dict[ [i, j] ].map{ "\($0)" } ?? d
}
}
public static func table<S, T>(elements: S, default d: String = "", symbol: String = "i", separator s: String = "\t", printHeaders: Bool = true) -> String
where S: Sequence, S.Element == (Int, T) {
let dict = Dictionary(elements)
if dict.isEmpty {
return "empty"
}
return Format.table(rows: [""],
cols: dict.keys.sorted(),
symbol: symbol,
separator: s,
printHeaders: printHeaders)
{ (_, i) -> String in
dict[i].map{ "\($0)" } ?? d
}
}
}
public extension AdditiveGroup {
static func printAddTable(values: [Self]) {
print( Format.table(rows: values, cols: values, symbol: "+") { $0 + $1 } )
}
}
public extension AdditiveGroup where Self: FiniteSet {
static func printAddTable() {
printAddTable(values: allElements)
}
}
public extension Monoid {
static func printMulTable(values: [Self]) {
print( Format.table(rows: values, cols: values, symbol: "*") { $0 * $1 } )
}
static func printExpTable(values: [Self], upTo n: Int) {
print( Format.table(rows: values, cols: Array(0 ... n), symbol: "^") { $0.pow($1) } )
}
}
public extension Monoid where Self: FiniteSet {
static func printMulTable() {
printMulTable(values: allElements)
}
static func printExpTable() {
let all = allElements
printExpTable(values: all, upTo: all.count - 1)
}
}
| cc0-1.0 | 376599b8682c24e4836e9ff855d01a2e | 31.336449 | 180 | 0.444942 | 3.892013 | false | false | false | false |
rnystrom/GitHawk | Classes/Issues/Comments/Details/IssueDetailBadgeView.swift | 1 | 1351 | //
// IssueDetailBadgeView.swift
// Freetime
//
// Created by Ryan Nystrom on 7/29/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import UIKit
final class IssueDetailBadgeView: UIImageView {
init() {
super.init(frame: .zero)
image = UIImage(named: "githawk-badge").withRenderingMode(.alwaysTemplate)
tintColor = Styles.Colors.Blue.medium.color
isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(
target: self,
action: #selector(ShowMoreDetailsLabel.showMenu(recognizer:))
)
addGestureRecognizer(tap)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var canBecomeFirstResponder: Bool {
return true
}
// MARK: Private API
@objc func showMenu(recognizer: UITapGestureRecognizer) {
becomeFirstResponder()
let menu = UIMenuController.shared
menu.menuItems = [
UIMenuItem(
title: NSLocalizedString("Sent with GitHawk", comment: ""),
action: #selector(IssueDetailBadgeView.empty)
)
]
menu.setTargetRect(bounds, in: self)
menu.setMenuVisible(true, animated: trueUnlessReduceMotionEnabled)
}
@objc func empty() {}
}
| mit | 1fed5a39b7601e981dfbf5e1e73226ab | 24.471698 | 82 | 0.62963 | 4.891304 | false | false | false | false |
daniel-barros/Comedores-UGR | Comedores UGR/LastUpdateTableViewCell.swift | 1 | 1784 | //
// LastUpdateTableViewCell.swift
// Comedores UGR
//
// Created by Daniel Barros López on 3/28/16.
/*
MIT License
Copyright (c) 2016 Daniel Barros
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
//
import UIKit
class LastUpdateTableViewCell: UITableViewCell {
@IBOutlet weak var label: UILabel!
func configure(with date: Date?) {
var string = NSLocalizedString("Last Update:") + " "
if let lastUpdate = date {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .short
formatter.doesRelativeDateFormatting = true
string += formatter.string(from: lastUpdate)
} else {
string += NSLocalizedString("Never")
}
label.text = string
}
}
| mit | 2506bf49f738b9c8372fe4b08bce87bf | 34.66 | 78 | 0.722378 | 4.754667 | false | false | false | false |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/ConversationV1/Models/UpdateWorkspace.swift | 2 | 4230 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/** UpdateWorkspace. */
public struct UpdateWorkspace: Encodable {
/// The name of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 64 characters.
public var name: String?
/// The description of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters.
public var description: String?
/// The language of the workspace.
public var language: String?
/// An array of objects defining the intents for the workspace.
public var intents: [CreateIntent]?
/// An array of objects defining the entities for the workspace.
public var entities: [CreateEntity]?
/// An array of objects defining the nodes in the workspace dialog.
public var dialogNodes: [CreateDialogNode]?
/// An array of objects defining input examples that have been marked as irrelevant input.
public var counterexamples: [CreateCounterexample]?
/// Any metadata related to the workspace.
public var metadata: [String: JSON]?
/// Whether training data from the workspace can be used by IBM for general service improvements. `true` indicates that workspace training data is not to be used.
public var learningOptOut: Bool?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case name = "name"
case description = "description"
case language = "language"
case intents = "intents"
case entities = "entities"
case dialogNodes = "dialog_nodes"
case counterexamples = "counterexamples"
case metadata = "metadata"
case learningOptOut = "learning_opt_out"
}
/**
Initialize a `UpdateWorkspace` with member variables.
- parameter name: The name of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 64 characters.
- parameter description: The description of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters.
- parameter language: The language of the workspace.
- parameter intents: An array of objects defining the intents for the workspace.
- parameter entities: An array of objects defining the entities for the workspace.
- parameter dialogNodes: An array of objects defining the nodes in the workspace dialog.
- parameter counterexamples: An array of objects defining input examples that have been marked as irrelevant input.
- parameter metadata: Any metadata related to the workspace.
- parameter learningOptOut: Whether training data from the workspace can be used by IBM for general service improvements. `true` indicates that workspace training data is not to be used.
- returns: An initialized `UpdateWorkspace`.
*/
public init(name: String? = nil, description: String? = nil, language: String? = nil, intents: [CreateIntent]? = nil, entities: [CreateEntity]? = nil, dialogNodes: [CreateDialogNode]? = nil, counterexamples: [CreateCounterexample]? = nil, metadata: [String: JSON]? = nil, learningOptOut: Bool? = nil) {
self.name = name
self.description = description
self.language = language
self.intents = intents
self.entities = entities
self.dialogNodes = dialogNodes
self.counterexamples = counterexamples
self.metadata = metadata
self.learningOptOut = learningOptOut
}
}
| mit | eaed8e08d4316756791a5a5d547a6008 | 46.52809 | 306 | 0.718203 | 4.823261 | false | false | false | false |
Bartlebys/Bartleby | Bartlebys.playground/Sources/PlaygroundsConfiguration.swift | 1 | 3330 | //
// TestsConfiguration.swift
// bsync
//
// Created by Benoit Pereira da silva on 29/12/2015.
// Copyright © 2015 Benoit Pereira da silva. All rights reserved.
//
import Alamofire
import BartlebyKit
// A shared configuration Model
open class PlaygroundsConfiguration: BartlebyConfiguration {
// The cryptographic key used to encrypt/decrypt the data
open static var KEY: String="UDJDJJDJJDJDJDJDJJDDJJDJDJJDJ-O9393972AA"
open static var SHARED_SALT: String="xyx38-d890x-899h-123e-30x6-3234e"
// To conform to crypto legal context
open static var KEY_SIZE: KeySize = .s128bits
//MARK: - URLS
static let trackAllApiCalls=true
open static var API_BASE_URL=__BASE_URL
// Bartleby Bprint
open static var ENABLE_GLOG: Bool=true
// Should Bprint entries be printed
public static var PRINT_GLOG_ENTRIES: Bool=true
// Use NoCrypto as CryptoDelegate (should be false)
open static var DISABLE_DATA_CRYPTO: Bool=false
//If set to true the created instances will be remove on maintenance Purge
open static var EPHEMERAL_MODE=true
//Should the app try to be online by default
open static var ONLINE_BY_DEFAULT=true
// Consignation
open static var API_CALL_TRACKING_IS_ENABLED: Bool=true
open static var BPRINT_API_TRACKED_CALLS: Bool=true
// Should the registries metadata be crypted on export (should be true)!
open static var CRYPTED_REGISTRIES_METADATA_EXPORT: Bool = true
// Should we save the password by Default ?
open static var SAVE_PASSWORD_DEFAULT_VALUE: Bool=false
// If set to JSON for example would be Indented
open static var HUMAN_FORMATTED_SERIALIZATON_FORMAT: Bool=false
// Supervision loop interval (1 second min )
open static var LOOP_TIME_INTERVAL_IN_SECONDS: Double = 1
// To guarantee the sequential Execution use 1
open static var MAX_OPERATIONS_BUNCH_SIZE: Int = 10
// The min password size
open static var MIN_PASSWORD_SIZE: UInt=6
// E.g : Default.DEFAULT_PASSWORD_CHAR_CART
open static var PASSWORD_CHAR_CART: String="ABCDEFGH1234567890"
// If set to true the keyed changes are stored in the ManagedModel - When opening the Inspector this default value is remplaced by true
public static var CHANGES_ARE_INSPECTABLES_BY_DEFAULT: Bool = false
//MARK: - Variable base URL
enum Environment {
case local
case development
case alternative
case production
}
static var currentEnvironment: Environment = .development
static fileprivate var __BASE_URL: URL {
get {
switch currentEnvironment {
case .local:
// On macOS you should point "yd.local" to your IP by editing /etc/host
return URL(string:"http://yd.local:8001/api/v1")!
case .development:
return URL(string:"https://dev.api.lylo.tv/api/v1")!
case .alternative:
return URL(string: "https://demo.bartlebys.org/www/api/v1")!
case .production:
return URL(string:"https://api.lylo.tv/api/v1")!
}
}
}
open static let TIME_OUT_DURATION = 10.0
open static let LONG_TIME_OUT_DURATION = 360.0
open static let ENABLE_TEST_OBSERVATION=true
}
| apache-2.0 | b392e45f6a22c999d9496fcab698c908 | 29.541284 | 139 | 0.676179 | 3.930342 | false | false | false | false |
khizkhiz/swift | test/SILGen/witnesses.swift | 1 | 29566 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module | FileCheck %s
infix operator <~> {}
func archetype_method<T: X>(x x: T, y: T) -> T {
var x = x
var y = y
return x.selfTypes(x: y)
}
// CHECK-LABEL: sil hidden @_TF9witnesses16archetype_method{{.*}} : $@convention(thin) <T where T : X> (@in T, @in T) -> @out T {
// CHECK: [[METHOD:%.*]] = witness_method $T, #X.selfTypes!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : X> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
// CHECK: apply [[METHOD]]<T>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : X> (@in τ_0_0, @inout τ_0_0) -> @out τ_0_0
// CHECK: }
func archetype_generic_method<T: X>(x x: T, y: Loadable) -> Loadable {
var x = x
return x.generic(x: y)
}
// CHECK-LABEL: sil hidden @_TF9witnesses24archetype_generic_method{{.*}} : $@convention(thin) <T where T : X> (@in T, Loadable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $T, #X.generic!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : X><τ_1_0> (@in τ_1_0, @inout τ_0_0) -> @out τ_1_0
// CHECK: apply [[METHOD]]<T, Loadable>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : X><τ_1_0> (@in τ_1_0, @inout τ_0_0) -> @out τ_1_0
// CHECK: }
// CHECK-LABEL: sil hidden @_TF9witnesses32archetype_associated_type_method{{.*}} : $@convention(thin) <T where T : WithAssoc> (@in T, @in T.AssocType) -> @out T
// CHECK: apply %{{[0-9]+}}<T, T.AssocType>
func archetype_associated_type_method<T: WithAssoc>(x x: T, y: T.AssocType) -> T {
return x.useAssocType(x: y)
}
protocol StaticMethod { static func staticMethod() }
// CHECK-LABEL: sil hidden @_TF9witnesses23archetype_static_method{{.*}} : $@convention(thin) <T where T : StaticMethod> (@in T) -> ()
func archetype_static_method<T: StaticMethod>(x x: T) {
// CHECK: [[METHOD:%.*]] = witness_method $T, #StaticMethod.staticMethod!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : StaticMethod> (@thick τ_0_0.Type) -> ()
// CHECK: apply [[METHOD]]<T>
T.staticMethod()
}
protocol Existentiable {
func foo() -> Loadable
func generic<T>() -> T
}
func protocol_method(x x: Existentiable) -> Loadable {
return x.foo()
}
// CHECK-LABEL: sil hidden @_TF9witnesses15protocol_methodFT1xPS_13Existentiable__VS_8Loadable : $@convention(thin) (@in Existentiable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.foo!1
// CHECK: apply [[METHOD]]<[[OPENED]]>({{%.*}})
// CHECK: }
func protocol_generic_method(x x: Existentiable) -> Loadable {
return x.generic()
}
// CHECK-LABEL: sil hidden @_TF9witnesses23protocol_generic_methodFT1xPS_13Existentiable__VS_8Loadable : $@convention(thin) (@in Existentiable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.generic!1
// CHECK: apply [[METHOD]]<[[OPENED]], Loadable>({{%.*}}, {{%.*}})
// CHECK: }
@objc protocol ObjCAble {
func foo()
}
// CHECK-LABEL: sil hidden @_TF9witnesses20protocol_objc_methodFT1xPS_8ObjCAble__T_ : $@convention(thin) (@owned ObjCAble) -> ()
// CHECK: witness_method [volatile] $@opened({{.*}}) ObjCAble, #ObjCAble.foo!1.foreign
func protocol_objc_method(x x: ObjCAble) {
x.foo()
}
struct Loadable {}
protocol AddrOnly {}
protocol Classes : class {}
protocol X {
mutating
func selfTypes(x x: Self) -> Self
mutating
func loadable(x x: Loadable) -> Loadable
mutating
func addrOnly(x x: AddrOnly) -> AddrOnly
mutating
func generic<A>(x x: A) -> A
mutating
func classes<A2: Classes>(x x: A2) -> A2
func <~>(x: Self, y: Self) -> Self
}
protocol Y {}
protocol WithAssoc {
associatedtype AssocType
func useAssocType(x x: AssocType) -> Self
}
protocol ClassBounded : class {
func selfTypes(x x: Self) -> Self
}
struct ConformingStruct : X {
mutating
func selfTypes(x x: ConformingStruct) -> ConformingStruct { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@in ConformingStruct, @inout ConformingStruct) -> @out ConformingStruct {
// CHECK: bb0(%0 : $*ConformingStruct, %1 : $*ConformingStruct, %2 : $*ConformingStruct):
// CHECK-NEXT: %3 = load %1 : $*ConformingStruct
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %4 = function_ref @_TFV9witnesses16ConformingStruct9selfTypes{{.*}} : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct
// CHECK-NEXT: %5 = apply %4(%3, %2) : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct
// CHECK-NEXT: store %5 to %0 : $*ConformingStruct
// CHECK-NEXT: %7 = tuple ()
// CHECK-NEXT: return %7 : $()
// CHECK-NEXT: }
mutating
func loadable(x x: Loadable) -> Loadable { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_8loadable{{.*}} : $@convention(witness_method) (Loadable, @inout ConformingStruct) -> Loadable {
// CHECK: bb0(%0 : $Loadable, %1 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %2 = function_ref @_TFV9witnesses16ConformingStruct8loadable{{.*}} : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable
// CHECK-NEXT: %3 = apply %2(%0, %1) : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable
// CHECK-NEXT: return %3 : $Loadable
// CHECK-NEXT: }
mutating
func addrOnly(x x: AddrOnly) -> AddrOnly { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_8addrOnly{{.*}} : $@convention(witness_method) (@in AddrOnly, @inout ConformingStruct) -> @out AddrOnly {
// CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses16ConformingStruct8addrOnly{{.*}} : $@convention(method) (@in AddrOnly, @inout ConformingStruct) -> @out AddrOnly
// CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@in AddrOnly, @inout ConformingStruct) -> @out AddrOnly
// CHECK-NEXT: %5 = tuple ()
// CHECK-NEXT: return %5 : $()
// CHECK-NEXT: }
mutating
func generic<C>(x x: C) -> C { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_7generic{{.*}} : $@convention(witness_method) <A> (@in A, @inout ConformingStruct) -> @out A {
// CHECK: bb0(%0 : $*A, %1 : $*A, %2 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses16ConformingStruct7generic{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformingStruct) -> @out τ_0_0
// CHECK-NEXT: %4 = apply %3<A>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformingStruct) -> @out τ_0_0
// CHECK-NEXT: %5 = tuple ()
// CHECK-NEXT: return %5 : $()
// CHECK-NEXT: }
mutating
func classes<C2: Classes>(x x: C2) -> C2 { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_7classes{{.*}} : $@convention(witness_method) <A2 where A2 : Classes> (@owned A2, @inout ConformingStruct) -> @owned A2 {
// CHECK: bb0(%0 : $A2, %1 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %2 = function_ref @_TFV9witnesses16ConformingStruct7classes{{.*}} : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0
// CHECK-NEXT: %3 = apply %2<A2>(%0, %1) : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0
// CHECK-NEXT: return %3 : $A2
// CHECK-NEXT: }
}
func <~>(x: ConformingStruct, y: ConformingStruct) -> ConformingStruct { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> @out ConformingStruct {
// CHECK: bb0(%0 : $*ConformingStruct, %1 : $*ConformingStruct, %2 : $*ConformingStruct, %3 : $@thick ConformingStruct.Type):
// CHECK-NEXT: %4 = load %1 : $*ConformingStruct
// CHECK-NEXT: %5 = load %2 : $*ConformingStruct
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %6 = function_ref @_TZF9witnessesoi3ltgFTVS_16ConformingStructS0__S0_ : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct
// CHECK-NEXT: %7 = apply %6(%4, %5) : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct
// CHECK-NEXT: store %7 to %0 : $*ConformingStruct
// CHECK-NEXT: %9 = tuple ()
// CHECK-NEXT: return %9 : $()
// CHECK-NEXT: }
final class ConformingClass : X {
func selfTypes(x x: ConformingClass) -> ConformingClass { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses15ConformingClassS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@in ConformingClass, @inout ConformingClass) -> @out ConformingClass {
// CHECK: bb0(%0 : $*ConformingClass, %1 : $*ConformingClass, %2 : $*ConformingClass):
// -- load and retain 'self' from inout witness 'self' parameter
// CHECK-NEXT: %3 = load %2 : $*ConformingClass
// CHECK-NEXT: strong_retain %3 : $ConformingClass
// CHECK-NEXT: %5 = load %1 : $*ConformingClass
// CHECK: %6 = function_ref @_TFC9witnesses15ConformingClass9selfTypes
// CHECK-NEXT: %7 = apply %6(%5, %3) : $@convention(method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass
// CHECK-NEXT: store %7 to %0 : $*ConformingClass
// CHECK-NEXT: %9 = tuple ()
// CHECK-NEXT: strong_release %3
// CHECK-NEXT: return %9 : $()
// CHECK-NEXT: }
func loadable(x x: Loadable) -> Loadable { return x }
func addrOnly(x x: AddrOnly) -> AddrOnly { return x }
func generic<D>(x x: D) -> D { return x }
func classes<D2: Classes>(x x: D2) -> D2 { return x }
}
func <~>(x: ConformingClass, y: ConformingClass) -> ConformingClass { return x }
extension ConformingClass : ClassBounded { }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses15ConformingClassS_12ClassBoundedS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass {
// CHECK: bb0([[C0:%.*]] : $ConformingClass, [[C1:%.*]] : $ConformingClass):
// CHECK-NEXT: strong_retain [[C1]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @_TFC9witnesses15ConformingClass9selfTypes
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[C0]], [[C1]]) : $@convention(method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass
// CHECK-NEXT: strong_release [[C1]]
// CHECK-NEXT: return [[RESULT]] : $ConformingClass
// CHECK-NEXT: }
struct ConformingAOStruct : X {
var makeMeAO : AddrOnly
mutating
func selfTypes(x x: ConformingAOStruct) -> ConformingAOStruct { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses18ConformingAOStructS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@in ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct {
// CHECK: bb0(%0 : $*ConformingAOStruct, %1 : $*ConformingAOStruct, %2 : $*ConformingAOStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses18ConformingAOStruct9selfTypes{{.*}} : $@convention(method) (@in ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct
// CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@in ConformingAOStruct, @inout ConformingAOStruct) -> @out ConformingAOStruct
// CHECK-NEXT: %5 = tuple ()
// CHECK-NEXT: return %5 : $()
// CHECK-NEXT: }
func loadable(x x: Loadable) -> Loadable { return x }
func addrOnly(x x: AddrOnly) -> AddrOnly { return x }
func generic<D>(x x: D) -> D { return x }
func classes<D2: Classes>(x x: D2) -> D2 { return x }
}
func <~>(x: ConformingAOStruct, y: ConformingAOStruct) -> ConformingAOStruct { return x }
struct ConformsWithMoreGeneric : X, Y {
mutating
func selfTypes<E>(x x: E) -> E { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@in ConformsWithMoreGeneric, @inout ConformsWithMoreGeneric) -> @out ConformsWithMoreGeneric {
// CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_TFV9witnesses23ConformsWithMoreGeneric9selfTypes{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<ConformsWithMoreGeneric>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
func loadable<F>(x x: F) -> F { return x }
mutating
func addrOnly<G>(x x: G) -> G { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_8addrOnly{{.*}} : $@convention(witness_method) (@in AddrOnly, @inout ConformsWithMoreGeneric) -> @out AddrOnly {
// CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses23ConformsWithMoreGeneric8addrOnly{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: %4 = apply %3<AddrOnly>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
mutating
func generic<H>(x x: H) -> H { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_7generic{{.*}} : $@convention(witness_method) <A> (@in A, @inout ConformsWithMoreGeneric) -> @out A {
// CHECK: bb0(%0 : $*A, %1 : $*A, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses23ConformsWithMoreGeneric7generic{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: %4 = apply %3<A>(%0, %1, %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
mutating
func classes<I>(x x: I) -> I { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_7classes{{.*}} : $@convention(witness_method) <A2 where A2 : Classes> (@owned A2, @inout ConformsWithMoreGeneric) -> @owned A2 {
// CHECK: bb0(%0 : $A2, %1 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $A2
// CHECK-NEXT: store %0 to [[SELF_BOX]] : $*A2
// CHECK-NEXT: // function_ref witnesses.ConformsWithMoreGeneric.classes
// CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_TFV9witnesses23ConformsWithMoreGeneric7classes{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT_BOX:%.*]] = alloc_stack $A2
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<A2>([[RESULT_BOX]], [[SELF_BOX]], %1) : $@convention(method) <τ_0_0> (@in τ_0_0, @inout ConformsWithMoreGeneric) -> @out τ_0_0
// CHECK-NEXT: [[RESULT:%.*]] = load [[RESULT_BOX]] : $*A2
// CHECK-NEXT: dealloc_stack [[RESULT_BOX]] : $*A2
// CHECK-NEXT: dealloc_stack [[SELF_BOX]] : $*A2
// CHECK-NEXT: return [[RESULT]] : $A2
// CHECK-NEXT: }
}
func <~> <J: Y, K: Y>(x: J, y: K) -> K { return y }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformsWithMoreGeneric, @in ConformsWithMoreGeneric, @thick ConformsWithMoreGeneric.Type) -> @out ConformsWithMoreGeneric {
// CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric, %3 : $@thick ConformsWithMoreGeneric.Type):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_TZF9witnessesoi3ltg{{.*}} : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@in τ_0_0, @in τ_0_1) -> @out τ_0_1
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<ConformsWithMoreGeneric, ConformsWithMoreGeneric>(%0, %1, %2) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@in τ_0_0, @in τ_0_1) -> @out τ_0_1
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
protocol LabeledRequirement {
func method(x x: Loadable)
}
struct UnlabeledWitness : LabeledRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16UnlabeledWitnessS_18LabeledRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (Loadable, @in_guaranteed UnlabeledWitness) -> ()
func method(x _: Loadable) {}
}
protocol LabeledSelfRequirement {
func method(x x: Self)
}
struct UnlabeledSelfWitness : LabeledSelfRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses20UnlabeledSelfWitnessS_22LabeledSelfRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (@in UnlabeledSelfWitness, @in_guaranteed UnlabeledSelfWitness) -> ()
func method(x _: UnlabeledSelfWitness) {}
}
protocol UnlabeledRequirement {
func method(x _: Loadable)
}
struct LabeledWitness : UnlabeledRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses14LabeledWitnessS_20UnlabeledRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (Loadable, @in_guaranteed LabeledWitness) -> ()
func method(x x: Loadable) {}
}
protocol UnlabeledSelfRequirement {
func method(_: Self)
}
struct LabeledSelfWitness : UnlabeledSelfRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses18LabeledSelfWitnessS_24UnlabeledSelfRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (@in LabeledSelfWitness, @in_guaranteed LabeledSelfWitness) -> ()
func method(x: LabeledSelfWitness) {}
}
protocol ReadOnlyRequirement {
var prop: String { get }
static var prop: String { get }
}
struct ImmutableModel: ReadOnlyRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses14ImmutableModelS_19ReadOnlyRequirementS_FS1_g4propSS : $@convention(witness_method) (@in_guaranteed ImmutableModel) -> @owned String
let prop: String = "a"
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses14ImmutableModelS_19ReadOnlyRequirementS_ZFS1_g4propSS : $@convention(witness_method) (@thick ImmutableModel.Type) -> @owned String
static let prop: String = "b"
}
protocol FailableRequirement {
init?(foo: Int)
}
protocol NonFailableRefinement: FailableRequirement {
init(foo: Int)
}
protocol IUOFailableRequirement {
init!(foo: Int)
}
struct NonFailableModel: FailableRequirement, NonFailableRefinement, IUOFailableRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16NonFailableModelS_19FailableRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableModel.Type) -> @out Optional<NonFailableModel>
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16NonFailableModelS_21NonFailableRefinementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableModel.Type) -> @out NonFailableModel
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16NonFailableModelS_22IUOFailableRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableModel.Type) -> @out ImplicitlyUnwrappedOptional<NonFailableModel>
init(foo: Int) {}
}
struct FailableModel: FailableRequirement, IUOFailableRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses13FailableModelS_19FailableRequirementS_FS1_C{{.*}}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses13FailableModelS_22IUOFailableRequirementS_FS1_C{{.*}}
// CHECK: bb0([[SELF:%[0-9]+]] : $*ImplicitlyUnwrappedOptional<FailableModel>, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick FailableModel.Type):
// CHECK: [[FN:%.*]] = function_ref @_TFV9witnesses13FailableModelC{{.*}}
// CHECK: [[INNER:%.*]] = apply [[FN]](
// CHECK: [[OUTER:%.*]] = unchecked_trivial_bit_cast [[INNER]] : $Optional<FailableModel> to $ImplicitlyUnwrappedOptional<FailableModel>
// CHECK: store [[OUTER]] to %0
// CHECK: return
init?(foo: Int) {}
}
struct IUOFailableModel : NonFailableRefinement, IUOFailableRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16IUOFailableModelS_21NonFailableRefinementS_FS1_C{{.*}}
// CHECK: bb0([[SELF:%[0-9]+]] : $*IUOFailableModel, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick IUOFailableModel.Type):
// CHECK: [[META:%[0-9]+]] = metatype $@thin IUOFailableModel.Type
// CHECK: [[INIT:%[0-9]+]] = function_ref @_TFV9witnesses16IUOFailableModelC{{.*}} : $@convention(thin) (Int, @thin IUOFailableModel.Type) -> ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: [[IUO_RESULT:%[0-9]+]] = apply [[INIT]]([[FOO]], [[META]]) : $@convention(thin) (Int, @thin IUOFailableModel.Type) -> ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: [[IUO_RESULT_TEMP:%[0-9]+]] = alloc_stack $ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: store [[IUO_RESULT]] to [[IUO_RESULT_TEMP]] : $*ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: [[FORCE_FN:%[0-9]+]] = function_ref @_TFs45_stdlib_ImplicitlyUnwrappedOptional_unwrappedurFGSQx_x{{.*}} : $@convention(thin) <τ_0_0> (@in ImplicitlyUnwrappedOptional<τ_0_0>) -> @out τ_0_0
// CHECK: [[RESULT_TEMP:%[0-9]+]] = alloc_stack $IUOFailableModel
// CHECK: apply [[FORCE_FN]]<IUOFailableModel>([[RESULT_TEMP]], [[IUO_RESULT_TEMP]]) : $@convention(thin) <τ_0_0> (@in ImplicitlyUnwrappedOptional<τ_0_0>) -> @out τ_0_0
// CHECK: [[RESULT:%[0-9]+]] = load [[RESULT_TEMP]] : $*IUOFailableModel
// CHECK: store [[RESULT]] to [[SELF]] : $*IUOFailableModel
// CHECK: dealloc_stack [[RESULT_TEMP]] : $*IUOFailableModel
// CHECK: dealloc_stack [[IUO_RESULT_TEMP]] : $*ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: return
init!(foo: Int) { return nil }
}
protocol FailableClassRequirement: class {
init?(foo: Int)
}
protocol NonFailableClassRefinement: FailableClassRequirement {
init(foo: Int)
}
protocol IUOFailableClassRequirement: class {
init!(foo: Int)
}
final class NonFailableClassModel: FailableClassRequirement, NonFailableClassRefinement, IUOFailableClassRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21NonFailableClassModelS_24FailableClassRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned Optional<NonFailableClassModel>
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21NonFailableClassModelS_26NonFailableClassRefinementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned NonFailableClassModel
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21NonFailableClassModelS_27IUOFailableClassRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned ImplicitlyUnwrappedOptional<NonFailableClassModel>
init(foo: Int) {}
}
final class FailableClassModel: FailableClassRequirement, IUOFailableClassRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses18FailableClassModelS_24FailableClassRequirementS_FS1_C{{.*}}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses18FailableClassModelS_27IUOFailableClassRequirementS_FS1_C{{.*}}
// CHECK: [[FUNC:%.*]] = function_ref @_TFC9witnesses18FailableClassModelC{{.*}}
// CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1)
// CHECK: [[OUTER:%.*]] = unchecked_ref_cast [[INNER]] : $Optional<FailableClassModel> to $ImplicitlyUnwrappedOptional<FailableClassModel>
// CHECK: return [[OUTER]] : $ImplicitlyUnwrappedOptional<FailableClassModel>
init?(foo: Int) {}
}
final class IUOFailableClassModel: NonFailableClassRefinement, IUOFailableClassRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21IUOFailableClassModelS_26NonFailableClassRefinementS_FS1_C{{.*}}
// CHECK: function_ref @_TFs45_stdlib_ImplicitlyUnwrappedOptional_unwrappedurFGSQx_x
// CHECK: return [[RESULT:%[0-9]+]] : $IUOFailableClassModel
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21IUOFailableClassModelS_27IUOFailableClassRequirementS_FS1_C{{.*}}
init!(foo: Int) {}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21IUOFailableClassModelS_24FailableClassRequirementS_FS1_C{{.*}}
// CHECK: [[FUNC:%.*]] = function_ref @_TFC9witnesses21IUOFailableClassModelC{{.*}}
// CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1)
// CHECK: [[OUTER:%.*]] = unchecked_ref_cast [[INNER]] : $ImplicitlyUnwrappedOptional<IUOFailableClassModel> to $Optional<IUOFailableClassModel>
// CHECK: return [[OUTER]] : $Optional<IUOFailableClassModel>
}
protocol HasAssoc {
associatedtype Assoc
}
protocol GenericParameterNameCollisionProtocol {
func foo<T>(x: T)
associatedtype Assoc2
func bar<T>(x: T -> Assoc2)
}
struct GenericParameterNameCollision<T: HasAssoc> :
GenericParameterNameCollisionProtocol {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTW{{.*}}GenericParameterNameCollision{{.*}}GenericParameterNameCollisionProtocol{{.*}}foo{{.*}} : $@convention(witness_method) <T1 where T1 : HasAssoc><T> (@in T, @in_guaranteed GenericParameterNameCollision<T1>) -> () {
// CHECK: bb0(%0 : $*T, %1 : $*GenericParameterNameCollision<T1>):
// CHECK: apply {{%.*}}<T1, T1.Assoc, T>
func foo<U>(x: U) {}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTW{{.*}}GenericParameterNameCollision{{.*}}GenericParameterNameCollisionProtocol{{.*}}bar{{.*}} : $@convention(witness_method) <T1 where T1 : HasAssoc><T> (@owned @callee_owned (@in T) -> @out T1.Assoc, @in_guaranteed GenericParameterNameCollision<T1>) -> () {
// CHECK: bb0(%0 : $@callee_owned (@in T) -> @out T1.Assoc, %1 : $*GenericParameterNameCollision<T1>):
// CHECK: apply {{%.*}}<T1, T1.Assoc, T>
func bar<V>(x: V -> T.Assoc) {}
}
protocol PropertyRequirement {
var width: Int { get set }
static var height: Int { get set }
var depth: Int { get set }
}
class PropertyRequirementBase {
var width: Int = 12
static var height: Int = 13
}
class PropertyRequirementWitnessFromBase : PropertyRequirementBase, PropertyRequirement {
var depth: Int = 14
// Make sure the contravariant return type in materializeForSet works correctly
// If the witness is in a base class of the conforming class, make sure we have a bit_cast in there:
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses34PropertyRequirementWitnessFromBaseS_19PropertyRequirementS_FS1_m5widthSi : {{.*}} {
// CHECK: upcast
// CHECK-NEXT: [[METH:%.*]] = class_method {{%.*}} : $PropertyRequirementBase, #PropertyRequirementBase.width!materializeForSet.1
// CHECK-NEXT: [[RES:%.*]] = apply [[METH]]
// CHECK-NEXT: [[CAR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 0
// CHECK-NEXT: [[CADR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 1
// CHECK-NEXT: [[CAST:%.*]] = unchecked_trivial_bit_cast [[CADR]]
// CHECK-NEXT: [[TUPLE:%.*]] = tuple ([[CAR]] : {{.*}}, [[CAST]] : {{.*}})
// CHECK-NEXT: strong_release
// CHECK-NEXT: return [[TUPLE]]
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses34PropertyRequirementWitnessFromBaseS_19PropertyRequirementS_ZFS1_m6heightSi : {{.*}} {
// CHECK: [[OBJ:%.*]] = upcast %2 : $@thick PropertyRequirementWitnessFromBase.Type to $@thick PropertyRequirementBase.Type
// CHECK: [[METH:%.*]] = function_ref @_TZFC9witnesses23PropertyRequirementBasem6heightSi
// CHECK-NEXT: [[RES:%.*]] = apply [[METH]]
// CHECK-NEXT: [[CAR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 0
// CHECK-NEXT: [[CADR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 1
// CHECK-NEXT: [[CAST:%.*]] = unchecked_trivial_bit_cast [[CADR]]
// CHECK-NEXT: [[TUPLE:%.*]] = tuple ([[CAR]] : {{.*}}, [[CAST]] : {{.*}})
// CHECK-NEXT: return [[TUPLE]]
// Otherwise, we shouldn't need the bit_cast:
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses34PropertyRequirementWitnessFromBaseS_19PropertyRequirementS_FS1_m5depthSi
// CHECK: [[METH:%.*]] = class_method {{%.*}} : $PropertyRequirementWitnessFromBase, #PropertyRequirementWitnessFromBase.depth!materializeForSet.1
// CHECK-NEXT: [[RES:%.*]] = apply [[METH]]
// CHECK-NEXT: tuple_extract
// CHECK-NEXT: tuple_extract
// CHECK-NEXT: [[RES:%.*]] = tuple
// CHECK-NEXT: strong_release
// CHECK-NEXT: return [[RES]]
}
| apache-2.0 | 12a1b7f6313ee056b9bf2483da442de1 | 58.321932 | 314 | 0.668792 | 3.358738 | false | false | false | false |
tkremenek/swift | test/IRGen/dllexport.swift | 21 | 2598 | // RUN: %swift -target thumbv7--windows-itanium -emit-ir -parse-as-library -disable-legacy-type-info -parse-stdlib -module-name dllexport %s -o - | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-NO-OPT
// RUN: %swift -target thumbv7--windows-itanium -O -emit-ir -parse-as-library -disable-legacy-type-info -parse-stdlib -module-name dllexport %s -o - | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-OPT
// REQUIRES: CODEGENERATOR=ARM
enum Never {}
@_silgen_name("_swift_fatalError")
func fatalError() -> Never
public protocol p {
func f()
}
open class c {
public init() { }
}
public var ci : c = c()
open class d {
private func m() -> Never {
fatalError()
}
}
// CHECK-DAG: @"$s9dllexport2ciAA1cCvp" = dllexport global %T9dllexport1cC* null, align 4
// CHECK-DAG: @"$s9dllexport1pMp" = dllexport constant
// CHECK-DAG: @"$s9dllexport1cCMn" = dllexport constant
// CHECK-DAG: @"$s9dllexport1cCN" = dllexport alias %swift.type
// CHECK-DAG: @"$s9dllexport1dCN" = dllexport alias %swift.type, bitcast ({{.*}})
// CHECK-DAG-OPT: @"$s9dllexport1dC1m33_C57BA610BA35E21738CC992438E660E9LLyyF" = dllexport alias void (), void ()* @_swift_dead_method_stub
// CHECK-DAG-OPT: @"$s9dllexport1dCACycfc" = dllexport alias void (), void ()* @_swift_dead_method_stub
// CHECK-DAG-OPT: @"$s9dllexport1cCACycfc" = dllexport alias void (), void ()* @_swift_dead_method_stub
// CHECK-DAG-OPT: @"$s9dllexport1cCACycfC" = dllexport alias void (), void ()* @_swift_dead_method_stub
// CHECK-DAG: define dllexport swiftcc %swift.refcounted* @"$s9dllexport1cCfd"(%T9dllexport1cC*{{.*}})
// CHECK-DAG-NO-OPT: define dllexport swiftcc %T9dllexport1cC* @"$s9dllexport1cCACycfc"(%T9dllexport1cC* %0)
// CHECK-DAG-NO-OPT: define dllexport swiftcc %T9dllexport1cC* @"$s9dllexport1cCACycfC"(%swift.type* %0)
// CHECK-DAG: define dllexport swiftcc i8* @"$s9dllexport2ciAA1cCvau"()
// CHECK-DAG-NO-OPT: define dllexport swiftcc void @"$s9dllexport1dC1m33_C57BA610BA35E21738CC992438E660E9LLyyF"(%T9dllexport1dC* %0)
// CHECK-DAG-NO-OPT: define dllexport swiftcc void @"$s9dllexport1dCfD"(%T9dllexport1dC* %0)
// CHECK-DAG: define dllexport swiftcc %swift.refcounted* @"$s9dllexport1dCfd"(%T9dllexport1dC*{{.*}})
// CHECK-DAG: define dllexport swiftcc %swift.metadata_response @"$s9dllexport1cCMa"(i32 %0)
// CHECK-DAG: define dllexport swiftcc %swift.metadata_response @"$s9dllexport1dCMa"(i32 %0)
// CHECK-DAG-NO-OPT: define dllexport swiftcc %T9dllexport1dC* @"$s9dllexport1dCACycfc"(%T9dllexport1dC* %0)
// CHECK-DAG-OPT: define dllexport swiftcc void @"$s9dllexport1dCfD"(%T9dllexport1dC* %0)
| apache-2.0 | 048df97e9f929d2e9276a3cd659ae832 | 54.276596 | 208 | 0.726328 | 3.122596 | false | false | false | false |
maxsokolov/Leeloo | Sources/NetworkClient.swift | 1 | 7034 | //
// Copyright (c) 2017 Max Sokolov https://twitter.com/max_sokolov
//
// 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 Alamofire
public typealias HttpMethod = HTTPMethod
extension Request: NetworkRequestTask {}
open class NetworkClient {
public let session: SessionManager
private let defaultBehaviors: [NetworkRequestBehavior]
public init(
configuration: URLSessionConfiguration = URLSessionConfiguration.default,
defaultBehaviors: [NetworkRequestBehavior] = [])
{
self.session = SessionManager(configuration: configuration)
self.defaultBehaviors = defaultBehaviors
}
// MARK: - Send methods
open func sendMultipart<R: NetworkMultipartDataRequest, T>(
request: R,
behaviors: [NetworkRequestBehavior] = [],
completion: ((_ result: NetworkRequestResult<T>) -> ())?)
where R.Response == T
{
let requestBehaviors = [defaultBehaviors, behaviors].reduce([], +)
session.upload(
multipartFormData: { multipartFormData in
if let parameters = request.parameters {
for (key, value) in parameters {
if let data = "\(value)".data(using: .utf8) {
multipartFormData.append(data, withName: key)
}
}
}
request.files.forEach {
switch $0.source {
case .data(let data):
multipartFormData.append(
data,
withName: $0.fileName,
fileName: $0.fileName,
mimeType: $0.mimeType
)
case .file(let url):
multipartFormData.append(
url,
withName: $0.fileName,
fileName: $0.fileName,
mimeType: $0.mimeType
)
}
}
},
to: request.endpoint + request.path,
method: request.method,
headers: getHeaders(forRequest: request, requestBehaviors: requestBehaviors),
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload
.uploadProgress { progress in // main queue by default
}
.responseObject(
networkRequest: request,
requestBehaviors: [],
completionHandler: { response in
switch response.result {
case .success(let value):
completion?(.value(value))
case .failure(let error):
if let requestError = error as? NetworkRequestError {
completion?(.error(requestError))
} else {
completion?(.error(NetworkRequestError.connectionError(error: error)))
}
}
}
)
case .failure(let encodingError):
print(encodingError)
}
}
)
}
@discardableResult
open func send<R: NetworkRequest, T>(
request: R,
behaviors: [NetworkRequestBehavior] = [],
completion: ((_ result: NetworkRequestResult<T>) -> ())?)
-> NetworkRequestTask? where R.Response == T
{
guard let baseUrl = try? request.endpoint.asURL() else { return nil }
let urlString = baseUrl.appendingPathComponent(request.path).absoluteString
let requestBehaviors = [defaultBehaviors, behaviors].reduce([], +)
// before send hook
requestBehaviors.forEach({ $0.willSend() })
return session
.request(
urlString,
method: request.method,
parameters: request.parameters,
encoding: JSONEncoding.default,
headers: getHeaders(forRequest: request, requestBehaviors: requestBehaviors)
)
.responseObject(
networkRequest: request,
requestBehaviors: requestBehaviors
) { (response) in
switch response.result {
case .success(let value):
completion?(.value(value))
case .failure(let error):
print(error)
if let requestError = error as? NetworkRequestError {
completion?(.error(requestError))
} else {
completion?(.error(NetworkRequestError.connectionError(error: error)))
}
}
}
}
// MARK: - Private
private func getHeaders<R: NetworkRequest>(
forRequest request: R,
requestBehaviors: [NetworkRequestBehavior])
-> [String: String]
{
// combine additional headers from behaviors
let headers = requestBehaviors.map({ $0.additionalHeaders }).reduce([], +)
var additionalHeaders: [String: String] = [:]
for item in headers {
additionalHeaders.updateValue(item.1, forKey: item.0)
}
return additionalHeaders
}
}
| mit | 2f699719677c61dc9da66ad992878c47 | 38.965909 | 110 | 0.507961 | 6.175593 | false | false | false | false |
CodeDrunkard/Algorithm | Algorithm.playground/Pages/Tree.xcplaygroundpage/Contents.swift | 1 | 2280 | /*:
Tree
*/
public class TreeNode<T> {
public var value: T
public weak var parent: TreeNode?
public var children = [TreeNode]()
public init(_ value: T) {
self.value = value
}
public var isRoot: Bool {
return parent == nil
}
public var depth: Int {
var d = 0
var p = parent
while p != nil {
d += 1
p = p!.parent
}
return d
}
public func addChild(_ node: TreeNode) {
children.append(node)
node.parent = self
}
}
extension TreeNode: CustomStringConvertible {
public var description: String {
var str = "\(value)"
if !children.isEmpty {
str += " {" + children.map { $0.description }.joined(separator: ", ") + "} "
}
return str
}
}
extension TreeNode where T: Equatable {
public func search(_ value: T) -> TreeNode? {
if value == self.value {
return self
}
for child in children {
if let found = child.search(value) {
return found
}
}
return nil
}
}
//: TEST
let tree = TreeNode<String>("beverages")
let hotNode = TreeNode<String>("hot")
let coldNode = TreeNode<String>("cold")
let teaNode = TreeNode<String>("tea")
let coffeeNode = TreeNode<String>("coffee")
let chocolateNode = TreeNode<String>("cocoa")
let blackTeaNode = TreeNode<String>("black")
let greenTeaNode = TreeNode<String>("green")
let chaiTeaNode = TreeNode<String>("chai")
let sodaNode = TreeNode<String>("soda")
let milkNode = TreeNode<String>("milk")
let gingerAleNode = TreeNode<String>("ginger ale")
let bitterLemonNode = TreeNode<String>("bitter lemon")
tree.addChild(hotNode)
tree.addChild(coldNode)
hotNode.addChild(teaNode)
hotNode.addChild(coffeeNode)
hotNode.addChild(chocolateNode)
coldNode.addChild(sodaNode)
coldNode.addChild(milkNode)
teaNode.addChild(blackTeaNode)
teaNode.addChild(greenTeaNode)
teaNode.addChild(chaiTeaNode)
sodaNode.addChild(gingerAleNode)
sodaNode.addChild(bitterLemonNode)
tree
tree.search("cocoa")
tree.search("chai")
tree.search("bubbly")
tree.depth
hotNode.depth
teaNode.depth
//: [Contents](Contents) | [Previous](@previous) | [Next](@next)
| mit | 02d53c067c0c81df61c84fa2f42d8864 | 21.135922 | 88 | 0.622807 | 3.68932 | false | false | false | false |
devpunk/velvet_room | Source/Model/Vita/MVitaPtpEvent.swift | 1 | 527 | enum MVitaPtpEvent:UInt16
{
case unknown
case sendItemsCount = 49412
case sendItemsMetadata = 49413
case sendItem = 49415
case requestItemStatus = 49423
case sendItemThumbnail = 49424
case requestSettings = 49426
case sendStorageSize = 49433
case requestItemTreat = 49442
case terminate = 49446
case itemPropertyChanged = 51201
}
| mit | 464d1dbb1a2cdbaf1e2f0da5603f50d1 | 36.642857 | 47 | 0.514231 | 5.27 | false | false | false | false |
garygriswold/Bible.js | Plugins/AWS/src/ios/OBSOLETE/AWS.swift | 2 | 8637 | //
// AWS.swift
// AWS
//
// Created by Gary Griswold on 5/15/17.
// Copyright © 2017 ShortSands. All rights reserved.
//
/**
* This class is the cordova native interface code that calls the AwsS3.
* It is a thin wrapper around the AwsS3 class that AwsS3 can also
* be used directly by other .swift classes.
*/
//import AWS used for AWS.framework
@objc(AWS) class AWS : CDVPlugin {
@objc(initializeRegion:)
func initializeRegion(command: CDVInvokedUrlCommand) {
let manager = AwsS3Manager.getSingleton()
let result = CDVPluginResult(status: CDVCommandStatus_OK)
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
@objc(echo2:)
func echo2(command: CDVInvokedUrlCommand) {
let message = command.arguments[0] as? String ?? ""
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: message)
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
@objc(echo3:)
func echo3(command: CDVInvokedUrlCommand) {
let message = command.arguments[0] as? String ?? ""
let response = AwsS3Manager.findSS().echo3(message: message);
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: response)
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
@objc(preSignedUrlGET:)
func preSignedUrlGET(command: CDVInvokedUrlCommand) {
AwsS3Manager.findSS().preSignedUrlGET(
s3Bucket: command.arguments[0] as? String ?? "",
s3Key: command.arguments[1] as? String ?? "",
expires: command.arguments[2] as? Int ?? 3600,
complete: { url in
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: url?.absoluteString)
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
)
}
@objc(preSignedUrlPUT:)
func preSignedUrlPUT(command: CDVInvokedUrlCommand) {
AwsS3Manager.findSS().preSignedUrlPUT(
s3Bucket: command.arguments[0] as? String ?? "",
s3Key: command.arguments[1] as? String ?? "",
expires: command.arguments[2] as? Int ?? 3600,
contentType: command.arguments[3] as? String ?? "",
complete: { url in
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: url?.absoluteString)
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
)
}
@objc(downloadText:)
func downloadText(command: CDVInvokedUrlCommand) {
AwsS3Manager.findSS().downloadText(
s3Bucket: command.arguments[0] as? String ?? "",
s3Key: command.arguments[1] as? String ?? "",
complete: { error, data in
var result: CDVPluginResult
if let err = error {
result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription)
} else {
result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: data)
}
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
)
}
@objc(downloadData:)
func downloadData(command: CDVInvokedUrlCommand) {
AwsS3Manager.findSS().downloadData(
s3Bucket: command.arguments[0] as? String ?? "",
s3Key: command.arguments[1] as? String ?? "",
complete: { error, data in
var result: CDVPluginResult
if let err = error {
result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription)
} else {
result = CDVPluginResult(status: CDVCommandStatus_OK, messageAsArrayBuffer: data)
}
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
)
}
@objc(downloadFile:)
func downloadFile(command: CDVInvokedUrlCommand) {
print("Documents \(NSHomeDirectory())")
let filePath: String = command.arguments[2] as? String ?? ""
AwsS3Manager.findSS().downloadFile(
s3Bucket: command.arguments[0] as? String ?? "",
s3Key: command.arguments[1] as? String ?? "",
filePath: URL(fileURLWithPath: NSHomeDirectory() + filePath),
complete: { error in
var result: CDVPluginResult
if let err = error {
result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription)
} else {
result = CDVPluginResult(status: CDVCommandStatus_OK)
}
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
)
}
@objc(downloadZipFile:)
func downloadZipFile(command: CDVInvokedUrlCommand) {
print("Documents \(NSHomeDirectory())")
let filePath: String = command.arguments[2] as? String ?? ""
AwsS3Manager.findSS().downloadZipFile(
s3Bucket: command.arguments[0] as? String ?? "",
s3Key: command.arguments[1] as? String ?? "",
filePath: URL(fileURLWithPath: NSHomeDirectory() + filePath),
view: self.webView,
complete: { error in
var result: CDVPluginResult
if let err = error {
result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription)
} else {
result = CDVPluginResult(status: CDVCommandStatus_OK)
}
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
)
}
@objc(uploadAnalytics:)
func uploadVideoAnalytics(command: CDVInvokedUrlCommand) {
let data = command.arguments[3] as? String ?? ""
AwsS3Manager.findSS().uploadAnalytics(
sessionId: command.arguments[0] as? String ?? "",
timestamp: command.arguments[1] as? String ?? "",
prefix: command.arguments[2] as? String ?? "",
json: data.data(using: String.Encoding.utf8)!,
complete: { error in
var result: CDVPluginResult
if let err = error {
result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription)
} else {
result = CDVPluginResult(status: CDVCommandStatus_OK)
}
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
)
}
@objc(uploadText:)
func uploadText(command: CDVInvokedUrlCommand) {
AwsS3Manager.findSS().uploadText(
s3Bucket: command.arguments[0] as? String ?? "",
s3Key: command.arguments[1] as? String ?? "",
data: command.arguments[2] as? String ?? "",
contentType: command.arguments[3] as? String ?? "",
complete: { error in
var result: CDVPluginResult
if let err = error {
result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription)
} else {
result = CDVPluginResult(status: CDVCommandStatus_OK)
}
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
)
}
@objc(uploadData:)
func uploadData(command: CDVInvokedUrlCommand) {
AwsS3Manager.findSS().uploadData(
s3Bucket: command.arguments[0] as? String ?? "",
s3Key: command.arguments[1] as? String ?? "",
data: command.arguments[2] as? Data ?? Data(),
contentType: command.arguments[3] as? String ?? "",
complete: { error in
var result: CDVPluginResult
if let err = error {
result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription)
} else {
result = CDVPluginResult(status: CDVCommandStatus_OK)
}
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
)
}
/**
* Warning: this does not use the uploadFile method of TransferUtility,
* See note in AwsS3.uploadFile for more info.
*/
@objc(uploadFile:)
func uploadFile(command: CDVInvokedUrlCommand) {
let filePath = command.arguments[2] as? String ?? ""
AwsS3Manager.findSS().uploadFile(
s3Bucket: command.arguments[0] as? String ?? "",
s3Key: command.arguments[1] as? String ?? "",
filePath: URL(fileURLWithPath: NSHomeDirectory() + filePath),
contentType: command.arguments[3] as? String ?? "",
complete: { error in
var result: CDVPluginResult
if let err = error {
result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err.localizedDescription)
} else {
result = CDVPluginResult(status: CDVCommandStatus_OK)
}
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
)
}
}
| mit | 5d6bcdfc086d3d21eceb234fb49f9de1 | 38.254545 | 107 | 0.636985 | 4.229187 | false | false | false | false |
mvader/advent-of-code | 2021/09/02.swift | 1 | 2457 | import Foundation
struct Point: Hashable {
let x: Int
let y: Int
init(_ x: Int, _ y: Int) {
self.x = x
self.y = y
}
}
func findBasin(_ heightmap: [[Int]], _ x: Int, _ y: Int) -> [Int] {
var result = [heightmap[y][x]]
var seen: Set = [Point(x, y)]
result.append(contentsOf: adjacentBasinPoints(heightmap, x, y, &seen))
return result
}
func adjacentBasinPoints(_ matrix: [[Int]], _ x: Int, _ y: Int, _ seen: inout Set<Point>) -> [Int] {
var result = [Int]()
if y > 0, matrix[y - 1][x] < 9, !seen.contains(Point(x, y - 1)) {
seen.insert(Point(x, y - 1))
result.append(matrix[y - 1][x])
result.append(contentsOf: adjacentBasinPoints(matrix, x, y - 1, &seen))
}
if y + 1 < matrix.count, matrix[y + 1][x] < 9, !seen.contains(Point(x, y + 1)) {
seen.insert(Point(x, y + 1))
result.append(matrix[y + 1][x])
result.append(contentsOf: adjacentBasinPoints(matrix, x, y + 1, &seen))
}
if x > 0, matrix[y][x - 1] < 9, !seen.contains(Point(x - 1, y)) {
seen.insert(Point(x - 1, y))
result.append(matrix[y][x - 1])
result.append(contentsOf: adjacentBasinPoints(matrix, x - 1, y, &seen))
}
if x + 1 < matrix[y].count, matrix[y][x + 1] < 9, !seen.contains(Point(x + 1, y)) {
seen.insert(Point(x + 1, y))
result.append(matrix[y][x + 1])
result.append(contentsOf: adjacentBasinPoints(matrix, x + 1, y, &seen))
}
return result
}
func adjacentPoints(_ matrix: [[Int]], _ x: Int, _ y: Int) -> [Int] {
var result = [Int]()
if y > 0 {
result.append(matrix[y - 1][x])
}
if y + 1 < matrix.count {
result.append(matrix[y + 1][x])
}
if x > 0 {
result.append(matrix[y][x - 1])
}
if x + 1 < matrix[y].count {
result.append(matrix[y][x + 1])
}
return result
}
func isLowPoint(_ heightmap: [[Int]], _ x: Int, _ y: Int) -> Bool {
let adjacents = adjacentPoints(heightmap, x, y)
return adjacents.allSatisfy { $0 > heightmap[y][x] }
}
func findBasins(_ heightmap: [[Int]]) -> [[Int]] {
var result = [[Int]]()
for y in 0 ..< heightmap.count {
let row = heightmap[y]
for x in 0 ..< row.count {
if isLowPoint(heightmap, x, y) {
let basin = findBasin(heightmap, x, y)
result.append(basin)
}
}
}
return result
}
let heightmap = try String(contentsOfFile: "./input.txt", encoding: .utf8)
.split(separator: "\n")
.map { line in
Array(line).map { c in
Int(String(c))!
}
}
let basins = findBasins(heightmap)
print(basins.map { $0.count }.sorted().reversed().prefix(3).reduce(1, *))
| mit | 23b1d1796ce4b41feed0525e62177f66 | 23.57 | 100 | 0.601954 | 2.514841 | false | false | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS | source/Core/Classes/RSEmailStepViewController.swift | 1 | 5017 | //
// RSEmailStepViewController.swift
// ResearchSuiteExtensions
//
// Created by James Kizer on 2/7/18.
//
import UIKit
import MessageUI
open class RSEmailStepViewController: RSQuestionViewController, MFMailComposeViewControllerDelegate {
open var emailSent: Bool = false
func showErrorMessage(emailStep: RSEmailStep) {
DispatchQueue.main.async {
self.emailSent = true
self.setContinueButtonTitle(title: "Continue")
let alertController = UIAlertController(title: "Email failed", message: emailStep.errorMessage, preferredStyle: UIAlertController.Style.alert)
// Replace UIAlertActionStyle.Default by UIAlertActionStyle.default
let okAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default) {
(result : UIAlertAction) -> Void in
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
func generateMailLink(emailStep: RSEmailStep) -> URL? {
let recipients: String = emailStep.recipientAddreses.joined(separator: ",")
var emailLink = "mailto:\(recipients)"
let params: [String: String] = {
var paramDict: [String: String] = [:]
if let subject = emailStep.messageSubject?.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
paramDict["Subject"] = subject
}
if let body = emailStep.messageBody?.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
paramDict["Body"] = body
}
return paramDict
}()
if params.count > 0 {
let paramStrings: [String] = params.map({ (pair) -> String in
return "\(pair.0)=\(pair.1)"
})
let paramsString = paramStrings.joined(separator: "&")
emailLink = "\(emailLink)?\(paramsString)"
}
return URL(string: emailLink)
}
func composeMail(emailStep: RSEmailStep) {
if MFMailComposeViewController.canSendMail() {
let composeVC = MFMailComposeViewController()
composeVC.mailComposeDelegate = self
// Configure the fields of the interface.
composeVC.setToRecipients(emailStep.recipientAddreses)
if let subject = emailStep.messageSubject {
composeVC.setSubject(subject)
}
if let body = emailStep.messageBody {
composeVC.setMessageBody(body, isHTML: emailStep.bodyIsHTML)
}
else {
composeVC.setMessageBody("", isHTML: false)
}
// Present the view controller modally.
composeVC.modalPresentationStyle = .fullScreen
self.present(composeVC, animated: true, completion: nil)
}
else {
if let url = self.generateMailLink(emailStep: emailStep),
UIApplication.shared.canOpenURL(url) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
if success {
self.emailSent = true
self.notifyDelegateAndMoveForward()
}
else {
self.showErrorMessage(emailStep: emailStep)
}
})
} else {
// Fallback on earlier versions
let success = UIApplication.shared.openURL(url)
if success {
self.emailSent = true
self.notifyDelegateAndMoveForward()
}
else {
self.showErrorMessage(emailStep: emailStep)
}
}
}
else {
self.showErrorMessage(emailStep: emailStep)
}
}
}
override open func continueTapped(_ sender: Any) {
if self.emailSent {
self.notifyDelegateAndMoveForward()
}
else if let emailStep = self.step as? RSEmailStep {
//load email
self.composeMail(emailStep: emailStep)
}
}
open func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
if result != .cancelled && result != .failed {
self.emailSent = true
self.notifyDelegateAndMoveForward()
}
else {
controller.dismiss(animated: true, completion: nil)
}
}
}
| apache-2.0 | 820ee706d56781d681a51123bd9a4981 | 33.840278 | 154 | 0.530397 | 5.766667 | false | false | false | false |
RobotsAndPencils/SwiftCharts | Examples/Examples/GroupedAndStackedBarsExample.swift | 1 | 8758 | //
// GroupedAndStackedBarsExample.swift
// Examples
//
// Created by ischuetz on 20/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
class GroupedAndStackedBarsExample: UIViewController {
private var chart: Chart?
private let dirSelectorHeight: CGFloat = 50
private func barsChart(horizontal horizontal: Bool) -> Chart {
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
let groupsData: [(title: String, bars: [(start: Double, quantities: [Double])])] = [
("A", [
(0,
[-20, -5, -10]
),
(0,
[10, 20, 30]
),
(0,
[30, 14, 5]
)
]),
("B", [
(0,
[-10, -15, -5]
),
(0,
[30, 25, 40]
),
(0,
[25, 40, 10]
)
]),
("C", [
(0,
[-15, -30, -10]
),
(0,
[-10, -10, -5]
),
(0,
[15, 30, 10]
)
]),
("D", [
(0,
[-20, -10, -10]
),
(0,
[30, 15, 27]
),
(0,
[8, 10, 25]
)
])
]
let frameColors = [UIColor.redColor().colorWithAlphaComponent(0.6), UIColor.blueColor().colorWithAlphaComponent(0.6), UIColor.greenColor().colorWithAlphaComponent(0.6)]
let groups: [ChartPointsBarGroup<ChartStackedBarModel>] = groupsData.enumerate().map {index, entry in
let constant = ChartAxisValueDouble(Double(index))
let bars: [ChartStackedBarModel] = entry.bars.enumerate().map {index, bars in
let items = bars.quantities.enumerate().map {index, quantity in
ChartStackedBarItemModel(quantity, frameColors[index])
}
return ChartStackedBarModel(constant: constant, start: ChartAxisValueDouble(bars.start), items: items)
}
return ChartPointsBarGroup(constant: constant, bars: bars)
}
let (axisValues1, axisValues2): ([ChartAxisValue], [ChartAxisValue]) = (
(-60).stride(through: 100, by: 20).map {ChartAxisValueDouble(Double($0), labelSettings: labelSettings)},
[ChartAxisValueString(order: -1)] +
groupsData.enumerate().map {index, tuple in ChartAxisValueString(tuple.0, order: index, labelSettings: labelSettings)} +
[ChartAxisValueString(order: groupsData.count)]
)
let (xValues, yValues) = horizontal ? (axisValues1, axisValues2) : (axisValues2, axisValues1)
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let frame = ExamplesDefaults.chartFrame(self.view.bounds)
let chartFrame = self.chart?.frame ?? CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height - self.dirSelectorHeight)
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
let groupsLayer = ChartGroupedStackedBarsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, groups: groups, horizontal: horizontal, barSpacing: 2, groupSpacing: 30, animDuration: 0.5)
let settings = ChartGuideLinesLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: horizontal ? .X : .Y, settings: settings)
let dummyZeroChartPoint = ChartPoint(x: ChartAxisValueDouble(0), y: ChartAxisValueDouble(0))
let zeroGuidelineLayer = ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: [dummyZeroChartPoint], viewGenerator: {(chartPointModel, layer, chart) -> UIView? in
let width: CGFloat = 2
let viewFrame: CGRect = {
if horizontal {
return CGRectMake(chartPointModel.screenLoc.x - width / 2, innerFrame.origin.y, width, innerFrame.size.height)
} else {
return CGRectMake(innerFrame.origin.x, chartPointModel.screenLoc.y - width / 2, innerFrame.size.width, width)
}
}()
let v = UIView(frame: viewFrame)
v.backgroundColor = UIColor.blackColor()
return v
})
return Chart(
frame: chartFrame,
layers: [
xAxis,
yAxis,
guidelinesLayer,
groupsLayer,
zeroGuidelineLayer
]
)
}
private func showChart(horizontal horizontal: Bool) {
self.chart?.clearView()
let chart = self.barsChart(horizontal: horizontal)
self.view.addSubview(chart.view)
self.chart = chart
}
override func viewDidLoad() {
self.showChart(horizontal: false)
if let chart = self.chart {
let dirSelector = DirSelector(frame: CGRectMake(0, chart.frame.origin.y + chart.frame.size.height, self.view.frame.size.width, self.dirSelectorHeight), controller: self)
self.view.addSubview(dirSelector)
}
}
class DirSelector: UIView {
let horizontal: UIButton
let vertical: UIButton
weak var controller: GroupedAndStackedBarsExample?
private let buttonDirs: [UIButton : Bool]
init(frame: CGRect, controller: GroupedAndStackedBarsExample) {
self.controller = controller
self.horizontal = UIButton()
self.horizontal.setTitle("Horizontal", forState: .Normal)
self.vertical = UIButton()
self.vertical.setTitle("Vertical", forState: .Normal)
self.buttonDirs = [self.horizontal : true, self.vertical : false]
super.init(frame: frame)
self.addSubview(self.horizontal)
self.addSubview(self.vertical)
for button in [self.horizontal, self.vertical] {
button.titleLabel?.font = ExamplesDefaults.fontWithSize(14)
button.setTitleColor(UIColor.blueColor(), forState: .Normal)
button.addTarget(self, action: "buttonTapped:", forControlEvents: .TouchUpInside)
}
}
func buttonTapped(sender: UIButton) {
let horizontal = sender == self.horizontal ? true : false
controller?.showChart(horizontal: horizontal)
}
override func didMoveToSuperview() {
let views = [self.horizontal, self.vertical]
for v in views {
v.translatesAutoresizingMaskIntoConstraints = false
}
let namedViews = views.enumerate().map{index, view in
("v\(index)", view)
}
let viewsDict = namedViews.reduce(Dictionary<String, UIView>()) {(var u, tuple) in
u[tuple.0] = tuple.1
return u
}
let buttonsSpace: CGFloat = Env.iPad ? 20 : 10
let hConstraintStr = namedViews.reduce("H:|") {str, tuple in
"\(str)-(\(buttonsSpace))-[\(tuple.0)]"
}
let vConstraits = namedViews.flatMap {NSLayoutConstraint.constraintsWithVisualFormat("V:|[\($0.0)]", options: NSLayoutFormatOptions(), metrics: nil, views: viewsDict)}
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(hConstraintStr, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDict)
+ vConstraits)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
| apache-2.0 | 000e563cdc04a8a34d46b4d8165c53f2 | 39.734884 | 204 | 0.552295 | 5.145711 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/MailingAddressConnection.swift | 1 | 5274 | //
// MailingAddressConnection.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// An auto-generated type for paginating through multiple MailingAddresses.
open class MailingAddressConnectionQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = MailingAddressConnection
/// A list of edges.
@discardableResult
open func edges(alias: String? = nil, _ subfields: (MailingAddressEdgeQuery) -> Void) -> MailingAddressConnectionQuery {
let subquery = MailingAddressEdgeQuery()
subfields(subquery)
addField(field: "edges", aliasSuffix: alias, subfields: subquery)
return self
}
/// A list of the nodes contained in MailingAddressEdge.
@discardableResult
open func nodes(alias: String? = nil, _ subfields: (MailingAddressQuery) -> Void) -> MailingAddressConnectionQuery {
let subquery = MailingAddressQuery()
subfields(subquery)
addField(field: "nodes", aliasSuffix: alias, subfields: subquery)
return self
}
/// Information to aid in pagination.
@discardableResult
open func pageInfo(alias: String? = nil, _ subfields: (PageInfoQuery) -> Void) -> MailingAddressConnectionQuery {
let subquery = PageInfoQuery()
subfields(subquery)
addField(field: "pageInfo", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// An auto-generated type for paginating through multiple MailingAddresses.
open class MailingAddressConnection: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = MailingAddressConnectionQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "edges":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: MailingAddressConnection.self, field: fieldName, value: fieldValue)
}
return try value.map { return try MailingAddressEdge(fields: $0) }
case "nodes":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: MailingAddressConnection.self, field: fieldName, value: fieldValue)
}
return try value.map { return try MailingAddress(fields: $0) }
case "pageInfo":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: MailingAddressConnection.self, field: fieldName, value: fieldValue)
}
return try PageInfo(fields: value)
default:
throw SchemaViolationError(type: MailingAddressConnection.self, field: fieldName, value: fieldValue)
}
}
/// A list of edges.
open var edges: [Storefront.MailingAddressEdge] {
return internalGetEdges()
}
func internalGetEdges(alias: String? = nil) -> [Storefront.MailingAddressEdge] {
return field(field: "edges", aliasSuffix: alias) as! [Storefront.MailingAddressEdge]
}
/// A list of the nodes contained in MailingAddressEdge.
open var nodes: [Storefront.MailingAddress] {
return internalGetNodes()
}
func internalGetNodes(alias: String? = nil) -> [Storefront.MailingAddress] {
return field(field: "nodes", aliasSuffix: alias) as! [Storefront.MailingAddress]
}
/// Information to aid in pagination.
open var pageInfo: Storefront.PageInfo {
return internalGetPageInfo()
}
func internalGetPageInfo(alias: String? = nil) -> Storefront.PageInfo {
return field(field: "pageInfo", aliasSuffix: alias) as! Storefront.PageInfo
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "edges":
internalGetEdges().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
case "nodes":
internalGetNodes().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
case "pageInfo":
response.append(internalGetPageInfo())
response.append(contentsOf: internalGetPageInfo().childResponseObjectMap())
default:
break
}
}
return response
}
}
}
| mit | 0a388fdd17371e6d36cb1bdd551e7c4a | 34.395973 | 122 | 0.724308 | 4.053805 | false | false | false | false |
MadAppGang/refresher | PullToRefreshDemo/BeatAnimator.swift | 1 | 4919 | //
// BeatAnimator.swift
//
// Copyright (c) 2014 Josip Cavar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import Refresher
import QuartzCore
class BeatAnimator: UIView, PullToRefreshViewDelegate {
enum Layout {
case Top, Bottom
}
private let layerLoader = CAShapeLayer()
private let layerSeparator = CAShapeLayer()
var layout:Layout = .Bottom {
didSet {
self.setNeedsLayout()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
layerLoader.lineWidth = 4
layerLoader.strokeColor = UIColor(red: 0.13, green: 0.79, blue: 0.31, alpha: 1).CGColor
layerLoader.strokeEnd = 0
layerSeparator.lineWidth = 1
layerSeparator.strokeColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1).CGColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func pullToRefresh(view: PullToRefreshView, progressDidChange progress: CGFloat) {
layerLoader.strokeEnd = progress
}
func pullToRefresh(view: PullToRefreshView, stateDidChange state: PullToRefreshViewState) {
}
func pullToRefreshAnimationDidEnd(view: PullToRefreshView) {
layerLoader.removeAllAnimations()
}
func pullToRefreshAnimationDidStart(view: PullToRefreshView) {
addAnimations()
}
func addAnimations() {
let pathAnimationEnd = CABasicAnimation(keyPath: "strokeEnd")
pathAnimationEnd.duration = 0.5
pathAnimationEnd.repeatCount = 100
pathAnimationEnd.autoreverses = true
pathAnimationEnd.fromValue = 1
pathAnimationEnd.toValue = 0.8
layerLoader.addAnimation(pathAnimationEnd, forKey: "strokeEndAnimation")
let pathAnimationStart = CABasicAnimation(keyPath: "strokeStart")
pathAnimationStart.duration = 0.5
pathAnimationStart.repeatCount = 100
pathAnimationStart.autoreverses = true
pathAnimationStart.fromValue = 0
pathAnimationStart.toValue = 0.2
layerLoader.addAnimation(pathAnimationStart, forKey: "strokeStartAnimation")
}
override func layoutSubviews() {
super.layoutSubviews()
if let superview = superview {
if layerLoader.superlayer == nil {
superview.layer.addSublayer(layerLoader)
}
if layerSeparator.superlayer == nil {
superview.layer.addSublayer(layerSeparator)
}
let verticalPosition = layout == .Bottom ? superview.frame.height - 3 : 2
let bezierPathLoader = UIBezierPath()
bezierPathLoader.moveToPoint(CGPointMake(0, verticalPosition))
bezierPathLoader.addLineToPoint(CGPoint(x: superview.frame.width, y: verticalPosition))
let verticalPositionSeparator = layout == .Bottom ? superview.frame.height - 1 : 0
let bezierPathSeparator = UIBezierPath()
bezierPathSeparator.moveToPoint(CGPointMake(0, verticalPositionSeparator))
bezierPathSeparator.addLineToPoint(CGPoint(x: superview.frame.width, y: verticalPositionSeparator))
layerLoader.path = bezierPathLoader.CGPath
layerSeparator.path = bezierPathSeparator.CGPath
}
}
}
extension BeatAnimator: LoadMoreViewDelegate {
func loadMoreAnimationDidStart(view: LoadMoreView) {
addAnimations()
}
func loadMoreAnimationDidEnd(view: LoadMoreView) {
layerLoader.removeAllAnimations()
}
func loadMore(view: LoadMoreView, progressDidChange progress: CGFloat) {
layerLoader.strokeEnd = progress
}
func loadMore(view: LoadMoreView, stateDidChange state: LoadMoreViewState) {
}
}
| mit | 4dbdb7d3d56f2bda4e4f3812d0616315 | 34.905109 | 111 | 0.678593 | 5.244136 | false | false | false | false |
mbuchetics/DataSource | Example/ViewControllers/Examples/RandomPersonsViewController.swift | 1 | 3407 | //
// RandomPersonsViewController.swift
// DataSource
//
// Created by Matthias Buchetics on 27/02/2017.
// Copyright © 2017 aaa - all about apps GmbH. All rights reserved.
//
import UIKit
import DataSource
// MARK: - View Controller
class RandomPersonsViewController: UITableViewController {
lazy var dataSource: DataSource = {
DataSource(
cellDescriptors: [
PersonCell.descriptor
.didSelect { (item, indexPath) in
print("\(item.firstName) \(item.lastName) selected")
return .deselect
}
],
sectionDescriptors: [
SectionDescriptor<String>()
.header { (title, _) in
.title(title)
}
])
}()
override func viewDidLoad() {
super.viewDidLoad()
dataSource.fallbackDelegate = self
tableView.dataSource = dataSource
tableView.delegate = dataSource
dataSource.sections = randomData()
dataSource.reloadData(tableView, animated: false)
}
private func randomData() -> [SectionType] {
let count = Int.random(5, 15)
let persons = (0 ..< count).map { _ in Person.random() }.sorted()
let letters = Set(["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"])
let firstGroup = persons.filter {
$0.lastNameStartsWith(letters: letters)
}
let secondGroup = persons.filter {
!$0.lastNameStartsWith(letters: letters)
}
return [
Section("A - L", items: firstGroup),
Section("M - Z", items: secondGroup),
]
}
@IBAction func refresh(_ sender: Any) {
dataSource.sections = randomData()
dataSource.reloadData(tableView, animated: true)
}
}
// MARK: - Scroll view delegate
extension RandomPersonsViewController {
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("scrolled: \(scrollView.contentOffset.y)")
}
}
// MARK: - Person
struct Person {
let firstName: String
let lastName: String
func lastNameStartsWith(letters: Set<String>) -> Bool {
let letter = String(lastName[lastName.startIndex])
return letters.contains(letter)
}
var fullName: String {
return "\(firstName) \(lastName)"
}
static func random() -> Person {
return Person(
firstName: Randoms.randomFirstName(),
lastName: Randoms.randomLastName()
)
}
}
extension Person: Equatable {
static func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.fullName == rhs.fullName
}
}
extension Person: Comparable {
static func <(lhs: Person, rhs: Person) -> Bool {
if lhs.lastName != rhs.lastName {
return lhs.lastName < rhs.lastName
} else if lhs.firstName != rhs.firstName {
return lhs.firstName < rhs.firstName
} else {
return false
}
}
}
extension Person: Diffable {
public var diffIdentifier: String {
return fullName
}
}
extension Person: CustomStringConvertible {
var description: String {
return fullName
}
}
| mit | d085a3c519c78e7fdf575d1909209ad1 | 23.681159 | 87 | 0.550206 | 4.797183 | false | false | false | false |
feliperuzg/CleanExample | CleanExampleTests/Core/Network/NetworkConfiguration/NetworkConfigurationSpec.swift | 1 | 801 | //
// NetworkConfigurationSpec.swift
// CleanExampleTests
//
// Created by Felipe Ruz on 13-12-17.
// Copyright © 2017 Felipe Ruz. All rights reserved.
//
import XCTest
@testable import CleanExample
class NetworkConfigurationSpec: XCTestCase {
var sut: NetworkConfiguration!
override func tearDown() {
super.tearDown()
sut = nil
}
func testNetworkConfigiurationReturnsURL() {
sut = NetworkConfiguration()
let url = sut.authenticationURL(for: .login)
XCTAssertNotNil(url)
}
func testNetworkConfigurationReturnsNil() {
sut = NetworkConfiguration()
sut.networkConfigurationList = "none"
sut.prepare()
let url = sut.authenticationURL(for: .login)
XCTAssertNil(url)
}
}
| mit | ccf898222fa1c64caf0aed52f98cd188 | 21.857143 | 53 | 0.6475 | 4.651163 | false | true | false | false |
glorybird/KeepReading2 | kr/kr/ui/CupView.swift | 1 | 1686 | //
// CupView.swift
// kr
//
// Created by FanFamily on 16/1/31.
// Copyright © 2016年 glorybird. All rights reserved.
//
import UIKit
class CupView: UIView {
var waveView: SCSiriWaveformView!
var level:CGFloat = 0.1
var dampTimer:NSTimer?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
waveView = SCSiriWaveformView()
waveView.backgroundColor = UIColor.whiteColor()
waveView.waveColor = UIColor.orangeColor()
waveView.primaryWaveLineWidth = 2.0
waveView.secondaryWaveLineWidth = 0.0
waveView.idleAmplitude = 0.0
waveView.density = 1.0
addSubview(waveView)
waveView.snp_makeConstraints { (make) -> Void in
make.margins.equalTo(self).offset(0)
}
let displaylink = CADisplayLink(target: self, selector:Selector.init("updateWave"))
displaylink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
}
func updateWave() {
if level >= 0 {
waveView.updateWithLevel(level)
}
}
func damping() {
level -= 0.01
if level < 0 {
if dampTimer != nil {
dampTimer!.invalidate()
dampTimer = nil
}
}
}
func changeProgress(progress:CGFloat) {
waveView.stage = progress
level = 0.1
// 自然衰减
if dampTimer != nil {
dampTimer!.invalidate()
}
dampTimer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: Selector.init("damping"), userInfo: nil, repeats: true)
}
}
| apache-2.0 | 1d71a7aa22214df194292bb5dd14f4d2 | 26.016129 | 143 | 0.585075 | 4.240506 | false | false | false | false |
googleprojectzero/fuzzilli | Sources/Fuzzilli/Mutators/ProbingMutator.swift | 1 | 20439 | // Copyright 2022 Google LLC
//
// 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
//
// https://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
/// This mutator inserts probes into a program to determine how existing variables are used.
///
/// Its main purpose is to determine which (non-existent) properties are accessed on existing objects and to then add these properties (or install accessors for them).
///
/// This mutator achieves this by doing the following:
/// 1. It instruments the given program by inserting special Probe operations which turn an existing variable into a "probe"
/// that records accesses to non-existent properties on the original value. In JavaScript, probing is implemented by
/// replacing an object's prototype with a Proxy around the original prototype. This Proxy will then see all accesses to
/// non-existent properties. Alternatively, the probed object itself could be replaced with a Proxy, however that will
/// cause various builtin methods to fail because they for example expect |this| to have a specific type.
/// 2. It executes the instrumented program. The program collects the property names of non-existent properties that were accessed
/// on a probe and reports this information to Fuzzilli through the FUZZOUT channel at the end of the program's execution.
/// 3. The mutator processes the output of step 2 and randomly selects properties to install (either as plain value or
/// accessor). It then converts the Probe operations to an appropriate FuzzIL operation (e.g. StoreProperty).
///
/// A large bit of the logic of this mutator is located in the lifter code that implements Probe operations
/// in the target language. For JavaScript, that logic can be found in JavaScriptProbeLifting.swift.
public class ProbingMutator: Mutator {
private let logger = Logger(withLabel: "ProbingMutator")
// If true, this mutator will log detailed statistics.
// Enable verbose mode by default while this feature is still under development.
private let verbose = true
// Statistics about how often we've installed a particular property. Printed in regular intervals if verbose mode is active, then reset.
private var installedPropertiesForGetAccess = [Property: Int]()
private var installedPropertiesForSetAccess = [Property: Int]()
// Counts the total number of installed properties installed. Printed in regular intervals if verbose mode is active, then reset.
private var installedPropertyCounter = 0
// The number of programs produced so far, mostly used for the verbose mode.
private var producedSamples = 0
// Normally, we will not overwrite properties that already exist on the prototype (e.g. Array.prototype.slice). This list contains the exceptions to this rule.
private let propertiesOnPrototypeToOverwrite = ["valueOf", "toString", "constructor"]
// The different outcomes of probing. Used for statistics in verbose mode.
private enum ProbingOutcome: String, CaseIterable {
case success = "Success"
case cannotInstrument = "Cannot instrument input"
case instrumentedProgramCrashed = "Instrumented program crashed"
case instrumentedProgramFailed = "Instrumented program failed"
case instrumentedProgramTimedOut = "Instrumented program timed out"
case noActions = "No actions received"
case unexpectedError = "Unexpected Error"
}
private var probingOutcomeCounts = [ProbingOutcome: Int]()
public override init() {
if verbose {
for outcome in ProbingOutcome.allCases {
probingOutcomeCounts[outcome] = 0
}
}
}
override func mutate(_ program: Program, using b: ProgramBuilder, for fuzzer: Fuzzer) -> Program? {
guard let instrumentedProgram = instrument(program, for: fuzzer) else {
// This means there are no variables that could be probed.
return failure(.cannotInstrument)
}
// Execute the instrumented program (with a higher timeout) and collect the output.
let execution = fuzzer.execute(instrumentedProgram, withTimeout: fuzzer.config.timeout * 2)
guard execution.outcome == .succeeded else {
if case .crashed(let signal) = execution.outcome {
// This is unexpected but we should still be able to handle it.
fuzzer.processCrash(instrumentedProgram, withSignal: signal, withStderr: execution.stderr, withStdout: execution.stdout, origin: .local)
return failure(.instrumentedProgramCrashed)
} else if case .failed(_) = execution.outcome {
// This is generally unexpected as the JavaScript code attempts to be as transparent as possible and to not alter the behavior of the program.
// However, there are some rare edge cases where this isn't possible, for example when the JavaScript code observes the modified prototype.
return failure(.instrumentedProgramFailed)
}
assert(execution.outcome == .timedOut)
return failure(.instrumentedProgramTimedOut)
}
let output = execution.fuzzout
// Parse the output: look for either "PROBING_ERROR" or "PROBING_RESULTS" and process the content.
var results = [String: Result]()
for line in output.split(whereSeparator: \.isNewline) {
guard line.starts(with: "PROBING") else { continue }
let errorMarker = "PROBING_ERROR: "
let resultsMarker = "PROBING_RESULTS: "
if line.hasPrefix(errorMarker) {
let ignoredErrors = ["maximum call stack size exceeded", "out of memory", "too much recursion"]
for error in ignoredErrors {
if line.lowercased().contains(error) {
return failure(.instrumentedProgramFailed)
}
}
// Everything else is unexpected and probably means there's a bug in the JavaScript implementation, so treat that as an error.
logger.error("\n" + fuzzer.lifter.lift(instrumentedProgram, withOptions: .includeLineNumbers))
logger.error("\nProbing failed: \(line.dropFirst(errorMarker.count))\n")
//maybeLogFailingExecution(execution, of: instrumentedProgram, usingLifter: fuzzer.lifter, usingLogLevel: .error)
// We could probably still continue in these cases, but since this is unexpected, it's probably better to stop here and treat this as an unexpected failure.
return failure(.unexpectedError)
}
guard line.hasPrefix(resultsMarker) else {
logger.error("Invalid probing result: \(line)")
return failure(.unexpectedError)
}
let decoder = JSONDecoder()
let payload = Data(line.dropFirst(resultsMarker.count).utf8)
guard let decodedResults = try? decoder.decode([String: Result].self, from: payload) else {
logger.error("Failed to decode JSON payload in \"\(line)\"")
return failure(.unexpectedError)
}
results = decodedResults
}
guard !results.isEmpty else {
return failure(.noActions)
}
// Now build the final program by parsing the results and replacing the Probe operations
// with FuzzIL operations that install one of the non-existent properties (if any).
b.adopting(from: instrumentedProgram) {
for instr in instrumentedProgram.code {
if let op = instr.op as? Probe {
if let results = results[op.id] {
let probedValue = b.adopt(instr.input(0))
b.trace("Probing value \(probedValue)")
processProbeResults(results, on: probedValue, using: b)
b.trace("Probing finished")
}
} else {
b.adopt(instr)
}
}
}
producedSamples += 1
let N = 1000
if verbose && (producedSamples % N) == 0 {
logger.info("Properties installed during the last \(N) successful runs:")
var statsAsList = installedPropertiesForGetAccess.map({ (key: $0, count: $1, op: "get") })
statsAsList += installedPropertiesForSetAccess.map({ (key: $0, count: $1, op: "set") })
for (key, count, op) in statsAsList.sorted(by: { $0.count > $1.count }) {
let type = isCallableProperty(key) ? "function" : "anything"
logger.info(" \(count)x \(key.description) (access: \(op), type: \(type))")
}
logger.info(" Total number of properties installed: \(installedPropertyCounter)")
installedPropertiesForGetAccess.removeAll()
installedPropertiesForSetAccess.removeAll()
installedPropertyCounter = 0
logger.info("Frequencies of probing outcomes:")
let totalOutcomes = probingOutcomeCounts.values.reduce(0, +)
for outcome in ProbingOutcome.allCases {
let count = probingOutcomeCounts[outcome]!
let frequency = (Double(count) / Double(totalOutcomes)) * 100.0
logger.info(" \(outcome.rawValue.rightPadded(toLength: 30)): \(String(format: "%.2f%%", frequency))")
}
}
return success(b.finalize())
}
private func processProbeResults(_ result: Result, on obj: Variable, using b: ProgramBuilder) {
// Extract all candidates: properties that are accessed but not present (or explicitly marked as overwritable).
let loadCandidates = result.loads.filter({ $0.value == .notFound || ($0.value == .found && propertiesOnPrototypeToOverwrite.contains($0.key)) }).map({ $0.key })
// For stores we only care about properties that don't exist anywhere on the prototype chain.
let storeCandidates = result.stores.filter({ $0.value == .notFound }).map({ $0.key })
let candidates = Set(loadCandidates).union(storeCandidates)
guard !candidates.isEmpty else { return }
// Pick a random property from the candidates.
let propertyName = chooseUniform(from: candidates)
let propertyIsLoaded = result.loads.keys.contains(propertyName)
let propertyIsStored = result.stores.keys.contains(propertyName)
// Install the property, either as regular property or as a property accessor.
let property = parsePropertyName(propertyName)
if probability(0.8) {
installRegularProperty(property, on: obj, using: b)
} else {
installPropertyAccessor(for: property, on: obj, using: b, shouldHaveGetter: propertyIsLoaded, shouldHaveSetter: propertyIsStored)
}
// Update our statistics.
if verbose && propertyIsLoaded {
installedPropertiesForGetAccess[property] = (installedPropertiesForGetAccess[property] ?? 0) + 1
}
if verbose && propertyIsStored {
installedPropertiesForSetAccess[property] = (installedPropertiesForSetAccess[property] ?? 0) + 1
}
installedPropertyCounter += 1
}
private func installRegularProperty(_ property: Property, on obj: Variable, using b: ProgramBuilder) {
let value = selectValue(for: property, using: b)
switch property {
case .regular(let name):
assert(name.rangeOfCharacter(from: .whitespacesAndNewlines) == nil)
b.storeProperty(value, as: name, on: obj)
case .element(let index):
b.storeElement(value, at: index, of: obj)
case .symbol(let desc):
let Symbol = b.loadBuiltin("Symbol")
let symbol = b.loadProperty(extractSymbolNameFromDescription(desc), of: Symbol)
b.storeComputedProperty(value, as: symbol, on: obj)
}
}
private func installPropertyAccessor(for property: Property, on obj: Variable, using b: ProgramBuilder, shouldHaveGetter: Bool, shouldHaveSetter: Bool) {
assert(shouldHaveGetter || shouldHaveSetter)
let installAsValue = probability(0.5)
let installGetter = !installAsValue && (shouldHaveGetter || probability(0.5))
let installSetter = !installAsValue && (shouldHaveSetter || probability(0.5))
let config: ProgramBuilder.PropertyConfiguration
if installAsValue {
config = .value(selectValue(for: property, using: b))
} else if installGetter && installSetter {
let getter = b.buildPlainFunction(with: .parameters(n: 0)) { _ in
let value = selectValue(for: property, using: b)
b.doReturn(value)
}
let setter = b.buildPlainFunction(with: .parameters(n: 1)) { _ in
b.build(n: 1)
}
config = .getterSetter(getter, setter)
} else if installGetter {
let getter = b.buildPlainFunction(with: .parameters(n: 0)) { _ in
let value = selectValue(for: property, using: b)
b.doReturn(value)
}
config = .getter(getter)
} else {
assert(installSetter)
let setter = b.buildPlainFunction(with: .parameters(n: 1)) { _ in
b.build(n: 1)
}
config = .setter(setter)
}
switch property {
case .regular(let name):
assert(name.rangeOfCharacter(from: .whitespacesAndNewlines) == nil)
b.configureProperty(name, of: obj, usingFlags: PropertyFlags.random(), as: config)
case .element(let index):
b.configureElement(index, of: obj, usingFlags: PropertyFlags.random(), as: config)
case .symbol(let desc):
let Symbol = b.loadBuiltin("Symbol")
let symbol = b.loadProperty(extractSymbolNameFromDescription(desc), of: Symbol)
b.configureComputedProperty(symbol, of: obj, usingFlags: PropertyFlags.random(), as: config)
}
}
private func extractSymbolNameFromDescription(_ desc: String) -> String {
// Well-known symbols are of the form "Symbol.toPrimitive". All other symbols should've been filtered out by the instrumented code.
let wellKnownSymbolPrefix = "Symbol."
guard desc.hasPrefix(wellKnownSymbolPrefix) else {
logger.error("Received invalid symbol property from instrumented code: \(desc)")
return desc
}
return String(desc.dropFirst(wellKnownSymbolPrefix.count))
}
private func isCallableProperty(_ property: Property) -> Bool {
let knownFunctionPropertyNames = ["valueOf", "toString", "constructor", "then", "get", "set"]
let knownNonFunctionSymbolNames = ["Symbol.isConcatSpreadable", "Symbol.unscopables", "Symbol.toStringTag"]
// Check if the property should be a function.
switch property {
case .regular(let name):
return knownFunctionPropertyNames.contains(name)
case .symbol(let desc):
return !knownNonFunctionSymbolNames.contains(desc)
case .element(_):
return false
}
}
private func selectValue(for property: Property, using b: ProgramBuilder) -> Variable {
if isCallableProperty(property) {
// Either create a new function or reuse an existing one
let probabilityOfReusingExistingFunction = 2.0 / 3.0
if let f = b.randVar(ofConservativeType: .function()), probability(probabilityOfReusingExistingFunction) {
return f
} else {
let f = b.buildPlainFunction(with: .parameters(n: Int.random(in: 0..<3))) { args in
b.build(n: 2) // TODO maybe forbid generating any nested blocks here?
b.doReturn(b.randVar())
}
return f
}
} else {
// Otherwise, just return a random variable.
return b.randVar()
}
}
private func parsePropertyName(_ propertyName: String) -> Property {
// Anything that parses as an Int64 is an element index.
if let index = Int64(propertyName) {
return .element(index)
}
// Symbols will be encoded as "Symbol(symbolDescription)".
let symbolPrefix = "Symbol("
let symbolSuffix = ")"
if propertyName.hasPrefix(symbolPrefix) && propertyName.hasSuffix(symbolSuffix) {
let desc = propertyName.dropFirst(symbolPrefix.count).dropLast(symbolSuffix.count)
return .symbol(String(desc))
}
// Everything else is a regular property name.
return .regular(propertyName)
}
private func instrument(_ program: Program, for fuzzer: Fuzzer) -> Program? {
// Determine candidates for probing: every variable that is used at least once as an input is a candidate.
var usedVariables = VariableSet()
for instr in program.code {
usedVariables.formUnion(instr.inputs)
}
let candidates = Array(usedVariables)
guard !candidates.isEmpty else { return nil }
// Select variables to instrument from the candidates.
let numVariablesToProbe = Int((Double(candidates.count) * 0.5).rounded(.up))
let variablesToProbe = VariableSet(candidates.shuffled().prefix(numVariablesToProbe))
var pendingVariablesToInstrument = [(v: Variable, depth: Int)]()
var depth = 0
let b = fuzzer.makeBuilder()
b.adopting(from: program) {
for instr in program.code {
b.adopt(instr)
for v in instr.innerOutputs where variablesToProbe.contains(v) {
b.probe(v, id: v.identifier)
}
for v in instr.outputs where variablesToProbe.contains(v) {
// We only want to instrument outer outputs of block heads after the end of that block.
// For example, a function definition should be turned into a probe not inside its body
// but right after the function definition ends in the surrounding block.
if instr.isBlockGroupStart {
pendingVariablesToInstrument.append((v, depth))
} else {
b.probe(v, id: v.identifier)
}
}
if instr.isBlockGroupStart {
depth += 1
} else if instr.isBlockGroupEnd {
depth -= 1
while pendingVariablesToInstrument.last?.depth == depth {
let (v, _) = pendingVariablesToInstrument.removeLast()
b.probe(v, id: v.identifier)
}
}
}
}
return b.finalize()
}
private func failure(_ outcome: ProbingOutcome) -> Program? {
assert(outcome != .success)
probingOutcomeCounts[outcome]! += 1
return nil
}
private func success(_ program: Program) -> Program {
probingOutcomeCounts[.success]! += 1
return program
}
private enum Property: Hashable, CustomStringConvertible {
case regular(String)
case symbol(String)
case element(Int64)
var description: String {
switch self {
case .regular(let name):
return name
case .symbol(let desc):
return desc
case .element(let index):
return String(index)
}
}
}
private struct Result: Decodable {
enum outcome: Int, Decodable {
case notFound = 0
case found = 1
}
let loads: [String: outcome]
let stores: [String: outcome]
}
}
| apache-2.0 | 0585df5a3d4cdb089b85637980e1253a | 47.548694 | 172 | 0.62914 | 4.773237 | false | false | false | false |
brunopinheiro/sabadinho | Sabadinho/Interactors/CalendarInteractor.swift | 1 | 3632 | //
// CalendarInteractor.swift
// Sabadinho
//
// Created by Bruno Pinheiro on 26/01/18.
// Copyright © 2018 Bruno Pinheiro. All rights reserved.
//
import Foundation
import RxSwift
protocol CalendarInteractorProtocol {
var today: Single<Day> { get }
func dayByAdding(months amount: Int, to day: Day) -> Single<Day>
func daysWithinSameMonth(as date: Date) -> Single<[Day]>
func daysWithinSameWeekBefore(_ date: Date) -> Single<[Day]>
func daysWithinSameWeekAfter(_ date: Date) -> Single<[Day]>
func week(of day: Day) -> Int?
}
class CalendarInteractor: CalendarInteractorProtocol {
private let calendarRepository: CalendarRepositoryProtocol
init(calendarRepository: CalendarRepositoryProtocol = CalendarRepository()) {
self.calendarRepository = calendarRepository
}
var today: Single<Day> {
return calendarRepository.today().map { Day(date: $0, timeEntries: []) }
}
func dayByAdding(months amount: Int, to day: Day) -> Single<Day> {
return calendarRepository
.dateByAdding(months: amount, to: day.date)
.map { Day(date: $0, timeEntries: []) }
}
func daysWithinSameMonth(as date: Date) -> Single<[Day]> {
return calendarRepository.datesWithinSameMonth(as: date).map { $0.map { Day(date: $0, timeEntries: []) } }
}
func daysWithinSameWeekBefore(_ date: Date) -> Single<[Day]> {
return belongsToFirstWeek(date)
.flatMap { $0 ? self.calendarRepository.dateByAdding(months: -1, to: date).asObservable() : Observable<Date>.empty() }
.flatMap(self.calendarRepository.datesWithinSameMonth)
.map { self.completeWeek(from: date, withPreviousDates: $0) }
.map(days)
.asObservable()
.ifEmpty(default: [])
.asSingle()
}
private func belongsToFirstWeek(_ date: Date) -> Observable<Bool> {
return .just(week(from: date) == 1)
}
private func week(from date: Date) -> Int {
guard let weekOfMonth = calendarRepository.calendar.dateComponents([.weekOfMonth], from: date).weekOfMonth else {
return -1
}
return weekOfMonth
}
private func completeWeek(from date: Date, withPreviousDates dates: [Date]) -> [Date] {
guard let weekday = calendarRepository.calendar.dateComponents([.weekday], from: date).weekday else {
return []
}
return Array(dates.suffix(weekday - 1))
}
private func days(from dates: [Date]) -> [Day] {
return dates.map { Day(date: $0, timeEntries: [Double]()) }
}
func daysWithinSameWeekAfter(_ date: Date) -> Single<[Day]> {
return belongsToLastWeek(date)
.flatMap { $0 ? self.calendarRepository.dateByAdding(months: 1, to: date).asObservable() : Observable<Date>.empty() }
.flatMap(self.calendarRepository.datesWithinSameMonth)
.map { self.completeWeek(from: date, withFollowingDates: $0) }
.map(days)
.asObservable()
.ifEmpty(default: [])
.asSingle()
}
private func belongsToLastWeek(_ date: Date) -> Observable<Bool> {
return Observable<Date>
.just(date)
.flatMap(calendarRepository.datesWithinSameMonth)
.map { self.week(from: date) == self.countWeeks(from: $0) }
}
private func countWeeks(from dates: [Date]) -> Int {
let weeks = dates.map { self.week(from: $0) }
return weeks.max() ?? 0
}
private func completeWeek(from date: Date, withFollowingDates dates: [Date]) -> [Date] {
guard let weekday = calendarRepository.calendar.dateComponents([.weekday], from: date).weekday else {
return []
}
return Array(dates.prefix(7 - weekday))
}
func week(of day: Day) -> Int? {
return calendarRepository.week(of: day.date)
}
}
| mit | b033a6dc0cdc72f59604edce1b87dac3 | 31.711712 | 124 | 0.673919 | 3.758799 | false | false | false | false |
artkirillov/DesignPatterns | Composite.playground/Contents.swift | 1 | 1543 | import Foundation
protocol Component {
var id: UInt32 { get }
func description() -> String
}
final class WashingMachine: Component {
var id = arc4random_uniform(100)
func description() -> String {
return "WashingMachine-\(id)"
}
}
final class Computer: Component {
var id = arc4random_uniform(100)
func description() -> String {
return "Computer-\(id)"
}
}
final class Speakers: Component {
var id = arc4random_uniform(100)
func description() -> String {
return "Speakers-\(id)"
}
}
final class Composite: Component {
private var components: [Component] = []
func add(component: Component) {
components.append(component)
}
func remove(component: Component) {
if let index = components.index(where: { $0.id == component.id }) {
components.remove(at: index)
}
}
var id = arc4random_uniform(100)
func description() -> String {
return components.reduce("", {"\($0)\($1.description()) "})
}
}
let computer = Computer()
let smallBox = Composite()
let mediumBox = Composite()
let bigBox = Composite()
smallBox.add(component: WashingMachine())
mediumBox.add(component: Computer())
mediumBox.add(component: Speakers())
bigBox.add(component: smallBox)
bigBox.add(component: mediumBox)
bigBox.add(component: WashingMachine())
print(computer.description())
print(smallBox.description())
print(mediumBox.description())
print(bigBox.description())
| mit | 4be0ccbd666c99a822e3e86af69768a5 | 20.136986 | 75 | 0.635126 | 3.976804 | false | false | false | false |
my-mail-ru/swiftperl | Sources/Perl/UnsafeCV.swift | 1 | 3553 | import CPerl
public typealias UnsafeCvPointer = UnsafeMutablePointer<CV>
typealias CvBody = (UnsafeXSubStack) throws -> Void
typealias UnsafeCvBodyPointer = UnsafeMutablePointer<CvBody>
extension CV {
fileprivate var bodyPointer: UnsafeCvBodyPointer {
mutating get { return CvXSUBANY(&self).pointee.any_ptr.assumingMemoryBound(to: CvBody.self) }
mutating set { CvXSUBANY(&self).pointee.any_ptr = UnsafeMutableRawPointer(newValue) }
}
}
struct UnsafeCvContext {
let cv: UnsafeCvPointer
let perl: PerlInterpreter
private static var mgvtbl = MGVTBL(
svt_get: nil,
svt_set: nil,
svt_len: nil,
svt_clear: nil,
svt_free: {
(perl, sv, magic) in
let bodyPointer = UnsafeMutableRawPointer(sv!).assumingMemoryBound(to: CV.self).pointee.bodyPointer
bodyPointer.deinitialize(count: 1)
bodyPointer.deallocate()
return 0
},
svt_copy: nil,
svt_dup: nil,
svt_local: nil
)
static func new(name: String? = nil, file: StaticString = #file, body: @escaping CvBody, perl: PerlInterpreter) -> UnsafeCvContext {
func newXS(_ name: UnsafePointer<CChar>?) -> UnsafeCvPointer {
return perl.pointee.newXS_flags(name, cvResolver, file.description, nil, UInt32(XS_DYNAMIC_FILENAME))
}
let cv = name?.withCString(newXS) ?? newXS(nil)
cv.withMemoryRebound(to: SV.self, capacity: 1) {
_ = perl.pointee.sv_magicext($0, nil, PERL_MAGIC_ext, &mgvtbl, nil, 0)
}
let bodyPointer = UnsafeCvBodyPointer.allocate(capacity: 1)
bodyPointer.initialize(to: body)
cv.pointee.bodyPointer = bodyPointer
return UnsafeCvContext(cv: cv, perl: perl)
}
var name: String? {
guard let gv = perl.pointee.CvGV(cv) else { return nil }
return String(cString: GvNAME(gv))
}
var fullname: String? {
guard let name = name else { return nil }
guard let gv = perl.pointee.CvGV(cv), let stash = GvSTASH(gv), let hvn = HvNAME(stash) else { return name }
return "\(String(cString: hvn))::\(name)"
}
var file: String? {
return CvFILE(cv).map { String(cString: $0) }
}
}
extension UnsafeCvContext {
init(dereference svc: UnsafeSvContext) throws {
guard let rvc = svc.referent, rvc.type == SVt_PVCV else {
throw PerlError.unexpectedValueType(fromUnsafeSvContext(inc: svc), want: PerlSub.self)
}
self.init(rebind: rvc)
}
init(rebind svc: UnsafeSvContext) {
let cv = UnsafeMutableRawPointer(svc.sv).bindMemory(to: CV.self, capacity: 1)
self.init(cv: cv, perl: svc.perl)
}
}
let PERL_MAGIC_ext = Int32(UnicodeScalar("~").value) // mg_vtable.h
private func cvResolver(perl: PerlInterpreter.Pointer, cv: UnsafeCvPointer) -> Void {
let perl = PerlInterpreter(perl)
let errsv: UnsafeSvPointer?
do {
let stack = UnsafeXSubStack(perl: perl)
try cv.pointee.bodyPointer.pointee(stack)
errsv = nil
} catch PerlError.died(let scalar) {
errsv = scalar.withUnsafeSvContext { UnsafeSvContext.new(copy: $0).mortal() }
} catch let error as PerlScalarConvertible {
let usv = error._toUnsafeSvPointer(perl: perl)
errsv = perl.pointee.sv_2mortal(usv)
} catch {
errsv = "\(error)".withCString { error in
let name = UnsafeCvContext(cv: cv, perl: perl).fullname ?? "__ANON__"
return name.withCString { name in
withVaList([name, error]) { perl.pointee.vmess("Exception in %s: %s", unsafeBitCast($0, to: UnsafeMutablePointer.self)) }
}
}
}
if let e = errsv {
perl.pointee.croak_sv(e)
// croak_sv() function never returns. It unwinds stack instead.
// No memory managment SIL operations should exist after it.
// Check it using --emit-sil if modification of this function required.
}
}
| mit | a4fb5a707b278f15fd4850b980787968 | 31.898148 | 133 | 0.712919 | 2.968254 | false | false | false | false |
Crisfole/SwiftWeather | SwiftWeather/WeatherViewController.swift | 2 | 1379 | //
// WeatherViewController.swift
// SwiftWeather
//
// Created by Jake Lin on 8/18/15.
// Copyright © 2015 Jake Lin. All rights reserved.
//
import UIKit
class WeatherViewController: UIViewController {
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var iconLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet var forecastViews: [ForecastView]!
override func viewDidLoad() {
super.viewDidLoad()
viewModel = WeatherViewModel()
viewModel?.startLocationService()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: ViewModel
var viewModel: WeatherViewModel? {
didSet {
viewModel?.location.observe {
[unowned self] in
self.locationLabel.text = $0
}
viewModel?.iconText.observe {
[unowned self] in
self.iconLabel.text = $0
}
viewModel?.temperature.observe {
[unowned self] in
self.temperatureLabel.text = $0
}
viewModel?.forecasts.observe {
[unowned self] (let forecastViewModels) in
if forecastViewModels.count >= 4 {
for (index, forecastView) in self.forecastViews.enumerate() {
forecastView.loadViewModel(forecastViewModels[index])
}
}
}
}
}
}
| mit | 5991dbfec7c1bbf54bcc1b5742268811 | 23.175439 | 71 | 0.648041 | 4.655405 | false | false | false | false |
SebastienVProject/openjarvis-ios | openjarvis/ViewController.swift | 1 | 10021 | //
// ViewController.swift
// openjarvis
//
// Created by utilisateur on 04/06/2017.
// Copyright © 2017 SVInfo. All rights reserved.
//
import UIKit
import Speech
import SwiftyPlistManager
class ViewController: UIViewController, SFSpeechRecognizerDelegate {
static var urljarvis: String!
static var portjarvis: String!
static var audioServeur: Bool!
static var audioApplication: Bool!
static var fontSize: Int!
static var fontSizeJarvis: Int!
static var fontStyle: String!
static var fontStyleJarvis: String!
static var keyAPIJarvis: String?
static var gitAPIKey: String!
static var heightContainer: Double!
@IBOutlet weak var imageJarvis: UIImageView!
@IBOutlet var containerView: UIView!
@IBOutlet weak var microphoneButton: UIButton!
@IBOutlet weak var scrollVue: UIScrollView!
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var MessageVue: UIView!
@IBOutlet weak var labelMenuHelp: UIBarButtonItem!
@IBOutlet weak var labelMenuParameter: UIBarButtonItem!
var HandleDeleteAllBubble: ((UIAlertAction?) -> Void)!
let speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: NSLocalizedString("codeLangue", comment: "Language code for speech recognizer")))!
var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
var recognitionTask: SFSpeechRecognitionTask?
let audioEngine = AVAudioEngine()
var whatIwant = ""
override func viewDidLoad() {
super.viewDidLoad()
labelMenuHelp.title = NSLocalizedString("labelMenuHelp", comment: "Help label")
labelMenuParameter.title = NSLocalizedString("labelMenuParameter", comment: "Parameter label")
microphoneButton.isEnabled = false
speechRecognizer.delegate = self
SFSpeechRecognizer.requestAuthorization { (authStatus) in
var isButtonEnabled = false
switch authStatus {
case .authorized:
isButtonEnabled = true
case .denied:
isButtonEnabled = false
print("User denied access to speech recognition")
case .restricted:
isButtonEnabled = false
print("Speech recognition restricted on this device")
case .notDetermined:
isButtonEnabled = false
print("Speech recognition not yet authorized")
}
OperationQueue.main.addOperation() {
self.microphoneButton.isEnabled = isButtonEnabled
}
}
//on recupere les parametres de l'applicatif
SwiftyPlistManager.shared.getValue(for: "urlJarvis", fromPlistWithName: "parametres") { (result, err) in
if err == nil {
ViewController.urljarvis = result as! String
}
}
SwiftyPlistManager.shared.getValue(for: "portJarvis", fromPlistWithName: "parametres") { (result, err) in
if err == nil {
ViewController.portjarvis = result as! String
}
}
SwiftyPlistManager.shared.getValue(for: "audioApplication", fromPlistWithName: "parametres") { (result, err) in
if err == nil {
ViewController.audioApplication = result as! Bool
}
}
SwiftyPlistManager.shared.getValue(for: "audioServeur", fromPlistWithName: "parametres") { (result, err) in
if err == nil {
ViewController.audioServeur = result as! Bool
}
}
SwiftyPlistManager.shared.getValue(for: "fontSize", fromPlistWithName: "parametres") { (result, err) in
if err == nil {
ViewController.fontSize = result as! Int
}
}
SwiftyPlistManager.shared.getValue(for: "fontSizeJarvis", fromPlistWithName: "parametres") { (result, err) in
if err == nil {
ViewController.fontSizeJarvis = result as! Int
}
}
SwiftyPlistManager.shared.getValue(for: "fontStyle", fromPlistWithName: "parametres") { (result, err) in
if err == nil {
ViewController.fontStyle = result as! String
}
}
SwiftyPlistManager.shared.getValue(for: "fontStyleJarvis", fromPlistWithName: "parametres") { (result, err) in
if err == nil {
ViewController.fontStyleJarvis = result as! String
}
}
SwiftyPlistManager.shared.getValue(for: "keyApiJarvis", fromPlistWithName: "parametres") { (result, err) in
if err == nil {
ViewController.keyAPIJarvis = result as? String
}
}
SwiftyPlistManager.shared.getValue(for: "gitApiKey", fromPlistWithName: "parametresGitIgnore") { (result, err) in
if err == nil {
ViewController.gitAPIKey = result as? String
}
}
ViewController.heightContainer = 10
/*
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.extraLight)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = imageJarvis.bounds
imageJarvis.addSubview(blurEffectView)
*/
let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.handleLongPress(_:)))
lpgr.minimumPressDuration = 1.2
scrollVue.addGestureRecognizer(lpgr)
HandleDeleteAllBubble = { (action: UIAlertAction!) -> Void in
while self.containerView.subviews.count > 0 {
self.containerView.subviews.first?.removeFromSuperview()
}
ViewController.heightContainer = 10
}
}
func handleLongPress(_ gesture: UILongPressGestureRecognizer){
if gesture.state != .began { return }
let alert = UIAlertController(title: NSLocalizedString("deletePopupTitle", comment: "title of the popup to delete conversation"), message: NSLocalizedString("deletePopupMessage", comment: "message of the popup to delete conversation"), preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("actionDelete", comment: "Delete action"), style: UIAlertActionStyle.destructive, handler: HandleDeleteAllBubble))
alert.addAction(UIAlertAction(title: NSLocalizedString("actionCancel", comment: "Cancel action"), style: UIAlertActionStyle.cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
@IBAction func microphoneTapped(_ sender: AnyObject) {
if audioEngine.isRunning {
audioEngine.stop()
recognitionRequest?.endAudio()
microphoneButton.isEnabled = false
microphoneButton.setTitle("Start Recording", for: .normal)
microphoneButton.setImage(UIImage(named: "micro.png"), for: .normal)
} else {
startRecording()
microphoneButton.setTitle("Stop Recording", for: .normal)
microphoneButton.setImage(UIImage(named: "microON.png"), for: .normal)
}
}
func startRecording() {
if recognitionTask != nil {
recognitionTask?.cancel()
recognitionTask = nil
}
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try audioSession.setMode(AVAudioSessionModeMeasurement)
try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
} catch {
print("audioSession properties weren't set because of an error.")
}
recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
guard let inputNode = audioEngine.inputNode else {
fatalError("Audio engine has no input node")
}
guard let recognitionRequest = recognitionRequest else {
fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object")
}
recognitionRequest.shouldReportPartialResults = true
recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in
var isFinal = false
if result != nil {
self.textView.text = result?.bestTranscription.formattedString
//self.whatIwant = result?.bestTranscription.formattedString
isFinal = (result?.isFinal)!
}
if error != nil || isFinal {
self.audioEngine.stop()
inputNode.removeTap(onBus: 0)
self.recognitionRequest = nil
self.recognitionTask = nil
self.microphoneButton.isEnabled = true
TraiterDemande(bulleText: self.textView.text, containerVue: self.containerView, scrollVue: self.scrollVue, messageVue: self.MessageVue)
}
})
let recordingFormat = inputNode.outputFormat(forBus: 0)
inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
self.recognitionRequest?.append(buffer)
}
audioEngine.prepare()
do {
try audioEngine.start()
} catch {
print("audioEngine couldn't start because of an error.")
}
textView.text = ""
}
func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
if available {
microphoneButton.isEnabled = true
} else {
microphoneButton.isEnabled = false
}
}
}
| mit | 3d412694be3e6d09cbcfb2cd7b6b976f | 38.294118 | 289 | 0.613573 | 5.572859 | false | false | false | false |
hpsoar/Today | Today/ViewUtility.swift | 1 | 1236 | //
// ViewUtility.swift
// Today
//
// Created by HuangPeng on 8/16/14.
// Copyright (c) 2014 beacon. All rights reserved.
//
import UIKit
extension UIView {
convenience init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) {
self.init(frame: CGRectMake(x, y, width, height))
}
func snapshot() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.frame.size, false, 0)
self.layer.renderInContext(UIGraphicsGetCurrentContext())
var image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image;
}
func drawLine(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) {
var context = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(context, x1, y1)
CGContextAddLineToPoint(context, x2, y2)
}
}
typealias UIViewPointer = AutoreleasingUnsafePointer<UIView?>
extension UIColor {
class func color(hexColor: NSInteger) -> UIColor! {
var r = CGFloat((hexColor >> 16) & 0xFF) / 255.5
var g = CGFloat((hexColor >> 8) & 0xFF) / 255.5
var b = CGFloat(hexColor & 0xFF) / 255.5
return UIColor(red: r, green: g, blue: b, alpha: 1)
}
}
| gpl-2.0 | 6cc675defcbc846d85d9c481bfb00f8b | 28.428571 | 79 | 0.63835 | 4.12 | false | false | false | false |
dfortuna/theCraic3 | theCraic3/Main/New Event/NewEventDetailsTableViewCell.swift | 1 | 5873 | //
// NewEventDetailsTableViewCell.swift
// theCraic3
//
// Created by Denis Fortuna on 13/5/18.
// Copyright © 2018 Denis. All rights reserved.
//
import UIKit
protocol DetailsProtocol: class {
func detailAdded(sender: NewEventDetailsTableViewCell)
}
class NewEventDetailsTableViewCell: UITableViewCell, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
@IBOutlet weak var eventNameTextField: UITextField!
@IBOutlet weak var addressTextField: UITextField!
@IBOutlet weak var categoryImageView: UIImageView!
@IBOutlet weak var categoryPickerTextField: UITextField!
@IBOutlet weak var pricePickerTextField: UITextField!
@IBOutlet weak var datePickerTextField: UITextField!
@IBOutlet weak var categoryQuestionLabel: UILabel!
@IBOutlet weak var priceDollarLabel: UILabel!
@IBOutlet weak var publicPostSwitchOutlet: UISwitch!
var isPublic = false
private var model = UserModel()
weak var delegate: DetailsProtocol?
private var categoryPicker = UIPickerView()
private let datePicker = UIDatePicker()
private var pricePicker = UIPickerView()
func formatUI(event: Event) {
eventNameTextField.delegate = self
addressTextField.delegate = self
createCategoryPicker()
createpricePicker()
categoryImageView.layer.cornerRadius = 5
categoryImageView.layer.masksToBounds = true
publicPostSwitchOutlet.addTarget(self, action: #selector(publicPostSwitch), for: UIControlEvents.touchUpInside)
loadData(event: event)
}
func loadData(event: Event) {
publicPostSwitchOutlet.setOn(event.isPublicEvent, animated: false)
if (event.eventCategory != "-- Select --") && (event.eventCategory != "") {
let (categoryImage, categoryColor) = model.getImagesForCategory(category: event.eventCategory)
categoryImageView.alpha = 1
categoryImageView.image = categoryImage
categoryImageView.tintColor = categoryColor
categoryQuestionLabel.alpha = 0
}
eventNameTextField.text = event.eventName
addressTextField.text = event.eventAddress
datePickerTextField.text = event.eventDate
categoryPickerTextField.text = event.eventCategory
pricePickerTextField.text = event.eventprice
}
@objc func publicPostSwitch(_ sender: UISwitch) {
if sender.isOn {
self.isPublic = true
} else {
self.isPublic = false
}
delegate?.detailAdded(sender: self)
}
@IBAction func dateTextFieldAction(_ sender: UITextField) {
let datePickerView:UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.dateAndTime
sender.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(self.datePickerValueChanged), for: UIControlEvents.valueChanged)
}
@objc func datePickerValueChanged(sender:UIDatePicker) {
let dateString = sender.date.getDateAndTimeStringFromDate()
datePickerTextField.text = dateString
delegate?.detailAdded(sender: self)
datePickerTextField.resignFirstResponder()
}
func createCategoryPicker() {
categoryPicker.tag = 1
categoryPicker.delegate = self
categoryPicker.dataSource = self
categoryPickerTextField.inputView = categoryPicker
}
func createpricePicker() {
pricePicker.tag = 2
pricePicker.delegate = self
pricePicker.dataSource = self
pricePickerTextField.inputView = pricePicker
}
// MARK: - PickerView Delegate
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView.tag == 1 {
return model.categories[row]
} else if pickerView.tag == 2 {
return model.priceRange[row]
}
return ""
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView.tag == 1 {
return model.categories.count
} else if pickerView.tag == 2 {
return model.priceRange.count
}
return 0
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView.tag == 1 {
formatCategoryTextField(fromRow: row)
} else if pickerView.tag == 2 {
formatPriceTextField(fromRow: row)
}
}
func formatPriceTextField(fromRow row: Int) {
let selected = model.priceRange[row]
if selected != "-- Select --" {
priceDollarLabel.text = model.getPrice(price: selected)
pricePickerTextField.text = model.priceRange[row]
delegate?.detailAdded(sender: self)
pricePickerTextField.resignFirstResponder()
}
}
func formatCategoryTextField(fromRow row: Int) {
let selected = model.categories[row]
if selected != "-- Select --" {
categoryPickerTextField.text = model.categories[row]
guard let eventCategory = categoryPickerTextField.text else { return }
let (categoryImage, categoryColor) = model.getImagesForCategory(category: eventCategory)
categoryImageView.alpha = 1
categoryImageView.image = categoryImage
categoryImageView.tintColor = categoryColor
categoryQuestionLabel.alpha = 0
delegate?.detailAdded(sender: self)
categoryPickerTextField.resignFirstResponder()
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
delegate?.detailAdded(sender: self)
}
}
| apache-2.0 | 73bf6a410b233ec72b88a361d9cef31f | 36.164557 | 121 | 0.666894 | 5.224199 | false | false | false | false |
yeziahehe/Gank | Pods/LeanCloud/Sources/Storage/CQLClient.swift | 1 | 3503 | //
// CQLClient.swift
// LeanCloud
//
// Created by Tang Tianyong on 5/30/16.
// Copyright © 2016 LeanCloud. All rights reserved.
//
import Foundation
/**
A type represents the result value of CQL execution.
*/
public final class LCCQLValue {
let response: LCResponse
init(response: LCResponse) {
self.response = response
}
var results: [[String: Any]] {
return (response.results as? [[String: Any]]) ?? []
}
var className: String {
return response["className"] ?? LCObject.objectClassName()
}
/**
Get objects for object query.
*/
public var objects: [LCObject] {
let results = self.results
let className = self.className
do {
let objects = try results.map { dictionary in
try ObjectProfiler.shared.object(dictionary: dictionary, className: className)
}
return objects
} catch {
return []
}
}
/**
Get count value for count query.
*/
public var count: Int {
return response.count
}
}
/**
CQL client.
CQLClient allow you to use CQL (Cloud Query Language) to make CRUD for object.
*/
public final class LCCQLClient {
static let endpoint = "cloudQuery"
/**
Assemble parameters for CQL execution.
- parameter cql: The CQL statement.
- parameter parameters: The parameters for placeholders in CQL statement.
- returns: The parameters for CQL execution.
*/
static func parameters(_ cql: String, parameters: LCArrayConvertible?) -> [String: Any] {
var result = ["cql": cql]
if let parameters = parameters?.lcArray {
if !parameters.isEmpty {
result["pvalues"] = Utility.jsonString(parameters.lconValue!)
}
}
return result
}
/**
Execute CQL statement synchronously.
- parameter cql: The CQL statement to be executed.
- parameter parameters: The parameters for placeholders in CQL statement.
- returns: The result of CQL statement.
*/
public static func execute(_ cql: String, parameters: LCArrayConvertible? = nil) -> LCCQLResult {
return expect { fulfill in
execute(cql, parameters: parameters, completionInBackground: { result in
fulfill(result)
})
}
}
/**
Execute CQL statement asynchronously.
- parameter cql: The CQL statement to be executed.
- parameter parameters: The parameters for placeholders in CQL statement.
- parameter completion: The completion callback closure.
*/
public static func execute(_ cql: String, parameters: LCArrayConvertible? = nil, completion: @escaping (_ result: LCCQLResult) -> Void) -> LCRequest {
return execute(cql, parameters: parameters, completionInBackground: { result in
mainQueueAsync {
completion(result)
}
})
}
@discardableResult
private static func execute(_ cql: String, parameters: LCArrayConvertible? = nil, completionInBackground completion: @escaping (LCCQLResult) -> Void) -> LCRequest {
let parameters = self.parameters(cql, parameters: parameters)
let request = HTTPClient.default.request(.get, endpoint, parameters: parameters) { response in
let result = LCCQLResult(response: response)
completion(result)
}
return request
}
}
| gpl-3.0 | 4f4a4047354430fa4bf914b4099ffe56 | 27.241935 | 168 | 0.617647 | 4.58377 | false | false | false | false |
yanniks/Robonect-iOS | Robonect/Views/Engines/EngineViewController.swift | 1 | 5049 | //
// Copyright (C) 2017 Yannik Ehlert.
//
// 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.
//
//
// EngineViewController.swift
// Robonect
//
// Created by Yannik Ehlert on 07.06.17.
//
import UIKit
class EngineViewController: UIViewController {
@IBOutlet weak var labelPowerStageLeft: UILabel!
@IBOutlet weak var labelPowerStageRight: UILabel!
@IBOutlet weak var labelSpeedLeft: UILabel!
@IBOutlet weak var labelSpeedRight: UILabel!
@IBOutlet weak var labelCurrentLeft: UILabel!
@IBOutlet weak var labelCurrentRight: UILabel!
@IBOutlet weak var labelBladeMotorSpeed: UILabel!
@IBOutlet weak var labelBladeMotorCurrent: UILabel!
@IBOutlet weak var progressPowerStageLeft: UIProgressView!
@IBOutlet weak var progressPowerStageRight: UIProgressView!
@IBOutlet weak var progressSpeedLeft: UIProgressView!
@IBOutlet weak var progressSpeedRight: UIProgressView!
@IBOutlet weak var progressCurrentLeft: UIProgressView!
@IBOutlet weak var progressCurrentRight: UIProgressView!
@IBOutlet weak var progressBladeMotorSpeed: UIProgressView!
@IBOutlet weak var progressBladeMotorCurrent: UIProgressView!
@IBOutlet weak var valuePowerStageLeft: UILabel!
@IBOutlet weak var valuePowerStageRight: UILabel!
@IBOutlet weak var valueSpeedLeft: UILabel!
@IBOutlet weak var valueSpeedRight: UILabel!
@IBOutlet weak var valueCurrentLeft: UILabel!
@IBOutlet weak var valueCurrentRight: UILabel!
@IBOutlet weak var valueBladeMotorSpeed: UILabel!
@IBOutlet weak var valueBladeMotorCurrent: UILabel!
private var engine : RobonectAPIResponse.Engine? = nil
private var timer : Timer? = nil
override func viewDidLoad() {
super.viewDidLoad()
title = "Engines"
fetchData()
}
func fetchData() {
NetworkingRequest.fetchEngine(mower: SharedSettings.shared.mower) { callback in
if !callback.isSuccessful {
ShowMessage.showMessage(message: .actionFailed)
}
if let engine = callback.value {
self.engine = engine
DispatchQueue.main.async {
self.updateValues()
}
}
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
timer?.invalidate()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(EngineViewController.fetchData), userInfo: nil, repeats: true)
}
func updateValues() {
progressPowerStageLeft.progress = abs(Float(engine?.pdrvpercentl ?? 0) / 100)
valuePowerStageLeft.text = String(engine?.pdrvpercentl ?? 0) + " %"
progressPowerStageRight.progress = abs(Float(engine?.pdrvpercentr ?? 0) / 100)
valuePowerStageRight.text = String(engine?.pdrvpercentr ?? 0) + " %"
progressSpeedLeft.progress = abs(Float(engine?.pdrvspeedl ?? 0) / 100)
valueSpeedLeft.text = String(engine?.pdrvspeedl ?? 0) + " cm/s"
progressSpeedRight.progress = abs(Float(engine?.pdrvspeedr ?? 0) / 100)
valueSpeedRight.text = String(engine?.pdrvspeedr ?? 0) + " cm/s"
progressCurrentLeft.progress = abs(Float(engine?.pdrvcurrentl ?? 0) / 100) * 0.2
valueCurrentLeft.text = String(engine?.pdrvcurrentl ?? 0) + " mA"
progressCurrentRight.progress = abs(Float(engine?.pdrvcurrentr ?? 0) / 100) * 0.2
valueCurrentRight.text = String(engine?.pdrvcurrentr ?? 0) + " mA"
progressBladeMotorSpeed.progress = abs(Float(engine?.pcutspeed ?? 0) / 100) * 0.02843439534
valueBladeMotorSpeed.text = String(engine?.pcutspeed ?? 0) + " RPM"
progressBladeMotorCurrent.progress = abs(Float(engine?.pcutcurrent ?? 0) / 100) * 0.2
valueBladeMotorCurrent.text = String(engine?.pcutcurrent ?? 0) + " mA"
}
}
| mit | 9f5173d9f1d15fad12ec77ee782c5a1b | 44.9 | 150 | 0.691622 | 4.214524 | false | false | false | false |
chenchangqing/travelMapMvvm | travelMapMvvm/travelMapMvvm/Views/Map/BasicMapAnnotationView.swift | 1 | 1059 | //
// BasicMapAnnotationView2.swift
// travelMap
//
// Created by green on 15/7/22.
// Copyright (c) 2015年 com.city8. All rights reserved.
//
import UIKit
class BasicMapAnnotationView: MKAnnotationView {
var indexL: UILabel!
override init!(annotation: MKAnnotation!, reuseIdentifier: String!) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
self.frame = CGRectMake(0, 0, 16, 16)
let circleV = GCircleControl(frame: CGRectMake(0, 0, 16, 16))
circleV.fillColor = UIColor.yellowColor()
circleV.borderWidth = 0
indexL = UILabel(frame: CGRectMake(0, 0, 16, 16))
indexL.textAlignment = NSTextAlignment.Center
indexL.font = UIFont.systemFontOfSize(14)
self.addSubview(circleV)
self.addSubview(indexL)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 3c2a4b76250fc34555c06ecc562447ab | 27.567568 | 77 | 0.631977 | 4.128906 | false | false | false | false |
reactive-swift/Future | Package.swift | 1 | 948 | //===--- Package.swift ----------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//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 PackageDescription
let package = Package(
name: "Future",
dependencies: [
.Package(url: "https://github.com/reactive-swift/Event.git", majorVersion: 0, minor: 2)
]
)
| apache-2.0 | 2257252f99c2482f56a6b3a5352cf01b | 38.5 | 95 | 0.621308 | 4.647059 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/UI/Challenges/Details/ChallengeDetailViewModel.swift | 1 | 21588 | //
// ChallengeDetailViewModel.swift
// Habitica
//
// Created by Elliot Schrock on 10/17/17.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import UIKit
import ReactiveSwift
import Habitica_Models
enum ChallengeButtonState {
case uninitialized, join, leave, publishDisabled, publishEnabled, viewParticipants, endChallenge
}
protocol ChallengeDetailViewModelInputs {
func viewDidLoad()
func setChallenge(_ challenge: ChallengeProtocol)
}
protocol ChallengeDetailViewModelOutputs {
var cellModelsSignal: Signal<[MultiModelDataSourceSection], Never> { get }
var reloadTableSignal: Signal<Void, Never> { get }
var animateUpdatesSignal: Signal<(), Never> { get }
var nextViewControllerSignal: Signal<UIViewController, Never> { get }
}
protocol ChallengeDetailViewModelProtocol {
var inputs: ChallengeDetailViewModelInputs { get }
var outputs: ChallengeDetailViewModelOutputs { get }
}
class ChallengeDetailViewModel: ChallengeDetailViewModelProtocol, ChallengeDetailViewModelInputs, ChallengeDetailViewModelOutputs, ResizableTableViewCellDelegate, ChallengeCreatorCellDelegate {
var inputs: ChallengeDetailViewModelInputs { return self }
var outputs: ChallengeDetailViewModelOutputs { return self }
let cellModelsSignal: Signal<[MultiModelDataSourceSection], Never>
let reloadTableSignal: Signal<Void, Never>
let animateUpdatesSignal: Signal<(), Never>
let nextViewControllerSignal: Signal<UIViewController, Never>
let challengeID: String?
let challengeProperty: MutableProperty<ChallengeProtocol?>
let challengeMembershipProperty = MutableProperty<ChallengeMembershipProtocol?>(nil)
let challengeCreatorProperty = MutableProperty<MemberProtocol?>(nil)
let viewDidLoadProperty = MutableProperty(())
let reloadTableProperty = MutableProperty(())
let animateUpdatesProperty = MutableProperty(())
let nextViewControllerProperty = MutableProperty<UIViewController?>(nil)
let cellModelsProperty: MutableProperty<[MultiModelDataSourceSection]> = MutableProperty<[MultiModelDataSourceSection]>([])
let infoSectionProperty: MutableProperty<MultiModelDataSourceSection> = MutableProperty<MultiModelDataSourceSection>(MultiModelDataSourceSection())
let habitsSectionProperty: MutableProperty<MultiModelDataSourceSection> = MutableProperty<MultiModelDataSourceSection>(MultiModelDataSourceSection())
let dailiesSectionProperty: MutableProperty<MultiModelDataSourceSection> = MutableProperty<MultiModelDataSourceSection>(MultiModelDataSourceSection())
let todosSectionProperty: MutableProperty<MultiModelDataSourceSection> = MutableProperty<MultiModelDataSourceSection>(MultiModelDataSourceSection())
let rewardsSectionProperty: MutableProperty<MultiModelDataSourceSection> = MutableProperty<MultiModelDataSourceSection>(MultiModelDataSourceSection())
let endSectionProperty: MutableProperty<MultiModelDataSourceSection> = MutableProperty<MultiModelDataSourceSection>(MultiModelDataSourceSection())
let mainButtonItemProperty: MutableProperty<ButtonCellMultiModelDataSourceItem?> = MutableProperty<ButtonCellMultiModelDataSourceItem?>(nil)
let endButtonItemProperty: MutableProperty<ButtonCellMultiModelDataSourceItem?> = MutableProperty<ButtonCellMultiModelDataSourceItem?>(nil)
let doubleEndButtonItemProperty: MutableProperty<DoubleButtonMultiModelDataSourceItem?> = MutableProperty<DoubleButtonMultiModelDataSourceItem?>(nil)
let joinLeaveStyleProvider: JoinLeaveButtonAttributeProvider
let publishStyleProvider: PublishButtonAttributeProvider
let participantsStyleProvider: ParticipantsButtonAttributeProvider
let endChallengeStyleProvider: EndChallengeButtonAttributeProvider
var joinInteractor: JoinChallengeInteractor?
var leaveInteractor: LeaveChallengeInteractor?
private let socialRepository = SocialRepository()
private let disposable = ScopedDisposable(CompositeDisposable())
init(challenge: ChallengeProtocol) {
self.challengeID = challenge.id
challengeProperty = MutableProperty<ChallengeProtocol?>(challenge)
reloadTableSignal = reloadTableProperty.signal
animateUpdatesSignal = animateUpdatesProperty.signal
nextViewControllerSignal = nextViewControllerProperty.signal.skipNil()
self.joinInteractor = JoinChallengeInteractor()
if let viewController = UIApplication.shared.keyWindow?.visibleController() {
self.leaveInteractor = LeaveChallengeInteractor(presentingViewController: viewController)
}
joinLeaveStyleProvider = JoinLeaveButtonAttributeProvider(challenge)
publishStyleProvider = PublishButtonAttributeProvider(challenge)
participantsStyleProvider = ParticipantsButtonAttributeProvider(challenge)
endChallengeStyleProvider = EndChallengeButtonAttributeProvider(challenge)
let initialCellModelsSignal = cellModelsProperty.signal.sample(on: viewDidLoadProperty.signal)
cellModelsSignal = Signal.merge(cellModelsProperty.signal, initialCellModelsSignal)
setup(challenge: challenge)
reloadChallenge()
}
init(challengeID: String) {
self.challengeID = challengeID
challengeProperty = MutableProperty<ChallengeProtocol?>(nil)
reloadTableSignal = reloadTableProperty.signal
animateUpdatesSignal = animateUpdatesProperty.signal
nextViewControllerSignal = nextViewControllerProperty.signal.skipNil()
joinLeaveStyleProvider = JoinLeaveButtonAttributeProvider(nil)
publishStyleProvider = PublishButtonAttributeProvider(nil)
participantsStyleProvider = ParticipantsButtonAttributeProvider(nil)
endChallengeStyleProvider = EndChallengeButtonAttributeProvider(nil)
let initialCellModelsSignal = cellModelsProperty.signal.sample(on: viewDidLoadProperty.signal)
cellModelsSignal = Signal.merge(cellModelsProperty.signal, initialCellModelsSignal)
setup(challenge: nil)
reloadChallenge()
}
private func setup(challenge: ChallengeProtocol?) {
Signal.combineLatest(infoSectionProperty.signal,
habitsSectionProperty.signal,
dailiesSectionProperty.signal,
todosSectionProperty.signal,
rewardsSectionProperty.signal,
endSectionProperty.signal)
.map { sectionTuple -> [MultiModelDataSourceSection] in
return [sectionTuple.0, sectionTuple.1, sectionTuple.2, sectionTuple.3, sectionTuple.4, sectionTuple.5]
}
.observeValues {[weak self] sections in
self?.cellModelsProperty.value = sections.filter { $0.items?.count ?? 0 > 0 }
}
setupInfo()
setupButtons()
challengeProperty.signal.observeValues {[weak self] newChallenge in
self?.joinLeaveStyleProvider.challengeProperty.value = newChallenge
self?.publishStyleProvider.challengeProperty.value = newChallenge
self?.participantsStyleProvider.challengeProperty.value = newChallenge
self?.endChallengeStyleProvider.challengeProperty.value = newChallenge
}
challengeMembershipProperty.signal.observeValues {[weak self] (membership) in
self?.joinLeaveStyleProvider.challengeMembershipProperty.value = membership
}
joinLeaveStyleProvider.challengeUpdatedProperty.signal.observeValues {[weak self] _ in
self?.reloadChallenge()
}
joinLeaveStyleProvider.buttonStateSignal.sample(on: joinLeaveStyleProvider.buttonPressedProperty.signal).observeValues { [weak self] (state) in
guard let challenge = self?.challengeProperty.value else {
return
}
if state == .join {
self?.joinInteractor?.run(with: challenge)
} else {
self?.leaveInteractor?.run(with: challenge)
}
}
}
func setupInfo() {
Signal.combineLatest(challengeProperty.signal.skipNil(), mainButtonItemProperty.signal, challengeCreatorProperty.signal)
.observeValues { (challenge, mainButtonValue, creator) in
let infoItem = ChallengeMultiModelDataSourceItem<ChallengeDetailInfoTableViewCell>(challenge, identifier: "info")
let creatorItem = ChallengeCreatorMultiModelDataSourceItem(challenge, creator: creator, cellDelegate: self, identifier: "creator")
let categoryItem = ChallengeResizableMultiModelDataSourceItem<ChallengeCategoriesTableViewCell>(challenge, resizingDelegate: self, identifier: "categories")
let descriptionItem = ChallengeResizableMultiModelDataSourceItem<ChallengeDescriptionTableViewCell>(challenge, resizingDelegate: self, identifier: "description")
let infoSection = MultiModelDataSourceSection()
if let mainButton = mainButtonValue {
infoSection.items = [infoItem, mainButton, creatorItem, categoryItem, descriptionItem]
} else {
infoSection.items = [infoItem, creatorItem, categoryItem, descriptionItem]
}
self.infoSectionProperty.value = infoSection
}
}
func setupTasks() {
disposable.inner.add(socialRepository.getChallengeTasks(challengeID: challengeProperty.value?.id ?? "").on(value: {[weak self] (tasks, _) in
let habitsSection = MultiModelDataSourceSection()
habitsSection.title = "Habits"
habitsSection.items = tasks.filter({ (task) -> Bool in
return task.type == TaskType.habit
}).map({ (task) -> MultiModelDataSourceItem in
return ChallengeTaskMultiModelDataSourceItem<HabitTableViewCell>(task, identifier: "habit")
})
self?.habitsSectionProperty.value = habitsSection
let dailiesSection = MultiModelDataSourceSection()
dailiesSection.title = "Dailies"
dailiesSection.items = tasks.filter({ (task) -> Bool in
return task.type == TaskType.daily
}).map({ (task) -> MultiModelDataSourceItem in
return ChallengeTaskMultiModelDataSourceItem<DailyTableViewCell>(task, identifier: "daily")
})
self?.dailiesSectionProperty.value = dailiesSection
let todosSection = MultiModelDataSourceSection()
todosSection.title = "Todos"
todosSection.items = tasks.filter({ (task) -> Bool in
return task.type == TaskType.todo
}).map({ (task) -> MultiModelDataSourceItem in
return ChallengeTaskMultiModelDataSourceItem<ToDoTableViewCell>(task, identifier: "todo")
})
self?.todosSectionProperty.value = todosSection
let rewardsSection = MultiModelDataSourceSection()
rewardsSection.title = "Rewards"
rewardsSection.items = tasks.filter({ (task) -> Bool in
return task.type == TaskType.reward
}).map({ (task) -> MultiModelDataSourceItem in
return RewardMultiModelDataSourceItem<ChallengeRewardTableViewCell>(task, identifier: "reward")
})
self?.rewardsSectionProperty.value = rewardsSection
}).start())
}
func setupButtons() {
let ownedChallengeSignal = challengeProperty.signal.skipNil().filter { (challenge) -> Bool in
return challenge.isOwner()
}
let unownedChallengeSignal = challengeProperty.signal.skipNil().filter { (challenge) -> Bool in
return !challenge.isOwner()
}
endButtonItemProperty.signal.skipNil().observeValues { (item) in
let endSection = MultiModelDataSourceSection()
endSection.items = [item]
self.endSectionProperty.value = endSection
}
doubleEndButtonItemProperty.signal.skipNil().observeValues { (item) in
let endSection = MultiModelDataSourceSection()
endSection.items = [item]
self.endSectionProperty.value = endSection
}
let endButtonNilSignal = endButtonItemProperty.signal.map { $0 == nil }
let doubleEndButtonNilSignal = doubleEndButtonItemProperty.signal.map { $0 == nil }
endButtonNilSignal.and(doubleEndButtonNilSignal).filter({ $0 }).observeValues({ _ in
let endSection = MultiModelDataSourceSection()
self.endSectionProperty.value = endSection
})
ownedChallengeSignal.observeValues {[weak self] _ in
self?.doubleEndButtonItemProperty.value = DoubleButtonMultiModelDataSourceItem(identifier: "endButton", leftAttributeProvider: self?.joinLeaveStyleProvider, leftInputs: self?.joinLeaveStyleProvider,
rightAttributeProvider: self?.endChallengeStyleProvider, rightInputs: self?.endChallengeStyleProvider)
}
ownedChallengeSignal
.filter({ (challenge) -> Bool in
return challenge.isPublished()
}).observeValues {[weak self] _ in
self?.mainButtonItemProperty.value = ButtonCellMultiModelDataSourceItem(attributeProvider: self?.participantsStyleProvider, inputs: self?.participantsStyleProvider, identifier: "mainButton")
}
ownedChallengeSignal
.filter({ (challenge) -> Bool in
return !challenge.isPublished()
}).observeValues {[weak self] _ in
self?.mainButtonItemProperty.value = ButtonCellMultiModelDataSourceItem(attributeProvider: self?.publishStyleProvider, inputs: self?.publishStyleProvider, identifier: "mainButton")
}
unownedChallengeSignal.observeValues { _ in
self.doubleEndButtonItemProperty.value = nil
}
challengeMembershipProperty.signal.combineLatest(with: unownedChallengeSignal)
.skipRepeats({ (first, second) -> Bool in
return (first.0 == nil) == (second.0 == nil)
})
.filter({ (membership, _) -> Bool in
return membership == nil
})
.observeValues {[weak self] _ in
self?.mainButtonItemProperty.value = ButtonCellMultiModelDataSourceItem(attributeProvider: self?.joinLeaveStyleProvider, inputs: self?.joinLeaveStyleProvider, identifier: "mainButton")
self?.endButtonItemProperty.value = nil
self?.doubleEndButtonItemProperty.value = nil
}
challengeMembershipProperty.signal.combineLatest(with: unownedChallengeSignal)
.skipRepeats({ (first, second) -> Bool in
return (first.0 == nil) == (second.0 == nil)
})
.filter({ (membership, _) -> Bool in
return membership != nil
}) .observeValues {[weak self] _ in
self?.mainButtonItemProperty.value = nil
self?.endButtonItemProperty.value = ButtonCellMultiModelDataSourceItem(attributeProvider: self?.joinLeaveStyleProvider, inputs: self?.joinLeaveStyleProvider, identifier: "mainButton")
self?.doubleEndButtonItemProperty.value = nil
}
}
func reloadChallenge() {
DispatchQueue.main.async {[weak self] in
self?.socialRepository.retrieveChallenge(challengeID: self?.challengeID ?? "").observeCompleted { }
}
}
// MARK: Resizing delegate
func cellResized() {
animateUpdatesProperty.value = ()
}
// MARK: Creator delegate
func userPressed(_ member: MemberProtocol) {
let secondStoryBoard = UIStoryboard(name: "Social", bundle: nil)
if let userViewController: UserProfileViewController = secondStoryBoard.instantiateViewController(withIdentifier: "UserProfileViewController") as? UserProfileViewController {
userViewController.userID = member.id
userViewController.username = member.profile?.name
nextViewControllerProperty.value = userViewController
}
}
func messagePressed(member: MemberProtocol) {
let secondStoryBoard = UIStoryboard(name: "Social", bundle: nil)
if let chatViewController: InboxChatViewController = secondStoryBoard.instantiateViewController(withIdentifier: "InboxChatViewController") as? InboxChatViewController {
chatViewController.userID = member.id
chatViewController.username = member.profile?.name
chatViewController.isPresentedModally = true
nextViewControllerProperty.value = chatViewController
}
}
// MARK: ChallengeDetailViewModelInputs
func viewDidLoad() {
viewDidLoadProperty.value = ()
disposable.inner.add(socialRepository.getChallenge(challengeID: challengeID ?? "")
.skipNil()
.on(value: {[weak self] challenge in
self?.setChallenge(challenge)
})
.map { challenge in
return challenge.leaderID
}
.skipNil()
.observe(on: QueueScheduler.main)
.flatMap(.latest, {[weak self] leaderID in
return self?.socialRepository.getMember(userID: leaderID, retrieveIfNotFound: true) ?? SignalProducer.empty
})
.on(value: {[weak self] creator in
self?.challengeCreatorProperty.value = creator
})
.start())
if let challengeID = self.challengeID {
disposable.inner.add(socialRepository.getChallengeMembership(challengeID: challengeID).on(value: {[weak self] membership in
self?.setChallengeMembership(membership)
}).start())
}
setupTasks()
}
func setChallenge(_ challenge: ChallengeProtocol) {
challengeProperty.value = challenge
}
func setChallengeMembership(_ membership: ChallengeMembershipProtocol?) {
challengeMembershipProperty.value = membership
}
}
// MARK: -
protocol ChallengeConfigurable {
func configure(with challenge: ChallengeProtocol)
}
// MARK: -
class ChallengeMultiModelDataSourceItem<T>: ConcreteMultiModelDataSourceItem<T> where T: UITableViewCell, T: ChallengeConfigurable {
private let challenge: ChallengeProtocol
init(_ challenge: ChallengeProtocol, identifier: String) {
self.challenge = challenge
super.init(identifier: identifier)
}
override func configureCell(_ cell: UITableViewCell) {
if let clazzCell: T = cell as? T {
clazzCell.configure(with: challenge)
}
}
}
// MARK: -
class ChallengeCreatorMultiModelDataSourceItem: ChallengeMultiModelDataSourceItem<ChallengeCreatorTableViewCell> {
private let challenge: ChallengeProtocol
private let creator: MemberProtocol?
private weak var cellDelegate: ChallengeCreatorCellDelegate?
init(_ challenge: ChallengeProtocol, creator: MemberProtocol?, cellDelegate: ChallengeCreatorCellDelegate, identifier: String) {
self.challenge = challenge
self.creator = creator
self.cellDelegate = cellDelegate
super.init(challenge, identifier: identifier)
}
override func configureCell(_ cell: UITableViewCell) {
super.configureCell(cell)
if let creatorCell = cell as? ChallengeCreatorTableViewCell {
creatorCell.delegate = cellDelegate
creatorCell.configure(member: creator)
}
}
}
// MARK: -
class ChallengeResizableMultiModelDataSourceItem<T>: ChallengeMultiModelDataSourceItem<T> where T: ChallengeConfigurable, T: ResizableTableViewCell {
weak var resizingDelegate: ResizableTableViewCellDelegate?
init(_ challenge: ChallengeProtocol, resizingDelegate: ResizableTableViewCellDelegate?, identifier: String) {
super.init(challenge, identifier: identifier)
self.resizingDelegate = resizingDelegate
}
override func configureCell(_ cell: UITableViewCell) {
super.configureCell(cell)
if let clazzCell: T = cell as? T {
clazzCell.resizingDelegate = resizingDelegate
}
}
}
// MARK: -
class ChallengeTaskMultiModelDataSourceItem<T>: ConcreteMultiModelDataSourceItem<T> where T: TaskTableViewCell {
private let challengeTask: TaskProtocol
public init(_ challengeTask: TaskProtocol, identifier: String) {
self.challengeTask = challengeTask
super.init(identifier: identifier)
}
override func configureCell(_ cell: UITableViewCell) {
if let clazzCell: T = cell as? T {
clazzCell.configure(task: challengeTask)
}
}
}
// MARK: -
class RewardMultiModelDataSourceItem<T>: ConcreteMultiModelDataSourceItem<T> where T: ChallengeRewardTableViewCell {
private let challengeTask: TaskProtocol
public init(_ challengeTask: TaskProtocol, identifier: String) {
self.challengeTask = challengeTask
super.init(identifier: identifier)
}
override func configureCell(_ cell: UITableViewCell) {
if let clazzCell: T = cell as? T {
clazzCell.configure(reward: challengeTask)
}
}
}
| gpl-3.0 | 2114f800228bb1a20ab36f239ce2f8dd | 45.027719 | 210 | 0.687636 | 5.555069 | false | false | false | false |
nathawes/swift | test/decl/protocol/conforms/fixit_stub_editor.swift | 15 | 6386 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %S/Inputs/fixit_stub_mutability_proto_module.swift -emit-module -parse-as-library -o %t
// RUN: %target-swift-frontend -typecheck %s -I %t -verify -diagnostics-editor-mode
protocol P0_A { associatedtype T }
protocol P0_B { associatedtype T }
class C0: P0_A, P0_B {} // expected-error{{type 'C0' does not conform to protocol 'P0_A'}} expected-error{{type 'C0' does not conform to protocol 'P0_B'}} expected-note{{do you want to add protocol stubs?}}{{23-23=\n typealias T = <#type#>\n}}
protocol P1 {
@available(*, deprecated)
func foo1()
func foo2()
func foo3(arg: Int, arg2: String)
func foo4<T: P1>(_: T)
}
protocol P2 {
func bar1()
func bar2()
func foo2()
func foo3(arg: Int, arg2: String)
func foo3(arg: Int, arg2: Int)
func foo4<T: P1>(_: T)
func foo4<T: P2>(_: T)
}
class C1 : P1, P2 {} // expected-error{{type 'C1' does not conform to protocol 'P1'}} expected-error{{type 'C1' does not conform to protocol 'P2'}} expected-note{{do you want to add protocol stubs?}}{{20-20=\n func foo1() {\n <#code#>\n \}\n\n func foo2() {\n <#code#>\n \}\n\n func foo3(arg: Int, arg2: String) {\n <#code#>\n \}\n\n func foo4<T>(_: T) where T : P1 {\n <#code#>\n \}\n\n func bar1() {\n <#code#>\n \}\n\n func bar2() {\n <#code#>\n \}\n\n func foo3(arg: Int, arg2: Int) {\n <#code#>\n \}\n}}
protocol P3 {
associatedtype T1
associatedtype T2
associatedtype T3
}
protocol P4 : P3 {
associatedtype T1
associatedtype T4 = T1
associatedtype T5 = T2
associatedtype T6 = T3
}
class C2 : P4 {} // expected-error{{type 'C2' does not conform to protocol 'P4'}} expected-error{{type 'C2' does not conform to protocol 'P3'}} expected-note{{do you want to add protocol stubs?}}{{16-16=\n typealias T1 = <#type#>\n\n typealias T2 = <#type#>\n\n typealias T3 = <#type#>\n}}
protocol P5 {
func foo1()
func foo2(arg: Int, arg2: String)
func foo3<T: P3>(_: T)
}
protocol P6: P5 {
func foo1()
func foo2(arg: Int, arg2: String)
func foo2(arg: Int, arg2: Int)
func foo3<T: P3>(_: T)
func foo3<T: P4>(_: T)
}
class C3 : P6 {} // expected-error{{type 'C3' does not conform to protocol 'P5'}} expected-error{{type 'C3' does not conform to protocol 'P6'}} expected-note{{do you want to add protocol stubs?}}{{16-16=\n func foo1() {\n <#code#>\n \}\n\n func foo2(arg: Int, arg2: String) {\n <#code#>\n \}\n\n func foo2(arg: Int, arg2: Int) {\n <#code#>\n \}\n\n func foo3<T>(_: T) where T : P3 {\n <#code#>\n \}\n}}
// =============================================================================
// Test how we print stubs for mutating and non-mutating requirements.
//
// - Test that we don't print 'mutating' in classes.
// - Test that we print 'non-mutating' for non-mutating setters
// in structs.
// =============================================================================
protocol MutabilityProto {
mutating func foo()
subscript() -> Int { get nonmutating set }
}
class Class1: MutabilityProto { // expected-error{{type 'Class1' does not conform to protocol 'MutabilityProto'}} expected-note{{do you want to add protocol stubs?}} {{32-32=\n func foo() {\n <#code#>\n \}\n\n subscript() -> Int {\n get {\n <#code#>\n \}\n set {\n <#code#>\n \}\n \}\n}}
}
struct Struct1: MutabilityProto { // expected-error{{type 'Struct1' does not conform to protocol 'MutabilityProto'}} expected-note{{do you want to add protocol stubs?}} {{34-34=\n mutating func foo() {\n <#code#>\n \}\n\n subscript() -> Int {\n get {\n <#code#>\n \}\n nonmutating set {\n <#code#>\n \}\n \}\n}}
}
import fixit_stub_mutability_proto_module
class Class2: ExternalMutabilityProto { // expected-error{{type 'Class2' does not conform to protocol 'ExternalMutabilityProto'}} expected-note{{do you want to add protocol stubs?}} {{40-40=\n func foo() {\n <#code#>\n \}\n\n subscript() -> Int {\n get {\n <#code#>\n \}\n set(newValue) {\n <#code#>\n \}\n \}\n}}
}
struct Struct2: ExternalMutabilityProto { // expected-error{{type 'Struct2' does not conform to protocol 'ExternalMutabilityProto'}} expected-note{{do you want to add protocol stubs?}} {{42-42=\n mutating func foo() {\n <#code#>\n \}\n\n subscript() -> Int {\n mutating get {\n <#code#>\n \}\n nonmutating set(newValue) {\n <#code#>\n \}\n \}\n}}
}
protocol PropertyMutabilityProto {
var computed: Int { mutating get nonmutating set }
var stored: Int { mutating get set }
}
class Class3: PropertyMutabilityProto { // expected-error{{type 'Class3' does not conform to protocol 'PropertyMutabilityProto'}} expected-note{{do you want to add protocol stubs?}} {{40-40=\n var computed: Int\n\n var stored: Int\n}}
}
struct Struct3: PropertyMutabilityProto { // expected-error{{type 'Struct3' does not conform to protocol 'PropertyMutabilityProto'}} expected-note{{do you want to add protocol stubs?}} {{42-42=\n var computed: Int {\n mutating get {\n <#code#>\n \}\n nonmutating set {\n <#code#>\n \}\n \}\n\n var stored: Int\n}}
}
class Class4 {}
extension Class4: PropertyMutabilityProto { // expected-error{{type 'Class4' does not conform to protocol 'PropertyMutabilityProto'}} expected-note{{do you want to add protocol stubs?}} {{44-44=\n var computed: Int {\n get {\n <#code#>\n \}\n set {\n <#code#>\n \}\n \}\n\n var stored: Int {\n get {\n <#code#>\n \}\n set {\n <#code#>\n \}\n \}\n}}
}
// https://bugs.swift.org/browse/SR-9868
protocol FooProto {
typealias CompletionType = (Int) -> Void
func doSomething(then completion: @escaping CompletionType)
}
struct FooType : FooProto { // expected-error {{type 'FooType' does not conform to protocol 'FooProto'}} expected-note {{do you want to add protocol stubs?}} {{28-28=\n func doSomething(then completion: @escaping CompletionType) {\n <#code#>\n \}\n}}
}
| apache-2.0 | 69664e02df8ce21042a95f4748f36e02 | 56.017857 | 599 | 0.57814 | 3.398616 | false | false | false | false |
vzhikserg/GoHappy | src/app/ios/KooKoo/KooKoo/SecurityViewController.swift | 1 | 1721 | //
// SecurityViewController.swift
// KooKoo
//
// Created by Channa Karunathilake on 6/25/16.
// Copyright © 2016 KooKoo. All rights reserved.
//
import UIKit
import CircleProgressBar
class SecurityViewController: UIViewController {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var securityContainer: UIView!
@IBOutlet weak var progressBar: CircleProgressBar!
let icons = ["bird", "cat", "elephant", "pig"]
override func viewDidLoad() {
super.viewDidLoad()
let img = UIImage(named: icons[Int((NSDate().timeIntervalSince1970 / 10) % 4)])?.imageWithRenderingMode(.AlwaysTemplate)
iconImageView.image = img
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
securityContainer.alpha = 0
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
securityContainer.popIn { (finished) in
self.progressBar.setProgress(0, animated: true, duration: 4)
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(5 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
let transition: CATransition = CATransition()
transition.duration = 0.15
transition.type = kCATransitionFade
self.navigationController?.view.layer.addAnimation(transition, forKey: nil)
self.navigationController?.popViewControllerAnimated(false)
}
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
securityContainer.layer.cornerRadius = securityContainer.bounds.width / 2
}
}
| bsd-2-clause | efa770deb91c524901bfce77366c2da3 | 29.175439 | 128 | 0.663953 | 4.751381 | false | false | false | false |
ashfurrow/eidolon | Kiosk/Bid Fulfillment/BidDetailsPreviewView.swift | 2 | 4039 | import UIKit
import Artsy_UILabels
import Artsy_UIButtons
import UIImageViewAligned
import RxSwift
import RxCocoa
class BidDetailsPreviewView: UIView {
let _bidDetails = Variable<BidDetails?>(nil)
var bidDetails: BidDetails? {
didSet {
self._bidDetails.value = bidDetails
}
}
@objc dynamic let artworkImageView = UIImageViewAligned()
@objc dynamic let artistNameLabel = ARSansSerifLabel()
@objc dynamic let artworkTitleLabel = ARSerifLabel()
@objc dynamic let currentBidPriceLabel = ARSerifLabel()
override func awakeFromNib() {
self.backgroundColor = .white
artistNameLabel.numberOfLines = 1
artworkTitleLabel.numberOfLines = 1
currentBidPriceLabel.numberOfLines = 1
artworkImageView.alignRight = true
artworkImageView.alignBottom = true
artworkImageView.contentMode = .scaleAspectFit
artistNameLabel.font = UIFont.sansSerifFont(withSize: 14)
currentBidPriceLabel.font = UIFont.serifBoldFont(withSize: 14)
let artwork = _bidDetails
.asObservable()
.filterNil()
.map { bidDetails in
return bidDetails.saleArtwork?.artwork
}
.take(1)
artwork
.subscribe(onNext: { [weak self] artwork in
if let url = artwork?.defaultImage?.thumbnailURL() {
self?.bidDetails?.setImage(url, self!.artworkImageView)
} else {
self?.artworkImageView.image = nil
}
})
.disposed(by: rx.disposeBag)
artwork
.map { artwork in
return artwork?.artists?.first?.name
}
.map { name in
return name ?? ""
}
.bind(to: artistNameLabel.rx.text)
.disposed(by: rx.disposeBag)
artwork
.map { artwork -> NSAttributedString in
guard let artwork = artwork else {
return NSAttributedString()
}
return artwork.titleAndDate
}
.mapToOptional()
.bind(to: artworkTitleLabel.rx.attributedText)
.disposed(by: rx.disposeBag)
_bidDetails
.asObservable()
.filterNil()
.take(1)
.map { bidDetails in
guard let cents = bidDetails.bidAmountCents.value else { return "" }
guard let currencySymbol = bidDetails.saleArtwork?.currencySymbol else { return "" }
return "Your bid: " + centsToPresentableDollarsString(cents.currencyValue, currencySymbol: currencySymbol)
}
.bind(to: currentBidPriceLabel.rx.text)
.disposed(by: rx.disposeBag)
for subview in [artworkImageView, artistNameLabel, artworkTitleLabel, currentBidPriceLabel] {
self.addSubview(subview)
}
self.constrainHeight("60")
artworkImageView.alignTop("0", leading: "0", bottom: "0", trailing: nil, to: self)
artworkImageView.constrainWidth("84")
artworkImageView.constrainHeight("60")
artistNameLabel.alignAttribute(.top, to: .top, of: self, predicate: "0")
artistNameLabel.constrainHeight("16")
artworkTitleLabel.alignAttribute(.top, to: .bottom, of: artistNameLabel, predicate: "8")
artworkTitleLabel.constrainHeight("16")
currentBidPriceLabel.alignAttribute(.top, to: .bottom, of: artworkTitleLabel, predicate: "4")
currentBidPriceLabel.constrainHeight("16")
UIView.alignAttribute(.leading, ofViews: [artistNameLabel, artworkTitleLabel, currentBidPriceLabel], to:.trailing, ofViews: [artworkImageView, artworkImageView, artworkImageView], predicate: "20")
UIView.alignAttribute(.trailing, ofViews: [artistNameLabel, artworkTitleLabel, currentBidPriceLabel], to:.trailing, ofViews: [self, self, self], predicate: "0")
}
}
| mit | 36d28bf915e44a78ee6562d8f27ff6ad | 35.387387 | 204 | 0.611538 | 5.335535 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/SensorData/GetSensorDataAsProtoOperation.swift | 1 | 2860 | /*
* Copyright 2019 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 Foundation
import third_party_sciencejournal_ios_ScienceJournalProtos
enum SensorDataExportError: Error {
/// Error fetching sensor data from the database. Associated data are the trial ID and sensor ID.
case failedToFetchDatabaseSensorData(String, String)
/// The sensor dumps recieved by dependent operations doesn't match the expected count.
case invalidSensorDumpCount
/// Error converting the sensor data proto into data.
case errorGettingDataFromProto
/// Error saving the data to disk.
case errorSavingDataToDisk
}
/// An operation that assembles sensor data dumps into a GSJScalarSensorData proto. This operation
/// requires one or more `GetTrialSensorDumpOperation`s as dependencies which provide the
/// GSJScalarSensorDataDump protos for GSJScalarSensorData.
class GetSensorDataAsProtoOperation: GSJOperation {
private let expectedSensorsCount: Int
private let saveFileURL: URL
/// Designated initializer.
///
/// - Parameters:
/// - saveFileURL: The file url where the proto should be saved.
/// - expectedSensorsCount: The expected number of sensor dumps created by dependencies.
/// Used for error checking.
init(saveFileURL: URL, expectedSensorsCount: Int) {
self.saveFileURL = saveFileURL
self.expectedSensorsCount = expectedSensorsCount
}
override func execute() {
let sensors = dependencies.compactMap { ($0 as? GetTrialSensorDumpOperation)?.dump }
// Verify the number of sensors equals the number we expected.
guard sensors.count == expectedSensorsCount else {
finish(withErrors: [SensorDataExportError.invalidSensorDumpCount])
return
}
// Don't save a proto unless there is at least one recording.
guard sensors.count > 0 else {
finish()
return
}
let sensorData = GSJScalarSensorData()
sensorData.sensorsArray = NSMutableArray(array: sensors)
guard let data = sensorData.data() else {
finish(withErrors: [SensorDataExportError.errorGettingDataFromProto])
return
}
do {
try data.write(to: saveFileURL)
} catch {
finish(withErrors: [SensorDataExportError.errorSavingDataToDisk])
return
}
finish()
}
}
| apache-2.0 | e40b8c7a15593ea587dc6703476cda52 | 33.047619 | 99 | 0.727622 | 4.5469 | false | false | false | false |
ldt25290/MyInstaMap | MyInstaMap/InstagramHelper.swift | 1 | 1533 | //
// InstagramHelper.swift
// MyMapBook
//
// Created by User on 8/30/17.
// Copyright © 2017 User. All rights reserved.
//
import Foundation
import UIKit
class InstagramHelper: NSObject {
var webView: UIWebView?
func getAccessTokenFromWebView() {
self.webView = UIWebView(frame: CGRect.init(origin: CGPoint.init(x: 0, y: 0) , size: CGSize.init(width: 200, height: 200)))
guard let myWebView = self.webView else {
return
}
myWebView.delegate = self
let url = NSURL (string: "http://www.instagram.com/oauth/authorize/?client_id=7179d974f29d414d8f596b8d0cff796c&redirect_uri=http://localhost&response_type=token&scope=basic")
let requestObj = NSURLRequest(url: url! as URL)
myWebView.loadRequest(requestObj as URLRequest)
}
deinit {
print("deinit InstagramHelper")
}
}
extension InstagramHelper: UIWebViewDelegate {
public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
print("1.2. shouldStartLoadWith request ", request.url?.absoluteString ?? "")
return true;
}
public func webViewDidStartLoad(_ webView: UIWebView) {
print(webView)
}
public func webViewDidFinishLoad(_ webView: UIWebView) {
print(webView)
}
public func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
print(error)
}
}
| mit | c16227e479d2c65580f0473306ac1ce7 | 26.854545 | 182 | 0.645561 | 4.427746 | false | false | false | false |
trungp/MulticastDelegate | MulticastDelegate/MulticastDelegate.swift | 1 | 3670 | //
// MulticastCallback.swift
// MulticastDelegate
//
// Created by TrungP1 on 4/7/16.
// Copyright © 2016 TrungP1. All rights reserved.
//
/**
* It provides a way for multiple delegates to be called, each on its own delegate queue.
* There are some versions for Objective-C on github. And this is the version for Swift.
*/
import Foundation
// Operator to compare two weakNodes
func ==(lhs: WeakNode, rhs: WeakNode) -> Bool {
return lhs.callback === rhs.callback
}
infix operator ~> {}
// Operator to perform closure on delegate
func ~> <T> (inout left: MulticastDelegate<T>?, right: ((T) -> Void)?) {
if let left = left, right = right {
left.performClosure(right)
}
}
infix operator += {}
// Operator to add delegate to multicast object
func += <T> (inout left: MulticastDelegate<T>?, right: T?) {
if let left = left, right = right {
left.addCallback(right)
}
}
func += <T> (inout left: MulticastDelegate<T>?, right: (T?, dispatch_queue_t?)?) {
if let left = left, right = right {
left.addCallback(right.0, queue: right.1)
}
}
// Operator to remove delegate from multicast object
func -= <T> (inout left: MulticastDelegate<T>?, right: T?) {
if let left = left, right = right {
left.removeCallback(right)
}
}
// This class provide the way to perform selector or notify to multiple object.
// Basically, it works like observer pattern, send message to all observer which registered with the multicast object.
// The multicast object hold the observer inside as weak storage so make sure you are not lose the object without any reason.
public class MulticastDelegate<T>: NSObject {
private var nodes: [WeakNode]?
public override init() {
super.init()
nodes = [WeakNode]()
}
/**
Ask to know number of nodes or delegates are in multicast object whhich are ready to perform selector.
- Returns Int: Number of delegates in multicast object.
*/
public func numberOfNodes() -> Int {
return nodes?.count ?? 0
}
/**
Add callback to perform selector on later.
- Parameter callback: The callback to perform selector in the future.
- Parameter queue: The queue to perform the callback on. Default is main queue
*/
public func addCallback(callback: T?, queue: dispatch_queue_t? = nil) {
// Default is main queue
let queue: dispatch_queue_t = {
guard let q = queue else { return dispatch_get_main_queue() }
return q
}()
if var nodes = nodes, let callback = callback {
let node = WeakNode(callback as? AnyObject, queue: queue)
nodes.append(node)
self.nodes = nodes
}
}
public func removeCallback(callback: T?) {
if let nodes = nodes, let cb1 = callback as? AnyObject {
self.nodes = nodes.filter { node in
if let cb = node.callback where cb === cb1 {
return false
}
return true
}
}
}
func performClosure(closure: ((T) -> Void)?) {
if let nodes = nodes, closure = closure {
nodes.forEach { node in
if let cb = node.callback as? T {
let queue: dispatch_queue_t = {
guard let q = node.queue else { return dispatch_get_main_queue() }
return q
}()
dispatch_async(queue, {
closure(cb)
})
}
}
}
}
}
| mit | c11222fdc562306d980064ba40d37916 | 29.831933 | 125 | 0.578904 | 4.362663 | false | false | false | false |
pokitdok/pokitdok-swift | pokitdok/PokitdokRequest.swift | 1 | 8835 | //
// PokitdokRequest.swift
// pokitdok
//
// Copyright (C) 2016, All Rights Reserved, PokitDok, Inc.
// https://www.pokitdok.com
//
// Please see the License.txt file for more information.
// All other rights reserved.
//
import Foundation
public class PokitdokRequest: NSObject {
/*
Class to facilitate a single HTTP request and the resulting response
Capable of packaging and transmitting all necessary parameters of the request and translating a JSON response back from the server
:VAR requestObject: URLRequest type object used to hold all request transmission information
:VAR responseObject: PokitdokResponse type object used to hold response information
*/
var requestObject: URLRequest
var responseObject: PokitdokResponse
public init(path: String, method: String = "GET", headers: Dictionary<String, String>? = nil, params: Dictionary<String, Any>? = nil, files: Array<FileData>? = nil) throws {
/*
Initialize requestObject variables
:PARAM path: String type url path for request
:PARAM method: String type http method for request, defaulted to "GET"
:PARAM headers: [String:String] type key:value headers for request
:PARAM params: [String:Any] type key:value parameters for request
:PARAM files: Array(FileData) type array of file information to accompany request
*/
requestObject = URLRequest(url: NSURL(string: path)! as URL)
responseObject = PokitdokResponse()
super.init()
requestObject.httpMethod = method
buildRequestHeaders(headers: headers)
try buildRequestBody(params: params, files: files)
}
public func call() throws -> PokitdokResponse {
/*
Send the request off and return result
:RETURNS responseObject: PokitdokResponse type holding all the response information
*/
let sema = DispatchSemaphore( value: 0 )
URLSession.shared.dataTask(with: requestObject, completionHandler: { (data, response, error) -> Void in
self.responseObject.response = response
self.responseObject.data = data
self.responseObject.error = error
if let response = response as? HTTPURLResponse {
self.responseObject.status = response.statusCode
if 200...299 ~= response.statusCode {
self.responseObject.success = true
} else if 401 ~= response.statusCode {
self.responseObject.message = "TOKEN_EXPIRED"
}
}
sema.signal() // signal request is complete
}).resume()
sema.wait() // wait for request to complete
if let data = responseObject.data {
do {
responseObject.json = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? Dictionary<String, Any>
} catch {
throw DataConversionError.FromJSON("Failed to parse JSON from data")
}
}
return responseObject
}
private func buildRequestHeaders(headers: Dictionary<String, String>? = nil){
/*
Set the header values on the requestObject
:PARAM headers: [String:Any] type key:value headers for the request
*/
if let headers = headers {
for (key, value) in headers { setHeader(key: key, value: value) }
}
}
private func buildRequestBody(params: Dictionary<String, Any>? = nil, files: Array<FileData>? = nil) throws -> Void {
/*
Create the data body of the request and set it on the requestObject
:PARAM params: [String:Any] type key:value parameters to be sent with request
:PARAM files: Array(FileData) type array of file information to be sent with request
*/
var body = Data()
if let files = files {
let boundary = "Boundary-\(UUID().uuidString)"
setHeader(key: "Content-Type", value: "multipart/form-data; boundary=\(boundary)")
if let params = params {
for (key, value) in params {
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)\r\n".data(using: .utf8)!)
}
}
for file in files {
body.append("--\(boundary)\r\n".data(using: .utf8)!)
try body.append(file.httpEncode())
}
body.append("--\(boundary)--\r\n".data(using: .utf8)!)
} else {
if let params = params {
if getMethod() == "GET" {
setPath(path: "\(getPath())?\(buildParamString(params: params))")
} else {
let contentType = getHeader(key: "Content-Type")
if contentType == "application/json" {
do {
body = try JSONSerialization.data(withJSONObject: params, options: [])
} catch {
throw DataConversionError.ToJSON("Failed to convert params to JSON")
}
} else if contentType == "application/x-www-form-urlencoded" {
body = buildParamString(params: params).data(using: .utf8)!
}
}
}
}
setBody(data: body)
}
private func buildParamString(params: Dictionary<String, Any>) -> String {
/*
Create a url safe parameter string based on a dictionary of key:values
:PARAM params: [String:Any] type to be encoded to query string
:RETURNS paramString: String type query string ex(key=val&key2=val2)
*/
var pcs = [String]()
for (key, value) in params {
var valStr = ""
if let value = value as? String {
valStr = value
} else if let value = value as? Dictionary<String, Any> {
// could use some work here
valStr = buildParamString(params: value)
} else if let value = value as? Array<String> {
// could use some work here
valStr = value.joined(separator: ",")
}
let escapedKey = key.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
let escapedValue = valStr.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
pcs.append("\(escapedKey ?? "")=\(escapedValue ?? "")")
}
return pcs.joined(separator: "&")
}
public func getHeader(key: String) -> String? {
/*
Enables user to manipulate headers from outside the class
return the header at the key from the requestObject
:PARAM key: String type header name
:RETURNS value: String? type value at header name
*/
return requestObject.value(forHTTPHeaderField: key)
}
public func setHeader(key: String, value: String){
/*
Enables user to manipulate headers from outside the class
set the header to the key: value pair
:PARAM key: String type header name
:PARAM value: String type header value
*/
requestObject.setValue(value, forHTTPHeaderField: key)
}
public func getMethod() -> String? {
/*
getter for httpMethod of requestObject
:RETURNS httpMethod: String? type http method
*/
return requestObject.httpMethod
}
public func setMethod(method: String){
/*
setter for httpMethod of requestObject
:PARAM method: String type http method, ex("GET", "POST", etc.)
*/
requestObject.httpMethod = method
}
public func getPath() -> String {
/*
getter for url of requestObject
:RETURNS url: String type url path of requestObject
*/
return (requestObject.url?.absoluteString)!
}
public func setPath(path: String){
/*
setter for url of requestObject
:PARAM path: String type to be wrapped by URL and passed to requestObject
*/
requestObject.url = NSURL(string: path)! as URL
}
public func getBody() -> Data?{
/*
getter for httpBody of the requestObject
:RETURNS httpBody: Data? type returned from httpBody
*/
return requestObject.httpBody
}
public func setBody(data: Data?){
/*
setter for httpBody of the requestObject
:PARAM data: Data? type to be sent into httpBody
*/
requestObject.httpBody = data
}
}
| mit | 8905933a41c9105f3fbd17839ff398bc | 38.797297 | 177 | 0.582683 | 4.997172 | false | false | false | false |
jmont/tutorial-TableViewFooter | TableViewFooterExample/TableViewFooter.swift | 1 | 2547 | //
// TableViewFooter.swift
// TableViewFooterExample
//
// Created by Montemayor Elosua, Juan Carlos on 7/14/15.
// Copyright (c) 2015 jmont. All rights reserved.
//
import UIKit
class TableViewFooter: UIView {
let titleLabel : UILabel
override init(frame: CGRect) {
self.titleLabel = UILabel()
super.init(frame: frame)
self.setupTitleLabel(self.titleLabel)
}
required init(coder aDecoder: NSCoder) {
self.titleLabel = UILabel()
super.init(coder: aDecoder)
self.setupTitleLabel(self.titleLabel)
}
func setupTitleLabel(label: UILabel) {
label.numberOfLines = 0
label.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(label)
self.addConstraint(NSLayoutConstraint(item: label, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 20.0))
self.addConstraint(NSLayoutConstraint(item: label, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: -20.0))
self.addConstraint(NSLayoutConstraint(item: label, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1.0, constant: -20.0))
self.addConstraint(NSLayoutConstraint(item: label, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: 20.0))
}
override func layoutSubviews() {
super.layoutSubviews()
// Don't forget to set `preferredMaxLayoutWidth` so that multiline labels work
self.titleLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.titleLabel.frame)
super.layoutSubviews()
}
}
extension UITableView {
/// @note MUST be called in UITableViewController's `-viewDidLayoutSubviews`
func layoutFooterView(footerView: TableViewFooter) {
// Since AutoLayout doesn't play well with UITableView.tableFooterView, we have to calculate the size, and then set the frame of the tableFooterView.
let calculatedHeight = footerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
let tableViewFooterFrame = CGRectMake(0, 0, CGRectGetWidth(self.frame), calculatedHeight)
if self.tableFooterView != footerView || !CGSizeEqualToSize(tableViewFooterFrame.size, footerView.frame.size) {
footerView.frame = tableViewFooterFrame
footerView.setNeedsLayout()
footerView.layoutIfNeeded()
self.tableFooterView = footerView
}
}
}
| mit | ca92eb467d4016de9ea151f56c0f2b53 | 37.014925 | 166 | 0.702002 | 4.673394 | false | false | false | false |
Havi4/Proposer | Proposer/Proposer.swift | 7 | 6290 | //
// Proposer.swift
// Lady
//
// Created by NIX on 15/7/11.
// Copyright (c) 2015年 nixWork. All rights reserved.
//
import Foundation
import AVFoundation
import Photos
import AddressBook
import CoreLocation
public enum PrivateResource {
case Photos
case Camera
case Microphone
case Contacts
public enum LocationUsage {
case WhenInUse
case Always
}
case Location(LocationUsage)
public var isNotDeterminedAuthorization: Bool {
switch self {
case .Photos:
return PHPhotoLibrary.authorizationStatus() == .NotDetermined
case .Camera:
return AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) == .NotDetermined
case .Microphone:
return AVAudioSession.sharedInstance().recordPermission() == .Undetermined
case .Contacts:
return ABAddressBookGetAuthorizationStatus() == .NotDetermined
case .Location:
return CLLocationManager.authorizationStatus() == .NotDetermined
}
}
}
public typealias Propose = () -> Void
public typealias ProposerAction = () -> Void
public func proposeToAccess(resource: PrivateResource, agreed successAction: ProposerAction, rejected failureAction: ProposerAction) {
switch resource {
case .Photos:
proposeToAccessPhotos(agreed: successAction, rejected: failureAction)
case .Camera:
proposeToAccessCamera(agreed: successAction, rejected: failureAction)
case .Microphone:
proposeToAccessMicrophone(agreed: successAction, rejected: failureAction)
case .Contacts:
proposeToAccessContacts(agreed: successAction, rejected: failureAction)
case .Location(let usage):
proposeToAccessLocation(usage, agreed: successAction, rejected: failureAction)
}
}
private func proposeToAccessPhotos(agreed successAction: ProposerAction, rejected failureAction: ProposerAction) {
PHPhotoLibrary.requestAuthorization { status in
dispatch_async(dispatch_get_main_queue()) {
switch status {
case .Authorized:
successAction()
default:
failureAction()
}
}
}
}
private func proposeToAccessCamera(agreed successAction: ProposerAction, rejected failureAction: ProposerAction) {
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo) { granted in
dispatch_async(dispatch_get_main_queue()) {
granted ? successAction() : failureAction()
}
}
}
private func proposeToAccessMicrophone(agreed successAction: ProposerAction, rejected failureAction: ProposerAction) {
AVAudioSession.sharedInstance().requestRecordPermission { granted in
dispatch_async(dispatch_get_main_queue()) {
granted ? successAction() : failureAction()
}
}
}
private func proposeToAccessContacts(agreed successAction: ProposerAction, rejected failureAction: ProposerAction) {
switch ABAddressBookGetAuthorizationStatus() {
case .Authorized:
successAction()
case .NotDetermined:
if let addressBook: ABAddressBook = ABAddressBookCreateWithOptions(nil, nil)?.takeRetainedValue() {
ABAddressBookRequestAccessWithCompletion(addressBook, { granted, error in
dispatch_async(dispatch_get_main_queue()) {
if granted {
successAction()
} else {
failureAction()
}
}
})
}
default:
failureAction()
}
}
private var _locationManager: CLLocationManager? // as strong ref
private func proposeToAccessLocation(locationUsage: PrivateResource.LocationUsage, agreed successAction: ProposerAction, rejected failureAction: ProposerAction) {
switch CLLocationManager.authorizationStatus() {
case .AuthorizedWhenInUse:
if locationUsage == .WhenInUse {
successAction()
} else {
failureAction()
}
case .AuthorizedAlways:
successAction()
case .NotDetermined:
if CLLocationManager.locationServicesEnabled() {
let locationManager = CLLocationManager()
_locationManager = locationManager
let delegate = LocationDelegate(locationUsage: locationUsage, successAction: successAction, failureAction: failureAction)
_locationDelegate = delegate
locationManager.delegate = delegate
switch locationUsage {
case .WhenInUse:
locationManager.requestWhenInUseAuthorization()
case .Always:
locationManager.requestAlwaysAuthorization()
}
locationManager.startUpdatingLocation()
} else {
failureAction()
}
default:
failureAction()
}
}
// MARK: LocationDelegate
private var _locationDelegate: LocationDelegate? // as strong ref
class LocationDelegate: NSObject, CLLocationManagerDelegate {
let locationUsage: PrivateResource.LocationUsage
let successAction: ProposerAction
let failureAction: ProposerAction
init(locationUsage: PrivateResource.LocationUsage, successAction: ProposerAction, failureAction: ProposerAction) {
self.locationUsage = locationUsage
self.successAction = successAction
self.failureAction = failureAction
}
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
dispatch_async(dispatch_get_main_queue()) {
switch status {
case .AuthorizedWhenInUse:
self.locationUsage == .WhenInUse ? self.successAction() : self.failureAction()
_locationManager = nil
_locationDelegate = nil
case .AuthorizedAlways:
self.locationUsage == .Always ? self.successAction() : self.failureAction()
_locationManager = nil
_locationDelegate = nil
case .Denied:
self.failureAction()
_locationManager = nil
_locationDelegate = nil
default:
break
}
}
}
}
| mit | c1ef5be69d4992c1d34422487d9b67e5 | 28.246512 | 162 | 0.653626 | 5.425367 | false | false | false | false |
stripe/stripe-ios | Example/Basic Integration/Basic Integration/Buttons.swift | 1 | 2340 | //
// Buttons.swift
// Basic Integration
//
// Created by Ben Guo on 4/25/16.
// Copyright © 2016 Stripe. All rights reserved.
//
import Stripe
import UIKit
class HighlightingButton: UIButton {
var highlightColor = UIColor(white: 0, alpha: 0.05)
convenience init(highlightColor: UIColor) {
self.init()
self.highlightColor = highlightColor
}
override var isHighlighted: Bool {
didSet {
if isHighlighted {
self.backgroundColor = self.highlightColor
} else {
self.backgroundColor = .clear
}
}
}
}
class BuyButton: UIButton {
static let defaultHeight = CGFloat(52)
static let defaultFont = UIFont.boldSystemFont(ofSize: 20)
var disabledColor = UIColor.lightGray
var enabledColor = UIColor.stripeBrightGreen
override var isEnabled: Bool {
didSet {
let color = isEnabled ? enabledColor : disabledColor
setTitleColor(.white, for: UIControl.State())
backgroundColor = color
}
}
init(enabled: Bool, title: String) {
super.init(frame: .zero)
// Shadow
layer.cornerRadius = 8
layer.shadowOpacity = 0.10
layer.shadowColor = UIColor.black.cgColor
layer.shadowRadius = 7
layer.shadowOffset = CGSize(width: 0, height: 7)
setTitle(title, for: UIControl.State())
titleLabel!.font = type(of: self).defaultFont
isEnabled = enabled
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class BrowseBuyButton: BuyButton {
let priceLabel = UILabel()
init(enabled: Bool) {
super.init(enabled: enabled, title: "Buy Now")
priceLabel.textColor = .white
addSubview(priceLabel)
priceLabel.translatesAutoresizingMaskIntoConstraints = false
priceLabel.font = type(of: self).defaultFont
priceLabel.textAlignment = .right
NSLayoutConstraint.activate([
priceLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8),
priceLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | f27926ca06654056930102ccd2b90d07 | 27.180723 | 88 | 0.630184 | 4.82268 | false | false | false | false |
cnoon/swift-compiler-crashes | crashes-duplicates/03981-swift-sourcemanager-getmessage.swift | 11 | 2461 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol A {
func g<T>
typealias e : c,
class func g
let f = {
var d = {
func g
class c,
case c<d where g: NSObject {
func i() {
class a<T {
class c<T {
class a<T where g: BooleanType, A {
let t: Int -> ("
return "[Void{
}
}
struct A {
return "
}
class a {
println(f: NSObject {
println() -> U)
func f: a {
typealias e == [1)
func i("
func g
func a<T>: T>: T>: e == {
case c<T where g
let f = "
}
}
return "
println(""\(f: e : a {
protocol P {
func g
func a<T: a {
class b: NSObject {
}
case c,
case c,
class a {
case c,
func g<T>
struct A {
let t: T>
class
protocol A {
let t: a {
protocol A : C {
func g<T>
class
typealias e == {
protocol A {
protocol A {
class
func f: C {
struct Q<T where T : b
}
case c<T: P
println(f: a {
class c,
typealias e : e
case c,
}
protocol A {
{
var d = [1)
class a
struct Q<T {
class
return "
class func a
func f: C {
func a
struct Q<T : BooleanType, A {
func g
let t: Int -> () -> () {
let i: C {
protocol A {
protocol P {
let t: b: BooleanType, A {
class c<T where T : e == ""
struct Q<T {
func f: NSObject {
class
typealias e : c {
let f = ""\() {
func g<T where T : NSObject {
typealias e : e
protocol A {
}
protocol A {
protocol A {
typealias e : a {
return "
}
class b
var d = [Void{
typealias e : b: T>
println("
protocol P {
typealias e == {
func f: c,
func i: NSObject {
}
case c<T where g<T : T: C {
case c,
class c<T where g
typealias e : C {
protocol A : e : e {
return "\("
let i: Int -> () -> () -> U)))"
let i(""\() {
{
var d where T : Int -> U)
}
}
class
typealias e {
}
func f: e
println(f: a {
func i() {
class a {
protocol P {
println() -> ("[Void{
protocol A {
func g: c {
class
func f: e == [Void{
var d where T : c {
typealias e : b: a {
func g: NSObject {
func a<T where g
protocol A : T>
let t: a {
case c,
let f = "
class a {
let f = [1))
struct Q<T : a {
let f = "\() -> U)
func i() -> U)"[1)
class func g<T where g
{
func f: a {
println(f: a {
class b
class func g: a {
typealias e : e : T>
class
case c,
return "[Void{
class
typealias e {
struct S<T : a {
var d where T : a {
let i: e
class b: a {
protocol A {
}
func i: Int -> U)"
case c,
func g: b: C {
{
typealias e : e
return "
return "
class c,
class a<T : a {
protocol A {
}
class a<T>: e {
{
func i(f: C {
protocol A {
protocol P {
case c,
class
func f: c<T: BooleanType, A
| mit | d635fa82f922dd415e888f62cd0b7768 | 12.302703 | 87 | 0.595286 | 2.511224 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.