repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
aschwaighofer/swift
refs/heads/master
stdlib/public/Darwin/Accelerate/vDSP_PolynomialEvaluation.swift
apache-2.0
8
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension vDSP { /// Evaluates a polynomial using specified coefficients and independent variables. Single-precision. /// /// - Parameter coefficients: Coefficients. /// - Parameter variables: Independent variables. /// - Returns: The polynomial evaluation result. /// /// For example, given the coefficients `[10, 20, 30]`, and independent variables `[2, 5]`, /// the result is calculated as: /// /// `result[0] = (10 * 2²) + (20 * 2¹) + (30 * 2⁰) // 110` /// /// `result[1] = (10 * 5²) + (20 * 5¹) + (30 * 5⁰) // 380` @inlinable public static func evaluatePolynomial<U>(usingCoefficients coefficients: [Float], withVariables variables: U) -> [Float] where U: AccelerateBuffer, U.Element == Float { let result = Array<Float>(unsafeUninitializedCapacity: variables.count) { buffer, initializedCount in evaluatePolynomial(usingCoefficients: coefficients, withVariables: variables, result: &buffer) initializedCount = variables.count } return result } /// Evaluates a polynomial using specified coefficients and independent variables. Single-precision. /// /// - Parameter coefficients: Coefficients. /// - Parameter variables: Independent variables. /// - Parameter result: Destination vector. /// /// For example, given the coefficients `[10, 20, 30]`, and independent variables `[2, 5]`, /// the result is calculated as: /// /// `result[0] = (10 * 2²) + (20 * 2¹) + (30 * 2⁰) // 110` /// /// `result[1] = (10 * 5²) + (20 * 5¹) + (30 * 5⁰) // 380` @inlinable public static func evaluatePolynomial<U, V>(usingCoefficients coefficients: [Float], withVariables variables: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Float, V.Element == Float { let n = vDSP_Length(min(variables.count, result.count)) let degreeOfPolynomial = vDSP_Length(coefficients.count - 1) result.withUnsafeMutableBufferPointer { dest in variables.withUnsafeBufferPointer { src in vDSP_vpoly(coefficients, 1, src.baseAddress!, 1, dest.baseAddress!, 1, n, degreeOfPolynomial) } } } /// Evaluates a polynomial using specified coefficients and independent variables. Double-precision. /// /// - Parameter coefficients: Coefficients. /// - Parameter variables: Independent variables. /// - Returns: The polynomial evaluation result. /// /// For example, given the coefficients `[10, 20, 30]`, and independent variables `[2, 5]`, /// the result is calculated as: /// /// `result[0] = (10 * 2²) + (20 * 2¹) + (30 * 2⁰) // 110` /// /// `result[1] = (10 * 5²) + (20 * 5¹) + (30 * 5⁰) // 380` @inlinable public static func evaluatePolynomial<U>(usingCoefficients coefficients: [Double], withVariables variables: U) -> [Double] where U: AccelerateBuffer, U.Element == Double { let result = Array<Double>(unsafeUninitializedCapacity: variables.count) { buffer, initializedCount in evaluatePolynomial(usingCoefficients: coefficients, withVariables: variables, result: &buffer) initializedCount = variables.count } return result } /// Evaluates a polynomial using specified coefficients and independent variables. Double-precision. /// /// - Parameter coefficients: Coefficients. /// - Parameter variables: Independent variables. /// - Parameter result: Destination vector. /// /// For example, given the coefficients `[10, 20, 30]`, and independent variables `[2, 5]`, /// the result is calculated as: /// /// `result[0] = (10 * 2²) + (20 * 2¹) + (30 * 2⁰) // 110` /// /// `result[1] = (10 * 5²) + (20 * 5¹) + (30 * 5⁰) // 380` @inlinable public static func evaluatePolynomial<U, V>(usingCoefficients coefficients: [Double], withVariables variables: U, result: inout V) where U: AccelerateBuffer, V: AccelerateMutableBuffer, U.Element == Double, V.Element == Double { let n = vDSP_Length(min(variables.count, result.count)) let degreeOfPolynomial = vDSP_Length(coefficients.count - 1) result.withUnsafeMutableBufferPointer { dest in variables.withUnsafeBufferPointer { src in vDSP_vpolyD(coefficients, 1, src.baseAddress!, 1, dest.baseAddress!, 1, n, degreeOfPolynomial) } } } }
55c0d95d4a5999f3908ce6d8a05e1b88
39.577922
104
0.503601
false
false
false
false
almazrafi/Metatron
refs/heads/master
Tests/MetatronTests/APE/APETagLyricsTest.swift
mit
1
// // APETagLyricsTest.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 XCTest @testable import Metatron class APETagLyricsTest: XCTestCase { // MARK: Instance Methods func test() { let tag = APETag() do { let value = TagLyrics() tag.lyrics = value XCTAssert(tag.lyrics == value.revised) XCTAssert(tag["Lyrics"] == nil) do { tag.version = APEVersion.v1 XCTAssert(tag.toData() == nil) } do { tag.version = APEVersion.v2 XCTAssert(tag.toData() == nil) } guard let item = tag.appendItem("Lyrics") else { return XCTFail() } item.lyricsValue = value XCTAssert(tag.lyrics == TagLyrics()) } do { let value = TagLyrics(pieces: [TagLyrics.Piece("Abc 123")]) tag.lyrics = value XCTAssert(tag.lyrics == value.revised) guard let item = tag["Lyrics"] else { return XCTFail() } guard let itemValue = item.lyricsValue else { return XCTFail() } XCTAssert(itemValue == value.revised) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } item.lyricsValue = value XCTAssert(tag.lyrics == value.revised) } do { let value = TagLyrics(pieces: [TagLyrics.Piece("Абв 123")]) tag.lyrics = value XCTAssert(tag.lyrics == value.revised) guard let item = tag["Lyrics"] else { return XCTFail() } guard let itemValue = item.lyricsValue else { return XCTFail() } XCTAssert(itemValue == value.revised) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } item.lyricsValue = value XCTAssert(tag.lyrics == value.revised) } do { let value = TagLyrics(pieces: [TagLyrics.Piece("Abc 1"), TagLyrics.Piece("Abc 2")]) tag.lyrics = value XCTAssert(tag.lyrics == value.revised) guard let item = tag["Lyrics"] else { return XCTFail() } guard let itemValue = item.lyricsValue else { return XCTFail() } XCTAssert(itemValue == value.revised) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } item.lyricsValue = value XCTAssert(tag.lyrics == value.revised) } do { let value = TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230), TagLyrics.Piece("Abc 2", timeStamp: 4560)]) tag.lyrics = value XCTAssert(tag.lyrics == value.revised) guard let item = tag["Lyrics"] else { return XCTFail() } guard let itemValue = item.lyricsValue else { return XCTFail() } XCTAssert(itemValue == value.revised) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } item.lyricsValue = value XCTAssert(tag.lyrics == value.revised) } do { let value = TagLyrics(pieces: [TagLyrics.Piece("Abc 1"), TagLyrics.Piece("Abc 2", timeStamp: 4560)]) tag.lyrics = value XCTAssert(tag.lyrics == value.revised) guard let item = tag["Lyrics"] else { return XCTFail() } guard let itemValue = item.lyricsValue else { return XCTFail() } XCTAssert(itemValue == value.revised) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } item.lyricsValue = value XCTAssert(tag.lyrics == value.revised) } do { let value = TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230), TagLyrics.Piece("Abc 2")]) tag.lyrics = value XCTAssert(tag.lyrics == value.revised) guard let item = tag["Lyrics"] else { return XCTFail() } guard let itemValue = item.lyricsValue else { return XCTFail() } XCTAssert(itemValue == value.revised) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } item.lyricsValue = value XCTAssert(tag.lyrics == value.revised) } do { let value = TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 4560), TagLyrics.Piece("Abc 2", timeStamp: 1230)]) tag.lyrics = value XCTAssert(tag.lyrics == value.revised) guard let item = tag["Lyrics"] else { return XCTFail() } guard let itemValue = item.lyricsValue else { return XCTFail() } XCTAssert(itemValue == value.revised) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } item.lyricsValue = value XCTAssert(tag.lyrics == value.revised) } do { let value = TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 1230), TagLyrics.Piece("Abc 2", timeStamp: 4560)]) tag.lyrics = value XCTAssert(tag.lyrics == value.revised) guard let item = tag["Lyrics"] else { return XCTFail() } guard let itemValue = item.lyricsValue else { return XCTFail() } XCTAssert(itemValue == value.revised) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } item.lyricsValue = value XCTAssert(tag.lyrics == value.revised) } do { let value = TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 4560), TagLyrics.Piece("Abc 2", timeStamp: 1230)]) tag.lyrics = value XCTAssert(tag.lyrics == value.revised) guard let item = tag["Lyrics"] else { return XCTFail() } guard let itemValue = item.lyricsValue else { return XCTFail() } XCTAssert(itemValue == value.revised) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } item.lyricsValue = value XCTAssert(tag.lyrics == value.revised) } do { let value = TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230), TagLyrics.Piece("", timeStamp: 4560)]) tag.lyrics = value XCTAssert(tag.lyrics == value.revised) guard let item = tag["Lyrics"] else { return XCTFail() } guard let itemValue = item.lyricsValue else { return XCTFail() } XCTAssert(itemValue == value.revised) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } item.lyricsValue = value XCTAssert(tag.lyrics == value.revised) } do { let value = TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 4560), TagLyrics.Piece("", timeStamp: 1230)]) tag.lyrics = value XCTAssert(tag.lyrics == value.revised) guard let item = tag["Lyrics"] else { return XCTFail() } guard let itemValue = item.lyricsValue else { return XCTFail() } XCTAssert(itemValue == value.revised) do { tag.version = APEVersion.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } do { tag.version = APEVersion.v2 guard let data = tag.toData() else { return XCTFail() } guard let other = APETag(fromData: data) else { return XCTFail() } XCTAssert(other.lyrics == value.revised) } item.lyricsValue = value XCTAssert(tag.lyrics == value.revised) } do { let value = TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 1230), TagLyrics.Piece("", timeStamp: 4560)]) tag.lyrics = value XCTAssert(tag.lyrics == value.revised) XCTAssert(tag["Lyrics"] == nil) do { tag.version = APEVersion.v1 XCTAssert(tag.toData() == nil) } do { tag.version = APEVersion.v2 XCTAssert(tag.toData() == nil) } guard let item = tag.appendItem("Lyrics") else { return XCTFail() } item.lyricsValue = value XCTAssert(tag.lyrics == value.revised) } do { let value = TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 4560), TagLyrics.Piece("", timeStamp: 1230)]) tag.lyrics = value XCTAssert(tag.lyrics == value.revised) XCTAssert(tag["Lyrics"] == nil) do { tag.version = APEVersion.v1 XCTAssert(tag.toData() == nil) } do { tag.version = APEVersion.v2 XCTAssert(tag.toData() == nil) } guard let item = tag.appendItem("Lyrics") else { return XCTFail() } item.lyricsValue = value XCTAssert(tag.lyrics == value.revised) } guard let item = tag.appendItem("Lyrics") else { return XCTFail() } do { item.value = [0] XCTAssert(tag.lyrics == TagLyrics()) } do { item.stringValue = "[1.23]Abc 1[4.56]Abc 2" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230), TagLyrics.Piece("Abc 2", timeStamp: 4560)])) } do { item.stringValue = "[1.23] Abc 1\n[4.56] Abc 2\n" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230), TagLyrics.Piece("Abc 2", timeStamp: 4560)])) } do { item.stringValue = "[4.56] Abc 1\n[1.23] Abc 2\n" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 4560), TagLyrics.Piece("Abc 2", timeStamp: 4560)])) } do { item.stringValue = "[1.23][4.56] Abc 2\n" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("Abc 2", timeStamp: 4560)])) } do { item.stringValue = "[1.23] Abc 1\n[4.56]" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230)])) } do { item.stringValue = "[1.23][4.56]" XCTAssert(tag.lyrics == TagLyrics()) } do { item.stringValue = "[] Abc 1\n[4.56] Abc 2\n" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("[] Abc 1\n[4.56] Abc 2\n")])) } do { item.stringValue = "[1.23] Abc 1\n[] Abc 2\n" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("Abc 1\n[] Abc 2", timeStamp: 1230)])) } do { item.stringValue = "[] Abc 1\n[] Abc 2\n" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("[] Abc 1\n[] Abc 2\n")])) } do { item.stringValue = "[][] Abc 2\n" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("[][] Abc 2\n")])) } do { item.stringValue = "[] Abc 1\n[]" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("[] Abc 1\n[]")])) } do { item.stringValue = "[][]" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("[][]")])) } do { item.stringValue = "[1.23] Abc\0 1\n[4.56] Abc\0 2\n" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("Abc", timeStamp: 1230), TagLyrics.Piece("Abc", timeStamp: 4560)])) } do { item.stringValue = "[[1.23]] Abc 1\n[4.56] Abc 2\n" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("[[1.23]] Abc 1\n[4.56] Abc 2\n")])) } do { item.stringValue = "[1.23] Abc 1\n[[4.56]] Abc 2\n" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("Abc 1\n[", timeStamp: 1230), TagLyrics.Piece("] Abc 2", timeStamp: 4560)])) } do { item.stringValue = "[[1.23]] Abc 1\n[[4.56]] Abc 2\n" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("[[1.23]] Abc 1\n[[4.56]] Abc 2\n")])) } do { item.stringValue = "[Abc 1] Abc 2\n" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("[Abc 1] Abc 2\n")])) } do { item.stringValue = "[\0] Abc 123\n" XCTAssert(tag.lyrics == TagLyrics(pieces: [TagLyrics.Piece("[")])) } } }
c66a03ccf2f47eba41dc35b7199f3163
26.038224
109
0.454259
false
false
false
false
wildthink/DataBasis
refs/heads/master
DataBasis/EID.swift
mit
1
// // EID.swift // DataBasis // // Created by Jason Jobe on 4/17/16. // Copyright © 2016 WildThink. All rights reserved. // import Foundation public struct EID64: Comparable { var type: UInt32 var ident: UInt32 init (type: UInt32, id: UInt32) { self.type = type self.ident = id } init (_ int64: Int64) { type = UInt32(int64 >> 32) ident = UInt32((int64 << 32) >> 32) } var int64: Int64 { get { return (Int64(type) << 32) | Int64(ident) } } var uint64: UInt64 { get { return (UInt64(type) << 32) | UInt64(ident) } } var min_instance_id: Int64 { return Int64(type) } var max_instance_id: Int64 { return Int64(type + UInt32.max) } } public func == (e1: EID64, e2: EID64) -> Bool { return e1.int64 == e2.int64 } public func < (lhs: EID64, rhs: EID64) -> Bool { return lhs.uint64 < rhs.uint64 } public struct EID32: Comparable { var type: UInt16 var ident: UInt16 init (type: UInt16, id: UInt16) { self.type = type self.ident = id } init (_ int32: UInt32) { type = UInt16(int32 >> 16) ident = UInt16((int32 << 16) >> 16) } var uint32: UInt32 { get { return (UInt32(type) << 16) | UInt32(ident) } } var int32: Int32 { get { return (Int32(type) << 16) | Int32(ident) } } var min_instance_id: Int32 { return Int32(type) } var max_instance_id: Int32 { return Int32(type + UInt16.max) } } public func == (e1: EID32, e2: EID32) -> Bool { return e1.int32 == e2.int32 } public func < (lhs: EID32, rhs: EID32) -> Bool { return lhs.uint32 < rhs.uint32 } extension Int64 { var hiBits: Int32 { get { return Int32((self >> 32)) } } func clearHi() -> Int64 { return (self & 0x00000000FFFFFFFF) } var loBits: UInt32 { get { return UInt32(self & 0x00000000FFFFFFFF) } } }
c9e8008aa494139a797e0fb1fab5fa0c
21.6
77
0.566372
false
false
false
false
gauuni/iOSProjectTemplate
refs/heads/master
iOSProjectTemplate/iOSProjectTemplate/Utilities/RootStyleManager.swift
mit
1
// // AppDelegate.swift // StyleManager // // Created by Duc Nguyen on 10/1/16. // Copyright © 2016 Reflect Apps Inc. All rights reserved. // import Foundation import UIKit class RootStyleManager { static let sharedInstance = RootStyleManager() func setupAppearance() { setupNav() setupBarButtonItem() setupTabbarItem() setLightStatusBar() } // Setup style for navigation bar here func setupNav() { UINavigationBar.appearance().barStyle = UIBarStyle.default // navigation bar color // UINavigationBar.appearance().barTintColor = RootColor(hex: "#171933").color // UINavigationBar.appearance().isTranslucent = false // UINavigationBar.appearance().tintColor = UIColor.white // UINavigationBar.appearance().titleTextAttributes = [ // NSFontAttributeName: UIFont.appFont(name: kFontMontserratBold, fontSize: 14.0), // NSForegroundColorAttributeName: UIColor.white // ] // // UINavigationBar.appearance().shadowImage = UIImage() // UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default) } func setLightStatusBar() { UIApplication.shared.statusBarStyle = .lightContent } func setupBarButtonItem() { } func setupTabbarItem() { } }
682157934f0a45d00237d9400c0597c8
25.264151
93
0.633621
false
false
false
false
AnirudhDas/AniruddhaDas.github.io
refs/heads/master
CricketNews/CricketNewsUnitTests/MockService/MockCricbuzzService.swift
apache-2.0
1
// // MockCricbuzzService.swift // CricketNewsUnitTests // // Created by Anirudh Das on 7/6/18. // Copyright © 2018 Aniruddha Das. All rights reserved. // import Foundation @testable import CricketNews import SwiftyJSON /** Mocks the CricbuzzService implementation */ class MockCricbuzzService: CricbuzzServiceProtocol { var apiURL: String init(apiURL: String) { self.apiURL = apiURL } func fetchAllNews(completionBlock: @escaping (_ response: CricbuzzNewsResponse?) -> Void) { AlamofireConfig.shared.manager.request(apiURL) .validate(statusCode: 200..<300) .responseJSON { response in switch response.result { case .success: let json = JSON(data: response.data!) guard json != JSON.null, let detailedURL = json["detailedURL"].string, let items = json["news_array"].array else { //Wrong Keys completionBlock(nil) return } var newsArray: [CricbuzzNews] = [] for item in items { if let news = CricbuzzNews(item) { newsArray.append(news) } } guard !newsArray.isEmpty else { completionBlock(nil) return } completionBlock(CricbuzzNewsResponse(detailedBaseUrl: detailedURL, newsArray: newsArray)) case .failure(_): completionBlock(nil) } } } func fetchDetailedNews(detailUrl: String, completionBlock: @escaping (_ response: CricbuzzStory?) -> Void) { AlamofireConfig.shared.manager.request(detailUrl) .validate(statusCode: 400..<500) //Wrong Status Code .responseJSON { response in switch response.result { case .success: let json = JSON(data: response.data!) guard json != JSON.null, let story = CricbuzzStory(json) else { completionBlock(nil) return } completionBlock(story) case .failure(_): completionBlock(nil) } } } }
d1f4a0f1e166b59705232226b7407cc7
34.367647
147
0.513514
false
false
false
false
Leo19/swift_begin
refs/heads/master
test-swift/Class_Inheritance.playground/Contents.swift
gpl-2.0
1
//: Playground - noun: a place where people can play // 2015-12-03 Leo)Xcode7.1 import UIKit /* 阻止被重写的方法,只需要在关键字前加上final(final var,final func) */ class Vehicle{ var currentSpeed = 0.0 var description: String{ return "traveling at \(currentSpeed) KM per hour" } func makeNoise(){ // maybe its subclass will do something } } let basicVehicle = Vehicle() basicVehicle.description // 第一个子类(自行车)给一个属性 class Bicycle: Vehicle{ var hasGlassWindow = false } let bicycle = Bicycle() bicycle.currentSpeed = 15.0 bicycle.hasGlassWindow = true print("Bicycle: \(bicycle.description)") // 第二个子类双人自行车 class Tandem: Bicycle{ var passengers = 2 } let tandem = Tandem() tandem.hasGlassWindow = false tandem.passengers = 2 tandem.currentSpeed = 18.0 print("Tandem: \(tandem.description)") // 重写属性和方法 class Car: Vehicle{ var gear = 1 override var description: String{ print(super.description) return super.description + " in gear \(gear)" } override func makeNoise() { print("Kahh Kahh") } } let car = Car() car.currentSpeed = 35.0 car.gear = 2 print("Car: " + car.description) car.makeNoise() // 给继承来的属性加属性观察器,一般不同时加set和观察器 class AutomaticCar: Car{ override var currentSpeed: Double{ didSet{ gear = Int(currentSpeed / 10.0) + 1 } } }
23a3bea2efa8563c28af51feda2ca306
15.554217
57
0.652838
false
false
false
false
codelynx/silvershadow
refs/heads/master
Silvershadow/XView+Z.swift
mit
1
// // UIView+Z.swift // ZKit // // Created by Kaz Yoshikawa on 12/12/16. // Copyright © 2016 Electricwoods LLC. All rights reserved. // #if os(iOS) import UIKit #elseif os(macOS) import Cocoa #endif extension XView { func transform(to view: XView) -> CGAffineTransform { let targetRect = self.convert(self.bounds, to: view) return view.bounds.transform(to: targetRect) } func addSubviewToFit(_ view: XView) { view.frame = self.bounds self.addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false view.topAnchor.constraint(equalTo: self.topAnchor).isActive = true view.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true view.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true view.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true } func setBorder(color: XColor?, width: CGFloat) { #if os(macOS) guard let layer = self.layer else { fatalError() } #endif layer.borderWidth = width layer.borderColor = color?.cgColor } #if os(macOS) var backgroundColor: NSColor? { get { return layer?.backgroundColor.flatMap { NSColor(cgColor: $0) } } set { self.wantsLayer = true // ?? self.layer?.backgroundColor = newValue?.cgColor } } #endif }
c14b560045bcbc7d437a43616d6086c1
22.351852
74
0.715305
false
false
false
false
Lordxen/MagistralSwift
refs/heads/develop
Carthage/Checkouts/CryptoSwift/Sources/CryptoSwift/MD5.swift
bsd-2-clause
9
// // MD5.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 06/08/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // public final class MD5: DigestType { static let blockSize: Int = 64 static let digestLength: Int = 16 // 128 / 8 fileprivate static let hashInitialValue: Array<UInt32> = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] fileprivate var accumulated = Array<UInt8>() fileprivate var processedBytesTotalCount: Int = 0 fileprivate var accumulatedHash: Array<UInt32> = MD5.hashInitialValue /** specifies the per-round shift amounts */ private let s: Array<UInt32> = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] /** binary integer part of the sines of integers (Radians) */ private let k: Array<UInt32> = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x2441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391] public init() { } public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> { do { return try self.update(withBytes: bytes, isLast: true) } catch { fatalError() } } // mutating currentHash in place is way faster than returning new result fileprivate func process(block chunk: ArraySlice<UInt8>, currentHash: inout Array<UInt32>) { // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 var M = chunk.toUInt32Array() assert(M.count == 16, "Invalid array") // Initialize hash value for this chunk: var A: UInt32 = currentHash[0] var B: UInt32 = currentHash[1] var C: UInt32 = currentHash[2] var D: UInt32 = currentHash[3] var dTemp: UInt32 = 0 // Main loop for j in 0 ..< k.count { var g = 0 var F: UInt32 = 0 switch (j) { case 0 ... 15: F = (B & C) | ((~B) & D) g = j break case 16 ... 31: F = (D & B) | (~D & C) g = (5 * j + 1) % 16 break case 32 ... 47: F = B ^ C ^ D g = (3 * j + 5) % 16 break case 48 ... 63: F = C ^ (B | (~D)) g = (7 * j) % 16 break default: break } dTemp = D D = C C = B B = B &+ rotateLeft(A &+ F &+ k[j] &+ M[g], by: s[j]) A = dTemp } currentHash[0] = currentHash[0] &+ A currentHash[1] = currentHash[1] &+ B currentHash[2] = currentHash[2] &+ C currentHash[3] = currentHash[3] &+ D } } extension MD5: Updatable { public func update<T: Collection>(withBytes bytes: T, isLast: Bool = false) throws -> Array<UInt8> where T.Iterator.Element == UInt8 { self.accumulated += bytes if isLast { let lengthInBits = (self.processedBytesTotalCount + self.accumulated.count) * 8 let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8) // A 64-bit representation of b // Step 1. Append padding bitPadding(to: &self.accumulated, blockSize: MD5.blockSize, allowance: 64 / 8) // Step 2. Append Length a 64-bit representation of lengthInBits self.accumulated += lengthBytes.reversed() } var processedBytes = 0 for chunk in BytesSequence(chunkSize: MD5.blockSize, data: self.accumulated) { if (isLast || (self.accumulated.count - processedBytes) >= MD5.blockSize) { self.process(block: chunk, currentHash: &self.accumulatedHash) processedBytes += chunk.count } } self.accumulated.removeFirst(processedBytes) self.processedBytesTotalCount += processedBytes // output current hash var result = Array<UInt8>() result.reserveCapacity(MD5.digestLength) for hElement in self.accumulatedHash { let hLE = hElement.littleEndian result += [UInt8(hLE & 0xff), UInt8((hLE >> 8) & 0xff), UInt8((hLE >> 16) & 0xff), UInt8((hLE >> 24) & 0xff)] } // reset hash value for instance if isLast { self.accumulatedHash = MD5.hashInitialValue } return result } }
3417f16be60aa7bad0f716536843732d
38.348993
138
0.516971
false
false
false
false
aldian/tensorflow
refs/heads/master
tensorflow/lite/experimental/swift/Sources/MetalDelegate.swift
apache-2.0
1
// Copyright 2019 Google Inc. 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 TensorFlowLiteCMetal /// A delegate that uses the `Metal` framework for performing TensorFlow Lite graph operations with /// GPU acceleration. /// /// - Important: This is an experimental interface that is subject to change. public final class MetalDelegate: Delegate { /// The configuration options for the `MetalDelegate`. public let options: Options // Conformance to the `Delegate` protocol. public private(set) var cDelegate: CDelegate /// Creates a new instance configured with the given `options`. /// /// - Parameters: /// - options: Configurations for the delegate. The default is a new instance of /// `MetalDelegate.Options` with the default configuration values. public init(options: Options = Options()) { self.options = options var delegateOptions = TFLGpuDelegateOptions() delegateOptions.allow_precision_loss = options.allowsPrecisionLoss delegateOptions.wait_type = options.waitType.cWaitType delegateOptions.enable_quantization = options.isQuantizationEnabled cDelegate = TFLGpuDelegateCreate(&delegateOptions) } deinit { TFLGpuDelegateDelete(cDelegate) } } extension MetalDelegate { /// Options for configuring the `MetalDelegate`. public struct Options: Equatable, Hashable { /// Indicates whether the GPU delegate allows precision loss, such as allowing `Float16` /// precision for a `Float32` computation. The default is `false`. public var allowsPrecisionLoss = false /// A type indicating how the current thread should wait for work on the GPU to complete. The /// default is `passive`. public var waitType: ThreadWaitType = .passive /// Indicates whether the GPU delegate allows execution of an 8-bit quantized model. The default /// is `false`. public var isQuantizationEnabled = false /// Creates a new instance with the default values. public init() {} } } /// A type indicating how the current thread should wait for work scheduled on the GPU to complete. public enum ThreadWaitType: Equatable, Hashable { /// The thread does not wait for the work to complete. Useful when the output of the work is used /// with the GPU pipeline. case none /// The thread waits until the work is complete. case passive /// The thread waits for the work to complete with minimal latency, which may require additional /// CPU resources. case active /// The thread waits for the work while trying to prevent the GPU from going into sleep mode. case aggressive /// The C `TFLGpuDelegateWaitType` for the current `ThreadWaitType`. var cWaitType: TFLGpuDelegateWaitType { switch self { case .none: return TFLGpuDelegateWaitTypeDoNotWait case .passive: return TFLGpuDelegateWaitTypePassive case .active: return TFLGpuDelegateWaitTypeActive case .aggressive: return TFLGpuDelegateWaitTypeAggressive } } }
a6c181209cfc766592f5a4432cb389ce
36.849462
100
0.734943
false
true
false
false
KennethTsang/GrowingTextView
refs/heads/master
Example/GrowingTextView/Example3.swift
mit
1
// // Example3.swift // GrowingTextView // // Created by Kenneth on 29/7/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import GrowingTextView class Example3: UIViewController { @IBOutlet weak var textView: GrowingTextView! override func viewDidLoad() { super.viewDidLoad() // *** Customize GrowingTextView *** textView.layer.cornerRadius = 4.0 textView.placeholder = "Say something..." textView.font = UIFont.systemFont(ofSize: 15) textView.minHeight = 30 textView.maxHeight = 100 // *** Hide keyboard when tapping outside *** let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapGestureHandler)) view.addGestureRecognizer(tapGesture) } @objc func tapGestureHandler() { view.endEditing(true) } @IBAction func minHeightChanged(_ sender: UISegmentedControl) { textView.minHeight = sender.selectedSegmentIndex == 0 ? 30 : 60 } @IBAction func maxHeightChanged(_ sender: UISegmentedControl) { textView.maxHeight = sender.selectedSegmentIndex == 0 ? 100 : 150 } } extension Example3: GrowingTextViewDelegate { // *** Call layoutIfNeeded on superview for animation when changing height *** func textViewDidChangeHeight(_ textView: GrowingTextView, height: CGFloat) { UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: [.curveLinear], animations: { () -> Void in self.view.layoutIfNeeded() }, completion: nil) } }
366b757dd0d17fb59fe2db67aa3bdaac
29.962264
163
0.660573
false
false
false
false
Cein-Markey/ios-guessinggame-app
refs/heads/master
Fingers/AppDelegate.swift
mit
1
// // AppDelegate.swift // Fingers // // Created by Cein Markey on 9/13/15. // Copyright © 2015 Cein Markey. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.example.Fingers" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Fingers", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
13d6f88467070becdd9deb90a3428a4b
53.837838
291
0.719238
false
false
false
false
box/box-ios-sdk
refs/heads/main
Sources/Responses/BoxResponseDescription.swift
apache-2.0
1
// // BoxResponseDescription.swift // BoxSDK // // Created by Daniel Cech on 10/05/2019. // Copyright © 2019 Box. All rights reserved. // import Foundation /// The components that make up a description of a BoxResponse public struct BoxResponseDescription { /// The HTTP status code of the response public var statusCode: Int? /// The HTTP headers of the response public var headers: BoxHTTPHeaders? /// The body component of the response public var body: [String: Any]? init(fromResponse response: BoxResponse) { statusCode = response.urlResponse?.statusCode headers = response.urlResponse?.allHeaderFields as? [String: String] if let unwrappedBody = response.body { body = try? JSONSerialization.jsonObject(with: unwrappedBody, options: []) as? [String: Any] } } func getDictionary() -> [String: Any] { var dict = [String: Any]() dict["statusCode"] = statusCode dict["headers"] = headers dict["body"] = body return dict } }
8bb91498aef4bb5039da3330acb9a85d
28.416667
104
0.649669
false
false
false
false
MiRchi/Trecker
refs/heads/master
Trecker/MapViewController.swift
gpl-3.0
1
// // MapViewController.swift // Trecker // // Created by Michael Schwarz on 31.10.16. // Copyright © 2016 Michael Schwarz. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! var apiModel: TreckerApiModel? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadFields() loadMembers() } //MARK: - Fields func loadFields() { apiModel?.loadFields() {result in do { try result() DispatchQueue.main.async { self.addFields() } } catch let error { DispatchQueue.main.async {} print(error) } } } func addFields() { guard let fields = self.apiModel?.fields else { return } for field in fields { self.mapView.add(field.overlay) } } //MARK: - Members func loadMembers() { apiModel?.loadMembers() {result in do { try result() DispatchQueue.main.async { self.addMembers() } } catch let error { DispatchQueue.main.async {} print(error) } } } func addMembers() { guard let members = self.apiModel?.members else { return } for member in members { guard let annotation = member.annotation else { continue } self.mapView.addAnnotation(annotation) } } } //MARK: Fields extension MapViewController: MKMapViewDelegate { override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self } func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if overlay is MKPolygon { let polygon = overlay as! MKPolygon let aRenderer = MKPolygonRenderer.init(polygon: polygon) aRenderer.fillColor = UIColor.cyan.withAlphaComponent(0.2) aRenderer.strokeColor = UIColor.blue.withAlphaComponent(0.7) aRenderer.lineWidth = 3; return aRenderer; } return MKOverlayRenderer() } }
eaaf134210f18d3c50f0f88a1934932e
23.242424
93
0.53375
false
false
false
false
AlvinL33/TownHunt
refs/heads/master
TownHunt-1.9/TownHunt/LeaderboardViewController.swift
apache-2.0
1
// // LeaderboardViewController.swift // TownHunt // // Created by Alvin Lee on 09/04/2017. // Copyright © 2017 LeeTech. All rights reserved. // import UIKit class LeaderboardViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { public var selectedPackKey = "" public var packCreatorID = "" private var packID = "" private var userID = "" private var leaderboardData = [String: Any]() private var leaderboardRecords = [[String:String]]() @IBOutlet var leaderboardTable: UITableView! @IBOutlet weak var packLeaderboardHeaderLabel: UIButton! @IBOutlet weak var userPositionLabel: UILabel! @IBOutlet weak var userPointsScoreLabel: UILabel! @IBOutlet weak var averagePointsScoredLabel: UILabel! @IBOutlet weak var numberOfPlayersLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() leaderboardTable.delegate = self leaderboardTable.dataSource = self //self.leaderboardTable.register(LeaderboardRecordTableViewCell.self, forCellReuseIdentifier: "leaderboardRecordCell") getUserID() getPackID() getLeaderboardData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func getUserID(){ userID = UserDefaults.standard.string(forKey: "UserID")! } // Retrieves the pack id of the selected pack private func getPackID(){ // Checks that the selectedPackKey and packCreatorID is not empty otherwise an error message is displayed if !(self.selectedPackKey.isEmpty || self.packCreatorID.isEmpty){ let userPackDictName = "UserID-\(packCreatorID)-LocalPacks" let defaults = UserDefaults.standard if let dictOfPacksOnPhone = defaults.dictionary(forKey: userPackDictName){ // Opens file and retrieves the pack data and hence the pack id let filename = dictOfPacksOnPhone[selectedPackKey] as! String let packData = PinPackMapViewController().loadPackFromFile(filename: filename, userPackDictName: userPackDictName, selectedPackKey: selectedPackKey, userID: packCreatorID) packID = packData["PackID"] as! String } else{ displayAlertMessage(alertTitle: "Error", alertMessage: "Data Couldn't be loaded") } } else{ displayAlertMessage(alertTitle: "Error", alertMessage: "Selected pack data not passed") } } func setLeaderboardData(data: [String:Any]){ leaderboardData = data leaderboardRecords = leaderboardData["topScoreRecords"] as! [[String : String]] leaderboardTable.reloadData() let userRank = data["userRank"]! as! String let userScore = data["userScore"]! as! String let averageScore = String(describing: data["averageScore"]!) let numOfPackPlayers = data["numOfPlayersOfPack"]! as! String setNonTableLabels(userRank: userRank, userScore: userScore, averageScore: averageScore, numPlayers: numOfPackPlayers) } private func setNonTableLabels(userRank: String, userScore: String, averageScore: String, numPlayers: String){ packLeaderboardHeaderLabel.setTitle("\(selectedPackKey): Top 10", for: UIControlState()) userPositionLabel.text = userRank userPointsScoreLabel.text = "\(userScore)pts" averagePointsScoredLabel.text = "\(averageScore)pts" numberOfPlayersLabel.text = numPlayers } private func getLeaderboardData(){ // Initialises database interaction object let dbInteraction = DatabaseInteraction() // Tests for internet connectivity if dbInteraction.connectedToNetwork(){ let postData = "packID=\(packID)&userID=\(userID)" let responseJSON = dbInteraction.postToDatabase(apiName: "getPackLeaderboardInfo.php", postData: postData){ (dbResponse: NSDictionary) in let isError = dbResponse["error"]! as! Bool var errorMessage = "" //let lbData = dbResponse as! Dictionary<String, Any> print(dbResponse) if !isError{ //let userRank = dbResponse["userRank"]! as! String //let userScore = dbResponse["userScore"]! as! String //let averageScore = dbResponse["averageScore"]! as! String //let numOfPackPlayers = dbResponse["numOfPlayersOfPack"]! as! String //self.setNonTableLabels(userRank: userRank, userScore: userScore, averageScore: averageScore, numPlayers: numOfPackPlayers) } else{ for message in dbResponse["message"] as! [String]{ errorMessage = errorMessage + "\n" + message } } // Displays a message to the user indicating the sucessfull/unsucessfull creation of a new pack DispatchQueue.main.async(execute: { if isError{ self.displayAlertMessage(alertTitle: "Error", alertMessage: errorMessage) } else{ self.setLeaderboardData(data: dbResponse as! Dictionary<String, Any>) print("Leaderboard data loaded") } }) } } else{ // If no internet connectivity, an error message is diplayed asking the user to connect to the internet let alertCon = UIAlertController(title: "Error: Couldn't Connect to Database", message: "No internet connectivity found. Please check your internet connection", preferredStyle: .alert) alertCon.addAction(UIAlertAction(title: "Try Again", style: .default, handler: { action in // Recursion is used to recall the function until internet connectivity is restored self.getLeaderboardData() })) self.present(alertCon, animated: true, completion: nil) } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return leaderboardRecords.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "leaderboardRecordCell", for: indexPath) as! LeaderboardRecordTableViewCell let record = leaderboardRecords[indexPath.row] cell.positionLabel?.text = String(indexPath.row + 1) cell.pointsScoreLabel?.text = "\(record["Score"]!)pts" cell.playerNameLabel?.text = record["Username"]! return cell } @IBAction func backNavButtonTapped(_ sender: Any) { self.dismiss(animated: true, completion: nil) } 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) } }
473c24899ef6830eacfa98b495c48c3c
43.819277
196
0.634946
false
false
false
false
maikotrindade/ios-basics
refs/heads/master
UiCollectionApp/UiCollectionApp/ViewController.swift
gpl-3.0
1
// // ViewController.swift // UiCollectionApp // // Created by ifsp on 23/09/16. // Copyright © 2016 ifsp. All rights reserved. // import UIKit class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet weak var collectionView: UICollectionView! let androids = ["Android 1", "Android 2", "Android 3", "Android 4", "Android 5"] let imageArray = [UIImage(named: "1"), UIImage(named: "2"), UIImage(named: "3"), UIImage(named: "4"), UIImage(named: "5")] func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.androids.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell cell.imageView?.image = self.imageArray[indexPath.row] cell.titleLabel?.text = self.androids[indexPath.row] return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { self.performSegueWithIdentifier("showImage", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showImage" { let indexPaths = self.collectionView!.indexPathsForSelectedItems()! let indexPath = indexPaths[0] as NSIndexPath let vc = segue.destinationViewController as! NewViewController vc.image = self.imageArray[indexPath.row]! vc.title = self.androids[indexPath.row] } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
6d0af50f7e634280e5ac773b6ce422ee
34.183333
130
0.669825
false
false
false
false
509dave16/udemy_swift_ios_projects
refs/heads/master
playground/variables-types.playground/Contents.swift
gpl-2.0
1
//: Playground - noun: a place where people can play import UIKit //Testing string operations var helloWorld = "Hello, playground"//String helloWorld += " I'm so cool!" var numA = 1.5//double var numB: Float = 1.5//Float var numC = 3 //Int var sum = 5 + 6 //add var product = 5 * 5 //multiply var divisor = 28 / 5 //divide var remainder = 22 % 5 //modulus var subtraction = 44 - 22 //subtraction var crazyResult = sum * product + (divisor * remainder + subtraction) var newStr = "Hey " + "how are you?" var firstName = "Jon" var lastName = "Smith" var fullName = "\(firstName) \(lastName)" var price = "Price: $\(numA)" price = "Bannana" let total = 5.0 //constant var jack = 0, jill = 1, bob = 2 jill = 6 let beaver = "beaver", stever = "stever", cleaver = "cleaver" var totalPrice: Double //type explicitly declared var sumStr: String = "This is a String"
2b950e4b2112d6a6342fb5e0e773a5b0
19.809524
69
0.663616
false
false
false
false
qiusuo8/AppInfoTracker
refs/heads/master
Sources/AppInfoTracker.swift
mit
1
// // AppInfoTracker.swift // AppInfoTracker // // Created by zhaozh on 2017/7/21. // Copyright © 2017年 qiusuo8. All rights reserved. // import Foundation fileprivate enum TrackerKey: String { case versionMap = "AppInfoTracker-version" case versionHistory = "AppInfoTracker-version-h" case dayLaunch = "AppInfoTracker-dayLaunch" } public class AppInfoTracker { public typealias FirstLaunchClosure = () -> Void public fileprivate(set) var isFirstLaunchForCurrentVersion: Bool = false public fileprivate(set) var isFirstLaunchForCurrentVersionAndBuild: Bool = false public fileprivate(set) var isFirstLaunchOfToday: Bool = false public static let shared = AppInfoTracker() public fileprivate(set) var versionHistory: [String] = [] fileprivate var versionMap: [String: [String: Int]] = [:] fileprivate var dayLaunchMap: [String: Int] = [:] fileprivate var todayId: String { let dateString = AppInfoTracker.dayFormatter.string(from: Date()) return dateString } fileprivate static var dayFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter }() private init() { if let versionMap = UserDefaults.standard.dictionary(forKey: TrackerKey.versionMap.rawValue) as? [String: [String: Int]] { self.versionMap = versionMap } if let versionHistory = UserDefaults.standard.stringArray(forKey: TrackerKey.versionHistory.rawValue) { self.versionHistory = versionHistory } if let dayLaunchMap = UserDefaults.standard.dictionary(forKey: TrackerKey.dayLaunch.rawValue) as? [String: Int] { self.dayLaunchMap = dayLaunchMap } } // MARK: - Tracker public class func track() { shared.startTracking() } // MARK: - First Launch public static func isFirstLaunchForVersion(_ version: String, firstLaunchCompletion: FirstLaunchClosure? = nil) -> Bool { let currentVersion = AppInfoTracker.currentVersion() let count = numbersOfStartupsForVersion(version) let isFirstLaunch: Bool = (count == 1 && currentVersion == version) if let closure = firstLaunchCompletion, isFirstLaunch == true { closure() } return isFirstLaunch } public class func isFirstLaunchForVersion(_ version: String, build: String, firstLaunchCompletion: FirstLaunchClosure? = nil) -> Bool { let currentVersion = AppInfoTracker.currentVersion() let currentBuild = AppInfoTracker.currentBuild() let count = numbersOfStartupsForVersion(version, build: build) let isFirstLaunch: Bool = (count == 1 && currentVersion == version && currentBuild == build) if let closure = firstLaunchCompletion, isFirstLaunch == true { closure() } return isFirstLaunch } public class func isFirstLaunchForToday(firstLaunchCompletion: FirstLaunchClosure? = nil) -> Bool { let count = numbersOfStartupsForToday() let isFirstLaunch: Bool = (count == 1) if let closure = firstLaunchCompletion, isFirstLaunch == true { closure() } return isFirstLaunch } // MARK: - Info public class func currentVersion() -> String { let currentVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") if let version = currentVersion as? String { return version } return "" } public class func previousVersion() -> String? { guard shared.versionHistory.count >= 2 else { return nil } return shared.versionHistory[shared.versionHistory.count - 2] } public class func currentBuild() -> String { let currentBuild = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) if let build = currentBuild as? String { return build } return "" } // MARK: - numbers of start app public class func numbersOfStartupsForVersion(_ version: String) -> Int { if let buildMap = shared.versionMap[version] { var sum = 0 for (_, value) in buildMap { sum += value } return sum } return 0 } public class func numbersOfStartupsForVersion(_ version: String, build: String) -> Int { if let buildMap = shared.versionMap[version] { if let count = buildMap[build] { return count } } return 0 } public class func numbersOfStartupsForToday() -> Int { if let num = shared.dayLaunchMap[shared.todayId] { return num } return 0 } public class func numbersOfStartupsSinceInstalled() -> Int { var sum = 0 for (_, buildMap) in shared.versionMap { for (_, value) in buildMap { sum += value } } return sum } } extension AppInfoTracker { fileprivate func startTracking() { updateFirstLaunchForVersion() updateFirstLaunchForToday() isFirstLaunchForCurrentVersion = AppInfoTracker.isFirstLaunchForVersion(AppInfoTracker.currentVersion()) isFirstLaunchForCurrentVersionAndBuild = AppInfoTracker.isFirstLaunchForVersion(AppInfoTracker.currentVersion(), build: AppInfoTracker.currentBuild()) isFirstLaunchOfToday = AppInfoTracker.numbersOfStartupsForToday() == 1 if dayLaunchMap.count > 20 { let keys = dayLaunchMap.keys.sorted() for i in 0..<10 { dayLaunchMap.removeValue(forKey: keys[i]) } } } fileprivate func updateFirstLaunchForVersion() { let currentVersion = AppInfoTracker.currentVersion() let currentBuild = AppInfoTracker.currentBuild() let latestVersion: String = versionHistory.last ?? "" if currentVersion != latestVersion { versionHistory.append(currentVersion) UserDefaults.standard.set(versionHistory, forKey: TrackerKey.versionHistory.rawValue) UserDefaults.standard.synchronize() } if var buildMap = versionMap[currentVersion] { var numbersOfStartupsForPreBuild = 1 if let count = buildMap[currentBuild] { numbersOfStartupsForPreBuild = count + 1 } buildMap[currentBuild] = numbersOfStartupsForPreBuild versionMap[currentVersion] = buildMap } else { let buildMap = [currentBuild: 1] versionMap[currentVersion] = buildMap } UserDefaults.standard.set(versionMap, forKey: TrackerKey.versionMap.rawValue) UserDefaults.standard.synchronize() } fileprivate func updateFirstLaunchForToday() { if let num = dayLaunchMap[todayId] { dayLaunchMap[todayId] = num + 1 } else { dayLaunchMap[todayId] = 1 } let keys = dayLaunchMap.keys.sorted { (s1, s2) -> Bool in return s1.compare(s2) == ComparisonResult.orderedDescending } if keys.count > 7 { dayLaunchMap.removeValue(forKey: keys[7]) } UserDefaults.standard.set(dayLaunchMap, forKey: TrackerKey.dayLaunch.rawValue) UserDefaults.standard.synchronize() } }
37fde7efe928fccb7e76de6de80ef842
33.234234
158
0.623553
false
false
false
false
zevwings/ZVRefreshing
refs/heads/master
ZVRefreshing/Footer/BackFooter/ZVRefreshBackNativeFooter.swift
mit
1
// // ZVRefreshBackDIYFooter.swift // ZVRefreshing // // Created by zevwings on 2017/7/17. // Copyright © 2017年 zevwings. All rights reserved. // import UIKit public class ZVRefreshBackNativeFooter: ZVRefreshBackStateFooter { // MARK: - Property private var arrowView: UIImageView? private var activityIndicator: UIActivityIndicatorView? public var activityIndicatorViewStyle: UIActivityIndicatorView.Style = .gray { didSet { activityIndicator?.style = activityIndicatorViewStyle setNeedsLayout() } } // MARK: - Subviews override public func prepare() { super.prepare() self.labelInsetLeft = 24.0 if arrowView == nil { arrowView = UIImageView() arrowView?.contentMode = .scaleAspectFit arrowView?.image = UIImage.arrow arrowView?.tintColor = .lightGray arrowView?.transform = CGAffineTransform(rotationAngle: 0.000001 - CGFloat(Double.pi)) addSubview(arrowView!) } if activityIndicator == nil { activityIndicator = UIActivityIndicatorView() activityIndicator?.style = activityIndicatorViewStyle activityIndicator?.hidesWhenStopped = true activityIndicator?.color = .lightGray addSubview(activityIndicator!) } } override public func placeSubViews() { super.placeSubViews() var centerX = frame.width * 0.5 if let stateLabel = stateLabel, !stateLabel.isHidden { let labelWith = stateLabel.textWidth let activityIndicatorOffset = (activityIndicator?.frame.width ?? 0.0) * 0.5 centerX -= (labelWith * 0.5 + labelInsetLeft + activityIndicatorOffset) } let centerY = frame.height * 0.5 let center = CGPoint(x: centerX, y: centerY) if let arrowView = arrowView, arrowView.constraints.isEmpty && arrowView.image != nil { arrowView.isHidden = false arrowView.frame.size = arrowView.image!.size arrowView.center = center } else { arrowView?.isHidden = true } if let activityIndicator = activityIndicator, activityIndicator.constraints.isEmpty { activityIndicator.center = center } } // MARK: - State Update open override func refreshStateUpdate( _ state: ZVRefreshControl.RefreshState, oldState: ZVRefreshControl.RefreshState ) { super.refreshStateUpdate(state, oldState: oldState) switch state { case .idle: if oldState == .refreshing { arrowView?.transform = CGAffineTransform(rotationAngle: 0.000001 - CGFloat(Double.pi)) UIView.animate(withDuration: 0.15, animations: { self.activityIndicator?.alpha = 0.0 }, completion: { _ in self.activityIndicator?.alpha = 1.0 self.activityIndicator?.stopAnimating() self.arrowView?.isHidden = false }) } else { arrowView?.isHidden = false activityIndicator?.stopAnimating() UIView.animate(withDuration: 0.15, animations: { self.arrowView?.transform = CGAffineTransform(rotationAngle: -CGFloat(Double.pi)) }) } case .pulling: arrowView?.isHidden = false activityIndicator?.stopAnimating() UIView.animate(withDuration: 0.15, animations: { self.arrowView?.transform = CGAffineTransform.identity }) case .refreshing: arrowView?.isHidden = true activityIndicator?.startAnimating() case .noMoreData: arrowView?.isHidden = true activityIndicator?.stopAnimating() default: break } } }
e8ff90be6817cb4aad4110ae331914ee
33.758621
102
0.585813
false
false
false
false
dmjio/aeson
refs/heads/master
parsers/test_PMJSON_1_1_0/Encoder.swift
bsd-3-clause
6
// // Encoder.swift // PMJSON // // Created by Kevin Ballard on 2/1/16. // Copyright © 2016 Postmates. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // extension JSON { /// Encodes a `JSON` to a `String`. /// - Parameter json: The `JSON` to encode. /// - Parameter pretty: If `true`, include extra whitespace for formatting. Default is `false`. /// - Returns: A `String` with the JSON representation of *json*. public static func encodeAsString(_ json: JSON, pretty: Bool = false) -> String { var s = "" encode(json, toStream: &s, pretty: pretty) return s } /// Encodes a `JSON` to an output stream. /// - Parameter json: The `JSON` to encode. /// - Parameter stream: The output stream to write the encoded JSON to. /// - Parameter pretty: If `true`, include extra whitespace for formatting. Default is `false`. public static func encode<Target: TextOutputStream>(_ json: JSON, toStream stream: inout Target, pretty: Bool = false) { encode(json, toStream: &stream, indent: pretty ? 0 : nil) } private static func encode<Target: TextOutputStream>(_ json: JSON, toStream stream: inout Target, indent: Int?) { switch json { case .null: encodeNull(&stream) case .bool(let b): encodeBool(b, toStream: &stream) case .int64(let i): encodeInt64(i, toStream: &stream) case .double(let d): encodeDouble(d, toStream: &stream) case .string(let s): encodeString(s, toStream: &stream) case .object(let obj): encodeObject(obj, toStream: &stream, indent: indent) case .array(let ary): encodeArray(ary, toStream: &stream, indent: indent) } } private static func encodeNull<Target: TextOutputStream>(_ stream: inout Target) { stream.write("null") } private static func encodeBool<Target: TextOutputStream>(_ value: Bool, toStream stream: inout Target) { stream.write(value ? "true" : "false") } private static func encodeInt64<Target: TextOutputStream>(_ value: Int64, toStream stream: inout Target) { stream.write(String(value)) } private static func encodeDouble<Target: TextOutputStream>(_ value: Double, toStream stream: inout Target) { stream.write(String(value)) } private static func encodeString<Target: TextOutputStream>(_ value: String, toStream stream: inout Target) { stream.write("\"") let scalars = value.unicodeScalars var start = scalars.startIndex let end = scalars.endIndex var idx = start while idx < scalars.endIndex { let s: String let c = scalars[idx] switch c { case "\\": s = "\\\\" case "\"": s = "\\\"" case "\n": s = "\\n" case "\r": s = "\\r" case "\t": s = "\\t" case "\u{8}": s = "\\b" case "\u{C}": s = "\\f" case "\0"..<"\u{10}": s = "\\u000\(String(c.value, radix: 16, uppercase: true))" case "\u{10}"..<" ": s = "\\u00\(String(c.value, radix: 16, uppercase: true))" default: idx = scalars.index(after: idx) continue } if idx != start { stream.write(String(scalars[start..<idx])) } stream.write(s) idx = scalars.index(after: idx) start = idx } if start != end { String(scalars[start..<end]).write(to: &stream) } stream.write("\"") } private static func encodeObject<Target: TextOutputStream>(_ object: JSONObject, toStream stream: inout Target, indent: Int?) { let indented = indent.map({$0+1}) if let indent = indented { stream.write("{\n") writeIndent(indent, toStream: &stream) } else { stream.write("{") } var first = true for (key, value) in object { if first { first = false } else if let indent = indented { stream.write(",\n") writeIndent(indent, toStream: &stream) } else { stream.write(",") } encodeString(key, toStream: &stream) stream.write(indented != nil ? ": " : ":") encode(value, toStream: &stream, indent: indented) } if let indent = indent { stream.write("\n") writeIndent(indent, toStream: &stream) } stream.write("}") } private static func encodeArray<Target: TextOutputStream>(_ array: JSONArray, toStream stream: inout Target, indent: Int?) { let indented = indent.map({$0+1}) if let indent = indented { stream.write("[\n") writeIndent(indent, toStream: &stream) } else { stream.write("[") } var first = true for elt in array { if first { first = false } else if let indent = indented { stream.write(",\n") writeIndent(indent, toStream: &stream) } else { stream.write(",") } encode(elt, toStream: &stream, indent: indented) } if let indent = indent { stream.write("\n") writeIndent(indent, toStream: &stream) } stream.write("]") } private static func writeIndent<Target: TextOutputStream>(_ indent: Int, toStream stream: inout Target) { for _ in stride(from: 4, through: indent, by: 4) { stream.write(" ") } switch indent % 4 { case 1: stream.write(" ") case 2: stream.write(" ") case 3: stream.write(" ") default: break } } }
54b4f507d81da446a3fd042feb5f48b3
36.017964
131
0.540925
false
false
false
false
kences/swift_weibo
refs/heads/master
Swift-SinaWeibo/Classes/Module/Main/Controller/LGMainViewController.swift
apache-2.0
1
// // LGMainViewController.swift // Swift-SinaWeibo // // Created by lu on 15/10/26. // Copyright © 2015年 lg. All rights reserved. // import UIKit class LGMainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() // 设置tabBar显示的颜色 tabBar.tintColor = UIColor.orangeColor() // 1.首页 let homeVC = LGHomeViewController() addChildViewController(homeVC, title: "首页", imageName: "tabbar_home", selImageName: "tabbar_home_highlighted") // 2.消息 let messageVC = LGMessageViewController() addChildViewController(messageVC, title: "消息", imageName: "tabbar_message_center", selImageName: "tabbar_message_center_highlighted") // 3.使用控制器来为中间的撰写按钮来占位 let vc = UIViewController() // imageName:随便给个名字让系统不报日志,如果查找不到会返回空 addChildViewController(vc, title: "", imageName: "sb", selImageName: "sb") // 4.发现 let discoverVC = LGDiscoverViewController() addChildViewController(discoverVC, title: "发现", imageName: "tabbar_discover", selImageName: "tabbar_discover_highlighted") // 5.我 let profileVC = LGProfileViewController() addChildViewController(profileVC, title: "我", imageName: "tabbar_profile", selImageName: "tabbar_profile_highlighted") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // 添加中间的撰写按钮,保证此最后被添加 tabBar.addSubview(composeBtn) // 设置frame let width = tabBar.bounds.width / 5 composeBtn.frame = CGRect(x: width * 2, y: 0, width: width, height: tabBar.bounds.height) } /// 添加子控制器 private func addChildViewController(childVC: UIViewController, title: String, imageName: String, selImageName:String) { // 设置标题和tabBar显示的图片 childVC.title = title // .imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) 图片的渲染模式 // childVC.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orangeColor()], forState: UIControlState.Normal) 文字的颜色 // tabBar.tintColor = UIColor.orangeColor() 统一设置tabBar的图片和文字 childVC.tabBarItem.image = UIImage(named: imageName) childVC.tabBarItem.selectedImage = UIImage(named: selImageName) // 包装为导航控制器,添加到tabBar控制器中 addChildViewController(UINavigationController(rootViewController: childVC)) } // MARK: - 按钮的点击事件 func composeButtonAction() { // print("composeButtonAction") if !LGUserAccount.isLogin { self.presentViewController(LGOAuthViewController(), animated: true, completion: nil) return } self.presentViewController(UINavigationController(rootViewController: LGComposeViewController()), animated: true, completion: nil) } // MARK: - 懒加载 // 撰写按钮 lazy var composeBtn: UIButton = { let composeBtn = UIButton() // 设置背景 composeBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal) composeBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted) // 设置显示图片 composeBtn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal) composeBtn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted) // 为按钮添加点击事件 composeBtn.addTarget(self, action: "composeButtonAction", forControlEvents: UIControlEvents.TouchUpInside) return composeBtn }() }
6a60096477e44378c7b34dcd8d776f63
33.623853
147
0.654478
false
false
false
false
Jnosh/swift
refs/heads/master
test/SILGen/keypath_application.swift
apache-2.0
4
// RUN: %target-swift-frontend -enable-experimental-keypath-components -emit-silgen %s | %FileCheck %s class A {} class B {} protocol P {} protocol Q {} // CHECK-LABEL: sil hidden @{{.*}}loadable func loadable(readonly: A, writable: inout A, value: B, kp: KeyPath<A, B>, wkp: WritableKeyPath<A, B>, rkp: ReferenceWritableKeyPath<A, B>) { // CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A // CHECK: [[ROOT_BORROW:%.*]] = begin_borrow %0 // CHECK: [[ROOT_COPY:%.*]] = copy_value [[ROOT_BORROW]] // CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]] // CHECK: [[KP_BORROW:%.*]] = begin_borrow %3 // CHECK: [[KP_COPY:%.*]] = copy_value [[KP_BORROW]] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly // CHECK: [[RESULT_TMP:%.*]] = alloc_stack $B // CHECK: apply [[PROJECT]]<A, B>([[RESULT_TMP]], [[ROOT_TMP]], [[KP_COPY]]) // CHECK: [[RESULT:%.*]] = load [take] [[RESULT_TMP]] // CHECK: destroy_value [[RESULT]] _ = readonly[keyPath: kp] _ = writable[keyPath: kp] _ = readonly[keyPath: wkp] // CHECK: [[TEMP:%.*]] = mark_uninitialized // CHECK: [[ROOT_ACCESS:%.*]] = begin_access [read] [unknown] %1 : $*A // CHECK: [[ROOT_RAW_PTR:%.*]] = address_to_pointer [[ROOT_ACCESS]] // CHECK: [[ROOT_PTR:%.*]] = struct $UnsafeMutablePointer<A> ([[ROOT_RAW_PTR]] // CHECK: [[KP_BORROW:%.*]] = begin_borrow %4 // CHECK: [[KP_COPY:%.*]] = copy_value [[KP_BORROW]] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathWritable // CHECK: [[PROJECTED:%.*]] = apply [[PROJECT]]<A, B>([[ROOT_PTR]], [[KP_COPY]]) // CHECK: [[PROJECTED_BORROW:%.*]] = begin_borrow [[PROJECTED]] // CHECK: [[PROJECTED_PTR:%.*]] = tuple_extract [[PROJECTED_BORROW]] // CHECK: [[PROJECTED_OWNER_B:%.*]] = tuple_extract [[PROJECTED_BORROW]] // CHECK: [[PROJECTED_OWNER:%.*]] = copy_value [[PROJECTED_OWNER_B]] // CHECK: destroy_value [[PROJECTED]] // CHECK: [[PROJECTED_RAW_PTR:%.*]] = struct_extract [[PROJECTED_PTR]] // CHECK: [[PROJECTED_ADDR:%.*]] = pointer_to_address [[PROJECTED_RAW_PTR]] // CHECK: [[PROJECTED_DEP:%.*]] = mark_dependence [[PROJECTED_ADDR]] : $*B on [[PROJECTED_OWNER]] // CHECK: [[COPY_TMP:%.*]] = load [copy] [[PROJECTED_DEP]] : $*B // CHECK: assign [[COPY_TMP]] to [[TEMP]] : $*B // CHECK: destroy_value [[PROJECTED_OWNER]] _ = writable[keyPath: wkp] // CHECK: [[TEMP:%.*]] = mark_uninitialized // CHECK: [[ROOT_BORROW:%.*]] = begin_borrow %0 // CHECK: [[ROOT_COPY:%.*]] = copy_value [[ROOT_BORROW]] // CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A // CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]] // CHECK: [[KP_BORROW:%.*]] = begin_borrow %5 // CHECK: [[KP_COPY:%.*]] = copy_value [[KP_BORROW]] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReferenceWritable // CHECK: [[PROJECTED:%.*]] = apply [[PROJECT]]<A, B>([[ROOT_TMP]], [[KP_COPY]]) // CHECK: [[PROJECTED_BORROW:%.*]] = begin_borrow [[PROJECTED]] // CHECK: [[PROJECTED_PTR:%.*]] = tuple_extract [[PROJECTED_BORROW]] // CHECK: [[PROJECTED_OWNER_B:%.*]] = tuple_extract [[PROJECTED_BORROW]] // CHECK: [[PROJECTED_OWNER:%.*]] = copy_value [[PROJECTED_OWNER_B]] // CHECK: destroy_value [[PROJECTED]] // CHECK: [[PROJECTED_RAW_PTR:%.*]] = struct_extract [[PROJECTED_PTR]] // CHECK: [[PROJECTED_ADDR:%.*]] = pointer_to_address [[PROJECTED_RAW_PTR]] // CHECK: [[PROJECTED_DEP:%.*]] = mark_dependence [[PROJECTED_ADDR]] : $*B on [[PROJECTED_OWNER]] // CHECK: [[COPY_TMP:%.*]] = load [copy] [[PROJECTED_DEP]] : $*B // CHECK: assign [[COPY_TMP]] to [[TEMP]] : $*B // CHECK: destroy_value [[PROJECTED_OWNER]] _ = readonly[keyPath: rkp] _ = writable[keyPath: rkp] writable[keyPath: wkp] = value readonly[keyPath: rkp] = value writable[keyPath: rkp] = value } // CHECK-LABEL: sil hidden @{{.*}}addressOnly func addressOnly(readonly: P, writable: inout P, value: Q, kp: KeyPath<P, Q>, wkp: WritableKeyPath<P, Q>, rkp: ReferenceWritableKeyPath<P, Q>) { // CHECK: [[ROOT_TMP:%.*]] = alloc_stack $P // CHECK: copy_addr %0 to [initialization] [[ROOT_TMP]] // CHECK: [[KP_BORROW:%.*]] = begin_borrow %3 // CHECK: [[KP_COPY:%.*]] = copy_value [[KP_BORROW]] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly // CHECK: [[RESULT:%.*]] = alloc_stack $Q // CHECK: apply [[PROJECT]]<P, Q>([[RESULT]], [[ROOT_TMP]], [[KP_COPY]]) // CHECK: destroy_addr [[RESULT]] _ = readonly[keyPath: kp] _ = writable[keyPath: kp] _ = readonly[keyPath: wkp] // CHECK: [[TEMP:%.*]] = mark_uninitialized // CHECK: [[ROOT_ACCESS:%.*]] = begin_access [read] [unknown] %1 : $*P // CHECK: [[ROOT_RAW_PTR:%.*]] = address_to_pointer [[ROOT_ACCESS]] // CHECK: [[ROOT_PTR:%.*]] = struct $UnsafeMutablePointer<P> ([[ROOT_RAW_PTR]] // CHECK: [[KP_BORROW:%.*]] = begin_borrow %4 // CHECK: [[KP_COPY:%.*]] = copy_value [[KP_BORROW]] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathWritable // CHECK: [[PROJECTED:%.*]] = apply [[PROJECT]]<P, Q>([[ROOT_PTR]], [[KP_COPY]]) // CHECK: [[PROJECTED_BORROW:%.*]] = begin_borrow [[PROJECTED]] // CHECK: [[PROJECTED_PTR:%.*]] = tuple_extract [[PROJECTED_BORROW]] // CHECK: [[PROJECTED_OWNER_B:%.*]] = tuple_extract [[PROJECTED_BORROW]] // CHECK: [[PROJECTED_OWNER:%.*]] = copy_value [[PROJECTED_OWNER_B]] // CHECK: destroy_value [[PROJECTED]] // CHECK: [[PROJECTED_RAW_PTR:%.*]] = struct_extract [[PROJECTED_PTR]] // CHECK: [[PROJECTED_ADDR:%.*]] = pointer_to_address [[PROJECTED_RAW_PTR]] // CHECK: [[PROJECTED_DEP:%.*]] = mark_dependence [[PROJECTED_ADDR]] : $*Q on [[PROJECTED_OWNER]] // CHECK: copy_addr [[PROJECTED_DEP]] to [initialization] [[CPY_TMP:%.*]] : $*Q // CHECK: copy_addr [take] [[CPY_TMP]] to [[TEMP]] : $*Q // CHECK: destroy_value [[PROJECTED_OWNER]] _ = writable[keyPath: wkp] // CHECK: [[TEMP:%.*]] = mark_uninitialized // CHECK: [[ROOT_TMP:%.*]] = alloc_stack $P // CHECK: copy_addr %0 to [initialization] [[ROOT_TMP]] // CHECK: [[KP_BORROW:%.*]] = begin_borrow %5 // CHECK: [[KP_COPY:%.*]] = copy_value [[KP_BORROW]] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReferenceWritable // CHECK: [[PROJECTED:%.*]] = apply [[PROJECT]]<P, Q>([[ROOT_TMP]], [[KP_COPY]]) // CHECK: [[PROJECTED_BORROW:%.*]] = begin_borrow [[PROJECTED]] // CHECK: [[PROJECTED_PTR:%.*]] = tuple_extract [[PROJECTED_BORROW]] // CHECK: [[PROJECTED_OWNER_B:%.*]] = tuple_extract [[PROJECTED_BORROW]] // CHECK: [[PROJECTED_OWNER:%.*]] = copy_value [[PROJECTED_OWNER_B]] // CHECK: destroy_value [[PROJECTED]] // CHECK: [[PROJECTED_RAW_PTR:%.*]] = struct_extract [[PROJECTED_PTR]] // CHECK: [[PROJECTED_ADDR:%.*]] = pointer_to_address [[PROJECTED_RAW_PTR]] // CHECK: [[PROJECTED_DEP:%.*]] = mark_dependence [[PROJECTED_ADDR]] : $*Q on [[PROJECTED_OWNER]] // CHECK: copy_addr [[PROJECTED_DEP]] to [initialization] [[CPY_TMP:%.*]] : $*Q // CHECK: copy_addr [take] [[CPY_TMP]] to [[TEMP]] : $*Q // CHECK: destroy_value [[PROJECTED_OWNER]] _ = readonly[keyPath: rkp] _ = writable[keyPath: rkp] writable[keyPath: wkp] = value readonly[keyPath: rkp] = value writable[keyPath: rkp] = value } // CHECK-LABEL: sil hidden @{{.*}}reabstracted func reabstracted(readonly: @escaping () -> (), writable: inout () -> (), value: @escaping (A) -> B, kp: KeyPath<() -> (), (A) -> B>, wkp: WritableKeyPath<() -> (), (A) -> B>, rkp: ReferenceWritableKeyPath<() -> (), (A) -> B>) { // CHECK: [[ROOT_TMP:%.*]] = alloc_stack $@callee_owned (@in ()) -> @out () // CHECK: [[ROOT_BORROW:%.*]] = begin_borrow %0 // CHECK: [[ROOT_COPY:%.*]] = copy_value [[ROOT_BORROW]] // CHECK: [[ROOT_ORIG:%.*]] = partial_apply {{.*}}([[ROOT_COPY]]) // CHECK: store [[ROOT_ORIG]] to [init] [[ROOT_TMP]] // CHECK: [[KP_BORROW:%.*]] = begin_borrow %3 // CHECK: [[KP_COPY:%.*]] = copy_value [[KP_BORROW]] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly // CHECK: [[RESULT_TMP:%.*]] = alloc_stack $@callee_owned (@in A) -> @out B // CHECK: apply [[PROJECT]]<() -> (), (A) -> B>([[RESULT_TMP]], [[ROOT_TMP]], [[KP_COPY]]) // CHECK: [[RESULT_ORIG:%.*]] = load [take] [[RESULT_TMP]] // CHECK: [[RESULT_SUBST:%.*]] = partial_apply {{.*}}([[RESULT_ORIG]]) // CHECK: destroy_value [[RESULT_SUBST]] _ = readonly[keyPath: kp] _ = writable[keyPath: kp] _ = readonly[keyPath: wkp] // CHECK: [[TEMP_SUBST:%.*]] = mark_uninitialized {{.*}} : $*@callee_owned (@owned A) -> @owned B // CHECK: [[ROOT_ACCESS:%.*]] = begin_access [read] [unknown] %1 : $*@callee_owned () -> () // CHECK: [[ROOT_ORIG_TMP:%.*]] = alloc_stack $@callee_owned (@in ()) -> @out () // CHECK: [[ROOT_SUBST:%.*]] = load [copy] [[ROOT_ACCESS]] // CHECK: [[ROOT_ORIG:%.*]] = partial_apply {{.*}}([[ROOT_SUBST]]) // CHECK: store [[ROOT_ORIG]] to [init] [[ROOT_ORIG_TMP]] // CHECK: [[ROOT_RAW_PTR:%.*]] = address_to_pointer [[ROOT_ORIG_TMP]] // CHECK: [[ROOT_PTR:%.*]] = struct $UnsafeMutablePointer<() -> ()> ([[ROOT_RAW_PTR]] // CHECK: [[KP_BORROW:%.*]] = begin_borrow %4 // CHECK: [[KP_COPY:%.*]] = copy_value [[KP_BORROW]] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathWritable // CHECK: [[PROJECTED:%.*]] = apply [[PROJECT]]<() -> (), (A) -> B>([[ROOT_PTR]], [[KP_COPY]]) // CHECK: [[PROJECTED_BORROW:%.*]] = begin_borrow [[PROJECTED]] // CHECK: [[PROJECTED_PTR:%.*]] = tuple_extract [[PROJECTED_BORROW]] // CHECK: [[PROJECTED_OWNER_B:%.*]] = tuple_extract [[PROJECTED_BORROW]] // CHECK: [[PROJECTED_OWNER:%.*]] = copy_value [[PROJECTED_OWNER_B]] // CHECK: destroy_value [[PROJECTED]] // CHECK: [[PROJECTED_RAW_PTR:%.*]] = struct_extract [[PROJECTED_PTR]] // CHECK: [[PROJECTED_ORIG_ADDR:%.*]] = pointer_to_address [[PROJECTED_RAW_PTR]] {{.*}} to [strict] $*@callee_owned (@in A) -> @out B // CHECK: [[PROJECTED_DEP:%.*]] = mark_dependence [[PROJECTED_ORIG_ADDR]] : $*@callee_owned (@in A) -> @out B on [[PROJECTED_OWNER]] // CHECK: [[PROJECTED_ORIG:%.*]] = load [copy] [[PROJECTED_DEP]] // CHECK: [[PROJECTED_SUBST:%.*]] = partial_apply {{.*}}([[PROJECTED_ORIG]]) // CHECK: destroy_addr [[ROOT_ORIG_TMP]] // CHECK: assign [[PROJECTED_SUBST]] to [[TEMP_SUBST]] // CHECK: destroy_value [[PROJECTED_OWNER]] _ = writable[keyPath: wkp] // CHECK: [[TEMP:%.*]] = mark_uninitialized // CHECK: [[ROOT_BORROW:%.*]] = begin_borrow %0 // CHECK: [[ROOT_COPY_SUBST:%.*]] = copy_value [[ROOT_BORROW]] // CHECK: [[ROOT_COPY_ORIG:%.*]] = partial_apply {{.*}}([[ROOT_COPY_SUBST]]) // CHECK: [[ROOT_TMP:%.*]] = alloc_stack $@callee_owned (@in ()) -> @out () // CHECK: store [[ROOT_COPY_ORIG]] to [init] [[ROOT_TMP]] // CHECK: [[KP_BORROW:%.*]] = begin_borrow %5 // CHECK: [[KP_COPY:%.*]] = copy_value [[KP_BORROW]] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReferenceWritable // CHECK: [[PROJECTED:%.*]] = apply [[PROJECT]]<() -> (), (A) -> B>([[ROOT_TMP]], [[KP_COPY]]) // CHECK: [[PROJECTED_BORROW:%.*]] = begin_borrow [[PROJECTED]] // CHECK: [[PROJECTED_PTR:%.*]] = tuple_extract [[PROJECTED_BORROW]] // CHECK: [[PROJECTED_OWNER_B:%.*]] = tuple_extract [[PROJECTED_BORROW]] // CHECK: [[PROJECTED_OWNER:%.*]] = copy_value [[PROJECTED_OWNER_B]] // CHECK: destroy_value [[PROJECTED]] // CHECK: [[PROJECTED_RAW_PTR:%.*]] = struct_extract [[PROJECTED_PTR]] // CHECK: [[PROJECTED_ADDR_ORIG:%.*]] = pointer_to_address [[PROJECTED_RAW_PTR]] {{.*}} to [strict] $*@callee_owned (@in A) -> @out B // CHECK: [[PROJECTED_DEP:%.*]] = mark_dependence [[PROJECTED_ADDR_ORIG]] : $*@callee_owned (@in A) -> @out B on [[PROJECTED_OWNER]] // CHECK: [[PROJECTED_ORIG:%.*]] = load [copy] [[PROJECTED_DEP]] // CHECK: [[PROJECTED_SUBST:%.*]] = partial_apply {{.*}}([[PROJECTED_ORIG]]) // CHECK: assign [[PROJECTED_SUBST]] to [[TEMP]] // CHECK: destroy_value [[PROJECTED_OWNER]] _ = readonly[keyPath: rkp] _ = writable[keyPath: rkp] writable[keyPath: wkp] = value readonly[keyPath: rkp] = value writable[keyPath: rkp] = value } // CHECK-LABEL: sil hidden @{{.*}}partial func partial<A>(valueA: A, valueB: Int, pkpA: PartialKeyPath<A>, pkpB: PartialKeyPath<Int>, akp: AnyKeyPath) { // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathAny // CHECK: apply [[PROJECT]]<A> _ = valueA[keyPath: akp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathPartial // CHECK: apply [[PROJECT]]<A> _ = valueA[keyPath: pkpA] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathAny // CHECK: apply [[PROJECT]]<Int> _ = valueB[keyPath: akp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathPartial // CHECK: apply [[PROJECT]]<Int> _ = valueB[keyPath: pkpB] }
c8012e66b875d9d6eb95c511579cd1b2
52.119342
135
0.569879
false
false
false
false
Mikelulu/BaiSiBuDeQiJie
refs/heads/master
LKBS/Pods/BMPlayer/Source/BMPlayer.swift
mit
1
// // BMPlayer.swift // Pods // // Created by BrikerMan on 16/4/28. // // import UIKit import SnapKit import MediaPlayer /// BMPlayerDelegate to obserbe player state public protocol BMPlayerDelegate : class { func bmPlayer(player: BMPlayer ,playerStateDidChange state: BMPlayerState) func bmPlayer(player: BMPlayer ,loadedTimeDidChange loadedDuration: TimeInterval, totalDuration: TimeInterval) func bmPlayer(player: BMPlayer ,playTimeDidChange currentTime : TimeInterval, totalTime: TimeInterval) func bmPlayer(player: BMPlayer ,playerIsPlaying playing: Bool) } /** internal enum to check the pan direction - horizontal: horizontal - vertical: vertical */ enum BMPanDirection: Int { case horizontal = 0 case vertical = 1 } open class BMPlayer: UIView { open weak var delegate: BMPlayerDelegate? open var backBlock:((Bool) -> Void)? /// Gesture to change volume / brightness open var panGesture: UIPanGestureRecognizer! /// AVLayerVideoGravityType open var videoGravity = AVLayerVideoGravityResizeAspect { didSet { self.playerLayer?.videoGravity = videoGravity } } open var isPlaying: Bool { get { return playerLayer?.isPlaying ?? false } } //Closure fired when play time changed open var playTimeDidChange:((TimeInterval, TimeInterval) -> Void)? //Closure fired when play state chaged open var playStateDidChange:((Bool) -> Void)? open var avPlayer: AVPlayer? { return playerLayer?.player } open var playerLayer: BMPlayerLayerView? fileprivate var resource: BMPlayerResource! fileprivate var currentDefinition = 0 fileprivate var controlView: BMPlayerControlView! fileprivate var customControlView: BMPlayerControlView? fileprivate var isFullScreen:Bool { get { return UIApplication.shared.statusBarOrientation.isLandscape } } /// 滑动方向 fileprivate var panDirection = BMPanDirection.horizontal /// 音量滑竿 fileprivate var volumeViewSlider: UISlider! fileprivate let BMPlayerAnimationTimeInterval:Double = 4.0 fileprivate let BMPlayerControlBarAutoFadeOutTimeInterval:Double = 0.5 /// 用来保存时间状态 fileprivate var sumTime : TimeInterval = 0 fileprivate var totalDuration : TimeInterval = 0 fileprivate var currentPosition : TimeInterval = 0 fileprivate var shouldSeekTo : TimeInterval = 0 fileprivate var isURLSet = false fileprivate var isSliderSliding = false fileprivate var isPauseByUser = false fileprivate var isVolume = false fileprivate var isMaskShowing = false fileprivate var isSlowed = false fileprivate var isMirrored = false fileprivate var isPlayToTheEnd = false //视频画面比例 fileprivate var aspectRatio:BMPlayerAspectRatio = .default //Cache is playing result to improve callback performance fileprivate var isPlayingCache: Bool? = nil // MARK: - Public functions /** Play - parameter resource: media resource - parameter definitionIndex: starting definition index, default start with the first definition */ open func setVideo(resource: BMPlayerResource, definitionIndex: Int = 0) { isURLSet = false self.resource = resource currentDefinition = definitionIndex controlView.prepareUI(for: resource, selectedIndex: definitionIndex) if BMPlayerConf.shouldAutoPlay { isURLSet = true let asset = resource.definitions[definitionIndex] playerLayer?.playAsset(asset: asset.avURLAsset) } else { controlView.showCover(url: resource.cover) controlView.hideLoader() } } /** auto start playing, call at viewWillAppear, See more at pause */ open func autoPlay() { if !isPauseByUser && isURLSet && !isPlayToTheEnd { play() } } /** Play */ open func play() { if resource == nil { return } if !isURLSet { let asset = resource.definitions[currentDefinition] playerLayer?.playAsset(asset: asset.avURLAsset) controlView.hideCoverImageView() isURLSet = true } panGesture.isEnabled = true playerLayer?.play() isPauseByUser = false } /** Pause - parameter allow: should allow to response `autoPlay` function */ open func pause(allowAutoPlay allow: Bool = false) { playerLayer?.pause() isPauseByUser = !allow } /** seek - parameter to: target time */ open func seek(_ to:TimeInterval, completion: (()->Void)? = nil) { playerLayer?.seek(to: to, completion: completion) } /** update UI to fullScreen */ open func updateUI(_ isFullScreen: Bool) { controlView.updateUI(isFullScreen) } /** increade volume with step, default step 0.1 - parameter step: step */ open func addVolume(step: Float = 0.1) { self.volumeViewSlider.value += step } /** decreace volume with step, default step 0.1 - parameter step: step */ open func reduceVolume(step: Float = 0.1) { self.volumeViewSlider.value -= step } /** prepare to dealloc player, call at View or Controllers deinit funciton. */ open func prepareToDealloc() { playerLayer?.prepareToDeinit() controlView.prepareToDealloc() } /** If you want to create BMPlayer with custom control in storyboard. create a subclass and override this method. - return: costom control which you want to use */ class open func storyBoardCustomControl() -> BMPlayerControlView? { return nil } // MARK: - Action Response @objc fileprivate func panDirection(_ pan: UIPanGestureRecognizer) { // 根据在view上Pan的位置,确定是调音量还是亮度 let locationPoint = pan.location(in: self) // 我们要响应水平移动和垂直移动 // 根据上次和本次移动的位置,算出一个速率的point let velocityPoint = pan.velocity(in: self) // 判断是垂直移动还是水平移动 switch pan.state { case UIGestureRecognizerState.began: // 使用绝对值来判断移动的方向 let x = fabs(velocityPoint.x) let y = fabs(velocityPoint.y) if x > y { self.panDirection = BMPanDirection.horizontal // 给sumTime初值 if let player = playerLayer?.player { let time = player.currentTime() self.sumTime = TimeInterval(time.value) / TimeInterval(time.timescale) } } else { self.panDirection = BMPanDirection.vertical if locationPoint.x > self.bounds.size.width / 2 { self.isVolume = true } else { self.isVolume = false } } case UIGestureRecognizerState.changed: switch self.panDirection { case BMPanDirection.horizontal: self.horizontalMoved(velocityPoint.x) case BMPanDirection.vertical: self.verticalMoved(velocityPoint.y) } case UIGestureRecognizerState.ended: // 移动结束也需要判断垂直或者平移 // 比如水平移动结束时,要快进到指定位置,如果这里没有判断,当我们调节音量完之后,会出现屏幕跳动的bug switch (self.panDirection) { case BMPanDirection.horizontal: controlView.hideSeekToView() isSliderSliding = false if isPlayToTheEnd { isPlayToTheEnd = false seek(self.sumTime, completion: { self.play() }) } else { seek(self.sumTime, completion: { self.autoPlay() }) } // 把sumTime滞空,不然会越加越多 self.sumTime = 0.0 case BMPanDirection.vertical: self.isVolume = false } default: break } } fileprivate func verticalMoved(_ value: CGFloat) { self.isVolume ? (self.volumeViewSlider.value -= Float(value / 10000)) : (UIScreen.main.brightness -= value / 10000) } fileprivate func horizontalMoved(_ value: CGFloat) { isSliderSliding = true if let playerItem = playerLayer?.playerItem { // 每次滑动需要叠加时间,通过一定的比例,使滑动一直处于统一水平 self.sumTime = self.sumTime + TimeInterval(value) / 100.0 * (TimeInterval(self.totalDuration)/400) let totalTime = playerItem.duration // 防止出现NAN if totalTime.timescale == 0 { return } let totalDuration = TimeInterval(totalTime.value) / TimeInterval(totalTime.timescale) if (self.sumTime >= totalDuration) { self.sumTime = totalDuration} if (self.sumTime <= 0){ self.sumTime = 0} controlView.showSeekToView(to: sumTime, total: totalDuration, isAdd: value > 0) } } @objc fileprivate func onOrientationChanged() { self.updateUI(isFullScreen) } @objc fileprivate func fullScreenButtonPressed() { controlView.updateUI(!self.isFullScreen) if isFullScreen { UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation") UIApplication.shared.setStatusBarHidden(false, with: .fade) UIApplication.shared.statusBarOrientation = .portrait } else { UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation") UIApplication.shared.setStatusBarHidden(false, with: .fade) UIApplication.shared.statusBarOrientation = .landscapeRight } } // MARK: - 生命周期 deinit { playerLayer?.pause() playerLayer?.prepareToDeinit() NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidChangeStatusBarOrientation, object: nil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) if let customControlView = classForCoder.storyBoardCustomControl() { self.customControlView = customControlView } initUI() initUIData() configureVolume() preparePlayer() } @available(*, deprecated:3.0, message:"Use newer init(customControlView:_)") public convenience init(customControllView: BMPlayerControlView?) { self.init(customControlView: customControllView) } public init(customControlView: BMPlayerControlView?) { super.init(frame:CGRect.zero) self.customControlView = customControlView initUI() initUIData() configureVolume() preparePlayer() } public convenience init() { self.init(customControlView:nil) } // MARK: - 初始化 fileprivate func initUI() { self.backgroundColor = UIColor.black if let customView = customControlView { controlView = customView } else { controlView = BMPlayerControlView() } addSubview(controlView) controlView.updateUI(isFullScreen) controlView.delegate = self controlView.player = self controlView.snp.makeConstraints { (make) in make.edges.equalTo(self) } panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.panDirection(_:))) self.addGestureRecognizer(panGesture) } fileprivate func initUIData() { NotificationCenter.default.addObserver(self, selector: #selector(self.onOrientationChanged), name: NSNotification.Name.UIApplicationDidChangeStatusBarOrientation, object: nil) } fileprivate func configureVolume() { let volumeView = MPVolumeView() for view in volumeView.subviews { if let slider = view as? UISlider { self.volumeViewSlider = slider } } } fileprivate func preparePlayer() { playerLayer = BMPlayerLayerView() playerLayer!.videoGravity = videoGravity insertSubview(playerLayer!, at: 0) playerLayer!.snp.makeConstraints { (make) in make.edges.equalTo(self) } playerLayer!.delegate = self controlView.showLoader() self.layoutIfNeeded() } } extension BMPlayer: BMPlayerLayerViewDelegate { public func bmPlayer(player: BMPlayerLayerView, playerIsPlaying playing: Bool) { controlView.playStateDidChange(isPlaying: playing) delegate?.bmPlayer(player: self, playerIsPlaying: playing) playStateDidChange?(player.isPlaying) } public func bmPlayer(player: BMPlayerLayerView ,loadedTimeDidChange loadedDuration: TimeInterval , totalDuration: TimeInterval) { BMPlayerManager.shared.log("loadedTimeDidChange - \(loadedDuration) - \(totalDuration)") controlView.loadedTimeDidChange(loadedDuration: loadedDuration , totalDuration: totalDuration) delegate?.bmPlayer(player: self, loadedTimeDidChange: loadedDuration, totalDuration: totalDuration) controlView.totalDuration = totalDuration self.totalDuration = totalDuration } public func bmPlayer(player: BMPlayerLayerView, playerStateDidChange state: BMPlayerState) { BMPlayerManager.shared.log("playerStateDidChange - \(state)") controlView.playerStateDidChange(state: state) switch state { case BMPlayerState.readyToPlay: if !isPauseByUser { play() } if shouldSeekTo != 0 { seek(shouldSeekTo, completion: { if !self.isPauseByUser { self.play() } else { self.pause() } }) } case BMPlayerState.bufferFinished: autoPlay() case BMPlayerState.playedToTheEnd: isPlayToTheEnd = true default: break } panGesture.isEnabled = state != .playedToTheEnd delegate?.bmPlayer(player: self, playerStateDidChange: state) } public func bmPlayer(player: BMPlayerLayerView, playTimeDidChange currentTime: TimeInterval, totalTime: TimeInterval) { BMPlayerManager.shared.log("playTimeDidChange - \(currentTime) - \(totalTime)") delegate?.bmPlayer(player: self, playTimeDidChange: currentTime, totalTime: totalTime) self.currentPosition = currentTime totalDuration = totalTime if isSliderSliding { return } controlView.playTimeDidChange(currentTime: currentTime, totalTime: totalTime) controlView.totalDuration = totalDuration playTimeDidChange?(currentTime, totalTime) } } extension BMPlayer: BMPlayerControlViewDelegate { public func controlView(controlView: BMPlayerControlView, didChooseDefition index: Int) { shouldSeekTo = currentPosition playerLayer?.resetPlayer() currentDefinition = index playerLayer?.playAsset(asset: resource.definitions[index].avURLAsset) } public func controlView(controlView: BMPlayerControlView, didPressButton button: UIButton) { if let action = BMPlayerControlView.ButtonType(rawValue: button.tag) { switch action { case .back: backBlock?(isFullScreen) if isFullScreen { fullScreenButtonPressed() } else { playerLayer?.prepareToDeinit() } case .play: if button.isSelected { pause() } else { if isPlayToTheEnd { seek(0, completion: { self.play() }) controlView.hidePlayToTheEndView() isPlayToTheEnd = false } play() } case .replay: isPlayToTheEnd = false seek(0) play() case .fullscreen: fullScreenButtonPressed() default: print("[Error] unhandled Action") } } } public func controlView(controlView: BMPlayerControlView, slider: UISlider, onSliderEvent event: UIControlEvents) { switch event { case UIControlEvents.touchDown: playerLayer?.onTimeSliderBegan() isSliderSliding = true case UIControlEvents.touchUpInside : isSliderSliding = false let target = self.totalDuration * Double(slider.value) if isPlayToTheEnd { isPlayToTheEnd = false seek(target, completion: { self.play() }) controlView.hidePlayToTheEndView() } else { seek(target, completion: { self.autoPlay() }) } default: break } } public func controlView(controlView: BMPlayerControlView, didChangeVideoAspectRatio: BMPlayerAspectRatio) { self.playerLayer?.aspectRatio = self.aspectRatio } public func controlView(controlView: BMPlayerControlView, didChangeVideoPlaybackRate rate: Float) { self.playerLayer?.player?.rate = rate } }
b4d61e639d0d52ac9242b419adfc159f
31.467372
183
0.585963
false
false
false
false
dvor/Antidote
refs/heads/master
Antidote/KeyboardNotificationController.swift
mit
1
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import UIKit class KeyboardNotificationController: UIViewController { init() { super.init(nibName: nil, bundle: nil) let center = NotificationCenter.default center.addObserver(self, selector: #selector(KeyboardNotificationController.keyboardWillShowNotification(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) center.addObserver(self, selector: #selector(KeyboardNotificationController.keyboardWillHideNotification(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { let center = NotificationCenter.default center.removeObserver(self) } func keyboardWillShowAnimated(keyboardFrame frame: CGRect) { // nop } func keyboardWillHideAnimated(keyboardFrame frame: CGRect) { // nop } func keyboardWillShowNotification(_ notification: Notification) { handleNotification(notification, willShow: true) } func keyboardWillHideNotification(_ notification: Notification) { handleNotification(notification, willShow: false) } } private extension KeyboardNotificationController { func handleNotification(_ notification: Notification, willShow: Bool) { let userInfo = notification.userInfo! let frame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue let curve = UIViewAnimationCurve(rawValue: (userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue)! let options: UIViewAnimationOptions switch curve { case .easeInOut: options = UIViewAnimationOptions() case .easeIn: options = .curveEaseIn case .easeOut: options = .curveEaseOut case .linear: options = .curveLinear } UIView.animate(withDuration: duration, delay: 0.0, options: options, animations: { [unowned self] in willShow ? self.keyboardWillShowAnimated(keyboardFrame: frame) : self.keyboardWillHideAnimated(keyboardFrame: frame) }, completion: nil) } }
ff373398e27b009498837c18523e485a
36.791045
177
0.691548
false
false
false
false
yeokm1/nus-soc-print-ios
refs/heads/master
NUS SOC Print/Storage.swift
mit
1
// // Storage.swift // NUS SOC Print // // Created by Yeo Kheng Meng on 12/8/14. // Copyright (c) 2014 Yeo Kheng Meng. All rights reserved. // import Foundation private let KEY_USERNAME = "KEY_USERNAME" private let KEY_PASSWORD = "KEY_PASSWORD" private let KEY_PRINTER = "KEY_PRINTER" private let KEY_SERVER = "KEY_SERVER" private let DEFAULT_SERVER = "sunfire.comp.nus.edu.sg" private let NATIVE_PRINTER_LIST = ["psts", "psts-sx", "pstsb", "pstsb-sx", "pstsc", "pstsc-sx", "psc008", "psc008-sx", "psc011", "psc011-sx", "psc245", "psc245-sx"] private let theOne : Storage = Storage() private var preferences : NSUserDefaults! class Storage { class var sharedInstance : Storage { preferences = NSUserDefaults.standardUserDefaults() return theOne } func getUsername() -> String? { return preferences.stringForKey(KEY_USERNAME) } func storeUsername(newUsername : String) { preferences.setObject(newUsername, forKey: KEY_USERNAME) } func getPassword() -> String? { return preferences.stringForKey(KEY_PASSWORD) } func storePassword(newPassword : String) { preferences.setObject(newPassword, forKey: KEY_PASSWORD) } func getPrinter() -> String? { return preferences.stringForKey(KEY_PRINTER) } func getPrinterList() -> Array<String> { let storedPrinter : String? = getPrinter() if(storedPrinter == nil || storedPrinter!.isEmpty){ return NATIVE_PRINTER_LIST } else { var newList : Array<String> = [storedPrinter!] for nativePrinter in NATIVE_PRINTER_LIST{ newList.append(nativePrinter) } return newList } } func storePrinter(newPrinter : String) { preferences.setObject(newPrinter, forKey: KEY_PRINTER) } func getServer() -> String { let storedServer : String? = preferences.stringForKey(KEY_SERVER) if(storedServer == nil || storedServer!.utf16.count == 0){ return DEFAULT_SERVER; } else { return storedServer!; } } func storeServer(newServer : String) { preferences.setObject(newServer, forKey: KEY_SERVER) } }
4cec3f961660c3a74dc312557b63071e
23.936842
164
0.601098
false
false
false
false
yonadev/yona-app-ios
refs/heads/develop
Yona/YonaTests/ActivityAPIServiceTests.swift
mpl-2.0
1
// // ActivityAPIServiceTests.swift // Yona // // Created by Ben Smith on 13/04/16. // Copyright © 2016 Yona. All rights reserved. // import XCTest @testable import Yona class ActivityAPIServiceTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } func testGetActivitiesNotAddedAfterAddingNoGoalsOtherThanMandatoryOne() { //setup let expectation = self.expectation(description: "Waiting to respond") let randomPhoneNumber = Int(arc4random_uniform(9999999)) let body = ["firstName": "Richard", "lastName": "Quin", "mobileNumber": "+31343" + String(randomPhoneNumber), "nickname": "RQ"] //Get user goals UserRequestManager.sharedInstance.postUser(body, confirmCode: nil) { (success, message, code, users) in if success == false{ XCTFail() } //confirm mobile number check, static code UserRequestManager.sharedInstance.confirmMobileNumber(["code":YonaConstants.testKeys.otpTestCode]) { success, message, code in if success { ActivitiesRequestManager.sharedInstance.getActivitiesNotAddedWithTheUsersGoals({ (success, message, code, budgetactivities, timezoneactivities, nogoactivities, goals, error) in if success{ //we added a social and there is always a gambling goal so only one goal should be passed back for activity in activities! { print(activity.activityCategoryName) } expectation.fulfill() } }) } else { XCTFail(message!) } } } waitForExpectations(timeout: 10.0, handler:nil) } func testGetActivitiesNotAddedArrayMethodAfterAddingSocial() { //setup let expectation = self.expectation(description: "Waiting to respond") let randomPhoneNumber = Int(arc4random_uniform(9999999)) let body = ["firstName": "Richard", "lastName": "Quin", "mobileNumber": "+31343" + String(randomPhoneNumber), "nickname": "RQ"] //Get user goals UserRequestManager.sharedInstance.postUser(body, confirmCode: nil) { (success, message, code, users) in if success == false{ XCTFail() } //confirm mobile number check, static code UserRequestManager.sharedInstance.confirmMobileNumber(["code":YonaConstants.testKeys.otpTestCode]) { success, message, code in if(success){ ActivitiesRequestManager.sharedInstance.getActivityLinkForActivityName(.socialString) { (success, socialActivityCategoryLink, message, code) in if success { //set body for budget social goal let socialActivityCategoryLinkReturned = socialActivityCategoryLink print("socialActivityCategoryLinkReturned: " + socialActivityCategoryLinkReturned!) let bodyTimeZoneSocialGoal: [String:AnyObject] = [ "@type": "TimeZoneGoal", "_links": [ "yona:activityCategory": ["href": socialActivityCategoryLinkReturned!] ] , "zones": ["8:00-17:00", "20:00-22:00", "22:00-20:00"] ] GoalsRequestManager.sharedInstance.postUserGoals(bodyTimeZoneSocialGoal) { (success, serverMessage, serverCode, goal, nil, err) in if success { ActivitiesRequestManager.sharedInstance.getActivitiesNotAddedWithTheUsersGoals({ (success, message, code, budgetactivities,timezoneactivities, nogoactivities, goals, error) in if success{ //we added a social and there is always a gambling goal so only one goal should be passed back for activity in activities! { print(activity.activityCategoryName) } expectation.fulfill() } }) } else { XCTFail(serverMessage!) } } } } } } } waitForExpectations(timeout: 10.0, handler:nil) } func testGetActivityCategories() { //setup let expectation = self.expectation(description: "Waiting to respond") let randomPhoneNumber = Int(arc4random_uniform(9999999)) let body = ["firstName": "Richard", "lastName": "Quin", "mobileNumber": "+31343" + String(randomPhoneNumber), "nickname": "RQ"] //Get user goals UserRequestManager.sharedInstance.postUser(body, confirmCode: nil) { (success, message, code, users) in if success == false{ XCTFail() } //confirm mobile number check, static code UserRequestManager.sharedInstance.confirmMobileNumber(["code":YonaConstants.testKeys.otpTestCode]) { success, message, code in if(success){ ActivitiesRequestManager.sharedInstance.getActivityCategories{ (success, serverMessage, serverCode, activities, err) in if success{ for activity in activities! { print(activity.activityCategoryName) } expectation.fulfill() } } } } } waitForExpectations(timeout: 10.0, handler:nil) } func testGetActivityCategoryWithID() { //setup let expectation = self.expectation(description: "Waiting to respond") let randomPhoneNumber = Int(arc4random_uniform(9999999)) let body = ["firstName": "Richard", "lastName": "Quin", "mobileNumber": "+31343" + String(randomPhoneNumber), "nickname": "RQ"] //Get user goals UserRequestManager.sharedInstance.postUser(body, confirmCode: nil) { (success, message, code, users) in if success == false{ XCTFail() } //confirm mobile number check, static code UserRequestManager.sharedInstance.confirmMobileNumber(["code":YonaConstants.testKeys.otpTestCode]) { success, message, code in if(success){ ActivitiesRequestManager.sharedInstance.getActivityCategories{ (success, serverMessage, serverCode, activities, err) in if success { let activity = activities![0] print(activity) ActivitiesRequestManager.sharedInstance.getActivityCategoryWithID(activity.activityID!, onCompletion: { (success, serverMessage, serverCode, activity, err) in if success{ print(activity) expectation.fulfill() } }) } } } } } waitForExpectations(timeout: 10.0, handler:nil) } func testGetActivityLinkForSocialActivityName() { let socialActivityCategoryLink = "http://85.222.227.142/activityCategories/27395d17-7022-4f71-9daf-f431ff4f11e8" // hard code this for now for test let expectation = self.expectation(description: "Waiting to respond") let randomPhoneNumber = Int(arc4random_uniform(9999999)) let body = ["firstName": "Richard", "lastName": "Quin", "mobileNumber": "+31343" + String(randomPhoneNumber), "nickname": "RQ"] //Get user goals UserRequestManager.sharedInstance.postUser(body, confirmCode: nil) { (success, message, code, users) in if success == false{ XCTFail() } //confirm mobile number check, static code UserRequestManager.sharedInstance.confirmMobileNumber(["code":YonaConstants.testKeys.otpTestCode]) { success, message, code in if(success){ ActivitiesRequestManager.sharedInstance.getActivityLinkForActivityName(.socialString) { (success, activityID, message, code) in if success{ XCTAssertTrue(socialActivityCategoryLink == activityID, "Correct Activity ID for Social received") expectation.fulfill() } else { XCTFail(message!) } } } } } waitForExpectations(timeout: 10.0, handler:nil) } }
fde9c4fe928c0e8e235d723661e999ab
43.650655
211
0.518631
false
true
false
false
lokinfey/MyPerfectframework
refs/heads/master
PerfectLib/SysProcess.swift
apache-2.0
1
// // SysProcess.swift // PerfectLib // // Created by Kyle Jessup on 7/20/15. // Copyright (C) 2015 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // #if os(Linux) import SwiftGlibc let WUNTRACED = Int32(2) let WNOHANG = Int32(1) let SIGTERM = Int32(15) #else import Darwin #endif /// This class permits an external process to be launched given a set of command line arguments and environment variables. /// The standard in, out and err file streams are made available. The process can be terminated or permitted to be run to completion. public class SysProcess : Closeable { /// The standard in file stream. public var stdin: File? /// The standard out file stream. public var stdout: File? /// The standard err file stream. public var stderr: File? /// The process identifier. public var pid = pid_t(-1) /// Initialize the object and launch the process. /// - parameter cmd: The path to the process which will be launched. /// - parameter args: An optional array of String arguments which will be given to the process. /// - parameter env: An optional array of environment variable name and value pairs. /// - throws: `LassoError.SystemError` public init(_ cmd: String, args: [String]?, env: [(String,String)]?) throws { let cArgsCount = args != nil ? args!.count : 0 let cArgs = UnsafeMutablePointer<UnsafeMutablePointer<CChar>>.alloc(cArgsCount + 2) defer { cArgs.destroy() ; cArgs.dealloc(cArgsCount + 2) } cArgs[0] = strdup(cmd) cArgs[cArgsCount + 1] = UnsafeMutablePointer<CChar>(()) var idx = 0 while idx < cArgsCount { cArgs[idx+1] = strdup(args![idx]) idx += 1 } let cEnvCount = env != nil ? env!.count : 0 let cEnv = UnsafeMutablePointer<UnsafeMutablePointer<CChar>>.alloc(cEnvCount + 1) defer { cEnv.destroy() ; cEnv.dealloc(cEnvCount + 1) } cEnv[cEnvCount] = UnsafeMutablePointer<CChar>(()) idx = 0 while idx < cEnvCount { cEnv[idx] = strdup(env![idx].0 + "=" + env![idx].1) idx += 1 } let fSTDIN = UnsafeMutablePointer<Int32>.alloc(2) let fSTDOUT = UnsafeMutablePointer<Int32>.alloc(2) let fSTDERR = UnsafeMutablePointer<Int32>.alloc(2) defer { fSTDIN.destroy() ; fSTDIN.dealloc(2) fSTDOUT.destroy() ; fSTDOUT.dealloc(2) fSTDERR.destroy() ; fSTDERR.dealloc(2) } pipe(fSTDIN) pipe(fSTDOUT) pipe(fSTDERR) var action = posix_spawn_file_actions_t() posix_spawn_file_actions_init(&action); posix_spawn_file_actions_adddup2(&action, fSTDOUT[1], STDOUT_FILENO); posix_spawn_file_actions_adddup2(&action, fSTDIN[0], STDIN_FILENO); posix_spawn_file_actions_adddup2(&action, fSTDERR[1], STDERR_FILENO); posix_spawn_file_actions_addclose(&action, fSTDOUT[0]); posix_spawn_file_actions_addclose(&action, fSTDIN[0]); posix_spawn_file_actions_addclose(&action, fSTDERR[0]); posix_spawn_file_actions_addclose(&action, fSTDOUT[1]); posix_spawn_file_actions_addclose(&action, fSTDIN[1]); posix_spawn_file_actions_addclose(&action, fSTDERR[1]); var procPid = pid_t() let spawnRes = posix_spawnp(&procPid, cmd, &action, UnsafeMutablePointer<posix_spawnattr_t>(()), cArgs, cEnv) posix_spawn_file_actions_destroy(&action) idx = 0 while idx < cArgsCount { free(cArgs[idx]) idx += 1 } idx = 0 while idx < cEnvCount { free(cEnv[idx]) idx += 1 } #if os(Linux) SwiftGlibc.close(fSTDIN[0]) SwiftGlibc.close(fSTDOUT[1]) SwiftGlibc.close(fSTDERR[1]) if spawnRes != 0 { SwiftGlibc.close(fSTDIN[1]) SwiftGlibc.close(fSTDOUT[0]) SwiftGlibc.close(fSTDERR[0]) try ThrowSystemError() } #else Darwin.close(fSTDIN[0]) Darwin.close(fSTDOUT[1]) Darwin.close(fSTDERR[1]) if spawnRes != 0 { Darwin.close(fSTDIN[1]) Darwin.close(fSTDOUT[0]) Darwin.close(fSTDERR[0]) try ThrowSystemError() } #endif self.pid = procPid self.stdin = File(fd: fSTDIN[1], path: "") self.stdout = File(fd: fSTDOUT[0], path: "") self.stderr = File(fd: fSTDERR[0], path: "") } deinit { self.close() } /// Returns true if the process was opened and was running at some point. /// Note that the process may not be currently running. Use `wait(false)` to check if the process is currently running. public func isOpen() -> Bool { return self.pid != -1 } /// Terminate the process and clean up. public func close() { if self.stdin != nil { self.stdin!.close() } if self.stdout != nil { self.stdout!.close() } if self.stderr != nil { self.stderr!.close() } if self.pid != -1 { do { try self.kill() } catch { } } self.stdin = nil self.stdout = nil self.stderr = nil self.pid = -1 } /// Detach from the process such that it will not be manually terminated when this object is deinitialized. public func detach() { self.pid = -1 } /// Determine if the process has completed running and retrieve its result code. public func wait(hang: Bool = true) throws -> Int32 { var code = Int32(0) let status = waitpid(self.pid, &code, WUNTRACED | (hang ? 0 : WNOHANG)) if status == -1 { try ThrowSystemError() } self.pid = -1 close() return code } /// Terminate the process and return its result code. public func kill(signal: Int32 = SIGTERM) throws -> Int32 { #if os(Linux) let status = SwiftGlibc.kill(self.pid, signal) #else let status = Darwin.kill(self.pid, signal) #endif guard status != -1 else { try ThrowSystemError() } return try self.wait() } }
160b92799e613ca25f0e385fb9e644e0
26.739336
133
0.654878
false
false
false
false
wantedly/Cerberus
refs/heads/v2
CerberusTests/CalendarServiceSpec.swift
mit
1
import Quick import Nimble import EventKit import EventKitUI import RxSwift @testable import Cerberus class CalendarServiceSpec: QuickSpec { override func spec() { describe("chooseCalendars(with:in:defaultCalendars:)") { var window: UIWindow! var calendarChooser: MockCalendarChooser! var disposeBag: DisposeBag! beforeEach { window = UIWindow() window.makeKeyAndVisible() window.rootViewController = UIViewController() calendarChooser = MockCalendarChooser() disposeBag = DisposeBag() } it("sets calendars passed by an argument") { let calendars = Set([EKCalendar(for: .event, eventStore: EKEventStore())]) CalendarService.chooseCalendars(with: calendarChooser, in: window.rootViewController, defaultCalendars: calendars) .subscribe() .disposed(by: disposeBag) expect(calendarChooser.setCalendars).toEventually(equal(calendars), timeout: 3) } it("emits calendars of the calendar chooser with a selection event") { var calendars: Set<EKCalendar>? CalendarService.chooseCalendars(with: calendarChooser, in: window.rootViewController) .subscribe(onNext: { calendars = $0 }) .disposed(by: disposeBag) calendarChooser.delegate!.calendarChooserSelectionDidChange!(calendarChooser) expect(calendars).toEventually(equal(calendarChooser.selectedCalendars), timeout: 3) } it("completes with a finish event") { var completed = false CalendarService.chooseCalendars(with: calendarChooser, in: window.rootViewController) .subscribe(onCompleted: { completed = true }) .disposed(by: disposeBag) calendarChooser.delegate!.calendarChooserDidFinish!(calendarChooser) expect(completed).toEventually(beTrue(), timeout: 3) } } } }
a6ebf7e68a27490ce63a35283c242b13
36.807018
130
0.604176
false
false
false
false
HocTran/CoreDataNotification
refs/heads/master
Example/CoreDataNotification/NotificationTableViewController.swift
mit
1
// // NotificationTableViewController.swift // CoreDataNotification // // Created by HocTran on 12/1/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import CoreData import CoreDataNotification class NotificationTableViewController: TableViewController { override func viewDidLoad() { super.viewDidLoad() //notification let moc = DataController.default.managedObjectContext let fetchRequest = NSFetchRequest<City>(entityName: "City") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)] notificationToken = moc.addNotificationBlock(fetchRequest: fetchRequest) { change in switch change { case .initial(let list): self.cities = list self.tableView.reloadData() case .insert(let list, let insertion): self.cities = list self.tableView.insertRows(at: [insertion], with: .automatic) case .delete(let list, let deletion): self.cities = list self.tableView.deleteRows(at: [deletion], with: .automatic) case .update(let list, let modification): self.cities = list self.tableView.reloadRows(at: [modification], with: .automatic) case .move(let list, let from, let to): self.cities = list self.tableView.moveRow(at: from, to: to) case .error(let error): print("++++++++ ERROR ++++++++") print(error) print("+++++++++++++++++++++++++") } } } }
952ec6adf45f1f8ed1d223c4c850e67a
33.918367
92
0.559906
false
false
false
false
Marketcloud/marketcloud-swift-application
refs/heads/master
Carthage/Checkouts/marketcloud-swift-sdk/Marketcloud/Carts.swift
apache-2.0
2
import Foundation internal class Carts { fileprivate var headers:[String : String] internal init(key: String) { headers = ["accept":"application/json","content-type":"application/json","authorization":key] } internal init(key: String, token: String) { headers = ["accept":"application/json","content-type":"application/json","authorization":"\(key):\(token)"] } //Creates cart------------------------------------ internal func createEmptyCart() -> NSDictionary { guard Reachability.isConnectedToNetwork() == true else { return [ "Error" : "No Connection"] } //print("creating a cart for unlogged user") let myDictOfDict = [ "items" : [NSDictionary]() ] guard let shouldReturn:HTTPResult = Just.post("https://api.marketcloud.it/v0/carts", data: myDictOfDict, headers:headers) else { return[ "Error" : "Critical Error in HTTP request (post)"] } if (shouldReturn.json == nil) { //print(shouldReturn.reason) return [ "Error" : "Returned JSON is nil"] } return shouldReturn.json as! NSDictionary } //retrieves a cart by its id internal func getCart(_ id:Int) -> NSDictionary { guard Reachability.isConnectedToNetwork() == true else { return [ "Error" : "No Connection"] } guard let shouldReturn:HTTPResult = Just.get("https://api.marketcloud.it/v0/carts/\(id)", headers:headers) else { return[ "Error" : "Critical Error in HTTP request (get)"] } if (shouldReturn.json == nil) { //print(shouldReturn.reason) return [ "Error" : "Returned JSON is nil"] } return shouldReturn.json as! NSDictionary } //retrieves logged user cart internal func getCart() -> NSDictionary { guard Reachability.isConnectedToNetwork() == true else { return [ "Error" : "No Connection"] } guard let shouldReturn:HTTPResult = Just.get("https://api.marketcloud.it/v0/carts/", headers:headers) else { return[ "Error" : "Critical Error in HTTP request (get)"] } if (shouldReturn.json == nil) { //print(shouldReturn.reason) return [ "Error" : "Returned JSON is nil"] } return shouldReturn.json as! NSDictionary } //adds a product to a cart internal func addToCart(_ cartId:Int, data:[Any]) -> NSDictionary { guard Reachability.isConnectedToNetwork() == true else { return [ "Error" : "No Connection"] } var finalArray = [String:Any]() finalArray["op"] = "add" as Any? finalArray["items"] = data as Any? guard let shouldReturn:HTTPResult = Just.patch("https://api.marketcloud.it/v0/carts/\(cartId)", data:finalArray, headers:headers) else { return[ "Error" : "Critical Error in HTTP request (patch)"] } if (shouldReturn.json == nil) { //print(shouldReturn.reason) return [ "Error" : "Returned JSON is nil"] } return shouldReturn.json as! NSDictionary } //updates object's quantity internal func updateCart(_ cartId:Int, data:[Any]) -> NSDictionary { guard Reachability.isConnectedToNetwork() == true else { return [ "Error" : "No Connection"] } var finalArray = [String:Any]() finalArray["op"] = "update" as Any? finalArray["items"] = data as Any? guard let shouldReturn:HTTPResult = Just.patch("https://api.marketcloud.it/v0/carts/\(cartId)", data:finalArray, headers:headers) else { return[ "Error" : "Critical Error in HTTP request (patch)"] } if (shouldReturn.json == nil) { //print(shouldReturn.reason) return [ "Error" : "Returned JSON is nil"] } return shouldReturn.json as! NSDictionary } //removes an object from a cart internal func removeFromCart(_ cartId:Int, data:[Any]) -> NSDictionary { guard Reachability.isConnectedToNetwork() == true else { return [ "Error" : "No Connection"] } var finalArray = [String:Any]() finalArray["op"] = "remove" as Any? finalArray["items"] = data as Any? guard let shouldReturn:HTTPResult = Just.patch("https://api.marketcloud.it/v0/carts/\(cartId)", data:finalArray, headers:headers) else { return[ "Error" : "Critical Error in HTTP request (patch)"] } if (shouldReturn.json == nil) { //print(shouldReturn.reason) return [ "Error" : "Returned JSON is nil"] } return shouldReturn.json as! NSDictionary } }
ab37c25474cff10aa378a59ce78341be
32.15
144
0.527715
false
false
false
false
luispadron/GradePoint
refs/heads/master
GradePoint/Extensions/UIViewController+Alert.swift
apache-2.0
1
// // UIViewController+Alert.swift // GradePoint // // Created by Luis Padron on 1/26/17. // Copyright © 2017 Luis Padron. All rights reserved. // import UIKit extension UIViewController { /// Presents an error blur alert with given title and message, optional completion handler func presentErrorAlert(title: String, message: String, completion: (() -> Void)? = nil) { let t = NSAttributedString(string: title, attributes: [.font : UIFont.systemFont(ofSize: 17), .foregroundColor: UIColor.red]) let m = NSAttributedString(string: message, attributes: [.font : UIFont.systemFont(ofSize: 15), .foregroundColor: ApplicationTheme.shared.mainTextColor(in: .light)]) let alert = UIBlurAlertController(size: CGSize(width: 300, height: 200), title: t, message: m) alert.alertFeedbackType = .error let ok = UIButton() ok.setTitle("OK", for: .normal) ok.backgroundColor = .warning alert.addButton(button: ok) { completion?() } alert.presentAlert(presentingViewController: self) } /// Presents and information blur alert func presentInfoAlert(title: String, message: String, completion: (() -> Void)? = nil) { let t = NSAttributedString(string: title, attributes: [.font: UIFont.systemFont(ofSize: 17), .foregroundColor: UIColor.red]) let m = NSAttributedString(string: message, attributes: [.font: UIFont.systemFont(ofSize: 15), .foregroundColor: ApplicationTheme.shared.mainTextColor(in: .light)]) let alert = UIBlurAlertController(size: CGSize(width: 300, height: 200), title: t, message: m) alert.alertFeedbackType = .success let ok = UIButton() ok.setTitle("OK", for: .normal) ok.backgroundColor = .info alert.addButton(button: ok) { completion?() } alert.presentAlert(presentingViewController: self) } }
299b2d1cb533385461ab6768aaa70d50
46.521739
134
0.585544
false
false
false
false
advantys/workflowgen-templates
refs/heads/master
integration/azure/authentication/azure-v1/auth-code-pkce/WorkflowGenExample/ios/CodeGenerator.swift
mit
1
import Foundation import CommonCrypto @objc(CodeGenerator) class CodeGenerator : NSObject, RCTBridgeModule { static func moduleName() -> String! { return "CodeGenerator" } static func requiresMainQueueSetup() -> Bool { return false } @objc(generateUUID:reject:) func generateUUID(_ resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { resolve(UUID().uuidString) } @objc(generateCodeVerifier:reject:) func generateCodeVerifier(_ resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { var buffer = [UInt8](repeating: 0, count: 32) _ = SecRandomCopyBytes(kSecRandomDefault, buffer.count, &buffer) let verifier = Data(buffer) .base64EncodedString() .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "=", with: "") .trimmingCharacters(in: .whitespaces) resolve(verifier) } @objc(generateCodeChallenge:resolve:reject:) func generateCodeChallenge(codeVerifier: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { guard let verifierData = codeVerifier.data(using: .utf8) else { reject( "codegenerator_challenge_error", "Could not get raw data from code verifier string.", NSError(domain: "codegenerator", code: 1, userInfo: nil) ) return } var buffer = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) verifierData.withUnsafeBytes { (b: UnsafeRawBufferPointer) in _ = CC_SHA256(b.baseAddress, CC_LONG(verifierData.count), &buffer) } let hash = Data(buffer) let challenge = hash .base64EncodedString() .replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_") .replacingOccurrences(of: "=", with: "") .trimmingCharacters(in: .whitespaces) resolve(challenge) } }
a87198a3056e9e7dee3ebb87a25e44a7
35.844828
118
0.605054
false
false
false
false
pNre/CryptoRates
refs/heads/master
CryptoRates/AppDelegate.swift
mit
1
// // AppDelegate.swift // CryptoRates // // Created by Pierluigi D'Andrea on 14/01/17. // Copyright © 2017 pNre. All rights reserved. // import Cocoa import Moya import ObjectMapper import ReactiveCocoa import ReactiveSwift import ReactiveMoya import Result import ServiceManagement @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { // MARK: Properties @IBOutlet weak var mainMenu: NSMenu! @IBOutlet weak var lastUpdateItem: NSMenuItem! @IBOutlet weak var toggleStartupLaunchItem: NSMenuItem! { didSet { toggleStartupLaunchItem.state = isLaunchedOnLogin ? NSOnState : NSOffState } } /// Status bar item private lazy var statusItem: NSStatusItem = { let item = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength) item.menu = self.mainMenu return item }() /// Last update date formatter private lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .short return formatter }() /// Time interval between price updates fileprivate let updateInterval: MutableProperty<DispatchTimeInterval> = MutableProperty(.seconds(60)) /// Currency to request the exchange rates for fileprivate let currency: MutableProperty<String> = MutableProperty(Locale.current.currencyCode ?? "EUR") /// Formatted buy and sell prices private lazy var prices: Property<(buy: String?, sell: String?)> = { let buy = self.priceProducer(for: { .buy(currency: $0) }) let sell = self.priceProducer(for: { .sell(currency: $0) }) let producer = SignalProducer.combineLatest(buy, sell) .map { (buy: $0, sell: $1) } return Property(initial: (buy: nil, sell: nil), then: producer) }() /// Provider for the Coinbase price API fileprivate lazy var provider: ReactiveSwiftMoyaProvider<Prices> = { return ReactiveSwiftMoyaProvider<Prices>(endpointClosure: { (target: Prices) -> Endpoint<Prices> in let defaultEndpoint = MoyaProvider.defaultEndpointMapping(for: target) return defaultEndpoint.adding(newHTTPHeaderFields: ["CB-VERSION": "2017-01-14"]) }) }() // MARK: AppDelegate func applicationDidFinishLaunching(_ aNotification: Notification) { prices.producer .skip(while: { $0?.isEmpty != false || $1?.isEmpty != false }) .observe(on: UIScheduler()) .startWithResult { [weak self] result in guard case .success(.some(let buy), .some(let sell)) = result else { return } self?.statusItem.attributedTitle = AppDelegate.statusItemTitleFor(buy: buy, sell: sell) if let date = self?.dateFormatter.string(from: Date()) { self?.lastUpdateItem.title = "Last update: \(date)" } else { self?.lastUpdateItem.title = "Last update: unknown" } } } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } } // MARK: - Requests extension AppDelegate { /// Formatted "sell" price fileprivate func priceProducer(for target: @escaping (String) -> Prices) -> SignalProducer<String?, NoError> { let provider = self.provider return SignalProducer.combineLatest(self.updateInterval.producer, self.currency.producer) .flatMap(.latest) { interval, currency -> SignalProducer<String?, NoError> in return timer(interval: interval, on: QueueScheduler()) .prefix(value: Date()) .flatMap(.latest) { _ -> SignalProducer<String?, NoError> in return provider.request(target(currency)) .map(AppDelegate.map) .flatMapError { _ -> SignalProducer<String?, NoError> in .empty } } } } fileprivate static func map(response: Response) -> String? { guard let string = try? response.mapString() else { return nil } return (try? Mapper<PricesResponse>().map(JSONString: string))?.amount.currencyString } } // MARK: - Actions extension AppDelegate { @IBAction func quitAction(_ sender: NSMenuItem) { NSApplication.shared().terminate(self) } @IBAction func toggleStartupLaunchItemAction(_ sender: NSMenuItem) { let shouldEnable = !isLaunchedOnLogin guard SMLoginItemSetEnabled("com.pNre.CryptoRatesLauncher" as CFString, shouldEnable) else { return } sender.state = shouldEnable ? NSOnState : NSOffState } } // MARK: - Formatting extension AppDelegate { fileprivate static func statusItemTitleFor(buy: String, sell: String) -> NSAttributedString { let title = "↓ \(buy) ⬝ ↑ \(sell)" let attributes = [NSFontAttributeName: NSFont.systemFont(ofSize: NSFont.smallSystemFontSize())] return NSAttributedString(string: title, attributes: attributes) } } // MARK: - Launch items extension AppDelegate { fileprivate var isLaunchedOnLogin: Bool { let dictionaries = SMCopyAllJobDictionaries(kSMDomainUserLaunchd).takeRetainedValue() guard let jobs = dictionaries as NSArray as? [[String: AnyObject]], !jobs.isEmpty else { return false } return jobs.contains { $0["Label"] as? String == "com.pNre.CryptoRatesLauncher" && $0["OnDemand"] as? Bool == true } } }
749d9a7ac85973eec3ed0e964df1f700
28.061224
124
0.633076
false
false
false
false
angmu/SwiftPlayCode
refs/heads/master
swift练习/swift基础学习.playground/section-1.swift
mit
1
// Playground - noun: a place where people can play import Foundation //var age = 23 let pi = 3.14 print("hello World!") let a = 20 let b = 3.14 let c = a + Int(b) if a > 10 { print("a大于10!") } else { print("a小于10!") } let score = 87 if score < 60 { print("不及格") } else if score <= 70 { print("及格") } else if score <= 80 { print("良好") } else if score <= 90 { print("优秀") } else { print("完美") } let age = 21 let result = age > 18 ? "可以上网" : "回家去" func online(age : Int) -> Void { guard age >= 18 else { // 判断语句为假,会执行else print("回家去") return } // 如果为真,继续执行 print("可以上网") } online(age:23)
746fc9a0a968e2391e26e15508e50de9
11.290909
51
0.52071
false
false
false
false
L550312242/SinaWeiBo-Switf
refs/heads/master
weibo 1/Class/Module(模块)/Compose/Controller/CZComposeViewController.swift
apache-2.0
1
import UIKit class CZComposeViewController: UIViewController { // MARK: - 属性 /// toolBar底部约束 private var toolBarBottomCon: NSLayoutConstraint? override func viewDidLoad() { super.viewDidLoad() // 需要设置背景颜色,不然弹出时动画有问题 view.backgroundColor = UIColor.whiteColor() prepareUI() // 添加键盘frame改变的通知 NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } /* notification:NSConcreteNotification 0x7f8fea5a4e20 {name = UIKeyboardDidChangeFrameNotification; userInfo = { UIKeyboardAnimationCurveUserInfoKey = 7; UIKeyboardAnimationDurationUserInfoKey = "0.25"; // 动画时间 UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}"; UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}"; UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}"; UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}"; UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}"; // 键盘最终的位置 UIKeyboardIsLocalUserInfoKey = 1; }} */ /// 键盘frame改变 func willChangeFrame(notification: NSNotification) { // print("notification:\(notification)") // 获取键盘最终位置 let endFrame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue // 动画时间 let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval toolBarBottomCon?.constant = -(UIScreen.height() - endFrame.origin.y) UIView.animateWithDuration(duration) { () -> Void in // 不能直接更新toolBar的约束 // self.toolBar.layoutIfNeeded() self.view.layoutIfNeeded() } } // MARK: - 准备UI private func prepareUI() { setupNavigationBar() setupToolBar() setupTextView() } /// 设置导航栏 private func setupNavigationBar() { // 设置按钮, 左边 navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close") // 右边 navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus") navigationItem.rightBarButtonItem?.enabled = false setupTitleView() } /// 设置toolBar private func setupToolBar() { // 添加子控件 view.addSubview(toolBar) // 添加约束 let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.width(), height: 44)) // 获取底部约束 toolBarBottomCon = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom) // 创建toolBar item var items = [UIBarButtonItem]() // 每个item对应的图片名称 let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"], ["imageName": "compose_trendbutton_background", "action": "trend"], ["imageName": "compose_mentionbutton_background", "action": "mention"], ["imageName": "compose_emoticonbutton_background", "action": "emoticon"], ["imageName": "compose_addbutton_background", "action": "add"]] var index = 0 // 遍历 itemSettings 获取图片名称,创建items for dict in itemSettings { // 获取图片的名称 let imageName = dict["imageName"]! // 获取图片对应点点击方法名称 let action = dict["action"]! let item = UIBarButtonItem(imageName: imageName) // 获取item里面的按钮 let button = item.customView as! UIButton button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside) items.append(item) // 添加弹簧 items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)) index++ } // 移除最后一个弹簧 items.removeLast() toolBar.items = items } /// 设置导航栏标题 private func setupTitleView() { let prefix = "发微博" // 获取用户的名称 if let name = CZUserAccount.loadAccount()?.name { // 有用户名 let titleName = prefix + "\n" + name // 创建可变的属性文本 let attrString = NSMutableAttributedString(string: titleName) // 创建label let label = UILabel() // 设置属性文本 label.numberOfLines = 0 label.textAlignment = NSTextAlignment.Center label.font = UIFont.systemFontOfSize(14) // 获取NSRange let nameRange = (titleName as NSString).rangeOfString(name) // 设置属性文本的属性 attrString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: nameRange) attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange) // 顺序不要搞错 label.attributedText = attrString label.sizeToFit() navigationItem.titleView = label } else { // 没有用户名 navigationItem.title = prefix } } /// 设置textView private func setupTextView() { // 添加子控件 view.addSubview(textView) /* 前提: 1.scrollView所在的控制器属于某个导航控制器 2.scrollView控制器的view或者控制器的view的第一个子view */ // scrollView会自动设置Insets, 比如scrollView所在的控制器属于某个导航控制器contentInset.top = 64 // automaticallyAdjustsScrollViewInsets = true // 添加约束 // 相对控制器的view的内部左上角 textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil) // 相对toolBar顶部右上角 textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil) } // MARK: - 按钮点击事件 func picture() { print("图片") } func trend() { print("#") } func mention() { print("@") } func emoticon() { print("表情") } func add() { print("加号") } /// 关闭控制器 @objc private func close() { // 关闭键盘 textView.resignFirstResponder() dismissViewControllerAnimated(true, completion: nil) } /// 发微博 func sendStatus() { print(__FUNCTION__) } // MARK: - 懒加载 /// toolBar private lazy var toolBar: UIToolbar = { let toolBar = UIToolbar() toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1) return toolBar }() /* iOS中可以让用户输入的控件: 1.UITextField: 1.只能显示一行 2.可以有占位符 3.不能滚动 2.UITextView: 1.可以显示多行 2.没有占位符 3.继承UIScrollView,可以滚动 */ /// textView private lazy var textView: CZPlaceholderTextView = { let textView = CZPlaceholderTextView() // 当textView被拖动的时候就会将键盘退回,textView能拖动 textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag textView.font = UIFont.systemFontOfSize(18) textView.backgroundColor = UIColor.brownColor() textView.textColor = UIColor.blackColor() textView.bounces = true textView.alwaysBounceVertical = true // 设置占位文本 textView.placeholder = "分享新鲜事..." // 设置顶部的偏移 textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0) // 设置控制器作为textView的代理来监听textView文本的改变 textView.delegate = self return textView }() } extension CZComposeViewController: UITextViewDelegate { /// textView文本改变的时候调用 func textViewDidChange(textView: UITextView) { // 当textView 有文本的时候,发送按钮可用, // 当textView 没有文本的时候,发送按钮不可用 navigationItem.rightBarButtonItem?.enabled = textView.hasText() } }
0da8ea421e15e15fc80f50f55dd4c106
28.874101
150
0.57929
false
false
false
false
MorganCabral/swiftrekt-ios-app-dev-challenge-2015
refs/heads/master
app-dev-challenge/app-dev-challenge/ViewController.swift
mit
1
// // ViewController.swift // app-dev-challenge // // Created by Morgan Cabral on 2/5/15. // Code by Holly Hastings // Tina is here too! // Copyright (c) 2015 Team SwiftRekt. All rights reserved. // import UIKit import SpriteKit class ViewController: UIViewController { @IBOutlet var startButton: UIButton! @IBOutlet weak var rotateSpriteView: SKView! override func viewDidLoad() { super.viewDidLoad() //startButton.backgroundColor = UIColor.clearColor() startButton.layer.cornerRadius = 10 startButton.layer.borderWidth = 1 // Set up the rotate spritekit view. let scene = LoadingScene(size: rotateSpriteView.bounds.size) scene.scaleMode = .ResizeFill rotateSpriteView.ignoresSiblingOrder = true rotateSpriteView.presentScene(scene) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prefersStatusBarHidden() -> Bool { return false; } override func shouldAutorotate() -> Bool { return false; } //here we should be able to activate the camera after hte button is pressed. Try to change the completion to something @IBAction func startAction(sender: UIButton) { let gameController = self.storyboard?.instantiateViewControllerWithIdentifier("gameController") as GameViewController self.navigationController?.pushViewController(gameController, animated: false) } }
feaa9ac3ca528e0dc6fcfa662bd268e2
27.596154
125
0.724277
false
false
false
false
IngmarStein/swift
refs/heads/master
validation-test/compiler_crashers_fixed/00458-swift-declcontext-lookupqualified.swift
apache-2.0
11
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse var m: Int -> Int = { n $0 o: Int = { d, l f }(, j: v where t.h == j struct c<d: Sequence, b where Optional<b> == d.Iterator.Element>
a4605ef83c754b12ac7636b60c7d5ba9
39.461538
78
0.705323
false
false
false
false
mleiv/MEGameTracker
refs/heads/master
MEGameTracker/Models/CoreData/CoreDataMigrations/BaseDataImport.swift
mit
1
// // BaseDataImport.swift // MEGameTracker // // Created by Emily Ivie on 10/1/15. // Copyright © 2015 Emily Ivie. All rights reserved. // import Foundation import CoreData public struct BaseDataImport: CoreDataMigrationType { let progressProcessImportChunk = 40.0 let progressFinalPadding = 20.0 let onProcessMapDataRow = Signal<Bool>() let onProcessMissionDataRow = Signal<Bool>() var isTestProject: Bool { return ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil } let manager: CodableCoreDataManageable? public init(manager: CodableCoreDataManageable? = nil) { self.manager = manager ?? CoreDataManager.current } public func run() throws { // Don't run base data load twice on same data: guard !CoreDataMigrationManager.didLoadBaseData else { return } try addData() CoreDataMigrationManager.didLoadBaseData = true print("Installed base data") } // Must group these by type public typealias CoreDataFileImport = (type: BaseDataFileImportType, filename: String, progress: Double) public let progressFilesEvents: [CoreDataFileImport] = [ (type: .event, filename: "DataEvents_1", progress: 1), (type: .event, filename: "DataEvents_2", progress: 1), (type: .event, filename: "DataEvents_3", progress: 1), ] public let progressFilesOther: [CoreDataFileImport] = [ (type: .decision, filename: "DataDecisions_1", progress: 1), (type: .decision, filename: "DataDecisions_2", progress: 1), (type: .decision, filename: "DataDecisions_3", progress: 1), (type: .person, filename: "DataPersons_1", progress: 1), (type: .person, filename: "DataPersons_1Others", progress: 3), (type: .person, filename: "DataPersons_2", progress: 1), (type: .person, filename: "DataPersons_2Others", progress: 3), (type: .person, filename: "DataPersons_3", progress: 1), (type: .person, filename: "DataPersons_3Others", progress: 3), (type: .map, filename: "DataMaps_Primary", progress: 2), (type: .map, filename: "DataMaps_TerminusSystems", progress: 5), (type: .map, filename: "DataMaps_AtticanTraverse", progress: 5), (type: .map, filename: "DataMaps_InnerCouncil", progress: 5), (type: .map, filename: "DataMaps_OuterCouncil", progress: 5), (type: .map, filename: "DataMaps_EarthSystemsAlliance", progress: 5), (type: .item, filename: "DataItems_1", progress: 1), (type: .item, filename: "DataItems_1Loot", progress: 1), (type: .item, filename: "DataItems_1Scans", progress: 1), (type: .item, filename: "DataItems_2", progress: 1), (type: .item, filename: "DataItems_2Loot", progress: 1), (type: .item, filename: "DataItems_3", progress: 1), (type: .item, filename: "DataItems_3Loot", progress: 1), (type: .item, filename: "DataItems_3Scans", progress: 1), (type: .mission, filename: "DataMissions_1", progress: 2), (type: .mission, filename: "DataMissions_1Assignments", progress: 5), (type: .mission, filename: "DataMissions_1Convos", progress: 3), (type: .mission, filename: "DataMissions_1Misc", progress: 3), (type: .mission, filename: "DataMissions_2", progress: 2), (type: .mission, filename: "DataMissions_2Assignments", progress: 5), (type: .mission, filename: "DataMissions_2Convos", progress: 5), (type: .mission, filename: "DataMissions_2Misc", progress: 5), (type: .mission, filename: "DataMissions_3", progress: 2), (type: .mission, filename: "DataMissions_3Assignments", progress: 5), (type: .mission, filename: "DataMissions_3Convos", progress: 5), (type: .mission, filename: "DataMissions_3Misc", progress: 5), ] func fireProgress(progress: Double, progressTotal: Double) { let progressPercent = progressTotal > 0 ? (progress > 0 ? Int((progress / progressTotal) * 100) : 0) : 1 // print("fireProgress \(progress)/\(progressTotal) \(progressPercent)%") DispatchQueue.main.async { CoreDataMigrations.onPercentProgress.fire(progressPercent) } } func addData() throws { let progressTotal = (progressFilesEvents + progressFilesOther).map { $0.progress }.reduce(0.0, +) + (progressProcessImportChunk * 2.0) + progressFinalPadding try importDataFiles(progress: 0.0, progressTotal: progressTotal) processImportedData( progress: progressTotal - (progressProcessImportChunk * 2.0), progressTotal: progressTotal ) } } extension BaseDataImport { func importDataFiles(progress: Double, progressTotal: Double) throws { var progress = progress fireProgress(progress: progress, progressTotal: progressTotal) // load up all ids so we know if some have been removed var deleteOldIds: [BaseDataFileImportType: [String]] = [:] for type in Array(Set((progressFilesEvents + progressFilesOther).map({ $0.type }))) { deleteOldIds[type] = self.getAllIds(type: type, with: manager) } let queue = DispatchQueue.global(qos: .userInitiated) let queueGroup = DispatchGroup() let markIdsImported: (BaseDataFileImportType, [String]) -> Void = { (type, ids) in deleteOldIds[type] = Array(Set(deleteOldIds[type] ?? []).subtracting(ids)) } let updateFileProgress: (Double) -> Void = { (batchProgress) in progress += batchProgress self.fireProgress(progress: progress, progressTotal: progressTotal) } // process all events first for row in progressFilesEvents { if isTestProject { try importFile(fileDefinition: row, markIdsImported: markIdsImported, updateProgress: updateFileProgress) } else { queueGroup.enter() queue.async(group: queueGroup) { do { try importFile(fileDefinition: row, markIdsImported: markIdsImported, updateProgress: updateFileProgress) queueGroup.leave() } catch { print("Failed to import", error) } } } } // wait for finish queueGroup.wait() for row in progressFilesOther { if isTestProject { try importFile(fileDefinition: row, markIdsImported: markIdsImported, updateProgress: updateFileProgress) } else { queueGroup.enter() queue.async(group: queueGroup) { do { try importFile(fileDefinition: row, markIdsImported: markIdsImported, updateProgress: updateFileProgress) queueGroup.leave() } catch let error { print("Failed to import", error) } } } } // wait for finish queueGroup.wait() // remove any old entries not included in this update // (this is unsupported in XCTest inMemoryStore) if !isTestProject { for (type, ids) in deleteOldIds { _ = deleteAllIds(type: type, ids: ids, with: manager) } } } func processImportedData(progress: Double, progressTotal: Double) { fireProgress(progress: progress, progressTotal: progressTotal) let queue = DispatchQueue.global(qos: .userInitiated) let queueGroup = DispatchGroup() var tempProgress1 = 0.0 var tempProgress2 = 0.0 let updateProgress1: ((Double, Bool) -> Void) = { (chunkProgress, isCompleted) in if isCompleted { tempProgress1 = self.progressProcessImportChunk self.fireProgress(progress: progress + tempProgress2 + tempProgress1, progressTotal: progressTotal) } else { tempProgress1 += chunkProgress self.fireProgress( progress: progress + tempProgress2 + tempProgress1, progressTotal: progressTotal ) } } let updateProgress2: ((Double, Bool) -> Void) = { (chunkProgress, isCompleted) in if isCompleted { tempProgress2 = self.progressProcessImportChunk self.fireProgress(progress: progress + tempProgress2 + tempProgress1, progressTotal: progressTotal) } else { tempProgress2 += chunkProgress self.fireProgress( progress: progress + tempProgress2 + tempProgress1, progressTotal: progressTotal ) } } if isTestProject { // XCTest has some multithreading issues, where the queueGroup wait blocks the Core Data wait. // So we will run it synchronously. processImportedMapData(queue: queue, updateProgress: updateProgress1) processImportedMissionData(queue: queue, updateProgress: updateProgress2) } else { // Queue #1 queueGroup.enter() queue.async(group: queueGroup) { self.processImportedMapData(queue: queue, updateProgress: updateProgress1) queueGroup.leave() } // Queue #2 queueGroup.enter() queue.async(group: queueGroup) { self.processImportedMissionData(queue: queue, updateProgress: updateProgress2) queueGroup.leave() } // wait for finish queueGroup.wait() } // TODO: delete orphan game data? fireProgress(progress: progressTotal, progressTotal: progressTotal) } func importFile( fileDefinition: CoreDataFileImport, markIdsImported: @escaping ((BaseDataFileImportType, [String]) -> Void), updateProgress: @escaping ((Double) -> Void) ) throws { let type = fileDefinition.type let filename = fileDefinition.filename let batchProgress = fileDefinition.progress do { if let file = Bundle.main.path(forResource: filename, ofType: "json") { let data = try Data(contentsOf: URL(fileURLWithPath: file)) let ids = try importData(data, with: manager) markIdsImported(type, ids) } } catch let error { // failure print("Failed to load file \(filename)") if (App.current.isDebug) { throw error; } } updateProgress(batchProgress) } func processImportedMapData( queue: DispatchQueue, updateProgress: @escaping ((Double, Bool) -> Void) ) { let manager = self.manager let mapsCount = DataMap.getCount(with: manager) var countProcessed: Int = 0 let chunkSize: Int = 20 let chunkPercentage = Double(chunkSize) / Double(mapsCount) let chunkProgress = Double(self.progressProcessImportChunk) * chunkPercentage for map in DataMap.getAll(with: manager, alterFetchRequest: { fetchRequest in // fetchRequest.predicate = NSPredicate(format: "(inMapId == nil)") fetchRequest.predicate = NSPredicate(format: "(relatedEvents.@count > 0)") }) { self.applyInheritedEvents( map: map, inheritableEvents: map.getInheritableEvents(), runOnEachMapBlock: { if countProcessed > 0 && countProcessed % chunkSize == 0 { // notify chunk done queue.sync { updateProgress(chunkProgress, false) } } countProcessed += 1 } ) } // notify all done queue.sync { updateProgress(0, true) } } func processImportedMissionData( queue: DispatchQueue, updateProgress: @escaping ((Double, Bool) -> Void) ) { let manager = self.manager let missionsCount = DataMission.getCount(with: manager) var countProcessed: Int = 0 let chunkSize: Int = 20 let chunkPercentage = Double(chunkSize) / Double(missionsCount) let chunkProgress = Double(self.progressProcessImportChunk) * chunkPercentage for mission in DataMission.getAll(with: manager, alterFetchRequest: { fetchRequest in // fetchRequest.predicate = NSPredicate(format: "(inMissionId == nil)") fetchRequest.predicate = NSPredicate(format: "(relatedEvents.@count > 0)") }) { self.applyInheritedEvents( mission: mission, inheritableEvents: mission.getInheritableEvents(), runOnEachMissionBlock: { if countProcessed > 0 && countProcessed % chunkSize == 0 { // notify chunk done queue.sync { updateProgress(chunkProgress, false) } } countProcessed += 1 } ) } // notify all done queue.sync { updateProgress(0, true) } } //TODO: Protocol events and generic this function // Note: items and persons don't inherit, so ignore them here func applyInheritedEvents( map: DataMap, inheritableEvents: [CodableDictionary], level: Int = 0, runOnEachMapBlock: @escaping (() -> Void) ) { guard !inheritableEvents.isEmpty else { return } var maps: [DataMap] = [] for (var childMap) in DataMap.getAll(with: manager, alterFetchRequest: { fetchRequest in fetchRequest.predicate = NSPredicate(format: "(inMapId = %@)", map.id) }) { var eventData = childMap.rawEventDictionary.map { $0.dictionary } var isChanged = false for event in inheritableEvents where !eventData.contains(where: { $0["id"] as? String == event["id"] as? String && $0["type"] as? String == event["type"] as? String }) { eventData.append(event.dictionary) isChanged = true } var childInheritableEvents = inheritableEvents + childMap.getInheritableEvents() while let index = eventData.firstIndex(where: { $0["eraseParentValue"] as? Bool == true }) { let event = eventData.remove(at: index) if let index2 = childInheritableEvents.firstIndex(where: { event["id"] as? String == $0["id"] as? String }) { childInheritableEvents.remove(at: index2) } isChanged = true } if isChanged { childMap.rawEventDictionary = eventData.map { CodableDictionary($0) } maps.append(childMap) } runOnEachMapBlock() self.applyInheritedEvents( map: childMap, inheritableEvents: childInheritableEvents, level: level + 1, runOnEachMapBlock: runOnEachMapBlock ) } _ = DataMap.saveAll(items: maps, with: manager) var items: [DataItem] = [] for (var childItem) in DataItem.getAll(with: manager, alterFetchRequest: { fetchRequest in fetchRequest.predicate = NSPredicate(format: "(inMapId = %@)", map.id) }) { var eventData = childItem.rawEventDictionary.map { $0.dictionary } var isChanged = false for event in inheritableEvents where !eventData.contains(where: { $0["id"] as? String == event["id"] as? String && $0["type"] as? String == event["type"] as? String }) { eventData.append(event.dictionary) isChanged = true } while let index = eventData.firstIndex(where: { $0["eraseParentValue"] as? Bool == true }) { eventData.remove(at: index) isChanged = true } if isChanged { childItem.rawEventDictionary = eventData.map { CodableDictionary($0) } items.append(childItem) } // no child item inheritance } _ = DataItem.saveAll(items: items, with: manager) } func applyInheritedEvents( mission: DataMission, inheritableEvents: [CodableDictionary], level: Int = 0, runOnEachMissionBlock: @escaping (() -> Void) ) { guard !inheritableEvents.isEmpty else { return } var missions: [DataMission] = [] for (var childMission) in DataMission.getAll(with: manager, alterFetchRequest: { fetchRequest in fetchRequest.predicate = NSPredicate(format: "(inMissionId = %@)", mission.id) }) { var eventData = childMission.rawEventDictionary.map { $0.dictionary } var isChanged = false for event in inheritableEvents where !eventData.contains(where: { $0["id"] as? String == event["id"] as? String && $0["type"] as? String == event["type"] as? String }) { eventData.append(event.dictionary) isChanged = true } var childInheritableEvents = inheritableEvents + childMission.getInheritableEvents() while let index = eventData.firstIndex(where: { $0["eraseParentValue"] as? Bool == true }) { let event = eventData.remove(at: index) if let index2 = childInheritableEvents.firstIndex(where: { event["id"] as? String == $0["id"] as? String }) { childInheritableEvents.remove(at: index2) } isChanged = true } if isChanged { childMission.rawEventDictionary = eventData.map { CodableDictionary($0) } missions.append(childMission) } runOnEachMissionBlock() self.applyInheritedEvents( mission: childMission, inheritableEvents: childInheritableEvents, level: level + 1, runOnEachMissionBlock: runOnEachMissionBlock ) } _ = DataMission.saveAll(items: missions, with: manager) var items: [DataItem] = [] for (var childItem) in DataItem.getAll(with: manager, alterFetchRequest: { fetchRequest in fetchRequest.predicate = NSPredicate(format: "(inMissionId = %@)", mission.id) }) { var eventData = childItem.rawEventDictionary.map { $0.dictionary } var isChanged = false for event in inheritableEvents where !eventData.contains(where: { $0["id"] as? String == event["id"] as? String && $0["type"] as? String == event["type"] as? String }) { eventData.append([ "id": event["id"] as? String, "type": event["type"] as? String, "eraseParentValue": event["eraseParentValue"] as? Bool ?? false, ]) isChanged = true } while let index = eventData.firstIndex(where: { $0["eraseParentValue"] as? Bool == true }) { eventData.remove(at: index) isChanged = true } if isChanged { childItem.rawEventDictionary = eventData.map { CodableDictionary($0) } items.append(childItem) } // no child item inheritance } _ = DataItem.saveAll(items: items, with: manager) } }
1eeb36a05dddf49a72db786ffbe869c4
39.74026
129
0.611625
false
false
false
false
The9Labs/AudioMate
refs/heads/develop
AudioMate/SampleRateAndClockSourceStatusBarView.swift
mit
2
// // SampleRateAndClockSourceStatusBarView.swift // AudioMate // // Created by Ruben Nine on 26/04/16. // Copyright © 2016 Ruben Nine. All rights reserved. // import Cocoa import PureLayout import AMCoreAudio class SampleRateAndClockSourceStatusBarView: NSView, StatusBarSubView { private var didSetupConstraints: Bool = false private var sampleRateTextField = AMTextField(forAutoLayout: ()) private var clockSourceTextField = AMTextField(forAutoLayout: ()) weak var representedObject: AnyObject? { didSet { setNeedsDisplay(bounds) } } var shouldHighlight: Bool = false { didSet { setNeedsDisplay(bounds) } } var isEnabled: Bool = true { didSet { setNeedsDisplay(bounds) } } override var intrinsicContentSize: NSSize { return NSSize(width: 82, height: 18) } // MARK: Lifecycle functions override init(frame frameRect: NSRect) { super.init(frame: frameRect) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Overrides override func draw(_ dirtyRect: NSRect) { updateUI() super.draw(dirtyRect) } override func viewDidMoveToSuperview() { addSubview(sampleRateTextField) addSubview(clockSourceTextField) } override func updateConstraints() { if didSetupConstraints == false { didSetupConstraints = true autoPinEdgesToSuperviewEdges(with: EdgeInsets(top: 1, left: 0, bottom: 1, right: 0)) sampleRateTextField.autoPinEdge(toSuperviewEdge: .top) sampleRateTextField.autoAlignAxis(toSuperviewAxis: .vertical) clockSourceTextField.autoPinEdge(toSuperviewEdge: .bottom) clockSourceTextField.autoAlignAxis(toSuperviewAxis: .vertical) } super.updateConstraints() } // MARK: Private functions private func updateUI() { if let device = representedObject as? AudioDevice { let formattedSampleRate = device.nominalSampleRate()?.string(as: .sampleRate) ?? "N/A" let formattedClockSource = device.clockSourceName() ?? NSLocalizedString("Internal Clock", comment: "") sampleRateTextField.attributedStringValue = attributedString(string: formattedSampleRate) clockSourceTextField.attributedStringValue = attributedString(string: formattedClockSource) sampleRateTextField.isEnabled = isEnabled clockSourceTextField.isEnabled = isEnabled } } private func attributedString(string: String) -> NSAttributedString { let textColor: NSColor = shouldHighlight ? .white : .labelColor let font = NSFont.boldSystemFont(ofSize: 9) let attrs = [NSFontAttributeName: font, NSForegroundColorAttributeName: textColor] let attrString = NSMutableAttributedString(string: string, attributes: attrs) attrString.setAlignment(NSTextAlignment.center, range: NSRange(location: 0, length: attrString.length)) return attrString.copy() as! NSAttributedString } }
b55a718411b088cf8739cc4304019f4e
25.957983
115
0.666771
false
false
false
false
jon-eikholm/iOSGames
refs/heads/master
A_Test_Project/A_Test_Project/GameViewController.swift
mit
1
// // GameViewController.swift // A_Test_Project // // Created by Jon on 08/02/15. // Copyright (c) 2015 ___Jon___. All rights reserved. // import UIKit import SpriteKit extension SKNode { class func unarchiveFromFile(file : NSString) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)! var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene archiver.finishDecoding() return scene } else { return nil } } } class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { // Configure the view. let skView = self.view as SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
34a0b8794f6b02f7a43e961f0e1073be
30.057971
104
0.621092
false
false
false
false
EstefaniaGilVaquero/OrienteeringQuizIOS
refs/heads/master
OrienteeringQuiz/OrienteeringQuiz/menuViewController.swift
apache-2.0
1
// // menuViewController.swift // memuDemo // // Created by Parth Changela on 09/10/16. // Copyright © 2016 Parth Changela. All rights reserved. // import UIKit class menuViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var tblTableView: UITableView! @IBOutlet weak var imgProfile: UIImageView! var ManuNameArray:Array = [String]() var iconArray:Array = [UIImage]() override func viewDidLoad() { super.viewDidLoad() ManuNameArray = ["Home","Message","Map","Setting"] iconArray = [UIImage(named:"home")!,UIImage(named:"message")!,UIImage(named:"map")!,UIImage(named:"setting")!] imgProfile.layer.borderWidth = 2 imgProfile.layer.borderColor = UIColor.green.cgColor imgProfile.layer.cornerRadius = 50 imgProfile.layer.masksToBounds = false imgProfile.clipsToBounds = true // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return ManuNameArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MenuCell", for: indexPath) as! MenuCell cell.lblMenuname.text! = ManuNameArray[indexPath.row] cell.imgIcon.image = iconArray[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let revealviewcontroller:SWRevealViewController = self.revealViewController() let cell:MenuCell = tableView.cellForRow(at: indexPath) as! MenuCell print(cell.lblMenuname.text!) if cell.lblMenuname.text! == "Home" { print("Home Tapped") let mainstoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let newViewcontroller = mainstoryboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController let newFrontController = UINavigationController.init(rootViewController: newViewcontroller) revealviewcontroller.pushFrontViewController(newFrontController, animated: true) } if cell.lblMenuname.text! == "Message" { print("message Tapped") let mainstoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let newViewcontroller = mainstoryboard.instantiateViewController(withIdentifier: "MessageViewController") as! MessageViewController let newFrontController = UINavigationController.init(rootViewController: newViewcontroller) revealviewcontroller.pushFrontViewController(newFrontController, animated: true) } if cell.lblMenuname.text! == "Map" { print("Map Tapped") } if cell.lblMenuname.text! == "Setting" { print("setting Tapped") } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
d124a0a315cf5af4511af220ae7bbabc
37.521277
143
0.660315
false
false
false
false
think-dev/MadridBUS
refs/heads/master
MadridBUS/Source/Data/Repositories/BusRepositoryBase.swift
mit
1
import Foundation import ObjectMapper class BusRepositoryBase: Repository, BusRepository { func groups() throws -> [BusGroup] { let request = RequestBuilder() .post() .url("/bus/GetGroups.php") .skip(key: "resultValues") .parameter(parameter: DTO()) .buildForJsonResponseFor(BusGroup.self) requestClient.execute(request) return try processMultiResponse(response: request.response) } func calendar(dto: BusCalendarDTO) throws -> [BusCalendarItem] { let request = RequestBuilder() .post() .url("/bus/GetCalendar.php") .skip(key: "resultValues") .parameter(parameter: dto) .buildForJsonResponseFor(BusCalendarItem.self) requestClient.execute(request) return try processMultiResponse(response: request.response) } internal func lineBasicInfo(dto: BusLinesBasicInfoDTO) throws -> [BusLineBasicInfo] { let request = RequestBuilder() .post() .url("/bus/GetListLines.php") .skip(key: "resultValues") .parameter(parameter: dto) .buildForJsonResponseFor(BusLineBasicInfo.self) requestClient.execute(request) do { let lines = try processMultiResponse(response: request.response) return lines } catch { let line = try processSingleResponse(response: request.response) return [line] } } internal func nodeBasicInfo(dto: BusNodesBasicInfoDTO) throws -> [BusNodeBasicInfo] { let request = RequestBuilder() .post() .url("/bus/GetNodesLines.php") .skip(key: "resultValues") .parameter(parameter: dto) .buildForJsonResponseFor(BusNodeBasicInfo.self) requestClient.execute(request) do { let nodes = try processMultiResponse(response: request.response) return nodes } catch { let node = try processSingleResponse(response: request.response) return [node] } } internal func nodesForBusLines(dto: BusNodesForBusLinesDTO) throws -> [BusNodeLocalized] { let request = RequestBuilder() .post() .url("/bus/GetRouteLines.php") .skip(key: "resultValues") .parameter(parameter: dto) .buildForJsonResponseFor(BusNodeLocalized.self) requestClient.execute(request) return try processMultiResponse(response: request.response) } internal func busLineSchedule(dto: BusLinesScheduleDTO) throws -> BusLineSchedule { let request = RequestBuilder() .post() .url("/bus/GetTimesLines.php") .skip(key: "resultValues") .parameter(parameter: dto) .buildForStringResponse() requestClient.execute(request) let jsonString = try processSingleResponse(response: request.response) return BusLineSchedule(using: jsonString) } internal func busLineTimeTable(dto: BusLineTimeTableDTO) throws -> [BusLineTimeTableItem] { let request = RequestBuilder() .post() .url("/bus/GetTimeTableLines.php") .skip(key: "resultValues") .parameter(parameter: dto) .buildForJsonResponseFor(BusLineTimeTableItem.self) requestClient.execute(request) return try processMultiResponse(response: request.response) } }
a6166f0dfad03070cd3a48ce8934d2f4
32.587156
95
0.595739
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Tool/Sources/ToolKit/General/Extensions/UserDefaults+Conveniences.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation extension UserDefaults { public func set<T: Encodable>(codable: T?, forKey key: String) { let encoder = JSONEncoder() guard codable != nil else { set(nil, forKey: key) return } do { let data = try encoder.encode(codable) let jsonString = String(data: data, encoding: .utf8)! set(jsonString, forKey: key) } catch { Logger.shared.error("Saving \"\(key)\" failed: \(error)") } } public func codable<T: Decodable>(_ codable: T.Type, forKey key: String) -> T? { guard let jsonString = string(forKey: key) else { return nil } guard let data = jsonString.data(using: .utf8) else { return nil } let decoder = JSONDecoder() return try? decoder.decode(codable, from: data) } }
e34d1228343784fbbace0facce07908b
33.037037
84
0.581066
false
false
false
false
alessiobrozzi/firefox-ios
refs/heads/master
Client/Frontend/Home/RemoteTabsPanel.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Account import Shared import SnapKit import Storage import Sync import XCGLogger private let log = Logger.browserLogger private struct RemoteTabsPanelUX { static let HeaderHeight = SiteTableViewControllerUX.RowHeight // Not HeaderHeight! static let RowHeight = SiteTableViewControllerUX.RowHeight static let HeaderBackgroundColor = UIColor(rgb: 0xf8f8f8) static let EmptyStateTitleTextColor = UIColor.darkGray static let EmptyStateInstructionsTextColor = UIColor.gray static let EmptyStateInstructionsWidth = 170 static let EmptyStateTopPaddingInBetweenItems: CGFloat = 15 // UX TODO I set this to 8 so that it all fits on landscape static let EmptyStateSignInButtonColor = UIColor(red:0.3, green:0.62, blue:1, alpha:1) static let EmptyStateSignInButtonTitleColor = UIColor.white static let EmptyStateSignInButtonCornerRadius: CGFloat = 4 static let EmptyStateSignInButtonHeight = 44 static let EmptyStateSignInButtonWidth = 200 // Backup and active strings added in Bug 1205294. static let EmptyStateInstructionsSyncTabsPasswordsBookmarksString = NSLocalizedString("Sync your tabs, bookmarks, passwords and more.", comment: "Text displayed when the Sync home panel is empty, describing the features provided by Sync to invite the user to log in.") static let EmptyStateInstructionsSyncTabsPasswordsString = NSLocalizedString("Sync your tabs, passwords and more.", comment: "Text displayed when the Sync home panel is empty, describing the features provided by Sync to invite the user to log in.") static let EmptyStateInstructionsGetTabsBookmarksPasswordsString = NSLocalizedString("Get your open tabs, bookmarks, and passwords from your other devices.", comment: "A re-worded offer about Sync, displayed when the Sync home panel is empty, that emphasizes one-way data transfer, not syncing.") static let HistoryTableViewHeaderChevronInset: CGFloat = 10 static let HistoryTableViewHeaderChevronSize: CGFloat = 20 static let HistoryTableViewHeaderChevronLineWidth: CGFloat = 3.0 } private let RemoteClientIdentifier = "RemoteClient" private let RemoteTabIdentifier = "RemoteTab" class RemoteTabsPanel: UIViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? fileprivate lazy var tableViewController: RemoteTabsTableViewController = RemoteTabsTableViewController() fileprivate lazy var historyBackButton: HistoryBackButton = { let button = HistoryBackButton() button.addTarget(self, action: #selector(RemoteTabsPanel.historyBackButtonWasTapped), for: .touchUpInside) return button }() var profile: Profile! init() { super.init(nibName: nil, bundle: nil) NotificationCenter.default.addObserver(self, selector: #selector(RemoteTabsPanel.notificationReceived(_:)), name: NotificationFirefoxAccountChanged, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(RemoteTabsPanel.notificationReceived(_:)), name: NotificationProfileDidFinishSyncing, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableViewController.profile = profile tableViewController.remoteTabsPanel = self view.backgroundColor = UIConstants.PanelBackgroundColor addChildViewController(tableViewController) self.view.addSubview(tableViewController.view) self.view.addSubview(historyBackButton) historyBackButton.snp.makeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(50) make.bottom.equalTo(tableViewController.view.snp.top) } tableViewController.view.snp.makeConstraints { make in make.top.equalTo(historyBackButton.snp.bottom) make.left.right.bottom.equalTo(self.view) } tableViewController.didMove(toParentViewController: self) } deinit { NotificationCenter.default.removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) NotificationCenter.default.removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil) } func notificationReceived(_ notification: Notification) { switch notification.name { case NotificationFirefoxAccountChanged, NotificationProfileDidFinishSyncing: DispatchQueue.main.async { print(notification.name) self.tableViewController.refreshTabs() } break default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } @objc fileprivate func historyBackButtonWasTapped(_ gestureRecognizer: UITapGestureRecognizer) { let _ = self.navigationController?.popViewController(animated: true) } } enum RemoteTabsError { case notLoggedIn case noClients case noTabs case failedToSync func localizedString() -> String { switch self { case .notLoggedIn: return "" // This does not have a localized string because we have a whole specific screen for it. case .noClients: return Strings.EmptySyncedTabsPanelNullStateDescription case .noTabs: return NSLocalizedString("You don't have any tabs open in Firefox on your other devices.", comment: "Error message in the remote tabs panel") case .failedToSync: return NSLocalizedString("There was a problem accessing tabs from your other devices. Try again in a few moments.", comment: "Error message in the remote tabs panel") } } } protocol RemoteTabsPanelDataSource: UITableViewDataSource, UITableViewDelegate { } class RemoteTabsPanelClientAndTabsDataSource: NSObject, RemoteTabsPanelDataSource { weak var homePanel: HomePanel? fileprivate var clientAndTabs: [ClientAndTabs] init(homePanel: HomePanel, clientAndTabs: [ClientAndTabs]) { self.homePanel = homePanel self.clientAndTabs = clientAndTabs } func numberOfSections(in tableView: UITableView) -> Int { return self.clientAndTabs.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.clientAndTabs[section].tabs.count } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return RemoteTabsPanelUX.HeaderHeight } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let clientTabs = self.clientAndTabs[section] let client = clientTabs.client let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: RemoteClientIdentifier) as! TwoLineHeaderFooterView view.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: RemoteTabsPanelUX.HeaderHeight) view.textLabel?.text = client.name view.contentView.backgroundColor = RemoteTabsPanelUX.HeaderBackgroundColor /* * A note on timestamps. * We have access to two timestamps here: the timestamp of the remote client record, * and the set of timestamps of the client's tabs. * Neither is "last synced". The client record timestamp changes whenever the remote * client uploads its record (i.e., infrequently), but also whenever another device * sends a command to that client -- which can be much later than when that client * last synced. * The client's tabs haven't necessarily changed, but it can still have synced. * Ideally, we should save and use the modified time of the tabs record itself. * This will be the real time that the other client uploaded tabs. */ let timestamp = clientTabs.approximateLastSyncTime() let label = NSLocalizedString("Last synced: %@", comment: "Remote tabs last synced time. Argument is the relative date string.") view.detailTextLabel?.text = String(format: label, Date.fromTimestamp(timestamp).toRelativeTimeString()) let image: UIImage? if client.type == "desktop" { image = UIImage(named: "deviceTypeDesktop") image?.accessibilityLabel = NSLocalizedString("computer", comment: "Accessibility label for Desktop Computer (PC) image in remote tabs list") } else { image = UIImage(named: "deviceTypeMobile") image?.accessibilityLabel = NSLocalizedString("mobile device", comment: "Accessibility label for Mobile Device image in remote tabs list") } view.imageView.image = image view.mergeAccessibilityLabels() return view } fileprivate func tabAtIndexPath(_ indexPath: IndexPath) -> RemoteTab { return clientAndTabs[indexPath.section].tabs[indexPath.item] } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: RemoteTabIdentifier, for: indexPath) as! TwoLineTableViewCell let tab = tabAtIndexPath(indexPath) cell.setLines(tab.title, detailText: tab.URL.absoluteString) // TODO: Bug 1144765 - Populate image with cached favicons. return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let tab = tabAtIndexPath(indexPath) if let homePanel = self.homePanel { // It's not a bookmark, so let's call it Typed (which means History, too). homePanel.homePanelDelegate?.homePanel(homePanel, didSelectURL: tab.URL, visitType: VisitType.typed) } } } // MARK: - class RemoteTabsPanelErrorDataSource: NSObject, RemoteTabsPanelDataSource { weak var homePanel: HomePanel? var error: RemoteTabsError var notLoggedCell: UITableViewCell? init(homePanel: HomePanel, error: RemoteTabsError) { self.homePanel = homePanel self.error = error self.notLoggedCell = nil } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let cell = self.notLoggedCell { cell.updateConstraints() } return tableView.bounds.height } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { // Making the footer height as small as possible because it will disable button tappability if too high. return 1 } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch error { case .notLoggedIn: let cell = RemoteTabsNotLoggedInCell(homePanel: homePanel) self.notLoggedCell = cell return cell default: let cell = RemoteTabsErrorCell(error: self.error) self.notLoggedCell = nil return cell } } } // MARK: - class RemoteTabsErrorCell: UITableViewCell { static let Identifier = "RemoteTabsErrorCell" init(error: RemoteTabsError) { super.init(style: .default, reuseIdentifier: RemoteTabsErrorCell.Identifier) separatorInset = UIEdgeInsets(top: 0, left: 1000, bottom: 0, right: 0) let containerView = UIView() contentView.addSubview(containerView) let imageView = UIImageView() imageView.image = UIImage(named: "emptySync") containerView.addSubview(imageView) imageView.snp.makeConstraints { (make) -> Void in make.top.equalTo(containerView) make.centerX.equalTo(containerView) } let titleLabel = UILabel() titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont titleLabel.text = Strings.EmptySyncedTabsPanelStateTitle titleLabel.textAlignment = NSTextAlignment.center titleLabel.textColor = RemoteTabsPanelUX.EmptyStateTitleTextColor containerView.addSubview(titleLabel) let instructionsLabel = UILabel() instructionsLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight instructionsLabel.text = error.localizedString() instructionsLabel.textAlignment = NSTextAlignment.center instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor instructionsLabel.numberOfLines = 0 containerView.addSubview(instructionsLabel) titleLabel.snp.makeConstraints { make in make.top.equalTo(imageView.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(imageView) } instructionsLabel.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems / 2) make.centerX.equalTo(containerView) make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth) } containerView.snp.makeConstraints { make in // Let the container wrap around the content make.top.equalTo(imageView.snp.top) make.left.bottom.right.equalTo(instructionsLabel) // And then center it in the overlay view that sits on top of the UITableView make.centerX.equalTo(contentView) // Sets proper top constraint for iPhone 6 in portait and for iPad. make.centerY.equalTo(contentView.snp.centerY).offset(HomePanelUX.EmptyTabContentOffset).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(contentView.snp.top).offset(20).priority(1000) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - class RemoteTabsNotLoggedInCell: UITableViewCell { static let Identifier = "RemoteTabsNotLoggedInCell" var homePanel: HomePanel? var instructionsLabel: UILabel var signInButton: UIButton var titleLabel: UILabel var emptyStateImageView: UIImageView init(homePanel: HomePanel?) { let titleLabel = UILabel() let instructionsLabel = UILabel() let signInButton = UIButton() let imageView = UIImageView() self.instructionsLabel = instructionsLabel self.signInButton = signInButton self.titleLabel = titleLabel self.emptyStateImageView = imageView super.init(style: .default, reuseIdentifier: RemoteTabsErrorCell.Identifier) self.homePanel = homePanel let createAnAccountButton = UIButton(type: .system) imageView.image = UIImage(named: "emptySync") contentView.addSubview(imageView) titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont titleLabel.text = Strings.EmptySyncedTabsPanelStateTitle titleLabel.textAlignment = NSTextAlignment.center titleLabel.textColor = RemoteTabsPanelUX.EmptyStateTitleTextColor contentView.addSubview(titleLabel) instructionsLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight instructionsLabel.text = Strings.EmptySyncedTabsPanelStateDescription instructionsLabel.textAlignment = NSTextAlignment.center instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor instructionsLabel.numberOfLines = 0 contentView.addSubview(instructionsLabel) signInButton.backgroundColor = RemoteTabsPanelUX.EmptyStateSignInButtonColor signInButton.setTitle(NSLocalizedString("Sign in", comment: "See http://mzl.la/1Qtkf0j"), for: UIControlState()) signInButton.setTitleColor(RemoteTabsPanelUX.EmptyStateSignInButtonTitleColor, for: UIControlState()) signInButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.subheadline) signInButton.layer.cornerRadius = RemoteTabsPanelUX.EmptyStateSignInButtonCornerRadius signInButton.clipsToBounds = true signInButton.addTarget(self, action: #selector(RemoteTabsNotLoggedInCell.SELsignIn), for: UIControlEvents.touchUpInside) contentView.addSubview(signInButton) createAnAccountButton.setTitle(NSLocalizedString("Create an account", comment: "See http://mzl.la/1Qtkf0j"), for: UIControlState()) createAnAccountButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption1) createAnAccountButton.addTarget(self, action: #selector(RemoteTabsNotLoggedInCell.SELcreateAnAccount), for: UIControlEvents.touchUpInside) contentView.addSubview(createAnAccountButton) imageView.snp.makeConstraints { (make) -> Void in make.centerX.equalTo(instructionsLabel) // Sets proper top constraint for iPhone 6 in portait and for iPad. make.centerY.equalTo(contentView).offset(HomePanelUX.EmptyTabContentOffset + 30).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(contentView.snp.top).priority(1000) } titleLabel.snp.makeConstraints { make in make.top.equalTo(imageView.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(imageView) } createAnAccountButton.snp.makeConstraints { (make) -> Void in make.centerX.equalTo(signInButton) make.top.equalTo(signInButton.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc fileprivate func SELsignIn() { if let homePanel = self.homePanel { homePanel.homePanelDelegate?.homePanelDidRequestToSignIn(homePanel) } } @objc fileprivate func SELcreateAnAccount() { if let homePanel = self.homePanel { homePanel.homePanelDelegate?.homePanelDidRequestToCreateAccount(homePanel) } } override func updateConstraints() { if UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) && !(DeviceInfo.deviceModel().range(of: "iPad") != nil) { instructionsLabel.snp.remakeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth) // Sets proper landscape layout for bigger phones: iPhone 6 and on. make.left.lessThanOrEqualTo(contentView.snp.left).offset(80).priority(100) // Sets proper landscape layout for smaller phones: iPhone 4 & 5. make.right.lessThanOrEqualTo(contentView.snp.centerX).offset(-30).priority(1000) } signInButton.snp.remakeConstraints { make in make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight) make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth) make.centerY.equalTo(emptyStateImageView).offset(2*RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) // Sets proper landscape layout for bigger phones: iPhone 6 and on. make.right.greaterThanOrEqualTo(contentView.snp.right).offset(-70).priority(100) // Sets proper landscape layout for smaller phones: iPhone 4 & 5. make.left.greaterThanOrEqualTo(contentView.snp.centerX).offset(10).priority(1000) } } else { instructionsLabel.snp.remakeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(contentView) make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth) } signInButton.snp.remakeConstraints { make in make.centerX.equalTo(contentView) make.top.equalTo(instructionsLabel.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight) make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth) } } super.updateConstraints() } } fileprivate class RemoteTabsTableViewController: UITableViewController { weak var remoteTabsPanel: RemoteTabsPanel? var profile: Profile! var tableViewDelegate: RemoteTabsPanelDataSource? { didSet { tableView.dataSource = tableViewDelegate tableView.delegate = tableViewDelegate } } override func viewDidLoad() { super.viewDidLoad() tableView.register(TwoLineHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: RemoteClientIdentifier) tableView.register(TwoLineTableViewCell.self, forCellReuseIdentifier: RemoteTabIdentifier) tableView.rowHeight = RemoteTabsPanelUX.RowHeight tableView.separatorInset = UIEdgeInsets.zero tableView.delegate = nil tableView.dataSource = nil refreshControl = UIRefreshControl() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refreshControl?.addTarget(self, action: #selector(RemoteTabsTableViewController.refreshTabs), for: .valueChanged) refreshTabs() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) refreshControl?.removeTarget(self, action: #selector(RemoteTabsTableViewController.refreshTabs), for: .valueChanged) } fileprivate func startRefreshing() { if let refreshControl = self.refreshControl { let height = -refreshControl.bounds.size.height tableView.setContentOffset(CGPoint(x: 0, y: height), animated: true) refreshControl.beginRefreshing() } } func endRefreshing() { if self.refreshControl?.isRefreshing ?? false { self.refreshControl?.endRefreshing() } self.tableView.isScrollEnabled = true self.tableView.reloadData() } func updateDelegateClientAndTabData(_ clientAndTabs: [ClientAndTabs]) { guard let remoteTabsPanel = remoteTabsPanel else { return } if clientAndTabs.count == 0 { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: remoteTabsPanel, error: .noClients) } else { let nonEmptyClientAndTabs = clientAndTabs.filter { $0.tabs.count > 0 } if nonEmptyClientAndTabs.count == 0 { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: remoteTabsPanel, error: .noTabs) } else { self.tableViewDelegate = RemoteTabsPanelClientAndTabsDataSource(homePanel: remoteTabsPanel, clientAndTabs: nonEmptyClientAndTabs) tableView.allowsSelection = true } } } @objc fileprivate func refreshTabs() { guard let remoteTabsPanel = remoteTabsPanel else { return } assert(Thread.isMainThread) tableView.isScrollEnabled = false tableView.allowsSelection = false tableView.tableFooterView = UIView(frame: CGRect.zero) // Short circuit if the user is not logged in if !profile.hasSyncableAccount() { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: remoteTabsPanel, error: .notLoggedIn) self.endRefreshing() return } self.profile.getCachedClientsAndTabs().uponQueue(DispatchQueue.main) { result in if let clientAndTabs = result.successValue { self.updateDelegateClientAndTabData(clientAndTabs) } // Otherwise, fetch the tabs cloud if it's been more than 1 minute since last sync let lastSyncTime = self.profile.prefs.timestampForKey(PrefsKeys.KeyLastRemoteTabSyncTime) if Date.now() > (lastSyncTime ?? 0) && Date.now() - (lastSyncTime ?? 0) > OneMinuteInMilliseconds && !(self.refreshControl?.isRefreshing ?? false) { self.startRefreshing() self.profile.getClientsAndTabs().uponQueue(DispatchQueue.main) { result in // We set the last sync time to now, regardless of whether the sync was successful, to avoid trying to sync over // and over again in cases whether the client is unable to sync (e.g. when there is no network connectivity). self.profile.prefs.setTimestamp(Date.now(), forKey: PrefsKeys.KeyLastRemoteTabSyncTime) if let clientAndTabs = result.successValue { self.updateDelegateClientAndTabData(clientAndTabs) } self.endRefreshing() } } else { // If we failed before and didn't sync, show the failure delegate if let _ = result.failureValue { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: remoteTabsPanel, error: .failedToSync) } self.endRefreshing() } } } }
09a63f8633b1a2a03a87c9de70020b0f
43.357751
300
0.698172
false
false
false
false
fs/FSHelper
refs/heads/master
Source/FSExtensions/FSE+UIImage.swift
mit
1
// // FSE+UIImage.swift // Swift-Base // // Created by Kruperfone on 23.09.15. // Copyright © 2015 Flatstack. All rights reserved. // import UIKit public extension UIImage { convenience public init(fs_color color: UIColor) { let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0) UIGraphicsBeginImageContext(rect.size) let context: CGContext = UIGraphicsGetCurrentContext()! context.setFillColor(color.cgColor) context.fill(rect) UIGraphicsEndImageContext() let image = context.makeImage()! self.init(cgImage: image) } public func fs_aspectFillImageWithSize(_ size: CGSize) -> UIImage{ UIGraphicsBeginImageContextWithOptions(size, false, 0) let scale = max(size.width / self.size.width, size.height / self.size.height) let newSize = CGSize(width: ceil(self.size.width * scale), height: ceil(self.size.height * scale)) let frame = CGRect(x: ceil((size.width - newSize.width) / 2.0), y: ceil((size.height - newSize.height) / 2.0), width: newSize.width, height: newSize.height) self.draw(in: frame) let image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } public func fs_aspectFitImageWithSize(_ size: CGSize) -> UIImage { let scale = min(size.width / self.size.width, size.height / self.size.height) let targetSize = CGSize(width: ceil(self.size.width * scale), height: ceil(self.size.height * scale)) return self.fs_aspectFillImageWithSize(targetSize) } public final func fs_scaled(toSize size: CGSize) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) self.draw(in: CGRect(x: 0.0, y: 0.0, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } public final func fs_scaled(toWidth width: CGFloat) -> UIImage? { let scaleFactor = width / self.size.width let scaledSize: CGSize = CGSize(width: self.size.width * scaleFactor, height: self.size.height * scaleFactor) UIGraphicsBeginImageContext(scaledSize) self.draw(in: CGRect(x: 0.0, y: 0.0, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } public var fs_base64: String { let imageData = self.pngData()! let base64String = imageData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) return base64String } }
faa0a3a1cb4723c702af5cfd530263d0
33.767442
117
0.590635
false
false
false
false
ijovi23/JvSpeechRecognizer
refs/heads/master
JvSpeechRecognizer/Classes/JvSpeechRecognizer.swift
mit
1
// // JvSpeechRecognizer.swift // JvSpeechRecognizerDemo // // Created by Jovi Du on 20/04/2017. // Copyright © 2017 Jovistudio. All rights reserved. // import Speech @objc public enum JvSpeechRecognizerStartResult: Int { case success = 0 case busy case noPermission case recognizerUnavailable case audioEngineNoInputNode case otherError } @objc public enum JvSpeechRecognizerStatus: Int { case idle case listening case recognizing } @objc public protocol JvSpeechRecognizerDelegate: NSObjectProtocol { @available(iOS 10.0, *) @objc optional func jvSpeechRecognizer(_ recognizer: JvSpeechRecognizer, didRecognizePartialResult partialResult: String) @available(iOS 10.0, *) @objc optional func jvSpeechRecognizer(_ recognizer: JvSpeechRecognizer, didRecognizeFinalResult finalResult: String, allResults: [String]) @available(iOS 10.0, *) @objc optional func jvSpeechRecognizerWasCancelled(_ recognizer: JvSpeechRecognizer) @available(iOS 10.0, *) @objc optional func jvSpeechRecognizer(_ recognizer: JvSpeechRecognizer, didFinishWithError error: Error?) } @available(iOS 10.0, *) open class JvSpeechRecognizer: NSObject { //Public Properties /// The delegate to receive events from the recognizer. weak open var delegate: JvSpeechRecognizerDelegate? /// The currnt status. open private(set) var status: JvSpeechRecognizerStatus = .idle /// If you want to control AVAudioSession by yourself, set this property to false. /// Default is true. open var audioSessionControlEnabled = true /// If true, partial (non-final) results for each utterance will be reported. /// Default is true. open var reportPartialResults = true /// If true, punctuations will be added to the results. /// Default is true. var needsPunctuation = true /// Whether the debug log will be printed. /// Default is false. open var needsDebugLog = false /// Whether the user permitted microphone usage for this app. public var microphonePermitted: Bool { get { return (avAudioSession.recordPermission() == .granted) } } /// Whether the user permitted speech recognition usage for this app. public var speechRecognitionPermitted: Bool { get { return (SFSpeechRecognizer.authorizationStatus() == .authorized) } } /// Whether the speech recognizer is available. /// It might be unavailable for reasons like locale, network, etc. public var isAvailable: Bool { get { return (microphonePermitted && speechRecognitionPermitted) && ((sfRecognizer != nil) && sfRecognizer!.isAvailable) } } //Private Properties private var sfRecognizer: SFSpeechRecognizer? private var sfRecognizerDelegate: JvSpeechRecognizer_nativeRecognizerDelegate private var sfRecognitionTask: SFSpeechRecognitionTask? private var sfAudioRecognitionRequest: SFSpeechAudioBufferRecognitionRequest? private var avAudioEngine: AVAudioEngine? weak private var avAudioSession: AVAudioSession! { get { return AVAudioSession.sharedInstance() } } /// Init with a locale identifier such as "en-US". public init?(localeId: String?) { if localeId != nil { sfRecognizer = SFSpeechRecognizer(locale: Locale(identifier: localeId!)) } else { sfRecognizer = SFSpeechRecognizer() } sfRecognizerDelegate = JvSpeechRecognizer_nativeRecognizerDelegate() super.init() sfRecognizerDelegate.ownerRecognizer = self } //Open Func /// Call this method to request the nesessary permissions for speech recognition.(asynchronous) /// Some system privacy alerts may show during this time. open func requestPermission(_ response: @escaping (Bool) -> Void) { _requestPermission(response) } /// Call this method to start recording and recognizing. /// The start result will return when it starts successfully or an error occurs. @discardableResult open func startSpeaking() -> JvSpeechRecognizerStartResult { return _startSpeaking() } /// Call this method to indicates a new delegate, start recording and recognizing. /// The start result will return when it starts successfully or an error occurs. @discardableResult open func startSpeaking(delegate del: JvSpeechRecognizerDelegate) -> JvSpeechRecognizerStartResult { delegate = del return _startSpeaking() } /// Call this method to stop recording. /// Recognizer would be still working until the final recognition result is reported. open func stopSpeaking() { _stopSpeaking() } /// Call this method to stop recording, recognizing. open func cancel() { _cancel() } //Private Func private func _requestPermission(_ response: @escaping (Bool) -> Void) { // Request Microphone Permission avAudioSession.requestRecordPermission { (granted) in if granted { // Microphone Usage Permitted // Then Request Speech Recognition Permission SFSpeechRecognizer.requestAuthorization({ (authStatus) in OperationQueue.main.addOperation { response(authStatus == .authorized) } }) } else { // Microphone Usage Refused OperationQueue.main.addOperation { response(false) } } } } @discardableResult private func _startSpeaking() -> JvSpeechRecognizerStartResult { guard microphonePermitted && speechRecognitionPermitted else { return .noPermission } guard let sfRecognizer = sfRecognizer else { return .recognizerUnavailable } guard sfRecognizer.isAvailable else { return .recognizerUnavailable } guard status == .idle else { return .busy } if audioSessionControlEnabled { do { try avAudioSession.setCategory(AVAudioSessionCategoryRecord) try avAudioSession.setMode(AVAudioSessionModeMeasurement) try avAudioSession.setActive(true, with: .notifyOthersOnDeactivation) } catch { printIfNeeded("AudioSession setup failed: \(error.localizedDescription)") return .otherError } } avAudioEngine = AVAudioEngine() guard let avAudioEngine = avAudioEngine else { return .otherError } guard let inputNode = avAudioEngine.inputNode else { printIfNeeded("Cannot perform input with current hardware/AVAudioSesssionCategory.") return .audioEngineNoInputNode } sfAudioRecognitionRequest = SFSpeechAudioBufferRecognitionRequest() guard let sfAudioRecognitionRequest = sfAudioRecognitionRequest else { printIfNeeded("Failed to create the instance of SFSpeechAudioBufferRecognitionRequest") return .otherError } sfAudioRecognitionRequest.shouldReportPartialResults = reportPartialResults sfRecognitionTask = sfRecognizer.recognitionTask(with: sfAudioRecognitionRequest, delegate: sfRecognizerDelegate) let recordingFormat = inputNode.outputFormat(forBus: 0) inputNode.installTap(onBus: 0, bufferSize: 8192, format: recordingFormat) { (buffer, when) in sfAudioRecognitionRequest.append(buffer) } avAudioEngine.prepare() do { try avAudioEngine.start() } catch { printIfNeeded("AudioEngine failed to start: \(error.localizedDescription)") return .otherError } status = .listening return .success } private func _stopSpeaking() { avAudioEngine?.stop() sfAudioRecognitionRequest?.endAudio() if sfRecognitionTask != nil { switch sfRecognitionTask!.state { case .starting, .running: sfRecognitionTask?.finish() default: break } } status = .recognizing } private func _cancel() { avAudioEngine?.stop() sfAudioRecognitionRequest?.endAudio() if sfRecognitionTask != nil { switch sfRecognitionTask!.state { case .starting, .running, .finishing: sfRecognitionTask?.cancel() default: break } } status = .idle } fileprivate func printIfNeeded(_ content: String) { if needsDebugLog { print(content) } } fileprivate func setStatus(_ newStatus: JvSpeechRecognizerStatus) { status = newStatus } } @available(iOS 10.0, *) private class JvSpeechRecognizer_nativeRecognizerDelegate: NSObject, SFSpeechRecognitionTaskDelegate { weak public var ownerRecognizer: JvSpeechRecognizer? public func speechRecognitionDidDetectSpeech(_ task: SFSpeechRecognitionTask) { ownerRecognizer?.printIfNeeded("speechRecognitionDidDetectSpeech") } public func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didHypothesizeTranscription transcription: SFTranscription) { ownerRecognizer?.printIfNeeded("speechRecognitionTaskDidHypothesizeTranscription") let result = (ownerRecognizer!.needsPunctuation) ? resultByAddingPunctuation(forTranscription: transcription, isFinal: false) : transcription.formattedString /*transcription.segments.forEach { (segment) in print("\(segment.timestamp)|\(segment.duration)|\(segment.substring)|(\(segment.substringRange.location),\(segment.substringRange.length))") } //test*/ OperationQueue.main.addOperation { self.ownerRecognizer?.delegate?.jvSpeechRecognizer?(self.ownerRecognizer!, didRecognizePartialResult: result) } } public func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didFinishRecognition recognitionResult: SFSpeechRecognitionResult) { ownerRecognizer?.printIfNeeded("speechRecognitionTaskDidFinishRecognition") let bestResult = (ownerRecognizer!.needsPunctuation) ? resultByAddingPunctuation(forTranscription: recognitionResult.bestTranscription, isFinal: true) : recognitionResult.bestTranscription.formattedString let results = recognitionResult.transcriptions.map({$0.formattedString}) /*recognitionResult.bestTranscription.segments.forEach { (segment) in print("\(segment.timestamp)|\(segment.duration)|\(segment.substring)|(\(segment.substringRange.location),\(segment.substringRange.length))") } //test*/ OperationQueue.main.addOperation { self.ownerRecognizer?.delegate?.jvSpeechRecognizer?(self.ownerRecognizer!, didRecognizeFinalResult: bestResult, allResults: results) } } public func speechRecognitionTaskFinishedReadingAudio(_ task: SFSpeechRecognitionTask) { ownerRecognizer?.printIfNeeded("speechRecognitionTaskFinishedReadingAudio") self.ownerRecognizer?.setStatus(.recognizing) } public func speechRecognitionTaskWasCancelled(_ task: SFSpeechRecognitionTask) { ownerRecognizer?.printIfNeeded("speechRecognitionTaskWasCancelled") self.ownerRecognizer?.setStatus(.idle) OperationQueue.main.addOperation { self.ownerRecognizer?.delegate?.jvSpeechRecognizerWasCancelled?(self.ownerRecognizer!) } } public func speechRecognitionTask(_ task: SFSpeechRecognitionTask, didFinishSuccessfully successfully: Bool) { if successfully { ownerRecognizer?.printIfNeeded("speechRecognitionTaskDidFinishSuccessfully") } else { ownerRecognizer?.printIfNeeded("speechRecognitionTaskDidFinishUnsuccessfully: \(task.error?.localizedDescription ?? "Unknown error")") } self.ownerRecognizer?.setStatus(.idle) OperationQueue.main.addOperation { self.ownerRecognizer?.delegate?.jvSpeechRecognizer?(self.ownerRecognizer!, didFinishWithError: task.error) } } public func resultByAddingPunctuation(forTranscription transcription: SFTranscription, isFinal: Bool) -> String { let ret: String = transcription.segments.reduce("") { var punc = "" if isEnd($1) { punc = (isFinal && $1 == transcription.segments.last) ? "." : "," } return $0 + $1.substring + punc + " " } return ret } func isEnd(_ segment: SFTranscriptionSegment) -> Bool { let length = segment.substringRange.length let boundaryDuration :TimeInterval = Double(length) * 0.11 + 0.8 return segment.duration > boundaryDuration } }
3395550ee82009d7067d350dee5566d1
35.589041
212
0.652714
false
false
false
false
tensorflow/examples
refs/heads/master
lite/examples/style_transfer/ios/StyleTransfer/TFLiteExtension.swift
apache-2.0
1
// Copyright 2020 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import CoreGraphics import Foundation import UIKit // MARK: - UIImage /// Extension of iOS classes that is useful for working with TensorFlow Lite computer vision models. extension UIImage { /// Creates and returns a new image scaled to the given size. The image preserves its original PNG /// or JPEG bitmap info. /// /// - Parameter size: The size to scale the image to. /// - Returns: The scaled image or `nil` if image could not be resized. func scaledImage(with size: CGSize) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } draw(in: CGRect(origin: .zero, size: size)) return UIGraphicsGetImageFromCurrentImageContext()?.data.flatMap(UIImage.init) } /// Returns the data representation of the image after scaling to the given `size` and removing /// the alpha component. This function assumes a batch size of one and three channels per image. /// Changing these parameters in the TF Lite model will cause conflicts. /// /// - Parameters /// - size: Size to scale the image to (i.e. image size used while training the model). /// - isQuantized: Whether the model is quantized (i.e. fixed point values rather than floating /// point values). /// - Returns: The scaled image as data or `nil` if the image could not be scaled. func scaledData(with size: CGSize, isQuantized: Bool) -> Data? { guard let cgImage = self.cgImage else { return nil } return UIImage.normalizedData(from: cgImage, resizingTo: size, quantum: Float32.self) } /// Make the same image with orientation being `.up`. /// - Returns: A copy of the image with .up orientation or `nil` if the image could not be /// rotated. func transformOrientationToUp() -> UIImage? { // Check if the image orientation is already .up and don't need any rotation. guard imageOrientation != UIImage.Orientation.up else { // No rotation needed so return a copy of this image. return self.copy() as? UIImage } // Make sure that this image has an CGImage attached. guard let cgImage = self.cgImage else { return nil } // Create a CGContext to draw the rotated image to. guard let colorSpace = cgImage.colorSpace, let context = CGContext( data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue ) else { return nil } var transform: CGAffineTransform = CGAffineTransform.identity // Calculate the transformation matrix that needed to bring the image orientation to .up switch imageOrientation { case .down, .downMirrored: transform = transform.translatedBy(x: size.width, y: size.height) transform = transform.rotated(by: CGFloat.pi) break case .left, .leftMirrored: transform = transform.translatedBy(x: size.width, y: 0) transform = transform.rotated(by: CGFloat.pi / 2.0) break case .right, .rightMirrored: transform = transform.translatedBy(x: 0, y: size.height) transform = transform.rotated(by: CGFloat.pi / -2.0) break case .up, .upMirrored: break @unknown default: break } // If the image is mirrored then flip it. switch imageOrientation { case .upMirrored, .downMirrored: transform = transform.translatedBy(x: size.width, y: 0) transform = transform.scaledBy(x: -1, y: 1) break case .leftMirrored, .rightMirrored: transform = transform.translatedBy(x: size.height, y: 0) transform = transform.scaledBy(x: -1, y: 1) case .up, .down, .left, .right: break @unknown default: break } // Apply transformation matrix to the CGContext. context.concatenate(transform) switch imageOrientation { case .left, .leftMirrored, .right, .rightMirrored: context.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width)) default: context.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) break } // Create a CGImage from the context. guard let newCGImage = context.makeImage() else { return nil } // Convert it to UIImage. return UIImage.init(cgImage: newCGImage, scale: 1, orientation: .up) } // MARK: - Private /// The PNG or JPEG data representation of the image or `nil` if the conversion failed. private var data: Data? { return self.pngData() ?? self.jpegData(compressionQuality: Constant.jpegCompressionQuality) } static func normalizeImage(_ image: CGImage, resizingTo size: CGSize) -> CGImage? { // The TF Lite model expects images in the RGB color space. // Device-specific RGB color spaces should have the same number of colors as the standard // RGB color space so we probably don't have to redraw them. let colorSpace = CGColorSpaceCreateDeviceRGB() let cgImageSize = CGSize(width: image.width, height: image.height) if cgImageSize == size, (image.colorSpace?.name == colorSpace.name || image.colorSpace?.name == CGColorSpace.sRGB) { // Return the image if it is in the right format // to save a redraw operation. return image } let bitmapInfo = CGBitmapInfo( rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue ) let width = Int(size.width) let scaledBytesPerRow = (image.bytesPerRow / image.width) * width guard let context = CGContext( data: nil, width: width, height: Int(size.height), bitsPerComponent: image.bitsPerComponent, bytesPerRow: scaledBytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else { return nil } context.draw(image, in: CGRect(origin: .zero, size: size)) return context.makeImage() } static func normalizedData<T>(from image: CGImage, resizingTo size: CGSize, quantum: T.Type) -> Data? where T: FloatingPoint { guard let normalizedImage = normalizeImage(image, resizingTo: size) else { return nil } guard let data = normalizedImage.dataProvider?.data as Data? else { return nil } // TF Lite expects an array of pixels in the form of floats normalized between 0 and 1. var floatArray: [T] // A full list of pixel formats is listed in this document under Table 2-1: // https://developer.apple.com/library/archive/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_context/dq_context.html#//apple_ref/doc/uid/TP30001066-CH203-CJBHBFFE // This code only handles pixel formats supported on iOS in the RGB color space. // If you're targeting macOS or macOS via Catalyst, you should support the macOS // pixel formats as well. switch normalizedImage.bitsPerPixel { // 16-bit pixel with no alpha channel. On iOS, this must have 5 bits per channel and // no alpha channel. The most significant bits are skipped. case 16: guard normalizedImage.bitsPerComponent == 5 else { return nil } guard normalizedImage.alphaInfo.rawValue & CGImageAlphaInfo.noneSkipFirst.rawValue != 0 else { return nil } // If this bool is false, assume little endian byte order. let bigEndian: Bool = { // Sometimes images have both littleEndian and bigEndian flags set. In this case, use the // non-default endianness because it seems to work best in empirical testing. let hasLittleEndian = normalizedImage.bitmapInfo.contains(.byteOrder16Little) let hasBigEndian = normalizedImage.bitmapInfo.contains(.byteOrder16Big) if !(hasLittleEndian && hasBigEndian) { return hasBigEndian } let currentByteOrder = CFByteOrderGetCurrent() switch currentByteOrder { case Int(CFByteOrderLittleEndian.rawValue): return true case Int(CFByteOrderBigEndian.rawValue): return false case _: // For unknown endianness, assume little endian since it's how most // Apple platforms are laid out nowadays. return false } }() let initializer: (inout UnsafeMutableBufferPointer<T>, inout Int) -> () = { bufferPointer, initializedCount in let redMask: UInt16 = UInt16(0b0111110000000000) let greenMask: UInt16 = UInt16(0b0000001111100000) let blueMask: UInt16 = UInt16(0b0000000000011111) for byteIndex in stride(from: 0, to: data.count, by: 2) { // pixels are two bytes wide let pixelRange = byteIndex ..< byteIndex + 2 let pixelData = data[pixelRange] let rawPixel = pixelData.withUnsafeBytes { $0.load(as: UInt16.self) } let pixel: UInt16 if bigEndian { pixel = rawPixel.bigEndian } else { pixel = rawPixel.littleEndian } let redChannel = ((pixel & redMask) &>> 10) let greenChannel = ((pixel & greenMask) &>> 5) let blueChannel = ((pixel & blueMask) &>> 0) let maximumChannelValue = T(31) // 2 ^ 5 - 1 let red = T(redChannel) / maximumChannelValue let green = T(greenChannel) / maximumChannelValue let blue = T(blueChannel) / maximumChannelValue let pixelIndex = byteIndex / 2 let floatIndex = pixelIndex * 3 bufferPointer[floatIndex] = red bufferPointer[floatIndex + 1] = green bufferPointer[floatIndex + 2] = blue } initializedCount = data.count / 2 * 3 } floatArray = [T](unsafeUninitializedCapacity: data.count / 2 * 3, initializingWith: initializer) // We discard the image's alpha channel before running the TF Lite model, so we can treat // alpha and non-alpha images identically. case 32: guard normalizedImage.bitsPerComponent == 8 else { return nil } let alphaFirst = normalizedImage.alphaInfo == CGImageAlphaInfo.noneSkipFirst || normalizedImage.alphaInfo == CGImageAlphaInfo.premultipliedFirst let alphaLast = normalizedImage.alphaInfo == CGImageAlphaInfo.noneSkipLast || normalizedImage.alphaInfo == CGImageAlphaInfo.premultipliedLast let bigEndian = normalizedImage.bitmapInfo.contains(.byteOrder32Big) let littleEndian = normalizedImage.bitmapInfo.contains(.byteOrder32Little) guard alphaFirst || alphaLast else { return nil } guard bigEndian || littleEndian else { return nil } // Iterate over channels individually. Since the order of the channels in memory // may vary, we cannot add channels to the float buffer we pass to TF Lite in the // order that they are iterated over. let initializer: (inout UnsafeMutableBufferPointer<T>, inout Int) -> () = { bufferPointer, initializedCount in let numberOfChannels = 4 let alphaOffset: UInt8 = { if bigEndian { return alphaFirst ? 0 : 3 } else { return alphaFirst ? 3 : 0 } }() let redOffset: UInt8 = { if bigEndian { return alphaFirst ? 1 : 0 } else { return alphaFirst ? 2 : 3 } }() let greenOffset: UInt8 = { if bigEndian { return alphaFirst ? 2 : 1 } else { return alphaFirst ? 1 : 2 } }() let blueOffset: UInt8 = { if bigEndian { return alphaFirst ? 3 : 2 } else { return alphaFirst ? 0 : 1 } }() // Make sure we add the pixel components to the float array in the right // order regardless of pixel endianness. var rgbHolder: (red: T?, green: T?, blue: T?) = (nil, nil, nil) var floatIndex = 0 func flushRGBs(_ rgbs: (red: T?, green: T?, blue: T?), to array: inout UnsafeMutableBufferPointer<T>, at index: Int) { guard let red = rgbs.red, let green = rgbs.green, let blue = rgbs.blue else { return } array[index] = red array[index + 1] = green array[index + 2] = blue floatIndex += 3 } let maximumChannelValue: T = 255 // 2 ^ 8 - 1 func normalizeChannel(_ channel: UInt8) -> T { return T( bigEndian ? channel.bigEndian : channel.littleEndian ) / maximumChannelValue } for component in data.enumerated() { switch UInt8(component.offset % numberOfChannels) { case alphaOffset: // Ignore alpha channels break // Breaks from the switch, not the loop case redOffset: rgbHolder.red = normalizeChannel(component.element) case greenOffset: rgbHolder.green = normalizeChannel(component.element) case blueOffset: rgbHolder.blue = normalizeChannel(component.element) case _: fatalError("Unhandled offset: \(component.offset)") } // After every 4th channel (one full pixel), write the RGBs to // the float buffer in the correct order. if component.offset % 4 == 3 { flushRGBs(rgbHolder, to: &bufferPointer, at: floatIndex) rgbHolder.red = nil; rgbHolder.green = nil; rgbHolder.blue = nil } } initializedCount = floatIndex } floatArray = [T](unsafeUninitializedCapacity: data.count / 4 * 3, initializingWith: initializer) case _: print("Unsupported format from image: \(normalizedImage)") return nil } return Data(copyingBufferOf: floatArray) } } // MARK: - Data extension Data { /// Creates a new buffer by copying the buffer pointer of the given array. /// /// - Warning: The given array's element type `T` must be trivial in that it can be copied bit /// for bit with no indirection or reference-counting operations; otherwise, reinterpreting /// data from the resulting buffer has undefined behavior. /// - Parameter array: An array with elements of type `T`. init<T>(copyingBufferOf array: [T]) { self = array.withUnsafeBufferPointer(Data.init) } /// Convert a Data instance to Array representation. func toArray<T>(type: T.Type) -> [T] where T: AdditiveArithmetic { var array = [T](repeating: T.zero, count: self.count/MemoryLayout<T>.stride) _ = array.withUnsafeMutableBytes { copyBytes(to: $0) } return array } } // MARK: - Constants private enum Constant { static let jpegCompressionQuality: CGFloat = 0.8 }
5129d10b6fd1f59ec1289514f9cd85f3
38.227848
184
0.646338
false
false
false
false
duliodenis/v
refs/heads/master
V/V/Views/ChatCell.swift
mit
1
// // ChatCell.swift // V // // Created by Dulio Denis on 5/15/16. // Copyright © 2016 Dulio Denis. All rights reserved. // import UIKit class ChatCell: UITableViewCell { let nameLabel = UILabel() let messageLabel = UILabel() let dateLabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // stylize the labels a bit nameLabel.font = UIFont(name: "AdventPro-Light", size: 18) messageLabel.textColor = UIColor(red: 149/255, green: 165/255, blue: 166/255, alpha: 1) dateLabel.textColor = UIColor(red: 149/255, green: 165/255, blue: 166/255, alpha: 1) // setup an array with our three label instances let labels = [nameLabel, messageLabel, dateLabel] // iterate through the label array for label in labels { // turn off translates autoresizing mask into contstraint label.translatesAutoresizingMaskIntoConstraints = false // and add to the content view contentView.addSubview(label) } // setup constraints in an array for activation let constraints: [NSLayoutConstraint] = [ // setup the name label to be constraint to the top anchor and leading anchor of the content view nameLabel.topAnchor.constraintEqualToAnchor(contentView.layoutMarginsGuide.topAnchor), nameLabel.leadingAnchor.constraintEqualToAnchor(contentView.layoutMarginsGuide.leadingAnchor), // constrain the message label to the bottom of the content view and the same leading anchor as the name label messageLabel.bottomAnchor.constraintEqualToAnchor(contentView.layoutMarginsGuide.bottomAnchor), messageLabel.leadingAnchor.constraintEqualToAnchor(nameLabel.leadingAnchor), // constrain the date label to the trailing anchor of the content view // and align to the first base line anchor of the name label dateLabel.trailingAnchor.constraintEqualToAnchor(contentView.layoutMarginsGuide.trailingAnchor), dateLabel.firstBaselineAnchor.constraintEqualToAnchor(nameLabel.firstBaselineAnchor) ] // activate the constraints with the constraint array NSLayoutConstraint.activateConstraints(constraints) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
9ed11afda4c88656d6e809ae44ae6f15
42.322034
122
0.678404
false
false
false
false
WangCrystal/actor-platform
refs/heads/master
actor-apps/app-ios/ActorApp/Controllers/Conversation/Cells/BubbleLayouts.swift
mit
11
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation struct CellSetting: Equatable { let showDate: Bool let clenchTop: Bool let clenchBottom: Bool init(showDate: Bool, clenchTop: Bool, clenchBottom: Bool) { self.showDate = showDate self.clenchTop = clenchTop self.clenchBottom = clenchBottom } } func ==(lhs: CellSetting, rhs: CellSetting) -> Bool { return lhs.showDate == rhs.showDate && lhs.clenchTop == rhs.clenchTop && lhs.clenchBottom == rhs.clenchBottom } class CellLayout { let key: String var height: CGFloat let date: String init(height: CGFloat, date: Int64, key: String) { self.date = CellLayout.formatDate(date) self.key = key self.height = height } class func formatDate(date: Int64) -> String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" return dateFormatter.stringFromDate(NSDate(timeIntervalSince1970: NSTimeInterval(Double(date) / 1000.0))) } }
f8ec9cbc3ceaa46e988a91ee63c41ea8
25.195122
113
0.645853
false
false
false
false
cameronklein/BigScreenVideos
refs/heads/master
BigScreenVideos/BigScreenVideos/NetworkController.swift
mit
1
// // NetworkController.swift // BigScreenVideos // // Created by Cameron Klein on 9/15/15. // Copyright © 2015 Cameron Klein. All rights reserved. // import UIKit enum SortStyle : String { case Hot = "hot" case New = "new" case Controversial = "controversial" } class NetworkController { static let baseURL = "https://reddit.com/r/" class func getVideosFromSubreddit(subreddit: String, sortedBy sortStyle: SortStyle, successHandler: (json: NSDictionary) -> (Void), failureHandler:(errorDescription: String) -> (Void)) { let urlString = baseURL + subreddit + "/" + sortStyle.rawValue + ".json" let url = NSURL(string: urlString) guard let requestURL = url else { failureHandler(errorDescription: "URL failed") return } let request = NSURLRequest(URL: requestURL) let dataTask = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in if let myError = error { failureHandler(errorDescription: myError.description) } guard let myResponse = response as? NSHTTPURLResponse else { failureHandler(errorDescription: "No response") return } switch myResponse.statusCode { case 200...299: guard let myData = data else { failureHandler(errorDescription: "Data error") return } if let json = try? NSJSONSerialization.JSONObjectWithData(myData, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary { dispatch_async(dispatch_get_main_queue()) { successHandler(json: json) } } default: failureHandler(errorDescription: "Something went wrong") } } dataTask.resume() } }
1c22eae12b520500d603d3517a60bea9
30.411765
188
0.537453
false
false
false
false
flypaper0/ethereum-wallet
refs/heads/release/1.1
ethereum-wallet/Classes/PresentationLayer/Popup/Module/PopupModule.swift
gpl-3.0
1
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import UIKit class PopupModule { class func create(app: Application, state: PopupState) -> PopupModuleInput { let router = PopupRouter() let presenter = PopupPresenter() let interactor = PopupInteractor() let viewController = R.storyboard.popup.popupViewController()! interactor.output = presenter viewController.output = presenter presenter.view = viewController presenter.router = router presenter.interactor = interactor router.app = app // MARK: Injection presenter.popupState = PopupStateFactory(state: state).create() interactor.postProcess = PopupPostProcessFactory(pushService: PushService(), biometryService: BiometryService()).create(state) return presenter } }
b78f4be3d751eb9d0786e92937c943ed
26.393939
102
0.670354
false
false
false
false
AshuMishra/MBPedometer
refs/heads/master
MBPedometer/Model Manager/PedometerManager.swift
mit
1
// // PedometerManager.swift // Pedometer // // Created by Ashutosh on 21/06/15. // Copyright (c) 2015 Ashutosh. All rights reserved. // import UIKit import CoreMotion enum DataSourceType { case DataSourceTypeHealthKit, DataSourceTypeCoreMotion } //Activity Structure to be passed public struct Activity { var startDate : NSDate var endDate : NSDate public var stepCount : NSNumber public var distanceCovered : NSNumber public var floorsAscended: NSNumber public var floorsDescended: NSNumber init(startDate : NSDate, endDate : NSDate){ self.startDate = startDate self.endDate = endDate self.stepCount = NSNumber() self.distanceCovered = NSNumber() self.floorsAscended = NSNumber() self.floorsDescended = NSNumber() } } public typealias CompletionBlock = (Activity?,NSError?) -> Void public typealias CompletionBlock_History = (stepsAraay: Array<Int>?, dateArray: Array<String>?, distanceArray: Array<Float>?, NSError?) -> Void public class PedometerManager: NSObject { var myActivityArray = [Activity]() let activityManager = CMMotionActivityManager() let pedoMeter = CMPedometer() var days:[String] = [] var stepsTaken:[Int] = [] var distanceTravelled:[Float] = [] static let sharedInstance = PedometerManager() //Check whether your application supports step counting or not public func checkStepCountingAvailability() -> Bool { return(CMPedometer.isStepCountingAvailable()) } //Check whether your application supports floor counting or not public func checkFloorCountingAvailability() -> Bool { return(CMPedometer.isFloorCountingAvailable()) } //Stop getting updates public func stopCountingUpdates() { self.pedoMeter.stopPedometerUpdates() } //Check whether your application supports activity tracking public func checkForMotionActivityAvailability() -> Bool { return (CMMotionActivityManager.isActivityAvailable()) } //Calculate Steps for specific intervels public func calculateStepsForInterval(#startDate:NSDate, endDate:NSDate,completionBlock:CompletionBlock) { var currentActivity = Activity(startDate: startDate, endDate: endDate) if(CMPedometer.isStepCountingAvailable()){ self.pedoMeter.queryPedometerDataFromDate(startDate, toDate: endDate) { (activity : CMPedometerData!, error) in println(activity) dispatch_async(dispatch_get_main_queue(), { () in if(error == nil) { currentActivity.stepCount = activity.numberOfSteps currentActivity.distanceCovered = activity.distance currentActivity.floorsAscended = activity.floorsAscended currentActivity.floorsDescended = activity.floorsDescended completionBlock(currentActivity, nil) } else { completionBlock(nil,error) } }) } } } //Count steps for live updates public func startStepCounterFromDate(date:NSDate, completionBlock:CompletionBlock) { var currentActivity = Activity(startDate: date,endDate: NSDate()) self.pedoMeter.startPedometerUpdatesFromDate(date, withHandler: { (data: CMPedometerData!, error) -> Void in if (error == nil) { currentActivity.startDate = data.startDate currentActivity.endDate = data.endDate currentActivity.stepCount = data.numberOfSteps currentActivity.distanceCovered = data.distance currentActivity.floorsAscended = data.floorsAscended currentActivity.floorsDescended = data.floorsDescended completionBlock(currentActivity, nil) } else { completionBlock(nil, error) } }) } //Get History of last 7 days func getHistory(completionBlock: CompletionBlock_History) { var serialQueue : dispatch_queue_t = dispatch_queue_create("com.example.MyQueue", nil) let formatter = NSDateFormatter() formatter.dateFormat = "d MMM" let today = NSDate() for day in 0...6{ let fromDate = NSDate(timeIntervalSinceNow: Double(-7+day) * 86400) let toDate = NSDate(timeIntervalSinceNow: Double(-7+day+1) * 86400) let dtStr = formatter.stringFromDate(toDate) self.pedoMeter.queryPedometerDataFromDate(fromDate, toDate: toDate) { (data : CMPedometerData!, error) in if(error == nil){ self.days.append(dtStr) self.stepsTaken.append(Int(data.numberOfSteps)) self.distanceTravelled.append(data.distance.floatValue) if(self.days.count == 7){ dispatch_async(dispatch_get_main_queue(), { () in completionBlock(stepsAraay: self.stepsTaken, dateArray: self.days, distanceArray: self.distanceTravelled, error) }) } } else { completionBlock(stepsAraay: nil, dateArray: nil, distanceArray: nil, error) } } } } }
03dc9184016c349252f7fc8087cf7dac
32.889655
143
0.690069
false
false
false
false
JGiola/swift
refs/heads/main
stdlib/public/core/Unicode.swift
apache-2.0
13
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims // Conversions between different Unicode encodings. Note that UTF-16 and // UTF-32 decoding are *not* currently resilient to erroneous data. /// The result of one Unicode decoding step. /// /// Each `UnicodeDecodingResult` instance can represent a Unicode scalar value, /// an indication that no more Unicode scalars are available, or an indication /// of a decoding error. @frozen public enum UnicodeDecodingResult: Equatable, Sendable { /// A decoded Unicode scalar value. case scalarValue(Unicode.Scalar) /// An indication that no more Unicode scalars are available in the input. case emptyInput /// An indication of a decoding error. case error @inlinable public static func == ( lhs: UnicodeDecodingResult, rhs: UnicodeDecodingResult ) -> Bool { switch (lhs, rhs) { case (.scalarValue(let lhsScalar), .scalarValue(let rhsScalar)): return lhsScalar == rhsScalar case (.emptyInput, .emptyInput): return true case (.error, .error): return true default: return false } } } /// A Unicode encoding form that translates between Unicode scalar values and /// form-specific code units. /// /// The `UnicodeCodec` protocol declares methods that decode code unit /// sequences into Unicode scalar values and encode Unicode scalar values /// into code unit sequences. The standard library implements codecs for the /// UTF-8, UTF-16, and UTF-32 encoding schemes as the `UTF8`, `UTF16`, and /// `UTF32` types, respectively. Use the `Unicode.Scalar` type to work with /// decoded Unicode scalar values. public protocol UnicodeCodec: Unicode.Encoding { /// Creates an instance of the codec. init() /// Starts or continues decoding a code unit sequence into Unicode scalar /// values. /// /// To decode a code unit sequence completely, call this method repeatedly /// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the /// iterator was exhausted is not sufficient, because the decoder can store /// buffered data from the input iterator. /// /// Because of buffering, it is impossible to find the corresponding position /// in the iterator for a given returned `Unicode.Scalar` or an error. /// /// The following example decodes the UTF-8 encoded bytes of a string into an /// array of `Unicode.Scalar` instances: /// /// let str = "✨Unicode✨" /// print(Array(str.utf8)) /// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]" /// /// var bytesIterator = str.utf8.makeIterator() /// var scalars: [Unicode.Scalar] = [] /// var utf8Decoder = UTF8() /// Decode: while true { /// switch utf8Decoder.decode(&bytesIterator) { /// case .scalarValue(let v): scalars.append(v) /// case .emptyInput: break Decode /// case .error: /// print("Decoding error") /// break Decode /// } /// } /// print(scalars) /// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]" /// /// - Parameter input: An iterator of code units to be decoded. `input` must be /// the same iterator instance in repeated calls to this method. Do not /// advance the iterator or any copies of the iterator outside this /// method. /// - Returns: A `UnicodeDecodingResult` instance, representing the next /// Unicode scalar, an indication of an error, or an indication that the /// UTF sequence has been fully decoded. mutating func decode<I: IteratorProtocol>( _ input: inout I ) -> UnicodeDecodingResult where I.Element == CodeUnit /// Encodes a Unicode scalar as a series of code units by calling the given /// closure on each code unit. /// /// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar /// value (`\u{1D110}`) but requires four code units for its UTF-8 /// representation. The following code uses the `UTF8` codec to encode a /// fermata in UTF-8: /// /// var bytes: [UTF8.CodeUnit] = [] /// UTF8.encode("𝄐", into: { bytes.append($0) }) /// print(bytes) /// // Prints "[240, 157, 132, 144]" /// /// - Parameters: /// - input: The Unicode scalar value to encode. /// - processCodeUnit: A closure that processes one code unit argument at a /// time. static func encode( _ input: Unicode.Scalar, into processCodeUnit: (CodeUnit) -> Void ) /// Searches for the first occurrence of a `CodeUnit` that is equal to 0. /// /// Is an equivalent of `strlen` for C-strings. /// /// - Complexity: O(*n*) static func _nullCodeUnitOffset(in input: UnsafePointer<CodeUnit>) -> Int } /// A codec for translating between Unicode scalar values and UTF-8 code /// units. extension Unicode.UTF8: UnicodeCodec { /// Creates an instance of the UTF-8 codec. @inlinable public init() { self = ._swift3Buffer(ForwardParser()) } /// Starts or continues decoding a UTF-8 sequence. /// /// To decode a code unit sequence completely, call this method repeatedly /// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the /// iterator was exhausted is not sufficient, because the decoder can store /// buffered data from the input iterator. /// /// Because of buffering, it is impossible to find the corresponding position /// in the iterator for a given returned `Unicode.Scalar` or an error. /// /// The following example decodes the UTF-8 encoded bytes of a string into an /// array of `Unicode.Scalar` instances. This is a demonstration only---if /// you need the Unicode scalar representation of a string, use its /// `unicodeScalars` view. /// /// let str = "✨Unicode✨" /// print(Array(str.utf8)) /// // Prints "[226, 156, 168, 85, 110, 105, 99, 111, 100, 101, 226, 156, 168]" /// /// var bytesIterator = str.utf8.makeIterator() /// var scalars: [Unicode.Scalar] = [] /// var utf8Decoder = UTF8() /// Decode: while true { /// switch utf8Decoder.decode(&bytesIterator) { /// case .scalarValue(let v): scalars.append(v) /// case .emptyInput: break Decode /// case .error: /// print("Decoding error") /// break Decode /// } /// } /// print(scalars) /// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]" /// /// - Parameter input: An iterator of code units to be decoded. `input` must be /// the same iterator instance in repeated calls to this method. Do not /// advance the iterator or any copies of the iterator outside this /// method. /// - Returns: A `UnicodeDecodingResult` instance, representing the next /// Unicode scalar, an indication of an error, or an indication that the /// UTF sequence has been fully decoded. @inlinable @inline(__always) public mutating func decode<I: IteratorProtocol>( _ input: inout I ) -> UnicodeDecodingResult where I.Element == CodeUnit { guard case ._swift3Buffer(var parser) = self else { Builtin.unreachable() } defer { self = ._swift3Buffer(parser) } switch parser.parseScalar(from: &input) { case .valid(let s): return .scalarValue(UTF8.decode(s)) case .error: return .error case .emptyInput: return .emptyInput } } /// Attempts to decode a single UTF-8 code unit sequence starting at the LSB /// of `buffer`. /// /// - Returns: /// - result: The decoded code point if the code unit sequence is /// well-formed; `nil` otherwise. /// - length: The length of the code unit sequence in bytes if it is /// well-formed; otherwise the *maximal subpart of the ill-formed /// sequence* (Unicode 8.0.0, Ch 3.9, D93b), i.e. the number of leading /// code units that were valid or 1 in case none were valid. Unicode /// recommends to skip these bytes and replace them by a single /// replacement character (U+FFFD). /// /// - Requires: There is at least one used byte in `buffer`, and the unused /// space in `buffer` is filled with some value not matching the UTF-8 /// continuation byte form (`0b10xxxxxx`). @inlinable public // @testable static func _decodeOne(_ buffer: UInt32) -> (result: UInt32?, length: UInt8) { // Note the buffer is read least significant byte first: [ #3 #2 #1 #0 ]. if buffer & 0x80 == 0 { // 1-byte sequence (ASCII), buffer: [ ... ... ... CU0 ]. let value = buffer & 0xff return (value, 1) } var p = ForwardParser() p._buffer._storage = buffer p._buffer._bitCount = 32 var i = EmptyCollection<UInt8>().makeIterator() switch p.parseScalar(from: &i) { case .valid(let s): return ( result: UTF8.decode(s).value, length: UInt8(truncatingIfNeeded: s.count)) case .error(let l): return (result: nil, length: UInt8(truncatingIfNeeded: l)) case .emptyInput: Builtin.unreachable() } } /// Encodes a Unicode scalar as a series of code units by calling the given /// closure on each code unit. /// /// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar /// value (`\u{1D110}`) but requires four code units for its UTF-8 /// representation. The following code encodes a fermata in UTF-8: /// /// var bytes: [UTF8.CodeUnit] = [] /// UTF8.encode("𝄐", into: { bytes.append($0) }) /// print(bytes) /// // Prints "[240, 157, 132, 144]" /// /// - Parameters: /// - input: The Unicode scalar value to encode. /// - processCodeUnit: A closure that processes one code unit argument at a /// time. @inlinable @inline(__always) public static func encode( _ input: Unicode.Scalar, into processCodeUnit: (CodeUnit) -> Void ) { var s = encode(input)!._biasedBits processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01) s &>>= 8 if _fastPath(s == 0) { return } processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01) s &>>= 8 if _fastPath(s == 0) { return } processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01) s &>>= 8 if _fastPath(s == 0) { return } processCodeUnit(UInt8(truncatingIfNeeded: s) &- 0x01) } /// Returns a Boolean value indicating whether the specified code unit is a /// UTF-8 continuation byte. /// /// Continuation bytes take the form `0b10xxxxxx`. For example, a lowercase /// "e" with an acute accent above it (`"é"`) uses 2 bytes for its UTF-8 /// representation: `0b11000011` (195) and `0b10101001` (169). The second /// byte is a continuation byte. /// /// let eAcute = "é" /// for codeUnit in eAcute.utf8 { /// print(codeUnit, UTF8.isContinuation(codeUnit)) /// } /// // Prints "195 false" /// // Prints "169 true" /// /// - Parameter byte: A UTF-8 code unit. /// - Returns: `true` if `byte` is a continuation byte; otherwise, `false`. @inlinable public static func isContinuation(_ byte: CodeUnit) -> Bool { return byte & 0b11_00__0000 == 0b10_00__0000 } @inlinable public static func _nullCodeUnitOffset( in input: UnsafePointer<CodeUnit> ) -> Int { return Int(_swift_stdlib_strlen_unsigned(input)) } // Support parsing C strings as-if they are UTF8 strings. @inlinable public static func _nullCodeUnitOffset( in input: UnsafePointer<CChar> ) -> Int { return Int(_swift_stdlib_strlen(input)) } } /// A codec for translating between Unicode scalar values and UTF-16 code /// units. extension Unicode.UTF16: UnicodeCodec { /// Creates an instance of the UTF-16 codec. @inlinable public init() { self = ._swift3Buffer(ForwardParser()) } /// Starts or continues decoding a UTF-16 sequence. /// /// To decode a code unit sequence completely, call this method repeatedly /// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the /// iterator was exhausted is not sufficient, because the decoder can store /// buffered data from the input iterator. /// /// Because of buffering, it is impossible to find the corresponding position /// in the iterator for a given returned `Unicode.Scalar` or an error. /// /// The following example decodes the UTF-16 encoded bytes of a string into an /// array of `Unicode.Scalar` instances. This is a demonstration only---if /// you need the Unicode scalar representation of a string, use its /// `unicodeScalars` view. /// /// let str = "✨Unicode✨" /// print(Array(str.utf16)) /// // Prints "[10024, 85, 110, 105, 99, 111, 100, 101, 10024]" /// /// var codeUnitIterator = str.utf16.makeIterator() /// var scalars: [Unicode.Scalar] = [] /// var utf16Decoder = UTF16() /// Decode: while true { /// switch utf16Decoder.decode(&codeUnitIterator) { /// case .scalarValue(let v): scalars.append(v) /// case .emptyInput: break Decode /// case .error: /// print("Decoding error") /// break Decode /// } /// } /// print(scalars) /// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]" /// /// - Parameter input: An iterator of code units to be decoded. `input` must be /// the same iterator instance in repeated calls to this method. Do not /// advance the iterator or any copies of the iterator outside this /// method. /// - Returns: A `UnicodeDecodingResult` instance, representing the next /// Unicode scalar, an indication of an error, or an indication that the /// UTF sequence has been fully decoded. @inlinable public mutating func decode<I: IteratorProtocol>( _ input: inout I ) -> UnicodeDecodingResult where I.Element == CodeUnit { guard case ._swift3Buffer(var parser) = self else { Builtin.unreachable() } defer { self = ._swift3Buffer(parser) } switch parser.parseScalar(from: &input) { case .valid(let s): return .scalarValue(UTF16.decode(s)) case .error: return .error case .emptyInput: return .emptyInput } } /// Try to decode one Unicode scalar, and return the actual number of code /// units it spanned in the input. This function may consume more code /// units than required for this scalar. @inlinable internal mutating func _decodeOne<I: IteratorProtocol>( _ input: inout I ) -> (UnicodeDecodingResult, Int) where I.Element == CodeUnit { let result = decode(&input) switch result { case .scalarValue(let us): return (result, UTF16.width(us)) case .emptyInput: return (result, 0) case .error: return (result, 1) } } /// Encodes a Unicode scalar as a series of code units by calling the given /// closure on each code unit. /// /// For example, the musical fermata symbol ("𝄐") is a single Unicode scalar /// value (`\u{1D110}`) but requires two code units for its UTF-16 /// representation. The following code encodes a fermata in UTF-16: /// /// var codeUnits: [UTF16.CodeUnit] = [] /// UTF16.encode("𝄐", into: { codeUnits.append($0) }) /// print(codeUnits) /// // Prints "[55348, 56592]" /// /// - Parameters: /// - input: The Unicode scalar value to encode. /// - processCodeUnit: A closure that processes one code unit argument at a /// time. @inlinable public static func encode( _ input: Unicode.Scalar, into processCodeUnit: (CodeUnit) -> Void ) { var s = encode(input)!._storage processCodeUnit(UInt16(truncatingIfNeeded: s)) s &>>= 16 if _fastPath(s == 0) { return } processCodeUnit(UInt16(truncatingIfNeeded: s)) } } /// A codec for translating between Unicode scalar values and UTF-32 code /// units. extension Unicode.UTF32: UnicodeCodec { /// Creates an instance of the UTF-32 codec. @inlinable public init() { self = ._swift3Codec } /// Starts or continues decoding a UTF-32 sequence. /// /// To decode a code unit sequence completely, call this method repeatedly /// until it returns `UnicodeDecodingResult.emptyInput`. Checking that the /// iterator was exhausted is not sufficient, because the decoder can store /// buffered data from the input iterator. /// /// Because of buffering, it is impossible to find the corresponding position /// in the iterator for a given returned `Unicode.Scalar` or an error. /// /// The following example decodes the UTF-16 encoded bytes of a string /// into an array of `Unicode.Scalar` instances. This is a demonstration /// only---if you need the Unicode scalar representation of a string, use /// its `unicodeScalars` view. /// /// // UTF-32 representation of "✨Unicode✨" /// let codeUnits: [UTF32.CodeUnit] = /// [10024, 85, 110, 105, 99, 111, 100, 101, 10024] /// /// var codeUnitIterator = codeUnits.makeIterator() /// var scalars: [Unicode.Scalar] = [] /// var utf32Decoder = UTF32() /// Decode: while true { /// switch utf32Decoder.decode(&codeUnitIterator) { /// case .scalarValue(let v): scalars.append(v) /// case .emptyInput: break Decode /// case .error: /// print("Decoding error") /// break Decode /// } /// } /// print(scalars) /// // Prints "["\u{2728}", "U", "n", "i", "c", "o", "d", "e", "\u{2728}"]" /// /// - Parameter input: An iterator of code units to be decoded. `input` must be /// the same iterator instance in repeated calls to this method. Do not /// advance the iterator or any copies of the iterator outside this /// method. /// - Returns: A `UnicodeDecodingResult` instance, representing the next /// Unicode scalar, an indication of an error, or an indication that the /// UTF sequence has been fully decoded. @inlinable public mutating func decode<I: IteratorProtocol>( _ input: inout I ) -> UnicodeDecodingResult where I.Element == CodeUnit { var parser = ForwardParser() switch parser.parseScalar(from: &input) { case .valid(let s): return .scalarValue(UTF32.decode(s)) case .error: return .error case .emptyInput: return .emptyInput } } /// Encodes a Unicode scalar as a UTF-32 code unit by calling the given /// closure. /// /// For example, like every Unicode scalar, the musical fermata symbol ("𝄐") /// can be represented in UTF-32 as a single code unit. The following code /// encodes a fermata in UTF-32: /// /// var codeUnit: UTF32.CodeUnit = 0 /// UTF32.encode("𝄐", into: { codeUnit = $0 }) /// print(codeUnit) /// // Prints "119056" /// /// - Parameters: /// - input: The Unicode scalar value to encode. /// - processCodeUnit: A closure that processes one code unit argument at a /// time. @inlinable public static func encode( _ input: Unicode.Scalar, into processCodeUnit: (CodeUnit) -> Void ) { processCodeUnit(UInt32(input)) } } /// Translates the given input from one Unicode encoding to another by calling /// the given closure. /// /// The following example transcodes the UTF-8 representation of the string /// `"Fermata 𝄐"` into UTF-32. /// /// let fermata = "Fermata 𝄐" /// let bytes = fermata.utf8 /// print(Array(bytes)) /// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 240, 157, 132, 144]" /// /// var codeUnits: [UTF32.CodeUnit] = [] /// let sink = { codeUnits.append($0) } /// transcode(bytes.makeIterator(), from: UTF8.self, to: UTF32.self, /// stoppingOnError: false, into: sink) /// print(codeUnits) /// // Prints "[70, 101, 114, 109, 97, 116, 97, 32, 119056]" /// /// The `sink` closure is called with each resulting UTF-32 code unit as the /// function iterates over its input. /// /// - Parameters: /// - input: An iterator of code units to be translated, encoded as /// `inputEncoding`. If `stopOnError` is `false`, the entire iterator will /// be exhausted. Otherwise, iteration will stop if an encoding error is /// detected. /// - inputEncoding: The Unicode encoding of `input`. /// - outputEncoding: The destination Unicode encoding. /// - stopOnError: Pass `true` to stop translation when an encoding error is /// detected in `input`. Otherwise, a Unicode replacement character /// (`"\u{FFFD}"`) is inserted for each detected error. /// - processCodeUnit: A closure that processes one `outputEncoding` code /// unit at a time. /// - Returns: `true` if the translation detected encoding errors in `input`; /// otherwise, `false`. @inlinable @inline(__always) public func transcode< Input: IteratorProtocol, InputEncoding: Unicode.Encoding, OutputEncoding: Unicode.Encoding >( _ input: Input, from inputEncoding: InputEncoding.Type, to outputEncoding: OutputEncoding.Type, stoppingOnError stopOnError: Bool, into processCodeUnit: (OutputEncoding.CodeUnit) -> Void ) -> Bool where InputEncoding.CodeUnit == Input.Element { var input = input // NB. It is not possible to optimize this routine to a memcpy if // InputEncoding == OutputEncoding. The reason is that memcpy will not // substitute U+FFFD replacement characters for ill-formed sequences. var p = InputEncoding.ForwardParser() var hadError = false loop: while true { switch p.parseScalar(from: &input) { case .valid(let s): let t = OutputEncoding.transcode(s, from: inputEncoding) guard _fastPath(t != nil), let s = t else { break } s.forEach(processCodeUnit) continue loop case .emptyInput: return hadError case .error: if _slowPath(stopOnError) { return true } hadError = true } OutputEncoding.encodedReplacementCharacter.forEach(processCodeUnit) } } /// Instances of conforming types are used in internal `String` /// representation. public // @testable protocol _StringElement { static func _toUTF16CodeUnit(_: Self) -> UTF16.CodeUnit static func _fromUTF16CodeUnit(_ utf16: UTF16.CodeUnit) -> Self } extension UTF16.CodeUnit: _StringElement { @inlinable public // @testable static func _toUTF16CodeUnit(_ x: UTF16.CodeUnit) -> UTF16.CodeUnit { return x } @inlinable public // @testable static func _fromUTF16CodeUnit( _ utf16: UTF16.CodeUnit ) -> UTF16.CodeUnit { return utf16 } } extension UTF8.CodeUnit: _StringElement { @inlinable public // @testable static func _toUTF16CodeUnit(_ x: UTF8.CodeUnit) -> UTF16.CodeUnit { _internalInvariant(x <= 0x7f, "should only be doing this with ASCII") return UTF16.CodeUnit(truncatingIfNeeded: x) } @inlinable public // @testable static func _fromUTF16CodeUnit( _ utf16: UTF16.CodeUnit ) -> UTF8.CodeUnit { _internalInvariant(utf16 <= 0x7f, "should only be doing this with ASCII") return UTF8.CodeUnit(truncatingIfNeeded: utf16) } } // Unchecked init to avoid precondition branches in hot code paths where we // already know the value is a valid unicode scalar. extension Unicode.Scalar { /// Create an instance with numeric value `value`, bypassing the regular /// precondition checks for code point validity. @inlinable internal init(_unchecked value: UInt32) { _internalInvariant(value < 0xD800 || value > 0xDFFF, "high- and low-surrogate code points are not valid Unicode scalar values") _internalInvariant(value <= 0x10FFFF, "value is outside of Unicode codespace") self._value = value } } extension UnicodeCodec { @inlinable public static func _nullCodeUnitOffset( in input: UnsafePointer<CodeUnit> ) -> Int { var length = 0 while input[length] != 0 { length += 1 } return length } } @available(*, unavailable, message: "use 'transcode(_:from:to:stoppingOnError:into:)'") public func transcode<Input, InputEncoding, OutputEncoding>( _ inputEncoding: InputEncoding.Type, _ outputEncoding: OutputEncoding.Type, _ input: Input, _ output: (OutputEncoding.CodeUnit) -> Void, stopOnError: Bool ) -> Bool where Input: IteratorProtocol, InputEncoding: UnicodeCodec, OutputEncoding: UnicodeCodec, InputEncoding.CodeUnit == Input.Element { Builtin.unreachable() } /// A namespace for Unicode utilities. @frozen public enum Unicode {}
a3dd9e6c302a73864360fb7b63c79c07
35.75
87
0.645051
false
false
false
false
motoom/ios-apps
refs/heads/master
Pour3/Pour/SettingsController.swift
mit
1
import UIKit class SettingsController: UIViewController { var vesselCount = 3 var difficulty = 5 @IBOutlet weak var vesselSlider: UISlider! @IBOutlet weak var difficultySlider: UISlider! @IBAction func adjustVessels(_ sender: UISlider) { let roundedValue = round(sender.value) sender.value = roundedValue vesselCount = Int(sender.value) } @IBAction func adjustDifficulty(_ sender: UISlider) { let roundedValue = round(sender.value) sender.value = roundedValue difficulty = Int(sender.value) } override func viewDidLoad() { super.viewDidLoad() vesselSlider.value = Float(vesselCount) difficultySlider.value = Float(difficulty) } }
d185e85f60004a004e5a5f7f9a09ac3a
23
57
0.64974
false
false
false
false
kylef/Starship
refs/heads/master
Starship/ViewModels/ResourceViewModel.swift
bsd-2-clause
1
// // ResourceViewModel.swift // Starship // // Created by Kyle Fuller on 01/07/2015. // Copyright (c) 2015 Kyle Fuller. All rights reserved. // import Foundation import Representor import Hyperdrive enum ResourceViewModelResult { case Success(ResourceViewModel) case Refresh case Failure(NSError) } class ResourceViewModel { // MARK: RepresentorViewModel let hyperdrive:Hyperdrive private(set) var representor:Representor<HTTPTransition> init(hyperdrive:Hyperdrive, representor:Representor<HTTPTransition>) { self.hyperdrive = hyperdrive self.representor = representor } var canReload:Bool { return self.representor.transitions["self"] != nil } func reload(completion:((RepresentorResult) -> ())) { if let uri = self.representor.transitions["self"] { hyperdrive.request(uri) { result in switch result { case .Success(let representor): self.representor = representor case .Failure: break } completion(result) } } } // MARK: Private private var attributes:[(key:String, value:AnyObject)] { return representor.attributes.map { (key, value) in return (key: key, value: value) } } private var embeddedResources:[(relation:String, representor:Representor<HTTPTransition>)] { return representor.representors.reduce([]) { (accumulator, resources) in let name = resources.0 return accumulator + resources.1.map { representor in return (relation: name, representor: representor) } } } private var transitions:[(relation:String, transition:HTTPTransition)] { return representor.transitions .filter { (relation, transition) in relation != "self" } .map { (relation, transition) in (relation: relation, transition: transition) } } // MARK: Other var title:String? { return titlify(representor) } private func titlify(representor:Representor<HTTPTransition>) -> String? { for key in ["title", "name", "question", "choice"] { if let value = representor.attributes[key] as? String { return value } } return nil } // MARK: Attributes var numberOfAttributes:Int { return representor.attributes.count } func titleForAttribute(index:Int) -> String { return attributes[index].key } func valueForAttribute(index:Int) -> String { return "\(attributes[index].value)" } // MARK: Embedded Resources var numberOfEmbeddedResources:Int { return embeddedResources.count } func titleForEmbeddedResource(index:Int) -> String? { return titlify(embeddedResources[index].representor) } func relationForEmbeddedResource(index:Int) -> String { return embeddedResources[index].relation } func viewModelForEmbeddedResource(index:Int) -> ResourceViewModel { let representor = embeddedResources[index].representor return ResourceViewModel(hyperdrive: hyperdrive, representor: representor) } // MARK: Transitions var numberOfTransitions:Int { return transitions.count } func titleForTransition(index:Int) -> String { return transitions[index].relation } func viewModelForTransition(index:Int) -> TransitionViewModel? { let transition = transitions[index].transition if (transition.parameters.count + transition.attributes.count) > 0 { return TransitionViewModel(hyperdrive: hyperdrive, transition: transition) } return nil } func performTransition(index:Int, completion:(ResourceViewModelResult -> ())) { hyperdrive.request(transitions[index].transition) { result in switch result { case .Success(let representor): if let oldSelf = self.representor.transitions["self"], newSelf = representor.transitions["self"] { if oldSelf.uri == newSelf.uri { self.representor = representor completion(.Refresh) return } } completion(.Success(ResourceViewModel(hyperdrive: self.hyperdrive, representor: representor))) case .Failure(let error): completion(.Failure(error)) } } } }
bb1883867a14f9b1df915f2d6bf4a018
24.689441
106
0.681818
false
false
false
false
LDlalala/LDZBLiving
refs/heads/master
LDZBLiving/LDZBLiving/Classes/Live/GiftView/LDGiftListView.swift
mit
1
// // LDGiftListView.swift // LDZBLiving // // Created by 李丹 on 17/8/19. // Copyright © 2017年 LD. All rights reserved. // import UIKit private let cellID = "LDGiftViewCell" class LDGiftListView: UIView , NibLoadable{ // MARK: 控件属性 @IBOutlet weak var giftView: UIView! @IBOutlet weak var sendGiftBtn: UIButton! var giftVM : LDGiftViewModel = LDGiftViewModel() var pageCollectionView : LDPageCollectionView! } // MARK:- 初始化子控件 extension LDGiftListView{ override func awakeFromNib() { super.awakeFromNib() // 初始化子控件 setupUI() // 加载礼物数据 loadGiftDatas() } private func setupUI(){ let frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height) let layout = LDPageCollectionViewLayout() layout.cols = 4 layout.row = 2 layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 let style = LDPageStyle() let pageCollectionView = LDPageCollectionView(frame: frame, titles: ["热门", "高级", "豪华", "专属"], isTitleInTop: false, layout: layout, style: style) pageCollectionView.dataSource = self pageCollectionView.delegate = self addSubview(pageCollectionView) // 注册cell pageCollectionView.register(nib: UINib(nibName: "LDGiftViewCell", bundle: nil), identifier: cellID) } private func loadGiftDatas(){ giftVM.loadGiftDatas { self.pageCollectionView.reloadData() } } } // MARK:- 送礼物 extension LDGiftListView { @IBAction func sendGiftBtnClick() { } } // MARK:- 实现代理方法 extension LDGiftListView : LDPageCollectionViewDelegate{ func collectionView(_ pageCollectionView: LDPageCollectionView, _ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let giftModel = giftVM.giftlistDatas[indexPath.section].list[indexPath.item] print(giftModel) } } // MARK:- 实现数据源方法 extension LDGiftListView : LDPageCollectionViewDataSource{ func numberOfSections(in pageCollectionView: LDPageCollectionView) -> Int { return giftVM.giftlistDatas.count } func collectionView(_ pageCollectionView: LDPageCollectionView, numberOfItemsInSection section: Int) -> Int { return giftVM.giftlistDatas[section].list.count } func collectionView(_ pageCollectionView: LDPageCollectionView, _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! LDGiftViewCell cell.giftModel = giftVM.giftlistDatas[indexPath.section].list[indexPath.item] return cell } }
1e858d5fe542ca28509d3f7810d72973
26.90099
165
0.666785
false
false
false
false
madapper/HTMLDOMKit
refs/heads/master
Sources/HTMLDOMKit.swift
mit
1
import Foundation public protocol DOMConvertible { func toHTML() -> String } public extension DOMConvertible { var DOMKeyTag:String { return "tag" } var DOMKeyAttributes:String { return "attributes" } var DOMKeyChildren:String { return "children" } var DOMKeyContent:String { return "content" } } public struct DOMElement { public var tag:String = "" public var attributes:[DOMAttribute] = [] public var content:String = "" public var children:[DOMElement] = [] public init() { } public init?<K:Hashable, V>(dictionary:Dictionary<K, V>) { if let tag = dictionary.valueForKey(DOMKeyTag) as? String { self.tag = tag } if let content = dictionary.valueForKey(DOMKeyContent) as? String where tag.isEmpty { self.content = content } guard !tag.isEmpty || !content.isEmpty else { return } if let att = dictionary.valueForKey(DOMKeyAttributes) as? [String:AnyObject] { let attr = att.attributesFromDictionary() attributes = attr } if let children = dictionary.valueForKey(DOMKeyChildren) as? [AnyObject] { for child in children { if let object = child as? Dictionary<K, V>, let item = DOMElement(dictionary:object) { self.children.append(item) } } } } } public struct DOMAttribute { public let key:String public let value:AnyObject public init(key:String, value:AnyObject) { self.key = key self.value = value } } extension DOMAttribute: DOMConvertible{ public func toHTML() -> String { let dict = [key:value] return dict.attributeStringFromDictionary() } } extension Dictionary { public func valueForKey(key:String) -> AnyObject? { let values = Array(self.values) for (index, k) in self.keys.enumerate() { if let k = k as? String, let value = values[index] as? AnyObject where k == key { return value } } return nil } } extension DOMElement: DOMConvertible{ public func toHTML() -> String { if !tag.isEmpty { var startTag = "<\(tag)" let endTag = "</\(tag)>" var dict:[String:AnyObject] = [:] for attribute in attributes { dict.updateValue(attribute.value, forKey: attribute.key) } startTag += dict.attributeStringFromDictionary() startTag += ">" for child in children { startTag += child.toHTML() } return startTag + endTag } return content } } extension Dictionary: DOMConvertible{ public func toHTML() -> String { if let tagName = self.valueForKey(DOMKeyTag) { var startTag = "<\(tagName)" let endTag = "</\(tagName)>" if let att = self.valueForKey(DOMKeyAttributes) as? [String:AnyObject] { let attr = att.attributeStringFromDictionary() startTag += attr } startTag += ">" if let children = self.valueForKey(DOMKeyChildren) as? [AnyObject] { for child in children { if let object = child as? Dictionary { let item = object.toHTML() startTag += item } } } return startTag + endTag } if let content = self.valueForKey(DOMKeyContent) as? String { return content } return "" } func attributesFromDictionary() -> [DOMAttribute] { var attributes:[DOMAttribute] = [] for (key, value) in self { guard let key = key as? String, let value = value as? AnyObject else { break } switch value { case is String, is Int8, is Int16, is Int32, is Int64, is Float, is Double: let attribute = DOMAttribute(key: key, value: value) attributes.append(attribute) default: break } } return attributes } func attributeStringFromDictionary() -> String { var att = "" for (key, value) in self { switch value { case is String: att += " \(key)=\"\(value)\" " case is Int8, is Int16, is Int32, is Int64, is Float, is Double: att += " \(key)=\(value) " default: break } } return att } }
c0115345eac251b934a89781d5eb5026
24.857143
102
0.476944
false
false
false
false
coreyjv/Emby.ApiClient.Swift
refs/heads/master
Emby.ApiClient/apiinteraction/connect/ConnectService.swift
mit
1
// // ConnectService.swift // Emby.ApiClient // // Created by Vedran Ozir on 07/10/15. // Copyright © 2015 Vedran Ozir. All rights reserved. // import Foundation enum Error:ErrorType { case IllegalArgumentException(String) case LowBridge } public class ConnectService { public let JsonSerializer: IJsonSerializer let logger: ILogger let httpClient: IAsyncHttpClient private let appName: String private let appVersion: String public init(jsonSerializer: IJsonSerializer, logger: ILogger, httpClient: IAsyncHttpClient, appName: String, appVersion: String) { self.JsonSerializer = jsonSerializer self.logger = logger self.httpClient = httpClient self.appName = appName self.appVersion = appVersion } public func Authenticate(username: String, password: String, success: (ConnectAuthenticationResult) -> Void, failure: (EmbyError) -> Void) { // UnsupportedEncodingException, NoSuchAlgorithmException { let args = QueryStringDictionary() args.Add("nameOrEmail", value: username) args.Add("password", value: ConnectPassword.PerformPreHashFilter(password).md5()) let url = GetConnectUrl("user/authenticate") let request = HttpRequest(url: url, method: .POST, postData: args) AddXApplicationName(request) httpClient.sendRequest(request, success: success, failure: failure) } public func CreatePin(deviceId: String, success: (PinCreationResult) -> Void, failure: (EmbyError) -> Void) { let args = QueryStringDictionary() args.Add("deviceId", value: deviceId) let url = GetConnectUrl("pin") + "?" + args.GetQueryString() let request = HttpRequest(url: url, method: .POST, postData: args) AddXApplicationName(request) httpClient.sendRequest(request, success: success, failure: failure) } public func GetPinStatus(pin: PinCreationResult, success: (PinStatusResult) -> Void, failure: (EmbyError) -> Void) { let dict = QueryStringDictionary() dict.Add("deviceId", value: pin.deviceId) dict.Add("pin", value: pin.pin) let url = GetConnectUrl("pin") + "?" + dict.GetQueryString() let request = HttpRequest(url: url, method: .GET) AddXApplicationName(request) httpClient.sendRequest(request, success: success, failure: failure) } public func ExchangePin(pin: PinCreationResult, success: (PinExchangeResult) -> Void, failure: (EmbyError) -> Void) { let args = QueryStringDictionary() args.Add("deviceId", value: pin.deviceId) args.Add("pin", value: pin.pin) let url = GetConnectUrl("pin/authenticate") let request = HttpRequest(url: url, method: .POST, postData: args) AddXApplicationName(request) httpClient.sendRequest(request, success: success, failure: failure) } public func GetConnectUser(query: ConnectUserQuery, connectAccessToken: String?, success: (ConnectUser) -> Void, failure: (EmbyError) -> Void) throws { let dict = QueryStringDictionary() if let id = query.id { dict.Add("id", value: id) } else if let name = query.name { dict.Add("name", value: name) } else if let email = query.email { dict.Add("email", value: email) } else if let nameOrEmail = query.nameOrEmail { dict.Add("nameOrEmail", value: nameOrEmail) } else { throw Error.IllegalArgumentException("Empty ConnectUserQuery") } let url = GetConnectUrl("user") + "?" + dict.GetQueryString() let request = HttpRequest(url: url, method: .GET) try AddUserAccessToken(request, accessToken: connectAccessToken) AddXApplicationName(request) httpClient.sendRequest(request, success: success, failure: failure) } public func GetServers(userId: String, connectAccessToken: String, success: ([ConnectUserServer]) -> Void, failure: (EmbyError) -> Void) throws { let dict = QueryStringDictionary() dict.Add("userId", value: userId) let url = GetConnectUrl("servers") + "?" + dict.GetQueryString() let request = HttpRequest(url: url, method: .GET) try AddUserAccessToken(request, accessToken: connectAccessToken) AddXApplicationName(request) httpClient.sendCollectionRequest(request, success: success, failure: failure) } public func Logout(connectAccessToken: String, success: (EmptyResponse) -> Void, failure: (EmbyError) -> Void) throws { let url = GetConnectUrl("user/logout") let request = HttpRequest(url: url, method: .POST) try AddUserAccessToken(request, accessToken: connectAccessToken) AddXApplicationName(request) httpClient.sendRequest(request, success: success, failure: failure) } private func GetConnectUrl(handler: String) -> String { return Configuration.mediaBrowserTV_APIServer + handler } private func AddUserAccessToken(request: HttpRequest, accessToken: String?) throws { if let accessToken = accessToken { request.headers["X-Connect-UserToken"] = accessToken } else { throw Error.IllegalArgumentException("accessToken") } } private func AddXApplicationName(request: HttpRequest) { request.headers["X-Application"] = appName + "/" + appVersion } public func GetRegistrationInfo(userId: String, feature: String, connectAccessToken: String, success: (RegistrationInfo) -> Void, failure: (EmbyError) -> Void) throws { let dict = QueryStringDictionary() dict.Add("userId", value: userId) dict.Add("feature", value: feature) let url = GetConnectUrl("registrationInfo") + "?" + dict.GetQueryString() let request = HttpRequest(url: url, method: .GET) try AddUserAccessToken(request, accessToken: connectAccessToken) AddXApplicationName(request) httpClient.sendRequest(request, success: success, failure: failure) } }
1fdfcc09598fb10e414bf79f0dff574c
32.482234
170
0.618499
false
false
false
false
SummertimSadness/YANetworkLoadView
refs/heads/master
YANetworkLoadViewDemo/YANetworkLoadViewDemo/YANetworkLoadView/YANetworkLoadView.swift
mit
1
// // YANetworkLoadView.swift // TestDemoPark // // Created by ss on 15/10/15. // Copyright © 2015年 Yasin. All rights reserved. // import UIKit protocol YANetworkLoadViewDelegate: NSObjectProtocol{ func retryRequest() } @IBDesignable class YANetworkLoadView: UIView { @IBOutlet private var contView: UIView! @IBOutlet private weak var loadingView: UIView! @IBOutlet private weak var activityIndicatorView: YAActivityIndicator! @IBOutlet private weak var errorView: UIView! @IBOutlet private weak var errorLabel: UILabel! weak var delegate:YANetworkLoadViewDelegate? @IBInspectable var errorStr:String?{ get{ return errorLabel.text } set(errorStr){ errorLabel.text = errorStr } } deinit{ print("\(self)释放了") } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { contView = initFromXIB() contView.frame = bounds contView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth,UIViewAutoresizing.FlexibleHeight] self.addSubview(contView) self.backgroundColor = UIColor.clearColor() showLoadingView() } func initFromXIB() -> UIView { let bundle = NSBundle(forClass: self.dynamicType) let nib = UINib(nibName: "YANetworkLoadView", bundle: bundle) let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView return view } func show(showInView:UIView) { if self.superview != nil { self.removeFromSuperview() } showInView.addSubview(self) showInView.bringSubviewToFront(self) } func hidenFromSuperview() { UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { () -> Void in self.removeFromSuperview() }, completion: nil) } func setupErrorLabelText() { errorLabel.text = errorStr } func showLoadingView() { dispatch_async(dispatch_get_main_queue()) { () -> Void in self.loadingView.hidden = false self.errorView.hidden = true self.activityIndicatorView?.color = UIColor(red: 232.0/255.0, green: 35.0/255.0, blue: 111.0/255.0, alpha: 1.0) self.activityIndicatorView?.startAnimating() } } func showErrorView() { dispatch_async(dispatch_get_main_queue()) { () -> Void in self.errorView.hidden = false self.loadingView.hidden = true } } @IBAction func retryRequest(sender: AnyObject) { delegate?.retryRequest() } }
a2ba8651e18567b918bfd582d2aea000
29.311828
134
0.623271
false
false
false
false
lanffy/phpmanual
refs/heads/master
swift/Demo.playground/Contents.swift
apache-2.0
1
import UIKit let colors = [ "Air Force Blue":(red:93,green:138,blue:168), "Bittersweet":(red:254,green:111,blue:94), "Canary Yellow":(red:255,green:239,blue:0), "Dark Orange":(red:255,green:140,blue:0), "Electric Violet":(red:143,green:0,blue:255), "Fern":(red:113,green:188,blue:120), "Gamboge":(red:228,green:155,blue:15), "Hollywood Cerise":(red:252,green:0,blue:161), "Icterine":(red:252,green:247,blue:94), "Jazzberry Jam":(red:165,green:11,blue:94) ] print(colors) var backView = UIView(frame: CGRect.init(x: 0.0, y: 0.0, width: 320.0, height: CGFloat(colors.count * 50))) backView.backgroundColor = UIColor.black backView var index = 0 for (colorName,rgbTuple) in colors { let colorStripe = UILabel.init(frame: CGRect.init(x: 0.0, y: CGFloat(index * 50 + 5), width: 320.0, height: 40.0)) colorStripe.backgroundColor = UIColor.init( red: CGFloat(rgbTuple.red) / 255.0, green: CGFloat(rgbTuple.green) / 255.0, blue: CGFloat(rgbTuple.blue) / 255.0, alpha: 1.0 ) let colorNameLable = UILabel.init(frame: CGRect.init(x: 0.0, y: 0.0, width: 300.0, height: 40.0)) colorNameLable.font = UIFont.init(name: "Arial", size: 24.0) colorNameLable.textColor = UIColor.black colorNameLable.textAlignment = NSTextAlignment.right colorNameLable.text = colorName colorStripe.addSubview(colorNameLable) backView.addSubview(colorStripe) index += 1 } backView
a2dfc8c7d0468b3cdc03b1a11aafaedc
30.104167
118
0.659745
false
false
false
false
lieonCX/Live
refs/heads/master
Live/Others/Lib/RITLImagePicker/Photofiles/Photo/RITLPhotosCell.swift
mit
1
// // RITLPhotosCell.swift // RITLImagePicker-Swift // // Created by YueWen on 2017/1/16. // Copyright © 2017年 YueWen. All rights reserved. // import UIKit typealias RITLPhotoCellOperationClosure = ((RITLPhotosCell) -> Void) let ritl_deselectedImage = UIImage(named: "RITLDeselected") let ritl_selectedImage = UIImage(named: "RITLSelected") /// 选择图片的cell class RITLPhotosCell: UICollectionViewCell { /// control对象点击的闭包 var chooseImageDidSelectHandle :RITLPhotoCellOperationClosure? /// 显示图片的背景图片 lazy var ritl_imageView : UIImageView = { var imageView = UIImageView() imageView.clipsToBounds = true imageView.contentMode = .scaleAspectFill imageView.backgroundColor = .white return imageView }() /// 显示信息的视图,比如视频的时间长度,默认hidden = true lazy var ritl_messageView : UIView = { let view = UIView() view.isHidden = true view.backgroundColor = .black return view }() /// 显示在ritl_messageView上显示时间长度的标签 lazy var ritl_messageLabel : UILabel = { var messageLabel = UILabel() messageLabel.font = .systemFont(ofSize: 11) messageLabel.textColor = .white messageLabel.textAlignment = .right messageLabel.text = "00:25" return messageLabel }() /// 模拟显示选中的按钮 lazy var ritl_chooseImageView : UIImageView = { var chooseImageView = UIImageView() chooseImageView.backgroundColor = UIColor.black.withAlphaComponent(0.5) chooseImageView.layer.cornerRadius = 25 / 2.0 chooseImageView.clipsToBounds = true chooseImageView.image = ritl_deselectedImage return chooseImageView }() /// 模拟响应选中状态的control对象 lazy var ritl_chooseControl : UIControl = { var chooseControl = UIControl() chooseControl.backgroundColor = .clear chooseControl.action(at: .touchUpInside, handle: { [weak self](sender) in let strongSelf = self //响应选择回调 strongSelf!.chooseImageDidSelectHandle?(strongSelf!) }) return chooseControl }() override init(frame: CGRect){ super.init(frame: frame) addAndLayoutSubViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() addAndLayoutSubViews() } /// cell进行点击 /// /// - Parameter isSelected: 当前选中的状态 func selected(_ isSelected:Bool) { ritl_chooseImageView.image = !isSelected ? ritl_deselectedImage : ritl_selectedImage if isSelected { animatedForSelected() } } // MARK: private /// 选中动画 fileprivate func animatedForSelected() { UIView.animate(withDuration: 0.2, animations: { self.ritl_chooseImageView.transform = CGAffineTransform(scaleX: 1.2,y: 1.2) }) { (finish) in UIView.animate(withDuration: 0.2, animations: { self.ritl_chooseImageView.transform = CGAffineTransform.identity }) } } override func prepareForReuse() { ritl_imageView.image = nil ritl_chooseImageView.isHidden = false ritl_messageView.isHidden = true ritl_messageLabel.text = nil ritl_chooseImageView.image = ritl_deselectedImage } fileprivate func addAndLayoutSubViews(){ // subviews self.contentView.addSubview(ritl_imageView) self.contentView.addSubview(ritl_messageView) self.contentView.addSubview(ritl_chooseControl) ritl_chooseControl.addSubview(ritl_chooseImageView) ritl_messageView.addSubview(ritl_messageLabel) //layout ritl_imageView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } ritl_chooseControl.snp.makeConstraints { (make) in make.width.height.equalTo(45) make.right.bottom.equalToSuperview().inset(3) } ritl_chooseImageView.snp.makeConstraints { (make) in make.width.height.equalTo(25) make.right.bottom.equalToSuperview() } ritl_messageView.snp.makeConstraints {(make) in make.left.equalToSuperview() make.right.equalToSuperview() make.bottom.equalToSuperview() make.height.equalTo(20) } ritl_messageLabel.snp.makeConstraints { [weak self](make) in let strongSelf = self make.left.equalTo(strongSelf!.ritl_messageView.snp.left) make.right.equalTo(strongSelf!.ritl_messageView).inset(3) make.bottom.equalTo(strongSelf!.ritl_messageView) make.height.equalTo(20) } } }
2a3d6c6a9df120ff7147ecaa9b2da75c
23.934884
92
0.563701
false
false
false
false
luongtsu/MHCalendar
refs/heads/master
MHCalendar/MHCalendar0.swift
mit
1
// // MHCalendar.swift // MHCalendarDemo // // Created by Luong Minh Hiep on 9/11/17. // Copyright © 2017 Luong Minh Hiep. All rights reserved. // /* import UIKit private let collectionCellReuseIdentifier = "MHCollectionViewCell" protocol MHCalendarResponsible: class { func didSelectDate(date: Date) func didSelectDates(dates: [Date]) func didSelectAnotherMonth(isNextMonth: Bool) } open class MHCalendar0: UIView { weak var mhCalendarObserver : MHCalendarResponsible? // Appearance var tintColor: UIColor var dayDisabledTintColor: UIColor var weekdayTintColor: UIColor var weekendTintColor: UIColor var todayTintColor: UIColor var dateSelectionColor: UIColor var monthTitleColor: UIColor var backgroundImage: UIImage? var backgroundColor: UIColor? // Other config var selectedDates = [Date]() var startDate: Date? var hightlightsToday: Bool = true var hideDaysFromOtherMonth: Bool = false var multiSelectEnabled: Bool = true var displayingMonthIndex: Int = 0// count from starting date fileprivate(set) open var startYear: Int fileprivate(set) open var endYear: Int override open func viewDidLoad() { super.viewDidLoad() // setup collectionview self.collectionView?.delegate = self self.collectionView?.backgroundColor = UIColor.clear self.collectionView?.showsHorizontalScrollIndicator = false self.collectionView?.showsVerticalScrollIndicator = false // Register cell classes self.collectionView!.register(UINib(nibName: "MHCollectionViewCell", bundle: Bundle(for: MHCalendar.self )), forCellWithReuseIdentifier: collectionCellReuseIdentifier) self.collectionView!.register(UINib(nibName: "MHCalendarHeaderView", bundle: Bundle(for: MHCalendar.self )), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "MHCalendarHeaderView") if backgroundImage != nil { self.collectionView!.backgroundView = UIImageView(image: backgroundImage) } else if backgroundColor != nil { self.collectionView?.backgroundColor = backgroundColor } else { self.collectionView?.backgroundColor = UIColor.white } } public init(startYear: Int = Date().year(), endYear: Int = Date().year(), multiSelection: Bool = true, selectedDates: [Date] = []) { self.startYear = startYear self.endYear = endYear self.multiSelectEnabled = multiSelection self.selectedDates = selectedDates //Text color initializations self.tintColor = UIColor.rgb(192, 55, 44) self.dayDisabledTintColor = UIColor.rgb(200, 200, 200) self.weekdayTintColor = UIColor.rgb(46, 204, 113) self.weekendTintColor = UIColor.rgb(192, 57, 43) self.dateSelectionColor = UIColor.rgb(52, 152, 219) self.monthTitleColor = UIColor.rgb(211, 84, 0) self.todayTintColor = UIColor.rgb(248, 160, 46) //Layout creation let layout = UICollectionViewFlowLayout() layout.sectionHeadersPinToVisibleBounds = true layout.minimumInteritemSpacing = 1 layout.minimumLineSpacing = 1 layout.headerReferenceSize = CGSize(width: UIScreen.main.bounds.width, height: MHCalendarHeaderView.defaultHeight) super.init(collectionViewLayout: layout) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewFlowLayout override open func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let startDate = Date(year: startYear, month: 1, day: 1) let firstDayOfMonth = startDate.dateByAddingMonths(displayingMonthIndex) let addingPrefixDaysWithMonthDyas = ( firstDayOfMonth.numberOfDaysInMonth() + firstDayOfMonth.weekday() - Calendar.current.firstWeekday ) let addingSuffixDays = addingPrefixDaysWithMonthDyas%7 var totalNumber = addingPrefixDaysWithMonthDyas if addingSuffixDays != 0 { totalNumber = totalNumber + (7 - addingSuffixDays) } return totalNumber } override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionCellReuseIdentifier, for: indexPath) as! MHCollectionViewCell let calendarStartDate = Date(year:startYear, month: 1, day: 1) let firstDayOfThisMonth = calendarStartDate.dateByAddingMonths(displayingMonthIndex) let prefixDays = ( firstDayOfThisMonth.weekday() - Calendar.current.firstWeekday) if indexPath.row >= prefixDays { cell.isCellSelectable = true let currentDate = firstDayOfThisMonth.dateByAddingDays(indexPath.row-prefixDays) let nextMonthFirstDay = firstDayOfThisMonth.dateByAddingDays(firstDayOfThisMonth.numberOfDaysInMonth()-1) cell.currentDate = currentDate cell.titleLabel.text = "\(currentDate.day())" if selectedDates.filter({ $0.isDateSameDay(currentDate)}).count > 0 && (firstDayOfThisMonth.month() == currentDate.month()) { cell.selectedForLabelColor(dateSelectionColor) } else { cell.deSelectedForLabelColor(weekdayTintColor) if cell.currentDate.isSaturday() || cell.currentDate.isSunday() { cell.titleLabel.textColor = weekendTintColor } if (currentDate > nextMonthFirstDay) { cell.isCellSelectable = false if hideDaysFromOtherMonth { cell.titleLabel.textColor = UIColor.clear } else { cell.titleLabel.textColor = self.dayDisabledTintColor } } if currentDate.isToday() && hightlightsToday { cell.setTodayCellColor(todayTintColor) } if startDate != nil { if Calendar.current.startOfDay(for: cell.currentDate as Date) < Calendar.current.startOfDay(for: startDate!) { cell.isCellSelectable = false cell.titleLabel.textColor = self.dayDisabledTintColor } } } } else { cell.deSelectedForLabelColor(weekdayTintColor) cell.isCellSelectable = false let previousDay = firstDayOfThisMonth.dateByAddingDays(-( prefixDays - indexPath.row)) cell.currentDate = previousDay cell.titleLabel.text = "\(previousDay.day())" if hideDaysFromOtherMonth { cell.titleLabel.textColor = UIColor.clear } else { cell.titleLabel.textColor = self.dayDisabledTintColor } } cell.backgroundColor = UIColor.clear return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { let rect = UIScreen.main.bounds let screenWidth = rect.size.width - 7 return CGSize(width: screenWidth/7, height: screenWidth/7); } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(5, 0, 5, 0); //top,left,bottom,right } override open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "MHCalendarHeaderView", for: indexPath) as! MHCalendarHeaderView let startDate = Date(year: startYear, month: 1, day: 1) let firstDayOfMonth = startDate.dateByAddingMonths(indexPath.section) header.currentMonthLabel.text = firstDayOfMonth.monthNameFull() header.currentMonthLabel.textColor = monthTitleColor header.updateWeekdaysLabelColor(weekdayTintColor) header.updateWeekendLabelColor(weekendTintColor) header.backgroundColor = UIColor.clear return header; } return UICollectionReusableView() } override open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! MHCollectionViewCell if !multiSelectEnabled && cell.isCellSelectable! { mhCalendarObserver?.didSelectDate(date: cell.currentDate) cell.selectedForLabelColor(dateSelectionColor) selectedDates.append(cell.currentDate) return } if cell.isCellSelectable! { if selectedDates.filter({ $0.isDateSameDay(cell.currentDate) }).count == 0 { selectedDates.append(cell.currentDate) cell.selectedForLabelColor(dateSelectionColor) if cell.currentDate.isToday() { cell.setTodayCellColor(dateSelectionColor) } } else { selectedDates = selectedDates.filter(){ return !($0.isDateSameDay(cell.currentDate)) } if cell.currentDate.isSaturday() || cell.currentDate.isSunday() { cell.deSelectedForLabelColor(weekendTintColor) } else { cell.deSelectedForLabelColor(weekdayTintColor) } if cell.currentDate.isToday() && hightlightsToday{ cell.setTodayCellColor(todayTintColor) } } } } }*/
2a240062c8a458b5c2ff728ed522a030
41.951417
227
0.644076
false
false
false
false
xiaoxionglaoshi/DNSwiftProject
refs/heads/master
DNSwiftProject/DNSwiftProject/Classes/Expend/DNNetwork/DNNetwork.swift
apache-2.0
1
// // DNNetwork.swift // DNSwiftProject // // Created by mainone on 16/11/25. // Copyright © 2016年 wjn. All rights reserved. // /* 接口: 🌏 错误: ❌ 正确: ✅ */ import UIKit import SwiftyJSON import Alamofire typealias DNNetworkSuccess = (_ jsonData: JSON?) -> Void typealias DNNetworkFailure = (_ error: Error?) -> Void typealias DNProgressValue = (_ progress: Double) -> Void private let DNNetworkShareInstance = DNNetwork() class DNNetwork: NSObject { // 创建一个单例 open class var shared: DNNetwork { return DNNetworkShareInstance } /// 主机域名 private var host: String { get { return DNConfig.getHost() } } // 请求配置 private let sessionManager: SessionManager = { let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = 20 return SessionManager(configuration: configuration) }() /// GET请求 /// /// - parameter url: 请求接口 不包含主机域名 /// - parameter parameters: 参数 /// - parameter success: 成功后回调 返回JSON数据 /// - parameter failure: 失败后回调 open func GET(url: String, parameters: [String: Any]? = [:], success: @escaping DNNetworkSuccess, failure: @escaping DNNetworkFailure) { var requestUrlString = url if !url.hasPrefix("http://") && !url.hasPrefix("https://") { requestUrlString = self.host + url } DNPrint("🌏GET🌏\(requestUrlString)🌏GET🌏") sessionManager.request(requestUrlString, parameters: parameters).responseJSON { (response) in guard response.result.isSuccess else { DNPrint("❌GET❌\(response.result.error)❌GET❌") failure(response.result.error) return } let json = JSON(data: response.data!); DNPrint("✅GET✅\(json)✅GET✅") success(json) } } open func POST(url: String, parameters: [String: Any]? = [:], success: @escaping DNNetworkSuccess, failure: @escaping DNNetworkFailure) { var requestUrlString = url if !url.hasPrefix("http://") && !url.hasPrefix("https://") { requestUrlString = self.host + url } DNPrint("🌏POST🌏\(requestUrlString)🌏POST🌏") sessionManager.request(requestUrlString, method: .post, parameters: parameters).responseJSON { (response) in guard response.result.isSuccess else { DNPrint("❌POST❌\(response.result.error)❌POST❌") failure(response.result.error) return } let json = JSON(data: response.data!); DNPrint("✅POST✅\(json)✅POST✅") success(json) } } /// 获取目录中的json文件内容 /// /// - parameter forResource: 文件名 /// - parameter success: 成功后回调 open func GetJsonData(forResource: String?, success: DNNetworkSuccess) { //1.获取JSON文件路径 guard let jsonPath = Bundle.main.path(forResource: forResource, ofType: nil) else { DNPrint("❌JSON❌没有获取到对应的文件路径❌JSON❌") return } //2.读取json文件中的内容 guard let jsonData = try? Data(contentsOf: URL(fileURLWithPath: jsonPath)) else { DNPrint("❌JSON❌没有获取到json文件中数据❌JSON❌") return } let json = JSON(data: jsonData); DNPrint("✅JSON✅\(json)✅JSON✅") success(json) } /// 上传文件 /// /// - parameter url: 上传地址 /// - parameter parameters: 参数 /// - parameter datas: 文件data /// - parameter progressValue: 上传进度 /// - parameter success: 上传成功 /// - parameter failure: 上传失败 open func upload(url: String, parameters: [String: Any]? = [:], datas: [UIImage], progressValue: @escaping DNProgressValue, success: @escaping DNNetworkSuccess, failure: @escaping DNNetworkFailure) { //上传文件 sessionManager.upload(multipartFormData: { multipartFormData in // 多个文件添加 for index in 0..<datas.count { DNPrint("添加文件") let data = UIImageJPEGRepresentation(datas[index], 0.01) multipartFormData.append(data!, withName: "data\(index)") } // 同时传参数 if !(parameters?.isEmpty)! { DNPrint("参数: \(parameters)") for (key, value) in parameters! { let parData = (value as AnyObject).data(using: String.Encoding.utf8.rawValue) multipartFormData.append(parData!, withName: key) } } }, to: url) { (encodingResult) in // 返回结果 switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in guard response.result.isSuccess else { DNPrint("❌UPLOAD❌\(response.result.error)❌UPLOAD❌") return } let json = JSON(data: response.data!); DNPrint("✅UPLOAD✅\(response)✅UPLOAD✅") success(json) }.uploadProgress { progress in DNPrint("上传进度: \(progress.fractionCompleted)") progressValue(progress.fractionCompleted) } case .failure(let encodingError): DNPrint("❌UPLOAD❌\(encodingError)❌UPLOAD❌") failure(encodingError) } } } }
6f6969869b2ae99c69035b7215207356
34.031056
203
0.539184
false
false
false
false
creatubbles/ctb-api-swift
refs/heads/develop
CreatubblesAPIClient/Sources/Requests/Hashtag/SuggestedHashtagsFetchRequest.swift
mit
1
// // SuggestedHashtagsFetchRequest.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class SuggestedHashtagsFetchRequest: Request { override var method: RequestMethod { return .get } override var parameters: Dictionary<String, AnyObject> { return prepareParameters() } override var endpoint: String { return "hashtags/suggested" } fileprivate let page: Int? fileprivate let perPage: Int? init(page: Int?, perPage: Int?) { self.page = page self.perPage = perPage } fileprivate func prepareParameters() -> Dictionary<String, AnyObject> { var params = Dictionary<String, AnyObject>() if let page = page { params["page"] = page as AnyObject? } if let perPage = perPage { params["per_page"] = perPage as AnyObject? } return params } }
f6ac4c8b1a647001e350eef57ccbe3f3
34.344828
89
0.685854
false
false
false
false
Sajjon/ViewComposer
refs/heads/master
Example/Source/ViewControllers/Vanilla/VanillaLabelsViewController.swift
mit
1
// // VanillaLabelsViewController.swift // Example // // Created by Alexander Cyon on 2017-06-02. // Copyright © 2017 Alexander Cyon. All rights reserved. // import UIKit class VanillaLabelsViewController: UIViewController, StackViewOwner { private lazy var fooLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Foo" label.textColor = .red label.backgroundColor = .yellow label.textAlignment = .center label.font = .boldSystemFont(ofSize: 30) return label }() private lazy var barLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Bar" label.backgroundColor = .red label.textColor = .blue label.textAlignment = .center label.font = .boldSystemFont(ofSize: 30) return label }() private lazy var bazLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Baz" label.backgroundColor = .green label.textColor = .red label.textAlignment = .left label.font = .boldSystemFont(ofSize: 45) return label }() private lazy var attributedLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false let attributedText = "This is an attributed string".applyAttributes([ NSAttributedStringKey.foregroundColor: UIColor.red, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 30) ], toSubstring: "attributed") label.backgroundColor = .purple label.textColor = .green label.textAlignment = .center label.font = .systemFont(ofSize: 14) return label }() lazy var stackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [self.fooLabel, self.barLabel, self.bazLabel, self.attributedLabel]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.distribution = .fillEqually stackView.axis = .vertical stackView.spacing = 50 let margin: CGFloat = 40 stackView.layoutMargins = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin) stackView.self.isLayoutMarginsRelativeArrangement = true return stackView }() init() { super.init(nibName: nil, bundle: nil) view.backgroundColor = .blue } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupViews() title = "Vanilla - Labels" } }
501c2ffb22f7b0b4b45c9450f092b075
32.034884
122
0.639212
false
false
false
false
Esri/arcgis-runtime-samples-ios
refs/heads/main
arcgis-ios-sdk-samples/Display information/Create symbol styles from web styles/CreateSymbolStylesFromWebStylesViewController.swift
apache-2.0
1
// Copyright 2021 Esri // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 UIKit import ArcGIS class CreateSymbolStylesFromWebStylesViewController: UIViewController, UIAdaptivePresentationControllerDelegate { // MARK: Storyboard views /// The map view managed by the view controller. @IBOutlet var mapView: AGSMapView! { didSet { mapView.map = makeMap(referenceScale: 1e5) mapView.setViewpoint( AGSViewpoint( latitude: 34.28301, longitude: -118.44186, scale: 1e4 ) ) } } /// The button to show legend table. @IBOutlet var legendBarButtonItem: UIBarButtonItem! // MARK: Instance properties /// The Esri 2D point symbol style created from a web style. let symbolStyle = AGSSymbolStyle(styleName: "Esri2DPointSymbolsStyle", portal: .arcGISOnline(withLoginRequired: false)) /// The observation on the map view's `mapScale` property. var mapScaleObservation: NSKeyValueObservation? /// The data source for the legend table. private var symbolsDataSource: SymbolsDataSource? { didSet { legendBarButtonItem.isEnabled = true } } /// A feature layer with LA County Points of Interest service. let featureLayer: AGSFeatureLayer = { let serviceFeatureTable = AGSServiceFeatureTable(url: URL(string: "http://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/LA_County_Points_of_Interest/FeatureServer/0")!) let layer = AGSFeatureLayer(featureTable: serviceFeatureTable) return layer }() // MARK: Methods /// Create a map with a reference scale. func makeMap(referenceScale: Double) -> AGSMap { let map = AGSMap(basemapStyle: .arcGISLightGray) map.referenceScale = referenceScale return map } /// Create an `AGSUniqueValueRenderer` to render feature layer with symbol styles. /// - Parameters: /// - fieldNames: The attributes to match the unique values against. /// - symbolDetails: A dictionary of symbols and their associated information. /// - Returns: An `AGSUniqueValueRenderer` object. func makeUniqueValueRenderer(fieldNames: [String], symbolDetails: [AGSSymbol: (name: String, values: [String])]) -> AGSUniqueValueRenderer { let renderer = AGSUniqueValueRenderer() renderer.fieldNames = fieldNames renderer.uniqueValues = symbolDetails.flatMap { symbol, infos in // For each category value of a symbol, we need to create a // unique value for it, so the field name matches to all // category values. infos.values.map { symbolValue in AGSUniqueValue(description: "", label: infos.name, symbol: symbol, values: [symbolValue]) } } return renderer } /// Get certain types of symbols from a symbol style. /// - Parameters: /// - symbolStyle: An `AGSSymbolStyle` object. /// - types: The types of symbols to search in the symbol style. private func getSymbols(symbolStyle: AGSSymbolStyle, types: [SymbolType]) { let getSymbolsGroup = DispatchGroup() var legendItems = [LegendItem]() var symbolDetails = [AGSSymbol: (String, [String])]() // Get the `AGSSymbol` for each symbol type. types.forEach { category in getSymbolsGroup.enter() let symbolName = category.symbolName let symbolCategoryValues = category.symbolCategoryValues symbolStyle.symbol(forKeys: [symbolName]) { symbol, _ in // Add the symbol to result dictionary and ignore any error. if let symbol = symbol { symbolDetails[symbol] = (symbolName, symbolCategoryValues) // Get the image swatch for the symbol. symbol.createSwatch { image, _ in defer { getSymbolsGroup.leave() } guard let image = image else { return } legendItems.append(LegendItem(name: symbolName, image: image)) } } else { getSymbolsGroup.leave() } } } getSymbolsGroup.notify(queue: .main) { [weak self] in guard let self = self else { return } // Create the data source for the legend table. self.symbolsDataSource = SymbolsDataSource(legendItems: legendItems.sorted { $0.name < $1.name }) // Create unique values and set them to the renderer. self.featureLayer.renderer = self.makeUniqueValueRenderer(fieldNames: ["cat2"], symbolDetails: symbolDetails) // Add the feature layer to the map. self.mapView.map?.operationalLayers.add(self.featureLayer) } } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["CreateSymbolStylesFromWebStylesViewController"] // Get the symbols from the symbol style hosted on an ArcGIS portal. getSymbols(symbolStyle: symbolStyle, types: SymbolType.allCases) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) mapScaleObservation = mapView.observe(\.mapScale, options: .initial) { [weak self] (_, _) in DispatchQueue.main.async { guard let self = self else { return } self.featureLayer.scaleSymbols = self.mapView.mapScale >= 8e4 } } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) mapScaleObservation = nil } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "LegendTableSegue", let controller = segue.destination as? UITableViewController { controller.presentationController?.delegate = self controller.tableView.dataSource = symbolsDataSource } } // MARK: UIAdaptivePresentationControllerDelegate func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { // Ensure that the settings are shown in a popover on small displays. return .none } } // MARK: - SymbolsDataSource, UITableViewDataSource private class SymbolsDataSource: NSObject, UITableViewDataSource { /// The legend items for the legend table. private let legendItems: [LegendItem] init(legendItems: [LegendItem]) { self.legendItems = legendItems } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { legendItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Basic", for: indexPath) let legendItem = legendItems[indexPath.row] cell.textLabel?.text = legendItem.name cell.imageView?.image = legendItem.image return cell } func numberOfSections(in tableView: UITableView) -> Int { 1 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { "Symbol Styles" } } // MARK: - LegendItem private struct LegendItem { let name: String let image: UIImage } // MARK: - SymbolType private enum SymbolType: CaseIterable, Comparable { case atm, beach, campground, cityHall, hospital, library, park, placeOfWorship, policeStation, postOffice, school, trail /// The names of the symbols in the web style. var symbolName: String { let name: String switch self { case .atm: name = "atm" case .beach: name = "beach" case .campground: name = "campground" case .cityHall: name = "city-hall" case .hospital: name = "hospital" case .library: name = "library" case .park: name = "park" case .placeOfWorship: name = "place-of-worship" case .policeStation: name = "police-station" case .postOffice: name = "post-office" case .school: name = "school" case .trail: name = "trail" } return name } /// The category names of features represented by a type of symbol. var symbolCategoryValues: [String] { let values: [String] switch self { case .atm: values = ["Banking and Finance"] case .beach: values = ["Beaches and Marinas"] case .campground: values = ["Campgrounds"] case .cityHall: values = ["City Halls", "Government Offices"] case .hospital: values = ["Hospitals and Medical Centers", "Health Screening and Testing", "Health Centers", "Mental Health Centers"] case .library: values = ["Libraries"] case .park: values = ["Parks and Gardens"] case .placeOfWorship: values = ["Churches"] case .policeStation: values = ["Sheriff and Police Stations"] case .postOffice: values = ["DHL Locations", "Federal Express Locations"] case .school: values = ["Public High Schools", "Public Elementary Schools", "Private and Charter Schools"] case .trail: values = ["Trails"] } return values } }
6c82788cf3052b0878e6a2d20bbca276
37.260073
188
0.620297
false
false
false
false
objecthub/swift-lispkit
refs/heads/master
Sources/LispKit/Base/Bitset.swift
apache-2.0
1
// // Bitset.swift // LispKit // // This is a slightly modified version of the code at https://github.com/lemire/SwiftBitset // Copyright © 2019 Daniel Lemire. 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 /// /// Efficient set container for non-negative integers. /// public final class Bitset: Sequence, Equatable, CustomStringConvertible, Hashable, ExpressibleByArrayLiteral { static let wordSize = 8 /// How many words have been allocated? var capacity: Int /// How many words are used? var wordcount: Int /// Biset storage var data: UnsafeMutablePointer<UInt64> /// Initializer for empty bitset public init(capacity: Int = 1) { self.capacity = capacity self.wordcount = 0 self.data = UnsafeMutablePointer<UInt64>.allocate(capacity: capacity) } /// Copy initializer public init(_ other: Bitset) { self.capacity = other.wordcount self.wordcount = other.wordcount self.data = UnsafeMutablePointer<UInt64>.allocate(capacity: other.wordcount) for i in 0..<self.capacity { self.data[i] = other.data[i] } } deinit { data.deallocate() } /// Make a bitset containing the list of integers, all values must be non-negative /// adding the value i to the bitset will cause the use of least (i+8)/8 bytes public init(_ allints: [Int]) { var mymax = 0 for i in allints { mymax = mymax < i ? i : mymax } self.wordcount = (mymax+63)/64 + 1 self.capacity = self.wordcount self.data = UnsafeMutablePointer<UInt64>.allocate(capacity: self.wordcount) for k in 0..<wordcount { self.data[k] = 0 } self.addMany(allints) } /// Initializing from array literal required public init(arrayLiteral elements: Int...) { var mymax = 0 for i in elements { mymax = mymax < i ? i : mymax } wordcount = (mymax+63)/64 + 1 capacity = wordcount data = UnsafeMutablePointer<UInt64>.allocate(capacity:wordcount) for k in 0..<wordcount { data[k] = 0 } for i in elements { add(i) } } // load an uncompressed bitmap from a byte buffer, in ascending order // The expected format is equivalent to that of an array of 64-bit unsigned integers stored // using the little endian encoding, except that zero bytes at the end are omitted. // This function is compatible with the toData() function. public init(bytes: Data) { assert(Bitset.wordSize == 8) // this logic is expecting a 64-bit internal representation let byteCount = bytes.count if (byteCount == 0) { self.capacity = 1 self.wordcount = 0 self.data = UnsafeMutablePointer<UInt64>.allocate(capacity:capacity) return } self.capacity = (byteCount - 1) / Bitset.wordSize + 1 self.wordcount = capacity self.data = UnsafeMutablePointer<UInt64>.allocate(capacity: self.capacity) func iterate<T>(_ pointer: T, _ f: (T, Int, Int) -> UInt64) -> Int { var remaining = byteCount var offset = 0 for w in 0..<capacity { if remaining < Bitset.wordSize { break } // copy entire word - assumes data is aligned to word boundary let next = offset + Bitset.wordSize var word: UInt64 = f(pointer, offset, w) word = CFSwapInt64LittleToHost(word) remaining -= Bitset.wordSize offset = next data[w] = word } return remaining } var remaining = byteCount if remaining > Bitset.wordSize { remaining = bytes.withUnsafeBytes { (pointer: UnsafeRawBufferPointer) -> Int in iterate(pointer) { (pointer, offset, _) in pointer.load(fromByteOffset: offset, as: UInt64.self) } } } if remaining > 0 { // copy last word fragment // manual byte copy is about 50% faster than `copyBytes` with `withUnsafeMutableBytes` var word: UInt64 = 0 let offset = byteCount - remaining for b in 0..<remaining { let byte = UInt64(clamping: bytes[offset + b]) word = word | (byte << (b * 8)) } data[capacity-1] = word } // TODO: shrink bitmap according to MSB } // store as uncompressed bitmap as a byte buffer in ascending order, with a bytes // size that captures the most significant bit, or an empty instance if no bits are // present. The format is equivalent to that of an array of 64-bit unsigned integers // stored using the little endian encoding, except that zero bytes at the end are // omitted. This function is compatible with the init(bytes: Data) constructor. public func toData() -> Data { assert(Bitset.wordSize == 8) // this logic is expecting a 64-bit internal representation let heighestWord = self.heighestWord() if heighestWord < 0 { return Data() } let lastWord = Int64(bitPattern: data[heighestWord]) let lastBit = Int(flsll(lastWord)) let lastBytes = lastBit == 0 ? 0 : (lastBit - 1) / 8 + 1 let size = heighestWord * Bitset.wordSize + lastBytes var output = Data(capacity: size) for w in 0...heighestWord { var word = CFSwapInt64HostToLittle(data[w]) let byteCount = w == heighestWord ? lastBytes : Bitset.wordSize let bytes = Data(bytes: &word, count: byteCount) // about 10x faster than memory copy output.append(bytes) } return output } public typealias Element = Int // return an empty bitset public static var allZeros: Bitset { return Bitset() } // union between two bitsets, producing a new bitset public static func | (lhs: Bitset, rhs: Bitset) -> Bitset { let mycopy = Bitset(lhs) mycopy.union(rhs) return mycopy } // compute the union between two bitsets inplace public static func |= (lhs: Bitset, rhs: Bitset) { lhs.union(rhs) } // difference between two bitsets, producing a new bitset public static func - (lhs: Bitset, rhs: Bitset) -> Bitset { let mycopy = Bitset(lhs) mycopy.difference(rhs) return mycopy } // inplace difference between two bitsets public static func -= (lhs: Bitset, rhs: Bitset) { lhs.difference(rhs) } // symmetric difference between two bitsets, producing a new bitset public static func ^ (lhs: Bitset, rhs: Bitset) -> Bitset { let mycopy = Bitset(lhs) mycopy.symmetricDifference(rhs) return mycopy } // inplace symmetric difference between two bitsets public static func ^= (lhs: Bitset, rhs: Bitset) { lhs.symmetricDifference(rhs) } // compute the union between two bitsets inplace public static func &= (lhs: Bitset, rhs: Bitset) { lhs.intersection(rhs) } // computes the intersection between two bitsets and return a new bitset public static func & (lhs: Bitset, rhs: Bitset) -> Bitset { let mycopy = Bitset(lhs) mycopy.intersection(rhs) return mycopy } // hash value for the bitset public func hash(into hasher: inout Hasher) { let b: UInt64 = 31 var hash: UInt64 = 0 for i in 0..<wordcount { let w = data[i] hash = hash &* b &+ w } hash = hash ^ (hash >> 33) hash = hash &* 0xff51afd7ed558ccd hash = hash ^ (hash >> 33) hash = hash &* 0xc4ceb9fe1a85ec53 hasher.combine(hash) } // returns a string representation of the bitset public var description: String { var ret = prefix(100).map { $0.description }.joined(separator: ", ") if count() >= 100 { ret.append(", ...") } return "{\(ret)}" } // create an iterator over the values contained in the bitset public func makeIterator() -> BitsetIterator { return BitsetIterator(self) } // count how many values have been stored in the bitset (this function is not // free of computation) public func count() -> Int { var sum: Int = 0 for i in 0..<wordcount { let w = data[i] sum = sum &+ w.nonzeroBitCount } return sum } // proxy for "count" public func cardinality() -> Int { return count() } // add a value to the bitset, all values must be non-negative // adding the value i to the bitset will cause the use of least (i+8)/8 bytes public func add(_ value: Int) { let index = value >> 6 if index >= self.wordcount { increaseWordCount( index + 1) } data[index] |= 1 << (UInt64(value & 63)) } // add all the values to the bitset // adding the value i to the bitset will cause the use of least (i+8)/8 bytes public func addMany(_ allints: Int...) { var mymax = 0 for i in allints { mymax = mymax < i ? i : mymax } let maxindex = mymax >> 6 if maxindex >= self.wordcount { increaseWordCount(maxindex + 1) } for i in allints { add(i) } } // add all the values to the bitset // adding the value i to the bitset will cause the use of least (i+8)/8 bytes public func addMany(_ allints: [Int]) { var mymax = 0 for i in allints { mymax = mymax < i ? i : mymax } let maxindex = mymax >> 6 if maxindex >= self.wordcount { increaseWordCount(maxindex + 1) } for i in allints { add(i) } } // check that a value is in the bitset, all values must be non-negative public func contains(_ value: Int) -> Bool { let index = value >> 6 if index >= self.wordcount { return false } return data[index] & (1 << (UInt64(value & 63))) != 0 } public subscript(value: Int) -> Bool { get { return contains(value) } set(newValue) { if newValue { add(value) } else { remove(value) } } } // compute the intersection (in place) with another bitset public func intersection(_ other: Bitset) { let mincount = Swift.min(self.wordcount, other.wordcount) for i in 0..<mincount { data[i] &= other.data[i] } for i in mincount..<self.wordcount { data[i] = 0 } } // compute the size of the intersection with another bitset public func intersectionCount(_ other: Bitset) -> Int { let mincount = Swift.min(self.wordcount, other.wordcount) var sum = 0 for i in 0..<mincount { sum = sum &+ ( data[i] & other.data[i]).nonzeroBitCount } return sum } // compute the union (in place) with another bitset public func union(_ other: Bitset) { let mincount = Swift.min(self.wordcount, other.wordcount) for i in 0..<mincount { data[i] |= other.data[i] } if other.wordcount > self.wordcount { self.matchWordCapacity(other.wordcount) self.wordcount = other.wordcount for i in mincount..<other.wordcount { data[i] = other.data[i] } } } // compute the size of the union with another bitset public func unionCount(_ other: Bitset) -> Int { let mincount = Swift.min(self.wordcount, other.wordcount) var sum = 0 for i in 0..<mincount { sum = sum &+ (data[i] | other.data[i]).nonzeroBitCount } if other.wordcount > self.wordcount { for i in mincount..<other.wordcount { sum = sum &+ (other.data[i]).nonzeroBitCount } } else { for i in mincount..<self.wordcount { sum = sum &+ (data[i]).nonzeroBitCount } } return sum } // compute the symmetric difference (in place) with another bitset public func symmetricDifference(_ other: Bitset) { let mincount = Swift.min(self.wordcount, other.wordcount) for i in 0..<mincount { data[i] ^= other.data[i] } if other.wordcount > self.wordcount { self.matchWordCapacity(other.wordcount) self.wordcount = other.wordcount for i in mincount..<other.wordcount { data[i] = other.data[i] } } } // compute the size union with another bitset public func symmetricDifferenceCount(_ other: Bitset) -> Int { let mincount = Swift.min(self.wordcount, other.wordcount) var sum = 0 for i in 0..<mincount { sum = sum &+ (data[i] ^ other.data[i]).nonzeroBitCount } if other.wordcount > self.wordcount { for i in mincount..<other.wordcount { sum = sum &+ other.data[i].nonzeroBitCount } } else { for i in mincount..<self.wordcount { sum = sum &+ (data[i]).nonzeroBitCount } } return sum } // compute the difference (in place) with another bitset public func difference(_ other: Bitset) { let mincount = Swift.min(self.wordcount, other.wordcount) for i in 0..<mincount { data[i] &= ~other.data[i] } } // compute the size of the difference with another bitset public func differenceCount(_ other: Bitset) -> Int { let mincount = Swift.min(self.wordcount, other.wordcount) var sum = 0 for i in 0..<mincount { sum = sum &+ ( data[i] & ~other.data[i]).nonzeroBitCount } for i in mincount..<self.wordcount { sum = sum &+ (data[i]).nonzeroBitCount } return sum } // remove a value, must be non-negative public func remove(_ value: Int) { let index = value >> 6 if index < self.wordcount { data[index] &= ~(1 << UInt64(value & 63)) } } // remove a value, if it is present it is removed, otherwise it is added, must // be non-negative public func flip(_ value: Int) { let index = value >> 6 if index < self.wordcount { data[index] ^= 1 << UInt64(value & 63) } else { increaseWordCount(index + 1) data[index] |= 1 << UInt64(value & 63) } } // remove many values, all must be non-negative public func removeMany(_ allints: Int...) { for i in allints { remove(i) } } // return the memory usage of the backing array in bytes public func memoryUsage() -> Int { return self.capacity * 8 } // check whether the value is empty public func isEmpty() -> Bool { for i in 0..<wordcount { let w = data[i] if w != 0 { return false } } return true } // remove all elements, optionally keeping the capacity intact public func removeAll(keepingCapacity keepCapacity: Bool = false) { wordcount = 0 if !keepCapacity { data.deallocate() capacity = 8 // reset to some default data = UnsafeMutablePointer<UInt64>.allocate(capacity:capacity) } } // Returns the next element in the bitset, starting the search from `current` public func next(current: Int = 0) -> Int? { var value = current var x = value >> 6 if x >= self.wordcount { return nil } var w = self.data[x] w >>= UInt64(value & 63) if w != 0 { value = value &+ w.trailingZeroBitCount return value } x = x &+ 1 while x < self.wordcount { let w = self.data[x] if w != 0 { value = x &* 64 &+ w.trailingZeroBitCount return value } x = x &+ 1 } return nil } private static func nextCapacity(mincap: Int) -> Int { return 2 * mincap } // caller is responsible to ensure that index < wordcount otherwise this function fails! func increaseWordCount(_ newWordCount: Int) { if(newWordCount <= wordcount) { print(newWordCount, wordcount) } if newWordCount > capacity { growWordCapacity(Bitset.nextCapacity(mincap : newWordCount)) } for i in wordcount..<newWordCount { data[i] = 0 } wordcount = newWordCount } func growWordCapacity(_ newcapacity: Int) { let newdata = UnsafeMutablePointer<UInt64>.allocate(capacity:newcapacity) for i in 0..<self.wordcount { newdata[i] = self.data[i] } data.deallocate() data = newdata self.capacity = newcapacity } func matchWordCapacity(_ newcapacity: Int) { if newcapacity > self.capacity { growWordCapacity(newcapacity) } } func heighestWord() -> Int { for i in (0..<wordcount).reversed() { let w = data[i] if w.nonzeroBitCount > 0 { return i } } return -1 } // checks whether the two bitsets have the same content public static func == (lhs: Bitset, rhs: Bitset) -> Bool { if lhs.wordcount > rhs.wordcount { for i in rhs.wordcount..<lhs.wordcount where lhs.data[i] != 0 { return false } } else if lhs.wordcount < rhs.wordcount { for i in lhs.wordcount..<rhs.wordcount where rhs.data[i] != 0 { return false } } let mincount = Swift.min(rhs.wordcount, lhs.wordcount) for i in 0..<mincount where rhs.data[i] != lhs.data[i] { return false } return true } } public struct BitsetIterator: IteratorProtocol { let bitset: Bitset var value: Int = -1 init(_ bitset: Bitset) { self.bitset = bitset } public mutating func next() -> Int? { value = value &+ 1 var x = value >> 6 if x >= bitset.wordcount { return nil } var w = bitset.data[x] w >>= UInt64(value & 63) if w != 0 { value = value &+ w.trailingZeroBitCount return value } x = x &+ 1 while x < bitset.wordcount { let w = bitset.data[x] if w != 0 { value = x &* 64 &+ w.trailingZeroBitCount return value } x = x &+ 1 } return nil } }
821b2b81a3fe9e7fb021766734e176b3
28.240066
94
0.624653
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Insurance
refs/heads/master
PerchReadyApp/apps/Perch/iphone/native/Perch/Controllers/CoverageViewController.swift
epl-1.0
1
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit /** * This view controller is embedded in the profile view controller. It displays the user's coverage information in an itemized form. */ class CoverageViewController: PerchViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var savingsButton: UIButton! @IBOutlet weak var tableViewTopConstraint: NSLayoutConstraint! var topSectionHeaderView: CoverageTableTopSectionHeaderView? var midSectionHeaderView: CoverageTableSectionHeaderView? let currentUser = CurrentUser.sharedInstance let configManager = ConfigManager.sharedInstance let arrowImgTag = 99 override func viewDidLoad() { super.viewDidLoad() // Setup the savings button savingsButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left savingsButton.titleLabel?.adjustsFontSizeToFitWidth = true savingsButton.titleLabel?.minimumScaleFactor = 0.2 savingsButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0) // Create the view that will be used in the table view topSectionHeaderView = UINib(nibName: "CoverageTableTopSectionHeader", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as? CoverageTableTopSectionHeaderView midSectionHeaderView = UINib(nibName: "CoverageTableSectionHeader", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as? CoverageTableSectionHeaderView } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // if iPhone 6+, increase the margins of the elements on the screen if UIScreen.mainScreen().bounds.size.height == 736 { savingsButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 0) } // If NOT an iPhone 5 or 5s, have an attributed title so we can have kerning if UIScreen.mainScreen().bounds.size.height > 568 { let attrString = NSAttributedString(string: savingsButton.titleLabel!.text!, attributes: [NSKernAttributeName:2.0, NSForegroundColorAttributeName: UIColor.perchOrange(1.0)]) savingsButton.setAttributedTitle(attrString, forState: UIControlState.Normal) } } } // MARK: UITableView Data Source extension CoverageViewController: UITableViewDataSource { // There are two sections (coverage items, and savings items) func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return currentUser.insurance.insuranceItems.count } else { return currentUser.insurance.creditItems.count } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 25 } /** Populate the cells from the Current User object */ func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("coverageCell") as! CoverageTableViewCell if indexPath.section == 0{ if indexPath.row < currentUser.insurance.insuranceItems.count { let insuranceItem = currentUser.insurance.insuranceItems[indexPath.row] cell.coverageType.text = insuranceItem.coverageName cell.coverageLimit.text = insuranceItem.coverageLimitString cell.coveragePremium.text = insuranceItem.coveragePremiumString } } else { if indexPath.row < currentUser.insurance.creditItems.count { let creditItem = currentUser.insurance.creditItems[indexPath.row] cell.coverageType.text = creditItem.creditName cell.coverageLimit.text = "" cell.coveragePremium.text = creditItem.creditSavingsString } } // If this is the 6+ tell the cell to layout differently if UIScreen.mainScreen().bounds.size.height == 736 { cell.changeMargins() } return cell } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return topSectionHeaderView!.suggestedHeight } return midSectionHeaderView!.suggestedHeight } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { if topSectionHeaderView != nil { return topSectionHeaderView! } } else { if midSectionHeaderView != nil { return midSectionHeaderView! } } return nil } } // MARK: UITableView Delegate extension CoverageViewController: UITableViewDelegate { }
3f94a1d14e335e8ce384b59b378d15f4
38.671875
185
0.674281
false
false
false
false
DAloG/BlueCap
refs/heads/master
BlueCap/Central/PeripheralServiceCharacteristicValuesViewController.swift
mit
1
// // PeripheralServiceCharacteristicValuesViewController.swift // BlueCap // // Created by Troy Stribling on 7/5/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import UIKit import BlueCapKit class PeripheralServiceCharacteristicValuesViewController : UITableViewController { weak var characteristic : Characteristic? let progressView : ProgressView! var peripheralViewController : PeripheralViewController? @IBOutlet var refreshButton :UIButton! struct MainStoryboard { static let peripheralServiceCharactertisticValueCell = "PeripheralServiceCharacteristicValueCell" static let peripheralServiceCharacteristicEditDiscreteValuesSegue = "PeripheralServiceCharacteristicEditDiscreteValues" static let peripheralServiceCharacteristicEditValueSeque = "PeripheralServiceCharacteristicEditValue" } required init?(coder aDecoder:NSCoder) { self.progressView = ProgressView() super.init(coder:aDecoder) } override func viewDidLoad() { super.viewDidLoad() if let characteristic = self.characteristic { self.navigationItem.title = characteristic.name if characteristic.isNotifying { self.refreshButton.enabled = false } else { self.refreshButton.enabled = true } } self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.Plain, target:nil, action:nil) } override func viewDidAppear(animated:Bool) { NSNotificationCenter.defaultCenter().addObserver(self, selector:"peripheralDisconnected", name:BlueCapNotification.peripheralDisconnected, object:self.characteristic?.service.peripheral) NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil) self.updateValues() } override func viewDidDisappear(animated: Bool) { if let characteristic = self.characteristic { if characteristic.isNotifying { characteristic.stopNotificationUpdates() } } NSNotificationCenter.defaultCenter().removeObserver(self) } override func prepareForSegue(segue:UIStoryboardSegue, sender:AnyObject!) { if segue.identifier == MainStoryboard.peripheralServiceCharacteristicEditDiscreteValuesSegue { let viewController = segue.destinationViewController as! PeripheralServiceCharacteristicEditDiscreteValuesViewController viewController.characteristic = self.characteristic } else if segue.identifier == MainStoryboard.peripheralServiceCharacteristicEditValueSeque { let viewController = segue.destinationViewController as! PeripheralServiceCharacteristicEditValueViewController viewController.characteristic = self.characteristic if let stringValues = self.characteristic?.stringValue { let selectedIndex = sender as! NSIndexPath let names = stringValues.keys.array viewController.valueName = names[selectedIndex.row] } } } @IBAction func updateValues() { if let characteristic = self.characteristic { if characteristic.isNotifying { let future = characteristic.recieveNotificationUpdates(10) future.onSuccess {_ in self.updateWhenActive() } future.onFailure{(error) in self.presentViewController(UIAlertController.alertOnError(error), animated:true, completion:nil) } } else if characteristic.propertyEnabled(.Read) { self.progressView.show() let future = characteristic.read(Double(ConfigStore.getCharacteristicReadWriteTimeout())) future.onSuccess {_ in self.updateWhenActive() self.progressView.remove() } future.onFailure {(error) in self.progressView.remove() self.presentViewController(UIAlertController.alertOnError(error) {(action) in self.navigationController?.popViewControllerAnimated(true) return }, animated:true, completion:nil) } } } } func peripheralDisconnected() { Logger.debug() if let peripheralViewController = self.peripheralViewController { if peripheralViewController.peripehealConnected { self.progressView.remove() self.presentViewController(UIAlertController.alertWithMessage("Peripheral disconnected") {(action) in peripheralViewController.peripehealConnected = false }, animated:true, completion:nil) } } } func didResignActive() { self.navigationController?.popToRootViewControllerAnimated(false) Logger.debug() } func didBecomeActive() { Logger.debug() } // UITableViewDataSource override func numberOfSectionsInTableView(tableView:UITableView) -> Int { return 1 } override func tableView(_:UITableView, numberOfRowsInSection section:Int) -> Int { if let values = self.characteristic?.stringValue { return values.count } else { return 0; } } override func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.peripheralServiceCharactertisticValueCell, forIndexPath:indexPath) as! CharacteristicValueCell if let characteristic = self.characteristic { if let stringValues = characteristic.stringValue { let names = stringValues.keys.array let values = stringValues.values.array cell.valueNameLabel.text = names[indexPath.row] cell.valueLable.text = values[indexPath.row] } if characteristic.propertyEnabled(.Write) || characteristic.propertyEnabled(.WriteWithoutResponse) { cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator } else { cell.accessoryType = UITableViewCellAccessoryType.None } } return cell } // UITableViewDelegate override func tableView(tableView:UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) { if let characteristic = self.characteristic { if characteristic.propertyEnabled(.Write) || characteristic.propertyEnabled(.WriteWithoutResponse) { if characteristic.stringValues.isEmpty { self.performSegueWithIdentifier(MainStoryboard.peripheralServiceCharacteristicEditValueSeque, sender:indexPath) } else { self.performSegueWithIdentifier(MainStoryboard.peripheralServiceCharacteristicEditDiscreteValuesSegue, sender:indexPath) } } } } }
fc20ba675e5f1dccc31526a38adbf95b
43.291667
194
0.65811
false
false
false
false
gaurav1981/Swiftz
refs/heads/master
Swiftz/Functor.swift
bsd-3-clause
1
// // Functor.swift // swiftz_core // // Created by Josh Abernathy on 6/7/2014. // Copyright (c) 2014 Josh Abernathy. All rights reserved. // /// Functors are mappings from the functions and objects in one set to the functions and objects /// in another set. public protocol Functor { /// Source typealias A /// Target typealias B /// A Target Functor typealias FB = K1<B> /// Map a function over the value encapsulated by the Functor. func fmap(f : A -> B) -> FB } /// The Identity Functor holds a singular value. public struct Id<A> { private let a : () -> A public init(@autoclosure(escaping) _ aa : () -> A) { a = aa } public var runId : A { return a() } } extension Id : Functor { public typealias B = Any public func fmap<B>(f : A -> B) -> Id<B> { return (Id<B>(f(self.runId))) } } extension Id : Copointed { public func extract() -> A { return self.a() } } extension Id : Comonad { typealias FFA = Id<Id<A>> public func duplicate() -> Id<Id<A>> { return Id<Id<A>>(self) } public func extend(f : Id<A> -> B) -> Id<B> { return self.duplicate().fmap(f) } } // The Constant Functor ignores fmap. public struct Const<A, B> { private let a : () -> A public init(@autoclosure(escaping) _ aa : () -> A) { a = aa } public var runConst : A { return a() } } // TODO: File rdar; This has to be in this file or we get linker errors. extension Const : Bifunctor { typealias B = Any typealias C = B typealias D = Any typealias PAC = Const<A, C> typealias PAD = Const<A, D> typealias PBC = Const<B, C> typealias PBD = Const<B, D> public func bimap<B, C, D>(f : A -> B, _ g : C -> D) -> Const<B, D> { return Const<B, D>(f(self.runConst)) } public func leftMap<C, B>(f : A -> B) -> Const<B, C> { return self.bimap(f, identity) } public func rightMap<C, D>(g : C -> D) -> Const<A, D> { return self.bimap(identity, g) } } extension Const : Functor { typealias FB = Const<A, B> public func fmap<B>(f : A -> B) -> Const<A, B> { return Const<A, B>(self.runConst) } }
5bbff044780079da5c8afab8e6d24ff9
18.495238
96
0.614069
false
false
false
false
Aishwarya-Ramakrishnan/sparkios
refs/heads/master
Tests/MessageTests.swift
mit
1
// Copyright 2016 Cisco Systems Inc // // 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 Quick import Nimble @testable import SparkSDK class MessageSpec: QuickSpec { private let Text = "test text" private let FileUrl = "https://developer.ciscospark.com/index.html" private var other: TestUser! private var room: TestRoom? private var roomId: String { return room!.id! } private func getISO8601Date() -> String { let formatter = DateFormatter() let enUSPosixLocale = Locale(identifier: "en_US_POSIX") formatter.locale = enUSPosixLocale formatter.dateFormat = "yyyy-MM-dd\'T\'HH:mm:ss.SSSXXX" return formatter.string(from: Date()) } private func validate(message: Message) { expect(message.id).notTo(beNil()) expect(message.personId).notTo(beNil()) expect(message.personEmail).notTo(beNil()) expect(message.roomId).notTo(beNil()) expect(message.created).notTo(beNil()) } override func spec() { beforeSuite { self.other = TestUserFactory.sharedInstance.createUser() Spark.initWith(accessToken: Config.selfUser.token!) self.room = TestRoom() } afterSuite { Utils.wait(interval: Config.TestcaseInterval) } // MARK: - Post message to room describe("post message to room") { it("with text") { do { let message = try Spark.messages.post(roomId: self.roomId, text: self.Text) self.validate(message: message) expect(message.text).to(equal(self.Text)) } catch let error as NSError { fail("Failed to post message, \(error.localizedFailureReason)") } } it("with file") { do { let message = try Spark.messages.post(roomId: self.roomId, files: self.FileUrl) self.validate(message: message) expect(message.files).notTo(beNil()) } catch let error as NSError { fail("Failed to post message, \(error.localizedFailureReason)") } } it("with text/file") { do { let message = try Spark.messages.post(roomId: self.roomId, text: self.Text, files: self.FileUrl) self.validate(message: message) expect(message.text).to(equal(self.Text)) expect(message.files).notTo(beNil()) } catch let error as NSError { fail("Failed to post message, \(error.localizedFailureReason)") } } it("with nothing") { let message = try? Spark.messages.post(roomId: self.roomId) expect(message).to(beNil()) } it("with invalid room Id") { let message = try? Spark.messages.post(roomId: Config.InvalidId, text: self.Text) expect(message).to(beNil()) } } // MARK: - Post message to person with person Id describe("post message to person with person Id") { it("with text") { do { let message = try Spark.messages.post(personId: (self.other.personId)!, text: self.Text) self.validate(message: message) expect(message.toPersonId).to(equal(self.other.personId)) expect(message.text).to(equal(self.Text)) } catch let error as NSError { fail("Failed to post message, \(error.localizedFailureReason)") } } it("with file") { do { let message = try Spark.messages.post(personId: (self.other.personId)!, files: self.FileUrl) self.validate(message: message) expect(message.toPersonId).to(equal(self.other.personId)) expect(message.files).notTo(beNil()) } catch let error as NSError { fail("Failed to post message, \(error.localizedFailureReason)") } } it("with text/file") { do { let message = try Spark.messages.post(personId: (self.other.personId)!, text: self.Text, files: self.FileUrl) self.validate(message: message) expect(message.toPersonId).to(equal(self.other.personId)) expect(message.text).to(equal(self.Text)) expect(message.files).notTo(beNil()) } catch let error as NSError { fail("Failed to post message, \(error.localizedFailureReason)") } } it("with nothing") { let message = try? Spark.messages.post(personId: (self.other.personId)!) expect(message).to(beNil()) } it("with invalid person Id") { let message = try? Spark.messages.post(personId: Config.InvalidId, text: self.Text) expect(message).to(beNil()) } } // MARK: - Post message to person with person email describe("post message to person with person email") { it("with text") { do { let message = try Spark.messages.post(personEmail: (self.other.email)!, text: self.Text) self.validate(message: message) expect(message.toPersonEmail).to(equal(self.other.email)) expect(message.text).to(equal(self.Text)) } catch let error as NSError { fail("Failed to post message, \(error.localizedFailureReason)") } } it("with file") { do { let message = try Spark.messages.post(personEmail: (self.other.email)!, files: self.FileUrl) self.validate(message: message) expect(message.toPersonEmail).to(equal(self.other.email)) expect(message.files).notTo(beNil()) } catch let error as NSError { fail("Failed to post message, \(error.localizedFailureReason)") } } it("with text/file") { do { let message = try Spark.messages.post(personEmail: (self.other.email)!, text: self.Text, files: self.FileUrl) self.validate(message: message) expect(message.toPersonEmail).to(equal(self.other.email)) expect(message.text).to(equal(self.Text)) expect(message.files).notTo(beNil()) } catch let error as NSError { fail("Failed to post message, \(error.localizedFailureReason)") } } it("with nothing") { let message = try? Spark.messages.post(personEmail: (self.other.email)!) expect(message).to(beNil()) } it("with invalid person email") { let message = try? Spark.messages.post(personEmail: Config.InvalidEmail, text: self.Text) expect(message).notTo(beNil()) } } // MARK: - List message describe("list message") { it("normal") { do { let messages = try Spark.messages.list(roomId: self.roomId) expect(messages.isEmpty).to(beFalse()) } catch let error as NSError { fail("Failed to list message, \(error.localizedFailureReason)") } } it("with max value") { do { let messages = try Spark.messages.list(roomId: self.roomId, max: 2) expect(messages.count).to(equal(2)) } catch let error as NSError { fail("Failed to list message, \(error.localizedFailureReason)") } } it("before a date") { do { let message1 = try Spark.messages.post(roomId: self.roomId, text: self.Text) Utils.wait(interval: Config.TestcaseInterval) let now = self.getISO8601Date() let message2 = try Spark.messages.post(roomId: self.roomId, text: self.Text) let messages = try Spark.messages.list(roomId: self.roomId, before: now) expect(messages.contains() {$0.id == message1.id}).to(beTrue()) expect(messages.contains() {$0.id == message2.id}).to(beFalse()) } catch let error as NSError { fail("Failed to list message, \(error.localizedFailureReason)") } } it("before message Id") { do { let message1 = try Spark.messages.post(roomId: self.roomId, text: self.Text) let message2 = try Spark.messages.post(roomId: self.roomId, text: self.Text) let messages = try Spark.messages.list(roomId: self.roomId, beforeMessage: message2.id!) expect(messages.contains() {$0.id == message1.id}).to(beTrue()) expect(messages.contains() {$0.id == message2.id}).to(beFalse()) } catch let error as NSError { fail("Failed to list message, \(error.localizedFailureReason)") } } it("before a date and message Id") { do { let message = try Spark.messages.post(roomId: self.roomId, text: self.Text) let now = self.getISO8601Date() let messages = try Spark.messages.list(roomId: self.roomId, before: now, beforeMessage: message.id!) expect(messages.contains() {$0.id == message.id}).to(beFalse()) } catch let error as NSError { fail("Failed to list message, \(error.localizedFailureReason)") } } it("with invalid room Id") { expect{try Spark.messages.list(roomId: Config.InvalidId)}.to(throwError()) } } // MARK: - Get message describe("get message") { it("normal") { do { let messageFromCreate = try Spark.messages.post(roomId: self.roomId, text: self.Text) self.validate(message: messageFromCreate) let messageFromGet = try Spark.messages.get(messageId: (messageFromCreate.id)!) self.validate(message: messageFromGet) expect(messageFromGet.id).to(equal(messageFromCreate.id)) expect(messageFromGet.text).to(equal(messageFromCreate.text)) } catch let error as NSError { fail("Failed to get message, \(error.localizedFailureReason)") } } it("with invalid message Id") { expect{try Spark.messages.get(messageId: Config.InvalidId)}.to(throwError()) } } // MARK: - Delete message describe("delete message") { it("normal") { do { let message = try Spark.messages.post(roomId: self.roomId, text: self.Text) expect{try Spark.messages.delete(messageId: (message.id)!)}.notTo(throwError()) } catch let error as NSError { fail("Failed to create message, \(error.localizedFailureReason)") } } it("with invalid message Id") { expect{try Spark.messages.delete(messageId: Config.InvalidId)}.to(throwError()) } } } }
14941a59d7af1bf043963dac8096dd08
39.850144
129
0.497919
false
false
false
false
matthewcheok/Kaleidoscope
refs/heads/master
Kaleidoscope/Lexer.swift
mit
1
// // Lexer.swift // Kaleidoscope // // Created by Matthew Cheok on 15/11/15. // Copyright © 2015 Matthew Cheok. All rights reserved. // import Foundation public enum Token { case Define case Identifier(String) case Number(Float) case ParensOpen case ParensClose case Comma case Other(String) } typealias TokenGenerator = (String) -> Token? let tokenList: [(String, TokenGenerator)] = [ ("[ \t\n]", { _ in nil }), ("[a-zA-Z][a-zA-Z0-9]*", { $0 == "def" ? .Define : .Identifier($0) }), ("[0-9.]+", { (r: String) in .Number((r as NSString).floatValue) }), ("\\(", { _ in .ParensOpen }), ("\\)", { _ in .ParensClose }), (",", { _ in .Comma }), ] public class Lexer { let input: String init(input: String) { self.input = input } public func tokenize() -> [Token] { var tokens = [Token]() var content = input while (content.characters.count > 0) { var matched = false for (pattern, generator) in tokenList { if let m = content.match(pattern) { if let t = generator(m) { tokens.append(t) } content = content.substringFromIndex(content.startIndex.advancedBy(m.characters.count)) matched = true break } } if !matched { let index = content.startIndex.advancedBy(1) tokens.append(.Other(content.substringToIndex(index))) content = content.substringFromIndex(index) } } return tokens } }
0580e6aba9191846d9005eeaae35ca33
25.873016
107
0.510638
false
false
false
false
jeancarlosaps/swift
refs/heads/master
Swift em 4 Semanas/Playgrounds/Semana 1/3-Tipos Fundamentais.playground/Contents.swift
mit
2
// Playground - noun: a place where people can play import UIKit //Inteiros e Decimais var anguloDeLançamento: Int = 4 var anguloDeLançamentoMaisPreciso: Double = 4.3248969578956 //Booleanos var gostaDeBanana = true //Swift infere o tipo como sendo Bool var clienteMilhas = false //clienteMilhas = "não tem!" //erro, a variável é do tipo Bool e não String. //Conversão de Tipos var valorFixo = 40 var ajuste = 0.3567 //Soma feita usando valores literais, ou seja, que não fora associados a uma varável ou constante 40 + 0.3567 //Não é possível realizar a soma abaixo, pois Swift verifica que uma variável é do tipo Int e outra do tipo Double //valorFixo + ajuste var valorFixoTipoDouble = Double(valorFixo) + ajuste let integerTaxaFixa = Int(valorFixoTipoDouble) //Tipagem Segura //var nome: String = 3 //erro, atribuindo Int a uma variável do tipo String var tempoAproximado = 10 //Swift deduz que é do tipo Int var tempoExato = 10 + 0.3456 //Não gera erro, pois está somando valores litera
64d7b2ed9a882ec0d193153432b89d16
19.215686
114
0.739088
false
false
false
false
vi4m/Zewo
refs/heads/master
Modules/ExampleApplication/Sources/ExampleApplication/main.swift
mit
1
import HTTPServer import HTTPClient // fetches port to serve on from command line arguments let arguments = try Configuration.commandLineArguments() let port = arguments["port"].int ?? 8080 // logs all incoming requests and responses let log = LogMiddleware() // catches errors and formats them if possible let recover = RecoveryMiddleware() // sends requests to different handlers based on their path let router = BasicRouter { route in // reponds to GET /hello with hello world route.get("/hello") { request in return Response(body: "Hello, world!") } // forwards all requests to github api // for example, GET /orgs/zewo hits api.github.com/orgs/zewo route.get("/orgs/*") { request in let client = try Client(url: "https://api.github.com") return try client.get(request.path ?? "") } } // ties everything together let server = try Server(port: port, middleware: [log, recover], responder: router) // starts the actual server try server.start()
15aa58ef5f4365649a87f1bca6650acb
29.484848
82
0.702783
false
false
false
false
zhouxj6112/ARKit
refs/heads/master
ARHome/ARHome/Additional View Controllers/StatusViewController.swift
apache-2.0
1
/* See LICENSE folder for this sample’s licensing information. Abstract: Utility class for showing messages above the AR view. */ import Foundation import ARKit /** Displayed at the top of the main interface of the app that allows users to see the status of the AR experience, as well as the ability to control restarting the experience altogether. - Tag: StatusViewController */ class StatusViewController: UIViewController { // MARK: - Types enum MessageType { case trackingStateEscalation case planeEstimation case contentPlacement case focusSquare static var all: [MessageType] = [ .trackingStateEscalation, .planeEstimation, .contentPlacement, .focusSquare ] } // MARK: - IBOutlets @IBOutlet weak private var messagePanel: UIVisualEffectView! @IBOutlet weak private var messageLabel: UILabel! @IBOutlet weak private var closeButton: UIButton! @IBOutlet weak private var recordButton: UIButton! // MARK: - Properties /// Trigerred when the "Restart Experience" button is tapped. var restartExperienceHandler: () -> Void = {} /// Seconds before the timer message should fade out. Adjust if the app needs longer transient messages. private let displayDuration: TimeInterval = 6 // Timer for hiding messages. private var messageHideTimer: Timer? private var timers: [MessageType: Timer] = [:] override func viewDidLoad() { super.viewDidLoad() // closeButton.frame = CGRect.init(x: self.view.frame.size.width-40, y: 20, width: 40, height: 40); recordButton.frame = CGRect.init(x: 0, y: 20, width: 40, height: 40); messagePanel.frame = CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: 20); messageLabel.frame = CGRect.init(x: 0, y: 0, width: messagePanel.frame.size.width, height: messagePanel.frame.size.height); messageLabel.textAlignment = .center; } // MARK: - Message Handling func showMessage(_ text: String, autoHide: Bool = true) { // Cancel any previous hide timer. messageHideTimer?.invalidate() messageLabel.text = text // Make sure status is showing. setMessageHidden(false, animated: true) if autoHide { messageHideTimer = Timer.scheduledTimer(withTimeInterval: displayDuration, repeats: false, block: { [weak self] _ in self?.setMessageHidden(true, animated: true) }) } } func scheduleMessage(_ text: String, inSeconds seconds: TimeInterval, messageType: MessageType) { cancelScheduledMessage(for: messageType) let timer = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: { [weak self] timer in self?.showMessage(text) timer.invalidate() }) timers[messageType] = timer } func cancelScheduledMessage(`for` messageType: MessageType) { timers[messageType]?.invalidate() timers[messageType] = nil } func cancelAllScheduledMessages() { for messageType in MessageType.all { cancelScheduledMessage(for: messageType) } } // MARK: - ARKit func showTrackingQualityInfo(for trackingState: ARCamera.TrackingState, autoHide: Bool) { showMessage(trackingState.presentationString, autoHide: autoHide) } func escalateFeedback(for trackingState: ARCamera.TrackingState, inSeconds seconds: TimeInterval) { cancelScheduledMessage(for: .trackingStateEscalation) let timer = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: { [unowned self] _ in self.cancelScheduledMessage(for: .trackingStateEscalation) var message = trackingState.presentationString if let recommendation = trackingState.recommendation { message.append(": \(recommendation)") } self.showMessage(message, autoHide: false) }) timers[.trackingStateEscalation] = timer } // MARK: - IBActions @IBAction private func restartExperience(_ sender: UIButton) { restartExperienceHandler() } @IBAction private func handleRecord(_ sender: UIButton) { if ReplayKitUtil.isRecording() == false { ReplayKitUtil.startRecoder(self) recordButton.setImage(UIImage.init(named: "ar_stop"), for: .normal) } else { ReplayKitUtil.stopRecoder() recordButton.setImage(UIImage.init(named: "ar_start"), for: .normal) } } // MARK: - Panel Visibility private func setMessageHidden(_ hide: Bool, animated: Bool) { // The panel starts out hidden, so show it before animating opacity. messagePanel.isHidden = false guard animated else { messagePanel.alpha = hide ? 0 : 1 return } UIView.animate(withDuration: 0.2, delay: 0, options: [.beginFromCurrentState], animations: { self.messagePanel.alpha = hide ? 0 : 1 }, completion: nil) } } extension ARCamera.TrackingState { var presentationString: String { switch self { case .notAvailable: return "TRACKING UNAVAILABLE" case .normal: return "TRACKING NORMAL" case .limited(.excessiveMotion): return "TRACKING LIMITED\nExcessive motion" case .limited(.insufficientFeatures): return "TRACKING LIMITED\nLow detail" case .limited(.initializing): return "Initializing" case .limited(.relocalizing): return "Relocalizing" } } var recommendation: String? { switch self { case .limited(.excessiveMotion): return "Try slowing down your movement, or reset the session." case .limited(.insufficientFeatures): return "Try pointing at a flat surface, or reset the session." default: return nil } } }
82478b928c22f9dbf50cf3df97ad466e
30.947644
131
0.640118
false
false
false
false
gurenupet/hah-auth-ios-swift
refs/heads/master
Example/Pods/Mixpanel-swift/Mixpanel/Error.swift
apache-2.0
6
// // Error.swift // Mixpanel // // Created by Yarden Eitan on 6/10/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation enum PropertyError: Error { case invalidType(type: Any) } class Assertions { static var assertClosure = swiftAssertClosure static let swiftAssertClosure = { Swift.assert($0, $1, file: $2, line: $3) } } func MPAssert(_ condition: @autoclosure() -> Bool, _ message: @autoclosure() -> String = "", file: StaticString = #file, line: UInt = #line) { Assertions.assertClosure(condition(), message(), file, line) } class ErrorHandler { class func wrap<ReturnType>(_ f: () throws -> ReturnType?) -> ReturnType? { do { return try f() } catch let error { logError(error) return nil } } class func logError(_ error: Error) { let stackSymbols = Thread.callStackSymbols Logger.error(message: "Error: \(error) \n Stack Symbols: \(stackSymbols)") } }
cb609df2009094d8da8291e697c4a35c
23.904762
82
0.590822
false
false
false
false
wjk930726/weibo
refs/heads/master
weiBo/weiBo/iPhone/Modules/Home/Controller/WBHomeViewController.swift
mit
1
// // WBHomeViewController.swift // weiBo // // Created by 王靖凯 on 2016/11/24. // Copyright © 2016年 王靖凯. All rights reserved. // //import GTMWebKit import UIKit class WBHomeViewController: WBBaseViewController { var items: [DataItem] = [] lazy var listViewModel = WBStatusListViewModel() let cellReuseIdentifier = "dasfsdfsfsf" override func viewDidLoad() { super.viewDidLoad() loadStatus(isPull: true) { _ in } // Do any additional setup after loading the view. NotificationCenter.default.addObserver(self, selector: #selector(didSelectedAnImage(sender:)), name: clickThumbImage, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(didSelectedAHyperlink(sender:)), name: clickHyperlink, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } override func setupTableView() { super.setupTableView() tableView.register(WBStatusCell.self, forCellReuseIdentifier: cellReuseIdentifier) tableView.estimatedRowHeight = 200 tableView.rowHeight = UITableViewAutomaticDimension } } // MARK: - 读取数据 extension WBHomeViewController { fileprivate func loadStatus(isPull: Bool, callBack: @escaping (Bool) -> Void) { listViewModel.loadDate(isPull: isPull) { isSuccess in if isSuccess { self.tableView.reloadData() } else { self.view.makeToast("加载失败") } callBack(isSuccess) } } } // MARK: - reloadData extension WBHomeViewController { override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return listViewModel.dataSource.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! WBStatusCell cell.status = listViewModel.dataSource[indexPath.row] return cell } override func headerRefresh(callBack: @escaping (Bool) -> Void) { loadStatus(isPull: true, callBack: callBack) } override func footerRefresh(callBack: @escaping (Bool) -> Void) { loadStatus(isPull: false, callBack: callBack) } override func whenLoginIsSucess() { super.whenLoginIsSucess() loadStatus(isPull: true) { _ in } } } import ImageViewer extension WBHomeViewController: GalleryItemsDataSource { func itemCount() -> Int { return items.count } func provideGalleryItem(_ index: Int) -> GalleryItem { return items[index].galleryItem } struct DataItem { let imageView: UIImageView let galleryItem: GalleryItem } @objc fileprivate func didSelectedAnImage(sender: Notification) { if let index = sender.userInfo?[indexKey] as? NSNumber, let urls = sender.userInfo?[urlsKey] as? [String] { let browser = WBPhotoBrowserViewController(index: index.intValue, images: urls) presentImageGallery(browser.galleryViewController) } } @objc private func didSelectedAHyperlink(sender: Notification) { if let hyperlink = sender.userInfo?[hyperlinkTextKey] as? String { let reg = "http(s)?:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?" let pre = NSPredicate(format: "SELF MATCHES %@", reg) if pre.evaluate(with: hyperlink) { // let webVC = GTMWebViewController(with: hyperlink, navigType: .navbar) // webVC.hidesBottomBarWhenPushed = true // navigationController?.pushViewController(webVC, animated: true) } else { console.debug(hyperlink) } } } }
512f072a9a495a926b03fe7125825d5d
31.896552
140
0.647013
false
false
false
false
zqqf16/SYM
refs/heads/master
SYM/UI/Utils/Loading.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2022 zqqf16 // // 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 AppKit import Foundation import SnapKit protocol LoadingAble: AnyObject { var loadingIndicator: NSProgressIndicator! { get set } func showLoading() func hideLoading() } extension LoadingAble where Self: NSViewController { func showLoading() { DispatchQueue.main.async { defer { self.loadingIndicator.startAnimation(nil) self.loadingIndicator.isHidden = false } if self.loadingIndicator != nil { return } self.loadingIndicator = NSProgressIndicator() self.loadingIndicator.style = .spinning self.loadingIndicator.isDisplayedWhenStopped = false self.view.addSubview(self.loadingIndicator) self.loadingIndicator.snp.makeConstraints { make in make.width.height.equalTo(48) make.center.equalTo(self.view) } } } func hideLoading() { DispatchQueue.main.async { self.loadingIndicator.stopAnimation(nil) } } }
8f03ccd38c5fcba2855dc0c744e49483
35.360656
81
0.683499
false
false
false
false
SummerHH/swift3.0WeBo
refs/heads/master
WeBo/Classes/View/PhotoBrowser/PhotoBrowserController.swift
apache-2.0
1
// // PhotoBrowserController.swift // WeBo // // Created by Apple on 16/11/20. // Copyright © 2016年 叶炯. All rights reserved. // import UIKit import SnapKit import SVProgressHUD private let PhotoBrowserCell = "PhotoBrowserCell" class PhotoBrowserController: UIViewController { // MARK:- 定义属性 var indexPath : IndexPath var picURLs : [URL] // MARK:- 懒加载属性 fileprivate lazy var collectionView : UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: PhotoBrowserCollectionViewLayout()) fileprivate lazy var closeBtn : UIButton = UIButton(bgColor: UIColor.darkGray, fontSize: 14, title: "关 闭") fileprivate lazy var saveBtn : UIButton = UIButton(bgColor: UIColor.darkGray, fontSize: 14, title: "保 存") // MARK:- 自定义构造函数 init(indexPath : IndexPath, picURLs : [URL]) { self.indexPath = indexPath self.picURLs = picURLs super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK:- 系统回调函数 override func loadView() { super.loadView() view.frame.size.width += 20 } override func viewDidLoad() { super.viewDidLoad() // 1.设置UI界面 setupUI() // 2.滚动到对应的图片 collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .left) } } // MARK:- 设置UI界面内容 extension PhotoBrowserController { fileprivate func setupUI() { // 1.添加子控件 view.addSubview(collectionView) view.addSubview(closeBtn) view.addSubview(saveBtn) // 2.设置frame collectionView.frame = view.frame closeBtn.snp.makeConstraints { (make) -> Void in make.left.equalTo(20) make.bottom.equalTo(-20) make.size.equalTo(CGSize(width: 90, height: 32)) } saveBtn.snp.makeConstraints { (make) -> Void in make.right.equalTo(-20) make.bottom.equalTo(closeBtn.snp.bottom) make.size.equalTo(closeBtn.snp.size) } // 3.设置collectionView的属性 collectionView.register(PhotoBrowserViewCell.self, forCellWithReuseIdentifier: PhotoBrowserCell) collectionView.dataSource = self // 4.监听两个按钮的点击 closeBtn.addTarget(self, action: #selector(PhotoBrowserController.closeBtnClick), for: .touchUpInside) saveBtn.addTarget(self, action: #selector(PhotoBrowserController.saveBtnClick), for: .touchUpInside) } } // MARK:- 事件监听函数 extension PhotoBrowserController { @objc fileprivate func closeBtnClick() { dismiss(animated: true, completion: nil) } @objc fileprivate func saveBtnClick() { // 1.获取当前显示的图片 let cell = collectionView.visibleCells.first as! PhotoBrowserViewCell guard let image = cell.imageView.image else { return } // 2.将image对象保存相册 UIImageWriteToSavedPhotosAlbum(image, self, #selector(PhotoBrowserController.image(_:didFinishSavingWithError:contextInfo:)), nil) } @objc fileprivate func image(_ image : UIImage, didFinishSavingWithError error : NSError?, contextInfo : AnyObject) { var showInfo = "" if error != nil { showInfo = "保存失败" } else { showInfo = "保存成功" } SVProgressHUD.showInfo(withStatus: showInfo) } } // MARK:- 实现collectionView的数据源方法 extension PhotoBrowserController : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return picURLs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.创建cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoBrowserCell, for: indexPath) as! PhotoBrowserViewCell // 2.给cell设置数据 cell.picURL = picURLs[indexPath.item] cell.delegate = self return cell } } //MARK: - PhotoBrowserViewCellDelegate extension PhotoBrowserController: PhotoBrowserViewCellDelegate{ func imageViewBtnClick() { closeBtnClick() } } //MARK:- 遵守AnimatorDismissDelegate extension PhotoBrowserController: AnimatorDismissDelegate { func indexPathForDimissView() -> IndexPath { // 1.获取当前正在显示的indexPath let cell = collectionView.visibleCells.first! return collectionView.indexPath(for: cell)! } func imageViewForDimissView() -> UIImageView { // 1.创建UIImageView对象 let imageView = UIImageView() // 2.设置imageView的frame let cell = collectionView.visibleCells.first as! PhotoBrowserViewCell imageView.frame = cell.imageView.frame imageView.image = cell.imageView.image // 3.设置imageView的属性 imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true return imageView } } //MARK:- 自定义布局 class PhotoBrowserCollectionViewLayout : UICollectionViewFlowLayout { override func prepare() { super.prepare() // 1.设置itemSize itemSize = collectionView!.frame.size minimumInteritemSpacing = 0 minimumLineSpacing = 0 scrollDirection = .horizontal // 2.设置collectionView的属性 collectionView?.isPagingEnabled = true collectionView?.showsHorizontalScrollIndicator = false collectionView?.showsVerticalScrollIndicator = false } }
315f6511a990fbf087f4f6796778f948
28.559585
155
0.643996
false
false
false
false
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART
refs/heads/master
App/ViewController.swift
mit
1
// // ViewController.swift // adafruitBLEMinimized // // Created by Alejandro Castillejo on 9/13/16. // Copyright © 2016 Alejandro Castillejo. All rights reserved. // import UIKit class ViewController: UIViewController { //Your BLE UUID private var yourUUID: String? //UI @IBOutlet var statusBLELabel: UILabel! @IBOutlet var lastMessageLabel: UILabel! @IBOutlet var messageTextField: UITextField! @IBOutlet var connectDisconnectButton: UIButton! // Data private var peripheralList = PeripheralList() private let uartData = UartModuleManager() override func viewDidLoad() { super.viewDidLoad() //Example: // yourUUID = "1B3BC628-2E20-42F2-808C-6B762E7E7C1F" if yourUUID == nil{ let alert = UIAlertView() alert.title = "Alert" alert.message = "Set your BLE module UUID on the viewDidLoad method on the file ViewController.swift. You should be able to see the UUIDs printed on the console. Make sure not to run the app on the simulator, rather run it on an iPhone or iPad with bluetooth" alert.addButtonWithTitle(":-)") alert.show() } // Start scanning BleManager.sharedInstance.startScan() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Subscribe to Ble Notifications NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didDiscoverPeripheral(_:)), name: BleManager.BleNotifications.DidDiscoverPeripheral.rawValue, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didDiscoverPeripheral(_:)), name: BleManager.BleNotifications.DidUnDiscoverPeripheral.rawValue, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didDisconnectFromPeripheral(_:)), name: BleManager.BleNotifications.DidDisconnectFromPeripheral.rawValue, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didConnectToPeripheral(_:)), name: BleManager.BleNotifications.DidConnectToPeripheral.rawValue, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(willConnectToPeripheral(_:)), name: BleManager.BleNotifications.WillConnectToPeripheral.rawValue, object: nil) let isFullScreen = UIScreen.mainScreen().traitCollection.horizontalSizeClass == .Compact if isFullScreen { peripheralList.connectToPeripheral(nil) } // Check that the peripheral is still connected if BleManager.sharedInstance.blePeripheralConnected == nil { peripheralList.disconnected() } } @IBAction func connectDisconnectTapped(sender: AnyObject) { if(sender as! UIButton == self.connectDisconnectButton){ if (sender.selected == true) { //Disconnect if let peripheral = BleManager.sharedInstance.blePeripheralConnected { BleManager.sharedInstance.disconnect(peripheral) } // let mqttManager = MqttManager.sharedInstance // mqttManager.disconnect() } else if (sender.selected == false) { // Start scanning BleManager.sharedInstance.startScan() } } } @IBAction func send(sender: AnyObject) { uartData.sendMessageToUart(self.messageTextField.text!) } func didDiscoverPeripheral(notification : NSNotification) { //Connecting, not connected if(BleManager.sharedInstance.blePeripheralConnecting == nil){ // print(peripheralList) //Debugging let bleManager = BleManager.sharedInstance let blePeripheralsFound = bleManager.blePeripherals() for i in 0..<peripheralList.blePeripherals.count { let selectedBlePeripheralIdentifier = peripheralList.blePeripherals[i]; if let blePeripheral = blePeripheralsFound[selectedBlePeripheralIdentifier] { print("Peripheral") print(blePeripheral.name) print(peripheralList.blePeripherals[i]) } } if let _ = yourUUID { if(peripheralList.blePeripherals.contains(yourUUID!)){ peripheralList.connectToPeripheral(yourUUID!) } } } } func willConnectToPeripheral(notification : NSNotification) { dispatch_async(dispatch_get_main_queue(), { self.statusBLELabel.text = "Connecting" }) let isFullScreen = UIScreen.mainScreen().traitCollection.horizontalSizeClass == .Compact if isFullScreen { dispatch_async(dispatch_get_main_queue(), {[unowned self] in let localizationManager = LocalizationManager.sharedInstance let alertController = UIAlertController(title: nil, message: localizationManager.localizedString("peripheraldetails_connecting"), preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: localizationManager.localizedString("dialog_cancel"), style: .Cancel, handler: { (_) -> Void in if let peripheral = BleManager.sharedInstance.blePeripheralConnecting { BleManager.sharedInstance.disconnect(peripheral) } else if let peripheral = BleManager.sharedInstance.blePeripheralConnected { BleManager.sharedInstance.disconnect(peripheral) } })) self.presentViewController(alertController, animated: true, completion:nil) }) } } func didConnectToPeripheral(notification : NSNotification) { dispatch_async(dispatch_get_main_queue(), { self.statusBLELabel.text = "Connected" self.connectDisconnectButton.selected = true }) //1 let blePeripheral = BleManager.sharedInstance.blePeripheralConnected! blePeripheral.peripheral.delegate = self // startUpdatesCheck() //2 // Peripheral should be connected uartData.delegate = self uartData.blePeripheral = BleManager.sharedInstance.blePeripheralConnected // Note: this will start the service discovery guard uartData.blePeripheral != nil else { DLog("Error: Uart: blePeripheral is nil") return } self.dismissViewControllerAnimated(true, completion: nil) } func didDisconnectFromPeripheral(notification : NSNotification) { dispatch_async(dispatch_get_main_queue(), { self.statusBLELabel.text = "Not connected" self.connectDisconnectButton.selected = false }) dispatch_async(dispatch_get_main_queue(), {[unowned self] in DLog("list: disconnection detected a") self.peripheralList.disconnected() }) } } // MARK: - CBPeripheralDelegate extension ViewController: CBPeripheralDelegate { // Pass peripheral callbacks to UartData func peripheral(peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) { uartData.peripheral(peripheral, didModifyServices: invalidatedServices) } func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) { uartData.peripheral(peripheral, didDiscoverServices:error) } func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) { uartData.peripheral(peripheral, didDiscoverCharacteristicsForService: service, error: error) } func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) { uartData.peripheral(peripheral, didUpdateValueForCharacteristic: characteristic, error: error) } } // MARK: - UartModuleDelegate extension ViewController: UartModuleDelegate { func addChunkToUI(dataChunk : UartDataChunk) { //If the message is received (RX) and not (sent) TX if(dataChunk.mode == UartDataChunk.TransferMode.RX){ if let receivedMessage = NSString(data: dataChunk.data, encoding: NSUTF8StringEncoding) { self.lastMessageLabel.text = receivedMessage as String; } } } func mqttUpdateStatusUI() { //Needed for the protocol, I decided not to use this method. I didn't get rid of it because I didn't want to make any changes to the original code } func mqttError(message: String, isConnectionError: Bool) { let localizationManager = LocalizationManager.sharedInstance let alertMessage = isConnectionError ? localizationManager.localizedString("uart_mqtt_connectionerror_title"): message let alertController = UIAlertController(title: nil, message: alertMessage, preferredStyle: .Alert) let okAction = UIAlertAction(title: localizationManager.localizedString("dialog_ok"), style: .Default, handler:nil) alertController.addAction(okAction) self.presentViewController(alertController, animated: true, completion: nil) } }
1c411f6c2f016e402e067d94926725f0
38.830579
271
0.64986
false
false
false
false
DarrenKong/firefox-ios
refs/heads/master
Sync/SyncStateMachine.swift
mpl-2.0
6
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Account import XCGLogger import Deferred private let log = Logger.syncLogger private let StorageVersionCurrent = 5 // Names of collections that can be enabled/disabled locally. public let TogglableEngines: [String] = [ "bookmarks", "history", "tabs", "passwords" ] // Names of collections for which a synchronizer is implemented locally. private let LocalEngines: [String] = TogglableEngines + ["clients"] // Names of collections which will appear in a default meta/global produced locally. // Map collection name to engine version. See http://docs.services.mozilla.com/sync/objectformats.html. private let DefaultEngines: [String: Int] = [ "bookmarks": BookmarksStorageVersion, "clients": ClientsStorageVersion, "history": HistoryStorageVersion, "passwords": PasswordsStorageVersion, "tabs": TabsStorageVersion, // We opt-in to syncing collections we don't know about, since no client offers to sync non-enabled, // non-declined engines yet. See Bug 969669. "forms": 1, "addons": 1, "prefs": 2, ] // Names of collections which will appear as declined in a default // meta/global produced locally. private let DefaultDeclined: [String] = [String]() public func computeNewEngines(_ engineConfiguration: EngineConfiguration, enginesEnablements: [String: Bool]?) -> (engines: [String: EngineMeta], declined: [String]) { var enabled: Set<String> = Set(engineConfiguration.enabled) var declined: Set<String> = Set(engineConfiguration.declined) var engines: [String: EngineMeta] = [:] if let enginesEnablements = enginesEnablements { let enabledLocally = Set(enginesEnablements.filter { $0.value }.map { $0.key }) let declinedLocally = Set(enginesEnablements.filter { !$0.value }.map { $0.key }) enabled.subtract(declinedLocally) declined.subtract(enabledLocally) enabled.formUnion(enabledLocally) declined.formUnion(declinedLocally) } for engine in enabled { // We take this device's version, or, if we don't know the correct version, 0. Another client should recognize // the engine, see an old version, wipe and start again. // TODO: this client does not yet do this wipe-and-update itself! let version = DefaultEngines[engine] ?? 0 engines[engine] = EngineMeta(version: version, syncID: Bytes.generateGUID()) } return (engines: engines, declined: Array(declined)) } // public for testing. public func createMetaGlobalWithEngineConfiguration(_ engineConfiguration: EngineConfiguration, enginesEnablements: [String: Bool]?) -> MetaGlobal { let (engines, declined) = computeNewEngines(engineConfiguration, enginesEnablements: enginesEnablements) return MetaGlobal(syncID: Bytes.generateGUID(), storageVersion: StorageVersionCurrent, engines: engines, declined: declined) } public func createMetaGlobal(enginesEnablements: [String: Bool]?) -> MetaGlobal { let engineConfiguration = EngineConfiguration(enabled: Array(DefaultEngines.keys), declined: DefaultDeclined) return createMetaGlobalWithEngineConfiguration(engineConfiguration, enginesEnablements: enginesEnablements) } public typealias TokenSource = () -> Deferred<Maybe<TokenServerToken>> public typealias ReadyDeferred = Deferred<Maybe<Ready>> // See docs in docs/sync.md. // You might be wondering why this doesn't have a Sync15StorageClient like FxALoginStateMachine // does. Well, such a client is pinned to a particular server, and this state machine must // acknowledge that a Sync client occasionally must migrate between two servers, preserving // some state from the last. // The resultant 'Ready' will be able to provide a suitably initialized storage client. open class SyncStateMachine { // The keys are used as a set, to prevent cycles in the state machine. var stateLabelsSeen = [SyncStateLabel: Bool]() var stateLabelSequence = [SyncStateLabel]() let stateLabelsAllowed: Set<SyncStateLabel> let scratchpadPrefs: Prefs /// Use this set of states to constrain the state machine to attempt the barest /// minimum to get to Ready. This is suitable for extension uses. If it is not possible, /// then no destructive or expensive actions are taken (e.g. total HTTP requests, /// duration, records processed, database writes, fsyncs, blanking any local collections) public static let OptimisticStates = Set(SyncStateLabel.optimisticValues) /// The default set of states that the state machine is allowed to use. public static let AllStates = Set(SyncStateLabel.allValues) public init(prefs: Prefs, allowingStates labels: Set<SyncStateLabel> = SyncStateMachine.AllStates) { self.scratchpadPrefs = prefs.branch("scratchpad") self.stateLabelsAllowed = labels } open class func clearStateFromPrefs(_ prefs: Prefs) { log.debug("Clearing all Sync prefs.") Scratchpad.clearFromPrefs(prefs.branch("scratchpad")) // XXX this is convoluted. prefs.clearAll() } fileprivate func advanceFromState(_ state: SyncState) -> ReadyDeferred { log.info("advanceFromState: \(state.label)") // Record visibility before taking any action. let labelAlreadySeen = self.stateLabelsSeen.updateValue(true, forKey: state.label) != nil stateLabelSequence.append(state.label) if let ready = state as? Ready { // Sweet, we made it! return deferMaybe(ready) } // Cycles are not necessarily a problem, but seeing the same (recoverable) error condition is a problem. if state is RecoverableSyncState && labelAlreadySeen { return deferMaybe(StateMachineCycleError()) } guard stateLabelsAllowed.contains(state.label) else { return deferMaybe(DisallowedStateError(state.label, allowedStates: stateLabelsAllowed)) } return state.advance() >>== self.advanceFromState } open func toReady(_ authState: SyncAuthState) -> ReadyDeferred { let token = authState.token(Date.now(), canBeExpired: false) return chainDeferred(token, f: { (token, kSync) in log.debug("Got token from auth state.") if Logger.logPII { log.debug("Server is \(token.api_endpoint).") } let prior = Scratchpad.restoreFromPrefs(self.scratchpadPrefs, syncKeyBundle: KeyBundle.fromKSync(kSync)) if prior == nil { log.info("No persisted Sync state. Starting over.") } var scratchpad = prior ?? Scratchpad(b: KeyBundle.fromKSync(kSync), persistingTo: self.scratchpadPrefs) // Take the scratchpad and add the fxaDeviceId from the state, and hashedUID from the token let b = Scratchpad.Builder(p: scratchpad) if let deviceID = authState.deviceID { b.fxaDeviceId = deviceID } else { // Either deviceRegistration hasn't occurred yet (our bug) or // FxA has given us an UnknownDevice error. log.warning("Device registration has not taken place before sync.") } b.hashedUID = token.hashedFxAUID if let enginesEnablements = authState.enginesEnablements, !enginesEnablements.isEmpty { b.enginesEnablements = enginesEnablements } if let clientName = authState.clientName { b.clientName = clientName } // Detect if we've changed anything in our client record from the last time we synced… let ourClientUnchanged = (b.fxaDeviceId == scratchpad.fxaDeviceId) // …and if so, trigger a reset of clients. if !ourClientUnchanged { b.localCommands.insert(LocalCommand.resetEngine(engine: "clients")) } scratchpad = b.build() log.info("Advancing to InitialWithLiveToken.") let state = InitialWithLiveToken(scratchpad: scratchpad, token: token) // Start with fresh visibility data. self.stateLabelsSeen = [:] self.stateLabelSequence = [] return self.advanceFromState(state) }) } } public enum SyncStateLabel: String { case Stub = "STUB" // For 'abstract' base classes. case InitialWithExpiredToken = "initialWithExpiredToken" case InitialWithExpiredTokenAndInfo = "initialWithExpiredTokenAndInfo" case InitialWithLiveToken = "initialWithLiveToken" case InitialWithLiveTokenAndInfo = "initialWithLiveTokenAndInfo" case ResolveMetaGlobalVersion = "resolveMetaGlobalVersion" case ResolveMetaGlobalContent = "resolveMetaGlobalContent" case NeedsFreshMetaGlobal = "needsFreshMetaGlobal" case NewMetaGlobal = "newMetaGlobal" case HasMetaGlobal = "hasMetaGlobal" case NeedsFreshCryptoKeys = "needsFreshCryptoKeys" case HasFreshCryptoKeys = "hasFreshCryptoKeys" case Ready = "ready" case FreshStartRequired = "freshStartRequired" // Go around again... once only, perhaps. case ServerConfigurationRequired = "serverConfigurationRequired" case ChangedServer = "changedServer" case MissingMetaGlobal = "missingMetaGlobal" case MissingCryptoKeys = "missingCryptoKeys" case MalformedCryptoKeys = "malformedCryptoKeys" case SyncIDChanged = "syncIDChanged" case RemoteUpgradeRequired = "remoteUpgradeRequired" case ClientUpgradeRequired = "clientUpgradeRequired" static let allValues: [SyncStateLabel] = [ InitialWithExpiredToken, InitialWithExpiredTokenAndInfo, InitialWithLiveToken, InitialWithLiveTokenAndInfo, NeedsFreshMetaGlobal, ResolveMetaGlobalVersion, ResolveMetaGlobalContent, NewMetaGlobal, HasMetaGlobal, NeedsFreshCryptoKeys, HasFreshCryptoKeys, Ready, FreshStartRequired, ServerConfigurationRequired, ChangedServer, MissingMetaGlobal, MissingCryptoKeys, MalformedCryptoKeys, SyncIDChanged, RemoteUpgradeRequired, ClientUpgradeRequired, ] // This is the list of states needed to get to Ready, or failing. // This is useful in circumstances where it is important to conserve time and/or battery, and failure // to timely sync is acceptable. static let optimisticValues: [SyncStateLabel] = [ InitialWithLiveToken, InitialWithLiveTokenAndInfo, HasMetaGlobal, HasFreshCryptoKeys, Ready, ] } /** * States in this state machine all implement SyncState. * * States are either successful main-flow states, or (recoverable) error states. * Errors that aren't recoverable are simply errors. * Main-flow states flow one to one. * * (Terminal failure states might be introduced at some point.) * * Multiple error states (but typically only one) can arise from each main state transition. * For example, parsing meta/global can result in a number of different non-routine situations. * * For these reasons, and the lack of useful ADTs in Swift, we model the main flow as * the success branch of a Result, and the recovery flows as a part of the failure branch. * * We could just as easily use a ternary Either-style operator, but thanks to Swift's * optional-cast-let it's no saving to do so. * * Because of the lack of type system support, all RecoverableSyncStates must have the same * signature. That signature implies a possibly multi-state transition; individual states * will have richer type signatures. */ public protocol SyncState { var label: SyncStateLabel { get } func advance() -> Deferred<Maybe<SyncState>> } /* * Base classes to avoid repeating initializers all over the place. */ open class BaseSyncState: SyncState { open var label: SyncStateLabel { return SyncStateLabel.Stub } open let client: Sync15StorageClient! let token: TokenServerToken // Maybe expired. var scratchpad: Scratchpad // TODO: 304 for i/c. open func getInfoCollections() -> Deferred<Maybe<InfoCollections>> { return chain(self.client.getInfoCollections(), f: { return $0.value }) } public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) { self.scratchpad = scratchpad self.token = token self.client = client log.info("Inited \(self.label.rawValue)") } open func synchronizer<T: Synchronizer>(_ synchronizerClass: T.Type, delegate: SyncDelegate, prefs: Prefs, why: SyncReason) -> T { return T(scratchpad: self.scratchpad, delegate: delegate, basePrefs: prefs, why: why) } // This isn't a convenience initializer 'cos subclasses can't call convenience initializers. public init(scratchpad: Scratchpad, token: TokenServerToken) { let workQueue = DispatchQueue.global() let resultQueue = DispatchQueue.main let backoff = scratchpad.backoffStorage let client = Sync15StorageClient(token: token, workQueue: workQueue, resultQueue: resultQueue, backoff: backoff) self.scratchpad = scratchpad self.token = token self.client = client log.info("Inited \(self.label.rawValue)") } open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(StubStateError()) } } open class BaseSyncStateWithInfo: BaseSyncState { open let info: InfoCollections init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.info = info super.init(client: client, scratchpad: scratchpad, token: token) } init(scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.info = info super.init(scratchpad: scratchpad, token: token) } } /* * Error types. */ public protocol SyncError: MaybeErrorType, SyncPingFailureFormattable {} extension SyncError { public var failureReasonName: SyncPingFailureReasonName { return .unexpectedError } } open class UnknownError: SyncError { open var description: String { return "Unknown error." } } open class StateMachineCycleError: SyncError { open var description: String { return "The Sync state machine encountered a cycle. This is a coding error." } } open class CouldNotFetchMetaGlobalError: SyncError { open var description: String { return "Could not fetch meta/global." } } open class CouldNotFetchKeysError: SyncError { open var description: String { return "Could not fetch crypto/keys." } } open class StubStateError: SyncError { open var description: String { return "Unexpectedly reached a stub state. This is a coding error." } } open class ClientUpgradeRequiredError: SyncError { let targetStorageVersion: Int public init(target: Int) { self.targetStorageVersion = target } open var description: String { return "Client upgrade required to work with storage version \(self.targetStorageVersion)." } } open class InvalidKeysError: SyncError { let keys: Keys public init(_ keys: Keys) { self.keys = keys } open var description: String { return "Downloaded crypto/keys, but couldn't parse them." } } open class DisallowedStateError: SyncError { let state: SyncStateLabel let allowedStates: Set<SyncStateLabel> public init(_ state: SyncStateLabel, allowedStates: Set<SyncStateLabel>) { self.state = state self.allowedStates = allowedStates } open var description: String { return "Sync state machine reached \(String(describing: state)) state, which is disallowed. Legal states are: \(String(describing: allowedStates))" } } /** * Error states. These are errors that can be recovered from by taking actions. We use RecoverableSyncState as a * sentinel: if we see the same recoverable state twice, we bail out and complain that we've seen a cycle. (Seeing * some states -- principally initial states -- twice is fine.) */ public protocol RecoverableSyncState: SyncState { } /** * Recovery: discard our local timestamps and sync states; discard caches. * Be prepared to handle a conflict between our selected engines and the new * server's meta/global; if an engine is selected locally but not declined * remotely, then we'll need to upload a new meta/global and sync that engine. */ open class ChangedServerError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.ChangedServer } let newToken: TokenServerToken let newScratchpad: Scratchpad public init(scratchpad: Scratchpad, token: TokenServerToken) { self.newToken = token self.newScratchpad = Scratchpad(b: scratchpad.syncKeyBundle, persistingTo: scratchpad.prefs) } open func advance() -> Deferred<Maybe<SyncState>> { // TODO: mutate local storage to allow for a fresh start. let state = InitialWithLiveToken(scratchpad: newScratchpad.checkpoint(), token: newToken) return deferMaybe(state) } } /** * Recovery: same as for changed server, but no need to upload a new meta/global. */ open class SyncIDChangedError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.SyncIDChanged } fileprivate let previousState: BaseSyncStateWithInfo fileprivate let newMetaGlobal: Fetched<MetaGlobal> public init(previousState: BaseSyncStateWithInfo, newMetaGlobal: Fetched<MetaGlobal>) { self.previousState = previousState self.newMetaGlobal = newMetaGlobal } open func advance() -> Deferred<Maybe<SyncState>> { // TODO: mutate local storage to allow for a fresh start. let s = self.previousState.scratchpad.evolve().setGlobal(self.newMetaGlobal).setKeys(nil).build().checkpoint() let state = HasMetaGlobal(client: self.previousState.client, scratchpad: s, token: self.previousState.token, info: self.previousState.info) return deferMaybe(state) } } /** * Recovery: configure the server. */ open class ServerConfigurationRequiredError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.ServerConfigurationRequired } fileprivate let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } open func advance() -> Deferred<Maybe<SyncState>> { let client = self.previousState.client! let oldScratchpad = self.previousState.scratchpad let enginesEnablements = oldScratchpad.enginesEnablements let s = oldScratchpad.evolve() .setGlobal(nil) .addLocalCommandsFromKeys(nil) .setKeys(nil) .clearEnginesEnablements() .build().checkpoint() // Upload a new meta/global ... let metaGlobal: MetaGlobal if let oldEngineConfiguration = s.engineConfiguration { metaGlobal = createMetaGlobalWithEngineConfiguration(oldEngineConfiguration, enginesEnablements: enginesEnablements) } else { metaGlobal = createMetaGlobal(enginesEnablements: s.enginesEnablements) } return client.uploadMetaGlobal(metaGlobal, ifUnmodifiedSince: nil) // ... and a new crypto/keys. >>> { return client.uploadCryptoKeys(Keys.random(), withSyncKeyBundle: s.syncKeyBundle, ifUnmodifiedSince: nil) } >>> { return deferMaybe(InitialWithLiveToken(client: client, scratchpad: s, token: self.previousState.token)) } } } /** * Recovery: wipe the server (perhaps unnecessarily) and proceed to configure the server. */ open class FreshStartRequiredError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.FreshStartRequired } fileprivate let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } open func advance() -> Deferred<Maybe<SyncState>> { let client = self.previousState.client! return client.wipeStorage() >>> { return deferMaybe(ServerConfigurationRequiredError(previousState: self.previousState)) } } } open class MissingMetaGlobalError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.MissingMetaGlobal } fileprivate let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(FreshStartRequiredError(previousState: self.previousState)) } } open class MissingCryptoKeysError: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.MissingCryptoKeys } fileprivate let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(FreshStartRequiredError(previousState: self.previousState)) } } open class RemoteUpgradeRequired: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.RemoteUpgradeRequired } fileprivate let previousState: BaseSyncStateWithInfo public init(previousState: BaseSyncStateWithInfo) { self.previousState = previousState } open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(FreshStartRequiredError(previousState: self.previousState)) } } open class ClientUpgradeRequired: RecoverableSyncState { open var label: SyncStateLabel { return SyncStateLabel.ClientUpgradeRequired } fileprivate let previousState: BaseSyncStateWithInfo let targetStorageVersion: Int public init(previousState: BaseSyncStateWithInfo, target: Int) { self.previousState = previousState self.targetStorageVersion = target } open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(ClientUpgradeRequiredError(target: self.targetStorageVersion)) } } /* * Non-error states. */ open class InitialWithLiveToken: BaseSyncState { open override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveToken } // This looks totally redundant, but try taking it out, I dare you. public override init(scratchpad: Scratchpad, token: TokenServerToken) { super.init(scratchpad: scratchpad, token: token) } // This looks totally redundant, but try taking it out, I dare you. public override init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken) { super.init(client: client, scratchpad: scratchpad, token: token) } func advanceWithInfo(_ info: InfoCollections) -> SyncState { return InitialWithLiveTokenAndInfo(scratchpad: self.scratchpad, token: self.token, info: info) } override open func advance() -> Deferred<Maybe<SyncState>> { return chain(getInfoCollections(), f: self.advanceWithInfo) } } /** * Each time we fetch a new meta/global, we need to reconcile it with our * current state. * * It might be identical to our current meta/global, in which case we can short-circuit. * * We might have no previous meta/global at all, in which case this state * simply configures local storage to be ready to sync according to the * supplied meta/global. (Not necessarily datatype elections: those will be per-device.) * * Or it might be different. In this case the previous m/g and our local user preferences * are compared to the new, resulting in some actions and a final state. * * This states are similar in purpose to GlobalSession.processMetaGlobal in Android Sync. */ open class ResolveMetaGlobalVersion: BaseSyncStateWithInfo { let fetched: Fetched<MetaGlobal> init(fetched: Fetched<MetaGlobal>, client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.fetched = fetched super.init(client: client, scratchpad: scratchpad, token: token, info: info) } open override var label: SyncStateLabel { return SyncStateLabel.ResolveMetaGlobalVersion } class func fromState(_ state: BaseSyncStateWithInfo, fetched: Fetched<MetaGlobal>) -> ResolveMetaGlobalVersion { return ResolveMetaGlobalVersion(fetched: fetched, client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } override open func advance() -> Deferred<Maybe<SyncState>> { // First: check storage version. let v = fetched.value.storageVersion if v > StorageVersionCurrent { // New storage version? Uh-oh. No recovery possible here. log.info("Client upgrade required for storage version \(v)") return deferMaybe(ClientUpgradeRequired(previousState: self, target: v)) } if v < StorageVersionCurrent { // Old storage version? Uh-oh. Wipe and upload both meta/global and crypto/keys. log.info("Server storage version \(v) is outdated.") return deferMaybe(RemoteUpgradeRequired(previousState: self)) } return deferMaybe(ResolveMetaGlobalContent.fromState(self, fetched: self.fetched)) } } open class ResolveMetaGlobalContent: BaseSyncStateWithInfo { let fetched: Fetched<MetaGlobal> init(fetched: Fetched<MetaGlobal>, client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections) { self.fetched = fetched super.init(client: client, scratchpad: scratchpad, token: token, info: info) } open override var label: SyncStateLabel { return SyncStateLabel.ResolveMetaGlobalContent } class func fromState(_ state: BaseSyncStateWithInfo, fetched: Fetched<MetaGlobal>) -> ResolveMetaGlobalContent { return ResolveMetaGlobalContent(fetched: fetched, client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } override open func advance() -> Deferred<Maybe<SyncState>> { // Check global syncID and contents. if let previous = self.scratchpad.global?.value { // Do checks that only apply when we're coming from a previous meta/global. if previous.syncID != fetched.value.syncID { log.info("Remote global sync ID has changed. Dropping keys and resetting all local collections.") let s = self.scratchpad.freshStartWithGlobal(fetched).checkpoint() return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s)) } let b = self.scratchpad.evolve() .setGlobal(fetched) // We always adopt the upstream meta/global record. let previousEngines = Set(previous.engines.keys) let remoteEngines = Set(fetched.value.engines.keys) for engine in previousEngines.subtracting(remoteEngines) { log.info("Remote meta/global disabled previously enabled engine \(engine).") b.localCommands.insert(.disableEngine(engine: engine)) } for engine in remoteEngines.subtracting(previousEngines) { log.info("Remote meta/global enabled previously disabled engine \(engine).") b.localCommands.insert(.enableEngine(engine: engine)) } for engine in remoteEngines.intersection(previousEngines) { let remoteEngine = fetched.value.engines[engine]! let previousEngine = previous.engines[engine]! if previousEngine.syncID != remoteEngine.syncID { log.info("Remote sync ID for \(engine) has changed. Resetting local.") b.localCommands.insert(.resetEngine(engine: engine)) } } let s = b.build().checkpoint() return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s)) } // No previous meta/global. Adopt the new meta/global. let s = self.scratchpad.freshStartWithGlobal(fetched).checkpoint() return deferMaybe(HasMetaGlobal.fromState(self, scratchpad: s)) } } private func processFailure(_ failure: MaybeErrorType?) -> MaybeErrorType { if let failure = failure as? ServerInBackoffError { log.warning("Server in backoff. Bailing out. \(failure.description)") return failure } // TODO: backoff etc. for all of these. if let failure = failure as? ServerError<HTTPURLResponse> { // Be passive. log.error("Server error. Bailing out. \(failure.description)") return failure } if let failure = failure as? BadRequestError<HTTPURLResponse> { // Uh oh. log.error("Bad request. Bailing out. \(failure.description)") return failure } log.error("Unexpected failure. \(failure?.description ?? "nil")") return failure ?? UnknownError() } open class InitialWithLiveTokenAndInfo: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.InitialWithLiveTokenAndInfo } // This method basically hops over HasMetaGlobal, because it's not a state // that we expect consumers to know about. override open func advance() -> Deferred<Maybe<SyncState>> { // Either m/g and c/k are in our local cache, and they're up-to-date with i/c, // or we need to fetch them. // Cached and not changed in i/c? Use that. // This check would be inaccurate if any other fields were stored in meta/; this // has been the case in the past, with the Sync 1.1 migration indicator. if let global = self.scratchpad.global { if let metaModified = self.info.modified("meta") { // We check the last time we fetched the record, and that can be // later than the collection timestamp. All we care about here is if the // server might have a newer record. if global.timestamp >= metaModified { log.debug("Cached meta/global fetched at \(global.timestamp), newer than server modified \(metaModified). Using cached meta/global.") // Strictly speaking we can avoid fetching if this condition is not true, // but if meta/ is modified for a different reason -- store timestamps // for the last collection fetch. This will do for now. return deferMaybe(HasMetaGlobal.fromState(self)) } log.info("Cached meta/global fetched at \(global.timestamp) older than server modified \(metaModified). Fetching fresh meta/global.") } else { // No known modified time for meta/. That means the server has no meta/global. // Drop our cached value and fall through; we'll try to fetch, fail, and // go through the usual failure flow. log.warning("Local meta/global fetched at \(global.timestamp) found, but no meta collection on server. Dropping cached meta/global.") // If we bail because we've been overly optimistic, then we nil out the current (broken) // meta/global. Next time around, we end up in the "No cached meta/global found" branch. self.scratchpad = self.scratchpad.evolve().setGlobal(nil).setKeys(nil).build().checkpoint() } } else { log.debug("No cached meta/global found. Fetching fresh meta/global.") } return deferMaybe(NeedsFreshMetaGlobal.fromState(self)) } } /* * We've reached NeedsFreshMetaGlobal somehow, but we haven't yet done anything about it * (e.g. fetch a new one with GET /storage/meta/global ). * * If we don't want to hit the network (e.g. from an extension), we should stop if we get to this state. */ open class NeedsFreshMetaGlobal: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.NeedsFreshMetaGlobal } class func fromState(_ state: BaseSyncStateWithInfo) -> NeedsFreshMetaGlobal { return NeedsFreshMetaGlobal(client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } override open func advance() -> Deferred<Maybe<SyncState>> { // Fetch. return self.client.getMetaGlobal().bind { result in if let resp = result.successValue { // We use the server's timestamp, rather than the record's modified field. // Either can be made to work, but the latter has suffered from bugs: see Bug 1210625. let fetched = Fetched(value: resp.value, timestamp: resp.metadata.timestampMilliseconds) return deferMaybe(ResolveMetaGlobalVersion.fromState(self, fetched: fetched)) } if let _ = result.failureValue as? NotFound<HTTPURLResponse> { // OK, this is easy. // This state is responsible for creating the new m/g, uploading it, and // restarting with a clean scratchpad. return deferMaybe(MissingMetaGlobalError(previousState: self)) } // Otherwise, we have a failure state. Die on the sword! return deferMaybe(processFailure(result.failureValue)) } } } open class HasMetaGlobal: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.HasMetaGlobal } class func fromState(_ state: BaseSyncStateWithInfo) -> HasMetaGlobal { return HasMetaGlobal(client: state.client, scratchpad: state.scratchpad, token: state.token, info: state.info) } class func fromState(_ state: BaseSyncStateWithInfo, scratchpad: Scratchpad) -> HasMetaGlobal { return HasMetaGlobal(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info) } override open func advance() -> Deferred<Maybe<SyncState>> { // Check if we have enabled/disabled some engines. if let enginesEnablements = self.scratchpad.enginesEnablements, let oldMetaGlobal = self.scratchpad.global { let (engines, declined) = computeNewEngines(oldMetaGlobal.value.engineConfiguration(), enginesEnablements: enginesEnablements) let newMetaGlobal = MetaGlobal(syncID: oldMetaGlobal.value.syncID, storageVersion: oldMetaGlobal.value.storageVersion, engines: engines, declined: declined) return self.client.uploadMetaGlobal(newMetaGlobal, ifUnmodifiedSince: oldMetaGlobal.timestamp) >>> { self.scratchpad = self.scratchpad.evolve().clearEnginesEnablements().build().checkpoint() return deferMaybe(NeedsFreshMetaGlobal.fromState(self)) } } // Check if crypto/keys is fresh in the cache already. if let keys = self.scratchpad.keys, keys.value.valid { if let cryptoModified = self.info.modified("crypto") { // Both of these are server timestamps. If the record we stored was fetched after the last time the record was modified, as represented by the "crypto" entry in info/collections, and we're fetching from the // same server, then the record must be identical, and we can use it directly. If are ever additional records in the crypto collection, this will fetch keys too frequently. In that case, we should use X-I-U-S and expect some 304 responses. if keys.timestamp >= cryptoModified { log.debug("Cached keys fetched at \(keys.timestamp), newer than server modified \(cryptoModified). Using cached keys.") return deferMaybe(HasFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, collectionKeys: keys.value)) } // The server timestamp is newer, so there might be new keys. // Re-fetch keys and check to see if the actual contents differ. // If the keys are the same, we can ignore this change. If they differ, // we need to re-sync any collection whose keys just changed. log.info("Cached keys fetched at \(keys.timestamp) older than server modified \(cryptoModified). Fetching fresh keys.") return deferMaybe(NeedsFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, staleCollectionKeys: keys.value)) } else { // No known modified time for crypto/. That likely means the server has no keys. // Drop our cached value and fall through; we'll try to fetch, fail, and // go through the usual failure flow. log.warning("Local keys fetched at \(keys.timestamp) found, but no crypto collection on server. Dropping cached keys.") self.scratchpad = self.scratchpad.evolve().setKeys(nil).build().checkpoint() } } else { log.debug("No cached keys found. Fetching fresh keys.") } return deferMaybe(NeedsFreshCryptoKeys.fromState(self, scratchpad: self.scratchpad, staleCollectionKeys: nil)) } } open class NeedsFreshCryptoKeys: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.NeedsFreshCryptoKeys } let staleCollectionKeys: Keys? class func fromState(_ state: BaseSyncStateWithInfo, scratchpad: Scratchpad, staleCollectionKeys: Keys?) -> NeedsFreshCryptoKeys { return NeedsFreshCryptoKeys(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info, keys: staleCollectionKeys) } public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys?) { self.staleCollectionKeys = keys super.init(client: client, scratchpad: scratchpad, token: token, info: info) } override open func advance() -> Deferred<Maybe<SyncState>> { // Fetch crypto/keys. return self.client.getCryptoKeys(self.scratchpad.syncKeyBundle, ifUnmodifiedSince: nil).bind { result in if let resp = result.successValue { let collectionKeys = Keys(payload: resp.value.payload) if !collectionKeys.valid { log.error("Unexpectedly invalid crypto/keys during a successful fetch.") return Deferred(value: Maybe(failure: InvalidKeysError(collectionKeys))) } let fetched = Fetched(value: collectionKeys, timestamp: resp.metadata.timestampMilliseconds) let s = self.scratchpad.evolve() .addLocalCommandsFromKeys(fetched) .setKeys(fetched) .build().checkpoint() return deferMaybe(HasFreshCryptoKeys.fromState(self, scratchpad: s, collectionKeys: collectionKeys)) } if let _ = result.failureValue as? NotFound<HTTPURLResponse> { // No crypto/keys? We can handle this. Wipe and upload both meta/global and crypto/keys. return deferMaybe(MissingCryptoKeysError(previousState: self)) } // Otherwise, we have a failure state. return deferMaybe(processFailure(result.failureValue)) } } } open class HasFreshCryptoKeys: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.HasFreshCryptoKeys } let collectionKeys: Keys class func fromState(_ state: BaseSyncStateWithInfo, scratchpad: Scratchpad, collectionKeys: Keys) -> HasFreshCryptoKeys { return HasFreshCryptoKeys(client: state.client, scratchpad: scratchpad, token: state.token, info: state.info, keys: collectionKeys) } public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys) { self.collectionKeys = keys super.init(client: client, scratchpad: scratchpad, token: token, info: info) } override open func advance() -> Deferred<Maybe<SyncState>> { return deferMaybe(Ready(client: self.client, scratchpad: self.scratchpad, token: self.token, info: self.info, keys: self.collectionKeys)) } } public protocol EngineStateChanges { func collectionsThatNeedLocalReset() -> [String] func enginesEnabled() -> [String] func enginesDisabled() -> [String] func clearLocalCommands() } open class Ready: BaseSyncStateWithInfo { open override var label: SyncStateLabel { return SyncStateLabel.Ready } let collectionKeys: Keys public var hashedFxADeviceID: String { return (scratchpad.fxaDeviceId + token.hashedFxAUID).sha256.hexEncodedString } public var engineConfiguration: EngineConfiguration? { return scratchpad.engineConfiguration } public init(client: Sync15StorageClient, scratchpad: Scratchpad, token: TokenServerToken, info: InfoCollections, keys: Keys) { self.collectionKeys = keys super.init(client: client, scratchpad: scratchpad, token: token, info: info) } } extension Ready: EngineStateChanges { public func collectionsThatNeedLocalReset() -> [String] { var needReset: Set<String> = Set() for command in self.scratchpad.localCommands { switch command { case let .resetAllEngines(except: except): needReset.formUnion(Set(LocalEngines).subtracting(except)) case let .resetEngine(engine): needReset.insert(engine) case .enableEngine, .disableEngine: break } } return Array(needReset).sorted() } public func enginesEnabled() -> [String] { var engines: Set<String> = Set() for command in self.scratchpad.localCommands { switch command { case let .enableEngine(engine): engines.insert(engine) default: break } } return Array(engines).sorted() } public func enginesDisabled() -> [String] { var engines: Set<String> = Set() for command in self.scratchpad.localCommands { switch command { case let .disableEngine(engine): engines.insert(engine) default: break } } return Array(engines).sorted() } public func clearLocalCommands() { self.scratchpad = self.scratchpad.evolve().clearLocalCommands().build().checkpoint() } }
95576508ea423eb748986f5b52de72bd
41.488648
257
0.684673
false
false
false
false
GoogleCloudPlatform/ios-docs-samples
refs/heads/master
speech-to-speech/SpeechToSpeech/ApplicationConstants.swift
apache-2.0
1
// // Copyright 2019 Google Inc. 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 struct ApplicationConstants { static let TTS_Host = "texttospeech.googleapis.com" // TODO: Replace with your GCP PROJECT_ID static let translateParent = "projects/project_id/locations/global" static let languageCode = "en-US" static let STT_Host = "speech.googleapis.com" static let TRANSLATE_Host = "translation.googleapis.com" } extension ApplicationConstants { static let ttsScreenTitle = "Speech-to-Speech Translation" static let SpeechScreenTitle = "Speech-to-Speech Translation" static let SettingsScreenTtitle = "Settings" static let selfKey = "Self" static let botKey = "Bot" static let selectedTransFrom = "selectedTransFrom" static let selectedTransTo = "selectedTransTo" static let selectedVoiceType = "selectedVoiceType" static let selectedSynthName = "selectedSynthName" static let useerLanguagePreferences = "useerLanguagePreferences" static let translateFromPlaceholder = "Translate from" static let translateToPlaceholder = "Translate to" static let synthNamePlaceholder = "TTS Tech" static let voiceTypePlaceholder = "Voice type" } //MARK: Token service constants extension ApplicationConstants { static let token = "Token" static let accessToken = "accessToken" static let expireTime = "expireTime" static let tokenReceived = "tokenReceived" static let retreivingToken = "RetrievingToken" static let getTokenAPI = "getOAuthToken" static let tokenType = "Bearer " static let noTokenError = "No token is available" static let tokenFetchingAlertTitle = "Alert" static let tokenFetchingAlertMessage = "Retrieving token ..." }
fe5ca28aa5f8e30d1280af5dfada7477
36.881356
75
0.765101
false
false
false
false
hustlzp/Observable-Swift-Example
refs/heads/master
Observable-Swift-Example/HorizonalTagListView.swift
mit
1
// // HorizonalTagListView.swift // Face // // Created by hustlzp on 16/1/21. // Copyright © 2016年 hustlzp. All rights reserved. // import UIKit class HorizonalTagListView: UIView { var cornerRadius: CGFloat = 13.0 var textColor = UIColor(hexValue: 0x808393FF) var selectedTextColor = UIColor(hexValue: 0x808393FF) var paddingX: CGFloat = 9.5 var paddingY: CGFloat = 5.5 var tagBackgroundColor = UIColor(hexValue: 0xF3F3F9FF) var tagSelectedBackgroundColor = UIColor(hexValue: 0xF3F3F9FF).darker(0.1) var textFont = UIFont.systemFontOfSize(13.5) var marginX: CGFloat = 8.0 private var tagViews = [TagView]() private var width: CGFloat = 0 private var height: CGFloat = 0 func addTag(title: String) -> TagView { let tagView = TagView(title: title) tagView.textColor = textColor tagView.selectedTextColor = selectedTextColor tagView.tagBackgroundColor = tagBackgroundColor tagView.tagSelectedBackgroundColor = tagSelectedBackgroundColor tagView.cornerRadius = cornerRadius tagView.paddingY = paddingY tagView.paddingX = paddingX tagView.textFont = textFont tagViews.append(tagView) rearrangeViews() return tagView } override func layoutSubviews() { super.layoutSubviews() rearrangeViews() } override func intrinsicContentSize() -> CGSize { return CGSize(width: width, height: height) } // Public Methods func updateTags(tags: [String]) { removeAllTags() tags.forEach { addTag($0) } } func removeAllTags() { for tagView in tagViews { tagView.removeFromSuperview() } tagViews.removeAll() rearrangeViews() } func removeTag(index: Int) { if index < 0 || index > tagViews.count { return } tagViews[index].removeFromSuperview() tagViews.removeAtIndex(index) rearrangeViews() } func prepareRemoveTag(index: Int) { if index < 0 || index > tagViews.count { return } tagViews[index].backgroundColor = tagSelectedBackgroundColor } func cancelPrepareRemoveTag() { for tagView in tagViews { tagView.backgroundColor = tagBackgroundColor } } // Internal Helpers private func rearrangeViews() { width = 0 height = 0 for tagView in tagViews { tagView.removeFromSuperview() } for tagView in tagViews { let tagViewWidth = tagView.intrinsicContentSize().width let tagViewHeight = tagView.intrinsicContentSize().height var tagViewX: CGFloat if width == 0 { tagViewX = 0 } else { tagViewX = width + marginX } tagView.frame = CGRectMake(tagViewX, 0, tagViewWidth, tagViewHeight) addSubview(tagView) if tagViewHeight > height { height = tagViewHeight } width = tagViewX + tagViewWidth } invalidateIntrinsicContentSize() } }
cb2dbcac9b37134d37bcdee9d50008d3
25.007692
80
0.575274
false
false
false
false
EvsenevDev/SmartReceiptsiOS
refs/heads/master
SmartReceipts/Common/Exchange/ExchangeRateCalculator.swift
agpl-3.0
2
// // ExchangeRateCalculator.swift // SmartReceipts // // Created by Bogdan Evsenev on 19/07/2019. // Copyright © 2019 Will Baumann. All rights reserved. // import Foundation import RxSwift class ExchangeRateCalculator { let exchangeRateUpdate = PublishSubject<Double>() let baseCurrencyPriceUpdate = PublishSubject<Double>() private let bag = DisposeBag() init(price: Double = 0, exchangeRate: Double = 0) { self.price = price self.exchangeRate = exchangeRate } var price: Double = 0 { didSet { let result = price*exchangeRate baseCurrencyPriceUpdate.onNext(result) } } var exchangeRate: Double = 0 { didSet { let result = price*exchangeRate baseCurrencyPriceUpdate.onNext(result) } } var baseCurrencyPrice: Double = 0 { didSet { if price == 0 { return } let result = baseCurrencyPrice/price exchangeRateUpdate.onNext(result) } } }
5a9dd3ca58b761f1cfd4c6fef535f0de
23.44186
58
0.604186
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Plans/FeatureItemCell.swift
gpl-2.0
2
import UIKit import WordPressShared class FeatureItemCell: WPTableViewCell { @IBOutlet weak var featureTitleLabel: UILabel! @IBOutlet weak var featureDescriptionLabel: UILabel! @IBOutlet weak var separator: UIView! @IBOutlet var separatorEdgeConstraints: [NSLayoutConstraint]! override var separatorInset: UIEdgeInsets { didSet { for constraint in separatorEdgeConstraints { if constraint.firstAttribute == .leading { constraint.constant = separatorInset.left } else if constraint.firstAttribute == .trailing { constraint.constant = separatorInset.right } } separator.layoutIfNeeded() } } override func awakeFromNib() { super.awakeFromNib() layoutMargins = UIEdgeInsets.zero configureAppearance() } private func configureAppearance() { separator.heightAnchor.constraint(equalToConstant: .hairlineBorderWidth).isActive = true separator.backgroundColor = .divider featureTitleLabel.textColor = .primary featureDescriptionLabel.textColor = .text } override func prepareForReuse() { super.prepareForReuse() separator.isHidden = false featureTitleLabel.text = nil featureDescriptionLabel.text = nil } override func layoutSubviews() { super.layoutSubviews() // This is required to fix an issue where only the first line of text would // is displayed on the iPhone 6(s) Plus due to a fractional Y position. featureDescriptionLabel.frame = featureDescriptionLabel.frame.integral } }
a5e5c9b46e52f7f6f6276d79219e0f9a
29.428571
96
0.658451
false
false
false
false
instacrate/tapcrate-api
refs/heads/master
Sources/api/Collections/TagCollection.swift
mit
1
// // TagCollection.swift // tapcrate-api // // Created by Hakon Hanesand on 6/3/17. // // import HTTP import Vapor import Fluent final class TagCollection: EmptyInitializable { required init() { } typealias Wrapped = HTTP.Responder func build(_ builder: RouteBuilder) { builder.group("products") { products in products.post(Product.parameter, "tags") { request in let product: Product = try request.parameters.next() let delete = request.query?["delete"]?.bool ?? false let rawTags = request.json if (delete) { try product.tags().all().forEach { try product.tags().remove($0) } } let tags: [Tag] if let _tagIds: [Int]? = try? rawTags?.array?.converted(in: emptyContext), let tagIds = _tagIds { let ids = try tagIds.converted(to: Array<Node>.self, in: jsonContext) tags = try Tag.makeQuery().filter(.subset(Tag.idKey, .in, ids)).all() } else if let _tags: [Node] = rawTags?.node.array { tags = try _tags.map { let tag = try Tag(node: $0) try tag.save() return tag } } else { throw Abort.custom(status: .badRequest, message: "Invalid json, must be array of new tags to create, or array of existing tag_ids") } try tags.forEach { try product.tags().add($0) } return try product.tags().all().makeResponse() } products.post(Product.parameter, "tags", Tag.parameter) { request in let product: Product = try request.parameters.next() let tag: Tag = try request.parameters.next() guard try product.maker_id == request.maker().id() else { throw Abort.custom(status: .unauthorized, message: "Can not modify another user's product.") } try Pivot<Tag, Product>.attach(tag, product) return try product.tags().all().makeResponse() } products.delete(Product.parameter, "tags", Tag.parameter) { request in let product: Product = try request.parameters.next() let tag: Tag = try request.parameters.next() guard try product.maker_id == request.maker().id() else { throw Abort.custom(status: .unauthorized, message: "Can not modify another user's product.") } try Pivot<Tag, Product>.detach(tag, product) return try product.tags().all().makeResponse() } } } }
efa2e10df40e6797a5c92fef93463119
36.119048
151
0.471777
false
false
false
false
ushisantoasobu/Busquets
refs/heads/master
Example/BusquetsSample/ViewController.swift
mit
1
// // ViewController.swift // BusquetsSample // // Created by SatoShunsuke on 2015/11/29. // Copyright © 2015年 moguraproject. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! private let list = [ "http://soccerking.s3.amazonaws.com/wp-content/uploads/2014/08/get20140809_00010-500x333.jpg", "http://images.performgroup.com/di/library/Goal_Thailand/67/a/sergio-busquets_1tswa70lsd9jc1lepz0ewn6ilv.jpg?t=2012143044&w=620&h=430", "http://www.footballchannel.jp/wordpress/assets/2014/12/20141209_sergi_getty-560x373.jpg", "http://www.footballista.jp/wp-content/uploads/2015/02/460714026_news_Busquets.jpg", "http://www.soccerdigestweb.com/files/topics/12274_ext_04_0.jpg", "http://soccerking.s3.amazonaws.com/wp-content/uploads/2013/01/0067.jpg", "http://media2.fcbarcelona.com/media/asset_publics/resources/000/186/697/size_640x360/2015-09-26_BARCELONA-LAS_PALMAS_09-Optimized.v1443287579.JPG", "http://media3.fcbarcelona.com/media/asset_publics/resources/000/066/616/size_640x360/2013-09-14_BARCELONA-SEVILLA_02.v1379235220.JPG", "http://afpbb.ismcdn.jp/mwimgs/f/f/500x400/img_ffb636531d12bd42cdc24b8dd7ace131111641.jpg", "http://4.bp.blogspot.com/-N9HrKmHQgsk/UZjdHCcQJEI/AAAAAAAACUE/xUwLAQFJgWM/s1600/Sergio-Busquets-Barcelona-v.-Club-America-8-6-11-7.jpg", "http://static.goal.com/219900/219952.jpg" ] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.tableView.delegate = self self.tableView.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - private func getView(nibName :String) -> UIView { let nib = UINib(nibName: nibName, bundle: nil) var views = nib.instantiateWithOwner(self, options: nil) return views[0] as! UIView } // MARK: - UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.list.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.getView("ImageTableViewCell") as! ImageTableViewCell cell.setCustomImageUrlString(list[indexPath.row]) return cell } // MARK: - UITableViewDelegate func tableView(tableView:UITableView, heightForRowAtIndexPath indexPath:NSIndexPath)->CGFloat { return 240 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // } }
c3d9745ed578266d21bc4ad7fa4e24f9
38.013514
156
0.697956
false
false
false
false
dcutting/song
refs/heads/master
Sources/Song/Interpreter/BuiltIns.swift
mit
1
func evaluateEq(arguments: [Expression], context: Context) throws -> Expression { guard arguments.count == 2 else { throw EvaluationError.signatureMismatch(arguments) } let result: Expression do { result = try booleanOp(arguments: arguments, context: context) { .bool($0 == $1) } } catch EvaluationError.notABoolean { do { result = try numberOp(arguments: arguments, context: context) { try .bool($0.equalTo($1)) } } catch EvaluationError.notANumber { do { result = try characterOp(arguments: arguments, context: context) { .bool($0 == $1) } } catch EvaluationError.notACharacter { result = try listOp(arguments: arguments, context: context) { left, right in guard left.count == right.count else { return .no } for (l, r) in zip(left, right) { let lrEq = try evaluateEq(arguments: [l, r], context: context) if case .no = lrEq { return .no } } return .yes } // TODO: need propr equality check for listCons too. } } } return result } func evaluateNeq(arguments: [Expression], context: Context) throws -> Expression { let equalCall = Expression.call("Eq", arguments) let notCall = Expression.call("Not", [equalCall]) return try notCall.evaluate(context: context) } func evaluateNot(arguments: [Expression], context: Context) throws -> Expression { var bools = try toBools(arguments: arguments, context: context) guard bools.count == 1 else { throw EvaluationError.signatureMismatch(arguments) } let left = bools.removeFirst() return .bool(!left) } func evaluateAnd(arguments: [Expression], context: Context) throws -> Expression { var bools = try toBools(arguments: arguments, context: context) guard bools.count == 2 else { throw EvaluationError.signatureMismatch(arguments) } let left = bools.removeFirst() let right = bools.removeFirst() return .bool(left && right) } func evaluateOr(arguments: [Expression], context: Context) throws -> Expression { var bools = try toBools(arguments: arguments, context: context) guard bools.count == 2 else { throw EvaluationError.signatureMismatch(arguments) } let left = bools.removeFirst() let right = bools.removeFirst() return .bool(left || right) } func evaluateNumberConstructor(arguments: [Expression], context: Context) throws -> Expression { var numbers = arguments guard numbers.count == 1 else { throw EvaluationError.signatureMismatch(arguments) } let left = numbers.removeFirst() let result: Expression do { let string = try left.evaluate(context: context).asString() let number = try Number.convert(from: string) result = .number(number) } catch EvaluationError.numericMismatch { throw EvaluationError.notANumber(left) } return result } func evaluateStringConstructor(arguments: [Expression], context: Context) throws -> Expression { let output = try prepareOutput(for: arguments, context: context) return .string(output) } func evaluateTruncateConstructor(arguments: [Expression], context: Context) throws -> Expression { var numbers = try toNumbers(arguments: arguments, context: context) guard numbers.count == 1 else { throw EvaluationError.signatureMismatch(arguments) } let left = numbers.removeFirst() return .number(left.truncate()) } func evaluatePlus(arguments: [Expression], context: Context) throws -> Expression { guard arguments.count == 2 else { throw EvaluationError.signatureMismatch(arguments) } let result: Expression do { result = try numberOp(arguments: arguments, context: context) { .number($0.plus($1)) } } catch EvaluationError.notANumber { result = try listOp(arguments: arguments, context: context) { .list($0 + $1) } } return result } func evaluateMinus(arguments: [Expression], context: Context) throws -> Expression { var numbers = try toNumbers(arguments: arguments, context: context) let result: Expression if numbers.count == 1 { let right = numbers.removeFirst() result = .number(right.negate()) } else if numbers.count == 2 { let left = numbers.removeFirst() let right = numbers.removeFirst() result = .number(left.minus(right)) } else { throw EvaluationError.signatureMismatch(arguments) } return result } func evaluateTimes(arguments: [Expression], context: Context) throws -> Expression { var numbers = try toNumbers(arguments: arguments, context: context) guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) } let left = numbers.removeFirst() let right = numbers.removeFirst() return .number(left.times(right)) } func evaluateDividedBy(arguments: [Expression], context: Context) throws -> Expression { var numbers = try toNumbers(arguments: arguments, context: context) guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) } let left = numbers.removeFirst() let right = numbers.removeFirst() return .number(left.floatDividedBy(right)) } func evaluateMod(arguments: [Expression], context: Context) throws -> Expression { var numbers = try toNumbers(arguments: arguments, context: context) guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) } let left = numbers.removeFirst() let right = numbers.removeFirst() return .number(try left.modulo(right)) } func evaluateDiv(arguments: [Expression], context: Context) throws -> Expression { var numbers = try toNumbers(arguments: arguments, context: context) guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) } let left = numbers.removeFirst() let right = numbers.removeFirst() return .number(try left.integerDividedBy(right)) } func evaluateLessThan(arguments: [Expression], context: Context) throws -> Expression { var numbers = try toNumbers(arguments: arguments, context: context) guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) } let left = numbers.removeFirst() let right = numbers.removeFirst() return .bool(left.lessThan(right)) } func evaluateGreaterThan(arguments: [Expression], context: Context) throws -> Expression { var numbers = try toNumbers(arguments: arguments, context: context) guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) } let left = numbers.removeFirst() let right = numbers.removeFirst() return .bool(left.greaterThan(right)) } func evaluateLessThanOrEqual(arguments: [Expression], context: Context) throws -> Expression { var numbers = try toNumbers(arguments: arguments, context: context) guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) } let left = numbers.removeFirst() let right = numbers.removeFirst() return .bool(left.lessThanOrEqualTo(right)) } func evaluateGreaterThanOrEqual(arguments: [Expression], context: Context) throws -> Expression { var numbers = try toNumbers(arguments: arguments, context: context) guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) } let left = numbers.removeFirst() let right = numbers.removeFirst() return .bool(left.greaterThanOrEqualTo(right)) } func evaluateIn(arguments: [Expression], context: Context) throws -> Expression { let evaluated = try arguments.map { expr -> Expression in try expr.evaluate(context: context) } let output = evaluated.map { $0.out() }.joined(separator: " ") _stdOut.put(output) let line = _stdIn.get() ?? "" return .string(line) } func evaluateOut(arguments: [Expression], context: Context) throws -> Expression { let output = try prepareOutput(for: arguments, context: context) _stdOut.put(output + "\n") return .string(output) } func evaluateErr(arguments: [Expression], context: Context) throws -> Expression { let output = try prepareOutput(for: arguments, context: context) _stdErr.put(output + "\n") return .string(output) } /* Helpers. */ private func prepareOutput(for arguments: [Expression], context: Context) throws -> String { let evaluated = try arguments.map { expr -> Expression in try expr.evaluate(context: context) } return evaluated.map { $0.out() }.joined(separator: " ") } private func extractNumber(_ expression: Expression, context: Context) throws -> Number { if case .number(let number) = try expression.evaluate(context: context) { return number } throw EvaluationError.notANumber(expression) } private func extractBool(_ expression: Expression, context: Context) throws -> Bool { if case .bool(let value) = try expression.evaluate(context: context) { return value } throw EvaluationError.notABoolean(expression) } private func extractCharacter(_ expression: Expression, context: Context) throws -> Character { if case .char(let value) = try expression.evaluate(context: context) { return value } throw EvaluationError.notACharacter } private func extractList(_ expression: Expression, context: Context) throws -> [Expression] { if case .list(let list) = try expression.evaluate(context: context) { return list } throw EvaluationError.notAList(expression) } private func toNumbers(arguments: [Expression], context: Context) throws -> [Number] { return try arguments.map { arg -> Number in let evaluatedArg = try arg.evaluate(context: context) guard case let .number(n) = evaluatedArg else { throw EvaluationError.notANumber(evaluatedArg) } return n } } private func toBools(arguments: [Expression], context: Context) throws -> [Bool] { return try arguments.map { arg -> Bool in let evaluatedArg = try arg.evaluate(context: context) guard case let .bool(n) = evaluatedArg else { throw EvaluationError.notABoolean(evaluatedArg) } return n } } private func numberOp(arguments: [Expression], context: Context, callback: (Number, Number) throws -> Expression) throws -> Expression { var numbers = arguments let left = try extractNumber(numbers.removeFirst(), context: context) let right = try extractNumber(numbers.removeFirst(), context: context) return try callback(left, right) } private func booleanOp(arguments: [Expression], context: Context, callback: (Bool, Bool) throws -> Expression) throws -> Expression { var bools = arguments let left = try extractBool(bools.removeFirst(), context: context) let right = try extractBool(bools.removeFirst(), context: context) return try callback(left, right) } private func characterOp(arguments: [Expression], context: Context, callback: (Character, Character) throws -> Expression) throws -> Expression { var chars = arguments let left = try extractCharacter(chars.removeFirst(), context: context) let right = try extractCharacter(chars.removeFirst(), context: context) return try callback(left, right) } private func listOp(arguments: [Expression], context: Context, callback: ([Expression], [Expression]) throws -> Expression) throws -> Expression { var lists = arguments let left = try extractList(lists.removeFirst(), context: context) let right = try extractList(lists.removeFirst(), context: context) return try callback(left, right) }
ee43a5146a16966a1cbe7ececea35ed7
39.831034
146
0.683726
false
false
false
false
vmanot/swift-package-manager
refs/heads/master
Tests/UtilityTests/ProgressBarTests.swift
apache-2.0
1
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import Utility import libc @testable import Basic typealias Thread = Basic.Thread // FIXME: Copied from BasicTests, move to TestSupport once available. final class PseudoTerminal { let master: Int32 let slave: Int32 var outStream: LocalFileOutputByteStream init?(){ var master: Int32 = 0 var slave: Int32 = 0 if openpty(&master, &slave, nil, nil, nil) != 0 { return nil } guard let outStream = try? LocalFileOutputByteStream(filePointer: fdopen(slave, "w"), closeOnDeinit: false) else { return nil } self.outStream = outStream self.master = master self.slave = slave } func readMaster(maxChars n: Int = 1000) -> String? { var buf: [CChar] = [CChar](repeating: 0, count: n) if read(master, &buf, n) <= 0 { return nil } return String(cString: buf) } func closeSlave() { _ = libc.close(slave) } func closeMaster() { _ = libc.close(master) } } final class ProgressBarTests: XCTestCase { func testProgressBar() { guard let pty = PseudoTerminal() else { XCTFail("Couldn't create pseudo terminal.") return } // Test progress bar when writing to a non tty stream. let outStream = BufferedOutputByteStream() var bar = createProgressBar(forStream: outStream, header: "test") XCTAssertTrue(bar is SimpleProgressBar) runProgressBar(bar) XCTAssertEqual(outStream.bytes.asString, """ test 0%: 0 1%: 1 2%: 2 3%: 3 4%: 4 5%: 5 """) // Test progress bar when writing a tty stream. bar = createProgressBar(forStream: pty.outStream, header: "TestHeader") XCTAssertTrue(bar is ProgressBar) var output = "" let thread = Thread { while let out = pty.readMaster() { output += out } } thread.start() runProgressBar(bar) pty.closeSlave() // Make sure to read the complete output before checking it. thread.join() pty.closeMaster() XCTAssertTrue(output.chuzzle()?.hasPrefix("\u{1B}[36m\u{1B}[1mTestHeader\u{1B}[0m") ?? false) } private func runProgressBar(_ bar: ProgressBarProtocol) { for i in 0...5 { bar.update(percent: i, text: String(i)) } bar.complete() } static var allTests = [ ("testProgressBar", testProgressBar), ] }
ae36595e596f8e1050a54cbb4c775cca
26.481481
122
0.582547
false
true
false
false
imitationgame/pokemonpassport
refs/heads/master
pokepass/View/Main/Generic/VMainLoader.swift
mit
1
import UIKit class VMainLoader:UIImageView { private let kAnimationDuration:TimeInterval = 0.66 init() { super.init(frame:CGRect.zero) let images:[UIImage] = [ UIImage(named:"loader0")!, UIImage(named:"loader1")!, UIImage(named:"loader2")!, UIImage(named:"loader3")!, UIImage(named:"loader4")!, UIImage(named:"loader5")!, UIImage(named:"loader6")!, UIImage(named:"loader7")!, UIImage(named:"loader8")!, UIImage(named:"loader9")! ] isUserInteractionEnabled = false translatesAutoresizingMaskIntoConstraints = false clipsToBounds = true animationDuration = kAnimationDuration animationImages = images contentMode = UIViewContentMode.center startAnimating() } required init?(coder aDecoder:NSCoder) { fatalError() } }
698eb50fe9ee9d561cd523aaca8209b1
25.026316
57
0.559151
false
false
false
false
niklaskorz/WeathIt
refs/heads/master
WeathIt/ForecastDataSource.swift
mit
1
// // DataSource.swift // WeathIt // // Created by Niklas Korz on 13/10/17. // Copyright © 2017 Niklas Korz. All rights reserved. // import UIKit // DataSource for the weather forecast table class ForecastDataSource: NSObject, UITableViewDataSource { let dateFormatter = DateFormatter() var weatherList: [Weather] = [] override init() { dateFormatter.dateFormat = "dd.MM.yyyy HH" } func update(forecast: [Weather]) { weatherList = forecast } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return weatherList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: ForecastTableViewCell.identifier, for: indexPath) as! ForecastTableViewCell let weather = weatherList[indexPath.row] cell.iconImageView.image = UIImage(named: weather.icon) let date = Date(timeIntervalSince1970: TimeInterval(weather.timestamp)) cell.dateLabel.text = dateFormatter.string(from: date) + " Uhr" cell.degreesLabel.text = "\(weather.degrees)°C" cell.descriptionLabel.text = weather.description return cell } }
0599c823fe31877cc95639b0bd089545
28.957447
140
0.662642
false
false
false
false
aleph7/BrainCore
refs/heads/master
Source/NetNode.swift
mit
1
// Copyright © 2015 Venture Media Labs. All rights reserved. // // This file is part of BrainCore. The full BrainCore copyright notice, // including terms governing use, modification, and redistribution, is // contained in the file LICENSE at the root of the source code distribution // tree. /// A network definition node. class NetNode: Hashable { let layer: Layer weak var inputBuffer: NetBuffer? var inputRange: Range<Int> = 0..<0 weak var outputBuffer: NetBuffer? var outputRange: Range<Int> = 0..<0 var inputSize: Int { if let forwardLayer = layer as? ForwardLayer { return forwardLayer.inputSize } else if let sinkLayer = layer as? SinkLayer { return sinkLayer.inputSize } return 0 } var outputSize: Int { if let forwardLayer = layer as? ForwardLayer { return forwardLayer.outputSize } else if let dataLayer = layer as? DataLayer { return dataLayer.outputSize } return 0 } init(layer: Layer) { self.layer = layer } var hashValue: Int { return layer.id.hashValue } } func ==(lhs: NetNode, rhs: NetNode) -> Bool { return lhs.layer.id == rhs.layer.id } class WeakNetNode { weak var node: NetNode! init(_ node: NetNode) { self.node = node } }
216511315b4b6976a540466df37e3b2d
24.166667
76
0.62546
false
false
false
false
apple/swift
refs/heads/main
test/expr/delayed-ident/enum.swift
apache-2.0
4
// RUN: %target-typecheck-verify-swift // Simple enumeration type enum E1 { case First case Second(Int) case Third(Int, Double) case `default` } var e1: E1 = .First e1 = .Second(5) e1 = .Third(5, 3.14159) e1 = .default // SE-0071 // Generic enumeration type enum E2<T> { // expected-note {{'T' declared as parameter to type 'E2'}} case First case Second(T) } var e2a: E2<Int> = .First e2a = .Second(5) var e2b: E2 = .Second(5) e2b = .First var e2c: E2 = .First // expected-error{{generic parameter 'T' could not be inferred}} // https://github.com/apple/swift/issues/55797 struct S_55797 {} extension Optional where Wrapped == S_55797 { static var v55797: Self { .none } } func f_55797<T>(_: T?) { } f_55797(.v55797)
8ab39fbfb0439a02b2374fe5acd6616a
18.552632
85
0.652759
false
false
false
false
taylorguo/douyuZB
refs/heads/master
douyuzb/douyuzb/Classes/Home/PageTitleView.swift
mit
1
// // PageTitleView.swift // douyuzb // // Created by mac on 2017/10/23. // Copyright © 2017年 mac. All rights reserved. // import UIKit //MARK:- 定义协议 protocol PageTitleViewDelegate : class { func pageTitleView(titleView: PageTitleView, selectedIndex index : Int) } //MARK:- 定义常量 private let kScrollLineHeight : CGFloat = 2 private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85) private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0) class PageTitleView: UIView { //MARK:- 定义属性 private var currentIndex : Int = 0 private var titles: [String] weak var delegate :PageTitleViewDelegate? // 懒加载ScrollView private lazy var titleLabels : [UILabel] = [UILabel]() private lazy var scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.isPagingEnabled = false scrollView.bounces = false return scrollView }() private lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() //MARK:- 自定义构造函数 init(frame: CGRect, titles: [String]) { self.titles = titles super.init(frame: frame) //设置UI界面 setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageTitleView{ private func setupUI(){ // 1. 添加UIScrollView addSubview(scrollView) scrollView.frame = bounds // 2. 添加title对应的Label setupTitleLabels() // 3. 设置底线和滚动滑块 setupBottomLineAndScrollLine() } private func setupTitleLabels(){ // 0. 确定label frame的部分值 let labelWidth : CGFloat = frame.width / CGFloat(titles.count) let labelHeight : CGFloat = frame.height - kScrollLineHeight let labelY: CGFloat = 0 for (index, title) in titles.enumerated() { // 0.不需要调整UIScrollView 内边距 // scrollView.scrollIndicatorInsets //1. 创建UILabel let label = UILabel() //2. 设置label的属性 label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16.0) label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) label.textAlignment = .center // 3. 设置label frame let labelX : CGFloat = labelWidth * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelWidth, height: labelHeight) // 4. 将label 添加到scrollView scrollView.addSubview(label) titleLabels.append(label) // 5. 给Label添加手势 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:))) label.addGestureRecognizer(tapGes) } } private func setupBottomLineAndScrollLine() { // 1. 添加底线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineHeight : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineHeight, width: frame.width, height: lineHeight) addSubview(bottomLine) // 2. 添加scrollLine // 2.1 获取第一个label guard let firstLabel = titleLabels.first else {return} firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) // 2.2 设置ScrollLine的属性 scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineHeight, width: firstLabel.frame.width, height: kScrollLineHeight) } } //MARK:- 监听Label点击 extension PageTitleView{ @objc private func titleLabelClick(tapGes : UITapGestureRecognizer){ // 1. 获取当前label下标值 guard let currentLabel = tapGes.view as? UILabel else {return} // 2. 获取之前的Label let oldLabel = titleLabels[currentIndex] // 3. 切换文字颜色 currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) // 4. 保存最新Label下标值 currentIndex = currentLabel.tag // 5. 滚动条位置发生改变 let scrollLineX = CGFloat(currentIndex) * scrollLine.frame.width UIView.animate(withDuration: 0.15) { self.scrollLine.frame.origin.x = scrollLineX } // 6. 通知代理 delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex) } } //MARK:- 对外暴露方法 extension PageTitleView{ func setTitleWithProgress(progress: CGFloat, sourceIndex: Int, targetIndex: Int){ //1.取出sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] //2.处理滑块逻辑 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX //3.颜色的渐变 //3.1取出变化的范围 let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2) //3.2变化sourceLabel sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress) //3.3变化targetLabel targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) //4.记录最新的index currentIndex = targetIndex } }
3fe127de779f622f4afea7375ca2d24e
30.891753
174
0.606756
false
false
false
false
NoryCao/SwiftExtension
refs/heads/master
SwiftExtension/UIView+QSExtension.swift
mit
1
// // UIView+QSExtension.swift // SwiftExtension // // Created by Nory Cao on 2017/7/13. // Copyright © 2017年 QS. All rights reserved. // import Foundation import UIKit extension UIView { //MARK: - 截屏 func qs_screenShot()->UIImage?{ let size = self.bounds.size let transform:CGAffineTransform = __CGAffineTransformMake(-1, 0, 0, 1, size.width, 0) UIGraphicsBeginImageContextWithOptions(size, self.isOpaque, 0.0) let context = UIGraphicsGetCurrentContext() context?.concatenate(transform) self.layer.render(in: context!) let image:UIImage? = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func qs_nextController()->UIViewController?{ var nextResponder:UIResponder? = self.next while (nextResponder != nil) { if nextResponder?.isKind(of: UIViewController.self) == true { return nextResponder as? UIViewController } nextResponder = nextResponder?.next } return nil } }
02e8fdbde5d61562107f6b9d33833e2f
29.472222
93
0.639015
false
false
false
false
ioveracker/WebIOPiSwift
refs/heads/master
WebIOPi/Classes/Function.swift
mit
1
import Foundation /// Pin function options. public enum Function { /// Input case `in` /// Output case out case alt0 /// Returns all of the available Function cases. public static var all: [Function] { return [.in, .out, .alt0] } /// Attempts to create a Function from the given string. /// /// - parameter string: The string representing a Function. public static func makeFromString(string: String) -> Function? { if string == "IN" { return .in } else if string == "OUT" { return .out } else if string == "ALT0" { return .alt0 } return nil } }
449719888e48538ff78db35f5974987f
19.294118
68
0.546377
false
false
false
false
krimpedance/KRProgressHUD
refs/heads/master
KRProgressHUD/Classes/Extensions.swift
mit
1
// // Extensions.swift // KRProgressHUD // // Copyright © 2017 Krimpedance. All rights reserved. // import UIKit // MARK: - UIApplication extension ------------ extension UIApplication { func topViewController(_ base: UIViewController? = nil) -> UIViewController? { let base = base ?? keyWindow?.rootViewController if let top = (base as? UINavigationController)?.topViewController { return topViewController(top) } if let selected = (base as? UITabBarController)?.selectedViewController { return topViewController(selected) } if let presented = base?.presentedViewController { return topViewController(presented) } return base } } // MARK: - NSLayoutConstraint extension ------------ extension NSLayoutConstraint { convenience init(item view1: Any, attribute attr1: NSLayoutConstraint.Attribute, relatedBy relation: NSLayoutConstraint.Relation = .equal, toItem view2: Any? = nil, attribute attr2: NSLayoutConstraint.Attribute? = nil, constant: CGFloat = 0) { self.init(item: view1, attribute: attr1, relatedBy: relation, toItem: view2, attribute: attr2 ?? attr1, multiplier: 1.0, constant: constant) } }
54355b5f0155a0fc194bd97ea7ad30df
35.352941
247
0.675566
false
false
false
false
CLCreate/CLCDrag
refs/heads/master
DragComponent/DragComponent/DragComponent/BookShelfView.swift
mit
1
// // BookShelfView.swift // DragComponent // // Created by 陈 龙 on 16/1/23. // Copyright © 2016年 陈 龙. All rights reserved. // import UIKit class BookShelfView: UICollectionView{ // MARK: Properties let kBookShelfReuseIdentifier = "BookShelfCell" private lazy var dataSrc : CollectionViewDataSource = { var items : [Int] = [] for i in 0...23{ items.append(i) } let dataSource = CollectionViewDataSource(datas: items, identifier : "BookShelfCell") return dataSource }() // MARK: UICollectionView override override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) setupBookShelf() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupBookShelf() } // MARK: Private Methods private func setupBookShelf(){ // register cell self.registerNib(UINib(nibName: "BookShelfCell", bundle: nil), forCellWithReuseIdentifier: kBookShelfReuseIdentifier) // setup dataSource dataSource = dataSrc setupUI() } private func setupUI(){ contentInset = UIEdgeInsetsMake(20, 20, 20, 20) } } // MARK: - CLCDragFlowLayoutDelegate extension BookShelfView : CLCDragFlowLayoutDelegate{ func collectionView(collectionView : UICollectionView, moveCell fromIndexPath : NSIndexPath, toIndexPath : NSIndexPath){ let data = dataSrc.cellDatas?.removeAtIndex(fromIndexPath.item) dataSrc.cellDatas?.insert(data!, atIndex: toIndexPath.item) } }
e20a7ef7f65f02d0a2e9cf65abc56aa6
24.656716
125
0.638743
false
false
false
false
PiXeL16/MealPlanExchanges
refs/heads/master
MealPlanExchanges/Model/FoodGroup.swift
mit
1
// // FoodGroup.swift // MealPlanExchanges // // Created by Chris Jimenez on 6/2/16. // Copyright © 2016 Chris Jimenez. All rights reserved. // import UIKit /** * Represents a food group and the quantity that the food group has */ public struct FoodGroup { public var quantity: Double = 0 public var group: FoodTypes = FoodTypes.Other /** Initializer of the quantity and the group that the quantity is assign - parameter quantity: <#quantity description#> - parameter group: <#group description#> - returns: <#return value description#> */ init(quantity: Double = 0, group: FoodTypes = FoodTypes.Other){ self.quantity = quantity self.group = group } }
1de1aa0ded82efc68117e91b80cab0d8
21.878788
74
0.635762
false
false
false
false
Eonil/EditorLegacy
refs/heads/trial1
Modules/EditorUIComponents/WorkbenchForIconPreview/AppDelegate.swift
mit
1
// // AppDelegate.swift // WorkbenchForIconPreview // // Created by Hoon H. on 2015/02/21. // Copyright (c) 2015 Eonil. All rights reserved. // import Cocoa import EditorUIComponents @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! func applicationDidFinishLaunching(aNotification: NSNotification) { // let ch = UnicodeScalar(0xf06a) // let f = NSFont(name: "FontAwesome", size: 128)! // let m = IconUtility.vectorIconForCharacter(ch, font: f) let mv = NSImageView() mv.image = IconPalette.FontAwesome.WebApplicationIcons.exclamationCircle.image mv.wantsLayer = true mv.layer!.backgroundColor = NSColor.brownColor().CGColor window.contentView = mv } }
b670e89f11a8d75af248cec321fb3dd0
16.088889
84
0.717815
false
false
false
false
magnetsystems/message-samples-ios
refs/heads/master
QuickStart/Pods/MagnetMaxCore/MagnetMax/Core/MMUser.swift
apache-2.0
1
/* * Copyright (c) 2015 Magnet Systems, Inc. * 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 @objc public protocol MMUserDelegate { static func overrideCompletion(completion:((error: NSError?) -> Void), error:NSError?, context:String) } public extension MMUser { /// The currently logged-in user or nil. static private var currentlyLoggedInUser: MMUser? @nonobjc static public var delegate : MMUserDelegate.Type? /** Registers a new user. - Parameters: - success: A block object to be executed when the registration finishes successfully. This block has no return value and takes one argument: the newly created user. - failure: A block object to be executed when the registration finishes with an error. This block has no return value and takes one argument: the error object. */ public func register(success: ((user: MMUser) -> Void)?, failure: ((error: NSError) -> Void)?) { assert(!userName.isEmpty && !password.isEmpty, "userName or password cannot be empty") MMCoreConfiguration.serviceAdapter.registerUser(self, success: { user in success?(user: user) }) { error in failure?(error: error) }.executeInBackground(nil) } /** Logs in as an user. - Parameters: - credential: A credential object containing the user's userName and password. - success: A block object to be executed when the login finishes successfully. This block has no return value and takes no arguments. - failure: A block object to be executed when the login finishes with an error. This block has no return value and takes one argument: the error object. */ static public func login(credential: NSURLCredential, success: (() -> Void)?, failure: ((error: NSError) -> Void)?) { login(credential, rememberMe: false, success: success, failure: failure) } /** Logs in as an user. - Parameters: - credential: A credential object containing the user's userName and password. - rememberMe: A boolean indicating if the user should stay logged in across app restarts. - success: A block object to be executed when the login finishes successfully. This block has no return value and takes no arguments. - failure: A block object to be executed when the login finishes with an error. This block has no return value and takes one argument: the error object. */ static public func login(credential: NSURLCredential, rememberMe: Bool, success: (() -> Void)?, failure: ((error: NSError) -> Void)?) { let loginClosure : () -> Void = { () in MMCoreConfiguration.serviceAdapter.loginWithUsername(credential.user, password: credential.password, rememberMe: rememberMe, success: { _ in // Get current user now MMCoreConfiguration.serviceAdapter.getCurrentUserWithSuccess({ user -> Void in // Reset the state userTokenExpired(nil) currentlyLoggedInUser = user let userInfo = ["userID": user.userID, "deviceID": MMServiceAdapter.deviceUUID(), "token": MMCoreConfiguration.serviceAdapter.HATToken] NSNotificationCenter.defaultCenter().postNotificationName(MMServiceAdapterDidReceiveHATTokenNotification, object: self, userInfo: userInfo) // Register for token expired notification NSNotificationCenter.defaultCenter().addObserver(self, selector: "userTokenExpired:", name: MMServiceAdapterDidReceiveAuthenticationChallengeNotification, object: nil) if let _ = self.delegate { handleCompletion(success, failure: failure, error : nil, context: "com.magnet.login.succeeded") } else { success?() } }, failure: { error in if let _ = self.delegate { handleCompletion(success, failure: failure, error : error, context: "com.magnet.login.failed") } else { failure?(error: error) } }).executeInBackground(nil) }) { error in if let _ = self.delegate { handleCompletion(success, failure: failure, error : error, context: "com.magnet.login.failed") } else { failure?(error: error) } }.executeInBackground(nil) } //begin login if currentlyLoggedInUser != nil { MMUser.logout({ () in loginClosure() }) { error in failure?(error : error); } } else { loginClosure() } } static private func handleCompletion(success: (() -> Void)?, failure: ((error: NSError) -> Void)?, error: NSError?, context : String) { delegate?.overrideCompletion({ (error) -> Void in if let error = error { failure?(error: error) } else { success?() } }, error: error, context: context) } /** Acts as the userToken expired event receiver. - Parameters: - notification: The notification that was received. */ @objc static private func userTokenExpired(notification: NSNotification?) { currentlyLoggedInUser = nil // Unregister for token expired notification NSNotificationCenter.defaultCenter().removeObserver(self, name: MMServiceAdapterDidReceiveAuthenticationChallengeNotification, object: nil) } /** Logs out a currently logged-in user. */ static public func logout() { logout(nil, failure: nil) } /** Logs out a currently logged-in user. - Parameters: - success: A block object to be executed when the logout finishes successfully. This block has no return value and takes no arguments. - failure: A block object to be executed when the logout finishes with an error. This block has no return value and takes one argument: the error object. */ static public func logout(success: (() -> Void)?, failure: ((error: NSError) -> Void)?) { if currentUser() == nil { success?() return } userTokenExpired(nil) MMCoreConfiguration.serviceAdapter.logoutWithSuccess({ _ in success?() }) { error in failure?(error: error) }.executeInBackground(nil) } /** Get the currently logged-in user. - Returns: The currently logged-in user or nil. */ static public func currentUser() -> MMUser? { return currentlyLoggedInUser } /** Search for users based on some criteria. - Parameters: - query: The DSL can be found here: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#query-string-syntax - limit: The number of records to retrieve. - offset: The offset to start from. - sort: The sort criteria. - success: A block object to be executed when the call finishes successfully. This block has no return value and takes one argument: the list of users that match the specified criteria. - failure: A block object to be executed when the call finishes with an error. This block has no return value and takes one argument: the error object. */ static public func searchUsers(query: String, limit take: Int, offset skip: Int, sort: String, success: (([MMUser]) -> Void)?, failure: ((error: NSError) -> Void)?) { let userService = MMUserService() userService.searchUsers(query, take: Int32(take), skip: Int32(skip), sort: sort, success: { users in success?(users) }) { error in failure?(error: error) }.executeInBackground(nil) } /** Get users with userNames. - Parameters: - userNames: A list of userNames to fetch users for. - success: A block object to be executed when the logout finishes successfully. This block has no return value and takes one argument: the list of users for the specified userNames. - failure: A block object to be executed when the logout finishes with an error. This block has no return value and takes one argument: the error object. */ static public func usersWithUserNames(userNames:[String], success: (([MMUser]) -> Void)?, failure: ((error: NSError) -> Void)?) { let userService = MMUserService() userService.getUsersByUserNames(userNames, success: { users in success?(users) }) { error in failure?(error: error) }.executeInBackground(nil) } /** Get users with userIDs. - Parameters: - userNames: A list of userIDs to fetch users for. - success: A block object to be executed when the logout finishes successfully. This block has no return value and takes one argument: the list of users for the specified userIDs. - failure: A block object to be executed when the logout finishes with an error. This block has no return value and takes one argument: the error object. */ static public func usersWithUserIDs(userIDs:[String], success: (([MMUser]) -> Void)?, failure: ((error: NSError) -> Void)?) { let userService = MMUserService() userService.getUsersByUserIds(userIDs, success: { users in success?(users) }) { error in failure?(error: error) }.executeInBackground(nil) } /** Update the currently logged-in user's profile. - Parameters: - updateProfileRequest: A profile update request. - success: A block object to be executed when the update finishes successfully. This block has no return value and takes one argument: the updated user. - failure: A block object to be executed when the registration finishes with an error. This block has no return value and takes one argument: the error object. */ static public func updateProfile(updateProfileRequest: MMUpdateProfileRequest, success: ((user: MMUser) -> Void)?, failure: ((error: NSError) -> Void)?) { guard let _ = currentUser() else { // FIXME: Use a different domain failure?(error: NSError(domain: "MMXErrorDomain", code: 401, userInfo: nil)) return } let userService = MMUserService() userService.updateProfile(updateProfileRequest, success: { user in success?(user: user) }) { error in failure?(error: error) }.executeInBackground(nil) } override public func isEqual(object: AnyObject?) -> Bool { if let rhs = object as? MMUser { return userID != nil && userID == rhs.userID } return false } override var hash: Int { return userID != nil ? userID.hashValue : ObjectIdentifier(self).hashValue } }
2c98ba67dfcecdc07cacdc572e1b4c40
43.253676
197
0.614023
false
false
false
false